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