Merge branch 'master' of git://git.kernel.org/pub/scm/linux/kernel/git/linville/wirel...
[pandora-kernel.git] / drivers / media / IR / imon.c
1 /*
2  *   imon.c:    input and display driver for SoundGraph iMON IR/VFD/LCD
3  *
4  *   Copyright(C) 2009  Jarod Wilson <jarod@wilsonet.com>
5  *   Portions based on the original lirc_imon driver,
6  *      Copyright(C) 2004  Venky Raju(dev@venky.ws)
7  *
8  *   Huge thanks to R. Geoff Newbury for invaluable debugging on the
9  *   0xffdc iMON devices, and for sending me one to hack on, without
10  *   which the support for them wouldn't be nearly as good. Thanks
11  *   also to the numerous 0xffdc device owners that tested auto-config
12  *   support for me and provided debug dumps from their devices.
13  *
14  *   imon is free software; you can redistribute it and/or modify
15  *   it under the terms of the GNU General Public License as published by
16  *   the Free Software Foundation; either version 2 of the License, or
17  *   (at your option) any later version.
18  *
19  *   This program is distributed in the hope that it will be useful,
20  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
21  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  *   GNU General Public License for more details.
23  *
24  *   You should have received a copy of the GNU General Public License
25  *   along with this program; if not, write to the Free Software
26  *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27  */
28
29 #include <linux/errno.h>
30 #include <linux/init.h>
31 #include <linux/kernel.h>
32 #include <linux/module.h>
33 #include <linux/slab.h>
34 #include <linux/uaccess.h>
35
36 #include <linux/input.h>
37 #include <linux/usb.h>
38 #include <linux/usb/input.h>
39 #include <media/ir-core.h>
40
41 #include <linux/time.h>
42 #include <linux/timer.h>
43
44 #define MOD_AUTHOR      "Jarod Wilson <jarod@wilsonet.com>"
45 #define MOD_DESC        "Driver for SoundGraph iMON MultiMedia IR/Display"
46 #define MOD_NAME        "imon"
47 #define MOD_VERSION     "0.9.1"
48
49 #define DISPLAY_MINOR_BASE      144
50 #define DEVICE_NAME     "lcd%d"
51
52 #define BUF_CHUNK_SIZE  8
53 #define BUF_SIZE        128
54
55 #define BIT_DURATION    250     /* each bit received is 250us */
56
57 #define IMON_CLOCK_ENABLE_PACKETS       2
58
59 /*** P R O T O T Y P E S ***/
60
61 /* USB Callback prototypes */
62 static int imon_probe(struct usb_interface *interface,
63                       const struct usb_device_id *id);
64 static void imon_disconnect(struct usb_interface *interface);
65 static void usb_rx_callback_intf0(struct urb *urb);
66 static void usb_rx_callback_intf1(struct urb *urb);
67 static void usb_tx_callback(struct urb *urb);
68
69 /* suspend/resume support */
70 static int imon_resume(struct usb_interface *intf);
71 static int imon_suspend(struct usb_interface *intf, pm_message_t message);
72
73 /* Display file_operations function prototypes */
74 static int display_open(struct inode *inode, struct file *file);
75 static int display_close(struct inode *inode, struct file *file);
76
77 /* VFD write operation */
78 static ssize_t vfd_write(struct file *file, const char *buf,
79                          size_t n_bytes, loff_t *pos);
80
81 /* LCD file_operations override function prototypes */
82 static ssize_t lcd_write(struct file *file, const char *buf,
83                          size_t n_bytes, loff_t *pos);
84
85 /*** G L O B A L S ***/
86
87 struct imon_context {
88         struct device *dev;
89         struct ir_dev_props *props;
90         /* Newer devices have two interfaces */
91         struct usb_device *usbdev_intf0;
92         struct usb_device *usbdev_intf1;
93
94         bool display_supported;         /* not all controllers do */
95         bool display_isopen;            /* display port has been opened */
96         bool rf_device;                 /* true if iMON 2.4G LT/DT RF device */
97         bool rf_isassociating;          /* RF remote associating */
98         bool dev_present_intf0;         /* USB device presence, interface 0 */
99         bool dev_present_intf1;         /* USB device presence, interface 1 */
100
101         struct mutex lock;              /* to lock this object */
102         wait_queue_head_t remove_ok;    /* For unexpected USB disconnects */
103
104         struct usb_endpoint_descriptor *rx_endpoint_intf0;
105         struct usb_endpoint_descriptor *rx_endpoint_intf1;
106         struct usb_endpoint_descriptor *tx_endpoint;
107         struct urb *rx_urb_intf0;
108         struct urb *rx_urb_intf1;
109         struct urb *tx_urb;
110         bool tx_control;
111         unsigned char usb_rx_buf[8];
112         unsigned char usb_tx_buf[8];
113
114         struct tx_t {
115                 unsigned char data_buf[35];     /* user data buffer */
116                 struct completion finished;     /* wait for write to finish */
117                 bool busy;                      /* write in progress */
118                 int status;                     /* status of tx completion */
119         } tx;
120
121         u16 vendor;                     /* usb vendor ID */
122         u16 product;                    /* usb product ID */
123
124         struct input_dev *idev;         /* input device for remote */
125         struct input_dev *touch;        /* input device for touchscreen */
126
127         u32 kc;                         /* current input keycode */
128         u32 last_keycode;               /* last reported input keycode */
129         u64 ir_type;                    /* iMON or MCE (RC6) IR protocol? */
130         u8 mce_toggle_bit;              /* last mce toggle bit */
131         bool release_code;              /* some keys send a release code */
132
133         u8 display_type;                /* store the display type */
134         bool pad_mouse;                 /* toggle kbd(0)/mouse(1) mode */
135
136         char name_idev[128];            /* input device name */
137         char phys_idev[64];             /* input device phys path */
138         struct timer_list itimer;       /* input device timer, need for rc6 */
139
140         char name_touch[128];           /* touch screen name */
141         char phys_touch[64];            /* touch screen phys path */
142         struct timer_list ttimer;       /* touch screen timer */
143         int touch_x;                    /* x coordinate on touchscreen */
144         int touch_y;                    /* y coordinate on touchscreen */
145 };
146
147 #define TOUCH_TIMEOUT   (HZ/30)
148
149 /* vfd character device file operations */
150 static const struct file_operations vfd_fops = {
151         .owner          = THIS_MODULE,
152         .open           = &display_open,
153         .write          = &vfd_write,
154         .release        = &display_close
155 };
156
157 /* lcd character device file operations */
158 static const struct file_operations lcd_fops = {
159         .owner          = THIS_MODULE,
160         .open           = &display_open,
161         .write          = &lcd_write,
162         .release        = &display_close
163 };
164
165 enum {
166         IMON_DISPLAY_TYPE_AUTO = 0,
167         IMON_DISPLAY_TYPE_VFD  = 1,
168         IMON_DISPLAY_TYPE_LCD  = 2,
169         IMON_DISPLAY_TYPE_VGA  = 3,
170         IMON_DISPLAY_TYPE_NONE = 4,
171 };
172
173 enum {
174         IMON_KEY_IMON   = 0,
175         IMON_KEY_MCE    = 1,
176         IMON_KEY_PANEL  = 2,
177 };
178
179 /*
180  * USB Device ID for iMON USB Control Boards
181  *
182  * The Windows drivers contain 6 different inf files, more or less one for
183  * each new device until the 0x0034-0x0046 devices, which all use the same
184  * driver. Some of the devices in the 34-46 range haven't been definitively
185  * identified yet. Early devices have either a TriGem Computer, Inc. or a
186  * Samsung vendor ID (0x0aa8 and 0x04e8 respectively), while all later
187  * devices use the SoundGraph vendor ID (0x15c2). This driver only supports
188  * the ffdc and later devices, which do onboard decoding.
189  */
190 static struct usb_device_id imon_usb_id_table[] = {
191         /*
192          * Several devices with this same device ID, all use iMON_PAD.inf
193          * SoundGraph iMON PAD (IR & VFD)
194          * SoundGraph iMON PAD (IR & LCD)
195          * SoundGraph iMON Knob (IR only)
196          */
197         { USB_DEVICE(0x15c2, 0xffdc) },
198
199         /*
200          * Newer devices, all driven by the latest iMON Windows driver, full
201          * list of device IDs extracted via 'strings Setup/data1.hdr |grep 15c2'
202          * Need user input to fill in details on unknown devices.
203          */
204         /* SoundGraph iMON OEM Touch LCD (IR & 7" VGA LCD) */
205         { USB_DEVICE(0x15c2, 0x0034) },
206         /* SoundGraph iMON OEM Touch LCD (IR & 4.3" VGA LCD) */
207         { USB_DEVICE(0x15c2, 0x0035) },
208         /* SoundGraph iMON OEM VFD (IR & VFD) */
209         { USB_DEVICE(0x15c2, 0x0036) },
210         /* device specifics unknown */
211         { USB_DEVICE(0x15c2, 0x0037) },
212         /* SoundGraph iMON OEM LCD (IR & LCD) */
213         { USB_DEVICE(0x15c2, 0x0038) },
214         /* SoundGraph iMON UltraBay (IR & LCD) */
215         { USB_DEVICE(0x15c2, 0x0039) },
216         /* device specifics unknown */
217         { USB_DEVICE(0x15c2, 0x003a) },
218         /* device specifics unknown */
219         { USB_DEVICE(0x15c2, 0x003b) },
220         /* SoundGraph iMON OEM Inside (IR only) */
221         { USB_DEVICE(0x15c2, 0x003c) },
222         /* device specifics unknown */
223         { USB_DEVICE(0x15c2, 0x003d) },
224         /* device specifics unknown */
225         { USB_DEVICE(0x15c2, 0x003e) },
226         /* device specifics unknown */
227         { USB_DEVICE(0x15c2, 0x003f) },
228         /* device specifics unknown */
229         { USB_DEVICE(0x15c2, 0x0040) },
230         /* SoundGraph iMON MINI (IR only) */
231         { USB_DEVICE(0x15c2, 0x0041) },
232         /* Antec Veris Multimedia Station EZ External (IR only) */
233         { USB_DEVICE(0x15c2, 0x0042) },
234         /* Antec Veris Multimedia Station Basic Internal (IR only) */
235         { USB_DEVICE(0x15c2, 0x0043) },
236         /* Antec Veris Multimedia Station Elite (IR & VFD) */
237         { USB_DEVICE(0x15c2, 0x0044) },
238         /* Antec Veris Multimedia Station Premiere (IR & LCD) */
239         { USB_DEVICE(0x15c2, 0x0045) },
240         /* device specifics unknown */
241         { USB_DEVICE(0x15c2, 0x0046) },
242         {}
243 };
244
245 /* USB Device data */
246 static struct usb_driver imon_driver = {
247         .name           = MOD_NAME,
248         .probe          = imon_probe,
249         .disconnect     = imon_disconnect,
250         .suspend        = imon_suspend,
251         .resume         = imon_resume,
252         .id_table       = imon_usb_id_table,
253 };
254
255 static struct usb_class_driver imon_vfd_class = {
256         .name           = DEVICE_NAME,
257         .fops           = &vfd_fops,
258         .minor_base     = DISPLAY_MINOR_BASE,
259 };
260
261 static struct usb_class_driver imon_lcd_class = {
262         .name           = DEVICE_NAME,
263         .fops           = &lcd_fops,
264         .minor_base     = DISPLAY_MINOR_BASE,
265 };
266
267 /* imon receiver front panel/knob key table */
268 static const struct {
269         u64 hw_code;
270         u32 keycode;
271 } imon_panel_key_table[] = {
272         { 0x000000000f00ffeell, KEY_PROG1 }, /* Go */
273         { 0x000000001f00ffeell, KEY_AUDIO },
274         { 0x000000002000ffeell, KEY_VIDEO },
275         { 0x000000002100ffeell, KEY_CAMERA },
276         { 0x000000002700ffeell, KEY_DVD },
277         { 0x000000002300ffeell, KEY_TV },
278         { 0x000000000500ffeell, KEY_PREVIOUS },
279         { 0x000000000700ffeell, KEY_REWIND },
280         { 0x000000000400ffeell, KEY_STOP },
281         { 0x000000003c00ffeell, KEY_PLAYPAUSE },
282         { 0x000000000800ffeell, KEY_FASTFORWARD },
283         { 0x000000000600ffeell, KEY_NEXT },
284         { 0x000000010000ffeell, KEY_RIGHT },
285         { 0x000001000000ffeell, KEY_LEFT },
286         { 0x000000003d00ffeell, KEY_SELECT },
287         { 0x000100000000ffeell, KEY_VOLUMEUP },
288         { 0x010000000000ffeell, KEY_VOLUMEDOWN },
289         { 0x000000000100ffeell, KEY_MUTE },
290         /* iMON Knob values */
291         { 0x000100ffffffffeell, KEY_VOLUMEUP },
292         { 0x010000ffffffffeell, KEY_VOLUMEDOWN },
293         { 0x000008ffffffffeell, KEY_MUTE },
294 };
295
296 /* to prevent races between open() and disconnect(), probing, etc */
297 static DEFINE_MUTEX(driver_lock);
298
299 /* Module bookkeeping bits */
300 MODULE_AUTHOR(MOD_AUTHOR);
301 MODULE_DESCRIPTION(MOD_DESC);
302 MODULE_VERSION(MOD_VERSION);
303 MODULE_LICENSE("GPL");
304 MODULE_DEVICE_TABLE(usb, imon_usb_id_table);
305
306 static bool debug;
307 module_param(debug, bool, S_IRUGO | S_IWUSR);
308 MODULE_PARM_DESC(debug, "Debug messages: 0=no, 1=yes(default: no)");
309
310 /* lcd, vfd, vga or none? should be auto-detected, but can be overridden... */
311 static int display_type;
312 module_param(display_type, int, S_IRUGO);
313 MODULE_PARM_DESC(display_type, "Type of attached display. 0=autodetect, "
314                  "1=vfd, 2=lcd, 3=vga, 4=none (default: autodetect)");
315
316 static int pad_stabilize = 1;
317 module_param(pad_stabilize, int, S_IRUGO | S_IWUSR);
318 MODULE_PARM_DESC(pad_stabilize, "Apply stabilization algorithm to iMON PAD "
319                  "presses in arrow key mode. 0=disable, 1=enable (default).");
320
321 /*
322  * In certain use cases, mouse mode isn't really helpful, and could actually
323  * cause confusion, so allow disabling it when the IR device is open.
324  */
325 static bool nomouse;
326 module_param(nomouse, bool, S_IRUGO | S_IWUSR);
327 MODULE_PARM_DESC(nomouse, "Disable mouse input device mode when IR device is "
328                  "open. 0=don't disable, 1=disable. (default: don't disable)");
329
330 /* threshold at which a pad push registers as an arrow key in kbd mode */
331 static int pad_thresh;
332 module_param(pad_thresh, int, S_IRUGO | S_IWUSR);
333 MODULE_PARM_DESC(pad_thresh, "Threshold at which a pad push registers as an "
334                  "arrow key in kbd mode (default: 28)");
335
336
337 static void free_imon_context(struct imon_context *ictx)
338 {
339         struct device *dev = ictx->dev;
340
341         usb_free_urb(ictx->tx_urb);
342         usb_free_urb(ictx->rx_urb_intf0);
343         usb_free_urb(ictx->rx_urb_intf1);
344         kfree(ictx);
345
346         dev_dbg(dev, "%s: iMON context freed\n", __func__);
347 }
348
349 /**
350  * Called when the Display device (e.g. /dev/lcd0)
351  * is opened by the application.
352  */
353 static int display_open(struct inode *inode, struct file *file)
354 {
355         struct usb_interface *interface;
356         struct imon_context *ictx = NULL;
357         int subminor;
358         int retval = 0;
359
360         /* prevent races with disconnect */
361         mutex_lock(&driver_lock);
362
363         subminor = iminor(inode);
364         interface = usb_find_interface(&imon_driver, subminor);
365         if (!interface) {
366                 err("%s: could not find interface for minor %d",
367                     __func__, subminor);
368                 retval = -ENODEV;
369                 goto exit;
370         }
371         ictx = usb_get_intfdata(interface);
372
373         if (!ictx) {
374                 err("%s: no context found for minor %d", __func__, subminor);
375                 retval = -ENODEV;
376                 goto exit;
377         }
378
379         mutex_lock(&ictx->lock);
380
381         if (!ictx->display_supported) {
382                 err("%s: display not supported by device", __func__);
383                 retval = -ENODEV;
384         } else if (ictx->display_isopen) {
385                 err("%s: display port is already open", __func__);
386                 retval = -EBUSY;
387         } else {
388                 ictx->display_isopen = true;
389                 file->private_data = ictx;
390                 dev_dbg(ictx->dev, "display port opened\n");
391         }
392
393         mutex_unlock(&ictx->lock);
394
395 exit:
396         mutex_unlock(&driver_lock);
397         return retval;
398 }
399
400 /**
401  * Called when the display device (e.g. /dev/lcd0)
402  * is closed by the application.
403  */
404 static int display_close(struct inode *inode, struct file *file)
405 {
406         struct imon_context *ictx = NULL;
407         int retval = 0;
408
409         ictx = file->private_data;
410
411         if (!ictx) {
412                 err("%s: no context for device", __func__);
413                 return -ENODEV;
414         }
415
416         mutex_lock(&ictx->lock);
417
418         if (!ictx->display_supported) {
419                 err("%s: display not supported by device", __func__);
420                 retval = -ENODEV;
421         } else if (!ictx->display_isopen) {
422                 err("%s: display is not open", __func__);
423                 retval = -EIO;
424         } else {
425                 ictx->display_isopen = false;
426                 dev_dbg(ictx->dev, "display port closed\n");
427                 if (!ictx->dev_present_intf0) {
428                         /*
429                          * Device disconnected before close and IR port is not
430                          * open. If IR port is open, context will be deleted by
431                          * ir_close.
432                          */
433                         mutex_unlock(&ictx->lock);
434                         free_imon_context(ictx);
435                         return retval;
436                 }
437         }
438
439         mutex_unlock(&ictx->lock);
440         return retval;
441 }
442
443 /**
444  * Sends a packet to the device -- this function must be called
445  * with ictx->lock held.
446  */
447 static int send_packet(struct imon_context *ictx)
448 {
449         unsigned int pipe;
450         unsigned long timeout;
451         int interval = 0;
452         int retval = 0;
453         struct usb_ctrlrequest *control_req = NULL;
454
455         /* Check if we need to use control or interrupt urb */
456         if (!ictx->tx_control) {
457                 pipe = usb_sndintpipe(ictx->usbdev_intf0,
458                                       ictx->tx_endpoint->bEndpointAddress);
459                 interval = ictx->tx_endpoint->bInterval;
460
461                 usb_fill_int_urb(ictx->tx_urb, ictx->usbdev_intf0, pipe,
462                                  ictx->usb_tx_buf,
463                                  sizeof(ictx->usb_tx_buf),
464                                  usb_tx_callback, ictx, interval);
465
466                 ictx->tx_urb->actual_length = 0;
467         } else {
468                 /* fill request into kmalloc'ed space: */
469                 control_req = kmalloc(sizeof(struct usb_ctrlrequest),
470                                       GFP_KERNEL);
471                 if (control_req == NULL)
472                         return -ENOMEM;
473
474                 /* setup packet is '21 09 0200 0001 0008' */
475                 control_req->bRequestType = 0x21;
476                 control_req->bRequest = 0x09;
477                 control_req->wValue = cpu_to_le16(0x0200);
478                 control_req->wIndex = cpu_to_le16(0x0001);
479                 control_req->wLength = cpu_to_le16(0x0008);
480
481                 /* control pipe is endpoint 0x00 */
482                 pipe = usb_sndctrlpipe(ictx->usbdev_intf0, 0);
483
484                 /* build the control urb */
485                 usb_fill_control_urb(ictx->tx_urb, ictx->usbdev_intf0,
486                                      pipe, (unsigned char *)control_req,
487                                      ictx->usb_tx_buf,
488                                      sizeof(ictx->usb_tx_buf),
489                                      usb_tx_callback, ictx);
490                 ictx->tx_urb->actual_length = 0;
491         }
492
493         init_completion(&ictx->tx.finished);
494         ictx->tx.busy = true;
495         smp_rmb(); /* ensure later readers know we're busy */
496
497         retval = usb_submit_urb(ictx->tx_urb, GFP_KERNEL);
498         if (retval) {
499                 ictx->tx.busy = false;
500                 smp_rmb(); /* ensure later readers know we're not busy */
501                 err("%s: error submitting urb(%d)", __func__, retval);
502         } else {
503                 /* Wait for transmission to complete (or abort) */
504                 mutex_unlock(&ictx->lock);
505                 retval = wait_for_completion_interruptible(
506                                 &ictx->tx.finished);
507                 if (retval)
508                         err("%s: task interrupted", __func__);
509                 mutex_lock(&ictx->lock);
510
511                 retval = ictx->tx.status;
512                 if (retval)
513                         err("%s: packet tx failed (%d)", __func__, retval);
514         }
515
516         kfree(control_req);
517
518         /*
519          * Induce a mandatory 5ms delay before returning, as otherwise,
520          * send_packet can get called so rapidly as to overwhelm the device,
521          * particularly on faster systems and/or those with quirky usb.
522          */
523         timeout = msecs_to_jiffies(5);
524         set_current_state(TASK_UNINTERRUPTIBLE);
525         schedule_timeout(timeout);
526
527         return retval;
528 }
529
530 /**
531  * Sends an associate packet to the iMON 2.4G.
532  *
533  * This might not be such a good idea, since it has an id collision with
534  * some versions of the "IR & VFD" combo. The only way to determine if it
535  * is an RF version is to look at the product description string. (Which
536  * we currently do not fetch).
537  */
538 static int send_associate_24g(struct imon_context *ictx)
539 {
540         int retval;
541         const unsigned char packet[8] = { 0x01, 0x00, 0x00, 0x00,
542                                           0x00, 0x00, 0x00, 0x20 };
543
544         if (!ictx) {
545                 err("%s: no context for device", __func__);
546                 return -ENODEV;
547         }
548
549         if (!ictx->dev_present_intf0) {
550                 err("%s: no iMON device present", __func__);
551                 return -ENODEV;
552         }
553
554         memcpy(ictx->usb_tx_buf, packet, sizeof(packet));
555         retval = send_packet(ictx);
556
557         return retval;
558 }
559
560 /**
561  * Sends packets to setup and show clock on iMON display
562  *
563  * Arguments: year - last 2 digits of year, month - 1..12,
564  * day - 1..31, dow - day of the week (0-Sun...6-Sat),
565  * hour - 0..23, minute - 0..59, second - 0..59
566  */
567 static int send_set_imon_clock(struct imon_context *ictx,
568                                unsigned int year, unsigned int month,
569                                unsigned int day, unsigned int dow,
570                                unsigned int hour, unsigned int minute,
571                                unsigned int second)
572 {
573         unsigned char clock_enable_pkt[IMON_CLOCK_ENABLE_PACKETS][8];
574         int retval = 0;
575         int i;
576
577         if (!ictx) {
578                 err("%s: no context for device", __func__);
579                 return -ENODEV;
580         }
581
582         switch (ictx->display_type) {
583         case IMON_DISPLAY_TYPE_LCD:
584                 clock_enable_pkt[0][0] = 0x80;
585                 clock_enable_pkt[0][1] = year;
586                 clock_enable_pkt[0][2] = month-1;
587                 clock_enable_pkt[0][3] = day;
588                 clock_enable_pkt[0][4] = hour;
589                 clock_enable_pkt[0][5] = minute;
590                 clock_enable_pkt[0][6] = second;
591
592                 clock_enable_pkt[1][0] = 0x80;
593                 clock_enable_pkt[1][1] = 0;
594                 clock_enable_pkt[1][2] = 0;
595                 clock_enable_pkt[1][3] = 0;
596                 clock_enable_pkt[1][4] = 0;
597                 clock_enable_pkt[1][5] = 0;
598                 clock_enable_pkt[1][6] = 0;
599
600                 if (ictx->product == 0xffdc) {
601                         clock_enable_pkt[0][7] = 0x50;
602                         clock_enable_pkt[1][7] = 0x51;
603                 } else {
604                         clock_enable_pkt[0][7] = 0x88;
605                         clock_enable_pkt[1][7] = 0x8a;
606                 }
607
608                 break;
609
610         case IMON_DISPLAY_TYPE_VFD:
611                 clock_enable_pkt[0][0] = year;
612                 clock_enable_pkt[0][1] = month-1;
613                 clock_enable_pkt[0][2] = day;
614                 clock_enable_pkt[0][3] = dow;
615                 clock_enable_pkt[0][4] = hour;
616                 clock_enable_pkt[0][5] = minute;
617                 clock_enable_pkt[0][6] = second;
618                 clock_enable_pkt[0][7] = 0x40;
619
620                 clock_enable_pkt[1][0] = 0;
621                 clock_enable_pkt[1][1] = 0;
622                 clock_enable_pkt[1][2] = 1;
623                 clock_enable_pkt[1][3] = 0;
624                 clock_enable_pkt[1][4] = 0;
625                 clock_enable_pkt[1][5] = 0;
626                 clock_enable_pkt[1][6] = 0;
627                 clock_enable_pkt[1][7] = 0x42;
628
629                 break;
630
631         default:
632                 return -ENODEV;
633         }
634
635         for (i = 0; i < IMON_CLOCK_ENABLE_PACKETS; i++) {
636                 memcpy(ictx->usb_tx_buf, clock_enable_pkt[i], 8);
637                 retval = send_packet(ictx);
638                 if (retval) {
639                         err("%s: send_packet failed for packet %d",
640                             __func__, i);
641                         break;
642                 }
643         }
644
645         return retval;
646 }
647
648 /**
649  * These are the sysfs functions to handle the association on the iMON 2.4G LT.
650  */
651 static ssize_t show_associate_remote(struct device *d,
652                                      struct device_attribute *attr,
653                                      char *buf)
654 {
655         struct imon_context *ictx = dev_get_drvdata(d);
656
657         if (!ictx)
658                 return -ENODEV;
659
660         mutex_lock(&ictx->lock);
661         if (ictx->rf_isassociating)
662                 strcpy(buf, "associating\n");
663         else
664                 strcpy(buf, "closed\n");
665
666         dev_info(d, "Visit http://www.lirc.org/html/imon-24g.html for "
667                  "instructions on how to associate your iMON 2.4G DT/LT "
668                  "remote\n");
669         mutex_unlock(&ictx->lock);
670         return strlen(buf);
671 }
672
673 static ssize_t store_associate_remote(struct device *d,
674                                       struct device_attribute *attr,
675                                       const char *buf, size_t count)
676 {
677         struct imon_context *ictx;
678
679         ictx = dev_get_drvdata(d);
680
681         if (!ictx)
682                 return -ENODEV;
683
684         mutex_lock(&ictx->lock);
685         ictx->rf_isassociating = true;
686         send_associate_24g(ictx);
687         mutex_unlock(&ictx->lock);
688
689         return count;
690 }
691
692 /**
693  * sysfs functions to control internal imon clock
694  */
695 static ssize_t show_imon_clock(struct device *d,
696                                struct device_attribute *attr, char *buf)
697 {
698         struct imon_context *ictx = dev_get_drvdata(d);
699         size_t len;
700
701         if (!ictx)
702                 return -ENODEV;
703
704         mutex_lock(&ictx->lock);
705
706         if (!ictx->display_supported) {
707                 len = snprintf(buf, PAGE_SIZE, "Not supported.");
708         } else {
709                 len = snprintf(buf, PAGE_SIZE,
710                         "To set the clock on your iMON display:\n"
711                         "# date \"+%%y %%m %%d %%w %%H %%M %%S\" > imon_clock\n"
712                         "%s", ictx->display_isopen ?
713                         "\nNOTE: imon device must be closed\n" : "");
714         }
715
716         mutex_unlock(&ictx->lock);
717
718         return len;
719 }
720
721 static ssize_t store_imon_clock(struct device *d,
722                                 struct device_attribute *attr,
723                                 const char *buf, size_t count)
724 {
725         struct imon_context *ictx = dev_get_drvdata(d);
726         ssize_t retval;
727         unsigned int year, month, day, dow, hour, minute, second;
728
729         if (!ictx)
730                 return -ENODEV;
731
732         mutex_lock(&ictx->lock);
733
734         if (!ictx->display_supported) {
735                 retval = -ENODEV;
736                 goto exit;
737         } else if (ictx->display_isopen) {
738                 retval = -EBUSY;
739                 goto exit;
740         }
741
742         if (sscanf(buf, "%u %u %u %u %u %u %u", &year, &month, &day, &dow,
743                    &hour, &minute, &second) != 7) {
744                 retval = -EINVAL;
745                 goto exit;
746         }
747
748         if ((month < 1 || month > 12) ||
749             (day < 1 || day > 31) || (dow > 6) ||
750             (hour > 23) || (minute > 59) || (second > 59)) {
751                 retval = -EINVAL;
752                 goto exit;
753         }
754
755         retval = send_set_imon_clock(ictx, year, month, day, dow,
756                                      hour, minute, second);
757         if (retval)
758                 goto exit;
759
760         retval = count;
761 exit:
762         mutex_unlock(&ictx->lock);
763
764         return retval;
765 }
766
767
768 static DEVICE_ATTR(imon_clock, S_IWUSR | S_IRUGO, show_imon_clock,
769                    store_imon_clock);
770
771 static DEVICE_ATTR(associate_remote, S_IWUSR | S_IRUGO, show_associate_remote,
772                    store_associate_remote);
773
774 static struct attribute *imon_display_sysfs_entries[] = {
775         &dev_attr_imon_clock.attr,
776         NULL
777 };
778
779 static struct attribute_group imon_display_attribute_group = {
780         .attrs = imon_display_sysfs_entries
781 };
782
783 static struct attribute *imon_rf_sysfs_entries[] = {
784         &dev_attr_associate_remote.attr,
785         NULL
786 };
787
788 static struct attribute_group imon_rf_attribute_group = {
789         .attrs = imon_rf_sysfs_entries
790 };
791
792 /**
793  * Writes data to the VFD.  The iMON VFD is 2x16 characters
794  * and requires data in 5 consecutive USB interrupt packets,
795  * each packet but the last carrying 7 bytes.
796  *
797  * I don't know if the VFD board supports features such as
798  * scrolling, clearing rows, blanking, etc. so at
799  * the caller must provide a full screen of data.  If fewer
800  * than 32 bytes are provided spaces will be appended to
801  * generate a full screen.
802  */
803 static ssize_t vfd_write(struct file *file, const char *buf,
804                          size_t n_bytes, loff_t *pos)
805 {
806         int i;
807         int offset;
808         int seq;
809         int retval = 0;
810         struct imon_context *ictx;
811         const unsigned char vfd_packet6[] = {
812                 0x01, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF };
813
814         ictx = file->private_data;
815         if (!ictx) {
816                 err("%s: no context for device", __func__);
817                 return -ENODEV;
818         }
819
820         mutex_lock(&ictx->lock);
821
822         if (!ictx->dev_present_intf0) {
823                 err("%s: no iMON device present", __func__);
824                 retval = -ENODEV;
825                 goto exit;
826         }
827
828         if (n_bytes <= 0 || n_bytes > 32) {
829                 err("%s: invalid payload size", __func__);
830                 retval = -EINVAL;
831                 goto exit;
832         }
833
834         if (copy_from_user(ictx->tx.data_buf, buf, n_bytes)) {
835                 retval = -EFAULT;
836                 goto exit;
837         }
838
839         /* Pad with spaces */
840         for (i = n_bytes; i < 32; ++i)
841                 ictx->tx.data_buf[i] = ' ';
842
843         for (i = 32; i < 35; ++i)
844                 ictx->tx.data_buf[i] = 0xFF;
845
846         offset = 0;
847         seq = 0;
848
849         do {
850                 memcpy(ictx->usb_tx_buf, ictx->tx.data_buf + offset, 7);
851                 ictx->usb_tx_buf[7] = (unsigned char) seq;
852
853                 retval = send_packet(ictx);
854                 if (retval) {
855                         err("%s: send packet failed for packet #%d",
856                                         __func__, seq/2);
857                         goto exit;
858                 } else {
859                         seq += 2;
860                         offset += 7;
861                 }
862
863         } while (offset < 35);
864
865         /* Send packet #6 */
866         memcpy(ictx->usb_tx_buf, &vfd_packet6, sizeof(vfd_packet6));
867         ictx->usb_tx_buf[7] = (unsigned char) seq;
868         retval = send_packet(ictx);
869         if (retval)
870                 err("%s: send packet failed for packet #%d",
871                     __func__, seq / 2);
872
873 exit:
874         mutex_unlock(&ictx->lock);
875
876         return (!retval) ? n_bytes : retval;
877 }
878
879 /**
880  * Writes data to the LCD.  The iMON OEM LCD screen expects 8-byte
881  * packets. We accept data as 16 hexadecimal digits, followed by a
882  * newline (to make it easy to drive the device from a command-line
883  * -- even though the actual binary data is a bit complicated).
884  *
885  * The device itself is not a "traditional" text-mode display. It's
886  * actually a 16x96 pixel bitmap display. That means if you want to
887  * display text, you've got to have your own "font" and translate the
888  * text into bitmaps for display. This is really flexible (you can
889  * display whatever diacritics you need, and so on), but it's also
890  * a lot more complicated than most LCDs...
891  */
892 static ssize_t lcd_write(struct file *file, const char *buf,
893                          size_t n_bytes, loff_t *pos)
894 {
895         int retval = 0;
896         struct imon_context *ictx;
897
898         ictx = file->private_data;
899         if (!ictx) {
900                 err("%s: no context for device", __func__);
901                 return -ENODEV;
902         }
903
904         mutex_lock(&ictx->lock);
905
906         if (!ictx->display_supported) {
907                 err("%s: no iMON display present", __func__);
908                 retval = -ENODEV;
909                 goto exit;
910         }
911
912         if (n_bytes != 8) {
913                 err("%s: invalid payload size: %d (expecting 8)",
914                     __func__, (int) n_bytes);
915                 retval = -EINVAL;
916                 goto exit;
917         }
918
919         if (copy_from_user(ictx->usb_tx_buf, buf, 8)) {
920                 retval = -EFAULT;
921                 goto exit;
922         }
923
924         retval = send_packet(ictx);
925         if (retval) {
926                 err("%s: send packet failed!", __func__);
927                 goto exit;
928         } else {
929                 dev_dbg(ictx->dev, "%s: write %d bytes to LCD\n",
930                         __func__, (int) n_bytes);
931         }
932 exit:
933         mutex_unlock(&ictx->lock);
934         return (!retval) ? n_bytes : retval;
935 }
936
937 /**
938  * Callback function for USB core API: transmit data
939  */
940 static void usb_tx_callback(struct urb *urb)
941 {
942         struct imon_context *ictx;
943
944         if (!urb)
945                 return;
946         ictx = (struct imon_context *)urb->context;
947         if (!ictx)
948                 return;
949
950         ictx->tx.status = urb->status;
951
952         /* notify waiters that write has finished */
953         ictx->tx.busy = false;
954         smp_rmb(); /* ensure later readers know we're not busy */
955         complete(&ictx->tx.finished);
956 }
957
958 /**
959  * mce/rc6 keypresses have no distinct release code, use timer
960  */
961 static void imon_mce_timeout(unsigned long data)
962 {
963         struct imon_context *ictx = (struct imon_context *)data;
964
965         input_report_key(ictx->idev, ictx->last_keycode, 0);
966         input_sync(ictx->idev);
967 }
968
969 /**
970  * report touchscreen input
971  */
972 static void imon_touch_display_timeout(unsigned long data)
973 {
974         struct imon_context *ictx = (struct imon_context *)data;
975
976         if (ictx->display_type != IMON_DISPLAY_TYPE_VGA)
977                 return;
978
979         input_report_abs(ictx->touch, ABS_X, ictx->touch_x);
980         input_report_abs(ictx->touch, ABS_Y, ictx->touch_y);
981         input_report_key(ictx->touch, BTN_TOUCH, 0x00);
982         input_sync(ictx->touch);
983 }
984
985 /**
986  * iMON IR receivers support two different signal sets -- those used by
987  * the iMON remotes, and those used by the Windows MCE remotes (which is
988  * really just RC-6), but only one or the other at a time, as the signals
989  * are decoded onboard the receiver.
990  */
991 int imon_ir_change_protocol(void *priv, u64 ir_type)
992 {
993         int retval;
994         struct imon_context *ictx = priv;
995         struct device *dev = ictx->dev;
996         bool pad_mouse;
997         unsigned char ir_proto_packet[] = {
998                 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86 };
999
1000         if (ir_type && !(ir_type & ictx->props->allowed_protos))
1001                 dev_warn(dev, "Looks like you're trying to use an IR protocol "
1002                          "this device does not support\n");
1003
1004         switch (ir_type) {
1005         case IR_TYPE_RC6:
1006                 dev_dbg(dev, "Configuring IR receiver for MCE protocol\n");
1007                 ir_proto_packet[0] = 0x01;
1008                 pad_mouse = false;
1009                 init_timer(&ictx->itimer);
1010                 ictx->itimer.data = (unsigned long)ictx;
1011                 ictx->itimer.function = imon_mce_timeout;
1012                 break;
1013         case IR_TYPE_UNKNOWN:
1014         case IR_TYPE_OTHER:
1015                 dev_dbg(dev, "Configuring IR receiver for iMON protocol\n");
1016                 if (pad_stabilize)
1017                         pad_mouse = true;
1018                 else {
1019                         dev_dbg(dev, "PAD stabilize functionality disabled\n");
1020                         pad_mouse = false;
1021                 }
1022                 /* ir_proto_packet[0] = 0x00; // already the default */
1023                 ir_type = IR_TYPE_OTHER;
1024                 break;
1025         default:
1026                 dev_warn(dev, "Unsupported IR protocol specified, overriding "
1027                          "to iMON IR protocol\n");
1028                 if (pad_stabilize)
1029                         pad_mouse = true;
1030                 else {
1031                         dev_dbg(dev, "PAD stabilize functionality disabled\n");
1032                         pad_mouse = false;
1033                 }
1034                 /* ir_proto_packet[0] = 0x00; // already the default */
1035                 ir_type = IR_TYPE_OTHER;
1036                 break;
1037         }
1038
1039         memcpy(ictx->usb_tx_buf, &ir_proto_packet, sizeof(ir_proto_packet));
1040
1041         retval = send_packet(ictx);
1042         if (retval)
1043                 goto out;
1044
1045         ictx->ir_type = ir_type;
1046         ictx->pad_mouse = pad_mouse;
1047
1048 out:
1049         return retval;
1050 }
1051
1052 static inline int tv2int(const struct timeval *a, const struct timeval *b)
1053 {
1054         int usecs = 0;
1055         int sec   = 0;
1056
1057         if (b->tv_usec > a->tv_usec) {
1058                 usecs = 1000000;
1059                 sec--;
1060         }
1061
1062         usecs += a->tv_usec - b->tv_usec;
1063
1064         sec += a->tv_sec - b->tv_sec;
1065         sec *= 1000;
1066         usecs /= 1000;
1067         sec += usecs;
1068
1069         if (sec < 0)
1070                 sec = 1000;
1071
1072         return sec;
1073 }
1074
1075 /**
1076  * The directional pad behaves a bit differently, depending on whether this is
1077  * one of the older ffdc devices or a newer device. Newer devices appear to
1078  * have a higher resolution matrix for more precise mouse movement, but it
1079  * makes things overly sensitive in keyboard mode, so we do some interesting
1080  * contortions to make it less touchy. Older devices run through the same
1081  * routine with shorter timeout and a smaller threshold.
1082  */
1083 static int stabilize(int a, int b, u16 timeout, u16 threshold)
1084 {
1085         struct timeval ct;
1086         static struct timeval prev_time = {0, 0};
1087         static struct timeval hit_time  = {0, 0};
1088         static int x, y, prev_result, hits;
1089         int result = 0;
1090         int msec, msec_hit;
1091
1092         do_gettimeofday(&ct);
1093         msec = tv2int(&ct, &prev_time);
1094         msec_hit = tv2int(&ct, &hit_time);
1095
1096         if (msec > 100) {
1097                 x = 0;
1098                 y = 0;
1099                 hits = 0;
1100         }
1101
1102         x += a;
1103         y += b;
1104
1105         prev_time = ct;
1106
1107         if (abs(x) > threshold || abs(y) > threshold) {
1108                 if (abs(y) > abs(x))
1109                         result = (y > 0) ? 0x7F : 0x80;
1110                 else
1111                         result = (x > 0) ? 0x7F00 : 0x8000;
1112
1113                 x = 0;
1114                 y = 0;
1115
1116                 if (result == prev_result) {
1117                         hits++;
1118
1119                         if (hits > 3) {
1120                                 switch (result) {
1121                                 case 0x7F:
1122                                         y = 17 * threshold / 30;
1123                                         break;
1124                                 case 0x80:
1125                                         y -= 17 * threshold / 30;
1126                                         break;
1127                                 case 0x7F00:
1128                                         x = 17 * threshold / 30;
1129                                         break;
1130                                 case 0x8000:
1131                                         x -= 17 * threshold / 30;
1132                                         break;
1133                                 }
1134                         }
1135
1136                         if (hits == 2 && msec_hit < timeout) {
1137                                 result = 0;
1138                                 hits = 1;
1139                         }
1140                 } else {
1141                         prev_result = result;
1142                         hits = 1;
1143                         hit_time = ct;
1144                 }
1145         }
1146
1147         return result;
1148 }
1149
1150 static u32 imon_remote_key_lookup(struct imon_context *ictx, u32 hw_code)
1151 {
1152         u32 scancode = be32_to_cpu(hw_code);
1153         u32 keycode;
1154         u32 release;
1155         bool is_release_code = false;
1156
1157         /* Look for the initial press of a button */
1158         keycode = ir_g_keycode_from_table(ictx->idev, scancode);
1159
1160         /* Look for the release of a button */
1161         if (keycode == KEY_RESERVED) {
1162                 release = scancode & ~0x4000;
1163                 keycode = ir_g_keycode_from_table(ictx->idev, release);
1164                 if (keycode != KEY_RESERVED)
1165                         is_release_code = true;
1166         }
1167
1168         ictx->release_code = is_release_code;
1169
1170         return keycode;
1171 }
1172
1173 static u32 imon_mce_key_lookup(struct imon_context *ictx, u32 hw_code)
1174 {
1175         u32 scancode = be32_to_cpu(hw_code);
1176         u32 keycode;
1177
1178 #define MCE_KEY_MASK 0x7000
1179 #define MCE_TOGGLE_BIT 0x8000
1180
1181         /*
1182          * On some receivers, mce keys decode to 0x8000f04xx and 0x8000f84xx
1183          * (the toggle bit flipping between alternating key presses), while
1184          * on other receivers, we see 0x8000f74xx and 0x8000ff4xx. To keep
1185          * the table trim, we always or in the bits to look up 0x8000ff4xx,
1186          * but we can't or them into all codes, as some keys are decoded in
1187          * a different way w/o the same use of the toggle bit...
1188          */
1189         if ((scancode >> 24) & 0x80)
1190                 scancode = scancode | MCE_KEY_MASK | MCE_TOGGLE_BIT;
1191
1192         keycode = ir_g_keycode_from_table(ictx->idev, scancode);
1193
1194         return keycode;
1195 }
1196
1197 static u32 imon_panel_key_lookup(u64 hw_code)
1198 {
1199         int i;
1200         u64 code = be64_to_cpu(hw_code);
1201         u32 keycode = KEY_RESERVED;
1202
1203         for (i = 0; i < ARRAY_SIZE(imon_panel_key_table); i++) {
1204                 if (imon_panel_key_table[i].hw_code == (code | 0xffee)) {
1205                         keycode = imon_panel_key_table[i].keycode;
1206                         break;
1207                 }
1208         }
1209
1210         return keycode;
1211 }
1212
1213 static bool imon_mouse_event(struct imon_context *ictx,
1214                              unsigned char *buf, int len)
1215 {
1216         char rel_x = 0x00, rel_y = 0x00;
1217         u8 right_shift = 1;
1218         bool mouse_input = true;
1219         int dir = 0;
1220
1221         /* newer iMON device PAD or mouse button */
1222         if (ictx->product != 0xffdc && (buf[0] & 0x01) && len == 5) {
1223                 rel_x = buf[2];
1224                 rel_y = buf[3];
1225                 right_shift = 1;
1226         /* 0xffdc iMON PAD or mouse button input */
1227         } else if (ictx->product == 0xffdc && (buf[0] & 0x40) &&
1228                         !((buf[1] & 0x01) || ((buf[1] >> 2) & 0x01))) {
1229                 rel_x = (buf[1] & 0x08) | (buf[1] & 0x10) >> 2 |
1230                         (buf[1] & 0x20) >> 4 | (buf[1] & 0x40) >> 6;
1231                 if (buf[0] & 0x02)
1232                         rel_x |= ~0x0f;
1233                 rel_x = rel_x + rel_x / 2;
1234                 rel_y = (buf[2] & 0x08) | (buf[2] & 0x10) >> 2 |
1235                         (buf[2] & 0x20) >> 4 | (buf[2] & 0x40) >> 6;
1236                 if (buf[0] & 0x01)
1237                         rel_y |= ~0x0f;
1238                 rel_y = rel_y + rel_y / 2;
1239                 right_shift = 2;
1240         /* some ffdc devices decode mouse buttons differently... */
1241         } else if (ictx->product == 0xffdc && (buf[0] == 0x68)) {
1242                 right_shift = 2;
1243         /* ch+/- buttons, which we use for an emulated scroll wheel */
1244         } else if (ictx->kc == KEY_CHANNELUP && (buf[2] & 0x40) != 0x40) {
1245                 dir = 1;
1246         } else if (ictx->kc == KEY_CHANNELDOWN && (buf[2] & 0x40) != 0x40) {
1247                 dir = -1;
1248         } else
1249                 mouse_input = false;
1250
1251         if (mouse_input) {
1252                 dev_dbg(ictx->dev, "sending mouse data via input subsystem\n");
1253
1254                 if (dir) {
1255                         input_report_rel(ictx->idev, REL_WHEEL, dir);
1256                 } else if (rel_x || rel_y) {
1257                         input_report_rel(ictx->idev, REL_X, rel_x);
1258                         input_report_rel(ictx->idev, REL_Y, rel_y);
1259                 } else {
1260                         input_report_key(ictx->idev, BTN_LEFT, buf[1] & 0x1);
1261                         input_report_key(ictx->idev, BTN_RIGHT,
1262                                          buf[1] >> right_shift & 0x1);
1263                 }
1264                 input_sync(ictx->idev);
1265                 ictx->last_keycode = ictx->kc;
1266         }
1267
1268         return mouse_input;
1269 }
1270
1271 static void imon_touch_event(struct imon_context *ictx, unsigned char *buf)
1272 {
1273         mod_timer(&ictx->ttimer, jiffies + TOUCH_TIMEOUT);
1274         ictx->touch_x = (buf[0] << 4) | (buf[1] >> 4);
1275         ictx->touch_y = 0xfff - ((buf[2] << 4) | (buf[1] & 0xf));
1276         input_report_abs(ictx->touch, ABS_X, ictx->touch_x);
1277         input_report_abs(ictx->touch, ABS_Y, ictx->touch_y);
1278         input_report_key(ictx->touch, BTN_TOUCH, 0x01);
1279         input_sync(ictx->touch);
1280 }
1281
1282 static void imon_pad_to_keys(struct imon_context *ictx, unsigned char *buf)
1283 {
1284         int dir = 0;
1285         char rel_x = 0x00, rel_y = 0x00;
1286         u16 timeout, threshold;
1287         u64 temp_key;
1288         u32 remote_key;
1289
1290         /*
1291          * The imon directional pad functions more like a touchpad. Bytes 3 & 4
1292          * contain a position coordinate (x,y), with each component ranging
1293          * from -14 to 14. We want to down-sample this to only 4 discrete values
1294          * for up/down/left/right arrow keys. Also, when you get too close to
1295          * diagonals, it has a tendancy to jump back and forth, so lets try to
1296          * ignore when they get too close.
1297          */
1298         if (ictx->product != 0xffdc) {
1299                 /* first, pad to 8 bytes so it conforms with everything else */
1300                 buf[5] = buf[6] = buf[7] = 0;
1301                 timeout = 500;  /* in msecs */
1302                 /* (2*threshold) x (2*threshold) square */
1303                 threshold = pad_thresh ? pad_thresh : 28;
1304                 rel_x = buf[2];
1305                 rel_y = buf[3];
1306
1307                 if (ictx->ir_type == IR_TYPE_OTHER && pad_stabilize) {
1308                         if ((buf[1] == 0) && ((rel_x != 0) || (rel_y != 0))) {
1309                                 dir = stabilize((int)rel_x, (int)rel_y,
1310                                                 timeout, threshold);
1311                                 if (!dir) {
1312                                         ictx->kc = KEY_UNKNOWN;
1313                                         return;
1314                                 }
1315                                 buf[2] = dir & 0xFF;
1316                                 buf[3] = (dir >> 8) & 0xFF;
1317                                 memcpy(&temp_key, buf, sizeof(temp_key));
1318                                 remote_key = (u32) (le64_to_cpu(temp_key)
1319                                                     & 0xffffffff);
1320                                 ictx->kc = imon_remote_key_lookup(ictx,
1321                                                                   remote_key);
1322                         }
1323                 } else {
1324                         if (abs(rel_y) > abs(rel_x)) {
1325                                 buf[2] = (rel_y > 0) ? 0x7F : 0x80;
1326                                 buf[3] = 0;
1327                                 ictx->kc = (rel_y > 0) ? KEY_DOWN : KEY_UP;
1328                         } else {
1329                                 buf[2] = 0;
1330                                 buf[3] = (rel_x > 0) ? 0x7F : 0x80;
1331                                 ictx->kc = (rel_x > 0) ? KEY_RIGHT : KEY_LEFT;
1332                         }
1333                 }
1334
1335         /*
1336          * Handle on-board decoded pad events for e.g. older VFD/iMON-Pad
1337          * device (15c2:ffdc). The remote generates various codes from
1338          * 0x68nnnnB7 to 0x6AnnnnB7, the left mouse button generates
1339          * 0x688301b7 and the right one 0x688481b7. All other keys generate
1340          * 0x2nnnnnnn. Position coordinate is encoded in buf[1] and buf[2] with
1341          * reversed endianess. Extract direction from buffer, rotate endianess,
1342          * adjust sign and feed the values into stabilize(). The resulting codes
1343          * will be 0x01008000, 0x01007F00, which match the newer devices.
1344          */
1345         } else {
1346                 timeout = 10;   /* in msecs */
1347                 /* (2*threshold) x (2*threshold) square */
1348                 threshold = pad_thresh ? pad_thresh : 15;
1349
1350                 /* buf[1] is x */
1351                 rel_x = (buf[1] & 0x08) | (buf[1] & 0x10) >> 2 |
1352                         (buf[1] & 0x20) >> 4 | (buf[1] & 0x40) >> 6;
1353                 if (buf[0] & 0x02)
1354                         rel_x |= ~0x10+1;
1355                 /* buf[2] is y */
1356                 rel_y = (buf[2] & 0x08) | (buf[2] & 0x10) >> 2 |
1357                         (buf[2] & 0x20) >> 4 | (buf[2] & 0x40) >> 6;
1358                 if (buf[0] & 0x01)
1359                         rel_y |= ~0x10+1;
1360
1361                 buf[0] = 0x01;
1362                 buf[1] = buf[4] = buf[5] = buf[6] = buf[7] = 0;
1363
1364                 if (ictx->ir_type == IR_TYPE_OTHER && pad_stabilize) {
1365                         dir = stabilize((int)rel_x, (int)rel_y,
1366                                         timeout, threshold);
1367                         if (!dir) {
1368                                 ictx->kc = KEY_UNKNOWN;
1369                                 return;
1370                         }
1371                         buf[2] = dir & 0xFF;
1372                         buf[3] = (dir >> 8) & 0xFF;
1373                         memcpy(&temp_key, buf, sizeof(temp_key));
1374                         remote_key = (u32) (le64_to_cpu(temp_key) & 0xffffffff);
1375                         ictx->kc = imon_remote_key_lookup(ictx, remote_key);
1376                 } else {
1377                         if (abs(rel_y) > abs(rel_x)) {
1378                                 buf[2] = (rel_y > 0) ? 0x7F : 0x80;
1379                                 buf[3] = 0;
1380                                 ictx->kc = (rel_y > 0) ? KEY_DOWN : KEY_UP;
1381                         } else {
1382                                 buf[2] = 0;
1383                                 buf[3] = (rel_x > 0) ? 0x7F : 0x80;
1384                                 ictx->kc = (rel_x > 0) ? KEY_RIGHT : KEY_LEFT;
1385                         }
1386                 }
1387         }
1388 }
1389
1390 static int imon_parse_press_type(struct imon_context *ictx,
1391                                  unsigned char *buf, u8 ktype)
1392 {
1393         int press_type = 0;
1394         int rep_delay = ictx->idev->rep[REP_DELAY];
1395         int rep_period = ictx->idev->rep[REP_PERIOD];
1396
1397         /* key release of 0x02XXXXXX key */
1398         if (ictx->kc == KEY_RESERVED && buf[0] == 0x02 && buf[3] == 0x00)
1399                 ictx->kc = ictx->last_keycode;
1400
1401         /* mouse button release on (some) 0xffdc devices */
1402         else if (ictx->kc == KEY_RESERVED && buf[0] == 0x68 && buf[1] == 0x82 &&
1403                  buf[2] == 0x81 && buf[3] == 0xb7)
1404                 ictx->kc = ictx->last_keycode;
1405
1406         /* mouse button release on (some other) 0xffdc devices */
1407         else if (ictx->kc == KEY_RESERVED && buf[0] == 0x01 && buf[1] == 0x00 &&
1408                  buf[2] == 0x81 && buf[3] == 0xb7)
1409                 ictx->kc = ictx->last_keycode;
1410
1411         /* mce-specific button handling */
1412         else if (ktype == IMON_KEY_MCE) {
1413                 /* initial press */
1414                 if (ictx->kc != ictx->last_keycode
1415                     || buf[2] != ictx->mce_toggle_bit) {
1416                         ictx->last_keycode = ictx->kc;
1417                         ictx->mce_toggle_bit = buf[2];
1418                         press_type = 1;
1419                         mod_timer(&ictx->itimer,
1420                                   jiffies + msecs_to_jiffies(rep_delay));
1421                 /* repeat */
1422                 } else {
1423                         press_type = 2;
1424                         mod_timer(&ictx->itimer,
1425                                   jiffies + msecs_to_jiffies(rep_period));
1426                 }
1427
1428         /* incoherent or irrelevant data */
1429         } else if (ictx->kc == KEY_RESERVED)
1430                 press_type = -EINVAL;
1431
1432         /* key release of 0xXXXXXXb7 key */
1433         else if (ictx->release_code)
1434                 press_type = 0;
1435
1436         /* this is a button press */
1437         else
1438                 press_type = 1;
1439
1440         return press_type;
1441 }
1442
1443 /**
1444  * Process the incoming packet
1445  */
1446 static void imon_incoming_packet(struct imon_context *ictx,
1447                                  struct urb *urb, int intf)
1448 {
1449         int len = urb->actual_length;
1450         unsigned char *buf = urb->transfer_buffer;
1451         struct device *dev = ictx->dev;
1452         u32 kc;
1453         bool norelease = false;
1454         int i;
1455         u64 temp_key;
1456         u64 panel_key = 0;
1457         u32 remote_key = 0;
1458         struct input_dev *idev = NULL;
1459         int press_type = 0;
1460         int msec;
1461         struct timeval t;
1462         static struct timeval prev_time = { 0, 0 };
1463         u8 ktype = IMON_KEY_IMON;
1464
1465         idev = ictx->idev;
1466
1467         /* filter out junk data on the older 0xffdc imon devices */
1468         if ((buf[0] == 0xff) && (buf[1] == 0xff) && (buf[2] == 0xff))
1469                 return;
1470
1471         /* Figure out what key was pressed */
1472         memcpy(&temp_key, buf, sizeof(temp_key));
1473         if (len == 8 && buf[7] == 0xee) {
1474                 ktype = IMON_KEY_PANEL;
1475                 panel_key = le64_to_cpu(temp_key);
1476                 kc = imon_panel_key_lookup(panel_key);
1477         } else {
1478                 remote_key = (u32) (le64_to_cpu(temp_key) & 0xffffffff);
1479                 if (ictx->ir_type == IR_TYPE_RC6) {
1480                         if (buf[0] == 0x80)
1481                                 ktype = IMON_KEY_MCE;
1482                         kc = imon_mce_key_lookup(ictx, remote_key);
1483                 } else
1484                         kc = imon_remote_key_lookup(ictx, remote_key);
1485         }
1486
1487         /* keyboard/mouse mode toggle button */
1488         if (kc == KEY_KEYBOARD && !ictx->release_code) {
1489                 ictx->last_keycode = kc;
1490                 if (!nomouse) {
1491                         ictx->pad_mouse = ~(ictx->pad_mouse) & 0x1;
1492                         dev_dbg(dev, "toggling to %s mode\n",
1493                                 ictx->pad_mouse ? "mouse" : "keyboard");
1494                         return;
1495                 } else {
1496                         ictx->pad_mouse = 0;
1497                         dev_dbg(dev, "mouse mode disabled, passing key value\n");
1498                 }
1499         }
1500
1501         ictx->kc = kc;
1502
1503         /* send touchscreen events through input subsystem if touchpad data */
1504         if (ictx->display_type == IMON_DISPLAY_TYPE_VGA && len == 8 &&
1505             buf[7] == 0x86) {
1506                 imon_touch_event(ictx, buf);
1507
1508         /* look for mouse events with pad in mouse mode */
1509         } else if (ictx->pad_mouse) {
1510                 if (imon_mouse_event(ictx, buf, len))
1511                         return;
1512         }
1513
1514         /* Now for some special handling to convert pad input to arrow keys */
1515         if (((len == 5) && (buf[0] == 0x01) && (buf[4] == 0x00)) ||
1516             ((len == 8) && (buf[0] & 0x40) &&
1517              !(buf[1] & 0x1 || buf[1] >> 2 & 0x1))) {
1518                 len = 8;
1519                 imon_pad_to_keys(ictx, buf);
1520                 norelease = true;
1521         }
1522
1523         if (debug) {
1524                 printk(KERN_INFO "intf%d decoded packet: ", intf);
1525                 for (i = 0; i < len; ++i)
1526                         printk("%02x ", buf[i]);
1527                 printk("\n");
1528         }
1529
1530         press_type = imon_parse_press_type(ictx, buf, ktype);
1531         if (press_type < 0)
1532                 goto not_input_data;
1533
1534         if (ictx->kc == KEY_UNKNOWN)
1535                 goto unknown_key;
1536
1537         /* KEY_MUTE repeats from MCE and knob need to be suppressed */
1538         if ((ictx->kc == KEY_MUTE && ictx->kc == ictx->last_keycode)
1539             && (buf[7] == 0xee || ktype == IMON_KEY_MCE)) {
1540                 do_gettimeofday(&t);
1541                 msec = tv2int(&t, &prev_time);
1542                 prev_time = t;
1543                 if (msec < idev->rep[REP_DELAY])
1544                         return;
1545         }
1546
1547         input_report_key(idev, ictx->kc, press_type);
1548         input_sync(idev);
1549
1550         /* panel keys and some remote keys don't generate a release */
1551         if (panel_key || norelease) {
1552                 input_report_key(idev, ictx->kc, 0);
1553                 input_sync(idev);
1554         }
1555
1556         ictx->last_keycode = ictx->kc;
1557
1558         return;
1559
1560 unknown_key:
1561         dev_info(dev, "%s: unknown keypress, code 0x%llx\n", __func__,
1562                  (panel_key ? be64_to_cpu(panel_key) :
1563                               be32_to_cpu(remote_key)));
1564         return;
1565
1566 not_input_data:
1567         if (len != 8) {
1568                 dev_warn(dev, "imon %s: invalid incoming packet "
1569                          "size (len = %d, intf%d)\n", __func__, len, intf);
1570                 return;
1571         }
1572
1573         /* iMON 2.4G associate frame */
1574         if (buf[0] == 0x00 &&
1575             buf[2] == 0xFF &&                           /* REFID */
1576             buf[3] == 0xFF &&
1577             buf[4] == 0xFF &&
1578             buf[5] == 0xFF &&                           /* iMON 2.4G */
1579            ((buf[6] == 0x4E && buf[7] == 0xDF) ||       /* LT */
1580             (buf[6] == 0x5E && buf[7] == 0xDF))) {      /* DT */
1581                 dev_warn(dev, "%s: remote associated refid=%02X\n",
1582                          __func__, buf[1]);
1583                 ictx->rf_isassociating = false;
1584         }
1585 }
1586
1587 /**
1588  * Callback function for USB core API: receive data
1589  */
1590 static void usb_rx_callback_intf0(struct urb *urb)
1591 {
1592         struct imon_context *ictx;
1593         int intfnum = 0;
1594
1595         if (!urb)
1596                 return;
1597
1598         ictx = (struct imon_context *)urb->context;
1599         if (!ictx)
1600                 return;
1601
1602         switch (urb->status) {
1603         case -ENOENT:           /* usbcore unlink successful! */
1604                 return;
1605
1606         case -ESHUTDOWN:        /* transport endpoint was shut down */
1607                 break;
1608
1609         case 0:
1610                 imon_incoming_packet(ictx, urb, intfnum);
1611                 break;
1612
1613         default:
1614                 dev_warn(ictx->dev, "imon %s: status(%d): ignored\n",
1615                          __func__, urb->status);
1616                 break;
1617         }
1618
1619         usb_submit_urb(ictx->rx_urb_intf0, GFP_ATOMIC);
1620 }
1621
1622 static void usb_rx_callback_intf1(struct urb *urb)
1623 {
1624         struct imon_context *ictx;
1625         int intfnum = 1;
1626
1627         if (!urb)
1628                 return;
1629
1630         ictx = (struct imon_context *)urb->context;
1631         if (!ictx)
1632                 return;
1633
1634         switch (urb->status) {
1635         case -ENOENT:           /* usbcore unlink successful! */
1636                 return;
1637
1638         case -ESHUTDOWN:        /* transport endpoint was shut down */
1639                 break;
1640
1641         case 0:
1642                 imon_incoming_packet(ictx, urb, intfnum);
1643                 break;
1644
1645         default:
1646                 dev_warn(ictx->dev, "imon %s: status(%d): ignored\n",
1647                          __func__, urb->status);
1648                 break;
1649         }
1650
1651         usb_submit_urb(ictx->rx_urb_intf1, GFP_ATOMIC);
1652 }
1653
1654 static struct input_dev *imon_init_idev(struct imon_context *ictx)
1655 {
1656         struct input_dev *idev;
1657         struct ir_dev_props *props;
1658         int ret, i;
1659
1660         idev = input_allocate_device();
1661         if (!idev) {
1662                 dev_err(ictx->dev, "remote input dev allocation failed\n");
1663                 goto idev_alloc_failed;
1664         }
1665
1666         props = kzalloc(sizeof(struct ir_dev_props), GFP_KERNEL);
1667         if (!props) {
1668                 dev_err(ictx->dev, "remote ir dev props allocation failed\n");
1669                 goto props_alloc_failed;
1670         }
1671
1672         snprintf(ictx->name_idev, sizeof(ictx->name_idev),
1673                  "iMON Remote (%04x:%04x)", ictx->vendor, ictx->product);
1674         idev->name = ictx->name_idev;
1675
1676         usb_make_path(ictx->usbdev_intf0, ictx->phys_idev,
1677                       sizeof(ictx->phys_idev));
1678         strlcat(ictx->phys_idev, "/input0", sizeof(ictx->phys_idev));
1679         idev->phys = ictx->phys_idev;
1680
1681         idev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP) | BIT_MASK(EV_REL);
1682
1683         idev->keybit[BIT_WORD(BTN_MOUSE)] =
1684                 BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_RIGHT);
1685         idev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y) |
1686                 BIT_MASK(REL_WHEEL);
1687
1688         /* panel and/or knob code support */
1689         for (i = 0; i < ARRAY_SIZE(imon_panel_key_table); i++) {
1690                 u32 kc = imon_panel_key_table[i].keycode;
1691                 __set_bit(kc, idev->keybit);
1692         }
1693
1694         props->priv = ictx;
1695         props->driver_type = RC_DRIVER_SCANCODE;
1696         /* IR_TYPE_OTHER maps to iMON PAD remote, IR_TYPE_RC6 to MCE remote */
1697         props->allowed_protos = IR_TYPE_OTHER | IR_TYPE_RC6;
1698         props->change_protocol = imon_ir_change_protocol;
1699         ictx->props = props;
1700
1701         usb_to_input_id(ictx->usbdev_intf0, &idev->id);
1702         idev->dev.parent = ictx->dev;
1703
1704         ret = ir_input_register(idev, RC_MAP_IMON_PAD, props, MOD_NAME);
1705         if (ret < 0) {
1706                 dev_err(ictx->dev, "remote input dev register failed\n");
1707                 goto idev_register_failed;
1708         }
1709
1710         return idev;
1711
1712 idev_register_failed:
1713         kfree(props);
1714 props_alloc_failed:
1715         input_free_device(idev);
1716 idev_alloc_failed:
1717
1718         return NULL;
1719 }
1720
1721 static struct input_dev *imon_init_touch(struct imon_context *ictx)
1722 {
1723         struct input_dev *touch;
1724         int ret;
1725
1726         touch = input_allocate_device();
1727         if (!touch) {
1728                 dev_err(ictx->dev, "touchscreen input dev allocation failed\n");
1729                 goto touch_alloc_failed;
1730         }
1731
1732         snprintf(ictx->name_touch, sizeof(ictx->name_touch),
1733                  "iMON USB Touchscreen (%04x:%04x)",
1734                  ictx->vendor, ictx->product);
1735         touch->name = ictx->name_touch;
1736
1737         usb_make_path(ictx->usbdev_intf1, ictx->phys_touch,
1738                       sizeof(ictx->phys_touch));
1739         strlcat(ictx->phys_touch, "/input1", sizeof(ictx->phys_touch));
1740         touch->phys = ictx->phys_touch;
1741
1742         touch->evbit[0] =
1743                 BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
1744         touch->keybit[BIT_WORD(BTN_TOUCH)] =
1745                 BIT_MASK(BTN_TOUCH);
1746         input_set_abs_params(touch, ABS_X,
1747                              0x00, 0xfff, 0, 0);
1748         input_set_abs_params(touch, ABS_Y,
1749                              0x00, 0xfff, 0, 0);
1750
1751         input_set_drvdata(touch, ictx);
1752
1753         usb_to_input_id(ictx->usbdev_intf1, &touch->id);
1754         touch->dev.parent = ictx->dev;
1755         ret = input_register_device(touch);
1756         if (ret <  0) {
1757                 dev_info(ictx->dev, "touchscreen input dev register failed\n");
1758                 goto touch_register_failed;
1759         }
1760
1761         return touch;
1762
1763 touch_register_failed:
1764         input_free_device(ictx->touch);
1765
1766 touch_alloc_failed:
1767         return NULL;
1768 }
1769
1770 static bool imon_find_endpoints(struct imon_context *ictx,
1771                                 struct usb_host_interface *iface_desc)
1772 {
1773         struct usb_endpoint_descriptor *ep;
1774         struct usb_endpoint_descriptor *rx_endpoint = NULL;
1775         struct usb_endpoint_descriptor *tx_endpoint = NULL;
1776         int ifnum = iface_desc->desc.bInterfaceNumber;
1777         int num_endpts = iface_desc->desc.bNumEndpoints;
1778         int i, ep_dir, ep_type;
1779         bool ir_ep_found = false;
1780         bool display_ep_found = false;
1781         bool tx_control = false;
1782
1783         /*
1784          * Scan the endpoint list and set:
1785          *      first input endpoint = IR endpoint
1786          *      first output endpoint = display endpoint
1787          */
1788         for (i = 0; i < num_endpts && !(ir_ep_found && display_ep_found); ++i) {
1789                 ep = &iface_desc->endpoint[i].desc;
1790                 ep_dir = ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK;
1791                 ep_type = ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
1792
1793                 if (!ir_ep_found && ep_dir == USB_DIR_IN &&
1794                     ep_type == USB_ENDPOINT_XFER_INT) {
1795
1796                         rx_endpoint = ep;
1797                         ir_ep_found = true;
1798                         dev_dbg(ictx->dev, "%s: found IR endpoint\n", __func__);
1799
1800                 } else if (!display_ep_found && ep_dir == USB_DIR_OUT &&
1801                            ep_type == USB_ENDPOINT_XFER_INT) {
1802                         tx_endpoint = ep;
1803                         display_ep_found = true;
1804                         dev_dbg(ictx->dev, "%s: found display endpoint\n", __func__);
1805                 }
1806         }
1807
1808         if (ifnum == 0) {
1809                 ictx->rx_endpoint_intf0 = rx_endpoint;
1810                 /*
1811                  * tx is used to send characters to lcd/vfd, associate RF
1812                  * remotes, set IR protocol, and maybe more...
1813                  */
1814                 ictx->tx_endpoint = tx_endpoint;
1815         } else {
1816                 ictx->rx_endpoint_intf1 = rx_endpoint;
1817         }
1818
1819         /*
1820          * If we didn't find a display endpoint, this is probably one of the
1821          * newer iMON devices that use control urb instead of interrupt
1822          */
1823         if (!display_ep_found) {
1824                 tx_control = true;
1825                 display_ep_found = true;
1826                 dev_dbg(ictx->dev, "%s: device uses control endpoint, not "
1827                         "interface OUT endpoint\n", __func__);
1828         }
1829
1830         /*
1831          * Some iMON receivers have no display. Unfortunately, it seems
1832          * that SoundGraph recycles device IDs between devices both with
1833          * and without... :\
1834          */
1835         if (ictx->display_type == IMON_DISPLAY_TYPE_NONE) {
1836                 display_ep_found = false;
1837                 dev_dbg(ictx->dev, "%s: device has no display\n", __func__);
1838         }
1839
1840         /*
1841          * iMON Touch devices have a VGA touchscreen, but no "display", as
1842          * that refers to e.g. /dev/lcd0 (a character device LCD or VFD).
1843          */
1844         if (ictx->display_type == IMON_DISPLAY_TYPE_VGA) {
1845                 display_ep_found = false;
1846                 dev_dbg(ictx->dev, "%s: iMON Touch device found\n", __func__);
1847         }
1848
1849         /* Input endpoint is mandatory */
1850         if (!ir_ep_found)
1851                 err("%s: no valid input (IR) endpoint found.", __func__);
1852
1853         ictx->tx_control = tx_control;
1854
1855         if (display_ep_found)
1856                 ictx->display_supported = true;
1857
1858         return ir_ep_found;
1859
1860 }
1861
1862 static struct imon_context *imon_init_intf0(struct usb_interface *intf)
1863 {
1864         struct imon_context *ictx;
1865         struct urb *rx_urb;
1866         struct urb *tx_urb;
1867         struct device *dev = &intf->dev;
1868         struct usb_host_interface *iface_desc;
1869         int ret = -ENOMEM;
1870
1871         ictx = kzalloc(sizeof(struct imon_context), GFP_KERNEL);
1872         if (!ictx) {
1873                 dev_err(dev, "%s: kzalloc failed for context", __func__);
1874                 goto exit;
1875         }
1876         rx_urb = usb_alloc_urb(0, GFP_KERNEL);
1877         if (!rx_urb) {
1878                 dev_err(dev, "%s: usb_alloc_urb failed for IR urb", __func__);
1879                 goto rx_urb_alloc_failed;
1880         }
1881         tx_urb = usb_alloc_urb(0, GFP_KERNEL);
1882         if (!tx_urb) {
1883                 dev_err(dev, "%s: usb_alloc_urb failed for display urb",
1884                         __func__);
1885                 goto tx_urb_alloc_failed;
1886         }
1887
1888         mutex_init(&ictx->lock);
1889
1890         mutex_lock(&ictx->lock);
1891
1892         ictx->dev = dev;
1893         ictx->usbdev_intf0 = usb_get_dev(interface_to_usbdev(intf));
1894         ictx->dev_present_intf0 = true;
1895         ictx->rx_urb_intf0 = rx_urb;
1896         ictx->tx_urb = tx_urb;
1897         ictx->rf_device = false;
1898
1899         ictx->vendor  = le16_to_cpu(ictx->usbdev_intf0->descriptor.idVendor);
1900         ictx->product = le16_to_cpu(ictx->usbdev_intf0->descriptor.idProduct);
1901
1902         ret = -ENODEV;
1903         iface_desc = intf->cur_altsetting;
1904         if (!imon_find_endpoints(ictx, iface_desc)) {
1905                 goto find_endpoint_failed;
1906         }
1907
1908         ictx->idev = imon_init_idev(ictx);
1909         if (!ictx->idev) {
1910                 dev_err(dev, "%s: input device setup failed\n", __func__);
1911                 goto idev_setup_failed;
1912         }
1913
1914         usb_fill_int_urb(ictx->rx_urb_intf0, ictx->usbdev_intf0,
1915                 usb_rcvintpipe(ictx->usbdev_intf0,
1916                         ictx->rx_endpoint_intf0->bEndpointAddress),
1917                 ictx->usb_rx_buf, sizeof(ictx->usb_rx_buf),
1918                 usb_rx_callback_intf0, ictx,
1919                 ictx->rx_endpoint_intf0->bInterval);
1920
1921         ret = usb_submit_urb(ictx->rx_urb_intf0, GFP_KERNEL);
1922         if (ret) {
1923                 err("%s: usb_submit_urb failed for intf0 (%d)",
1924                     __func__, ret);
1925                 goto urb_submit_failed;
1926         }
1927
1928         return ictx;
1929
1930 urb_submit_failed:
1931         ir_input_unregister(ictx->idev);
1932 idev_setup_failed:
1933 find_endpoint_failed:
1934         mutex_unlock(&ictx->lock);
1935         usb_free_urb(tx_urb);
1936 tx_urb_alloc_failed:
1937         usb_free_urb(rx_urb);
1938 rx_urb_alloc_failed:
1939         kfree(ictx);
1940 exit:
1941         dev_err(dev, "unable to initialize intf0, err %d\n", ret);
1942
1943         return NULL;
1944 }
1945
1946 static struct imon_context *imon_init_intf1(struct usb_interface *intf,
1947                                             struct imon_context *ictx)
1948 {
1949         struct urb *rx_urb;
1950         struct usb_host_interface *iface_desc;
1951         int ret = -ENOMEM;
1952
1953         rx_urb = usb_alloc_urb(0, GFP_KERNEL);
1954         if (!rx_urb) {
1955                 err("%s: usb_alloc_urb failed for IR urb", __func__);
1956                 goto rx_urb_alloc_failed;
1957         }
1958
1959         mutex_lock(&ictx->lock);
1960
1961         if (ictx->display_type == IMON_DISPLAY_TYPE_VGA) {
1962                 init_timer(&ictx->ttimer);
1963                 ictx->ttimer.data = (unsigned long)ictx;
1964                 ictx->ttimer.function = imon_touch_display_timeout;
1965         }
1966
1967         ictx->usbdev_intf1 = usb_get_dev(interface_to_usbdev(intf));
1968         ictx->dev_present_intf1 = true;
1969         ictx->rx_urb_intf1 = rx_urb;
1970
1971         ret = -ENODEV;
1972         iface_desc = intf->cur_altsetting;
1973         if (!imon_find_endpoints(ictx, iface_desc))
1974                 goto find_endpoint_failed;
1975
1976         if (ictx->display_type == IMON_DISPLAY_TYPE_VGA) {
1977                 ictx->touch = imon_init_touch(ictx);
1978                 if (!ictx->touch)
1979                         goto touch_setup_failed;
1980         } else
1981                 ictx->touch = NULL;
1982
1983         usb_fill_int_urb(ictx->rx_urb_intf1, ictx->usbdev_intf1,
1984                 usb_rcvintpipe(ictx->usbdev_intf1,
1985                         ictx->rx_endpoint_intf1->bEndpointAddress),
1986                 ictx->usb_rx_buf, sizeof(ictx->usb_rx_buf),
1987                 usb_rx_callback_intf1, ictx,
1988                 ictx->rx_endpoint_intf1->bInterval);
1989
1990         ret = usb_submit_urb(ictx->rx_urb_intf1, GFP_KERNEL);
1991
1992         if (ret) {
1993                 err("%s: usb_submit_urb failed for intf1 (%d)",
1994                     __func__, ret);
1995                 goto urb_submit_failed;
1996         }
1997
1998         return ictx;
1999
2000 urb_submit_failed:
2001         if (ictx->touch)
2002                 input_unregister_device(ictx->touch);
2003 touch_setup_failed:
2004 find_endpoint_failed:
2005         mutex_unlock(&ictx->lock);
2006         usb_free_urb(rx_urb);
2007 rx_urb_alloc_failed:
2008         dev_err(ictx->dev, "unable to initialize intf0, err %d\n", ret);
2009
2010         return NULL;
2011 }
2012
2013 /*
2014  * The 0x15c2:0xffdc device ID was used for umpteen different imon
2015  * devices, and all of them constantly spew interrupts, even when there
2016  * is no actual data to report. However, byte 6 of this buffer looks like
2017  * its unique across device variants, so we're trying to key off that to
2018  * figure out which display type (if any) and what IR protocol the device
2019  * actually supports. These devices have their IR protocol hard-coded into
2020  * their firmware, they can't be changed on the fly like the newer hardware.
2021  */
2022 static void imon_get_ffdc_type(struct imon_context *ictx)
2023 {
2024         u8 ffdc_cfg_byte = ictx->usb_rx_buf[6];
2025         u8 detected_display_type = IMON_DISPLAY_TYPE_NONE;
2026         u64 allowed_protos = IR_TYPE_OTHER;
2027
2028         switch (ffdc_cfg_byte) {
2029         /* iMON Knob, no display, iMON IR + vol knob */
2030         case 0x21:
2031                 dev_info(ictx->dev, "0xffdc iMON Knob, iMON IR");
2032                 ictx->display_supported = false;
2033                 break;
2034         /* iMON 2.4G LT (usb stick), no display, iMON RF */
2035         case 0x4e:
2036                 dev_info(ictx->dev, "0xffdc iMON 2.4G LT, iMON RF");
2037                 ictx->display_supported = false;
2038                 ictx->rf_device = true;
2039                 break;
2040         /* iMON VFD, no IR (does have vol knob tho) */
2041         case 0x35:
2042                 dev_info(ictx->dev, "0xffdc iMON VFD + knob, no IR");
2043                 detected_display_type = IMON_DISPLAY_TYPE_VFD;
2044                 break;
2045         /* iMON VFD, iMON IR */
2046         case 0x24:
2047         case 0x85:
2048                 dev_info(ictx->dev, "0xffdc iMON VFD, iMON IR");
2049                 detected_display_type = IMON_DISPLAY_TYPE_VFD;
2050                 break;
2051         /* iMON LCD, MCE IR */
2052         case 0x9e:
2053         case 0x9f:
2054                 dev_info(ictx->dev, "0xffdc iMON LCD, MCE IR");
2055                 detected_display_type = IMON_DISPLAY_TYPE_LCD;
2056                 allowed_protos = IR_TYPE_RC6;
2057                 break;
2058         default:
2059                 dev_info(ictx->dev, "Unknown 0xffdc device, "
2060                          "defaulting to VFD and iMON IR");
2061                 detected_display_type = IMON_DISPLAY_TYPE_VFD;
2062                 break;
2063         }
2064
2065         printk(KERN_CONT " (id 0x%02x)\n", ffdc_cfg_byte);
2066
2067         ictx->display_type = detected_display_type;
2068         ictx->props->allowed_protos = allowed_protos;
2069         ictx->ir_type = allowed_protos;
2070 }
2071
2072 static void imon_set_display_type(struct imon_context *ictx,
2073                                   struct usb_interface *intf)
2074 {
2075         u8 configured_display_type = IMON_DISPLAY_TYPE_VFD;
2076
2077         /*
2078          * Try to auto-detect the type of display if the user hasn't set
2079          * it by hand via the display_type modparam. Default is VFD.
2080          */
2081
2082         if (display_type == IMON_DISPLAY_TYPE_AUTO) {
2083                 switch (ictx->product) {
2084                 case 0xffdc:
2085                         /* set in imon_get_ffdc_type() */
2086                         configured_display_type = ictx->display_type;
2087                         break;
2088                 case 0x0034:
2089                 case 0x0035:
2090                         configured_display_type = IMON_DISPLAY_TYPE_VGA;
2091                         break;
2092                 case 0x0038:
2093                 case 0x0039:
2094                 case 0x0045:
2095                         configured_display_type = IMON_DISPLAY_TYPE_LCD;
2096                         break;
2097                 case 0x003c:
2098                 case 0x0041:
2099                 case 0x0042:
2100                 case 0x0043:
2101                         configured_display_type = IMON_DISPLAY_TYPE_NONE;
2102                         ictx->display_supported = false;
2103                         break;
2104                 case 0x0036:
2105                 case 0x0044:
2106                 default:
2107                         configured_display_type = IMON_DISPLAY_TYPE_VFD;
2108                         break;
2109                 }
2110         } else {
2111                 configured_display_type = display_type;
2112                 if (display_type == IMON_DISPLAY_TYPE_NONE)
2113                         ictx->display_supported = false;
2114                 else
2115                         ictx->display_supported = true;
2116                 dev_info(ictx->dev, "%s: overriding display type to %d via "
2117                          "modparam\n", __func__, display_type);
2118         }
2119
2120         ictx->display_type = configured_display_type;
2121 }
2122
2123 static void imon_init_display(struct imon_context *ictx,
2124                               struct usb_interface *intf)
2125 {
2126         int ret;
2127
2128         dev_dbg(ictx->dev, "Registering iMON display with sysfs\n");
2129
2130         /* set up sysfs entry for built-in clock */
2131         ret = sysfs_create_group(&intf->dev.kobj,
2132                                  &imon_display_attribute_group);
2133         if (ret)
2134                 dev_err(ictx->dev, "Could not create display sysfs "
2135                         "entries(%d)", ret);
2136
2137         if (ictx->display_type == IMON_DISPLAY_TYPE_LCD)
2138                 ret = usb_register_dev(intf, &imon_lcd_class);
2139         else
2140                 ret = usb_register_dev(intf, &imon_vfd_class);
2141         if (ret)
2142                 /* Not a fatal error, so ignore */
2143                 dev_info(ictx->dev, "could not get a minor number for "
2144                          "display\n");
2145
2146 }
2147
2148 /**
2149  * Callback function for USB core API: Probe
2150  */
2151 static int __devinit imon_probe(struct usb_interface *interface,
2152                                 const struct usb_device_id *id)
2153 {
2154         struct usb_device *usbdev = NULL;
2155         struct usb_host_interface *iface_desc = NULL;
2156         struct usb_interface *first_if;
2157         struct device *dev = &interface->dev;
2158         int ifnum, code_length, sysfs_err;
2159         int ret = 0;
2160         struct imon_context *ictx = NULL;
2161         struct imon_context *first_if_ctx = NULL;
2162         u16 vendor, product;
2163         const unsigned char fp_packet[] = { 0x40, 0x00, 0x00, 0x00,
2164                                             0x00, 0x00, 0x00, 0x88 };
2165
2166         code_length = BUF_CHUNK_SIZE * 8;
2167
2168         usbdev     = usb_get_dev(interface_to_usbdev(interface));
2169         iface_desc = interface->cur_altsetting;
2170         ifnum      = iface_desc->desc.bInterfaceNumber;
2171         vendor     = le16_to_cpu(usbdev->descriptor.idVendor);
2172         product    = le16_to_cpu(usbdev->descriptor.idProduct);
2173
2174         dev_dbg(dev, "%s: found iMON device (%04x:%04x, intf%d)\n",
2175                 __func__, vendor, product, ifnum);
2176
2177         /* prevent races probing devices w/multiple interfaces */
2178         mutex_lock(&driver_lock);
2179
2180         first_if = usb_ifnum_to_if(usbdev, 0);
2181         first_if_ctx = (struct imon_context *)usb_get_intfdata(first_if);
2182
2183         if (ifnum == 0) {
2184                 ictx = imon_init_intf0(interface);
2185                 if (!ictx) {
2186                         err("%s: failed to initialize context!\n", __func__);
2187                         ret = -ENODEV;
2188                         goto fail;
2189                 }
2190
2191         } else {
2192         /* this is the secondary interface on the device */
2193                 ictx = imon_init_intf1(interface, first_if_ctx);
2194                 if (!ictx) {
2195                         err("%s: failed to attach to context!\n", __func__);
2196                         ret = -ENODEV;
2197                         goto fail;
2198                 }
2199
2200         }
2201
2202         usb_set_intfdata(interface, ictx);
2203
2204         if (ifnum == 0) {
2205                 /* Enable front-panel buttons and/or knobs */
2206                 memcpy(ictx->usb_tx_buf, &fp_packet, sizeof(fp_packet));
2207                 ret = send_packet(ictx);
2208                 /* Not fatal, but warn about it */
2209                 if (ret)
2210                         dev_info(dev, "failed to enable panel buttons "
2211                                  "and/or knobs\n");
2212
2213                 if (product == 0xffdc)
2214                         imon_get_ffdc_type(ictx);
2215
2216                 imon_set_display_type(ictx, interface);
2217
2218                 if (product == 0xffdc && ictx->rf_device) {
2219                         sysfs_err = sysfs_create_group(&interface->dev.kobj,
2220                                                        &imon_rf_attribute_group);
2221                         if (sysfs_err)
2222                                 err("%s: Could not create RF sysfs entries(%d)",
2223                                     __func__, sysfs_err);
2224                 }
2225
2226                 if (ictx->display_supported)
2227                         imon_init_display(ictx, interface);
2228         }
2229
2230         /* set IR protocol/remote type */
2231         ret = imon_ir_change_protocol(ictx, ictx->ir_type);
2232         if (ret) {
2233                 dev_warn(dev, "%s: failed to set IR protocol, falling back "
2234                          "to standard iMON protocol mode\n", __func__);
2235                 ictx->ir_type = IR_TYPE_OTHER;
2236         }
2237
2238         dev_info(dev, "iMON device (%04x:%04x, intf%d) on "
2239                  "usb<%d:%d> initialized\n", vendor, product, ifnum,
2240                  usbdev->bus->busnum, usbdev->devnum);
2241
2242         mutex_unlock(&ictx->lock);
2243         mutex_unlock(&driver_lock);
2244
2245         return 0;
2246
2247 fail:
2248         mutex_unlock(&driver_lock);
2249         dev_err(dev, "unable to register, err %d\n", ret);
2250
2251         return ret;
2252 }
2253
2254 /**
2255  * Callback function for USB core API: disconnect
2256  */
2257 static void __devexit imon_disconnect(struct usb_interface *interface)
2258 {
2259         struct imon_context *ictx;
2260         struct device *dev;
2261         int ifnum;
2262
2263         /* prevent races with multi-interface device probing and display_open */
2264         mutex_lock(&driver_lock);
2265
2266         ictx = usb_get_intfdata(interface);
2267         dev = ictx->dev;
2268         ifnum = interface->cur_altsetting->desc.bInterfaceNumber;
2269
2270         mutex_lock(&ictx->lock);
2271
2272         /*
2273          * sysfs_remove_group is safe to call even if sysfs_create_group
2274          * hasn't been called
2275          */
2276         sysfs_remove_group(&interface->dev.kobj,
2277                            &imon_display_attribute_group);
2278         sysfs_remove_group(&interface->dev.kobj,
2279                            &imon_rf_attribute_group);
2280
2281         usb_set_intfdata(interface, NULL);
2282
2283         /* Abort ongoing write */
2284         if (ictx->tx.busy) {
2285                 usb_kill_urb(ictx->tx_urb);
2286                 complete_all(&ictx->tx.finished);
2287         }
2288
2289         if (ifnum == 0) {
2290                 ictx->dev_present_intf0 = false;
2291                 usb_kill_urb(ictx->rx_urb_intf0);
2292                 ir_input_unregister(ictx->idev);
2293                 if (ictx->display_supported) {
2294                         if (ictx->display_type == IMON_DISPLAY_TYPE_LCD)
2295                                 usb_deregister_dev(interface, &imon_lcd_class);
2296                         else
2297                                 usb_deregister_dev(interface, &imon_vfd_class);
2298                 }
2299         } else {
2300                 ictx->dev_present_intf1 = false;
2301                 usb_kill_urb(ictx->rx_urb_intf1);
2302                 if (ictx->display_type == IMON_DISPLAY_TYPE_VGA)
2303                         input_unregister_device(ictx->touch);
2304         }
2305
2306         if (!ictx->dev_present_intf0 && !ictx->dev_present_intf1) {
2307                 if (ictx->display_type == IMON_DISPLAY_TYPE_VGA)
2308                         del_timer_sync(&ictx->ttimer);
2309                 mutex_unlock(&ictx->lock);
2310                 if (!ictx->display_isopen)
2311                         free_imon_context(ictx);
2312         } else {
2313                 if (ictx->ir_type == IR_TYPE_RC6)
2314                         del_timer_sync(&ictx->itimer);
2315                 mutex_unlock(&ictx->lock);
2316         }
2317
2318         mutex_unlock(&driver_lock);
2319
2320         dev_dbg(dev, "%s: iMON device (intf%d) disconnected\n",
2321                 __func__, ifnum);
2322 }
2323
2324 static int imon_suspend(struct usb_interface *intf, pm_message_t message)
2325 {
2326         struct imon_context *ictx = usb_get_intfdata(intf);
2327         int ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2328
2329         if (ifnum == 0)
2330                 usb_kill_urb(ictx->rx_urb_intf0);
2331         else
2332                 usb_kill_urb(ictx->rx_urb_intf1);
2333
2334         return 0;
2335 }
2336
2337 static int imon_resume(struct usb_interface *intf)
2338 {
2339         int rc = 0;
2340         struct imon_context *ictx = usb_get_intfdata(intf);
2341         int ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2342
2343         if (ifnum == 0) {
2344                 usb_fill_int_urb(ictx->rx_urb_intf0, ictx->usbdev_intf0,
2345                         usb_rcvintpipe(ictx->usbdev_intf0,
2346                                 ictx->rx_endpoint_intf0->bEndpointAddress),
2347                         ictx->usb_rx_buf, sizeof(ictx->usb_rx_buf),
2348                         usb_rx_callback_intf0, ictx,
2349                         ictx->rx_endpoint_intf0->bInterval);
2350
2351                 rc = usb_submit_urb(ictx->rx_urb_intf0, GFP_ATOMIC);
2352
2353         } else {
2354                 usb_fill_int_urb(ictx->rx_urb_intf1, ictx->usbdev_intf1,
2355                         usb_rcvintpipe(ictx->usbdev_intf1,
2356                                 ictx->rx_endpoint_intf1->bEndpointAddress),
2357                         ictx->usb_rx_buf, sizeof(ictx->usb_rx_buf),
2358                         usb_rx_callback_intf1, ictx,
2359                         ictx->rx_endpoint_intf1->bInterval);
2360
2361                 rc = usb_submit_urb(ictx->rx_urb_intf1, GFP_ATOMIC);
2362         }
2363
2364         return rc;
2365 }
2366
2367 static int __init imon_init(void)
2368 {
2369         int rc;
2370
2371         rc = usb_register(&imon_driver);
2372         if (rc) {
2373                 err("%s: usb register failed(%d)", __func__, rc);
2374                 rc = -ENODEV;
2375         }
2376
2377         return rc;
2378 }
2379
2380 static void __exit imon_exit(void)
2381 {
2382         usb_deregister(&imon_driver);
2383 }
2384
2385 module_init(imon_init);
2386 module_exit(imon_exit);