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