imon.c 72.4 KB
Newer Older
J
Jarod Wilson 已提交
1 2 3
/*
 *   imon.c:	input and display driver for SoundGraph iMON IR/VFD/LCD
 *
4
 *   Copyright(C) 2010  Jarod Wilson <jarod@wilsonet.com>
J
Jarod Wilson 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
 *   Portions based on the original lirc_imon driver,
 *	Copyright(C) 2004  Venky Raju(dev@venky.ws)
 *
 *   Huge thanks to R. Geoff Newbury for invaluable debugging on the
 *   0xffdc iMON devices, and for sending me one to hack on, without
 *   which the support for them wouldn't be nearly as good. Thanks
 *   also to the numerous 0xffdc device owners that tested auto-config
 *   support for me and provided debug dumps from their devices.
 *
 *   imon is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 */

25 26
#define pr_fmt(fmt) KBUILD_MODNAME ":%s: " fmt, __func__

J
Jarod Wilson 已提交
27 28 29 30 31 32
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
33
#include <linux/ratelimit.h>
J
Jarod Wilson 已提交
34 35 36 37

#include <linux/input.h>
#include <linux/usb.h>
#include <linux/usb/input.h>
38
#include <media/rc-core.h>
J
Jarod Wilson 已提交
39 40 41 42 43 44 45

#include <linux/time.h>
#include <linux/timer.h>

#define MOD_AUTHOR	"Jarod Wilson <jarod@wilsonet.com>"
#define MOD_DESC	"Driver for SoundGraph iMON MultiMedia IR/Display"
#define MOD_NAME	"imon"
46
#define MOD_VERSION	"0.9.4"
J
Jarod Wilson 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

#define DISPLAY_MINOR_BASE	144
#define DEVICE_NAME	"lcd%d"

#define BUF_CHUNK_SIZE	8
#define BUF_SIZE	128

#define BIT_DURATION	250	/* each bit received is 250us */

#define IMON_CLOCK_ENABLE_PACKETS	2

/*** P R O T O T Y P E S ***/

/* USB Callback prototypes */
static int imon_probe(struct usb_interface *interface,
		      const struct usb_device_id *id);
static void imon_disconnect(struct usb_interface *interface);
static void usb_rx_callback_intf0(struct urb *urb);
static void usb_rx_callback_intf1(struct urb *urb);
static void usb_tx_callback(struct urb *urb);

/* suspend/resume support */
static int imon_resume(struct usb_interface *intf);
static int imon_suspend(struct usb_interface *intf, pm_message_t message);

/* Display file_operations function prototypes */
static int display_open(struct inode *inode, struct file *file);
static int display_close(struct inode *inode, struct file *file);

/* VFD write operation */
77
static ssize_t vfd_write(struct file *file, const char __user *buf,
J
Jarod Wilson 已提交
78 79 80
			 size_t n_bytes, loff_t *pos);

/* LCD file_operations override function prototypes */
81
static ssize_t lcd_write(struct file *file, const char __user *buf,
J
Jarod Wilson 已提交
82 83 84 85
			 size_t n_bytes, loff_t *pos);

/*** G L O B A L S ***/

86 87 88 89 90 91 92 93 94
struct imon_panel_key_table {
	u64 hw_code;
	u32 keycode;
};

struct imon_usb_dev_descr {
	__u16 flags;
#define IMON_NO_FLAGS 0
#define IMON_NEED_20MS_PKT_DELAY 1
95
#define IMON_IR_RAW 2
96 97 98
	struct imon_panel_key_table key_table[];
};

J
Jarod Wilson 已提交
99 100 101 102 103 104 105 106
struct imon_context {
	struct device *dev;
	/* Newer devices have two interfaces */
	struct usb_device *usbdev_intf0;
	struct usb_device *usbdev_intf1;

	bool display_supported;		/* not all controllers do */
	bool display_isopen;		/* display port has been opened */
107
	bool rf_device;			/* true if iMON 2.4G LT/DT RF device */
J
Jarod Wilson 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
	bool rf_isassociating;		/* RF remote associating */
	bool dev_present_intf0;		/* USB device presence, interface 0 */
	bool dev_present_intf1;		/* USB device presence, interface 1 */

	struct mutex lock;		/* to lock this object */
	wait_queue_head_t remove_ok;	/* For unexpected USB disconnects */

	struct usb_endpoint_descriptor *rx_endpoint_intf0;
	struct usb_endpoint_descriptor *rx_endpoint_intf1;
	struct usb_endpoint_descriptor *tx_endpoint;
	struct urb *rx_urb_intf0;
	struct urb *rx_urb_intf1;
	struct urb *tx_urb;
	bool tx_control;
	unsigned char usb_rx_buf[8];
	unsigned char usb_tx_buf[8];
124
	unsigned int send_packet_delay;
J
Jarod Wilson 已提交
125

126 127 128 129 130 131
	struct rx_data {
		int count;		/* length of 0 or 1 sequence */
		int prev_bit;		/* logic level of sequence */
		int initial_space;	/* initial space flag */
	} rx;

J
Jarod Wilson 已提交
132 133 134 135 136 137 138 139 140 141
	struct tx_t {
		unsigned char data_buf[35];	/* user data buffer */
		struct completion finished;	/* wait for write to finish */
		bool busy;			/* write in progress */
		int status;			/* status of tx completion */
	} tx;

	u16 vendor;			/* usb vendor ID */
	u16 product;			/* usb product ID */

142
	struct rc_dev *rdev;		/* rc-core device for remote */
143
	struct input_dev *idev;		/* input device for panel & IR mouse */
J
Jarod Wilson 已提交
144 145
	struct input_dev *touch;	/* input device for touchscreen */

146
	spinlock_t kc_lock;		/* make sure we get keycodes right */
J
Jarod Wilson 已提交
147 148
	u32 kc;				/* current input keycode */
	u32 last_keycode;		/* last reported input keycode */
149 150
	u32 rc_scancode;		/* the computed remote scancode */
	u8 rc_toggle;			/* the computed remote toggle bit */
151
	u64 rc_proto;			/* iMON or MCE (RC6) IR protocol? */
J
Jarod Wilson 已提交
152 153 154 155 156
	bool release_code;		/* some keys send a release code */

	u8 display_type;		/* store the display type */
	bool pad_mouse;			/* toggle kbd(0)/mouse(1) mode */

157 158 159
	char name_rdev[128];		/* rc input device name */
	char phys_rdev[64];		/* rc input device phys path */

J
Jarod Wilson 已提交
160 161 162 163 164 165 166 167
	char name_idev[128];		/* input device name */
	char phys_idev[64];		/* input device phys path */

	char name_touch[128];		/* touch screen name */
	char phys_touch[64];		/* touch screen phys path */
	struct timer_list ttimer;	/* touch screen timer */
	int touch_x;			/* x coordinate on touchscreen */
	int touch_y;			/* y coordinate on touchscreen */
168 169
	struct imon_usb_dev_descr *dev_descr; /* device description with key
						 table for front panels */
J
Jarod Wilson 已提交
170 171 172 173 174 175 176 177 178
};

#define TOUCH_TIMEOUT	(HZ/30)

/* vfd character device file operations */
static const struct file_operations vfd_fops = {
	.owner		= THIS_MODULE,
	.open		= &display_open,
	.write		= &vfd_write,
179 180
	.release	= &display_close,
	.llseek		= noop_llseek,
J
Jarod Wilson 已提交
181 182 183 184 185 186 187
};

/* lcd character device file operations */
static const struct file_operations lcd_fops = {
	.owner		= THIS_MODULE,
	.open		= &display_open,
	.write		= &lcd_write,
188 189
	.release	= &display_close,
	.llseek		= noop_llseek,
J
Jarod Wilson 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
};

enum {
	IMON_DISPLAY_TYPE_AUTO = 0,
	IMON_DISPLAY_TYPE_VFD  = 1,
	IMON_DISPLAY_TYPE_LCD  = 2,
	IMON_DISPLAY_TYPE_VGA  = 3,
	IMON_DISPLAY_TYPE_NONE = 4,
};

enum {
	IMON_KEY_IMON	= 0,
	IMON_KEY_MCE	= 1,
	IMON_KEY_PANEL	= 2,
};

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
static struct usb_class_driver imon_vfd_class = {
	.name		= DEVICE_NAME,
	.fops		= &vfd_fops,
	.minor_base	= DISPLAY_MINOR_BASE,
};

static struct usb_class_driver imon_lcd_class = {
	.name		= DEVICE_NAME,
	.fops		= &lcd_fops,
	.minor_base	= DISPLAY_MINOR_BASE,
};

/* imon receiver front panel/knob key table */
static const struct imon_usb_dev_descr imon_default_table = {
	.flags = IMON_NO_FLAGS,
	.key_table = {
		{ 0x000000000f00ffeell, KEY_MEDIA }, /* Go */
		{ 0x000000001200ffeell, KEY_UP },
		{ 0x000000001300ffeell, KEY_DOWN },
		{ 0x000000001400ffeell, KEY_LEFT },
		{ 0x000000001500ffeell, KEY_RIGHT },
		{ 0x000000001600ffeell, KEY_ENTER },
		{ 0x000000001700ffeell, KEY_ESC },
		{ 0x000000001f00ffeell, KEY_AUDIO },
		{ 0x000000002000ffeell, KEY_VIDEO },
		{ 0x000000002100ffeell, KEY_CAMERA },
		{ 0x000000002700ffeell, KEY_DVD },
		{ 0x000000002300ffeell, KEY_TV },
		{ 0x000000002b00ffeell, KEY_EXIT },
		{ 0x000000002c00ffeell, KEY_SELECT },
		{ 0x000000002d00ffeell, KEY_MENU },
		{ 0x000000000500ffeell, KEY_PREVIOUS },
		{ 0x000000000700ffeell, KEY_REWIND },
		{ 0x000000000400ffeell, KEY_STOP },
		{ 0x000000003c00ffeell, KEY_PLAYPAUSE },
		{ 0x000000000800ffeell, KEY_FASTFORWARD },
		{ 0x000000000600ffeell, KEY_NEXT },
		{ 0x000000010000ffeell, KEY_RIGHT },
		{ 0x000001000000ffeell, KEY_LEFT },
		{ 0x000000003d00ffeell, KEY_SELECT },
		{ 0x000100000000ffeell, KEY_VOLUMEUP },
		{ 0x010000000000ffeell, KEY_VOLUMEDOWN },
		{ 0x000000000100ffeell, KEY_MUTE },
		/* 0xffdc iMON MCE VFD */
		{ 0x00010000ffffffeell, KEY_VOLUMEUP },
		{ 0x01000000ffffffeell, KEY_VOLUMEDOWN },
		{ 0x00000001ffffffeell, KEY_MUTE },
		{ 0x0000000fffffffeell, KEY_MEDIA },
		{ 0x00000012ffffffeell, KEY_UP },
		{ 0x00000013ffffffeell, KEY_DOWN },
		{ 0x00000014ffffffeell, KEY_LEFT },
		{ 0x00000015ffffffeell, KEY_RIGHT },
		{ 0x00000016ffffffeell, KEY_ENTER },
		{ 0x00000017ffffffeell, KEY_ESC },
		/* iMON Knob values */
		{ 0x000100ffffffffeell, KEY_VOLUMEUP },
		{ 0x010000ffffffffeell, KEY_VOLUMEDOWN },
		{ 0x000008ffffffffeell, KEY_MUTE },
		{ 0, KEY_RESERVED },
	}
};

static const struct imon_usb_dev_descr imon_OEM_VFD = {
	.flags = IMON_NEED_20MS_PKT_DELAY,
	.key_table = {
		{ 0x000000000f00ffeell, KEY_MEDIA }, /* Go */
		{ 0x000000001200ffeell, KEY_UP },
		{ 0x000000001300ffeell, KEY_DOWN },
		{ 0x000000001400ffeell, KEY_LEFT },
		{ 0x000000001500ffeell, KEY_RIGHT },
		{ 0x000000001600ffeell, KEY_ENTER },
		{ 0x000000001700ffeell, KEY_ESC },
		{ 0x000000001f00ffeell, KEY_AUDIO },
		{ 0x000000002b00ffeell, KEY_EXIT },
		{ 0x000000002c00ffeell, KEY_SELECT },
		{ 0x000000002d00ffeell, KEY_MENU },
		{ 0x000000000500ffeell, KEY_PREVIOUS },
		{ 0x000000000700ffeell, KEY_REWIND },
		{ 0x000000000400ffeell, KEY_STOP },
		{ 0x000000003c00ffeell, KEY_PLAYPAUSE },
		{ 0x000000000800ffeell, KEY_FASTFORWARD },
		{ 0x000000000600ffeell, KEY_NEXT },
		{ 0x000000010000ffeell, KEY_RIGHT },
		{ 0x000001000000ffeell, KEY_LEFT },
		{ 0x000000003d00ffeell, KEY_SELECT },
		{ 0x000100000000ffeell, KEY_VOLUMEUP },
		{ 0x010000000000ffeell, KEY_VOLUMEDOWN },
		{ 0x000000000100ffeell, KEY_MUTE },
		/* 0xffdc iMON MCE VFD */
		{ 0x00010000ffffffeell, KEY_VOLUMEUP },
		{ 0x01000000ffffffeell, KEY_VOLUMEDOWN },
		{ 0x00000001ffffffeell, KEY_MUTE },
		{ 0x0000000fffffffeell, KEY_MEDIA },
		{ 0x00000012ffffffeell, KEY_UP },
		{ 0x00000013ffffffeell, KEY_DOWN },
		{ 0x00000014ffffffeell, KEY_LEFT },
		{ 0x00000015ffffffeell, KEY_RIGHT },
		{ 0x00000016ffffffeell, KEY_ENTER },
		{ 0x00000017ffffffeell, KEY_ESC },
		/* iMON Knob values */
		{ 0x000100ffffffffeell, KEY_VOLUMEUP },
		{ 0x010000ffffffffeell, KEY_VOLUMEDOWN },
		{ 0x000008ffffffffeell, KEY_MUTE },
		{ 0, KEY_RESERVED },
	}
311 312
};

313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
/* imon receiver front panel/knob key table for DH102*/
static const struct imon_usb_dev_descr imon_DH102 = {
	.flags = IMON_NO_FLAGS,
	.key_table = {
		{ 0x000100000000ffeell, KEY_VOLUMEUP },
		{ 0x010000000000ffeell, KEY_VOLUMEDOWN },
		{ 0x000000010000ffeell, KEY_MUTE },
		{ 0x0000000f0000ffeell, KEY_MEDIA },
		{ 0x000000120000ffeell, KEY_UP },
		{ 0x000000130000ffeell, KEY_DOWN },
		{ 0x000000140000ffeell, KEY_LEFT },
		{ 0x000000150000ffeell, KEY_RIGHT },
		{ 0x000000160000ffeell, KEY_ENTER },
		{ 0x000000170000ffeell, KEY_ESC },
		{ 0x0000002b0000ffeell, KEY_EXIT },
		{ 0x0000002c0000ffeell, KEY_SELECT },
		{ 0x0000002d0000ffeell, KEY_MENU },
		{ 0, KEY_RESERVED }
	}
};

334 335 336 337
static const struct imon_usb_dev_descr imon_ir_raw = {
	.flags = IMON_IR_RAW,
};

J
Jarod Wilson 已提交
338 339 340 341 342 343 344 345 346 347 348
/*
 * USB Device ID for iMON USB Control Boards
 *
 * The Windows drivers contain 6 different inf files, more or less one for
 * each new device until the 0x0034-0x0046 devices, which all use the same
 * driver. Some of the devices in the 34-46 range haven't been definitively
 * identified yet. Early devices have either a TriGem Computer, Inc. or a
 * Samsung vendor ID (0x0aa8 and 0x04e8 respectively), while all later
 * devices use the SoundGraph vendor ID (0x15c2). This driver only supports
 * the ffdc and later devices, which do onboard decoding.
 */
349
static const struct usb_device_id imon_usb_id_table[] = {
J
Jarod Wilson 已提交
350 351 352 353 354 355
	/*
	 * Several devices with this same device ID, all use iMON_PAD.inf
	 * SoundGraph iMON PAD (IR & VFD)
	 * SoundGraph iMON PAD (IR & LCD)
	 * SoundGraph iMON Knob (IR only)
	 */
356 357
	{ USB_DEVICE(0x15c2, 0xffdc),
	  .driver_info = (unsigned long)&imon_default_table },
J
Jarod Wilson 已提交
358 359 360 361 362 363 364

	/*
	 * Newer devices, all driven by the latest iMON Windows driver, full
	 * list of device IDs extracted via 'strings Setup/data1.hdr |grep 15c2'
	 * Need user input to fill in details on unknown devices.
	 */
	/* SoundGraph iMON OEM Touch LCD (IR & 7" VGA LCD) */
365
	{ USB_DEVICE(0x15c2, 0x0034),
366
	  .driver_info = (unsigned long)&imon_DH102 },
J
Jarod Wilson 已提交
367
	/* SoundGraph iMON OEM Touch LCD (IR & 4.3" VGA LCD) */
368 369
	{ USB_DEVICE(0x15c2, 0x0035),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
370
	/* SoundGraph iMON OEM VFD (IR & VFD) */
371 372
	{ USB_DEVICE(0x15c2, 0x0036),
	  .driver_info = (unsigned long)&imon_OEM_VFD },
J
Jarod Wilson 已提交
373
	/* device specifics unknown */
374 375
	{ USB_DEVICE(0x15c2, 0x0037),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
376
	/* SoundGraph iMON OEM LCD (IR & LCD) */
377 378
	{ USB_DEVICE(0x15c2, 0x0038),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
379
	/* SoundGraph iMON UltraBay (IR & LCD) */
380 381
	{ USB_DEVICE(0x15c2, 0x0039),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
382
	/* device specifics unknown */
383 384
	{ USB_DEVICE(0x15c2, 0x003a),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
385
	/* device specifics unknown */
386 387
	{ USB_DEVICE(0x15c2, 0x003b),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
388
	/* SoundGraph iMON OEM Inside (IR only) */
389 390
	{ USB_DEVICE(0x15c2, 0x003c),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
391
	/* device specifics unknown */
392 393
	{ USB_DEVICE(0x15c2, 0x003d),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
394
	/* device specifics unknown */
395 396
	{ USB_DEVICE(0x15c2, 0x003e),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
397
	/* device specifics unknown */
398 399
	{ USB_DEVICE(0x15c2, 0x003f),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
400
	/* device specifics unknown */
401 402
	{ USB_DEVICE(0x15c2, 0x0040),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
403
	/* SoundGraph iMON MINI (IR only) */
404 405
	{ USB_DEVICE(0x15c2, 0x0041),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
406
	/* Antec Veris Multimedia Station EZ External (IR only) */
407 408
	{ USB_DEVICE(0x15c2, 0x0042),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
409
	/* Antec Veris Multimedia Station Basic Internal (IR only) */
410 411
	{ USB_DEVICE(0x15c2, 0x0043),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
412
	/* Antec Veris Multimedia Station Elite (IR & VFD) */
413 414
	{ USB_DEVICE(0x15c2, 0x0044),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
415
	/* Antec Veris Multimedia Station Premiere (IR & LCD) */
416 417
	{ USB_DEVICE(0x15c2, 0x0045),
	  .driver_info = (unsigned long)&imon_default_table},
J
Jarod Wilson 已提交
418
	/* device specifics unknown */
419 420
	{ USB_DEVICE(0x15c2, 0x0046),
	  .driver_info = (unsigned long)&imon_default_table},
421 422 423 424 425 426 427 428 429 430 431 432
	/* TriGem iMON (IR only) -- TG_iMON.inf */
	{ USB_DEVICE(0x0aa8, 0x8001),
	  .driver_info = (unsigned long)&imon_ir_raw},
	/* SoundGraph iMON (IR only) -- sg_imon.inf */
	{ USB_DEVICE(0x04e8, 0xff30),
	  .driver_info = (unsigned long)&imon_ir_raw},
	/* SoundGraph iMON VFD (IR & VFD) -- iMON_VFD.inf */
	{ USB_DEVICE(0x0aa8, 0xffda),
	  .driver_info = (unsigned long)&imon_ir_raw},
	/* SoundGraph iMON SS (IR & VFD) -- iMON_SS.inf */
	{ USB_DEVICE(0x15c2, 0xffda),
	  .driver_info = (unsigned long)&imon_ir_raw},
J
Jarod Wilson 已提交
433 434 435 436 437 438 439
	{}
};

/* USB Device data */
static struct usb_driver imon_driver = {
	.name		= MOD_NAME,
	.probe		= imon_probe,
440
	.disconnect	= imon_disconnect,
J
Jarod Wilson 已提交
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
	.suspend	= imon_suspend,
	.resume		= imon_resume,
	.id_table	= imon_usb_id_table,
};

/* to prevent races between open() and disconnect(), probing, etc */
static DEFINE_MUTEX(driver_lock);

/* Module bookkeeping bits */
MODULE_AUTHOR(MOD_AUTHOR);
MODULE_DESCRIPTION(MOD_DESC);
MODULE_VERSION(MOD_VERSION);
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(usb, imon_usb_id_table);

static bool debug;
module_param(debug, bool, S_IRUGO | S_IWUSR);
458
MODULE_PARM_DESC(debug, "Debug messages: 0=no, 1=yes (default: no)");
J
Jarod Wilson 已提交
459 460 461 462

/* lcd, vfd, vga or none? should be auto-detected, but can be overridden... */
static int display_type;
module_param(display_type, int, S_IRUGO);
463
MODULE_PARM_DESC(display_type, "Type of attached display. 0=autodetect, 1=vfd, 2=lcd, 3=vga, 4=none (default: autodetect)");
J
Jarod Wilson 已提交
464

465 466
static int pad_stabilize = 1;
module_param(pad_stabilize, int, S_IRUGO | S_IWUSR);
467
MODULE_PARM_DESC(pad_stabilize, "Apply stabilization algorithm to iMON PAD presses in arrow key mode. 0=disable, 1=enable (default).");
J
Jarod Wilson 已提交
468 469 470 471 472 473 474

/*
 * In certain use cases, mouse mode isn't really helpful, and could actually
 * cause confusion, so allow disabling it when the IR device is open.
 */
static bool nomouse;
module_param(nomouse, bool, S_IRUGO | S_IWUSR);
475
MODULE_PARM_DESC(nomouse, "Disable mouse input device mode when IR device is open. 0=don't disable, 1=disable. (default: don't disable)");
J
Jarod Wilson 已提交
476 477 478 479

/* threshold at which a pad push registers as an arrow key in kbd mode */
static int pad_thresh;
module_param(pad_thresh, int, S_IRUGO | S_IWUSR);
480
MODULE_PARM_DESC(pad_thresh, "Threshold at which a pad push registers as an arrow key in kbd mode (default: 28)");
J
Jarod Wilson 已提交
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511


static void free_imon_context(struct imon_context *ictx)
{
	struct device *dev = ictx->dev;

	usb_free_urb(ictx->tx_urb);
	usb_free_urb(ictx->rx_urb_intf0);
	usb_free_urb(ictx->rx_urb_intf1);
	kfree(ictx);

	dev_dbg(dev, "%s: iMON context freed\n", __func__);
}

/**
 * Called when the Display device (e.g. /dev/lcd0)
 * is opened by the application.
 */
static int display_open(struct inode *inode, struct file *file)
{
	struct usb_interface *interface;
	struct imon_context *ictx = NULL;
	int subminor;
	int retval = 0;

	/* prevent races with disconnect */
	mutex_lock(&driver_lock);

	subminor = iminor(inode);
	interface = usb_find_interface(&imon_driver, subminor);
	if (!interface) {
512
		pr_err("could not find interface for minor %d\n", subminor);
J
Jarod Wilson 已提交
513 514 515 516 517 518
		retval = -ENODEV;
		goto exit;
	}
	ictx = usb_get_intfdata(interface);

	if (!ictx) {
519
		pr_err("no context found for minor %d\n", subminor);
J
Jarod Wilson 已提交
520 521 522 523 524 525 526
		retval = -ENODEV;
		goto exit;
	}

	mutex_lock(&ictx->lock);

	if (!ictx->display_supported) {
527
		pr_err("display not supported by device\n");
J
Jarod Wilson 已提交
528 529
		retval = -ENODEV;
	} else if (ictx->display_isopen) {
530
		pr_err("display port is already open\n");
J
Jarod Wilson 已提交
531 532
		retval = -EBUSY;
	} else {
533
		ictx->display_isopen = true;
J
Jarod Wilson 已提交
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
		file->private_data = ictx;
		dev_dbg(ictx->dev, "display port opened\n");
	}

	mutex_unlock(&ictx->lock);

exit:
	mutex_unlock(&driver_lock);
	return retval;
}

/**
 * Called when the display device (e.g. /dev/lcd0)
 * is closed by the application.
 */
static int display_close(struct inode *inode, struct file *file)
{
	struct imon_context *ictx = NULL;
	int retval = 0;

554
	ictx = file->private_data;
J
Jarod Wilson 已提交
555 556

	if (!ictx) {
557
		pr_err("no context for device\n");
J
Jarod Wilson 已提交
558 559 560 561 562 563
		return -ENODEV;
	}

	mutex_lock(&ictx->lock);

	if (!ictx->display_supported) {
564
		pr_err("display not supported by device\n");
J
Jarod Wilson 已提交
565 566
		retval = -ENODEV;
	} else if (!ictx->display_isopen) {
567
		pr_err("display is not open\n");
J
Jarod Wilson 已提交
568 569
		retval = -EIO;
	} else {
570
		ictx->display_isopen = false;
J
Jarod Wilson 已提交
571 572 573 574 575 576 577 578
		dev_dbg(ictx->dev, "display port closed\n");
	}

	mutex_unlock(&ictx->lock);
	return retval;
}

/**
579 580 581
 * Sends a packet to the device -- this function must be called with
 * ictx->lock held, or its unlock/lock sequence while waiting for tx
 * to complete can/will lead to a deadlock.
J
Jarod Wilson 已提交
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
 */
static int send_packet(struct imon_context *ictx)
{
	unsigned int pipe;
	unsigned long timeout;
	int interval = 0;
	int retval = 0;
	struct usb_ctrlrequest *control_req = NULL;

	/* Check if we need to use control or interrupt urb */
	if (!ictx->tx_control) {
		pipe = usb_sndintpipe(ictx->usbdev_intf0,
				      ictx->tx_endpoint->bEndpointAddress);
		interval = ictx->tx_endpoint->bInterval;

		usb_fill_int_urb(ictx->tx_urb, ictx->usbdev_intf0, pipe,
				 ictx->usb_tx_buf,
				 sizeof(ictx->usb_tx_buf),
				 usb_tx_callback, ictx, interval);

		ictx->tx_urb->actual_length = 0;
	} else {
		/* fill request into kmalloc'ed space: */
605
		control_req = kmalloc(sizeof(*control_req), GFP_KERNEL);
J
Jarod Wilson 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627
		if (control_req == NULL)
			return -ENOMEM;

		/* setup packet is '21 09 0200 0001 0008' */
		control_req->bRequestType = 0x21;
		control_req->bRequest = 0x09;
		control_req->wValue = cpu_to_le16(0x0200);
		control_req->wIndex = cpu_to_le16(0x0001);
		control_req->wLength = cpu_to_le16(0x0008);

		/* control pipe is endpoint 0x00 */
		pipe = usb_sndctrlpipe(ictx->usbdev_intf0, 0);

		/* build the control urb */
		usb_fill_control_urb(ictx->tx_urb, ictx->usbdev_intf0,
				     pipe, (unsigned char *)control_req,
				     ictx->usb_tx_buf,
				     sizeof(ictx->usb_tx_buf),
				     usb_tx_callback, ictx);
		ictx->tx_urb->actual_length = 0;
	}

628
	reinit_completion(&ictx->tx.finished);
629
	ictx->tx.busy = true;
J
Jarod Wilson 已提交
630 631 632 633
	smp_rmb(); /* ensure later readers know we're busy */

	retval = usb_submit_urb(ictx->tx_urb, GFP_KERNEL);
	if (retval) {
634
		ictx->tx.busy = false;
J
Jarod Wilson 已提交
635
		smp_rmb(); /* ensure later readers know we're not busy */
636
		pr_err_ratelimited("error submitting urb(%d)\n", retval);
J
Jarod Wilson 已提交
637 638 639 640 641
	} else {
		/* Wait for transmission to complete (or abort) */
		mutex_unlock(&ictx->lock);
		retval = wait_for_completion_interruptible(
				&ictx->tx.finished);
642 643
		if (retval) {
			usb_kill_urb(ictx->tx_urb);
644
			pr_err_ratelimited("task interrupted\n");
645
		}
J
Jarod Wilson 已提交
646 647 648 649
		mutex_lock(&ictx->lock);

		retval = ictx->tx.status;
		if (retval)
650
			pr_err_ratelimited("packet tx failed (%d)\n", retval);
J
Jarod Wilson 已提交
651 652 653 654 655
	}

	kfree(control_req);

	/*
656
	 * Induce a mandatory delay before returning, as otherwise,
J
Jarod Wilson 已提交
657 658 659
	 * send_packet can get called so rapidly as to overwhelm the device,
	 * particularly on faster systems and/or those with quirky usb.
	 */
660 661
	timeout = msecs_to_jiffies(ictx->send_packet_delay);
	set_current_state(TASK_INTERRUPTIBLE);
J
Jarod Wilson 已提交
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
	schedule_timeout(timeout);

	return retval;
}

/**
 * Sends an associate packet to the iMON 2.4G.
 *
 * This might not be such a good idea, since it has an id collision with
 * some versions of the "IR & VFD" combo. The only way to determine if it
 * is an RF version is to look at the product description string. (Which
 * we currently do not fetch).
 */
static int send_associate_24g(struct imon_context *ictx)
{
	int retval;
	const unsigned char packet[8] = { 0x01, 0x00, 0x00, 0x00,
					  0x00, 0x00, 0x00, 0x20 };

	if (!ictx) {
682
		pr_err("no context for device\n");
J
Jarod Wilson 已提交
683 684 685 686
		return -ENODEV;
	}

	if (!ictx->dev_present_intf0) {
687
		pr_err("no iMON device present\n");
J
Jarod Wilson 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
		return -ENODEV;
	}

	memcpy(ictx->usb_tx_buf, packet, sizeof(packet));
	retval = send_packet(ictx);

	return retval;
}

/**
 * Sends packets to setup and show clock on iMON display
 *
 * Arguments: year - last 2 digits of year, month - 1..12,
 * day - 1..31, dow - day of the week (0-Sun...6-Sat),
 * hour - 0..23, minute - 0..59, second - 0..59
 */
static int send_set_imon_clock(struct imon_context *ictx,
			       unsigned int year, unsigned int month,
			       unsigned int day, unsigned int dow,
			       unsigned int hour, unsigned int minute,
			       unsigned int second)
{
	unsigned char clock_enable_pkt[IMON_CLOCK_ENABLE_PACKETS][8];
	int retval = 0;
	int i;

	if (!ictx) {
715
		pr_err("no context for device\n");
J
Jarod Wilson 已提交
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
		return -ENODEV;
	}

	switch (ictx->display_type) {
	case IMON_DISPLAY_TYPE_LCD:
		clock_enable_pkt[0][0] = 0x80;
		clock_enable_pkt[0][1] = year;
		clock_enable_pkt[0][2] = month-1;
		clock_enable_pkt[0][3] = day;
		clock_enable_pkt[0][4] = hour;
		clock_enable_pkt[0][5] = minute;
		clock_enable_pkt[0][6] = second;

		clock_enable_pkt[1][0] = 0x80;
		clock_enable_pkt[1][1] = 0;
		clock_enable_pkt[1][2] = 0;
		clock_enable_pkt[1][3] = 0;
		clock_enable_pkt[1][4] = 0;
		clock_enable_pkt[1][5] = 0;
		clock_enable_pkt[1][6] = 0;

		if (ictx->product == 0xffdc) {
			clock_enable_pkt[0][7] = 0x50;
			clock_enable_pkt[1][7] = 0x51;
		} else {
			clock_enable_pkt[0][7] = 0x88;
			clock_enable_pkt[1][7] = 0x8a;
		}

		break;

	case IMON_DISPLAY_TYPE_VFD:
		clock_enable_pkt[0][0] = year;
		clock_enable_pkt[0][1] = month-1;
		clock_enable_pkt[0][2] = day;
		clock_enable_pkt[0][3] = dow;
		clock_enable_pkt[0][4] = hour;
		clock_enable_pkt[0][5] = minute;
		clock_enable_pkt[0][6] = second;
		clock_enable_pkt[0][7] = 0x40;

		clock_enable_pkt[1][0] = 0;
		clock_enable_pkt[1][1] = 0;
		clock_enable_pkt[1][2] = 1;
		clock_enable_pkt[1][3] = 0;
		clock_enable_pkt[1][4] = 0;
		clock_enable_pkt[1][5] = 0;
		clock_enable_pkt[1][6] = 0;
		clock_enable_pkt[1][7] = 0x42;

		break;

	default:
		return -ENODEV;
	}

	for (i = 0; i < IMON_CLOCK_ENABLE_PACKETS; i++) {
		memcpy(ictx->usb_tx_buf, clock_enable_pkt[i], 8);
		retval = send_packet(ictx);
		if (retval) {
776
			pr_err("send_packet failed for packet %d\n", i);
J
Jarod Wilson 已提交
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801
			break;
		}
	}

	return retval;
}

/**
 * These are the sysfs functions to handle the association on the iMON 2.4G LT.
 */
static ssize_t show_associate_remote(struct device *d,
				     struct device_attribute *attr,
				     char *buf)
{
	struct imon_context *ictx = dev_get_drvdata(d);

	if (!ictx)
		return -ENODEV;

	mutex_lock(&ictx->lock);
	if (ictx->rf_isassociating)
		strcpy(buf, "associating\n");
	else
		strcpy(buf, "closed\n");

802
	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");
J
Jarod Wilson 已提交
803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818
	mutex_unlock(&ictx->lock);
	return strlen(buf);
}

static ssize_t store_associate_remote(struct device *d,
				      struct device_attribute *attr,
				      const char *buf, size_t count)
{
	struct imon_context *ictx;

	ictx = dev_get_drvdata(d);

	if (!ictx)
		return -ENODEV;

	mutex_lock(&ictx->lock);
819
	ictx->rf_isassociating = true;
J
Jarod Wilson 已提交
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912
	send_associate_24g(ictx);
	mutex_unlock(&ictx->lock);

	return count;
}

/**
 * sysfs functions to control internal imon clock
 */
static ssize_t show_imon_clock(struct device *d,
			       struct device_attribute *attr, char *buf)
{
	struct imon_context *ictx = dev_get_drvdata(d);
	size_t len;

	if (!ictx)
		return -ENODEV;

	mutex_lock(&ictx->lock);

	if (!ictx->display_supported) {
		len = snprintf(buf, PAGE_SIZE, "Not supported.");
	} else {
		len = snprintf(buf, PAGE_SIZE,
			"To set the clock on your iMON display:\n"
			"# date \"+%%y %%m %%d %%w %%H %%M %%S\" > imon_clock\n"
			"%s", ictx->display_isopen ?
			"\nNOTE: imon device must be closed\n" : "");
	}

	mutex_unlock(&ictx->lock);

	return len;
}

static ssize_t store_imon_clock(struct device *d,
				struct device_attribute *attr,
				const char *buf, size_t count)
{
	struct imon_context *ictx = dev_get_drvdata(d);
	ssize_t retval;
	unsigned int year, month, day, dow, hour, minute, second;

	if (!ictx)
		return -ENODEV;

	mutex_lock(&ictx->lock);

	if (!ictx->display_supported) {
		retval = -ENODEV;
		goto exit;
	} else if (ictx->display_isopen) {
		retval = -EBUSY;
		goto exit;
	}

	if (sscanf(buf, "%u %u %u %u %u %u %u",	&year, &month, &day, &dow,
		   &hour, &minute, &second) != 7) {
		retval = -EINVAL;
		goto exit;
	}

	if ((month < 1 || month > 12) ||
	    (day < 1 || day > 31) || (dow > 6) ||
	    (hour > 23) || (minute > 59) || (second > 59)) {
		retval = -EINVAL;
		goto exit;
	}

	retval = send_set_imon_clock(ictx, year, month, day, dow,
				     hour, minute, second);
	if (retval)
		goto exit;

	retval = count;
exit:
	mutex_unlock(&ictx->lock);

	return retval;
}


static DEVICE_ATTR(imon_clock, S_IWUSR | S_IRUGO, show_imon_clock,
		   store_imon_clock);

static DEVICE_ATTR(associate_remote, S_IWUSR | S_IRUGO, show_associate_remote,
		   store_associate_remote);

static struct attribute *imon_display_sysfs_entries[] = {
	&dev_attr_imon_clock.attr,
	NULL
};

913
static const struct attribute_group imon_display_attr_group = {
J
Jarod Wilson 已提交
914 915 916 917 918 919 920 921
	.attrs = imon_display_sysfs_entries
};

static struct attribute *imon_rf_sysfs_entries[] = {
	&dev_attr_associate_remote.attr,
	NULL
};

922
static const struct attribute_group imon_rf_attr_group = {
J
Jarod Wilson 已提交
923 924 925 926 927 928 929 930 931 932 933 934 935 936
	.attrs = imon_rf_sysfs_entries
};

/**
 * Writes data to the VFD.  The iMON VFD is 2x16 characters
 * and requires data in 5 consecutive USB interrupt packets,
 * each packet but the last carrying 7 bytes.
 *
 * I don't know if the VFD board supports features such as
 * scrolling, clearing rows, blanking, etc. so at
 * the caller must provide a full screen of data.  If fewer
 * than 32 bytes are provided spaces will be appended to
 * generate a full screen.
 */
937
static ssize_t vfd_write(struct file *file, const char __user *buf,
J
Jarod Wilson 已提交
938 939 940 941 942 943 944
			 size_t n_bytes, loff_t *pos)
{
	int i;
	int offset;
	int seq;
	int retval = 0;
	struct imon_context *ictx;
945
	static const unsigned char vfd_packet6[] = {
J
Jarod Wilson 已提交
946 947
		0x01, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF };

948
	ictx = file->private_data;
J
Jarod Wilson 已提交
949
	if (!ictx) {
950
		pr_err_ratelimited("no context for device\n");
J
Jarod Wilson 已提交
951 952 953 954 955 956
		return -ENODEV;
	}

	mutex_lock(&ictx->lock);

	if (!ictx->dev_present_intf0) {
957
		pr_err_ratelimited("no iMON device present\n");
J
Jarod Wilson 已提交
958 959 960 961 962
		retval = -ENODEV;
		goto exit;
	}

	if (n_bytes <= 0 || n_bytes > 32) {
963
		pr_err_ratelimited("invalid payload size\n");
J
Jarod Wilson 已提交
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
		retval = -EINVAL;
		goto exit;
	}

	if (copy_from_user(ictx->tx.data_buf, buf, n_bytes)) {
		retval = -EFAULT;
		goto exit;
	}

	/* Pad with spaces */
	for (i = n_bytes; i < 32; ++i)
		ictx->tx.data_buf[i] = ' ';

	for (i = 32; i < 35; ++i)
		ictx->tx.data_buf[i] = 0xFF;

	offset = 0;
	seq = 0;

	do {
		memcpy(ictx->usb_tx_buf, ictx->tx.data_buf + offset, 7);
		ictx->usb_tx_buf[7] = (unsigned char) seq;

		retval = send_packet(ictx);
		if (retval) {
989
			pr_err_ratelimited("send packet #%d failed\n", seq / 2);
J
Jarod Wilson 已提交
990 991 992 993 994 995 996 997 998 999 1000 1001 1002
			goto exit;
		} else {
			seq += 2;
			offset += 7;
		}

	} while (offset < 35);

	/* Send packet #6 */
	memcpy(ictx->usb_tx_buf, &vfd_packet6, sizeof(vfd_packet6));
	ictx->usb_tx_buf[7] = (unsigned char) seq;
	retval = send_packet(ictx);
	if (retval)
1003
		pr_err_ratelimited("send packet #%d failed\n", seq / 2);
J
Jarod Wilson 已提交
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023

exit:
	mutex_unlock(&ictx->lock);

	return (!retval) ? n_bytes : retval;
}

/**
 * Writes data to the LCD.  The iMON OEM LCD screen expects 8-byte
 * packets. We accept data as 16 hexadecimal digits, followed by a
 * newline (to make it easy to drive the device from a command-line
 * -- even though the actual binary data is a bit complicated).
 *
 * The device itself is not a "traditional" text-mode display. It's
 * actually a 16x96 pixel bitmap display. That means if you want to
 * display text, you've got to have your own "font" and translate the
 * text into bitmaps for display. This is really flexible (you can
 * display whatever diacritics you need, and so on), but it's also
 * a lot more complicated than most LCDs...
 */
1024
static ssize_t lcd_write(struct file *file, const char __user *buf,
J
Jarod Wilson 已提交
1025 1026 1027 1028 1029
			 size_t n_bytes, loff_t *pos)
{
	int retval = 0;
	struct imon_context *ictx;

1030
	ictx = file->private_data;
J
Jarod Wilson 已提交
1031
	if (!ictx) {
1032
		pr_err_ratelimited("no context for device\n");
J
Jarod Wilson 已提交
1033 1034 1035 1036 1037 1038
		return -ENODEV;
	}

	mutex_lock(&ictx->lock);

	if (!ictx->display_supported) {
1039
		pr_err_ratelimited("no iMON display present\n");
J
Jarod Wilson 已提交
1040 1041 1042 1043 1044
		retval = -ENODEV;
		goto exit;
	}

	if (n_bytes != 8) {
1045 1046
		pr_err_ratelimited("invalid payload size: %d (expected 8)\n",
				   (int)n_bytes);
J
Jarod Wilson 已提交
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
		retval = -EINVAL;
		goto exit;
	}

	if (copy_from_user(ictx->usb_tx_buf, buf, 8)) {
		retval = -EFAULT;
		goto exit;
	}

	retval = send_packet(ictx);
	if (retval) {
1058
		pr_err_ratelimited("send packet failed!\n");
J
Jarod Wilson 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
		goto exit;
	} else {
		dev_dbg(ictx->dev, "%s: write %d bytes to LCD\n",
			__func__, (int) n_bytes);
	}
exit:
	mutex_unlock(&ictx->lock);
	return (!retval) ? n_bytes : retval;
}

/**
 * Callback function for USB core API: transmit data
 */
static void usb_tx_callback(struct urb *urb)
{
	struct imon_context *ictx;

	if (!urb)
		return;
	ictx = (struct imon_context *)urb->context;
	if (!ictx)
		return;

	ictx->tx.status = urb->status;

	/* notify waiters that write has finished */
1085
	ictx->tx.busy = false;
J
Jarod Wilson 已提交
1086 1087 1088 1089 1090 1091 1092
	smp_rmb(); /* ensure later readers know we're not busy */
	complete(&ictx->tx.finished);
}

/**
 * report touchscreen input
 */
1093
static void imon_touch_display_timeout(struct timer_list *t)
J
Jarod Wilson 已提交
1094
{
1095
	struct imon_context *ictx = from_timer(ictx, t, ttimer);
J
Jarod Wilson 已提交
1096

1097
	if (ictx->display_type != IMON_DISPLAY_TYPE_VGA)
J
Jarod Wilson 已提交
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
		return;

	input_report_abs(ictx->touch, ABS_X, ictx->touch_x);
	input_report_abs(ictx->touch, ABS_Y, ictx->touch_y);
	input_report_key(ictx->touch, BTN_TOUCH, 0x00);
	input_sync(ictx->touch);
}

/**
 * iMON IR receivers support two different signal sets -- those used by
 * the iMON remotes, and those used by the Windows MCE remotes (which is
 * really just RC-6), but only one or the other at a time, as the signals
 * are decoded onboard the receiver.
1111 1112 1113 1114 1115 1116 1117 1118
 *
 * This function gets called two different ways, one way is from
 * rc_register_device, for initial protocol selection/setup, and the other is
 * via a userspace-initiated protocol change request, either by direct sysfs
 * prodding or by something like ir-keytable. In the rc_register_device case,
 * the imon context lock is already held, but when initiated from userspace,
 * it is not, so we must acquire it prior to calling send_packet, which
 * requires that the lock is held.
J
Jarod Wilson 已提交
1119
 */
1120
static int imon_ir_change_protocol(struct rc_dev *rc, u64 *rc_proto)
J
Jarod Wilson 已提交
1121 1122
{
	int retval;
1123
	struct imon_context *ictx = rc->priv;
J
Jarod Wilson 已提交
1124
	struct device *dev = ictx->dev;
1125
	bool unlock = false;
J
Jarod Wilson 已提交
1126 1127 1128
	unsigned char ir_proto_packet[] = {
		0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x86 };

1129
	if (*rc_proto && !(*rc_proto & rc->allowed_protocols))
1130
		dev_warn(dev, "Looks like you're trying to use an IR protocol this device does not support\n");
J
Jarod Wilson 已提交
1131

1132
	if (*rc_proto & RC_PROTO_BIT_RC6_MCE) {
J
Jarod Wilson 已提交
1133 1134
		dev_dbg(dev, "Configuring IR receiver for MCE protocol\n");
		ir_proto_packet[0] = 0x01;
1135 1136
		*rc_proto = RC_PROTO_BIT_RC6_MCE;
	} else if (*rc_proto & RC_PROTO_BIT_OTHER) {
1137
		dev_dbg(dev, "Configuring IR receiver for iMON protocol\n");
1138
		if (!pad_stabilize)
1139
			dev_dbg(dev, "PAD stabilize functionality disabled\n");
J
Jarod Wilson 已提交
1140
		/* ir_proto_packet[0] = 0x00; // already the default */
1141
		*rc_proto = RC_PROTO_BIT_OTHER;
1142
	} else {
1143
		dev_warn(dev, "Unsupported IR protocol specified, overriding to iMON IR protocol\n");
1144
		if (!pad_stabilize)
1145
			dev_dbg(dev, "PAD stabilize functionality disabled\n");
1146
		/* ir_proto_packet[0] = 0x00; // already the default */
1147
		*rc_proto = RC_PROTO_BIT_OTHER;
J
Jarod Wilson 已提交
1148 1149 1150 1151
	}

	memcpy(ictx->usb_tx_buf, &ir_proto_packet, sizeof(ir_proto_packet));

1152 1153 1154 1155 1156
	if (!mutex_is_locked(&ictx->lock)) {
		unlock = true;
		mutex_lock(&ictx->lock);
	}

J
Jarod Wilson 已提交
1157
	retval = send_packet(ictx);
1158 1159 1160
	if (retval)
		goto out;

1161
	ictx->rc_proto = *rc_proto;
1162
	ictx->pad_mouse = false;
1163 1164

out:
1165 1166 1167
	if (unlock)
		mutex_unlock(&ictx->lock);

1168
	return retval;
J
Jarod Wilson 已提交
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
}

static inline int tv2int(const struct timeval *a, const struct timeval *b)
{
	int usecs = 0;
	int sec   = 0;

	if (b->tv_usec > a->tv_usec) {
		usecs = 1000000;
		sec--;
	}

	usecs += a->tv_usec - b->tv_usec;

	sec += a->tv_sec - b->tv_sec;
	sec *= 1000;
	usecs /= 1000;
	sec += usecs;

	if (sec < 0)
		sec = 1000;

	return sec;
}

/**
 * The directional pad behaves a bit differently, depending on whether this is
 * one of the older ffdc devices or a newer device. Newer devices appear to
 * have a higher resolution matrix for more precise mouse movement, but it
 * makes things overly sensitive in keyboard mode, so we do some interesting
 * contortions to make it less touchy. Older devices run through the same
 * routine with shorter timeout and a smaller threshold.
 */
static int stabilize(int a, int b, u16 timeout, u16 threshold)
{
	struct timeval ct;
	static struct timeval prev_time = {0, 0};
	static struct timeval hit_time  = {0, 0};
	static int x, y, prev_result, hits;
	int result = 0;
	int msec, msec_hit;

	do_gettimeofday(&ct);
	msec = tv2int(&ct, &prev_time);
	msec_hit = tv2int(&ct, &hit_time);

	if (msec > 100) {
		x = 0;
		y = 0;
		hits = 0;
	}

	x += a;
	y += b;

	prev_time = ct;

	if (abs(x) > threshold || abs(y) > threshold) {
		if (abs(y) > abs(x))
			result = (y > 0) ? 0x7F : 0x80;
		else
			result = (x > 0) ? 0x7F00 : 0x8000;

		x = 0;
		y = 0;

		if (result == prev_result) {
			hits++;

			if (hits > 3) {
				switch (result) {
				case 0x7F:
					y = 17 * threshold / 30;
					break;
				case 0x80:
					y -= 17 * threshold / 30;
					break;
				case 0x7F00:
					x = 17 * threshold / 30;
					break;
				case 0x8000:
					x -= 17 * threshold / 30;
					break;
				}
			}

			if (hits == 2 && msec_hit < timeout) {
				result = 0;
				hits = 1;
			}
		} else {
			prev_result = result;
			hits = 1;
			hit_time = ct;
		}
	}

	return result;
}

1269
static u32 imon_remote_key_lookup(struct imon_context *ictx, u32 scancode)
J
Jarod Wilson 已提交
1270 1271 1272 1273 1274 1275
{
	u32 keycode;
	u32 release;
	bool is_release_code = false;

	/* Look for the initial press of a button */
1276
	keycode = rc_g_keycode_from_table(ictx->rdev, scancode);
1277 1278
	ictx->rc_toggle = 0x0;
	ictx->rc_scancode = scancode;
J
Jarod Wilson 已提交
1279 1280 1281 1282

	/* Look for the release of a button */
	if (keycode == KEY_RESERVED) {
		release = scancode & ~0x4000;
1283
		keycode = rc_g_keycode_from_table(ictx->rdev, release);
J
Jarod Wilson 已提交
1284 1285 1286 1287 1288 1289 1290 1291 1292
		if (keycode != KEY_RESERVED)
			is_release_code = true;
	}

	ictx->release_code = is_release_code;

	return keycode;
}

1293
static u32 imon_mce_key_lookup(struct imon_context *ictx, u32 scancode)
J
Jarod Wilson 已提交
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307
{
	u32 keycode;

#define MCE_KEY_MASK 0x7000
#define MCE_TOGGLE_BIT 0x8000

	/*
	 * On some receivers, mce keys decode to 0x8000f04xx and 0x8000f84xx
	 * (the toggle bit flipping between alternating key presses), while
	 * on other receivers, we see 0x8000f74xx and 0x8000ff4xx. To keep
	 * the table trim, we always or in the bits to look up 0x8000ff4xx,
	 * but we can't or them into all codes, as some keys are decoded in
	 * a different way w/o the same use of the toggle bit...
	 */
1308
	if (scancode & 0x80000000)
J
Jarod Wilson 已提交
1309 1310
		scancode = scancode | MCE_KEY_MASK | MCE_TOGGLE_BIT;

1311
	ictx->rc_scancode = scancode;
1312
	keycode = rc_g_keycode_from_table(ictx->rdev, scancode);
1313 1314 1315

	/* not used in mce mode, but make sure we know its false */
	ictx->release_code = false;
J
Jarod Wilson 已提交
1316 1317 1318 1319

	return keycode;
}

1320
static u32 imon_panel_key_lookup(struct imon_context *ictx, u64 code)
J
Jarod Wilson 已提交
1321 1322
{
	int i;
1323
	u32 keycode = KEY_RESERVED;
1324
	struct imon_panel_key_table *key_table = ictx->dev_descr->key_table;
J
Jarod Wilson 已提交
1325

1326 1327 1328
	for (i = 0; key_table[i].hw_code != 0; i++) {
		if (key_table[i].hw_code == (code | 0xffee)) {
			keycode = key_table[i].keycode;
J
Jarod Wilson 已提交
1329
			break;
1330 1331
		}
	}
1332
	ictx->release_code = false;
J
Jarod Wilson 已提交
1333 1334 1335 1336 1337 1338
	return keycode;
}

static bool imon_mouse_event(struct imon_context *ictx,
			     unsigned char *buf, int len)
{
1339
	signed char rel_x = 0x00, rel_y = 0x00;
J
Jarod Wilson 已提交
1340
	u8 right_shift = 1;
1341
	bool mouse_input = true;
J
Jarod Wilson 已提交
1342
	int dir = 0;
1343 1344 1345
	unsigned long flags;

	spin_lock_irqsave(&ictx->kc_lock, flags);
J
Jarod Wilson 已提交
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374

	/* newer iMON device PAD or mouse button */
	if (ictx->product != 0xffdc && (buf[0] & 0x01) && len == 5) {
		rel_x = buf[2];
		rel_y = buf[3];
		right_shift = 1;
	/* 0xffdc iMON PAD or mouse button input */
	} else if (ictx->product == 0xffdc && (buf[0] & 0x40) &&
			!((buf[1] & 0x01) || ((buf[1] >> 2) & 0x01))) {
		rel_x = (buf[1] & 0x08) | (buf[1] & 0x10) >> 2 |
			(buf[1] & 0x20) >> 4 | (buf[1] & 0x40) >> 6;
		if (buf[0] & 0x02)
			rel_x |= ~0x0f;
		rel_x = rel_x + rel_x / 2;
		rel_y = (buf[2] & 0x08) | (buf[2] & 0x10) >> 2 |
			(buf[2] & 0x20) >> 4 | (buf[2] & 0x40) >> 6;
		if (buf[0] & 0x01)
			rel_y |= ~0x0f;
		rel_y = rel_y + rel_y / 2;
		right_shift = 2;
	/* some ffdc devices decode mouse buttons differently... */
	} else if (ictx->product == 0xffdc && (buf[0] == 0x68)) {
		right_shift = 2;
	/* ch+/- buttons, which we use for an emulated scroll wheel */
	} else if (ictx->kc == KEY_CHANNELUP && (buf[2] & 0x40) != 0x40) {
		dir = 1;
	} else if (ictx->kc == KEY_CHANNELDOWN && (buf[2] & 0x40) != 0x40) {
		dir = -1;
	} else
1375
		mouse_input = false;
J
Jarod Wilson 已提交
1376

1377 1378
	spin_unlock_irqrestore(&ictx->kc_lock, flags);

J
Jarod Wilson 已提交
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
	if (mouse_input) {
		dev_dbg(ictx->dev, "sending mouse data via input subsystem\n");

		if (dir) {
			input_report_rel(ictx->idev, REL_WHEEL, dir);
		} else if (rel_x || rel_y) {
			input_report_rel(ictx->idev, REL_X, rel_x);
			input_report_rel(ictx->idev, REL_Y, rel_y);
		} else {
			input_report_key(ictx->idev, BTN_LEFT, buf[1] & 0x1);
			input_report_key(ictx->idev, BTN_RIGHT,
					 buf[1] >> right_shift & 0x1);
		}
		input_sync(ictx->idev);
1393
		spin_lock_irqsave(&ictx->kc_lock, flags);
J
Jarod Wilson 已提交
1394
		ictx->last_keycode = ictx->kc;
1395
		spin_unlock_irqrestore(&ictx->kc_lock, flags);
J
Jarod Wilson 已提交
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414
	}

	return mouse_input;
}

static void imon_touch_event(struct imon_context *ictx, unsigned char *buf)
{
	mod_timer(&ictx->ttimer, jiffies + TOUCH_TIMEOUT);
	ictx->touch_x = (buf[0] << 4) | (buf[1] >> 4);
	ictx->touch_y = 0xfff - ((buf[2] << 4) | (buf[1] & 0xf));
	input_report_abs(ictx->touch, ABS_X, ictx->touch_x);
	input_report_abs(ictx->touch, ABS_Y, ictx->touch_y);
	input_report_key(ictx->touch, BTN_TOUCH, 0x01);
	input_sync(ictx->touch);
}

static void imon_pad_to_keys(struct imon_context *ictx, unsigned char *buf)
{
	int dir = 0;
1415
	signed char rel_x = 0x00, rel_y = 0x00;
J
Jarod Wilson 已提交
1416
	u16 timeout, threshold;
1417
	u32 scancode = KEY_RESERVED;
1418
	unsigned long flags;
J
Jarod Wilson 已提交
1419 1420 1421 1422 1423 1424

	/*
	 * The imon directional pad functions more like a touchpad. Bytes 3 & 4
	 * contain a position coordinate (x,y), with each component ranging
	 * from -14 to 14. We want to down-sample this to only 4 discrete values
	 * for up/down/left/right arrow keys. Also, when you get too close to
L
Lucas De Marchi 已提交
1425
	 * diagonals, it has a tendency to jump back and forth, so lets try to
J
Jarod Wilson 已提交
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
	 * ignore when they get too close.
	 */
	if (ictx->product != 0xffdc) {
		/* first, pad to 8 bytes so it conforms with everything else */
		buf[5] = buf[6] = buf[7] = 0;
		timeout = 500;	/* in msecs */
		/* (2*threshold) x (2*threshold) square */
		threshold = pad_thresh ? pad_thresh : 28;
		rel_x = buf[2];
		rel_y = buf[3];

1437
		if (ictx->rc_proto == RC_PROTO_BIT_OTHER && pad_stabilize) {
J
Jarod Wilson 已提交
1438 1439 1440 1441
			if ((buf[1] == 0) && ((rel_x != 0) || (rel_y != 0))) {
				dir = stabilize((int)rel_x, (int)rel_y,
						timeout, threshold);
				if (!dir) {
1442 1443
					spin_lock_irqsave(&ictx->kc_lock,
							  flags);
J
Jarod Wilson 已提交
1444
					ictx->kc = KEY_UNKNOWN;
1445 1446
					spin_unlock_irqrestore(&ictx->kc_lock,
							       flags);
J
Jarod Wilson 已提交
1447 1448 1449 1450
					return;
				}
				buf[2] = dir & 0xFF;
				buf[3] = (dir >> 8) & 0xFF;
H
Hans Verkuil 已提交
1451
				scancode = be32_to_cpu(*((__be32 *)buf));
J
Jarod Wilson 已提交
1452 1453
			}
		} else {
1454 1455 1456 1457
			/*
			 * Hack alert: instead of using keycodes, we have
			 * to use hard-coded scancodes here...
			 */
J
Jarod Wilson 已提交
1458 1459 1460
			if (abs(rel_y) > abs(rel_x)) {
				buf[2] = (rel_y > 0) ? 0x7F : 0x80;
				buf[3] = 0;
1461 1462 1463 1464
				if (rel_y > 0)
					scancode = 0x01007f00; /* KEY_DOWN */
				else
					scancode = 0x01008000; /* KEY_UP */
J
Jarod Wilson 已提交
1465 1466 1467
			} else {
				buf[2] = 0;
				buf[3] = (rel_x > 0) ? 0x7F : 0x80;
1468 1469 1470 1471
				if (rel_x > 0)
					scancode = 0x0100007f; /* KEY_RIGHT */
				else
					scancode = 0x01000080; /* KEY_LEFT */
J
Jarod Wilson 已提交
1472 1473 1474 1475 1476 1477 1478 1479 1480
			}
		}

	/*
	 * Handle on-board decoded pad events for e.g. older VFD/iMON-Pad
	 * device (15c2:ffdc). The remote generates various codes from
	 * 0x68nnnnB7 to 0x6AnnnnB7, the left mouse button generates
	 * 0x688301b7 and the right one 0x688481b7. All other keys generate
	 * 0x2nnnnnnn. Position coordinate is encoded in buf[1] and buf[2] with
1481
	 * reversed endianness. Extract direction from buffer, rotate endianness,
J
Jarod Wilson 已提交
1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503
	 * adjust sign and feed the values into stabilize(). The resulting codes
	 * will be 0x01008000, 0x01007F00, which match the newer devices.
	 */
	} else {
		timeout = 10;	/* in msecs */
		/* (2*threshold) x (2*threshold) square */
		threshold = pad_thresh ? pad_thresh : 15;

		/* buf[1] is x */
		rel_x = (buf[1] & 0x08) | (buf[1] & 0x10) >> 2 |
			(buf[1] & 0x20) >> 4 | (buf[1] & 0x40) >> 6;
		if (buf[0] & 0x02)
			rel_x |= ~0x10+1;
		/* buf[2] is y */
		rel_y = (buf[2] & 0x08) | (buf[2] & 0x10) >> 2 |
			(buf[2] & 0x20) >> 4 | (buf[2] & 0x40) >> 6;
		if (buf[0] & 0x01)
			rel_y |= ~0x10+1;

		buf[0] = 0x01;
		buf[1] = buf[4] = buf[5] = buf[6] = buf[7] = 0;

1504
		if (ictx->rc_proto == RC_PROTO_BIT_OTHER && pad_stabilize) {
J
Jarod Wilson 已提交
1505 1506 1507
			dir = stabilize((int)rel_x, (int)rel_y,
					timeout, threshold);
			if (!dir) {
1508
				spin_lock_irqsave(&ictx->kc_lock, flags);
J
Jarod Wilson 已提交
1509
				ictx->kc = KEY_UNKNOWN;
1510
				spin_unlock_irqrestore(&ictx->kc_lock, flags);
J
Jarod Wilson 已提交
1511 1512 1513 1514
				return;
			}
			buf[2] = dir & 0xFF;
			buf[3] = (dir >> 8) & 0xFF;
H
Hans Verkuil 已提交
1515
			scancode = be32_to_cpu(*((__be32 *)buf));
J
Jarod Wilson 已提交
1516
		} else {
1517 1518 1519 1520
			/*
			 * Hack alert: instead of using keycodes, we have
			 * to use hard-coded scancodes here...
			 */
J
Jarod Wilson 已提交
1521 1522 1523
			if (abs(rel_y) > abs(rel_x)) {
				buf[2] = (rel_y > 0) ? 0x7F : 0x80;
				buf[3] = 0;
1524 1525 1526 1527
				if (rel_y > 0)
					scancode = 0x01007f00; /* KEY_DOWN */
				else
					scancode = 0x01008000; /* KEY_UP */
J
Jarod Wilson 已提交
1528 1529 1530
			} else {
				buf[2] = 0;
				buf[3] = (rel_x > 0) ? 0x7F : 0x80;
1531 1532 1533 1534
				if (rel_x > 0)
					scancode = 0x0100007f; /* KEY_RIGHT */
				else
					scancode = 0x01000080; /* KEY_LEFT */
J
Jarod Wilson 已提交
1535 1536 1537
			}
		}
	}
1538

1539 1540
	if (scancode) {
		spin_lock_irqsave(&ictx->kc_lock, flags);
1541
		ictx->kc = imon_remote_key_lookup(ictx, scancode);
1542 1543
		spin_unlock_irqrestore(&ictx->kc_lock, flags);
	}
J
Jarod Wilson 已提交
1544 1545
}

1546 1547 1548 1549 1550
/**
 * figure out if these is a press or a release. We don't actually
 * care about repeats, as those will be auto-generated within the IR
 * subsystem for repeating scancodes.
 */
J
Jarod Wilson 已提交
1551 1552 1553 1554
static int imon_parse_press_type(struct imon_context *ictx,
				 unsigned char *buf, u8 ktype)
{
	int press_type = 0;
1555 1556 1557
	unsigned long flags;

	spin_lock_irqsave(&ictx->kc_lock, flags);
J
Jarod Wilson 已提交
1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572

	/* key release of 0x02XXXXXX key */
	if (ictx->kc == KEY_RESERVED && buf[0] == 0x02 && buf[3] == 0x00)
		ictx->kc = ictx->last_keycode;

	/* mouse button release on (some) 0xffdc devices */
	else if (ictx->kc == KEY_RESERVED && buf[0] == 0x68 && buf[1] == 0x82 &&
		 buf[2] == 0x81 && buf[3] == 0xb7)
		ictx->kc = ictx->last_keycode;

	/* mouse button release on (some other) 0xffdc devices */
	else if (ictx->kc == KEY_RESERVED && buf[0] == 0x01 && buf[1] == 0x00 &&
		 buf[2] == 0x81 && buf[3] == 0xb7)
		ictx->kc = ictx->last_keycode;

1573
	/* mce-specific button handling, no keyup events */
J
Jarod Wilson 已提交
1574
	else if (ktype == IMON_KEY_MCE) {
1575 1576
		ictx->rc_toggle = buf[2];
		press_type = 1;
J
Jarod Wilson 已提交
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589

	/* incoherent or irrelevant data */
	} else if (ictx->kc == KEY_RESERVED)
		press_type = -EINVAL;

	/* key release of 0xXXXXXXb7 key */
	else if (ictx->release_code)
		press_type = 0;

	/* this is a button press */
	else
		press_type = 1;

1590 1591
	spin_unlock_irqrestore(&ictx->kc_lock, flags);

J
Jarod Wilson 已提交
1592 1593 1594 1595 1596 1597
	return press_type;
}

/**
 * Process the incoming packet
 */
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
/**
 * Convert bit count to time duration (in us) and submit
 * the value to lirc_dev.
 */
static void submit_data(struct imon_context *context)
{
	DEFINE_IR_RAW_EVENT(ev);

	ev.pulse = context->rx.prev_bit;
	ev.duration = US_TO_NS(context->rx.count * BIT_DURATION);
	ir_raw_event_store_with_filter(context->rdev, &ev);
}

/**
 * Process the incoming packet
 */
static void imon_incoming_ir_raw(struct imon_context *context,
J
Jarod Wilson 已提交
1615
				 struct urb *urb, int intf)
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
{
	int len = urb->actual_length;
	unsigned char *buf = urb->transfer_buffer;
	struct device *dev = context->dev;
	int octet, bit;
	unsigned char mask;

	if (len != 8) {
		dev_warn(dev, "imon %s: invalid incoming packet size (len = %d, intf%d)\n",
			 __func__, len, intf);
		return;
	}

	if (debug)
		dev_info(dev, "raw packet: %*ph\n", len, buf);
	/*
	 * Translate received data to pulse and space lengths.
	 * Received data is active low, i.e. pulses are 0 and
	 * spaces are 1.
	 *
	 * My original algorithm was essentially similar to
	 * Changwoo Ryu's with the exception that he switched
	 * the incoming bits to active high and also fed an
	 * initial space to LIRC at the start of a new sequence
	 * if the previous bit was a pulse.
	 *
	 * I've decided to adopt his algorithm.
	 */

	if (buf[7] == 1 && context->rx.initial_space) {
		/* LIRC requires a leading space */
		context->rx.prev_bit = 0;
		context->rx.count = 4;
		submit_data(context);
		context->rx.count = 0;
	}

	for (octet = 0; octet < 5; ++octet) {
		mask = 0x80;
		for (bit = 0; bit < 8; ++bit) {
			int curr_bit = !(buf[octet] & mask);

			if (curr_bit != context->rx.prev_bit) {
				if (context->rx.count) {
					submit_data(context);
					context->rx.count = 0;
				}
				context->rx.prev_bit = curr_bit;
			}
			++context->rx.count;
			mask >>= 1;
		}
	}

	if (buf[7] == 10) {
		if (context->rx.count) {
			submit_data(context);
			context->rx.count = 0;
		}
		context->rx.initial_space = context->rx.prev_bit;
	}

	ir_raw_event_handle(context->rdev);
}

static void imon_incoming_scancode(struct imon_context *ictx,
				   struct urb *urb, int intf)
J
Jarod Wilson 已提交
1683 1684 1685 1686
{
	int len = urb->actual_length;
	unsigned char *buf = urb->transfer_buffer;
	struct device *dev = ictx->dev;
1687
	unsigned long flags;
J
Jarod Wilson 已提交
1688
	u32 kc;
1689
	u64 scancode;
J
Jarod Wilson 已提交
1690 1691 1692 1693
	int press_type = 0;
	int msec;
	struct timeval t;
	static struct timeval prev_time = { 0, 0 };
1694
	u8 ktype;
J
Jarod Wilson 已提交
1695 1696

	/* filter out junk data on the older 0xffdc imon devices */
1697
	if ((buf[0] == 0xff) && (buf[1] == 0xff) && (buf[2] == 0xff))
J
Jarod Wilson 已提交
1698 1699 1700 1701
		return;

	/* Figure out what key was pressed */
	if (len == 8 && buf[7] == 0xee) {
H
Hans Verkuil 已提交
1702
		scancode = be64_to_cpu(*((__be64 *)buf));
J
Jarod Wilson 已提交
1703
		ktype = IMON_KEY_PANEL;
1704
		kc = imon_panel_key_lookup(ictx, scancode);
1705
		ictx->release_code = false;
J
Jarod Wilson 已提交
1706
	} else {
H
Hans Verkuil 已提交
1707
		scancode = be32_to_cpu(*((__be32 *)buf));
1708
		if (ictx->rc_proto == RC_PROTO_BIT_RC6_MCE) {
1709
			ktype = IMON_KEY_IMON;
J
Jarod Wilson 已提交
1710 1711
			if (buf[0] == 0x80)
				ktype = IMON_KEY_MCE;
1712 1713 1714 1715 1716
			kc = imon_mce_key_lookup(ictx, scancode);
		} else {
			ktype = IMON_KEY_IMON;
			kc = imon_remote_key_lookup(ictx, scancode);
		}
J
Jarod Wilson 已提交
1717 1718
	}

1719
	spin_lock_irqsave(&ictx->kc_lock, flags);
J
Jarod Wilson 已提交
1720 1721 1722 1723
	/* keyboard/mouse mode toggle button */
	if (kc == KEY_KEYBOARD && !ictx->release_code) {
		ictx->last_keycode = kc;
		if (!nomouse) {
1724
			ictx->pad_mouse = !ictx->pad_mouse;
J
Jarod Wilson 已提交
1725 1726
			dev_dbg(dev, "toggling to %s mode\n",
				ictx->pad_mouse ? "mouse" : "keyboard");
1727
			spin_unlock_irqrestore(&ictx->kc_lock, flags);
J
Jarod Wilson 已提交
1728 1729
			return;
		} else {
1730
			ictx->pad_mouse = false;
J
Jarod Wilson 已提交
1731 1732 1733 1734 1735
			dev_dbg(dev, "mouse mode disabled, passing key value\n");
		}
	}

	ictx->kc = kc;
1736
	spin_unlock_irqrestore(&ictx->kc_lock, flags);
J
Jarod Wilson 已提交
1737 1738 1739 1740 1741

	/* send touchscreen events through input subsystem if touchpad data */
	if (ictx->display_type == IMON_DISPLAY_TYPE_VGA && len == 8 &&
	    buf[7] == 0x86) {
		imon_touch_event(ictx, buf);
1742
		return;
J
Jarod Wilson 已提交
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758

	/* look for mouse events with pad in mouse mode */
	} else if (ictx->pad_mouse) {
		if (imon_mouse_event(ictx, buf, len))
			return;
	}

	/* Now for some special handling to convert pad input to arrow keys */
	if (((len == 5) && (buf[0] == 0x01) && (buf[4] == 0x00)) ||
	    ((len == 8) && (buf[0] & 0x40) &&
	     !(buf[1] & 0x1 || buf[1] >> 2 & 0x1))) {
		len = 8;
		imon_pad_to_keys(ictx, buf);
	}

	if (debug) {
1759 1760
		printk(KERN_INFO "intf%d decoded packet: %*ph\n",
		       intf, len, buf);
J
Jarod Wilson 已提交
1761 1762 1763 1764 1765 1766
	}

	press_type = imon_parse_press_type(ictx, buf, ktype);
	if (press_type < 0)
		goto not_input_data;

1767 1768
	if (ktype != IMON_KEY_PANEL) {
		if (press_type == 0)
1769
			rc_keyup(ictx->rdev);
1770
		else {
1771 1772
			if (ictx->rc_proto == RC_PROTO_BIT_RC6_MCE ||
			    ictx->rc_proto == RC_PROTO_BIT_OTHER)
1773
				rc_keydown(ictx->rdev,
1774
					   ictx->rc_proto == RC_PROTO_BIT_RC6_MCE ? RC_PROTO_RC6_MCE : RC_PROTO_OTHER,
1775
					   ictx->rc_scancode, ictx->rc_toggle);
1776
			spin_lock_irqsave(&ictx->kc_lock, flags);
1777
			ictx->last_keycode = ictx->kc;
1778
			spin_unlock_irqrestore(&ictx->kc_lock, flags);
1779 1780 1781
		}
		return;
	}
J
Jarod Wilson 已提交
1782

1783
	/* Only panel type events left to process now */
1784 1785
	spin_lock_irqsave(&ictx->kc_lock, flags);

1786
	do_gettimeofday(&t);
1787 1788
	/* KEY_MUTE repeats from knob need to be suppressed */
	if (ictx->kc == KEY_MUTE && ictx->kc == ictx->last_keycode) {
J
Jarod Wilson 已提交
1789
		msec = tv2int(&t, &prev_time);
1790
		if (msec < ictx->idev->rep[REP_DELAY]) {
1791
			spin_unlock_irqrestore(&ictx->kc_lock, flags);
J
Jarod Wilson 已提交
1792
			return;
1793
		}
J
Jarod Wilson 已提交
1794
	}
1795
	prev_time = t;
1796
	kc = ictx->kc;
J
Jarod Wilson 已提交
1797

1798
	spin_unlock_irqrestore(&ictx->kc_lock, flags);
J
Jarod Wilson 已提交
1799

1800 1801
	input_report_key(ictx->idev, kc, press_type);
	input_sync(ictx->idev);
J
Jarod Wilson 已提交
1802

1803
	/* panel keys don't generate a release */
1804 1805
	input_report_key(ictx->idev, kc, 0);
	input_sync(ictx->idev);
J
Jarod Wilson 已提交
1806

1807
	spin_lock_irqsave(&ictx->kc_lock, flags);
1808
	ictx->last_keycode = kc;
1809
	spin_unlock_irqrestore(&ictx->kc_lock, flags);
J
Jarod Wilson 已提交
1810 1811 1812 1813 1814

	return;

not_input_data:
	if (len != 8) {
1815 1816
		dev_warn(dev, "imon %s: invalid incoming packet size (len = %d, intf%d)\n",
			 __func__, len, intf);
J
Jarod Wilson 已提交
1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
		return;
	}

	/* iMON 2.4G associate frame */
	if (buf[0] == 0x00 &&
	    buf[2] == 0xFF &&				/* REFID */
	    buf[3] == 0xFF &&
	    buf[4] == 0xFF &&
	    buf[5] == 0xFF &&				/* iMON 2.4G */
	   ((buf[6] == 0x4E && buf[7] == 0xDF) ||	/* LT */
	    (buf[6] == 0x5E && buf[7] == 0xDF))) {	/* DT */
		dev_warn(dev, "%s: remote associated refid=%02X\n",
			 __func__, buf[1]);
1830
		ictx->rf_isassociating = false;
J
Jarod Wilson 已提交
1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845
	}
}

/**
 * Callback function for USB core API: receive data
 */
static void usb_rx_callback_intf0(struct urb *urb)
{
	struct imon_context *ictx;
	int intfnum = 0;

	if (!urb)
		return;

	ictx = (struct imon_context *)urb->context;
1846
	if (!ictx)
J
Jarod Wilson 已提交
1847 1848
		return;

1849 1850 1851 1852 1853 1854 1855 1856
	/*
	 * if we get a callback before we're done configuring the hardware, we
	 * can't yet process the data, as there's nowhere to send it, but we
	 * still need to submit a new rx URB to avoid wedging the hardware
	 */
	if (!ictx->dev_present_intf0)
		goto out;

J
Jarod Wilson 已提交
1857 1858 1859 1860 1861 1862 1863 1864
	switch (urb->status) {
	case -ENOENT:		/* usbcore unlink successful! */
		return;

	case -ESHUTDOWN:	/* transport endpoint was shut down */
		break;

	case 0:
1865 1866 1867 1868
		if (ictx->rdev->driver_type == RC_DRIVER_IR_RAW)
			imon_incoming_ir_raw(ictx, urb, intfnum);
		else
			imon_incoming_scancode(ictx, urb, intfnum);
J
Jarod Wilson 已提交
1869 1870 1871 1872 1873 1874 1875 1876
		break;

	default:
		dev_warn(ictx->dev, "imon %s: status(%d): ignored\n",
			 __func__, urb->status);
		break;
	}

1877
out:
J
Jarod Wilson 已提交
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889
	usb_submit_urb(ictx->rx_urb_intf0, GFP_ATOMIC);
}

static void usb_rx_callback_intf1(struct urb *urb)
{
	struct imon_context *ictx;
	int intfnum = 1;

	if (!urb)
		return;

	ictx = (struct imon_context *)urb->context;
1890
	if (!ictx)
J
Jarod Wilson 已提交
1891 1892
		return;

1893 1894 1895 1896 1897 1898 1899 1900
	/*
	 * if we get a callback before we're done configuring the hardware, we
	 * can't yet process the data, as there's nowhere to send it, but we
	 * still need to submit a new rx URB to avoid wedging the hardware
	 */
	if (!ictx->dev_present_intf1)
		goto out;

J
Jarod Wilson 已提交
1901 1902 1903 1904 1905 1906 1907 1908
	switch (urb->status) {
	case -ENOENT:		/* usbcore unlink successful! */
		return;

	case -ESHUTDOWN:	/* transport endpoint was shut down */
		break;

	case 0:
1909 1910 1911 1912
		if (ictx->rdev->driver_type == RC_DRIVER_IR_RAW)
			imon_incoming_ir_raw(ictx, urb, intfnum);
		else
			imon_incoming_scancode(ictx, urb, intfnum);
J
Jarod Wilson 已提交
1913 1914 1915 1916 1917 1918 1919 1920
		break;

	default:
		dev_warn(ictx->dev, "imon %s: status(%d): ignored\n",
			 __func__, urb->status);
		break;
	}

1921
out:
J
Jarod Wilson 已提交
1922 1923 1924
	usb_submit_urb(ictx->rx_urb_intf1, GFP_ATOMIC);
}

1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
/*
 * The 0x15c2:0xffdc device ID was used for umpteen different imon
 * devices, and all of them constantly spew interrupts, even when there
 * is no actual data to report. However, byte 6 of this buffer looks like
 * its unique across device variants, so we're trying to key off that to
 * figure out which display type (if any) and what IR protocol the device
 * actually supports. These devices have their IR protocol hard-coded into
 * their firmware, they can't be changed on the fly like the newer hardware.
 */
static void imon_get_ffdc_type(struct imon_context *ictx)
{
	u8 ffdc_cfg_byte = ictx->usb_rx_buf[6];
	u8 detected_display_type = IMON_DISPLAY_TYPE_NONE;
1938
	u64 allowed_protos = RC_PROTO_BIT_OTHER;
1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963

	switch (ffdc_cfg_byte) {
	/* iMON Knob, no display, iMON IR + vol knob */
	case 0x21:
		dev_info(ictx->dev, "0xffdc iMON Knob, iMON IR");
		ictx->display_supported = false;
		break;
	/* iMON 2.4G LT (usb stick), no display, iMON RF */
	case 0x4e:
		dev_info(ictx->dev, "0xffdc iMON 2.4G LT, iMON RF");
		ictx->display_supported = false;
		ictx->rf_device = true;
		break;
	/* iMON VFD, no IR (does have vol knob tho) */
	case 0x35:
		dev_info(ictx->dev, "0xffdc iMON VFD + knob, no IR");
		detected_display_type = IMON_DISPLAY_TYPE_VFD;
		break;
	/* iMON VFD, iMON IR */
	case 0x24:
	case 0x85:
		dev_info(ictx->dev, "0xffdc iMON VFD, iMON IR");
		detected_display_type = IMON_DISPLAY_TYPE_VFD;
		break;
	/* iMON VFD, MCE IR */
1964
	case 0x46:
1965
	case 0x7e:
1966 1967 1968
	case 0x9e:
		dev_info(ictx->dev, "0xffdc iMON VFD, MCE IR");
		detected_display_type = IMON_DISPLAY_TYPE_VFD;
1969
		allowed_protos = RC_PROTO_BIT_RC6_MCE;
1970 1971 1972 1973 1974
		break;
	/* iMON LCD, MCE IR */
	case 0x9f:
		dev_info(ictx->dev, "0xffdc iMON LCD, MCE IR");
		detected_display_type = IMON_DISPLAY_TYPE_LCD;
1975
		allowed_protos = RC_PROTO_BIT_RC6_MCE;
1976 1977
		break;
	default:
1978
		dev_info(ictx->dev, "Unknown 0xffdc device, defaulting to VFD and iMON IR");
1979
		detected_display_type = IMON_DISPLAY_TYPE_VFD;
1980 1981
		/* We don't know which one it is, allow user to set the
		 * RC6 one from userspace if OTHER wasn't correct. */
1982
		allowed_protos |= RC_PROTO_BIT_RC6_MCE;
1983 1984 1985 1986 1987 1988
		break;
	}

	printk(KERN_CONT " (id 0x%02x)\n", ffdc_cfg_byte);

	ictx->display_type = detected_display_type;
1989
	ictx->rc_proto = allowed_protos;
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019
}

static void imon_set_display_type(struct imon_context *ictx)
{
	u8 configured_display_type = IMON_DISPLAY_TYPE_VFD;

	/*
	 * Try to auto-detect the type of display if the user hasn't set
	 * it by hand via the display_type modparam. Default is VFD.
	 */

	if (display_type == IMON_DISPLAY_TYPE_AUTO) {
		switch (ictx->product) {
		case 0xffdc:
			/* set in imon_get_ffdc_type() */
			configured_display_type = ictx->display_type;
			break;
		case 0x0034:
		case 0x0035:
			configured_display_type = IMON_DISPLAY_TYPE_VGA;
			break;
		case 0x0038:
		case 0x0039:
		case 0x0045:
			configured_display_type = IMON_DISPLAY_TYPE_LCD;
			break;
		case 0x003c:
		case 0x0041:
		case 0x0042:
		case 0x0043:
2020 2021
		case 0x8001:
		case 0xff30:
2022 2023 2024 2025 2026
			configured_display_type = IMON_DISPLAY_TYPE_NONE;
			ictx->display_supported = false;
			break;
		case 0x0036:
		case 0x0044:
2027
		case 0xffda:
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
		default:
			configured_display_type = IMON_DISPLAY_TYPE_VFD;
			break;
		}
	} else {
		configured_display_type = display_type;
		if (display_type == IMON_DISPLAY_TYPE_NONE)
			ictx->display_supported = false;
		else
			ictx->display_supported = true;
2038 2039
		dev_info(ictx->dev, "%s: overriding display type to %d via modparam\n",
			 __func__, display_type);
2040 2041 2042 2043 2044
	}

	ictx->display_type = configured_display_type;
}

2045
static struct rc_dev *imon_init_rdev(struct imon_context *ictx)
2046
{
2047
	struct rc_dev *rdev;
2048
	int ret;
2049 2050
	static const unsigned char fp_packet[] = {
		0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x88 };
2051

2052 2053
	rdev = rc_allocate_device(ictx->dev_descr->flags & IMON_IR_RAW ?
				  RC_DRIVER_IR_RAW : RC_DRIVER_SCANCODE);
2054
	if (!rdev) {
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064
		dev_err(ictx->dev, "remote control dev allocation failed\n");
		goto out;
	}

	snprintf(ictx->name_rdev, sizeof(ictx->name_rdev),
		 "iMON Remote (%04x:%04x)", ictx->vendor, ictx->product);
	usb_make_path(ictx->usbdev_intf0, ictx->phys_rdev,
		      sizeof(ictx->phys_rdev));
	strlcat(ictx->phys_rdev, "/input0", sizeof(ictx->phys_rdev));

2065
	rdev->device_name = ictx->name_rdev;
2066 2067
	rdev->input_phys = ictx->phys_rdev;
	usb_to_input_id(ictx->usbdev_intf0, &rdev->input_id);
2068 2069
	rdev->dev.parent = ictx->dev;

2070
	rdev->priv = ictx;
2071
	if (ictx->dev_descr->flags & IMON_IR_RAW)
2072
		rdev->allowed_protocols = RC_PROTO_BIT_ALL_IR_DECODER;
2073 2074
	else
		/* iMON PAD or MCE */
2075 2076
		rdev->allowed_protocols = RC_PROTO_BIT_OTHER |
					  RC_PROTO_BIT_RC6_MCE;
2077 2078
	rdev->change_protocol = imon_ir_change_protocol;
	rdev->driver_name = MOD_NAME;
2079

2080 2081 2082 2083 2084 2085 2086
	/* Enable front-panel buttons and/or knobs */
	memcpy(ictx->usb_tx_buf, &fp_packet, sizeof(fp_packet));
	ret = send_packet(ictx);
	/* Not fatal, but warn about it */
	if (ret)
		dev_info(ictx->dev, "panel buttons/knobs setup failed\n");

2087
	if (ictx->product == 0xffdc) {
2088
		imon_get_ffdc_type(ictx);
2089
		rdev->allowed_protocols = ictx->rc_proto;
2090
	}
2091 2092 2093

	imon_set_display_type(ictx);

2094
	if (ictx->rc_proto == RC_PROTO_BIT_RC6_MCE ||
2095
	    ictx->dev_descr->flags & IMON_IR_RAW)
2096 2097 2098 2099
		rdev->map_name = RC_MAP_IMON_MCE;
	else
		rdev->map_name = RC_MAP_IMON_PAD;

2100
	ret = rc_register_device(rdev);
2101 2102 2103 2104 2105 2106 2107 2108
	if (ret < 0) {
		dev_err(ictx->dev, "remote input dev register failed\n");
		goto out;
	}

	return rdev;

out:
2109
	rc_free_device(rdev);
2110 2111 2112
	return NULL;
}

J
Jarod Wilson 已提交
2113 2114
static struct input_dev *imon_init_idev(struct imon_context *ictx)
{
2115
	struct imon_panel_key_table *key_table = ictx->dev_descr->key_table;
J
Jarod Wilson 已提交
2116 2117 2118 2119
	struct input_dev *idev;
	int ret, i;

	idev = input_allocate_device();
2120
	if (!idev)
2121
		goto out;
J
Jarod Wilson 已提交
2122 2123

	snprintf(ictx->name_idev, sizeof(ictx->name_idev),
2124 2125
		 "iMON Panel, Knob and Mouse(%04x:%04x)",
		 ictx->vendor, ictx->product);
J
Jarod Wilson 已提交
2126 2127 2128 2129
	idev->name = ictx->name_idev;

	usb_make_path(ictx->usbdev_intf0, ictx->phys_idev,
		      sizeof(ictx->phys_idev));
2130
	strlcat(ictx->phys_idev, "/input1", sizeof(ictx->phys_idev));
J
Jarod Wilson 已提交
2131 2132
	idev->phys = ictx->phys_idev;

2133
	idev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP) | BIT_MASK(EV_REL);
J
Jarod Wilson 已提交
2134 2135 2136 2137 2138 2139 2140

	idev->keybit[BIT_WORD(BTN_MOUSE)] =
		BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_RIGHT);
	idev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y) |
		BIT_MASK(REL_WHEEL);

	/* panel and/or knob code support */
2141 2142
	for (i = 0; key_table[i].hw_code != 0; i++) {
		u32 kc = key_table[i].keycode;
J
Jarod Wilson 已提交
2143 2144 2145 2146 2147
		__set_bit(kc, idev->keybit);
	}

	usb_to_input_id(ictx->usbdev_intf0, &idev->id);
	idev->dev.parent = ictx->dev;
2148
	input_set_drvdata(idev, ictx);
J
Jarod Wilson 已提交
2149

2150
	ret = input_register_device(idev);
J
Jarod Wilson 已提交
2151
	if (ret < 0) {
2152 2153
		dev_err(ictx->dev, "input dev register failed\n");
		goto out;
J
Jarod Wilson 已提交
2154 2155 2156 2157
	}

	return idev;

2158
out:
J
Jarod Wilson 已提交
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
	input_free_device(idev);
	return NULL;
}

static struct input_dev *imon_init_touch(struct imon_context *ictx)
{
	struct input_dev *touch;
	int ret;

	touch = input_allocate_device();
2169
	if (!touch)
J
Jarod Wilson 已提交
2170 2171 2172 2173 2174 2175 2176 2177 2178
		goto touch_alloc_failed;

	snprintf(ictx->name_touch, sizeof(ictx->name_touch),
		 "iMON USB Touchscreen (%04x:%04x)",
		 ictx->vendor, ictx->product);
	touch->name = ictx->name_touch;

	usb_make_path(ictx->usbdev_intf1, ictx->phys_touch,
		      sizeof(ictx->phys_touch));
2179
	strlcat(ictx->phys_touch, "/input2", sizeof(ictx->phys_touch));
J
Jarod Wilson 已提交
2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203
	touch->phys = ictx->phys_touch;

	touch->evbit[0] =
		BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
	touch->keybit[BIT_WORD(BTN_TOUCH)] =
		BIT_MASK(BTN_TOUCH);
	input_set_abs_params(touch, ABS_X,
			     0x00, 0xfff, 0, 0);
	input_set_abs_params(touch, ABS_Y,
			     0x00, 0xfff, 0, 0);

	input_set_drvdata(touch, ictx);

	usb_to_input_id(ictx->usbdev_intf1, &touch->id);
	touch->dev.parent = ictx->dev;
	ret = input_register_device(touch);
	if (ret <  0) {
		dev_info(ictx->dev, "touchscreen input dev register failed\n");
		goto touch_register_failed;
	}

	return touch;

touch_register_failed:
2204
	input_free_device(touch);
J
Jarod Wilson 已提交
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218

touch_alloc_failed:
	return NULL;
}

static bool imon_find_endpoints(struct imon_context *ictx,
				struct usb_host_interface *iface_desc)
{
	struct usb_endpoint_descriptor *ep;
	struct usb_endpoint_descriptor *rx_endpoint = NULL;
	struct usb_endpoint_descriptor *tx_endpoint = NULL;
	int ifnum = iface_desc->desc.bInterfaceNumber;
	int num_endpts = iface_desc->desc.bNumEndpoints;
	int i, ep_dir, ep_type;
2219 2220 2221
	bool ir_ep_found = false;
	bool display_ep_found = false;
	bool tx_control = false;
J
Jarod Wilson 已提交
2222 2223 2224 2225 2226 2227 2228 2229 2230

	/*
	 * Scan the endpoint list and set:
	 *	first input endpoint = IR endpoint
	 *	first output endpoint = display endpoint
	 */
	for (i = 0; i < num_endpts && !(ir_ep_found && display_ep_found); ++i) {
		ep = &iface_desc->endpoint[i].desc;
		ep_dir = ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK;
2231
		ep_type = usb_endpoint_type(ep);
J
Jarod Wilson 已提交
2232 2233 2234 2235 2236

		if (!ir_ep_found && ep_dir == USB_DIR_IN &&
		    ep_type == USB_ENDPOINT_XFER_INT) {

			rx_endpoint = ep;
2237
			ir_ep_found = true;
J
Jarod Wilson 已提交
2238 2239 2240 2241 2242
			dev_dbg(ictx->dev, "%s: found IR endpoint\n", __func__);

		} else if (!display_ep_found && ep_dir == USB_DIR_OUT &&
			   ep_type == USB_ENDPOINT_XFER_INT) {
			tx_endpoint = ep;
2243
			display_ep_found = true;
J
Jarod Wilson 已提交
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
			dev_dbg(ictx->dev, "%s: found display endpoint\n", __func__);
		}
	}

	if (ifnum == 0) {
		ictx->rx_endpoint_intf0 = rx_endpoint;
		/*
		 * tx is used to send characters to lcd/vfd, associate RF
		 * remotes, set IR protocol, and maybe more...
		 */
		ictx->tx_endpoint = tx_endpoint;
	} else {
		ictx->rx_endpoint_intf1 = rx_endpoint;
	}

	/*
	 * If we didn't find a display endpoint, this is probably one of the
	 * newer iMON devices that use control urb instead of interrupt
	 */
	if (!display_ep_found) {
2264 2265
		tx_control = true;
		display_ep_found = true;
2266 2267
		dev_dbg(ictx->dev, "%s: device uses control endpoint, not interface OUT endpoint\n",
			__func__);
J
Jarod Wilson 已提交
2268 2269 2270 2271 2272 2273 2274 2275
	}

	/*
	 * Some iMON receivers have no display. Unfortunately, it seems
	 * that SoundGraph recycles device IDs between devices both with
	 * and without... :\
	 */
	if (ictx->display_type == IMON_DISPLAY_TYPE_NONE) {
2276
		display_ep_found = false;
J
Jarod Wilson 已提交
2277 2278 2279 2280 2281 2282 2283 2284
		dev_dbg(ictx->dev, "%s: device has no display\n", __func__);
	}

	/*
	 * iMON Touch devices have a VGA touchscreen, but no "display", as
	 * that refers to e.g. /dev/lcd0 (a character device LCD or VFD).
	 */
	if (ictx->display_type == IMON_DISPLAY_TYPE_VGA) {
2285
		display_ep_found = false;
J
Jarod Wilson 已提交
2286 2287 2288 2289 2290
		dev_dbg(ictx->dev, "%s: iMON Touch device found\n", __func__);
	}

	/* Input endpoint is mandatory */
	if (!ir_ep_found)
2291
		pr_err("no valid input (IR) endpoint found\n");
J
Jarod Wilson 已提交
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301

	ictx->tx_control = tx_control;

	if (display_ep_found)
		ictx->display_supported = true;

	return ir_ep_found;

}

2302 2303
static struct imon_context *imon_init_intf0(struct usb_interface *intf,
					    const struct usb_device_id *id)
J
Jarod Wilson 已提交
2304 2305 2306 2307 2308 2309
{
	struct imon_context *ictx;
	struct urb *rx_urb;
	struct urb *tx_urb;
	struct device *dev = &intf->dev;
	struct usb_host_interface *iface_desc;
2310
	int ret = -ENOMEM;
J
Jarod Wilson 已提交
2311

2312
	ictx = kzalloc(sizeof(*ictx), GFP_KERNEL);
2313
	if (!ictx)
J
Jarod Wilson 已提交
2314
		goto exit;
2315

J
Jarod Wilson 已提交
2316
	rx_urb = usb_alloc_urb(0, GFP_KERNEL);
2317
	if (!rx_urb)
J
Jarod Wilson 已提交
2318 2319
		goto rx_urb_alloc_failed;
	tx_urb = usb_alloc_urb(0, GFP_KERNEL);
2320
	if (!tx_urb)
J
Jarod Wilson 已提交
2321 2322 2323
		goto tx_urb_alloc_failed;

	mutex_init(&ictx->lock);
2324
	spin_lock_init(&ictx->kc_lock);
J
Jarod Wilson 已提交
2325 2326 2327 2328 2329 2330 2331

	mutex_lock(&ictx->lock);

	ictx->dev = dev;
	ictx->usbdev_intf0 = usb_get_dev(interface_to_usbdev(intf));
	ictx->rx_urb_intf0 = rx_urb;
	ictx->tx_urb = tx_urb;
2332
	ictx->rf_device = false;
J
Jarod Wilson 已提交
2333

2334 2335
	init_completion(&ictx->tx.finished);

J
Jarod Wilson 已提交
2336 2337 2338
	ictx->vendor  = le16_to_cpu(ictx->usbdev_intf0->descriptor.idVendor);
	ictx->product = le16_to_cpu(ictx->usbdev_intf0->descriptor.idProduct);

2339 2340
	/* save drive info for later accessing the panel/knob key table */
	ictx->dev_descr = (struct imon_usb_dev_descr *)id->driver_info;
2341
	/* default send_packet delay is 5ms but some devices need more */
2342 2343
	ictx->send_packet_delay = ictx->dev_descr->flags &
				  IMON_NEED_20MS_PKT_DELAY ? 20 : 5;
2344

2345
	ret = -ENODEV;
J
Jarod Wilson 已提交
2346
	iface_desc = intf->cur_altsetting;
2347
	if (!imon_find_endpoints(ictx, iface_desc)) {
J
Jarod Wilson 已提交
2348
		goto find_endpoint_failed;
2349
	}
J
Jarod Wilson 已提交
2350 2351 2352 2353 2354 2355 2356 2357 2358 2359

	usb_fill_int_urb(ictx->rx_urb_intf0, ictx->usbdev_intf0,
		usb_rcvintpipe(ictx->usbdev_intf0,
			ictx->rx_endpoint_intf0->bEndpointAddress),
		ictx->usb_rx_buf, sizeof(ictx->usb_rx_buf),
		usb_rx_callback_intf0, ictx,
		ictx->rx_endpoint_intf0->bInterval);

	ret = usb_submit_urb(ictx->rx_urb_intf0, GFP_KERNEL);
	if (ret) {
2360
		pr_err("usb_submit_urb failed for intf0 (%d)\n", ret);
J
Jarod Wilson 已提交
2361 2362 2363
		goto urb_submit_failed;
	}

2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375
	ictx->idev = imon_init_idev(ictx);
	if (!ictx->idev) {
		dev_err(dev, "%s: input device setup failed\n", __func__);
		goto idev_setup_failed;
	}

	ictx->rdev = imon_init_rdev(ictx);
	if (!ictx->rdev) {
		dev_err(dev, "%s: rc device setup failed\n", __func__);
		goto rdev_setup_failed;
	}

2376 2377
	ictx->dev_present_intf0 = true;

2378
	mutex_unlock(&ictx->lock);
J
Jarod Wilson 已提交
2379 2380
	return ictx;

2381 2382
rdev_setup_failed:
	input_unregister_device(ictx->idev);
J
Jarod Wilson 已提交
2383
idev_setup_failed:
2384 2385
	usb_kill_urb(ictx->rx_urb_intf0);
urb_submit_failed:
J
Jarod Wilson 已提交
2386
find_endpoint_failed:
2387
	usb_put_dev(ictx->usbdev_intf0);
J
Jarod Wilson 已提交
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
	mutex_unlock(&ictx->lock);
	usb_free_urb(tx_urb);
tx_urb_alloc_failed:
	usb_free_urb(rx_urb);
rx_urb_alloc_failed:
	kfree(ictx);
exit:
	dev_err(dev, "unable to initialize intf0, err %d\n", ret);

	return NULL;
}

static struct imon_context *imon_init_intf1(struct usb_interface *intf,
					    struct imon_context *ictx)
{
	struct urb *rx_urb;
	struct usb_host_interface *iface_desc;
2405
	int ret = -ENOMEM;
J
Jarod Wilson 已提交
2406 2407

	rx_urb = usb_alloc_urb(0, GFP_KERNEL);
2408
	if (!rx_urb)
J
Jarod Wilson 已提交
2409 2410 2411 2412 2413
		goto rx_urb_alloc_failed;

	mutex_lock(&ictx->lock);

	if (ictx->display_type == IMON_DISPLAY_TYPE_VGA) {
2414
		timer_setup(&ictx->ttimer, imon_touch_display_timeout, 0);
J
Jarod Wilson 已提交
2415 2416 2417 2418 2419
	}

	ictx->usbdev_intf1 = usb_get_dev(interface_to_usbdev(intf));
	ictx->rx_urb_intf1 = rx_urb;

2420
	ret = -ENODEV;
J
Jarod Wilson 已提交
2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441
	iface_desc = intf->cur_altsetting;
	if (!imon_find_endpoints(ictx, iface_desc))
		goto find_endpoint_failed;

	if (ictx->display_type == IMON_DISPLAY_TYPE_VGA) {
		ictx->touch = imon_init_touch(ictx);
		if (!ictx->touch)
			goto touch_setup_failed;
	} else
		ictx->touch = NULL;

	usb_fill_int_urb(ictx->rx_urb_intf1, ictx->usbdev_intf1,
		usb_rcvintpipe(ictx->usbdev_intf1,
			ictx->rx_endpoint_intf1->bEndpointAddress),
		ictx->usb_rx_buf, sizeof(ictx->usb_rx_buf),
		usb_rx_callback_intf1, ictx,
		ictx->rx_endpoint_intf1->bInterval);

	ret = usb_submit_urb(ictx->rx_urb_intf1, GFP_KERNEL);

	if (ret) {
2442
		pr_err("usb_submit_urb failed for intf1 (%d)\n", ret);
J
Jarod Wilson 已提交
2443 2444 2445
		goto urb_submit_failed;
	}

2446 2447
	ictx->dev_present_intf1 = true;

2448
	mutex_unlock(&ictx->lock);
J
Jarod Wilson 已提交
2449 2450 2451
	return ictx;

urb_submit_failed:
2452
	if (ictx->touch)
J
Jarod Wilson 已提交
2453 2454 2455
		input_unregister_device(ictx->touch);
touch_setup_failed:
find_endpoint_failed:
2456
	usb_put_dev(ictx->usbdev_intf1);
J
Jarod Wilson 已提交
2457 2458 2459
	mutex_unlock(&ictx->lock);
	usb_free_urb(rx_urb);
rx_urb_alloc_failed:
2460
	dev_err(ictx->dev, "unable to initialize intf1, err %d\n", ret);
J
Jarod Wilson 已提交
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472

	return NULL;
}

static void imon_init_display(struct imon_context *ictx,
			      struct usb_interface *intf)
{
	int ret;

	dev_dbg(ictx->dev, "Registering iMON display with sysfs\n");

	/* set up sysfs entry for built-in clock */
2473
	ret = sysfs_create_group(&intf->dev.kobj, &imon_display_attr_group);
J
Jarod Wilson 已提交
2474
	if (ret)
2475 2476
		dev_err(ictx->dev, "Could not create display sysfs entries(%d)",
			ret);
J
Jarod Wilson 已提交
2477 2478 2479 2480 2481 2482 2483

	if (ictx->display_type == IMON_DISPLAY_TYPE_LCD)
		ret = usb_register_dev(intf, &imon_lcd_class);
	else
		ret = usb_register_dev(intf, &imon_vfd_class);
	if (ret)
		/* Not a fatal error, so ignore */
2484
		dev_info(ictx->dev, "could not get a minor number for display\n");
J
Jarod Wilson 已提交
2485 2486 2487 2488 2489 2490

}

/**
 * Callback function for USB core API: Probe
 */
2491 2492
static int imon_probe(struct usb_interface *interface,
		      const struct usb_device_id *id)
J
Jarod Wilson 已提交
2493 2494 2495 2496 2497
{
	struct usb_device *usbdev = NULL;
	struct usb_host_interface *iface_desc = NULL;
	struct usb_interface *first_if;
	struct device *dev = &interface->dev;
2498
	int ifnum, sysfs_err;
J
Jarod Wilson 已提交
2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
	int ret = 0;
	struct imon_context *ictx = NULL;
	struct imon_context *first_if_ctx = NULL;
	u16 vendor, product;

	usbdev     = usb_get_dev(interface_to_usbdev(interface));
	iface_desc = interface->cur_altsetting;
	ifnum      = iface_desc->desc.bInterfaceNumber;
	vendor     = le16_to_cpu(usbdev->descriptor.idVendor);
	product    = le16_to_cpu(usbdev->descriptor.idProduct);

	dev_dbg(dev, "%s: found iMON device (%04x:%04x, intf%d)\n",
		__func__, vendor, product, ifnum);

	/* prevent races probing devices w/multiple interfaces */
	mutex_lock(&driver_lock);

	first_if = usb_ifnum_to_if(usbdev, 0);
2517 2518 2519 2520 2521
	if (!first_if) {
		ret = -ENODEV;
		goto fail;
	}

2522
	first_if_ctx = usb_get_intfdata(first_if);
J
Jarod Wilson 已提交
2523 2524

	if (ifnum == 0) {
2525
		ictx = imon_init_intf0(interface, id);
J
Jarod Wilson 已提交
2526
		if (!ictx) {
2527
			pr_err("failed to initialize context!\n");
J
Jarod Wilson 已提交
2528 2529 2530 2531 2532
			ret = -ENODEV;
			goto fail;
		}

	} else {
2533 2534 2535 2536 2537 2538 2539 2540
		/* this is the secondary interface on the device */

		/* fail early if first intf failed to register */
		if (!first_if_ctx) {
			ret = -ENODEV;
			goto fail;
		}

J
Jarod Wilson 已提交
2541 2542
		ictx = imon_init_intf1(interface, first_if_ctx);
		if (!ictx) {
2543
			pr_err("failed to attach to context!\n");
J
Jarod Wilson 已提交
2544 2545 2546 2547 2548 2549 2550 2551 2552
			ret = -ENODEV;
			goto fail;
		}

	}

	usb_set_intfdata(interface, ictx);

	if (ifnum == 0) {
2553 2554
		mutex_lock(&ictx->lock);

2555 2556
		if (product == 0xffdc && ictx->rf_device) {
			sysfs_err = sysfs_create_group(&interface->dev.kobj,
2557
						       &imon_rf_attr_group);
2558
			if (sysfs_err)
2559 2560
				pr_err("Could not create RF sysfs entries(%d)\n",
				       sysfs_err);
2561 2562
		}

J
Jarod Wilson 已提交
2563 2564
		if (ictx->display_supported)
			imon_init_display(ictx, interface);
2565 2566

		mutex_unlock(&ictx->lock);
J
Jarod Wilson 已提交
2567 2568
	}

2569 2570
	dev_info(dev, "iMON device (%04x:%04x, intf%d) on usb<%d:%d> initialized\n",
		 vendor, product, ifnum,
J
Jarod Wilson 已提交
2571 2572 2573
		 usbdev->bus->busnum, usbdev->devnum);

	mutex_unlock(&driver_lock);
2574
	usb_put_dev(usbdev);
J
Jarod Wilson 已提交
2575 2576 2577 2578 2579

	return 0;

fail:
	mutex_unlock(&driver_lock);
2580
	usb_put_dev(usbdev);
J
Jarod Wilson 已提交
2581 2582 2583 2584 2585 2586 2587 2588
	dev_err(dev, "unable to register, err %d\n", ret);

	return ret;
}

/**
 * Callback function for USB core API: disconnect
 */
2589
static void imon_disconnect(struct usb_interface *interface)
J
Jarod Wilson 已提交
2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605
{
	struct imon_context *ictx;
	struct device *dev;
	int ifnum;

	/* prevent races with multi-interface device probing and display_open */
	mutex_lock(&driver_lock);

	ictx = usb_get_intfdata(interface);
	dev = ictx->dev;
	ifnum = interface->cur_altsetting->desc.bInterfaceNumber;

	/*
	 * sysfs_remove_group is safe to call even if sysfs_create_group
	 * hasn't been called
	 */
2606 2607
	sysfs_remove_group(&interface->dev.kobj, &imon_display_attr_group);
	sysfs_remove_group(&interface->dev.kobj, &imon_rf_attr_group);
J
Jarod Wilson 已提交
2608 2609 2610 2611 2612 2613

	usb_set_intfdata(interface, NULL);

	/* Abort ongoing write */
	if (ictx->tx.busy) {
		usb_kill_urb(ictx->tx_urb);
2614
		complete(&ictx->tx.finished);
J
Jarod Wilson 已提交
2615 2616 2617
	}

	if (ifnum == 0) {
2618
		ictx->dev_present_intf0 = false;
J
Jarod Wilson 已提交
2619
		usb_kill_urb(ictx->rx_urb_intf0);
2620
		usb_put_dev(ictx->usbdev_intf0);
2621
		input_unregister_device(ictx->idev);
2622
		rc_unregister_device(ictx->rdev);
J
Jarod Wilson 已提交
2623 2624 2625
		if (ictx->display_supported) {
			if (ictx->display_type == IMON_DISPLAY_TYPE_LCD)
				usb_deregister_dev(interface, &imon_lcd_class);
2626
			else if (ictx->display_type == IMON_DISPLAY_TYPE_VFD)
J
Jarod Wilson 已提交
2627 2628 2629
				usb_deregister_dev(interface, &imon_vfd_class);
		}
	} else {
2630
		ictx->dev_present_intf1 = false;
J
Jarod Wilson 已提交
2631
		usb_kill_urb(ictx->rx_urb_intf1);
2632
		usb_put_dev(ictx->usbdev_intf1);
2633
		if (ictx->display_type == IMON_DISPLAY_TYPE_VGA) {
J
Jarod Wilson 已提交
2634
			input_unregister_device(ictx->touch);
2635 2636
			del_timer_sync(&ictx->ttimer);
		}
J
Jarod Wilson 已提交
2637 2638
	}

2639 2640
	if (!ictx->dev_present_intf0 && !ictx->dev_present_intf1)
		free_imon_context(ictx);
J
Jarod Wilson 已提交
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690

	mutex_unlock(&driver_lock);

	dev_dbg(dev, "%s: iMON device (intf%d) disconnected\n",
		__func__, ifnum);
}

static int imon_suspend(struct usb_interface *intf, pm_message_t message)
{
	struct imon_context *ictx = usb_get_intfdata(intf);
	int ifnum = intf->cur_altsetting->desc.bInterfaceNumber;

	if (ifnum == 0)
		usb_kill_urb(ictx->rx_urb_intf0);
	else
		usb_kill_urb(ictx->rx_urb_intf1);

	return 0;
}

static int imon_resume(struct usb_interface *intf)
{
	int rc = 0;
	struct imon_context *ictx = usb_get_intfdata(intf);
	int ifnum = intf->cur_altsetting->desc.bInterfaceNumber;

	if (ifnum == 0) {
		usb_fill_int_urb(ictx->rx_urb_intf0, ictx->usbdev_intf0,
			usb_rcvintpipe(ictx->usbdev_intf0,
				ictx->rx_endpoint_intf0->bEndpointAddress),
			ictx->usb_rx_buf, sizeof(ictx->usb_rx_buf),
			usb_rx_callback_intf0, ictx,
			ictx->rx_endpoint_intf0->bInterval);

		rc = usb_submit_urb(ictx->rx_urb_intf0, GFP_ATOMIC);

	} else {
		usb_fill_int_urb(ictx->rx_urb_intf1, ictx->usbdev_intf1,
			usb_rcvintpipe(ictx->usbdev_intf1,
				ictx->rx_endpoint_intf1->bEndpointAddress),
			ictx->usb_rx_buf, sizeof(ictx->usb_rx_buf),
			usb_rx_callback_intf1, ictx,
			ictx->rx_endpoint_intf1->bInterval);

		rc = usb_submit_urb(ictx->rx_urb_intf1, GFP_ATOMIC);
	}

	return rc;
}

2691
module_usb_driver(imon_driver);