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