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