[media] drivers/media/IR/imon.c: Use pr_err instead of err
[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 #define pr_fmt(fmt) KBUILD_MODNAME ":%s: " fmt, __func__
30
31 #include <linux/errno.h>
32 #include <linux/init.h>
33 #include <linux/kernel.h>
34 #include <linux/module.h>
35 #include <linux/slab.h>
36 #include <linux/uaccess.h>
37
38 #include <linux/input.h>
39 #include <linux/usb.h>
40 #include <linux/usb/input.h>
41 #include <media/ir-core.h>
42
43 #include <linux/time.h>
44 #include <linux/timer.h>
45
46 #define MOD_AUTHOR      "Jarod Wilson <jarod@wilsonet.com>"
47 #define MOD_DESC        "Driver for SoundGraph iMON MultiMedia IR/Display"
48 #define MOD_NAME        "imon"
49 #define MOD_VERSION     "0.9.2"
50
51 #define DISPLAY_MINOR_BASE      144
52 #define DEVICE_NAME     "lcd%d"
53
54 #define BUF_CHUNK_SIZE  8
55 #define BUF_SIZE        128
56
57 #define BIT_DURATION    250     /* each bit received is 250us */
58
59 #define IMON_CLOCK_ENABLE_PACKETS       2
60
61 /*** P R O T O T Y P E S ***/
62
63 /* USB Callback prototypes */
64 static int imon_probe(struct usb_interface *interface,
65                       const struct usb_device_id *id);
66 static void imon_disconnect(struct usb_interface *interface);
67 static void usb_rx_callback_intf0(struct urb *urb);
68 static void usb_rx_callback_intf1(struct urb *urb);
69 static void usb_tx_callback(struct urb *urb);
70
71 /* suspend/resume support */
72 static int imon_resume(struct usb_interface *intf);
73 static int imon_suspend(struct usb_interface *intf, pm_message_t message);
74
75 /* Display file_operations function prototypes */
76 static int display_open(struct inode *inode, struct file *file);
77 static int display_close(struct inode *inode, struct file *file);
78
79 /* VFD write operation */
80 static ssize_t vfd_write(struct file *file, const char *buf,
81                          size_t n_bytes, loff_t *pos);
82
83 /* LCD file_operations override function prototypes */
84 static ssize_t lcd_write(struct file *file, const char *buf,
85                          size_t n_bytes, loff_t *pos);
86
87 /*** G L O B A L S ***/
88
89 struct imon_context {
90         struct device *dev;
91         struct ir_dev_props *props;
92         /* Newer devices have two interfaces */
93         struct usb_device *usbdev_intf0;
94         struct usb_device *usbdev_intf1;
95
96         bool display_supported;         /* not all controllers do */
97         bool display_isopen;            /* display port has been opened */
98         bool rf_device;                 /* true if iMON 2.4G LT/DT RF device */
99         bool rf_isassociating;          /* RF remote associating */
100         bool dev_present_intf0;         /* USB device presence, interface 0 */
101         bool dev_present_intf1;         /* USB device presence, interface 1 */
102
103         struct mutex lock;              /* to lock this object */
104         wait_queue_head_t remove_ok;    /* For unexpected USB disconnects */
105
106         struct usb_endpoint_descriptor *rx_endpoint_intf0;
107         struct usb_endpoint_descriptor *rx_endpoint_intf1;
108         struct usb_endpoint_descriptor *tx_endpoint;
109         struct urb *rx_urb_intf0;
110         struct urb *rx_urb_intf1;
111         struct urb *tx_urb;
112         bool tx_control;
113         unsigned char usb_rx_buf[8];
114         unsigned char usb_tx_buf[8];
115
116         struct tx_t {
117                 unsigned char data_buf[35];     /* user data buffer */
118                 struct completion finished;     /* wait for write to finish */
119                 bool busy;                      /* write in progress */
120                 int status;                     /* status of tx completion */
121         } tx;
122
123         u16 vendor;                     /* usb vendor ID */
124         u16 product;                    /* usb product ID */
125
126         struct input_dev *rdev;         /* input device for remote */
127         struct input_dev *idev;         /* input device for panel & IR mouse */
128         struct input_dev *touch;        /* input device for touchscreen */
129
130         spinlock_t kc_lock;             /* make sure we get keycodes right */
131         u32 kc;                         /* current input keycode */
132         u32 last_keycode;               /* last reported input keycode */
133         u32 rc_scancode;                /* the computed remote scancode */
134         u8 rc_toggle;                   /* the computed remote toggle bit */
135         u64 ir_type;                    /* iMON or MCE (RC6) IR protocol? */
136         bool release_code;              /* some keys send a release code */
137
138         u8 display_type;                /* store the display type */
139         bool pad_mouse;                 /* toggle kbd(0)/mouse(1) mode */
140
141         char name_rdev[128];            /* rc input device name */
142         char phys_rdev[64];             /* rc input device phys path */
143
144         char name_idev[128];            /* input device name */
145         char phys_idev[64];             /* input device phys path */
146
147         char name_touch[128];           /* touch screen name */
148         char phys_touch[64];            /* touch screen phys path */
149         struct timer_list ttimer;       /* touch screen timer */
150         int touch_x;                    /* x coordinate on touchscreen */
151         int touch_y;                    /* y coordinate on touchscreen */
152 };
153
154 #define TOUCH_TIMEOUT   (HZ/30)
155
156 /* vfd character device file operations */
157 static const struct file_operations vfd_fops = {
158         .owner          = THIS_MODULE,
159         .open           = &display_open,
160         .write          = &vfd_write,
161         .release        = &display_close
162 };
163
164 /* lcd character device file operations */
165 static const struct file_operations lcd_fops = {
166         .owner          = THIS_MODULE,
167         .open           = &display_open,
168         .write          = &lcd_write,
169         .release        = &display_close
170 };
171
172 enum {
173         IMON_DISPLAY_TYPE_AUTO = 0,
174         IMON_DISPLAY_TYPE_VFD  = 1,
175         IMON_DISPLAY_TYPE_LCD  = 2,
176         IMON_DISPLAY_TYPE_VGA  = 3,
177         IMON_DISPLAY_TYPE_NONE = 4,
178 };
179
180 enum {
181         IMON_KEY_IMON   = 0,
182         IMON_KEY_MCE    = 1,
183         IMON_KEY_PANEL  = 2,
184 };
185
186 /*
187  * USB Device ID for iMON USB Control Boards
188  *
189  * The Windows drivers contain 6 different inf files, more or less one for
190  * each new device until the 0x0034-0x0046 devices, which all use the same
191  * driver. Some of the devices in the 34-46 range haven't been definitively
192  * identified yet. Early devices have either a TriGem Computer, Inc. or a
193  * Samsung vendor ID (0x0aa8 and 0x04e8 respectively), while all later
194  * devices use the SoundGraph vendor ID (0x15c2). This driver only supports
195  * the ffdc and later devices, which do onboard decoding.
196  */
197 static struct usb_device_id imon_usb_id_table[] = {
198         /*
199          * Several devices with this same device ID, all use iMON_PAD.inf
200          * SoundGraph iMON PAD (IR & VFD)
201          * SoundGraph iMON PAD (IR & LCD)
202          * SoundGraph iMON Knob (IR only)
203          */
204         { USB_DEVICE(0x15c2, 0xffdc) },
205
206         /*
207          * Newer devices, all driven by the latest iMON Windows driver, full
208          * list of device IDs extracted via 'strings Setup/data1.hdr |grep 15c2'
209          * Need user input to fill in details on unknown devices.
210          */
211         /* SoundGraph iMON OEM Touch LCD (IR & 7" VGA LCD) */
212         { USB_DEVICE(0x15c2, 0x0034) },
213         /* SoundGraph iMON OEM Touch LCD (IR & 4.3" VGA LCD) */
214         { USB_DEVICE(0x15c2, 0x0035) },
215         /* SoundGraph iMON OEM VFD (IR & VFD) */
216         { USB_DEVICE(0x15c2, 0x0036) },
217         /* device specifics unknown */
218         { USB_DEVICE(0x15c2, 0x0037) },
219         /* SoundGraph iMON OEM LCD (IR & LCD) */
220         { USB_DEVICE(0x15c2, 0x0038) },
221         /* SoundGraph iMON UltraBay (IR & LCD) */
222         { USB_DEVICE(0x15c2, 0x0039) },
223         /* device specifics unknown */
224         { USB_DEVICE(0x15c2, 0x003a) },
225         /* device specifics unknown */
226         { USB_DEVICE(0x15c2, 0x003b) },
227         /* SoundGraph iMON OEM Inside (IR only) */
228         { USB_DEVICE(0x15c2, 0x003c) },
229         /* device specifics unknown */
230         { USB_DEVICE(0x15c2, 0x003d) },
231         /* device specifics unknown */
232         { USB_DEVICE(0x15c2, 0x003e) },
233         /* device specifics unknown */
234         { USB_DEVICE(0x15c2, 0x003f) },
235         /* device specifics unknown */
236         { USB_DEVICE(0x15c2, 0x0040) },
237         /* SoundGraph iMON MINI (IR only) */
238         { USB_DEVICE(0x15c2, 0x0041) },
239         /* Antec Veris Multimedia Station EZ External (IR only) */
240         { USB_DEVICE(0x15c2, 0x0042) },
241         /* Antec Veris Multimedia Station Basic Internal (IR only) */
242         { USB_DEVICE(0x15c2, 0x0043) },
243         /* Antec Veris Multimedia Station Elite (IR & VFD) */
244         { USB_DEVICE(0x15c2, 0x0044) },
245         /* Antec Veris Multimedia Station Premiere (IR & LCD) */
246         { USB_DEVICE(0x15c2, 0x0045) },
247         /* device specifics unknown */
248         { USB_DEVICE(0x15c2, 0x0046) },
249         {}
250 };
251
252 /* USB Device data */
253 static struct usb_driver imon_driver = {
254         .name           = MOD_NAME,
255         .probe          = imon_probe,
256         .disconnect     = imon_disconnect,
257         .suspend        = imon_suspend,
258         .resume         = imon_resume,
259         .id_table       = imon_usb_id_table,
260 };
261
262 static struct usb_class_driver imon_vfd_class = {
263         .name           = DEVICE_NAME,
264         .fops           = &vfd_fops,
265         .minor_base     = DISPLAY_MINOR_BASE,
266 };
267
268 static struct usb_class_driver imon_lcd_class = {
269         .name           = DEVICE_NAME,
270         .fops           = &lcd_fops,
271         .minor_base     = DISPLAY_MINOR_BASE,
272 };
273
274 /* imon receiver front panel/knob key table */
275 static const struct {
276         u64 hw_code;
277         u32 keycode;
278 } imon_panel_key_table[] = {
279         { 0x000000000f00ffeell, KEY_PROG1 }, /* Go */
280         { 0x000000001f00ffeell, KEY_AUDIO },
281         { 0x000000002000ffeell, KEY_VIDEO },
282         { 0x000000002100ffeell, KEY_CAMERA },
283         { 0x000000002700ffeell, KEY_DVD },
284         { 0x000000002300ffeell, KEY_TV },
285         { 0x000000000500ffeell, KEY_PREVIOUS },
286         { 0x000000000700ffeell, KEY_REWIND },
287         { 0x000000000400ffeell, KEY_STOP },
288         { 0x000000003c00ffeell, KEY_PLAYPAUSE },
289         { 0x000000000800ffeell, KEY_FASTFORWARD },
290         { 0x000000000600ffeell, KEY_NEXT },
291         { 0x000000010000ffeell, KEY_RIGHT },
292         { 0x000001000000ffeell, KEY_LEFT },
293         { 0x000000003d00ffeell, KEY_SELECT },
294         { 0x000100000000ffeell, KEY_VOLUMEUP },
295         { 0x010000000000ffeell, KEY_VOLUMEDOWN },
296         { 0x000000000100ffeell, KEY_MUTE },
297         /* 0xffdc iMON MCE VFD */
298         { 0x00010000ffffffeell, KEY_VOLUMEUP },
299         { 0x01000000ffffffeell, KEY_VOLUMEDOWN },
300         /* iMON Knob values */
301         { 0x000100ffffffffeell, KEY_VOLUMEUP },
302         { 0x010000ffffffffeell, KEY_VOLUMEDOWN },
303         { 0x000008ffffffffeell, KEY_MUTE },
304 };
305
306 /* to prevent races between open() and disconnect(), probing, etc */
307 static DEFINE_MUTEX(driver_lock);
308
309 /* Module bookkeeping bits */
310 MODULE_AUTHOR(MOD_AUTHOR);
311 MODULE_DESCRIPTION(MOD_DESC);
312 MODULE_VERSION(MOD_VERSION);
313 MODULE_LICENSE("GPL");
314 MODULE_DEVICE_TABLE(usb, imon_usb_id_table);
315
316 static bool debug;
317 module_param(debug, bool, S_IRUGO | S_IWUSR);
318 MODULE_PARM_DESC(debug, "Debug messages: 0=no, 1=yes(default: no)");
319
320 /* lcd, vfd, vga or none? should be auto-detected, but can be overridden... */
321 static int display_type;
322 module_param(display_type, int, S_IRUGO);
323 MODULE_PARM_DESC(display_type, "Type of attached display. 0=autodetect, "
324                  "1=vfd, 2=lcd, 3=vga, 4=none (default: autodetect)");
325
326 static int pad_stabilize = 1;
327 module_param(pad_stabilize, int, S_IRUGO | S_IWUSR);
328 MODULE_PARM_DESC(pad_stabilize, "Apply stabilization algorithm to iMON PAD "
329                  "presses in arrow key mode. 0=disable, 1=enable (default).");
330
331 /*
332  * In certain use cases, mouse mode isn't really helpful, and could actually
333  * cause confusion, so allow disabling it when the IR device is open.
334  */
335 static bool nomouse;
336 module_param(nomouse, bool, S_IRUGO | S_IWUSR);
337 MODULE_PARM_DESC(nomouse, "Disable mouse input device mode when IR device is "
338                  "open. 0=don't disable, 1=disable. (default: don't disable)");
339
340 /* threshold at which a pad push registers as an arrow key in kbd mode */
341 static int pad_thresh;
342 module_param(pad_thresh, int, S_IRUGO | S_IWUSR);
343 MODULE_PARM_DESC(pad_thresh, "Threshold at which a pad push registers as an "
344                  "arrow key in kbd mode (default: 28)");
345
346
347 static void free_imon_context(struct imon_context *ictx)
348 {
349         struct device *dev = ictx->dev;
350
351         usb_free_urb(ictx->tx_urb);
352         usb_free_urb(ictx->rx_urb_intf0);
353         usb_free_urb(ictx->rx_urb_intf1);
354         kfree(ictx);
355
356         dev_dbg(dev, "%s: iMON context freed\n", __func__);
357 }
358
359 /**
360  * Called when the Display device (e.g. /dev/lcd0)
361  * is opened by the application.
362  */
363 static int display_open(struct inode *inode, struct file *file)
364 {
365         struct usb_interface *interface;
366         struct imon_context *ictx = NULL;
367         int subminor;
368         int retval = 0;
369
370         /* prevent races with disconnect */
371         mutex_lock(&driver_lock);
372
373         subminor = iminor(inode);
374         interface = usb_find_interface(&imon_driver, subminor);
375         if (!interface) {
376                 pr_err("could not find interface for minor %d\n", subminor);
377                 retval = -ENODEV;
378                 goto exit;
379         }
380         ictx = usb_get_intfdata(interface);
381
382         if (!ictx) {
383                 pr_err("no context found for minor %d\n", subminor);
384                 retval = -ENODEV;
385                 goto exit;
386         }
387
388         mutex_lock(&ictx->lock);
389
390         if (!ictx->display_supported) {
391                 pr_err("display not supported by device\n");
392                 retval = -ENODEV;
393         } else if (ictx->display_isopen) {
394                 pr_err("display port is already open\n");
395                 retval = -EBUSY;
396         } else {
397                 ictx->display_isopen = true;
398                 file->private_data = ictx;
399                 dev_dbg(ictx->dev, "display port opened\n");
400         }
401
402         mutex_unlock(&ictx->lock);
403
404 exit:
405         mutex_unlock(&driver_lock);
406         return retval;
407 }
408
409 /**
410  * Called when the display device (e.g. /dev/lcd0)
411  * is closed by the application.
412  */
413 static int display_close(struct inode *inode, struct file *file)
414 {
415         struct imon_context *ictx = NULL;
416         int retval = 0;
417
418         ictx = file->private_data;
419
420         if (!ictx) {
421                 pr_err("no context for device\n");
422                 return -ENODEV;
423         }
424
425         mutex_lock(&ictx->lock);
426
427         if (!ictx->display_supported) {
428                 pr_err("display not supported by device\n");
429                 retval = -ENODEV;
430         } else if (!ictx->display_isopen) {
431                 pr_err("display is not open\n");
432                 retval = -EIO;
433         } else {
434                 ictx->display_isopen = false;
435                 dev_dbg(ictx->dev, "display port closed\n");
436                 if (!ictx->dev_present_intf0) {
437                         /*
438                          * Device disconnected before close and IR port is not
439                          * open. If IR port is open, context will be deleted by
440                          * ir_close.
441                          */
442                         mutex_unlock(&ictx->lock);
443                         free_imon_context(ictx);
444                         return retval;
445                 }
446         }
447
448         mutex_unlock(&ictx->lock);
449         return retval;
450 }
451
452 /**
453  * Sends a packet to the device -- this function must be called
454  * with ictx->lock held.
455  */
456 static int send_packet(struct imon_context *ictx)
457 {
458         unsigned int pipe;
459         unsigned long timeout;
460         int interval = 0;
461         int retval = 0;
462         struct usb_ctrlrequest *control_req = NULL;
463
464         /* Check if we need to use control or interrupt urb */
465         if (!ictx->tx_control) {
466                 pipe = usb_sndintpipe(ictx->usbdev_intf0,
467                                       ictx->tx_endpoint->bEndpointAddress);
468                 interval = ictx->tx_endpoint->bInterval;
469
470                 usb_fill_int_urb(ictx->tx_urb, ictx->usbdev_intf0, pipe,
471                                  ictx->usb_tx_buf,
472                                  sizeof(ictx->usb_tx_buf),
473                                  usb_tx_callback, ictx, interval);
474
475                 ictx->tx_urb->actual_length = 0;
476         } else {
477                 /* fill request into kmalloc'ed space: */
478                 control_req = kmalloc(sizeof(struct usb_ctrlrequest),
479                                       GFP_KERNEL);
480                 if (control_req == NULL)
481                         return -ENOMEM;
482
483                 /* setup packet is '21 09 0200 0001 0008' */
484                 control_req->bRequestType = 0x21;
485                 control_req->bRequest = 0x09;
486                 control_req->wValue = cpu_to_le16(0x0200);
487                 control_req->wIndex = cpu_to_le16(0x0001);
488                 control_req->wLength = cpu_to_le16(0x0008);
489
490                 /* control pipe is endpoint 0x00 */
491                 pipe = usb_sndctrlpipe(ictx->usbdev_intf0, 0);
492
493                 /* build the control urb */
494                 usb_fill_control_urb(ictx->tx_urb, ictx->usbdev_intf0,
495                                      pipe, (unsigned char *)control_req,
496                                      ictx->usb_tx_buf,
497                                      sizeof(ictx->usb_tx_buf),
498                                      usb_tx_callback, ictx);
499                 ictx->tx_urb->actual_length = 0;
500         }
501
502         init_completion(&ictx->tx.finished);
503         ictx->tx.busy = true;
504         smp_rmb(); /* ensure later readers know we're busy */
505
506         retval = usb_submit_urb(ictx->tx_urb, GFP_KERNEL);
507         if (retval) {
508                 ictx->tx.busy = false;
509                 smp_rmb(); /* ensure later readers know we're not busy */
510                 pr_err("error submitting urb(%d)\n", retval);
511         } else {
512                 /* Wait for transmission to complete (or abort) */
513                 mutex_unlock(&ictx->lock);
514                 retval = wait_for_completion_interruptible(
515                                 &ictx->tx.finished);
516                 if (retval)
517                         pr_err("task interrupted\n");
518                 mutex_lock(&ictx->lock);
519
520                 retval = ictx->tx.status;
521                 if (retval)
522                         pr_err("packet tx failed (%d)\n", retval);
523         }
524
525         kfree(control_req);
526
527         /*
528          * Induce a mandatory 5ms delay before returning, as otherwise,
529          * send_packet can get called so rapidly as to overwhelm the device,
530          * particularly on faster systems and/or those with quirky usb.
531          */
532         timeout = msecs_to_jiffies(5);
533         set_current_state(TASK_UNINTERRUPTIBLE);
534         schedule_timeout(timeout);
535
536         return retval;
537 }
538
539 /**
540  * Sends an associate packet to the iMON 2.4G.
541  *
542  * This might not be such a good idea, since it has an id collision with
543  * some versions of the "IR & VFD" combo. The only way to determine if it
544  * is an RF version is to look at the product description string. (Which
545  * we currently do not fetch).
546  */
547 static int send_associate_24g(struct imon_context *ictx)
548 {
549         int retval;
550         const unsigned char packet[8] = { 0x01, 0x00, 0x00, 0x00,
551                                           0x00, 0x00, 0x00, 0x20 };
552
553         if (!ictx) {
554                 pr_err("no context for device\n");
555                 return -ENODEV;
556         }
557
558         if (!ictx->dev_present_intf0) {
559                 pr_err("no iMON device present\n");
560                 return -ENODEV;
561         }
562
563         memcpy(ictx->usb_tx_buf, packet, sizeof(packet));
564         retval = send_packet(ictx);
565
566         return retval;
567 }
568
569 /**
570  * Sends packets to setup and show clock on iMON display
571  *
572  * Arguments: year - last 2 digits of year, month - 1..12,
573  * day - 1..31, dow - day of the week (0-Sun...6-Sat),
574  * hour - 0..23, minute - 0..59, second - 0..59
575  */
576 static int send_set_imon_clock(struct imon_context *ictx,
577                                unsigned int year, unsigned int month,
578                                unsigned int day, unsigned int dow,
579                                unsigned int hour, unsigned int minute,
580                                unsigned int second)
581 {
582         unsigned char clock_enable_pkt[IMON_CLOCK_ENABLE_PACKETS][8];
583         int retval = 0;
584         int i;
585
586         if (!ictx) {
587                 pr_err("no context for device\n");
588                 return -ENODEV;
589         }
590
591         switch (ictx->display_type) {
592         case IMON_DISPLAY_TYPE_LCD:
593                 clock_enable_pkt[0][0] = 0x80;
594                 clock_enable_pkt[0][1] = year;
595                 clock_enable_pkt[0][2] = month-1;
596                 clock_enable_pkt[0][3] = day;
597                 clock_enable_pkt[0][4] = hour;
598                 clock_enable_pkt[0][5] = minute;
599                 clock_enable_pkt[0][6] = second;
600
601                 clock_enable_pkt[1][0] = 0x80;
602                 clock_enable_pkt[1][1] = 0;
603                 clock_enable_pkt[1][2] = 0;
604                 clock_enable_pkt[1][3] = 0;
605                 clock_enable_pkt[1][4] = 0;
606                 clock_enable_pkt[1][5] = 0;
607                 clock_enable_pkt[1][6] = 0;
608
609                 if (ictx->product == 0xffdc) {
610                         clock_enable_pkt[0][7] = 0x50;
611                         clock_enable_pkt[1][7] = 0x51;
612                 } else {
613                         clock_enable_pkt[0][7] = 0x88;
614                         clock_enable_pkt[1][7] = 0x8a;
615                 }
616
617                 break;
618
619         case IMON_DISPLAY_TYPE_VFD:
620                 clock_enable_pkt[0][0] = year;
621                 clock_enable_pkt[0][1] = month-1;
622                 clock_enable_pkt[0][2] = day;
623                 clock_enable_pkt[0][3] = dow;
624                 clock_enable_pkt[0][4] = hour;
625                 clock_enable_pkt[0][5] = minute;
626                 clock_enable_pkt[0][6] = second;
627                 clock_enable_pkt[0][7] = 0x40;
628
629                 clock_enable_pkt[1][0] = 0;
630                 clock_enable_pkt[1][1] = 0;
631                 clock_enable_pkt[1][2] = 1;
632                 clock_enable_pkt[1][3] = 0;
633                 clock_enable_pkt[1][4] = 0;
634                 clock_enable_pkt[1][5] = 0;
635                 clock_enable_pkt[1][6] = 0;
636                 clock_enable_pkt[1][7] = 0x42;
637
638                 break;
639
640         default:
641                 return -ENODEV;
642         }
643
644         for (i = 0; i < IMON_CLOCK_ENABLE_PACKETS; i++) {
645                 memcpy(ictx->usb_tx_buf, clock_enable_pkt[i], 8);
646                 retval = send_packet(ictx);
647                 if (retval) {
648                         pr_err("send_packet failed for packet %d\n", i);
649                         break;
650                 }
651         }
652
653         return retval;
654 }
655
656 /**
657  * These are the sysfs functions to handle the association on the iMON 2.4G LT.
658  */
659 static ssize_t show_associate_remote(struct device *d,
660                                      struct device_attribute *attr,
661                                      char *buf)
662 {
663         struct imon_context *ictx = dev_get_drvdata(d);
664
665         if (!ictx)
666                 return -ENODEV;
667
668         mutex_lock(&ictx->lock);
669         if (ictx->rf_isassociating)
670                 strcpy(buf, "associating\n");
671         else
672                 strcpy(buf, "closed\n");
673
674         dev_info(d, "Visit http://www.lirc.org/html/imon-24g.html for "
675                  "instructions on how to associate your iMON 2.4G DT/LT "
676                  "remote\n");
677         mutex_unlock(&ictx->lock);
678         return strlen(buf);
679 }
680
681 static ssize_t store_associate_remote(struct device *d,
682                                       struct device_attribute *attr,
683                                       const char *buf, size_t count)
684 {
685         struct imon_context *ictx;
686
687         ictx = dev_get_drvdata(d);
688
689         if (!ictx)
690                 return -ENODEV;
691
692         mutex_lock(&ictx->lock);
693         ictx->rf_isassociating = true;
694         send_associate_24g(ictx);
695         mutex_unlock(&ictx->lock);
696
697         return count;
698 }
699
700 /**
701  * sysfs functions to control internal imon clock
702  */
703 static ssize_t show_imon_clock(struct device *d,
704                                struct device_attribute *attr, char *buf)
705 {
706         struct imon_context *ictx = dev_get_drvdata(d);
707         size_t len;
708
709         if (!ictx)
710                 return -ENODEV;
711
712         mutex_lock(&ictx->lock);
713
714         if (!ictx->display_supported) {
715                 len = snprintf(buf, PAGE_SIZE, "Not supported.");
716         } else {
717                 len = snprintf(buf, PAGE_SIZE,
718                         "To set the clock on your iMON display:\n"
719                         "# date \"+%%y %%m %%d %%w %%H %%M %%S\" > imon_clock\n"
720                         "%s", ictx->display_isopen ?
721                         "\nNOTE: imon device must be closed\n" : "");
722         }
723
724         mutex_unlock(&ictx->lock);
725
726         return len;
727 }
728
729 static ssize_t store_imon_clock(struct device *d,
730                                 struct device_attribute *attr,
731                                 const char *buf, size_t count)
732 {
733         struct imon_context *ictx = dev_get_drvdata(d);
734         ssize_t retval;
735         unsigned int year, month, day, dow, hour, minute, second;
736
737         if (!ictx)
738                 return -ENODEV;
739
740         mutex_lock(&ictx->lock);
741
742         if (!ictx->display_supported) {
743                 retval = -ENODEV;
744                 goto exit;
745         } else if (ictx->display_isopen) {
746                 retval = -EBUSY;
747                 goto exit;
748         }
749
750         if (sscanf(buf, "%u %u %u %u %u %u %u", &year, &month, &day, &dow,
751                    &hour, &minute, &second) != 7) {
752                 retval = -EINVAL;
753                 goto exit;
754         }
755
756         if ((month < 1 || month > 12) ||
757             (day < 1 || day > 31) || (dow > 6) ||
758             (hour > 23) || (minute > 59) || (second > 59)) {
759                 retval = -EINVAL;
760                 goto exit;
761         }
762
763         retval = send_set_imon_clock(ictx, year, month, day, dow,
764                                      hour, minute, second);
765         if (retval)
766                 goto exit;
767
768         retval = count;
769 exit:
770         mutex_unlock(&ictx->lock);
771
772         return retval;
773 }
774
775
776 static DEVICE_ATTR(imon_clock, S_IWUSR | S_IRUGO, show_imon_clock,
777                    store_imon_clock);
778
779 static DEVICE_ATTR(associate_remote, S_IWUSR | S_IRUGO, show_associate_remote,
780                    store_associate_remote);
781
782 static struct attribute *imon_display_sysfs_entries[] = {
783         &dev_attr_imon_clock.attr,
784         NULL
785 };
786
787 static struct attribute_group imon_display_attribute_group = {
788         .attrs = imon_display_sysfs_entries
789 };
790
791 static struct attribute *imon_rf_sysfs_entries[] = {
792         &dev_attr_associate_remote.attr,
793         NULL
794 };
795
796 static struct attribute_group imon_rf_attribute_group = {
797         .attrs = imon_rf_sysfs_entries
798 };
799
800 /**
801  * Writes data to the VFD.  The iMON VFD is 2x16 characters
802  * and requires data in 5 consecutive USB interrupt packets,
803  * each packet but the last carrying 7 bytes.
804  *
805  * I don't know if the VFD board supports features such as
806  * scrolling, clearing rows, blanking, etc. so at
807  * the caller must provide a full screen of data.  If fewer
808  * than 32 bytes are provided spaces will be appended to
809  * generate a full screen.
810  */
811 static ssize_t vfd_write(struct file *file, const char *buf,
812                          size_t n_bytes, loff_t *pos)
813 {
814         int i;
815         int offset;
816         int seq;
817         int retval = 0;
818         struct imon_context *ictx;
819         const unsigned char vfd_packet6[] = {
820                 0x01, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF };
821
822         ictx = file->private_data;
823         if (!ictx) {
824                 pr_err("no context for device\n");
825                 return -ENODEV;
826         }
827
828         mutex_lock(&ictx->lock);
829
830         if (!ictx->dev_present_intf0) {
831                 pr_err("no iMON device present\n");
832                 retval = -ENODEV;
833                 goto exit;
834         }
835
836         if (n_bytes <= 0 || n_bytes > 32) {
837                 pr_err("invalid payload size\n");
838                 retval = -EINVAL;
839                 goto exit;
840         }
841
842         if (copy_from_user(ictx->tx.data_buf, buf, n_bytes)) {
843                 retval = -EFAULT;
844                 goto exit;
845         }
846
847         /* Pad with spaces */
848         for (i = n_bytes; i < 32; ++i)
849                 ictx->tx.data_buf[i] = ' ';
850
851         for (i = 32; i < 35; ++i)
852                 ictx->tx.data_buf[i] = 0xFF;
853
854         offset = 0;
855         seq = 0;
856
857         do {
858                 memcpy(ictx->usb_tx_buf, ictx->tx.data_buf + offset, 7);
859                 ictx->usb_tx_buf[7] = (unsigned char) seq;
860
861                 retval = send_packet(ictx);
862                 if (retval) {
863                         pr_err("send packet failed for packet #%d\n", seq / 2);
864                         goto exit;
865                 } else {
866                         seq += 2;
867                         offset += 7;
868                 }
869
870         } while (offset < 35);
871
872         /* Send packet #6 */
873         memcpy(ictx->usb_tx_buf, &vfd_packet6, sizeof(vfd_packet6));
874         ictx->usb_tx_buf[7] = (unsigned char) seq;
875         retval = send_packet(ictx);
876         if (retval)
877                 pr_err("send packet failed for packet #%d\n", seq / 2);
878
879 exit:
880         mutex_unlock(&ictx->lock);
881
882         return (!retval) ? n_bytes : retval;
883 }
884
885 /**
886  * Writes data to the LCD.  The iMON OEM LCD screen expects 8-byte
887  * packets. We accept data as 16 hexadecimal digits, followed by a
888  * newline (to make it easy to drive the device from a command-line
889  * -- even though the actual binary data is a bit complicated).
890  *
891  * The device itself is not a "traditional" text-mode display. It's
892  * actually a 16x96 pixel bitmap display. That means if you want to
893  * display text, you've got to have your own "font" and translate the
894  * text into bitmaps for display. This is really flexible (you can
895  * display whatever diacritics you need, and so on), but it's also
896  * a lot more complicated than most LCDs...
897  */
898 static ssize_t lcd_write(struct file *file, const char *buf,
899                          size_t n_bytes, loff_t *pos)
900 {
901         int retval = 0;
902         struct imon_context *ictx;
903
904         ictx = file->private_data;
905         if (!ictx) {
906                 pr_err("no context for device\n");
907                 return -ENODEV;
908         }
909
910         mutex_lock(&ictx->lock);
911
912         if (!ictx->display_supported) {
913                 pr_err("no iMON display present\n");
914                 retval = -ENODEV;
915                 goto exit;
916         }
917
918         if (n_bytes != 8) {
919                 pr_err("invalid payload size: %d (expected 8)\n", (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                 pr_err("send packet failed!\n");
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 /*
1705  * The 0x15c2:0xffdc device ID was used for umpteen different imon
1706  * devices, and all of them constantly spew interrupts, even when there
1707  * is no actual data to report. However, byte 6 of this buffer looks like
1708  * its unique across device variants, so we're trying to key off that to
1709  * figure out which display type (if any) and what IR protocol the device
1710  * actually supports. These devices have their IR protocol hard-coded into
1711  * their firmware, they can't be changed on the fly like the newer hardware.
1712  */
1713 static void imon_get_ffdc_type(struct imon_context *ictx)
1714 {
1715         u8 ffdc_cfg_byte = ictx->usb_rx_buf[6];
1716         u8 detected_display_type = IMON_DISPLAY_TYPE_NONE;
1717         u64 allowed_protos = IR_TYPE_OTHER;
1718
1719         switch (ffdc_cfg_byte) {
1720         /* iMON Knob, no display, iMON IR + vol knob */
1721         case 0x21:
1722                 dev_info(ictx->dev, "0xffdc iMON Knob, iMON IR");
1723                 ictx->display_supported = false;
1724                 break;
1725         /* iMON 2.4G LT (usb stick), no display, iMON RF */
1726         case 0x4e:
1727                 dev_info(ictx->dev, "0xffdc iMON 2.4G LT, iMON RF");
1728                 ictx->display_supported = false;
1729                 ictx->rf_device = true;
1730                 break;
1731         /* iMON VFD, no IR (does have vol knob tho) */
1732         case 0x35:
1733                 dev_info(ictx->dev, "0xffdc iMON VFD + knob, no IR");
1734                 detected_display_type = IMON_DISPLAY_TYPE_VFD;
1735                 break;
1736         /* iMON VFD, iMON IR */
1737         case 0x24:
1738         case 0x85:
1739                 dev_info(ictx->dev, "0xffdc iMON VFD, iMON IR");
1740                 detected_display_type = IMON_DISPLAY_TYPE_VFD;
1741                 break;
1742         /* iMON VFD, MCE IR */
1743         case 0x9e:
1744                 dev_info(ictx->dev, "0xffdc iMON VFD, MCE IR");
1745                 detected_display_type = IMON_DISPLAY_TYPE_VFD;
1746                 allowed_protos = IR_TYPE_RC6;
1747                 break;
1748         /* iMON LCD, MCE IR */
1749         case 0x9f:
1750                 dev_info(ictx->dev, "0xffdc iMON LCD, MCE IR");
1751                 detected_display_type = IMON_DISPLAY_TYPE_LCD;
1752                 allowed_protos = IR_TYPE_RC6;
1753                 break;
1754         default:
1755                 dev_info(ictx->dev, "Unknown 0xffdc device, "
1756                          "defaulting to VFD and iMON IR");
1757                 detected_display_type = IMON_DISPLAY_TYPE_VFD;
1758                 break;
1759         }
1760
1761         printk(KERN_CONT " (id 0x%02x)\n", ffdc_cfg_byte);
1762
1763         ictx->display_type = detected_display_type;
1764         ictx->props->allowed_protos = allowed_protos;
1765         ictx->ir_type = allowed_protos;
1766 }
1767
1768 static void imon_set_display_type(struct imon_context *ictx)
1769 {
1770         u8 configured_display_type = IMON_DISPLAY_TYPE_VFD;
1771
1772         /*
1773          * Try to auto-detect the type of display if the user hasn't set
1774          * it by hand via the display_type modparam. Default is VFD.
1775          */
1776
1777         if (display_type == IMON_DISPLAY_TYPE_AUTO) {
1778                 switch (ictx->product) {
1779                 case 0xffdc:
1780                         /* set in imon_get_ffdc_type() */
1781                         configured_display_type = ictx->display_type;
1782                         break;
1783                 case 0x0034:
1784                 case 0x0035:
1785                         configured_display_type = IMON_DISPLAY_TYPE_VGA;
1786                         break;
1787                 case 0x0038:
1788                 case 0x0039:
1789                 case 0x0045:
1790                         configured_display_type = IMON_DISPLAY_TYPE_LCD;
1791                         break;
1792                 case 0x003c:
1793                 case 0x0041:
1794                 case 0x0042:
1795                 case 0x0043:
1796                         configured_display_type = IMON_DISPLAY_TYPE_NONE;
1797                         ictx->display_supported = false;
1798                         break;
1799                 case 0x0036:
1800                 case 0x0044:
1801                 default:
1802                         configured_display_type = IMON_DISPLAY_TYPE_VFD;
1803                         break;
1804                 }
1805         } else {
1806                 configured_display_type = display_type;
1807                 if (display_type == IMON_DISPLAY_TYPE_NONE)
1808                         ictx->display_supported = false;
1809                 else
1810                         ictx->display_supported = true;
1811                 dev_info(ictx->dev, "%s: overriding display type to %d via "
1812                          "modparam\n", __func__, display_type);
1813         }
1814
1815         ictx->display_type = configured_display_type;
1816 }
1817
1818 static struct input_dev *imon_init_rdev(struct imon_context *ictx)
1819 {
1820         struct input_dev *rdev;
1821         struct ir_dev_props *props;
1822         int ret;
1823         char *ir_codes = NULL;
1824         const unsigned char fp_packet[] = { 0x40, 0x00, 0x00, 0x00,
1825                                             0x00, 0x00, 0x00, 0x88 };
1826
1827         rdev = input_allocate_device();
1828         props = kzalloc(sizeof(*props), GFP_KERNEL);
1829         if (!rdev || !props) {
1830                 dev_err(ictx->dev, "remote control dev allocation failed\n");
1831                 goto out;
1832         }
1833
1834         snprintf(ictx->name_rdev, sizeof(ictx->name_rdev),
1835                  "iMON Remote (%04x:%04x)", ictx->vendor, ictx->product);
1836         usb_make_path(ictx->usbdev_intf0, ictx->phys_rdev,
1837                       sizeof(ictx->phys_rdev));
1838         strlcat(ictx->phys_rdev, "/input0", sizeof(ictx->phys_rdev));
1839
1840         rdev->name = ictx->name_rdev;
1841         rdev->phys = ictx->phys_rdev;
1842         usb_to_input_id(ictx->usbdev_intf0, &rdev->id);
1843         rdev->dev.parent = ictx->dev;
1844         rdev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP);
1845         input_set_drvdata(rdev, ictx);
1846
1847         props->priv = ictx;
1848         props->driver_type = RC_DRIVER_SCANCODE;
1849         props->allowed_protos = IR_TYPE_OTHER | IR_TYPE_RC6; /* iMON PAD or MCE */
1850         props->change_protocol = imon_ir_change_protocol;
1851         ictx->props = props;
1852
1853         /* Enable front-panel buttons and/or knobs */
1854         memcpy(ictx->usb_tx_buf, &fp_packet, sizeof(fp_packet));
1855         ret = send_packet(ictx);
1856         /* Not fatal, but warn about it */
1857         if (ret)
1858                 dev_info(ictx->dev, "panel buttons/knobs setup failed\n");
1859
1860         if (ictx->product == 0xffdc)
1861                 imon_get_ffdc_type(ictx);
1862
1863         imon_set_display_type(ictx);
1864
1865         if (ictx->ir_type == IR_TYPE_RC6)
1866                 ir_codes = RC_MAP_IMON_MCE;
1867         else
1868                 ir_codes = RC_MAP_IMON_PAD;
1869
1870         ret = ir_input_register(rdev, ir_codes, props, MOD_NAME);
1871         if (ret < 0) {
1872                 dev_err(ictx->dev, "remote input dev register failed\n");
1873                 goto out;
1874         }
1875
1876         return rdev;
1877
1878 out:
1879         kfree(props);
1880         input_free_device(rdev);
1881         return NULL;
1882 }
1883
1884 static struct input_dev *imon_init_idev(struct imon_context *ictx)
1885 {
1886         struct input_dev *idev;
1887         int ret, i;
1888
1889         idev = input_allocate_device();
1890         if (!idev) {
1891                 dev_err(ictx->dev, "input dev allocation failed\n");
1892                 goto out;
1893         }
1894
1895         snprintf(ictx->name_idev, sizeof(ictx->name_idev),
1896                  "iMON Panel, Knob and Mouse(%04x:%04x)",
1897                  ictx->vendor, ictx->product);
1898         idev->name = ictx->name_idev;
1899
1900         usb_make_path(ictx->usbdev_intf0, ictx->phys_idev,
1901                       sizeof(ictx->phys_idev));
1902         strlcat(ictx->phys_idev, "/input1", sizeof(ictx->phys_idev));
1903         idev->phys = ictx->phys_idev;
1904
1905         idev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP) | BIT_MASK(EV_REL);
1906
1907         idev->keybit[BIT_WORD(BTN_MOUSE)] =
1908                 BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_RIGHT);
1909         idev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y) |
1910                 BIT_MASK(REL_WHEEL);
1911
1912         /* panel and/or knob code support */
1913         for (i = 0; i < ARRAY_SIZE(imon_panel_key_table); i++) {
1914                 u32 kc = imon_panel_key_table[i].keycode;
1915                 __set_bit(kc, idev->keybit);
1916         }
1917
1918         usb_to_input_id(ictx->usbdev_intf0, &idev->id);
1919         idev->dev.parent = ictx->dev;
1920         input_set_drvdata(idev, ictx);
1921
1922         ret = input_register_device(idev);
1923         if (ret < 0) {
1924                 dev_err(ictx->dev, "input dev register failed\n");
1925                 goto out;
1926         }
1927
1928         return idev;
1929
1930 out:
1931         input_free_device(idev);
1932         return NULL;
1933 }
1934
1935 static struct input_dev *imon_init_touch(struct imon_context *ictx)
1936 {
1937         struct input_dev *touch;
1938         int ret;
1939
1940         touch = input_allocate_device();
1941         if (!touch) {
1942                 dev_err(ictx->dev, "touchscreen input dev allocation failed\n");
1943                 goto touch_alloc_failed;
1944         }
1945
1946         snprintf(ictx->name_touch, sizeof(ictx->name_touch),
1947                  "iMON USB Touchscreen (%04x:%04x)",
1948                  ictx->vendor, ictx->product);
1949         touch->name = ictx->name_touch;
1950
1951         usb_make_path(ictx->usbdev_intf1, ictx->phys_touch,
1952                       sizeof(ictx->phys_touch));
1953         strlcat(ictx->phys_touch, "/input2", sizeof(ictx->phys_touch));
1954         touch->phys = ictx->phys_touch;
1955
1956         touch->evbit[0] =
1957                 BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
1958         touch->keybit[BIT_WORD(BTN_TOUCH)] =
1959                 BIT_MASK(BTN_TOUCH);
1960         input_set_abs_params(touch, ABS_X,
1961                              0x00, 0xfff, 0, 0);
1962         input_set_abs_params(touch, ABS_Y,
1963                              0x00, 0xfff, 0, 0);
1964
1965         input_set_drvdata(touch, ictx);
1966
1967         usb_to_input_id(ictx->usbdev_intf1, &touch->id);
1968         touch->dev.parent = ictx->dev;
1969         ret = input_register_device(touch);
1970         if (ret <  0) {
1971                 dev_info(ictx->dev, "touchscreen input dev register failed\n");
1972                 goto touch_register_failed;
1973         }
1974
1975         return touch;
1976
1977 touch_register_failed:
1978         input_free_device(ictx->touch);
1979
1980 touch_alloc_failed:
1981         return NULL;
1982 }
1983
1984 static bool imon_find_endpoints(struct imon_context *ictx,
1985                                 struct usb_host_interface *iface_desc)
1986 {
1987         struct usb_endpoint_descriptor *ep;
1988         struct usb_endpoint_descriptor *rx_endpoint = NULL;
1989         struct usb_endpoint_descriptor *tx_endpoint = NULL;
1990         int ifnum = iface_desc->desc.bInterfaceNumber;
1991         int num_endpts = iface_desc->desc.bNumEndpoints;
1992         int i, ep_dir, ep_type;
1993         bool ir_ep_found = false;
1994         bool display_ep_found = false;
1995         bool tx_control = false;
1996
1997         /*
1998          * Scan the endpoint list and set:
1999          *      first input endpoint = IR endpoint
2000          *      first output endpoint = display endpoint
2001          */
2002         for (i = 0; i < num_endpts && !(ir_ep_found && display_ep_found); ++i) {
2003                 ep = &iface_desc->endpoint[i].desc;
2004                 ep_dir = ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK;
2005                 ep_type = ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK;
2006
2007                 if (!ir_ep_found && ep_dir == USB_DIR_IN &&
2008                     ep_type == USB_ENDPOINT_XFER_INT) {
2009
2010                         rx_endpoint = ep;
2011                         ir_ep_found = true;
2012                         dev_dbg(ictx->dev, "%s: found IR endpoint\n", __func__);
2013
2014                 } else if (!display_ep_found && ep_dir == USB_DIR_OUT &&
2015                            ep_type == USB_ENDPOINT_XFER_INT) {
2016                         tx_endpoint = ep;
2017                         display_ep_found = true;
2018                         dev_dbg(ictx->dev, "%s: found display endpoint\n", __func__);
2019                 }
2020         }
2021
2022         if (ifnum == 0) {
2023                 ictx->rx_endpoint_intf0 = rx_endpoint;
2024                 /*
2025                  * tx is used to send characters to lcd/vfd, associate RF
2026                  * remotes, set IR protocol, and maybe more...
2027                  */
2028                 ictx->tx_endpoint = tx_endpoint;
2029         } else {
2030                 ictx->rx_endpoint_intf1 = rx_endpoint;
2031         }
2032
2033         /*
2034          * If we didn't find a display endpoint, this is probably one of the
2035          * newer iMON devices that use control urb instead of interrupt
2036          */
2037         if (!display_ep_found) {
2038                 tx_control = true;
2039                 display_ep_found = true;
2040                 dev_dbg(ictx->dev, "%s: device uses control endpoint, not "
2041                         "interface OUT endpoint\n", __func__);
2042         }
2043
2044         /*
2045          * Some iMON receivers have no display. Unfortunately, it seems
2046          * that SoundGraph recycles device IDs between devices both with
2047          * and without... :\
2048          */
2049         if (ictx->display_type == IMON_DISPLAY_TYPE_NONE) {
2050                 display_ep_found = false;
2051                 dev_dbg(ictx->dev, "%s: device has no display\n", __func__);
2052         }
2053
2054         /*
2055          * iMON Touch devices have a VGA touchscreen, but no "display", as
2056          * that refers to e.g. /dev/lcd0 (a character device LCD or VFD).
2057          */
2058         if (ictx->display_type == IMON_DISPLAY_TYPE_VGA) {
2059                 display_ep_found = false;
2060                 dev_dbg(ictx->dev, "%s: iMON Touch device found\n", __func__);
2061         }
2062
2063         /* Input endpoint is mandatory */
2064         if (!ir_ep_found)
2065                 pr_err("no valid input (IR) endpoint found\n");
2066
2067         ictx->tx_control = tx_control;
2068
2069         if (display_ep_found)
2070                 ictx->display_supported = true;
2071
2072         return ir_ep_found;
2073
2074 }
2075
2076 static struct imon_context *imon_init_intf0(struct usb_interface *intf)
2077 {
2078         struct imon_context *ictx;
2079         struct urb *rx_urb;
2080         struct urb *tx_urb;
2081         struct device *dev = &intf->dev;
2082         struct usb_host_interface *iface_desc;
2083         int ret = -ENOMEM;
2084
2085         ictx = kzalloc(sizeof(struct imon_context), GFP_KERNEL);
2086         if (!ictx) {
2087                 dev_err(dev, "%s: kzalloc failed for context", __func__);
2088                 goto exit;
2089         }
2090         rx_urb = usb_alloc_urb(0, GFP_KERNEL);
2091         if (!rx_urb) {
2092                 dev_err(dev, "%s: usb_alloc_urb failed for IR urb", __func__);
2093                 goto rx_urb_alloc_failed;
2094         }
2095         tx_urb = usb_alloc_urb(0, GFP_KERNEL);
2096         if (!tx_urb) {
2097                 dev_err(dev, "%s: usb_alloc_urb failed for display urb",
2098                         __func__);
2099                 goto tx_urb_alloc_failed;
2100         }
2101
2102         mutex_init(&ictx->lock);
2103         spin_lock_init(&ictx->kc_lock);
2104
2105         mutex_lock(&ictx->lock);
2106
2107         ictx->dev = dev;
2108         ictx->usbdev_intf0 = usb_get_dev(interface_to_usbdev(intf));
2109         ictx->dev_present_intf0 = true;
2110         ictx->rx_urb_intf0 = rx_urb;
2111         ictx->tx_urb = tx_urb;
2112         ictx->rf_device = false;
2113
2114         ictx->vendor  = le16_to_cpu(ictx->usbdev_intf0->descriptor.idVendor);
2115         ictx->product = le16_to_cpu(ictx->usbdev_intf0->descriptor.idProduct);
2116
2117         ret = -ENODEV;
2118         iface_desc = intf->cur_altsetting;
2119         if (!imon_find_endpoints(ictx, iface_desc)) {
2120                 goto find_endpoint_failed;
2121         }
2122
2123         ictx->idev = imon_init_idev(ictx);
2124         if (!ictx->idev) {
2125                 dev_err(dev, "%s: input device setup failed\n", __func__);
2126                 goto idev_setup_failed;
2127         }
2128
2129         ictx->rdev = imon_init_rdev(ictx);
2130         if (!ictx->rdev) {
2131                 dev_err(dev, "%s: rc device setup failed\n", __func__);
2132                 goto rdev_setup_failed;
2133         }
2134
2135         usb_fill_int_urb(ictx->rx_urb_intf0, ictx->usbdev_intf0,
2136                 usb_rcvintpipe(ictx->usbdev_intf0,
2137                         ictx->rx_endpoint_intf0->bEndpointAddress),
2138                 ictx->usb_rx_buf, sizeof(ictx->usb_rx_buf),
2139                 usb_rx_callback_intf0, ictx,
2140                 ictx->rx_endpoint_intf0->bInterval);
2141
2142         ret = usb_submit_urb(ictx->rx_urb_intf0, GFP_KERNEL);
2143         if (ret) {
2144                 pr_err("usb_submit_urb failed for intf0 (%d)\n", ret);
2145                 goto urb_submit_failed;
2146         }
2147
2148         return ictx;
2149
2150 urb_submit_failed:
2151         ir_input_unregister(ictx->rdev);
2152 rdev_setup_failed:
2153         input_unregister_device(ictx->idev);
2154 idev_setup_failed:
2155 find_endpoint_failed:
2156         mutex_unlock(&ictx->lock);
2157         usb_free_urb(tx_urb);
2158 tx_urb_alloc_failed:
2159         usb_free_urb(rx_urb);
2160 rx_urb_alloc_failed:
2161         kfree(ictx);
2162 exit:
2163         dev_err(dev, "unable to initialize intf0, err %d\n", ret);
2164
2165         return NULL;
2166 }
2167
2168 static struct imon_context *imon_init_intf1(struct usb_interface *intf,
2169                                             struct imon_context *ictx)
2170 {
2171         struct urb *rx_urb;
2172         struct usb_host_interface *iface_desc;
2173         int ret = -ENOMEM;
2174
2175         rx_urb = usb_alloc_urb(0, GFP_KERNEL);
2176         if (!rx_urb) {
2177                 pr_err("usb_alloc_urb failed for IR urb\n");
2178                 goto rx_urb_alloc_failed;
2179         }
2180
2181         mutex_lock(&ictx->lock);
2182
2183         if (ictx->display_type == IMON_DISPLAY_TYPE_VGA) {
2184                 init_timer(&ictx->ttimer);
2185                 ictx->ttimer.data = (unsigned long)ictx;
2186                 ictx->ttimer.function = imon_touch_display_timeout;
2187         }
2188
2189         ictx->usbdev_intf1 = usb_get_dev(interface_to_usbdev(intf));
2190         ictx->dev_present_intf1 = true;
2191         ictx->rx_urb_intf1 = rx_urb;
2192
2193         ret = -ENODEV;
2194         iface_desc = intf->cur_altsetting;
2195         if (!imon_find_endpoints(ictx, iface_desc))
2196                 goto find_endpoint_failed;
2197
2198         if (ictx->display_type == IMON_DISPLAY_TYPE_VGA) {
2199                 ictx->touch = imon_init_touch(ictx);
2200                 if (!ictx->touch)
2201                         goto touch_setup_failed;
2202         } else
2203                 ictx->touch = NULL;
2204
2205         usb_fill_int_urb(ictx->rx_urb_intf1, ictx->usbdev_intf1,
2206                 usb_rcvintpipe(ictx->usbdev_intf1,
2207                         ictx->rx_endpoint_intf1->bEndpointAddress),
2208                 ictx->usb_rx_buf, sizeof(ictx->usb_rx_buf),
2209                 usb_rx_callback_intf1, ictx,
2210                 ictx->rx_endpoint_intf1->bInterval);
2211
2212         ret = usb_submit_urb(ictx->rx_urb_intf1, GFP_KERNEL);
2213
2214         if (ret) {
2215                 pr_err("usb_submit_urb failed for intf1 (%d)\n", ret);
2216                 goto urb_submit_failed;
2217         }
2218
2219         return ictx;
2220
2221 urb_submit_failed:
2222         if (ictx->touch)
2223                 input_unregister_device(ictx->touch);
2224 touch_setup_failed:
2225 find_endpoint_failed:
2226         mutex_unlock(&ictx->lock);
2227         usb_free_urb(rx_urb);
2228 rx_urb_alloc_failed:
2229         dev_err(ictx->dev, "unable to initialize intf0, err %d\n", ret);
2230
2231         return NULL;
2232 }
2233
2234 static void imon_init_display(struct imon_context *ictx,
2235                               struct usb_interface *intf)
2236 {
2237         int ret;
2238
2239         dev_dbg(ictx->dev, "Registering iMON display with sysfs\n");
2240
2241         /* set up sysfs entry for built-in clock */
2242         ret = sysfs_create_group(&intf->dev.kobj,
2243                                  &imon_display_attribute_group);
2244         if (ret)
2245                 dev_err(ictx->dev, "Could not create display sysfs "
2246                         "entries(%d)", ret);
2247
2248         if (ictx->display_type == IMON_DISPLAY_TYPE_LCD)
2249                 ret = usb_register_dev(intf, &imon_lcd_class);
2250         else
2251                 ret = usb_register_dev(intf, &imon_vfd_class);
2252         if (ret)
2253                 /* Not a fatal error, so ignore */
2254                 dev_info(ictx->dev, "could not get a minor number for "
2255                          "display\n");
2256
2257 }
2258
2259 /**
2260  * Callback function for USB core API: Probe
2261  */
2262 static int __devinit imon_probe(struct usb_interface *interface,
2263                                 const struct usb_device_id *id)
2264 {
2265         struct usb_device *usbdev = NULL;
2266         struct usb_host_interface *iface_desc = NULL;
2267         struct usb_interface *first_if;
2268         struct device *dev = &interface->dev;
2269         int ifnum, code_length, sysfs_err;
2270         int ret = 0;
2271         struct imon_context *ictx = NULL;
2272         struct imon_context *first_if_ctx = NULL;
2273         u16 vendor, product;
2274
2275         code_length = BUF_CHUNK_SIZE * 8;
2276
2277         usbdev     = usb_get_dev(interface_to_usbdev(interface));
2278         iface_desc = interface->cur_altsetting;
2279         ifnum      = iface_desc->desc.bInterfaceNumber;
2280         vendor     = le16_to_cpu(usbdev->descriptor.idVendor);
2281         product    = le16_to_cpu(usbdev->descriptor.idProduct);
2282
2283         dev_dbg(dev, "%s: found iMON device (%04x:%04x, intf%d)\n",
2284                 __func__, vendor, product, ifnum);
2285
2286         /* prevent races probing devices w/multiple interfaces */
2287         mutex_lock(&driver_lock);
2288
2289         first_if = usb_ifnum_to_if(usbdev, 0);
2290         first_if_ctx = (struct imon_context *)usb_get_intfdata(first_if);
2291
2292         if (ifnum == 0) {
2293                 ictx = imon_init_intf0(interface);
2294                 if (!ictx) {
2295                         pr_err("failed to initialize context!\n");
2296                         ret = -ENODEV;
2297                         goto fail;
2298                 }
2299
2300         } else {
2301         /* this is the secondary interface on the device */
2302                 ictx = imon_init_intf1(interface, first_if_ctx);
2303                 if (!ictx) {
2304                         pr_err("failed to attach to context!\n");
2305                         ret = -ENODEV;
2306                         goto fail;
2307                 }
2308
2309         }
2310
2311         usb_set_intfdata(interface, ictx);
2312
2313         if (ifnum == 0) {
2314                 if (product == 0xffdc && ictx->rf_device) {
2315                         sysfs_err = sysfs_create_group(&interface->dev.kobj,
2316                                                        &imon_rf_attribute_group);
2317                         if (sysfs_err)
2318                                 pr_err("Could not create RF sysfs entries(%d)\n",
2319                                        sysfs_err);
2320                 }
2321
2322                 if (ictx->display_supported)
2323                         imon_init_display(ictx, interface);
2324         }
2325
2326         /* set IR protocol/remote type */
2327         ret = imon_ir_change_protocol(ictx, ictx->ir_type);
2328         if (ret) {
2329                 dev_warn(dev, "%s: failed to set IR protocol, falling back "
2330                          "to standard iMON protocol mode\n", __func__);
2331                 ictx->ir_type = IR_TYPE_OTHER;
2332         }
2333
2334         dev_info(dev, "iMON device (%04x:%04x, intf%d) on "
2335                  "usb<%d:%d> initialized\n", vendor, product, ifnum,
2336                  usbdev->bus->busnum, usbdev->devnum);
2337
2338         mutex_unlock(&ictx->lock);
2339         mutex_unlock(&driver_lock);
2340
2341         return 0;
2342
2343 fail:
2344         mutex_unlock(&driver_lock);
2345         dev_err(dev, "unable to register, err %d\n", ret);
2346
2347         return ret;
2348 }
2349
2350 /**
2351  * Callback function for USB core API: disconnect
2352  */
2353 static void __devexit imon_disconnect(struct usb_interface *interface)
2354 {
2355         struct imon_context *ictx;
2356         struct device *dev;
2357         int ifnum;
2358
2359         /* prevent races with multi-interface device probing and display_open */
2360         mutex_lock(&driver_lock);
2361
2362         ictx = usb_get_intfdata(interface);
2363         dev = ictx->dev;
2364         ifnum = interface->cur_altsetting->desc.bInterfaceNumber;
2365
2366         mutex_lock(&ictx->lock);
2367
2368         /*
2369          * sysfs_remove_group is safe to call even if sysfs_create_group
2370          * hasn't been called
2371          */
2372         sysfs_remove_group(&interface->dev.kobj,
2373                            &imon_display_attribute_group);
2374         sysfs_remove_group(&interface->dev.kobj,
2375                            &imon_rf_attribute_group);
2376
2377         usb_set_intfdata(interface, NULL);
2378
2379         /* Abort ongoing write */
2380         if (ictx->tx.busy) {
2381                 usb_kill_urb(ictx->tx_urb);
2382                 complete_all(&ictx->tx.finished);
2383         }
2384
2385         if (ifnum == 0) {
2386                 ictx->dev_present_intf0 = false;
2387                 usb_kill_urb(ictx->rx_urb_intf0);
2388                 input_unregister_device(ictx->idev);
2389                 ir_input_unregister(ictx->rdev);
2390                 if (ictx->display_supported) {
2391                         if (ictx->display_type == IMON_DISPLAY_TYPE_LCD)
2392                                 usb_deregister_dev(interface, &imon_lcd_class);
2393                         else
2394                                 usb_deregister_dev(interface, &imon_vfd_class);
2395                 }
2396         } else {
2397                 ictx->dev_present_intf1 = false;
2398                 usb_kill_urb(ictx->rx_urb_intf1);
2399                 if (ictx->display_type == IMON_DISPLAY_TYPE_VGA)
2400                         input_unregister_device(ictx->touch);
2401         }
2402
2403         if (!ictx->dev_present_intf0 && !ictx->dev_present_intf1) {
2404                 if (ictx->display_type == IMON_DISPLAY_TYPE_VGA)
2405                         del_timer_sync(&ictx->ttimer);
2406                 mutex_unlock(&ictx->lock);
2407                 if (!ictx->display_isopen)
2408                         free_imon_context(ictx);
2409         } else
2410                 mutex_unlock(&ictx->lock);
2411
2412         mutex_unlock(&driver_lock);
2413
2414         dev_dbg(dev, "%s: iMON device (intf%d) disconnected\n",
2415                 __func__, ifnum);
2416 }
2417
2418 static int imon_suspend(struct usb_interface *intf, pm_message_t message)
2419 {
2420         struct imon_context *ictx = usb_get_intfdata(intf);
2421         int ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2422
2423         if (ifnum == 0)
2424                 usb_kill_urb(ictx->rx_urb_intf0);
2425         else
2426                 usb_kill_urb(ictx->rx_urb_intf1);
2427
2428         return 0;
2429 }
2430
2431 static int imon_resume(struct usb_interface *intf)
2432 {
2433         int rc = 0;
2434         struct imon_context *ictx = usb_get_intfdata(intf);
2435         int ifnum = intf->cur_altsetting->desc.bInterfaceNumber;
2436
2437         if (ifnum == 0) {
2438                 usb_fill_int_urb(ictx->rx_urb_intf0, ictx->usbdev_intf0,
2439                         usb_rcvintpipe(ictx->usbdev_intf0,
2440                                 ictx->rx_endpoint_intf0->bEndpointAddress),
2441                         ictx->usb_rx_buf, sizeof(ictx->usb_rx_buf),
2442                         usb_rx_callback_intf0, ictx,
2443                         ictx->rx_endpoint_intf0->bInterval);
2444
2445                 rc = usb_submit_urb(ictx->rx_urb_intf0, GFP_ATOMIC);
2446
2447         } else {
2448                 usb_fill_int_urb(ictx->rx_urb_intf1, ictx->usbdev_intf1,
2449                         usb_rcvintpipe(ictx->usbdev_intf1,
2450                                 ictx->rx_endpoint_intf1->bEndpointAddress),
2451                         ictx->usb_rx_buf, sizeof(ictx->usb_rx_buf),
2452                         usb_rx_callback_intf1, ictx,
2453                         ictx->rx_endpoint_intf1->bInterval);
2454
2455                 rc = usb_submit_urb(ictx->rx_urb_intf1, GFP_ATOMIC);
2456         }
2457
2458         return rc;
2459 }
2460
2461 static int __init imon_init(void)
2462 {
2463         int rc;
2464
2465         rc = usb_register(&imon_driver);
2466         if (rc) {
2467                 pr_err("usb register failed(%d)\n", rc);
2468                 rc = -ENODEV;
2469         }
2470
2471         return rc;
2472 }
2473
2474 static void __exit imon_exit(void)
2475 {
2476         usb_deregister(&imon_driver);
2477 }
2478
2479 module_init(imon_init);
2480 module_exit(imon_exit);