xref: /openbmc/linux/drivers/media/rc/mceusb.c (revision ca481398)
1 /*
2  * Driver for USB Windows Media Center Ed. eHome Infrared Transceivers
3  *
4  * Copyright (c) 2010-2011, Jarod Wilson <jarod@redhat.com>
5  *
6  * Based on the original lirc_mceusb and lirc_mceusb2 drivers, by Dan
7  * Conti, Martin Blatter and Daniel Melander, the latter of which was
8  * in turn also based on the lirc_atiusb driver by Paul Miller. The
9  * two mce drivers were merged into one by Jarod Wilson, with transmit
10  * support for the 1st-gen device added primarily by Patrick Calhoun,
11  * with a bit of tweaks by Jarod. Debugging improvements and proper
12  * support for what appears to be 3rd-gen hardware added by Jarod.
13  * Initial port from lirc driver to ir-core drivery by Jarod, based
14  * partially on a port to an earlier proposed IR infrastructure by
15  * Jon Smirl, which included enhancements and simplifications to the
16  * incoming IR buffer parsing routines.
17  *
18  * Updated in July of 2011 with the aid of Microsoft's official
19  * remote/transceiver requirements and specification document, found at
20  * download.microsoft.com, title
21  * Windows-Media-Center-RC-IR-Collection-Green-Button-Specification-03-08-2011-V2.pdf
22  *
23  *
24  * This program is free software; you can redistribute it and/or modify
25  * it under the terms of the GNU General Public License as published by
26  * the Free Software Foundation; either version 2 of the License, or
27  * (at your option) any later version.
28  *
29  * This program is distributed in the hope that it will be useful,
30  * but WITHOUT ANY WARRANTY; without even the implied warranty of
31  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
32  * GNU General Public License for more details.
33  *
34  */
35 
36 #include <linux/device.h>
37 #include <linux/module.h>
38 #include <linux/slab.h>
39 #include <linux/workqueue.h>
40 #include <linux/usb.h>
41 #include <linux/usb/input.h>
42 #include <linux/pm_wakeup.h>
43 #include <media/rc-core.h>
44 
45 #define DRIVER_VERSION	"1.93"
46 #define DRIVER_AUTHOR	"Jarod Wilson <jarod@redhat.com>"
47 #define DRIVER_DESC	"Windows Media Center Ed. eHome Infrared Transceiver " \
48 			"device driver"
49 #define DRIVER_NAME	"mceusb"
50 
51 #define USB_CTRL_MSG_SZ		2  /* Size of usb ctrl msg on gen1 hw */
52 #define MCE_G1_INIT_MSGS	40 /* Init messages on gen1 hw to throw out */
53 
54 /* MCE constants */
55 #define MCE_CMDBUF_SIZE		384  /* MCE Command buffer length */
56 #define MCE_TIME_UNIT		50   /* Approx 50us resolution */
57 #define MCE_CODE_LENGTH		5    /* Normal length of packet (with header) */
58 #define MCE_PACKET_SIZE		4    /* Normal length of packet (without header) */
59 #define MCE_IRDATA_HEADER	0x84 /* Actual header format is 0x80 + num_bytes */
60 #define MCE_IRDATA_TRAILER	0x80 /* End of IR data */
61 #define MCE_MAX_CHANNELS	2    /* Two transmitters, hardware dependent? */
62 #define MCE_DEFAULT_TX_MASK	0x03 /* Vals: TX1=0x01, TX2=0x02, ALL=0x03 */
63 #define MCE_PULSE_BIT		0x80 /* Pulse bit, MSB set == PULSE else SPACE */
64 #define MCE_PULSE_MASK		0x7f /* Pulse mask */
65 #define MCE_MAX_PULSE_LENGTH	0x7f /* Longest transmittable pulse symbol */
66 
67 /*
68  * The interface between the host and the IR hardware is command-response
69  * based. All commands and responses have a consistent format, where a lead
70  * byte always identifies the type of data following it. The lead byte has
71  * a port value in the 3 highest bits and a length value in the 5 lowest
72  * bits.
73  *
74  * The length field is overloaded, with a value of 11111 indicating that the
75  * following byte is a command or response code, and the length of the entire
76  * message is determined by the code. If the length field is not 11111, then
77  * it specifies the number of bytes of port data that follow.
78  */
79 #define MCE_CMD			0x1f
80 #define MCE_PORT_IR		0x4	/* (0x4 << 5) | MCE_CMD = 0x9f */
81 #define MCE_PORT_SYS		0x7	/* (0x7 << 5) | MCE_CMD = 0xff */
82 #define MCE_PORT_SER		0x6	/* 0xc0 thru 0xdf flush & 0x1f bytes */
83 #define MCE_PORT_MASK		0xe0	/* Mask out command bits */
84 
85 /* Command port headers */
86 #define MCE_CMD_PORT_IR		0x9f	/* IR-related cmd/rsp */
87 #define MCE_CMD_PORT_SYS	0xff	/* System (non-IR) device cmd/rsp */
88 
89 /* Commands that set device state  (2-4 bytes in length) */
90 #define MCE_CMD_RESET		0xfe	/* Reset device, 2 bytes */
91 #define MCE_CMD_RESUME		0xaa	/* Resume device after error, 2 bytes */
92 #define MCE_CMD_SETIRCFS	0x06	/* Set tx carrier, 4 bytes */
93 #define MCE_CMD_SETIRTIMEOUT	0x0c	/* Set timeout, 4 bytes */
94 #define MCE_CMD_SETIRTXPORTS	0x08	/* Set tx ports, 3 bytes */
95 #define MCE_CMD_SETIRRXPORTEN	0x14	/* Set rx ports, 3 bytes */
96 #define MCE_CMD_FLASHLED	0x23	/* Flash receiver LED, 2 bytes */
97 
98 /* Commands that query device state (all 2 bytes, unless noted) */
99 #define MCE_CMD_GETIRCFS	0x07	/* Get carrier */
100 #define MCE_CMD_GETIRTIMEOUT	0x0d	/* Get timeout */
101 #define MCE_CMD_GETIRTXPORTS	0x13	/* Get tx ports */
102 #define MCE_CMD_GETIRRXPORTEN	0x15	/* Get rx ports */
103 #define MCE_CMD_GETPORTSTATUS	0x11	/* Get tx port status, 3 bytes */
104 #define MCE_CMD_GETIRNUMPORTS	0x16	/* Get number of ports */
105 #define MCE_CMD_GETWAKESOURCE	0x17	/* Get wake source */
106 #define MCE_CMD_GETEMVER	0x22	/* Get emulator interface version */
107 #define MCE_CMD_GETDEVDETAILS	0x21	/* Get device details (em ver2 only) */
108 #define MCE_CMD_GETWAKESUPPORT	0x20	/* Get wake details (em ver2 only) */
109 #define MCE_CMD_GETWAKEVERSION	0x18	/* Get wake pattern (em ver2 only) */
110 
111 /* Misc commands */
112 #define MCE_CMD_NOP		0xff	/* No operation */
113 
114 /* Responses to commands (non-error cases) */
115 #define MCE_RSP_EQIRCFS		0x06	/* tx carrier, 4 bytes */
116 #define MCE_RSP_EQIRTIMEOUT	0x0c	/* rx timeout, 4 bytes */
117 #define MCE_RSP_GETWAKESOURCE	0x17	/* wake source, 3 bytes */
118 #define MCE_RSP_EQIRTXPORTS	0x08	/* tx port mask, 3 bytes */
119 #define MCE_RSP_EQIRRXPORTEN	0x14	/* rx port mask, 3 bytes */
120 #define MCE_RSP_GETPORTSTATUS	0x11	/* tx port status, 7 bytes */
121 #define MCE_RSP_EQIRRXCFCNT	0x15	/* rx carrier count, 4 bytes */
122 #define MCE_RSP_EQIRNUMPORTS	0x16	/* number of ports, 4 bytes */
123 #define MCE_RSP_EQWAKESUPPORT	0x20	/* wake capabilities, 3 bytes */
124 #define MCE_RSP_EQWAKEVERSION	0x18	/* wake pattern details, 6 bytes */
125 #define MCE_RSP_EQDEVDETAILS	0x21	/* device capabilities, 3 bytes */
126 #define MCE_RSP_EQEMVER		0x22	/* emulator interface ver, 3 bytes */
127 #define MCE_RSP_FLASHLED	0x23	/* success flashing LED, 2 bytes */
128 
129 /* Responses to error cases, must send MCE_CMD_RESUME to clear them */
130 #define MCE_RSP_CMD_ILLEGAL	0xfe	/* illegal command for port, 2 bytes */
131 #define MCE_RSP_TX_TIMEOUT	0x81	/* tx timed out, 2 bytes */
132 
133 /* Misc commands/responses not defined in the MCE remote/transceiver spec */
134 #define MCE_CMD_SIG_END		0x01	/* End of signal */
135 #define MCE_CMD_PING		0x03	/* Ping device */
136 #define MCE_CMD_UNKNOWN		0x04	/* Unknown */
137 #define MCE_CMD_UNKNOWN2	0x05	/* Unknown */
138 #define MCE_CMD_UNKNOWN3	0x09	/* Unknown */
139 #define MCE_CMD_UNKNOWN4	0x0a	/* Unknown */
140 #define MCE_CMD_G_REVISION	0x0b	/* Get hw/sw revision */
141 #define MCE_CMD_UNKNOWN5	0x0e	/* Unknown */
142 #define MCE_CMD_UNKNOWN6	0x0f	/* Unknown */
143 #define MCE_CMD_UNKNOWN8	0x19	/* Unknown */
144 #define MCE_CMD_UNKNOWN9	0x1b	/* Unknown */
145 #define MCE_CMD_NULL		0x00	/* These show up various places... */
146 
147 /* if buf[i] & MCE_PORT_MASK == 0x80 and buf[i] != MCE_CMD_PORT_IR,
148  * then we're looking at a raw IR data sample */
149 #define MCE_COMMAND_IRDATA	0x80
150 #define MCE_PACKET_LENGTH_MASK	0x1f /* Packet length mask */
151 
152 #define VENDOR_PHILIPS		0x0471
153 #define VENDOR_SMK		0x0609
154 #define VENDOR_TATUNG		0x1460
155 #define VENDOR_GATEWAY		0x107b
156 #define VENDOR_SHUTTLE		0x1308
157 #define VENDOR_SHUTTLE2		0x051c
158 #define VENDOR_MITSUMI		0x03ee
159 #define VENDOR_TOPSEED		0x1784
160 #define VENDOR_RICAVISION	0x179d
161 #define VENDOR_ITRON		0x195d
162 #define VENDOR_FIC		0x1509
163 #define VENDOR_LG		0x043e
164 #define VENDOR_MICROSOFT	0x045e
165 #define VENDOR_FORMOSA		0x147a
166 #define VENDOR_FINTEK		0x1934
167 #define VENDOR_PINNACLE		0x2304
168 #define VENDOR_ECS		0x1019
169 #define VENDOR_WISTRON		0x0fb8
170 #define VENDOR_COMPRO		0x185b
171 #define VENDOR_NORTHSTAR	0x04eb
172 #define VENDOR_REALTEK		0x0bda
173 #define VENDOR_TIVO		0x105a
174 #define VENDOR_CONEXANT		0x0572
175 #define VENDOR_TWISTEDMELON	0x2596
176 #define VENDOR_HAUPPAUGE	0x2040
177 #define VENDOR_PCTV		0x2013
178 #define VENDOR_ADAPTEC		0x03f3
179 
180 enum mceusb_model_type {
181 	MCE_GEN2 = 0,		/* Most boards */
182 	MCE_GEN1,
183 	MCE_GEN3,
184 	MCE_GEN2_TX_INV,
185 	POLARIS_EVK,
186 	CX_HYBRID_TV,
187 	MULTIFUNCTION,
188 	TIVO_KIT,
189 	MCE_GEN2_NO_TX,
190 	HAUPPAUGE_CX_HYBRID_TV,
191 };
192 
193 struct mceusb_model {
194 	u32 mce_gen1:1;
195 	u32 mce_gen2:1;
196 	u32 mce_gen3:1;
197 	u32 tx_mask_normal:1;
198 	u32 no_tx:1;
199 
200 	int ir_intfnum;
201 
202 	const char *rc_map;	/* Allow specify a per-board map */
203 	const char *name;	/* per-board name */
204 };
205 
206 static const struct mceusb_model mceusb_model[] = {
207 	[MCE_GEN1] = {
208 		.mce_gen1 = 1,
209 		.tx_mask_normal = 1,
210 	},
211 	[MCE_GEN2] = {
212 		.mce_gen2 = 1,
213 	},
214 	[MCE_GEN2_NO_TX] = {
215 		.mce_gen2 = 1,
216 		.no_tx = 1,
217 	},
218 	[MCE_GEN2_TX_INV] = {
219 		.mce_gen2 = 1,
220 		.tx_mask_normal = 1,
221 	},
222 	[MCE_GEN3] = {
223 		.mce_gen3 = 1,
224 		.tx_mask_normal = 1,
225 	},
226 	[POLARIS_EVK] = {
227 		/*
228 		 * In fact, the EVK is shipped without
229 		 * remotes, but we should have something handy,
230 		 * to allow testing it
231 		 */
232 		.name = "Conexant Hybrid TV (cx231xx) MCE IR",
233 	},
234 	[CX_HYBRID_TV] = {
235 		.no_tx = 1, /* tx isn't wired up at all */
236 		.name = "Conexant Hybrid TV (cx231xx) MCE IR",
237 	},
238 	[HAUPPAUGE_CX_HYBRID_TV] = {
239 		.no_tx = 1, /* eeprom says it has no tx */
240 		.name = "Conexant Hybrid TV (cx231xx) MCE IR no TX",
241 	},
242 	[MULTIFUNCTION] = {
243 		.mce_gen2 = 1,
244 		.ir_intfnum = 2,
245 	},
246 	[TIVO_KIT] = {
247 		.mce_gen2 = 1,
248 		.rc_map = RC_MAP_TIVO,
249 	},
250 };
251 
252 static struct usb_device_id mceusb_dev_table[] = {
253 	/* Original Microsoft MCE IR Transceiver (often HP-branded) */
254 	{ USB_DEVICE(VENDOR_MICROSOFT, 0x006d),
255 	  .driver_info = MCE_GEN1 },
256 	/* Philips Infrared Transceiver - Sahara branded */
257 	{ USB_DEVICE(VENDOR_PHILIPS, 0x0608) },
258 	/* Philips Infrared Transceiver - HP branded */
259 	{ USB_DEVICE(VENDOR_PHILIPS, 0x060c),
260 	  .driver_info = MCE_GEN2_TX_INV },
261 	/* Philips SRM5100 */
262 	{ USB_DEVICE(VENDOR_PHILIPS, 0x060d) },
263 	/* Philips Infrared Transceiver - Omaura */
264 	{ USB_DEVICE(VENDOR_PHILIPS, 0x060f) },
265 	/* Philips Infrared Transceiver - Spinel plus */
266 	{ USB_DEVICE(VENDOR_PHILIPS, 0x0613) },
267 	/* Philips eHome Infrared Transceiver */
268 	{ USB_DEVICE(VENDOR_PHILIPS, 0x0815) },
269 	/* Philips/Spinel plus IR transceiver for ASUS */
270 	{ USB_DEVICE(VENDOR_PHILIPS, 0x206c) },
271 	/* Philips/Spinel plus IR transceiver for ASUS */
272 	{ USB_DEVICE(VENDOR_PHILIPS, 0x2088) },
273 	/* Philips IR transceiver (Dell branded) */
274 	{ USB_DEVICE(VENDOR_PHILIPS, 0x2093),
275 	  .driver_info = MCE_GEN2_TX_INV },
276 	/* Realtek MCE IR Receiver and card reader */
277 	{ USB_DEVICE(VENDOR_REALTEK, 0x0161),
278 	  .driver_info = MULTIFUNCTION },
279 	/* SMK/Toshiba G83C0004D410 */
280 	{ USB_DEVICE(VENDOR_SMK, 0x031d),
281 	  .driver_info = MCE_GEN2_TX_INV },
282 	/* SMK eHome Infrared Transceiver (Sony VAIO) */
283 	{ USB_DEVICE(VENDOR_SMK, 0x0322),
284 	  .driver_info = MCE_GEN2_TX_INV },
285 	/* bundled with Hauppauge PVR-150 */
286 	{ USB_DEVICE(VENDOR_SMK, 0x0334),
287 	  .driver_info = MCE_GEN2_TX_INV },
288 	/* SMK eHome Infrared Transceiver */
289 	{ USB_DEVICE(VENDOR_SMK, 0x0338) },
290 	/* SMK/I-O Data GV-MC7/RCKIT Receiver */
291 	{ USB_DEVICE(VENDOR_SMK, 0x0353),
292 	  .driver_info = MCE_GEN2_NO_TX },
293 	/* SMK RXX6000 Infrared Receiver */
294 	{ USB_DEVICE(VENDOR_SMK, 0x0357),
295 	  .driver_info = MCE_GEN2_NO_TX },
296 	/* Tatung eHome Infrared Transceiver */
297 	{ USB_DEVICE(VENDOR_TATUNG, 0x9150) },
298 	/* Shuttle eHome Infrared Transceiver */
299 	{ USB_DEVICE(VENDOR_SHUTTLE, 0xc001) },
300 	/* Shuttle eHome Infrared Transceiver */
301 	{ USB_DEVICE(VENDOR_SHUTTLE2, 0xc001) },
302 	/* Gateway eHome Infrared Transceiver */
303 	{ USB_DEVICE(VENDOR_GATEWAY, 0x3009) },
304 	/* Mitsumi */
305 	{ USB_DEVICE(VENDOR_MITSUMI, 0x2501) },
306 	/* Topseed eHome Infrared Transceiver */
307 	{ USB_DEVICE(VENDOR_TOPSEED, 0x0001),
308 	  .driver_info = MCE_GEN2_TX_INV },
309 	/* Topseed HP eHome Infrared Transceiver */
310 	{ USB_DEVICE(VENDOR_TOPSEED, 0x0006),
311 	  .driver_info = MCE_GEN2_TX_INV },
312 	/* Topseed eHome Infrared Transceiver */
313 	{ USB_DEVICE(VENDOR_TOPSEED, 0x0007),
314 	  .driver_info = MCE_GEN2_TX_INV },
315 	/* Topseed eHome Infrared Transceiver */
316 	{ USB_DEVICE(VENDOR_TOPSEED, 0x0008),
317 	  .driver_info = MCE_GEN3 },
318 	/* Topseed eHome Infrared Transceiver */
319 	{ USB_DEVICE(VENDOR_TOPSEED, 0x000a),
320 	  .driver_info = MCE_GEN2_TX_INV },
321 	/* Topseed eHome Infrared Transceiver */
322 	{ USB_DEVICE(VENDOR_TOPSEED, 0x0011),
323 	  .driver_info = MCE_GEN3 },
324 	/* Ricavision internal Infrared Transceiver */
325 	{ USB_DEVICE(VENDOR_RICAVISION, 0x0010) },
326 	/* Itron ione Libra Q-11 */
327 	{ USB_DEVICE(VENDOR_ITRON, 0x7002) },
328 	/* FIC eHome Infrared Transceiver */
329 	{ USB_DEVICE(VENDOR_FIC, 0x9242) },
330 	/* LG eHome Infrared Transceiver */
331 	{ USB_DEVICE(VENDOR_LG, 0x9803) },
332 	/* Microsoft MCE Infrared Transceiver */
333 	{ USB_DEVICE(VENDOR_MICROSOFT, 0x00a0) },
334 	/* Formosa eHome Infrared Transceiver */
335 	{ USB_DEVICE(VENDOR_FORMOSA, 0xe015) },
336 	/* Formosa21 / eHome Infrared Receiver */
337 	{ USB_DEVICE(VENDOR_FORMOSA, 0xe016) },
338 	/* Formosa aim / Trust MCE Infrared Receiver */
339 	{ USB_DEVICE(VENDOR_FORMOSA, 0xe017),
340 	  .driver_info = MCE_GEN2_NO_TX },
341 	/* Formosa Industrial Computing / Beanbag Emulation Device */
342 	{ USB_DEVICE(VENDOR_FORMOSA, 0xe018) },
343 	/* Formosa21 / eHome Infrared Receiver */
344 	{ USB_DEVICE(VENDOR_FORMOSA, 0xe03a) },
345 	/* Formosa Industrial Computing AIM IR605/A */
346 	{ USB_DEVICE(VENDOR_FORMOSA, 0xe03c) },
347 	/* Formosa Industrial Computing */
348 	{ USB_DEVICE(VENDOR_FORMOSA, 0xe03e) },
349 	/* Formosa Industrial Computing */
350 	{ USB_DEVICE(VENDOR_FORMOSA, 0xe042) },
351 	/* Fintek eHome Infrared Transceiver (HP branded) */
352 	{ USB_DEVICE(VENDOR_FINTEK, 0x5168),
353 	  .driver_info = MCE_GEN2_TX_INV },
354 	/* Fintek eHome Infrared Transceiver */
355 	{ USB_DEVICE(VENDOR_FINTEK, 0x0602) },
356 	/* Fintek eHome Infrared Transceiver (in the AOpen MP45) */
357 	{ USB_DEVICE(VENDOR_FINTEK, 0x0702) },
358 	/* Pinnacle Remote Kit */
359 	{ USB_DEVICE(VENDOR_PINNACLE, 0x0225),
360 	  .driver_info = MCE_GEN3 },
361 	/* Elitegroup Computer Systems IR */
362 	{ USB_DEVICE(VENDOR_ECS, 0x0f38) },
363 	/* Wistron Corp. eHome Infrared Receiver */
364 	{ USB_DEVICE(VENDOR_WISTRON, 0x0002) },
365 	/* Compro K100 */
366 	{ USB_DEVICE(VENDOR_COMPRO, 0x3020) },
367 	/* Compro K100 v2 */
368 	{ USB_DEVICE(VENDOR_COMPRO, 0x3082) },
369 	/* Northstar Systems, Inc. eHome Infrared Transceiver */
370 	{ USB_DEVICE(VENDOR_NORTHSTAR, 0xe004) },
371 	/* TiVo PC IR Receiver */
372 	{ USB_DEVICE(VENDOR_TIVO, 0x2000),
373 	  .driver_info = TIVO_KIT },
374 	/* Conexant Hybrid TV "Shelby" Polaris SDK */
375 	{ USB_DEVICE(VENDOR_CONEXANT, 0x58a1),
376 	  .driver_info = POLARIS_EVK },
377 	/* Conexant Hybrid TV RDU253S Polaris */
378 	{ USB_DEVICE(VENDOR_CONEXANT, 0x58a5),
379 	  .driver_info = CX_HYBRID_TV },
380 	/* Twisted Melon Inc. - Manta Mini Receiver */
381 	{ USB_DEVICE(VENDOR_TWISTEDMELON, 0x8008) },
382 	/* Twisted Melon Inc. - Manta Pico Receiver */
383 	{ USB_DEVICE(VENDOR_TWISTEDMELON, 0x8016) },
384 	/* Twisted Melon Inc. - Manta Transceiver */
385 	{ USB_DEVICE(VENDOR_TWISTEDMELON, 0x8042) },
386 	/* Hauppauge WINTV-HVR-HVR 930C-HD - based on cx231xx */
387 	{ USB_DEVICE(VENDOR_HAUPPAUGE, 0xb130),
388 	  .driver_info = HAUPPAUGE_CX_HYBRID_TV },
389 	{ USB_DEVICE(VENDOR_HAUPPAUGE, 0xb131),
390 	  .driver_info = HAUPPAUGE_CX_HYBRID_TV },
391 	{ USB_DEVICE(VENDOR_HAUPPAUGE, 0xb138),
392 	  .driver_info = HAUPPAUGE_CX_HYBRID_TV },
393 	{ USB_DEVICE(VENDOR_HAUPPAUGE, 0xb139),
394 	  .driver_info = HAUPPAUGE_CX_HYBRID_TV },
395 	{ USB_DEVICE(VENDOR_PCTV, 0x0259),
396 	  .driver_info = HAUPPAUGE_CX_HYBRID_TV },
397 	{ USB_DEVICE(VENDOR_PCTV, 0x025e),
398 	  .driver_info = HAUPPAUGE_CX_HYBRID_TV },
399 	/* Adaptec / HP eHome Receiver */
400 	{ USB_DEVICE(VENDOR_ADAPTEC, 0x0094) },
401 
402 	/* Terminating entry */
403 	{ }
404 };
405 
406 /* data structure for each usb transceiver */
407 struct mceusb_dev {
408 	/* ir-core bits */
409 	struct rc_dev *rc;
410 
411 	/* optional features we can enable */
412 	bool learning_enabled;
413 
414 	/* core device bits */
415 	struct device *dev;
416 
417 	/* usb */
418 	struct usb_device *usbdev;
419 	struct urb *urb_in;
420 	unsigned int pipe_in;
421 	struct usb_endpoint_descriptor *usb_ep_out;
422 	unsigned int pipe_out;
423 
424 	/* buffers and dma */
425 	unsigned char *buf_in;
426 	unsigned int len_in;
427 	dma_addr_t dma_in;
428 
429 	enum {
430 		CMD_HEADER = 0,
431 		SUBCMD,
432 		CMD_DATA,
433 		PARSE_IRDATA,
434 	} parser_state;
435 
436 	u8 cmd, rem;		/* Remaining IR data bytes in packet */
437 
438 	struct {
439 		u32 connected:1;
440 		u32 tx_mask_normal:1;
441 		u32 microsoft_gen1:1;
442 		u32 no_tx:1;
443 	} flags;
444 
445 	/* transmit support */
446 	u32 carrier;
447 	unsigned char tx_mask;
448 
449 	char name[128];
450 	char phys[64];
451 	enum mceusb_model_type model;
452 
453 	bool need_reset;	/* flag to issue a device resume cmd */
454 	u8 emver;		/* emulator interface version */
455 	u8 num_txports;		/* number of transmit ports */
456 	u8 num_rxports;		/* number of receive sensors */
457 	u8 txports_cabled;	/* bitmask of transmitters with cable */
458 	u8 rxports_active;	/* bitmask of active receive sensors */
459 
460 	/*
461 	 * support for async error handler mceusb_deferred_kevent()
462 	 * where usb_clear_halt(), usb_reset_configuration(),
463 	 * usb_reset_device(), etc. must be done in process context
464 	 */
465 	struct work_struct kevent;
466 	unsigned long kevent_flags;
467 #		define EVENT_TX_HALT	0
468 #		define EVENT_RX_HALT	1
469 };
470 
471 /* MCE Device Command Strings, generally a port and command pair */
472 static char DEVICE_RESUME[]	= {MCE_CMD_NULL, MCE_CMD_PORT_SYS,
473 				   MCE_CMD_RESUME};
474 static char GET_REVISION[]	= {MCE_CMD_PORT_SYS, MCE_CMD_G_REVISION};
475 static char GET_EMVER[]		= {MCE_CMD_PORT_SYS, MCE_CMD_GETEMVER};
476 static char GET_WAKEVERSION[]	= {MCE_CMD_PORT_SYS, MCE_CMD_GETWAKEVERSION};
477 static char FLASH_LED[]		= {MCE_CMD_PORT_SYS, MCE_CMD_FLASHLED};
478 static char GET_UNKNOWN2[]	= {MCE_CMD_PORT_IR, MCE_CMD_UNKNOWN2};
479 static char GET_CARRIER_FREQ[]	= {MCE_CMD_PORT_IR, MCE_CMD_GETIRCFS};
480 static char GET_RX_TIMEOUT[]	= {MCE_CMD_PORT_IR, MCE_CMD_GETIRTIMEOUT};
481 static char GET_NUM_PORTS[]	= {MCE_CMD_PORT_IR, MCE_CMD_GETIRNUMPORTS};
482 static char GET_TX_BITMASK[]	= {MCE_CMD_PORT_IR, MCE_CMD_GETIRTXPORTS};
483 static char GET_RX_SENSOR[]	= {MCE_CMD_PORT_IR, MCE_CMD_GETIRRXPORTEN};
484 /* sub in desired values in lower byte or bytes for full command */
485 /* FIXME: make use of these for transmit.
486 static char SET_CARRIER_FREQ[]	= {MCE_CMD_PORT_IR,
487 				   MCE_CMD_SETIRCFS, 0x00, 0x00};
488 static char SET_TX_BITMASK[]	= {MCE_CMD_PORT_IR, MCE_CMD_SETIRTXPORTS, 0x00};
489 static char SET_RX_TIMEOUT[]	= {MCE_CMD_PORT_IR,
490 				   MCE_CMD_SETIRTIMEOUT, 0x00, 0x00};
491 static char SET_RX_SENSOR[]	= {MCE_CMD_PORT_IR,
492 				   MCE_RSP_EQIRRXPORTEN, 0x00};
493 */
494 
495 static int mceusb_cmd_datasize(u8 cmd, u8 subcmd)
496 {
497 	int datasize = 0;
498 
499 	switch (cmd) {
500 	case MCE_CMD_NULL:
501 		if (subcmd == MCE_CMD_PORT_SYS)
502 			datasize = 1;
503 		break;
504 	case MCE_CMD_PORT_SYS:
505 		switch (subcmd) {
506 		case MCE_RSP_GETPORTSTATUS:
507 			datasize = 5;
508 			break;
509 		case MCE_RSP_EQWAKEVERSION:
510 			datasize = 4;
511 			break;
512 		case MCE_CMD_G_REVISION:
513 			datasize = 2;
514 			break;
515 		case MCE_RSP_EQWAKESUPPORT:
516 		case MCE_RSP_GETWAKESOURCE:
517 		case MCE_RSP_EQDEVDETAILS:
518 		case MCE_RSP_EQEMVER:
519 			datasize = 1;
520 			break;
521 		}
522 	case MCE_CMD_PORT_IR:
523 		switch (subcmd) {
524 		case MCE_CMD_UNKNOWN:
525 		case MCE_RSP_EQIRCFS:
526 		case MCE_RSP_EQIRTIMEOUT:
527 		case MCE_RSP_EQIRRXCFCNT:
528 		case MCE_RSP_EQIRNUMPORTS:
529 			datasize = 2;
530 			break;
531 		case MCE_CMD_SIG_END:
532 		case MCE_RSP_EQIRTXPORTS:
533 		case MCE_RSP_EQIRRXPORTEN:
534 			datasize = 1;
535 			break;
536 		}
537 	}
538 	return datasize;
539 }
540 
541 static void mceusb_dev_printdata(struct mceusb_dev *ir, u8 *buf, int buf_len,
542 				 int offset, int len, bool out)
543 {
544 #if defined(DEBUG) || defined(CONFIG_DYNAMIC_DEBUG)
545 	char *inout;
546 	u8 cmd, subcmd, *data;
547 	struct device *dev = ir->dev;
548 	int start, skip = 0;
549 	u32 carrier, period;
550 
551 	/* skip meaningless 0xb1 0x60 header bytes on orig receiver */
552 	if (ir->flags.microsoft_gen1 && !out && !offset)
553 		skip = 2;
554 
555 	if (len <= skip)
556 		return;
557 
558 	dev_dbg(dev, "%cx data: %*ph (length=%d)",
559 		(out ? 't' : 'r'),
560 		min(len, buf_len - offset), buf + offset, len);
561 
562 	inout = out ? "Request" : "Got";
563 
564 	start  = offset + skip;
565 	cmd    = buf[start] & 0xff;
566 	subcmd = buf[start + 1] & 0xff;
567 	data = buf + start + 2;
568 
569 	switch (cmd) {
570 	case MCE_CMD_NULL:
571 		if (subcmd == MCE_CMD_NULL)
572 			break;
573 		if ((subcmd == MCE_CMD_PORT_SYS) &&
574 		    (data[0] == MCE_CMD_RESUME))
575 			dev_dbg(dev, "Device resume requested");
576 		else
577 			dev_dbg(dev, "Unknown command 0x%02x 0x%02x",
578 				 cmd, subcmd);
579 		break;
580 	case MCE_CMD_PORT_SYS:
581 		switch (subcmd) {
582 		case MCE_RSP_EQEMVER:
583 			if (!out)
584 				dev_dbg(dev, "Emulator interface version %x",
585 					 data[0]);
586 			break;
587 		case MCE_CMD_G_REVISION:
588 			if (len == 2)
589 				dev_dbg(dev, "Get hw/sw rev?");
590 			else
591 				dev_dbg(dev, "hw/sw rev %*ph",
592 					4, &buf[start + 2]);
593 			break;
594 		case MCE_CMD_RESUME:
595 			dev_dbg(dev, "Device resume requested");
596 			break;
597 		case MCE_RSP_CMD_ILLEGAL:
598 			dev_dbg(dev, "Illegal PORT_SYS command");
599 			break;
600 		case MCE_RSP_EQWAKEVERSION:
601 			if (!out)
602 				dev_dbg(dev, "Wake version, proto: 0x%02x, payload: 0x%02x, address: 0x%02x, version: 0x%02x",
603 					data[0], data[1], data[2], data[3]);
604 			break;
605 		case MCE_RSP_GETPORTSTATUS:
606 			if (!out)
607 				/* We use data1 + 1 here, to match hw labels */
608 				dev_dbg(dev, "TX port %d: blaster is%s connected",
609 					 data[0] + 1, data[3] ? " not" : "");
610 			break;
611 		case MCE_CMD_FLASHLED:
612 			dev_dbg(dev, "Attempting to flash LED");
613 			break;
614 		default:
615 			dev_dbg(dev, "Unknown command 0x%02x 0x%02x",
616 				 cmd, subcmd);
617 			break;
618 		}
619 		break;
620 	case MCE_CMD_PORT_IR:
621 		switch (subcmd) {
622 		case MCE_CMD_SIG_END:
623 			dev_dbg(dev, "End of signal");
624 			break;
625 		case MCE_CMD_PING:
626 			dev_dbg(dev, "Ping");
627 			break;
628 		case MCE_CMD_UNKNOWN:
629 			dev_dbg(dev, "Resp to 9f 05 of 0x%02x 0x%02x",
630 				data[0], data[1]);
631 			break;
632 		case MCE_RSP_EQIRCFS:
633 			period = DIV_ROUND_CLOSEST((1U << data[0] * 2) *
634 						   (data[1] + 1), 10);
635 			if (!period)
636 				break;
637 			carrier = (1000 * 1000) / period;
638 			dev_dbg(dev, "%s carrier of %u Hz (period %uus)",
639 				 inout, carrier, period);
640 			break;
641 		case MCE_CMD_GETIRCFS:
642 			dev_dbg(dev, "Get carrier mode and freq");
643 			break;
644 		case MCE_RSP_EQIRTXPORTS:
645 			dev_dbg(dev, "%s transmit blaster mask of 0x%02x",
646 				 inout, data[0]);
647 			break;
648 		case MCE_RSP_EQIRTIMEOUT:
649 			/* value is in units of 50us, so x*50/1000 ms */
650 			period = ((data[0] << 8) | data[1]) *
651 				  MCE_TIME_UNIT / 1000;
652 			dev_dbg(dev, "%s receive timeout of %d ms",
653 				 inout, period);
654 			break;
655 		case MCE_CMD_GETIRTIMEOUT:
656 			dev_dbg(dev, "Get receive timeout");
657 			break;
658 		case MCE_CMD_GETIRTXPORTS:
659 			dev_dbg(dev, "Get transmit blaster mask");
660 			break;
661 		case MCE_RSP_EQIRRXPORTEN:
662 			dev_dbg(dev, "%s %s-range receive sensor in use",
663 				 inout, data[0] == 0x02 ? "short" : "long");
664 			break;
665 		case MCE_CMD_GETIRRXPORTEN:
666 		/* aka MCE_RSP_EQIRRXCFCNT */
667 			if (out)
668 				dev_dbg(dev, "Get receive sensor");
669 			else if (ir->learning_enabled)
670 				dev_dbg(dev, "RX pulse count: %d",
671 					((data[0] << 8) | data[1]));
672 			break;
673 		case MCE_RSP_EQIRNUMPORTS:
674 			if (out)
675 				break;
676 			dev_dbg(dev, "Num TX ports: %x, num RX ports: %x",
677 				data[0], data[1]);
678 			break;
679 		case MCE_RSP_CMD_ILLEGAL:
680 			dev_dbg(dev, "Illegal PORT_IR command");
681 			break;
682 		default:
683 			dev_dbg(dev, "Unknown command 0x%02x 0x%02x",
684 				 cmd, subcmd);
685 			break;
686 		}
687 		break;
688 	default:
689 		break;
690 	}
691 
692 	if (cmd == MCE_IRDATA_TRAILER)
693 		dev_dbg(dev, "End of raw IR data");
694 	else if ((cmd != MCE_CMD_PORT_IR) &&
695 		 ((cmd & MCE_PORT_MASK) == MCE_COMMAND_IRDATA))
696 		dev_dbg(dev, "Raw IR data, %d pulse/space samples", ir->rem);
697 #endif
698 }
699 
700 /*
701  * Schedule work that can't be done in interrupt handlers
702  * (mceusb_dev_recv() and mce_async_callback()) nor tasklets.
703  * Invokes mceusb_deferred_kevent() for recovering from
704  * error events specified by the kevent bit field.
705  */
706 static void mceusb_defer_kevent(struct mceusb_dev *ir, int kevent)
707 {
708 	set_bit(kevent, &ir->kevent_flags);
709 	if (!schedule_work(&ir->kevent))
710 		dev_err(ir->dev, "kevent %d may have been dropped", kevent);
711 	else
712 		dev_dbg(ir->dev, "kevent %d scheduled", kevent);
713 }
714 
715 static void mce_async_callback(struct urb *urb)
716 {
717 	struct mceusb_dev *ir;
718 	int len;
719 
720 	if (!urb)
721 		return;
722 
723 	ir = urb->context;
724 
725 	switch (urb->status) {
726 	/* success */
727 	case 0:
728 		len = urb->actual_length;
729 
730 		mceusb_dev_printdata(ir, urb->transfer_buffer, len,
731 				     0, len, true);
732 		break;
733 
734 	case -ECONNRESET:
735 	case -ENOENT:
736 	case -EILSEQ:
737 	case -ESHUTDOWN:
738 		break;
739 
740 	case -EPIPE:
741 		dev_err(ir->dev, "Error: request urb status = %d (TX HALT)",
742 			urb->status);
743 		mceusb_defer_kevent(ir, EVENT_TX_HALT);
744 		break;
745 
746 	default:
747 		dev_err(ir->dev, "Error: request urb status = %d", urb->status);
748 		break;
749 	}
750 
751 	/* the transfer buffer and urb were allocated in mce_request_packet */
752 	kfree(urb->transfer_buffer);
753 	usb_free_urb(urb);
754 }
755 
756 /* request outgoing (send) usb packet - used to initialize remote */
757 static void mce_request_packet(struct mceusb_dev *ir, unsigned char *data,
758 								int size)
759 {
760 	int res;
761 	struct urb *async_urb;
762 	struct device *dev = ir->dev;
763 	unsigned char *async_buf;
764 
765 	async_urb = usb_alloc_urb(0, GFP_KERNEL);
766 	if (unlikely(!async_urb)) {
767 		dev_err(dev, "Error, couldn't allocate urb!");
768 		return;
769 	}
770 
771 	async_buf = kmalloc(size, GFP_KERNEL);
772 	if (!async_buf) {
773 		usb_free_urb(async_urb);
774 		return;
775 	}
776 
777 	/* outbound data */
778 	if (usb_endpoint_xfer_int(ir->usb_ep_out))
779 		usb_fill_int_urb(async_urb, ir->usbdev, ir->pipe_out,
780 				 async_buf, size, mce_async_callback, ir,
781 				 ir->usb_ep_out->bInterval);
782 	else
783 		usb_fill_bulk_urb(async_urb, ir->usbdev, ir->pipe_out,
784 				  async_buf, size, mce_async_callback, ir);
785 
786 	memcpy(async_buf, data, size);
787 
788 	dev_dbg(dev, "send request called (size=%#x)", size);
789 
790 	res = usb_submit_urb(async_urb, GFP_ATOMIC);
791 	if (res) {
792 		dev_err(dev, "send request FAILED! (res=%d)", res);
793 		kfree(async_buf);
794 		usb_free_urb(async_urb);
795 		return;
796 	}
797 	dev_dbg(dev, "send request complete (res=%d)", res);
798 }
799 
800 static void mce_async_out(struct mceusb_dev *ir, unsigned char *data, int size)
801 {
802 	int rsize = sizeof(DEVICE_RESUME);
803 
804 	if (ir->need_reset) {
805 		ir->need_reset = false;
806 		mce_request_packet(ir, DEVICE_RESUME, rsize);
807 		msleep(10);
808 	}
809 
810 	mce_request_packet(ir, data, size);
811 	msleep(10);
812 }
813 
814 /* Send data out the IR blaster port(s) */
815 static int mceusb_tx_ir(struct rc_dev *dev, unsigned *txbuf, unsigned count)
816 {
817 	struct mceusb_dev *ir = dev->priv;
818 	int i, length, ret = 0;
819 	int cmdcount = 0;
820 	unsigned char cmdbuf[MCE_CMDBUF_SIZE];
821 
822 	/* MCE tx init header */
823 	cmdbuf[cmdcount++] = MCE_CMD_PORT_IR;
824 	cmdbuf[cmdcount++] = MCE_CMD_SETIRTXPORTS;
825 	cmdbuf[cmdcount++] = ir->tx_mask;
826 
827 	/* Send the set TX ports command */
828 	mce_async_out(ir, cmdbuf, cmdcount);
829 	cmdcount = 0;
830 
831 	/* Generate mce packet data */
832 	for (i = 0; (i < count) && (cmdcount < MCE_CMDBUF_SIZE); i++) {
833 		txbuf[i] = txbuf[i] / MCE_TIME_UNIT;
834 
835 		do { /* loop to support long pulses/spaces > 127*50us=6.35ms */
836 
837 			/* Insert mce packet header every 4th entry */
838 			if ((cmdcount < MCE_CMDBUF_SIZE) &&
839 			    (cmdcount % MCE_CODE_LENGTH) == 0)
840 				cmdbuf[cmdcount++] = MCE_IRDATA_HEADER;
841 
842 			/* Insert mce packet data */
843 			if (cmdcount < MCE_CMDBUF_SIZE)
844 				cmdbuf[cmdcount++] =
845 					(txbuf[i] < MCE_PULSE_BIT ?
846 					 txbuf[i] : MCE_MAX_PULSE_LENGTH) |
847 					 (i & 1 ? 0x00 : MCE_PULSE_BIT);
848 			else {
849 				ret = -EINVAL;
850 				goto out;
851 			}
852 
853 		} while ((txbuf[i] > MCE_MAX_PULSE_LENGTH) &&
854 			 (txbuf[i] -= MCE_MAX_PULSE_LENGTH));
855 	}
856 
857 	/* Check if we have room for the empty packet at the end */
858 	if (cmdcount >= MCE_CMDBUF_SIZE) {
859 		ret = -EINVAL;
860 		goto out;
861 	}
862 
863 	/* Fix packet length in last header */
864 	length = cmdcount % MCE_CODE_LENGTH;
865 	cmdbuf[cmdcount - length] -= MCE_CODE_LENGTH - length;
866 
867 	/* All mce commands end with an empty packet (0x80) */
868 	cmdbuf[cmdcount++] = MCE_IRDATA_TRAILER;
869 
870 	/* Transmit the command to the mce device */
871 	mce_async_out(ir, cmdbuf, cmdcount);
872 
873 out:
874 	return ret ? ret : count;
875 }
876 
877 /* Sets active IR outputs -- mce devices typically have two */
878 static int mceusb_set_tx_mask(struct rc_dev *dev, u32 mask)
879 {
880 	struct mceusb_dev *ir = dev->priv;
881 
882 	/* return number of transmitters */
883 	int emitters = ir->num_txports ? ir->num_txports : 2;
884 
885 	if (mask >= (1 << emitters))
886 		return emitters;
887 
888 	if (ir->flags.tx_mask_normal)
889 		ir->tx_mask = mask;
890 	else
891 		ir->tx_mask = (mask != MCE_DEFAULT_TX_MASK ?
892 				mask ^ MCE_DEFAULT_TX_MASK : mask) << 1;
893 
894 	return 0;
895 }
896 
897 /* Sets the send carrier frequency and mode */
898 static int mceusb_set_tx_carrier(struct rc_dev *dev, u32 carrier)
899 {
900 	struct mceusb_dev *ir = dev->priv;
901 	int clk = 10000000;
902 	int prescaler = 0, divisor = 0;
903 	unsigned char cmdbuf[4] = { MCE_CMD_PORT_IR,
904 				    MCE_CMD_SETIRCFS, 0x00, 0x00 };
905 
906 	/* Carrier has changed */
907 	if (ir->carrier != carrier) {
908 
909 		if (carrier == 0) {
910 			ir->carrier = carrier;
911 			cmdbuf[2] = MCE_CMD_SIG_END;
912 			cmdbuf[3] = MCE_IRDATA_TRAILER;
913 			dev_dbg(ir->dev, "disabling carrier modulation");
914 			mce_async_out(ir, cmdbuf, sizeof(cmdbuf));
915 			return 0;
916 		}
917 
918 		for (prescaler = 0; prescaler < 4; ++prescaler) {
919 			divisor = (clk >> (2 * prescaler)) / carrier;
920 			if (divisor <= 0xff) {
921 				ir->carrier = carrier;
922 				cmdbuf[2] = prescaler;
923 				cmdbuf[3] = divisor;
924 				dev_dbg(ir->dev, "requesting %u HZ carrier",
925 								carrier);
926 
927 				/* Transmit new carrier to mce device */
928 				mce_async_out(ir, cmdbuf, sizeof(cmdbuf));
929 				return 0;
930 			}
931 		}
932 
933 		return -EINVAL;
934 
935 	}
936 
937 	return 0;
938 }
939 
940 /*
941  * We don't do anything but print debug spew for many of the command bits
942  * we receive from the hardware, but some of them are useful information
943  * we want to store so that we can use them.
944  */
945 static void mceusb_handle_command(struct mceusb_dev *ir, int index)
946 {
947 	u8 hi = ir->buf_in[index + 1] & 0xff;
948 	u8 lo = ir->buf_in[index + 2] & 0xff;
949 
950 	switch (ir->buf_in[index]) {
951 	/* the one and only 5-byte return value command */
952 	case MCE_RSP_GETPORTSTATUS:
953 		if ((ir->buf_in[index + 4] & 0xff) == 0x00)
954 			ir->txports_cabled |= 1 << hi;
955 		break;
956 
957 	/* 2-byte return value commands */
958 	case MCE_RSP_EQIRTIMEOUT:
959 		ir->rc->timeout = US_TO_NS((hi << 8 | lo) * MCE_TIME_UNIT);
960 		break;
961 	case MCE_RSP_EQIRNUMPORTS:
962 		ir->num_txports = hi;
963 		ir->num_rxports = lo;
964 		break;
965 
966 	/* 1-byte return value commands */
967 	case MCE_RSP_EQEMVER:
968 		ir->emver = hi;
969 		break;
970 	case MCE_RSP_EQIRTXPORTS:
971 		ir->tx_mask = hi;
972 		break;
973 	case MCE_RSP_EQIRRXPORTEN:
974 		ir->learning_enabled = ((hi & 0x02) == 0x02);
975 		ir->rxports_active = hi;
976 		break;
977 	case MCE_RSP_CMD_ILLEGAL:
978 		ir->need_reset = true;
979 		break;
980 	default:
981 		break;
982 	}
983 }
984 
985 static void mceusb_process_ir_data(struct mceusb_dev *ir, int buf_len)
986 {
987 	DEFINE_IR_RAW_EVENT(rawir);
988 	bool event = false;
989 	int i = 0;
990 
991 	/* skip meaningless 0xb1 0x60 header bytes on orig receiver */
992 	if (ir->flags.microsoft_gen1)
993 		i = 2;
994 
995 	/* if there's no data, just return now */
996 	if (buf_len <= i)
997 		return;
998 
999 	for (; i < buf_len; i++) {
1000 		switch (ir->parser_state) {
1001 		case SUBCMD:
1002 			ir->rem = mceusb_cmd_datasize(ir->cmd, ir->buf_in[i]);
1003 			mceusb_dev_printdata(ir, ir->buf_in, buf_len, i - 1,
1004 					     ir->rem + 2, false);
1005 			mceusb_handle_command(ir, i);
1006 			ir->parser_state = CMD_DATA;
1007 			break;
1008 		case PARSE_IRDATA:
1009 			ir->rem--;
1010 			init_ir_raw_event(&rawir);
1011 			rawir.pulse = ((ir->buf_in[i] & MCE_PULSE_BIT) != 0);
1012 			rawir.duration = (ir->buf_in[i] & MCE_PULSE_MASK)
1013 					 * US_TO_NS(MCE_TIME_UNIT);
1014 
1015 			dev_dbg(ir->dev, "Storing %s with duration %u",
1016 				rawir.pulse ? "pulse" : "space",
1017 				rawir.duration);
1018 
1019 			if (ir_raw_event_store_with_filter(ir->rc, &rawir))
1020 				event = true;
1021 			break;
1022 		case CMD_DATA:
1023 			ir->rem--;
1024 			break;
1025 		case CMD_HEADER:
1026 			/* decode mce packets of the form (84),AA,BB,CC,DD */
1027 			/* IR data packets can span USB messages - rem */
1028 			ir->cmd = ir->buf_in[i];
1029 			if ((ir->cmd == MCE_CMD_PORT_IR) ||
1030 			    ((ir->cmd & MCE_PORT_MASK) !=
1031 			     MCE_COMMAND_IRDATA)) {
1032 				ir->parser_state = SUBCMD;
1033 				continue;
1034 			}
1035 			ir->rem = (ir->cmd & MCE_PACKET_LENGTH_MASK);
1036 			mceusb_dev_printdata(ir, ir->buf_in, buf_len,
1037 					     i, ir->rem + 1, false);
1038 			if (ir->rem)
1039 				ir->parser_state = PARSE_IRDATA;
1040 			else
1041 				ir_raw_event_reset(ir->rc);
1042 			break;
1043 		}
1044 
1045 		if (ir->parser_state != CMD_HEADER && !ir->rem)
1046 			ir->parser_state = CMD_HEADER;
1047 	}
1048 	if (event) {
1049 		dev_dbg(ir->dev, "processed IR data");
1050 		ir_raw_event_handle(ir->rc);
1051 	}
1052 }
1053 
1054 static void mceusb_dev_recv(struct urb *urb)
1055 {
1056 	struct mceusb_dev *ir;
1057 
1058 	if (!urb)
1059 		return;
1060 
1061 	ir = urb->context;
1062 	if (!ir) {
1063 		usb_unlink_urb(urb);
1064 		return;
1065 	}
1066 
1067 	switch (urb->status) {
1068 	/* success */
1069 	case 0:
1070 		mceusb_process_ir_data(ir, urb->actual_length);
1071 		break;
1072 
1073 	case -ECONNRESET:
1074 	case -ENOENT:
1075 	case -EILSEQ:
1076 	case -ESHUTDOWN:
1077 		usb_unlink_urb(urb);
1078 		return;
1079 
1080 	case -EPIPE:
1081 		dev_err(ir->dev, "Error: urb status = %d (RX HALT)",
1082 			urb->status);
1083 		mceusb_defer_kevent(ir, EVENT_RX_HALT);
1084 		return;
1085 
1086 	default:
1087 		dev_err(ir->dev, "Error: urb status = %d", urb->status);
1088 		break;
1089 	}
1090 
1091 	usb_submit_urb(urb, GFP_ATOMIC);
1092 }
1093 
1094 static void mceusb_get_emulator_version(struct mceusb_dev *ir)
1095 {
1096 	/* If we get no reply or an illegal command reply, its ver 1, says MS */
1097 	ir->emver = 1;
1098 	mce_async_out(ir, GET_EMVER, sizeof(GET_EMVER));
1099 }
1100 
1101 static void mceusb_gen1_init(struct mceusb_dev *ir)
1102 {
1103 	int ret;
1104 	struct device *dev = ir->dev;
1105 	char *data;
1106 
1107 	data = kzalloc(USB_CTRL_MSG_SZ, GFP_KERNEL);
1108 	if (!data) {
1109 		dev_err(dev, "%s: memory allocation failed!", __func__);
1110 		return;
1111 	}
1112 
1113 	/*
1114 	 * This is a strange one. Windows issues a set address to the device
1115 	 * on the receive control pipe and expect a certain value pair back
1116 	 */
1117 	ret = usb_control_msg(ir->usbdev, usb_rcvctrlpipe(ir->usbdev, 0),
1118 			      USB_REQ_SET_ADDRESS, USB_TYPE_VENDOR, 0, 0,
1119 			      data, USB_CTRL_MSG_SZ, HZ * 3);
1120 	dev_dbg(dev, "set address - ret = %d", ret);
1121 	dev_dbg(dev, "set address - data[0] = %d, data[1] = %d",
1122 						data[0], data[1]);
1123 
1124 	/* set feature: bit rate 38400 bps */
1125 	ret = usb_control_msg(ir->usbdev, usb_sndctrlpipe(ir->usbdev, 0),
1126 			      USB_REQ_SET_FEATURE, USB_TYPE_VENDOR,
1127 			      0xc04e, 0x0000, NULL, 0, HZ * 3);
1128 
1129 	dev_dbg(dev, "set feature - ret = %d", ret);
1130 
1131 	/* bRequest 4: set char length to 8 bits */
1132 	ret = usb_control_msg(ir->usbdev, usb_sndctrlpipe(ir->usbdev, 0),
1133 			      4, USB_TYPE_VENDOR,
1134 			      0x0808, 0x0000, NULL, 0, HZ * 3);
1135 	dev_dbg(dev, "set char length - retB = %d", ret);
1136 
1137 	/* bRequest 2: set handshaking to use DTR/DSR */
1138 	ret = usb_control_msg(ir->usbdev, usb_sndctrlpipe(ir->usbdev, 0),
1139 			      2, USB_TYPE_VENDOR,
1140 			      0x0000, 0x0100, NULL, 0, HZ * 3);
1141 	dev_dbg(dev, "set handshake  - retC = %d", ret);
1142 
1143 	/* device resume */
1144 	mce_async_out(ir, DEVICE_RESUME, sizeof(DEVICE_RESUME));
1145 
1146 	/* get hw/sw revision? */
1147 	mce_async_out(ir, GET_REVISION, sizeof(GET_REVISION));
1148 
1149 	kfree(data);
1150 }
1151 
1152 static void mceusb_gen2_init(struct mceusb_dev *ir)
1153 {
1154 	/* device resume */
1155 	mce_async_out(ir, DEVICE_RESUME, sizeof(DEVICE_RESUME));
1156 
1157 	/* get wake version (protocol, key, address) */
1158 	mce_async_out(ir, GET_WAKEVERSION, sizeof(GET_WAKEVERSION));
1159 
1160 	/* unknown what this one actually returns... */
1161 	mce_async_out(ir, GET_UNKNOWN2, sizeof(GET_UNKNOWN2));
1162 }
1163 
1164 static void mceusb_get_parameters(struct mceusb_dev *ir)
1165 {
1166 	int i;
1167 	unsigned char cmdbuf[3] = { MCE_CMD_PORT_SYS,
1168 				    MCE_CMD_GETPORTSTATUS, 0x00 };
1169 
1170 	/* defaults, if the hardware doesn't support querying */
1171 	ir->num_txports = 2;
1172 	ir->num_rxports = 2;
1173 
1174 	/* get number of tx and rx ports */
1175 	mce_async_out(ir, GET_NUM_PORTS, sizeof(GET_NUM_PORTS));
1176 
1177 	/* get the carrier and frequency */
1178 	mce_async_out(ir, GET_CARRIER_FREQ, sizeof(GET_CARRIER_FREQ));
1179 
1180 	if (ir->num_txports && !ir->flags.no_tx)
1181 		/* get the transmitter bitmask */
1182 		mce_async_out(ir, GET_TX_BITMASK, sizeof(GET_TX_BITMASK));
1183 
1184 	/* get receiver timeout value */
1185 	mce_async_out(ir, GET_RX_TIMEOUT, sizeof(GET_RX_TIMEOUT));
1186 
1187 	/* get receiver sensor setting */
1188 	mce_async_out(ir, GET_RX_SENSOR, sizeof(GET_RX_SENSOR));
1189 
1190 	for (i = 0; i < ir->num_txports; i++) {
1191 		cmdbuf[2] = i;
1192 		mce_async_out(ir, cmdbuf, sizeof(cmdbuf));
1193 	}
1194 }
1195 
1196 static void mceusb_flash_led(struct mceusb_dev *ir)
1197 {
1198 	if (ir->emver < 2)
1199 		return;
1200 
1201 	mce_async_out(ir, FLASH_LED, sizeof(FLASH_LED));
1202 }
1203 
1204 /*
1205  * Workqueue function
1206  * for resetting or recovering device after occurrence of error events
1207  * specified in ir->kevent bit field.
1208  * Function runs (via schedule_work()) in non-interrupt context, for
1209  * calls here (such as usb_clear_halt()) requiring non-interrupt context.
1210  */
1211 static void mceusb_deferred_kevent(struct work_struct *work)
1212 {
1213 	struct mceusb_dev *ir =
1214 		container_of(work, struct mceusb_dev, kevent);
1215 	int status;
1216 
1217 	if (test_bit(EVENT_RX_HALT, &ir->kevent_flags)) {
1218 		usb_unlink_urb(ir->urb_in);
1219 		status = usb_clear_halt(ir->usbdev, ir->pipe_in);
1220 		if (status < 0) {
1221 			dev_err(ir->dev, "rx clear halt error %d",
1222 				status);
1223 		}
1224 		clear_bit(EVENT_RX_HALT, &ir->kevent_flags);
1225 		if (status == 0) {
1226 			status = usb_submit_urb(ir->urb_in, GFP_KERNEL);
1227 			if (status < 0) {
1228 				dev_err(ir->dev,
1229 					"rx unhalt submit urb error %d",
1230 					status);
1231 			}
1232 		}
1233 	}
1234 
1235 	if (test_bit(EVENT_TX_HALT, &ir->kevent_flags)) {
1236 		status = usb_clear_halt(ir->usbdev, ir->pipe_out);
1237 		if (status < 0)
1238 			dev_err(ir->dev, "tx clear halt error %d", status);
1239 		clear_bit(EVENT_TX_HALT, &ir->kevent_flags);
1240 	}
1241 }
1242 
1243 static struct rc_dev *mceusb_init_rc_dev(struct mceusb_dev *ir)
1244 {
1245 	struct usb_device *udev = ir->usbdev;
1246 	struct device *dev = ir->dev;
1247 	struct rc_dev *rc;
1248 	int ret;
1249 
1250 	rc = rc_allocate_device(RC_DRIVER_IR_RAW);
1251 	if (!rc) {
1252 		dev_err(dev, "remote dev allocation failed");
1253 		goto out;
1254 	}
1255 
1256 	snprintf(ir->name, sizeof(ir->name), "%s (%04x:%04x)",
1257 		 mceusb_model[ir->model].name ?
1258 			mceusb_model[ir->model].name :
1259 			"Media Center Ed. eHome Infrared Remote Transceiver",
1260 		 le16_to_cpu(ir->usbdev->descriptor.idVendor),
1261 		 le16_to_cpu(ir->usbdev->descriptor.idProduct));
1262 
1263 	usb_make_path(ir->usbdev, ir->phys, sizeof(ir->phys));
1264 
1265 	rc->device_name = ir->name;
1266 	rc->input_phys = ir->phys;
1267 	usb_to_input_id(ir->usbdev, &rc->input_id);
1268 	rc->dev.parent = dev;
1269 	rc->priv = ir;
1270 	rc->allowed_protocols = RC_PROTO_BIT_ALL_IR_DECODER;
1271 	rc->timeout = MS_TO_NS(100);
1272 	if (!ir->flags.no_tx) {
1273 		rc->s_tx_mask = mceusb_set_tx_mask;
1274 		rc->s_tx_carrier = mceusb_set_tx_carrier;
1275 		rc->tx_ir = mceusb_tx_ir;
1276 	}
1277 	rc->driver_name = DRIVER_NAME;
1278 
1279 	switch (le16_to_cpu(udev->descriptor.idVendor)) {
1280 	case VENDOR_HAUPPAUGE:
1281 		rc->map_name = RC_MAP_HAUPPAUGE;
1282 		break;
1283 	case VENDOR_PCTV:
1284 		rc->map_name = RC_MAP_PINNACLE_PCTV_HD;
1285 		break;
1286 	default:
1287 		rc->map_name = RC_MAP_RC6_MCE;
1288 	}
1289 	if (mceusb_model[ir->model].rc_map)
1290 		rc->map_name = mceusb_model[ir->model].rc_map;
1291 
1292 	ret = rc_register_device(rc);
1293 	if (ret < 0) {
1294 		dev_err(dev, "remote dev registration failed");
1295 		goto out;
1296 	}
1297 
1298 	return rc;
1299 
1300 out:
1301 	rc_free_device(rc);
1302 	return NULL;
1303 }
1304 
1305 static int mceusb_dev_probe(struct usb_interface *intf,
1306 			    const struct usb_device_id *id)
1307 {
1308 	struct usb_device *dev = interface_to_usbdev(intf);
1309 	struct usb_host_interface *idesc;
1310 	struct usb_endpoint_descriptor *ep = NULL;
1311 	struct usb_endpoint_descriptor *ep_in = NULL;
1312 	struct usb_endpoint_descriptor *ep_out = NULL;
1313 	struct mceusb_dev *ir = NULL;
1314 	int pipe, maxp, i, res;
1315 	char buf[63], name[128] = "";
1316 	enum mceusb_model_type model = id->driver_info;
1317 	bool is_gen3;
1318 	bool is_microsoft_gen1;
1319 	bool tx_mask_normal;
1320 	int ir_intfnum;
1321 
1322 	dev_dbg(&intf->dev, "%s called", __func__);
1323 
1324 	idesc  = intf->cur_altsetting;
1325 
1326 	is_gen3 = mceusb_model[model].mce_gen3;
1327 	is_microsoft_gen1 = mceusb_model[model].mce_gen1;
1328 	tx_mask_normal = mceusb_model[model].tx_mask_normal;
1329 	ir_intfnum = mceusb_model[model].ir_intfnum;
1330 
1331 	/* There are multi-function devices with non-IR interfaces */
1332 	if (idesc->desc.bInterfaceNumber != ir_intfnum)
1333 		return -ENODEV;
1334 
1335 	/* step through the endpoints to find first bulk in and out endpoint */
1336 	for (i = 0; i < idesc->desc.bNumEndpoints; ++i) {
1337 		ep = &idesc->endpoint[i].desc;
1338 
1339 		if (ep_in == NULL) {
1340 			if (usb_endpoint_is_bulk_in(ep)) {
1341 				ep_in = ep;
1342 				dev_dbg(&intf->dev, "acceptable bulk inbound endpoint found\n");
1343 			} else if (usb_endpoint_is_int_in(ep)) {
1344 				ep_in = ep;
1345 				ep_in->bInterval = 1;
1346 				dev_dbg(&intf->dev, "acceptable interrupt inbound endpoint found\n");
1347 			}
1348 		}
1349 
1350 		if (ep_out == NULL) {
1351 			if (usb_endpoint_is_bulk_out(ep)) {
1352 				ep_out = ep;
1353 				dev_dbg(&intf->dev, "acceptable bulk outbound endpoint found\n");
1354 			} else if (usb_endpoint_is_int_out(ep)) {
1355 				ep_out = ep;
1356 				ep_out->bInterval = 1;
1357 				dev_dbg(&intf->dev, "acceptable interrupt outbound endpoint found\n");
1358 			}
1359 		}
1360 	}
1361 	if (!ep_in || !ep_out) {
1362 		dev_dbg(&intf->dev, "required endpoints not found\n");
1363 		return -ENODEV;
1364 	}
1365 
1366 	if (usb_endpoint_xfer_int(ep_in))
1367 		pipe = usb_rcvintpipe(dev, ep_in->bEndpointAddress);
1368 	else
1369 		pipe = usb_rcvbulkpipe(dev, ep_in->bEndpointAddress);
1370 	maxp = usb_maxpacket(dev, pipe, usb_pipeout(pipe));
1371 
1372 	ir = kzalloc(sizeof(struct mceusb_dev), GFP_KERNEL);
1373 	if (!ir)
1374 		goto mem_alloc_fail;
1375 
1376 	ir->pipe_in = pipe;
1377 	ir->buf_in = usb_alloc_coherent(dev, maxp, GFP_ATOMIC, &ir->dma_in);
1378 	if (!ir->buf_in)
1379 		goto buf_in_alloc_fail;
1380 
1381 	ir->urb_in = usb_alloc_urb(0, GFP_KERNEL);
1382 	if (!ir->urb_in)
1383 		goto urb_in_alloc_fail;
1384 
1385 	ir->usbdev = usb_get_dev(dev);
1386 	ir->dev = &intf->dev;
1387 	ir->len_in = maxp;
1388 	ir->flags.microsoft_gen1 = is_microsoft_gen1;
1389 	ir->flags.tx_mask_normal = tx_mask_normal;
1390 	ir->flags.no_tx = mceusb_model[model].no_tx;
1391 	ir->model = model;
1392 
1393 	/* Saving usb interface data for use by the transmitter routine */
1394 	ir->usb_ep_out = ep_out;
1395 	if (usb_endpoint_xfer_int(ep_out))
1396 		ir->pipe_out = usb_sndintpipe(ir->usbdev,
1397 					      ep_out->bEndpointAddress);
1398 	else
1399 		ir->pipe_out = usb_sndbulkpipe(ir->usbdev,
1400 					       ep_out->bEndpointAddress);
1401 
1402 	if (dev->descriptor.iManufacturer
1403 	    && usb_string(dev, dev->descriptor.iManufacturer,
1404 			  buf, sizeof(buf)) > 0)
1405 		strlcpy(name, buf, sizeof(name));
1406 	if (dev->descriptor.iProduct
1407 	    && usb_string(dev, dev->descriptor.iProduct,
1408 			  buf, sizeof(buf)) > 0)
1409 		snprintf(name + strlen(name), sizeof(name) - strlen(name),
1410 			 " %s", buf);
1411 
1412 	/*
1413 	 * Initialize async USB error handler before registering
1414 	 * or activating any mceusb RX and TX functions
1415 	 */
1416 	INIT_WORK(&ir->kevent, mceusb_deferred_kevent);
1417 
1418 	ir->rc = mceusb_init_rc_dev(ir);
1419 	if (!ir->rc)
1420 		goto rc_dev_fail;
1421 
1422 	/* wire up inbound data handler */
1423 	if (usb_endpoint_xfer_int(ep_in))
1424 		usb_fill_int_urb(ir->urb_in, dev, pipe, ir->buf_in, maxp,
1425 				 mceusb_dev_recv, ir, ep_in->bInterval);
1426 	else
1427 		usb_fill_bulk_urb(ir->urb_in, dev, pipe, ir->buf_in, maxp,
1428 				  mceusb_dev_recv, ir);
1429 
1430 	ir->urb_in->transfer_dma = ir->dma_in;
1431 	ir->urb_in->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1432 
1433 	/* flush buffers on the device */
1434 	dev_dbg(&intf->dev, "Flushing receive buffers");
1435 	res = usb_submit_urb(ir->urb_in, GFP_KERNEL);
1436 	if (res)
1437 		dev_err(&intf->dev, "failed to flush buffers: %d", res);
1438 
1439 	/* figure out which firmware/emulator version this hardware has */
1440 	mceusb_get_emulator_version(ir);
1441 
1442 	/* initialize device */
1443 	if (ir->flags.microsoft_gen1)
1444 		mceusb_gen1_init(ir);
1445 	else if (!is_gen3)
1446 		mceusb_gen2_init(ir);
1447 
1448 	mceusb_get_parameters(ir);
1449 
1450 	mceusb_flash_led(ir);
1451 
1452 	if (!ir->flags.no_tx)
1453 		mceusb_set_tx_mask(ir->rc, MCE_DEFAULT_TX_MASK);
1454 
1455 	usb_set_intfdata(intf, ir);
1456 
1457 	/* enable wake via this device */
1458 	device_set_wakeup_capable(ir->dev, true);
1459 	device_set_wakeup_enable(ir->dev, true);
1460 
1461 	dev_info(&intf->dev, "Registered %s with mce emulator interface version %x",
1462 		name, ir->emver);
1463 	dev_info(&intf->dev, "%x tx ports (0x%x cabled) and %x rx sensors (0x%x active)",
1464 		 ir->num_txports, ir->txports_cabled,
1465 		 ir->num_rxports, ir->rxports_active);
1466 
1467 	return 0;
1468 
1469 	/* Error-handling path */
1470 rc_dev_fail:
1471 	cancel_work_sync(&ir->kevent);
1472 	usb_put_dev(ir->usbdev);
1473 	usb_kill_urb(ir->urb_in);
1474 	usb_free_urb(ir->urb_in);
1475 urb_in_alloc_fail:
1476 	usb_free_coherent(dev, maxp, ir->buf_in, ir->dma_in);
1477 buf_in_alloc_fail:
1478 	kfree(ir);
1479 mem_alloc_fail:
1480 	dev_err(&intf->dev, "%s: device setup failed!", __func__);
1481 
1482 	return -ENOMEM;
1483 }
1484 
1485 
1486 static void mceusb_dev_disconnect(struct usb_interface *intf)
1487 {
1488 	struct usb_device *dev = interface_to_usbdev(intf);
1489 	struct mceusb_dev *ir = usb_get_intfdata(intf);
1490 
1491 	usb_set_intfdata(intf, NULL);
1492 
1493 	if (!ir)
1494 		return;
1495 
1496 	ir->usbdev = NULL;
1497 	cancel_work_sync(&ir->kevent);
1498 	rc_unregister_device(ir->rc);
1499 	usb_kill_urb(ir->urb_in);
1500 	usb_free_urb(ir->urb_in);
1501 	usb_free_coherent(dev, ir->len_in, ir->buf_in, ir->dma_in);
1502 	usb_put_dev(dev);
1503 
1504 	kfree(ir);
1505 }
1506 
1507 static int mceusb_dev_suspend(struct usb_interface *intf, pm_message_t message)
1508 {
1509 	struct mceusb_dev *ir = usb_get_intfdata(intf);
1510 	dev_info(ir->dev, "suspend");
1511 	usb_kill_urb(ir->urb_in);
1512 	return 0;
1513 }
1514 
1515 static int mceusb_dev_resume(struct usb_interface *intf)
1516 {
1517 	struct mceusb_dev *ir = usb_get_intfdata(intf);
1518 	dev_info(ir->dev, "resume");
1519 	if (usb_submit_urb(ir->urb_in, GFP_ATOMIC))
1520 		return -EIO;
1521 	return 0;
1522 }
1523 
1524 static struct usb_driver mceusb_dev_driver = {
1525 	.name =		DRIVER_NAME,
1526 	.probe =	mceusb_dev_probe,
1527 	.disconnect =	mceusb_dev_disconnect,
1528 	.suspend =	mceusb_dev_suspend,
1529 	.resume =	mceusb_dev_resume,
1530 	.reset_resume =	mceusb_dev_resume,
1531 	.id_table =	mceusb_dev_table
1532 };
1533 
1534 module_usb_driver(mceusb_dev_driver);
1535 
1536 MODULE_DESCRIPTION(DRIVER_DESC);
1537 MODULE_AUTHOR(DRIVER_AUTHOR);
1538 MODULE_LICENSE("GPL");
1539 MODULE_DEVICE_TABLE(usb, mceusb_dev_table);
1540