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