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