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