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