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