Merge git://git.kernel.org/pub/scm/linux/kernel/git/steve/gfs2-2.6-nmw
[pandora-kernel.git] / drivers / media / IR / mceusb.c
1 /*
2  * Driver for USB Windows Media Center Ed. eHome Infrared Transceivers
3  *
4  * Copyright (c) 2010 by 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  *
19  * This program is free software; you can redistribute it and/or modify
20  * it under the terms of the GNU General Public License as published by
21  * the Free Software Foundation; either version 2 of the License, or
22  * (at your option) any later version.
23  *
24  * This program is distributed in the hope that it will be useful,
25  * but WITHOUT ANY WARRANTY; without even the implied warranty of
26  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27  * GNU General Public License for more details.
28  *
29  * You should have received a copy of the GNU General Public License
30  * along with this program; if not, write to the Free Software
31  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32  *
33  */
34
35 #include <linux/device.h>
36 #include <linux/module.h>
37 #include <linux/slab.h>
38 #include <linux/usb.h>
39 #include <linux/input.h>
40 #include <media/ir-core.h>
41 #include <media/ir-common.h>
42
43 #define DRIVER_VERSION  "1.91"
44 #define DRIVER_AUTHOR   "Jarod Wilson <jarod@wilsonet.com>"
45 #define DRIVER_DESC     "Windows Media Center Ed. eHome Infrared Transceiver " \
46                         "device driver"
47 #define DRIVER_NAME     "mceusb"
48
49 #define USB_BUFLEN      32      /* USB reception buffer length */
50 #define USB_CTRL_MSG_SZ 2       /* Size of usb ctrl msg on gen1 hw */
51 #define MCE_G1_INIT_MSGS 40     /* Init messages on gen1 hw to throw out */
52
53 /* MCE constants */
54 #define MCE_CMDBUF_SIZE 384 /* MCE Command buffer length */
55 #define MCE_TIME_UNIT   50 /* Approx 50us resolution */
56 #define MCE_CODE_LENGTH 5 /* Normal length of packet (with header) */
57 #define MCE_PACKET_SIZE 4 /* Normal length of packet (without header) */
58 #define MCE_PACKET_HEADER 0x84 /* Actual header format is 0x80 + num_bytes */
59 #define MCE_CONTROL_HEADER 0x9F /* MCE status header */
60 #define MCE_TX_HEADER_LENGTH 3 /* # of bytes in the initializing tx header */
61 #define MCE_MAX_CHANNELS 2 /* Two transmitters, hardware dependent? */
62 #define MCE_DEFAULT_TX_MASK 0x03 /* Val opts: 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 #define MCE_PACKET_LENGTH_MASK  0x1F /* Packet length mask */
67
68
69 /* module parameters */
70 #ifdef CONFIG_USB_DEBUG
71 static int debug = 1;
72 #else
73 static int debug;
74 #endif
75
76 /* general constants */
77 #define SEND_FLAG_IN_PROGRESS   1
78 #define SEND_FLAG_COMPLETE      2
79 #define RECV_FLAG_IN_PROGRESS   3
80 #define RECV_FLAG_COMPLETE      4
81
82 #define MCEUSB_RX               1
83 #define MCEUSB_TX               2
84
85 #define VENDOR_PHILIPS          0x0471
86 #define VENDOR_SMK              0x0609
87 #define VENDOR_TATUNG           0x1460
88 #define VENDOR_GATEWAY          0x107b
89 #define VENDOR_SHUTTLE          0x1308
90 #define VENDOR_SHUTTLE2         0x051c
91 #define VENDOR_MITSUMI          0x03ee
92 #define VENDOR_TOPSEED          0x1784
93 #define VENDOR_RICAVISION       0x179d
94 #define VENDOR_ITRON            0x195d
95 #define VENDOR_FIC              0x1509
96 #define VENDOR_LG               0x043e
97 #define VENDOR_MICROSOFT        0x045e
98 #define VENDOR_FORMOSA          0x147a
99 #define VENDOR_FINTEK           0x1934
100 #define VENDOR_PINNACLE         0x2304
101 #define VENDOR_ECS              0x1019
102 #define VENDOR_WISTRON          0x0fb8
103 #define VENDOR_COMPRO           0x185b
104 #define VENDOR_NORTHSTAR        0x04eb
105 #define VENDOR_REALTEK          0x0bda
106 #define VENDOR_TIVO             0x105a
107
108 static struct usb_device_id mceusb_dev_table[] = {
109         /* Original Microsoft MCE IR Transceiver (often HP-branded) */
110         { USB_DEVICE(VENDOR_MICROSOFT, 0x006d) },
111         /* Philips Infrared Transceiver - Sahara branded */
112         { USB_DEVICE(VENDOR_PHILIPS, 0x0608) },
113         /* Philips Infrared Transceiver - HP branded */
114         { USB_DEVICE(VENDOR_PHILIPS, 0x060c) },
115         /* Philips SRM5100 */
116         { USB_DEVICE(VENDOR_PHILIPS, 0x060d) },
117         /* Philips Infrared Transceiver - Omaura */
118         { USB_DEVICE(VENDOR_PHILIPS, 0x060f) },
119         /* Philips Infrared Transceiver - Spinel plus */
120         { USB_DEVICE(VENDOR_PHILIPS, 0x0613) },
121         /* Philips eHome Infrared Transceiver */
122         { USB_DEVICE(VENDOR_PHILIPS, 0x0815) },
123         /* Philips/Spinel plus IR transceiver for ASUS */
124         { USB_DEVICE(VENDOR_PHILIPS, 0x206c) },
125         /* Philips/Spinel plus IR transceiver for ASUS */
126         { USB_DEVICE(VENDOR_PHILIPS, 0x2088) },
127         /* Realtek MCE IR Receiver */
128         { USB_DEVICE(VENDOR_REALTEK, 0x0161) },
129         /* SMK/Toshiba G83C0004D410 */
130         { USB_DEVICE(VENDOR_SMK, 0x031d) },
131         /* SMK eHome Infrared Transceiver (Sony VAIO) */
132         { USB_DEVICE(VENDOR_SMK, 0x0322) },
133         /* bundled with Hauppauge PVR-150 */
134         { USB_DEVICE(VENDOR_SMK, 0x0334) },
135         /* SMK eHome Infrared Transceiver */
136         { USB_DEVICE(VENDOR_SMK, 0x0338) },
137         /* Tatung eHome Infrared Transceiver */
138         { USB_DEVICE(VENDOR_TATUNG, 0x9150) },
139         /* Shuttle eHome Infrared Transceiver */
140         { USB_DEVICE(VENDOR_SHUTTLE, 0xc001) },
141         /* Shuttle eHome Infrared Transceiver */
142         { USB_DEVICE(VENDOR_SHUTTLE2, 0xc001) },
143         /* Gateway eHome Infrared Transceiver */
144         { USB_DEVICE(VENDOR_GATEWAY, 0x3009) },
145         /* Mitsumi */
146         { USB_DEVICE(VENDOR_MITSUMI, 0x2501) },
147         /* Topseed eHome Infrared Transceiver */
148         { USB_DEVICE(VENDOR_TOPSEED, 0x0001) },
149         /* Topseed HP eHome Infrared Transceiver */
150         { USB_DEVICE(VENDOR_TOPSEED, 0x0006) },
151         /* Topseed eHome Infrared Transceiver */
152         { USB_DEVICE(VENDOR_TOPSEED, 0x0007) },
153         /* Topseed eHome Infrared Transceiver */
154         { USB_DEVICE(VENDOR_TOPSEED, 0x0008) },
155         /* Topseed eHome Infrared Transceiver */
156         { USB_DEVICE(VENDOR_TOPSEED, 0x000a) },
157         /* Topseed eHome Infrared Transceiver */
158         { USB_DEVICE(VENDOR_TOPSEED, 0x0011) },
159         /* Ricavision internal Infrared Transceiver */
160         { USB_DEVICE(VENDOR_RICAVISION, 0x0010) },
161         /* Itron ione Libra Q-11 */
162         { USB_DEVICE(VENDOR_ITRON, 0x7002) },
163         /* FIC eHome Infrared Transceiver */
164         { USB_DEVICE(VENDOR_FIC, 0x9242) },
165         /* LG eHome Infrared Transceiver */
166         { USB_DEVICE(VENDOR_LG, 0x9803) },
167         /* Microsoft MCE Infrared Transceiver */
168         { USB_DEVICE(VENDOR_MICROSOFT, 0x00a0) },
169         /* Formosa eHome Infrared Transceiver */
170         { USB_DEVICE(VENDOR_FORMOSA, 0xe015) },
171         /* Formosa21 / eHome Infrared Receiver */
172         { USB_DEVICE(VENDOR_FORMOSA, 0xe016) },
173         /* Formosa aim / Trust MCE Infrared Receiver */
174         { USB_DEVICE(VENDOR_FORMOSA, 0xe017) },
175         /* Formosa Industrial Computing / Beanbag Emulation Device */
176         { USB_DEVICE(VENDOR_FORMOSA, 0xe018) },
177         /* Formosa21 / eHome Infrared Receiver */
178         { USB_DEVICE(VENDOR_FORMOSA, 0xe03a) },
179         /* Formosa Industrial Computing AIM IR605/A */
180         { USB_DEVICE(VENDOR_FORMOSA, 0xe03c) },
181         /* Formosa Industrial Computing */
182         { USB_DEVICE(VENDOR_FORMOSA, 0xe03e) },
183         /* Fintek eHome Infrared Transceiver */
184         { USB_DEVICE(VENDOR_FINTEK, 0x0602) },
185         /* Fintek eHome Infrared Transceiver (in the AOpen MP45) */
186         { USB_DEVICE(VENDOR_FINTEK, 0x0702) },
187         /* Pinnacle Remote Kit */
188         { USB_DEVICE(VENDOR_PINNACLE, 0x0225) },
189         /* Elitegroup Computer Systems IR */
190         { USB_DEVICE(VENDOR_ECS, 0x0f38) },
191         /* Wistron Corp. eHome Infrared Receiver */
192         { USB_DEVICE(VENDOR_WISTRON, 0x0002) },
193         /* Compro K100 */
194         { USB_DEVICE(VENDOR_COMPRO, 0x3020) },
195         /* Compro K100 v2 */
196         { USB_DEVICE(VENDOR_COMPRO, 0x3082) },
197         /* Northstar Systems, Inc. eHome Infrared Transceiver */
198         { USB_DEVICE(VENDOR_NORTHSTAR, 0xe004) },
199         /* TiVo PC IR Receiver */
200         { USB_DEVICE(VENDOR_TIVO, 0x2000) },
201         /* Terminating entry */
202         { }
203 };
204
205 static struct usb_device_id gen3_list[] = {
206         { USB_DEVICE(VENDOR_PINNACLE, 0x0225) },
207         { USB_DEVICE(VENDOR_TOPSEED, 0x0008) },
208         {}
209 };
210
211 static struct usb_device_id microsoft_gen1_list[] = {
212         { USB_DEVICE(VENDOR_MICROSOFT, 0x006d) },
213         {}
214 };
215
216 static struct usb_device_id std_tx_mask_list[] = {
217         { USB_DEVICE(VENDOR_MICROSOFT, 0x006d) },
218         { USB_DEVICE(VENDOR_PHILIPS, 0x060c) },
219         { USB_DEVICE(VENDOR_SMK, 0x031d) },
220         { USB_DEVICE(VENDOR_SMK, 0x0322) },
221         { USB_DEVICE(VENDOR_SMK, 0x0334) },
222         { USB_DEVICE(VENDOR_TOPSEED, 0x0001) },
223         { USB_DEVICE(VENDOR_TOPSEED, 0x0006) },
224         { USB_DEVICE(VENDOR_TOPSEED, 0x0007) },
225         { USB_DEVICE(VENDOR_TOPSEED, 0x0008) },
226         { USB_DEVICE(VENDOR_TOPSEED, 0x000a) },
227         { USB_DEVICE(VENDOR_TOPSEED, 0x0011) },
228         { USB_DEVICE(VENDOR_PINNACLE, 0x0225) },
229         {}
230 };
231
232 /* data structure for each usb transceiver */
233 struct mceusb_dev {
234         /* ir-core bits */
235         struct ir_dev_props *props;
236         struct ir_raw_event rawir;
237
238         /* core device bits */
239         struct device *dev;
240         struct input_dev *idev;
241
242         /* usb */
243         struct usb_device *usbdev;
244         struct urb *urb_in;
245         struct usb_endpoint_descriptor *usb_ep_in;
246         struct usb_endpoint_descriptor *usb_ep_out;
247
248         /* buffers and dma */
249         unsigned char *buf_in;
250         unsigned int len_in;
251         u8 cmd;         /* MCE command type */
252         u8 rem;         /* Remaining IR data bytes in packet */
253         dma_addr_t dma_in;
254         dma_addr_t dma_out;
255
256         struct {
257                 u32 connected:1;
258                 u32 tx_mask_inverted:1;
259                 u32 microsoft_gen1:1;
260                 u32 reserved:29;
261         } flags;
262
263         /* transmit support */
264         int send_flags;
265         u32 carrier;
266         unsigned char tx_mask;
267
268         char name[128];
269         char phys[64];
270 };
271
272 /*
273  * MCE Device Command Strings
274  * Device command responses vary from device to device...
275  * - DEVICE_RESET resets the hardware to its default state
276  * - GET_REVISION fetches the hardware/software revision, common
277  *   replies are ff 0b 45 ff 1b 08 and ff 0b 50 ff 1b 42
278  * - GET_CARRIER_FREQ gets the carrier mode and frequency of the
279  *   device, with replies in the form of 9f 06 MM FF, where MM is 0-3,
280  *   meaning clk of 10000000, 2500000, 625000 or 156250, and FF is
281  *   ((clk / frequency) - 1)
282  * - GET_RX_TIMEOUT fetches the receiver timeout in units of 50us,
283  *   response in the form of 9f 0c msb lsb
284  * - GET_TX_BITMASK fetches the transmitter bitmask, replies in
285  *   the form of 9f 08 bm, where bm is the bitmask
286  * - GET_RX_SENSOR fetches the RX sensor setting -- long-range
287  *   general use one or short-range learning one, in the form of
288  *   9f 14 ss, where ss is either 01 for long-range or 02 for short
289  * - SET_CARRIER_FREQ sets a new carrier mode and frequency
290  * - SET_TX_BITMASK sets the transmitter bitmask
291  * - SET_RX_TIMEOUT sets the receiver timeout
292  * - SET_RX_SENSOR sets which receiver sensor to use
293  */
294 static char DEVICE_RESET[]      = {0x00, 0xff, 0xaa};
295 static char GET_REVISION[]      = {0xff, 0x0b};
296 static char GET_UNKNOWN[]       = {0xff, 0x18};
297 static char GET_UNKNOWN2[]      = {0x9f, 0x05};
298 static char GET_CARRIER_FREQ[]  = {0x9f, 0x07};
299 static char GET_RX_TIMEOUT[]    = {0x9f, 0x0d};
300 static char GET_TX_BITMASK[]    = {0x9f, 0x13};
301 static char GET_RX_SENSOR[]     = {0x9f, 0x15};
302 /* sub in desired values in lower byte or bytes for full command */
303 /* FIXME: make use of these for transmit.
304 static char SET_CARRIER_FREQ[]  = {0x9f, 0x06, 0x00, 0x00};
305 static char SET_TX_BITMASK[]    = {0x9f, 0x08, 0x00};
306 static char SET_RX_TIMEOUT[]    = {0x9f, 0x0c, 0x00, 0x00};
307 static char SET_RX_SENSOR[]     = {0x9f, 0x14, 0x00};
308 */
309
310 static void mceusb_dev_printdata(struct mceusb_dev *ir, char *buf,
311                                  int len, bool out)
312 {
313         char codes[USB_BUFLEN * 3 + 1];
314         char inout[9];
315         int i;
316         u8 cmd, subcmd, data1, data2;
317         struct device *dev = ir->dev;
318         int idx = 0;
319
320         /* skip meaningless 0xb1 0x60 header bytes on orig receiver */
321         if (ir->flags.microsoft_gen1 && !out)
322                 idx = 2;
323
324         if (len <= idx)
325                 return;
326
327         for (i = 0; i < len && i < USB_BUFLEN; i++)
328                 snprintf(codes + i * 3, 4, "%02x ", buf[i] & 0xFF);
329
330         dev_info(dev, "%sx data: %s (length=%d)\n",
331                  (out ? "t" : "r"), codes, len);
332
333         if (out)
334                 strcpy(inout, "Request\0");
335         else
336                 strcpy(inout, "Got\0");
337
338         cmd    = buf[idx] & 0xff;
339         subcmd = buf[idx + 1] & 0xff;
340         data1  = buf[idx + 2] & 0xff;
341         data2  = buf[idx + 3] & 0xff;
342
343         switch (cmd) {
344         case 0x00:
345                 if (subcmd == 0xff && data1 == 0xaa)
346                         dev_info(dev, "Device reset requested\n");
347                 else
348                         dev_info(dev, "Unknown command 0x%02x 0x%02x\n",
349                                  cmd, subcmd);
350                 break;
351         case 0xff:
352                 switch (subcmd) {
353                 case 0x0b:
354                         if (len == 2)
355                                 dev_info(dev, "Get hw/sw rev?\n");
356                         else
357                                 dev_info(dev, "hw/sw rev 0x%02x 0x%02x "
358                                          "0x%02x 0x%02x\n", data1, data2,
359                                          buf[idx + 4], buf[idx + 5]);
360                         break;
361                 case 0xaa:
362                         dev_info(dev, "Device reset requested\n");
363                         break;
364                 case 0xfe:
365                         dev_info(dev, "Previous command not supported\n");
366                         break;
367                 case 0x18:
368                 case 0x1b:
369                 default:
370                         dev_info(dev, "Unknown command 0x%02x 0x%02x\n",
371                                  cmd, subcmd);
372                         break;
373                 }
374                 break;
375         case 0x9f:
376                 switch (subcmd) {
377                 case 0x03:
378                         dev_info(dev, "Ping\n");
379                         break;
380                 case 0x04:
381                         dev_info(dev, "Resp to 9f 05 of 0x%02x 0x%02x\n",
382                                  data1, data2);
383                         break;
384                 case 0x06:
385                         dev_info(dev, "%s carrier mode and freq of "
386                                  "0x%02x 0x%02x\n", inout, data1, data2);
387                         break;
388                 case 0x07:
389                         dev_info(dev, "Get carrier mode and freq\n");
390                         break;
391                 case 0x08:
392                         dev_info(dev, "%s transmit blaster mask of 0x%02x\n",
393                                  inout, data1);
394                         break;
395                 case 0x0c:
396                         /* value is in units of 50us, so x*50/100 or x/2 ms */
397                         dev_info(dev, "%s receive timeout of %d ms\n",
398                                  inout, ((data1 << 8) | data2) / 2);
399                         break;
400                 case 0x0d:
401                         dev_info(dev, "Get receive timeout\n");
402                         break;
403                 case 0x13:
404                         dev_info(dev, "Get transmit blaster mask\n");
405                         break;
406                 case 0x14:
407                         dev_info(dev, "%s %s-range receive sensor in use\n",
408                                  inout, data1 == 0x02 ? "short" : "long");
409                         break;
410                 case 0x15:
411                         if (len == 2)
412                                 dev_info(dev, "Get receive sensor\n");
413                         else
414                                 dev_info(dev, "Received pulse count is %d\n",
415                                          ((data1 << 8) | data2));
416                         break;
417                 case 0xfe:
418                         dev_info(dev, "Error! Hardware is likely wedged...\n");
419                         break;
420                 case 0x05:
421                 case 0x09:
422                 case 0x0f:
423                 default:
424                         dev_info(dev, "Unknown command 0x%02x 0x%02x\n",
425                                  cmd, subcmd);
426                         break;
427                 }
428                 break;
429         default:
430                 break;
431         }
432 }
433
434 static void mce_async_callback(struct urb *urb, struct pt_regs *regs)
435 {
436         struct mceusb_dev *ir;
437         int len;
438
439         if (!urb)
440                 return;
441
442         ir = urb->context;
443         if (ir) {
444                 len = urb->actual_length;
445
446                 dev_dbg(ir->dev, "callback called (status=%d len=%d)\n",
447                         urb->status, len);
448
449                 if (debug)
450                         mceusb_dev_printdata(ir, urb->transfer_buffer,
451                                              len, true);
452         }
453
454 }
455
456 /* request incoming or send outgoing usb packet - used to initialize remote */
457 static void mce_request_packet(struct mceusb_dev *ir,
458                                struct usb_endpoint_descriptor *ep,
459                                unsigned char *data, int size, int urb_type)
460 {
461         int res;
462         struct urb *async_urb;
463         struct device *dev = ir->dev;
464         unsigned char *async_buf;
465
466         if (urb_type == MCEUSB_TX) {
467                 async_urb = usb_alloc_urb(0, GFP_KERNEL);
468                 if (unlikely(!async_urb)) {
469                         dev_err(dev, "Error, couldn't allocate urb!\n");
470                         return;
471                 }
472
473                 async_buf = kzalloc(size, GFP_KERNEL);
474                 if (!async_buf) {
475                         dev_err(dev, "Error, couldn't allocate buf!\n");
476                         usb_free_urb(async_urb);
477                         return;
478                 }
479
480                 /* outbound data */
481                 usb_fill_int_urb(async_urb, ir->usbdev,
482                         usb_sndintpipe(ir->usbdev, ep->bEndpointAddress),
483                         async_buf, size, (usb_complete_t)mce_async_callback,
484                         ir, ep->bInterval);
485                 memcpy(async_buf, data, size);
486
487         } else if (urb_type == MCEUSB_RX) {
488                 /* standard request */
489                 async_urb = ir->urb_in;
490                 ir->send_flags = RECV_FLAG_IN_PROGRESS;
491
492         } else {
493                 dev_err(dev, "Error! Unknown urb type %d\n", urb_type);
494                 return;
495         }
496
497         dev_dbg(dev, "receive request called (size=%#x)\n", size);
498
499         async_urb->transfer_buffer_length = size;
500         async_urb->dev = ir->usbdev;
501
502         res = usb_submit_urb(async_urb, GFP_ATOMIC);
503         if (res) {
504                 dev_dbg(dev, "receive request FAILED! (res=%d)\n", res);
505                 return;
506         }
507         dev_dbg(dev, "receive request complete (res=%d)\n", res);
508 }
509
510 static void mce_async_out(struct mceusb_dev *ir, unsigned char *data, int size)
511 {
512         mce_request_packet(ir, ir->usb_ep_out, data, size, MCEUSB_TX);
513 }
514
515 static void mce_sync_in(struct mceusb_dev *ir, unsigned char *data, int size)
516 {
517         mce_request_packet(ir, ir->usb_ep_in, data, size, MCEUSB_RX);
518 }
519
520 /* Send data out the IR blaster port(s) */
521 static int mceusb_tx_ir(void *priv, int *txbuf, u32 n)
522 {
523         struct mceusb_dev *ir = priv;
524         int i, ret = 0;
525         int count, cmdcount = 0;
526         unsigned char *cmdbuf; /* MCE command buffer */
527         long signal_duration = 0; /* Singnal length in us */
528         struct timeval start_time, end_time;
529
530         do_gettimeofday(&start_time);
531
532         count = n / sizeof(int);
533
534         cmdbuf = kzalloc(sizeof(int) * MCE_CMDBUF_SIZE, GFP_KERNEL);
535         if (!cmdbuf)
536                 return -ENOMEM;
537
538         /* MCE tx init header */
539         cmdbuf[cmdcount++] = MCE_CONTROL_HEADER;
540         cmdbuf[cmdcount++] = 0x08;
541         cmdbuf[cmdcount++] = ir->tx_mask;
542
543         /* Generate mce packet data */
544         for (i = 0; (i < count) && (cmdcount < MCE_CMDBUF_SIZE); i++) {
545                 signal_duration += txbuf[i];
546                 txbuf[i] = txbuf[i] / MCE_TIME_UNIT;
547
548                 do { /* loop to support long pulses/spaces > 127*50us=6.35ms */
549
550                         /* Insert mce packet header every 4th entry */
551                         if ((cmdcount < MCE_CMDBUF_SIZE) &&
552                             (cmdcount - MCE_TX_HEADER_LENGTH) %
553                              MCE_CODE_LENGTH == 0)
554                                 cmdbuf[cmdcount++] = MCE_PACKET_HEADER;
555
556                         /* Insert mce packet data */
557                         if (cmdcount < MCE_CMDBUF_SIZE)
558                                 cmdbuf[cmdcount++] =
559                                         (txbuf[i] < MCE_PULSE_BIT ?
560                                          txbuf[i] : MCE_MAX_PULSE_LENGTH) |
561                                          (i & 1 ? 0x00 : MCE_PULSE_BIT);
562                         else {
563                                 ret = -EINVAL;
564                                 goto out;
565                         }
566
567                 } while ((txbuf[i] > MCE_MAX_PULSE_LENGTH) &&
568                          (txbuf[i] -= MCE_MAX_PULSE_LENGTH));
569         }
570
571         /* Fix packet length in last header */
572         cmdbuf[cmdcount - (cmdcount - MCE_TX_HEADER_LENGTH) % MCE_CODE_LENGTH] =
573                 0x80 + (cmdcount - MCE_TX_HEADER_LENGTH) % MCE_CODE_LENGTH - 1;
574
575         /* Check if we have room for the empty packet at the end */
576         if (cmdcount >= MCE_CMDBUF_SIZE) {
577                 ret = -EINVAL;
578                 goto out;
579         }
580
581         /* All mce commands end with an empty packet (0x80) */
582         cmdbuf[cmdcount++] = 0x80;
583
584         /* Transmit the command to the mce device */
585         mce_async_out(ir, cmdbuf, cmdcount);
586
587         /*
588          * The lircd gap calculation expects the write function to
589          * wait the time it takes for the ircommand to be sent before
590          * it returns.
591          */
592         do_gettimeofday(&end_time);
593         signal_duration -= (end_time.tv_usec - start_time.tv_usec) +
594                            (end_time.tv_sec - start_time.tv_sec) * 1000000;
595
596         /* delay with the closest number of ticks */
597         set_current_state(TASK_INTERRUPTIBLE);
598         schedule_timeout(usecs_to_jiffies(signal_duration));
599
600 out:
601         kfree(cmdbuf);
602         return ret ? ret : n;
603 }
604
605 /* Sets active IR outputs -- mce devices typically (all?) have two */
606 static int mceusb_set_tx_mask(void *priv, u32 mask)
607 {
608         struct mceusb_dev *ir = priv;
609
610         if (ir->flags.tx_mask_inverted)
611                 ir->tx_mask = (mask != 0x03 ? mask ^ 0x03 : mask) << 1;
612         else
613                 ir->tx_mask = mask;
614
615         return 0;
616 }
617
618 /* Sets the send carrier frequency and mode */
619 static int mceusb_set_tx_carrier(void *priv, u32 carrier)
620 {
621         struct mceusb_dev *ir = priv;
622         int clk = 10000000;
623         int prescaler = 0, divisor = 0;
624         unsigned char cmdbuf[4] = { 0x9f, 0x06, 0x00, 0x00 };
625
626         /* Carrier has changed */
627         if (ir->carrier != carrier) {
628
629                 if (carrier == 0) {
630                         ir->carrier = carrier;
631                         cmdbuf[2] = 0x01;
632                         cmdbuf[3] = 0x80;
633                         dev_dbg(ir->dev, "%s: disabling carrier "
634                                 "modulation\n", __func__);
635                         mce_async_out(ir, cmdbuf, sizeof(cmdbuf));
636                         return carrier;
637                 }
638
639                 for (prescaler = 0; prescaler < 4; ++prescaler) {
640                         divisor = (clk >> (2 * prescaler)) / carrier;
641                         if (divisor <= 0xFF) {
642                                 ir->carrier = carrier;
643                                 cmdbuf[2] = prescaler;
644                                 cmdbuf[3] = divisor;
645                                 dev_dbg(ir->dev, "%s: requesting %u HZ "
646                                         "carrier\n", __func__, carrier);
647
648                                 /* Transmit new carrier to mce device */
649                                 mce_async_out(ir, cmdbuf, sizeof(cmdbuf));
650                                 return carrier;
651                         }
652                 }
653
654                 return -EINVAL;
655
656         }
657
658         return carrier;
659 }
660
661 static void mceusb_process_ir_data(struct mceusb_dev *ir, int buf_len)
662 {
663         struct ir_raw_event rawir = { .pulse = false, .duration = 0 };
664         int i, start_index = 0;
665         u8 hdr = MCE_CONTROL_HEADER;
666
667         /* skip meaningless 0xb1 0x60 header bytes on orig receiver */
668         if (ir->flags.microsoft_gen1)
669                 start_index = 2;
670
671         for (i = start_index; i < buf_len;) {
672                 if (ir->rem == 0) {
673                         /* decode mce packets of the form (84),AA,BB,CC,DD */
674                         /* IR data packets can span USB messages - rem */
675                         hdr = ir->buf_in[i];
676                         ir->rem = (hdr & MCE_PACKET_LENGTH_MASK);
677                         ir->cmd = (hdr & ~MCE_PACKET_LENGTH_MASK);
678                         dev_dbg(ir->dev, "New data. rem: 0x%02x, cmd: 0x%02x\n",
679                                 ir->rem, ir->cmd);
680                         i++;
681                 }
682
683                 /* don't process MCE commands */
684                 if (hdr == MCE_CONTROL_HEADER || hdr == 0xff) {
685                         ir->rem = 0;
686                         return;
687                 }
688
689                 for (; (ir->rem > 0) && (i < buf_len); i++) {
690                         ir->rem--;
691
692                         rawir.pulse = ((ir->buf_in[i] & MCE_PULSE_BIT) != 0);
693                         rawir.duration = (ir->buf_in[i] & MCE_PULSE_MASK)
694                                          * MCE_TIME_UNIT * 1000;
695
696                         if ((ir->buf_in[i] & MCE_PULSE_MASK) == 0x7f) {
697                                 if (ir->rawir.pulse == rawir.pulse)
698                                         ir->rawir.duration += rawir.duration;
699                                 else {
700                                         ir->rawir.duration = rawir.duration;
701                                         ir->rawir.pulse = rawir.pulse;
702                                 }
703                                 continue;
704                         }
705                         rawir.duration += ir->rawir.duration;
706                         ir->rawir.duration = 0;
707                         ir->rawir.pulse = rawir.pulse;
708
709                         dev_dbg(ir->dev, "Storing %s with duration %d\n",
710                                 rawir.pulse ? "pulse" : "space",
711                                 rawir.duration);
712
713                         ir_raw_event_store(ir->idev, &rawir);
714                 }
715
716                 if (ir->buf_in[i] == 0x80 || ir->buf_in[i] == 0x9f)
717                         ir->rem = 0;
718
719                 dev_dbg(ir->dev, "calling ir_raw_event_handle\n");
720                 ir_raw_event_handle(ir->idev);
721         }
722 }
723
724 static void mceusb_dev_recv(struct urb *urb, struct pt_regs *regs)
725 {
726         struct mceusb_dev *ir;
727         int buf_len;
728
729         if (!urb)
730                 return;
731
732         ir = urb->context;
733         if (!ir) {
734                 usb_unlink_urb(urb);
735                 return;
736         }
737
738         buf_len = urb->actual_length;
739
740         if (debug)
741                 mceusb_dev_printdata(ir, urb->transfer_buffer, buf_len, false);
742
743         if (ir->send_flags == RECV_FLAG_IN_PROGRESS) {
744                 ir->send_flags = SEND_FLAG_COMPLETE;
745                 dev_dbg(ir->dev, "setup answer received %d bytes\n",
746                         buf_len);
747         }
748
749         switch (urb->status) {
750         /* success */
751         case 0:
752                 mceusb_process_ir_data(ir, buf_len);
753                 break;
754
755         case -ECONNRESET:
756         case -ENOENT:
757         case -ESHUTDOWN:
758                 usb_unlink_urb(urb);
759                 return;
760
761         case -EPIPE:
762         default:
763                 break;
764         }
765
766         usb_submit_urb(urb, GFP_ATOMIC);
767 }
768
769 static void mceusb_gen1_init(struct mceusb_dev *ir)
770 {
771         int ret;
772         int maxp = ir->len_in;
773         struct device *dev = ir->dev;
774         char *data;
775
776         data = kzalloc(USB_CTRL_MSG_SZ, GFP_KERNEL);
777         if (!data) {
778                 dev_err(dev, "%s: memory allocation failed!\n", __func__);
779                 return;
780         }
781
782         /*
783          * This is a strange one. Windows issues a set address to the device
784          * on the receive control pipe and expect a certain value pair back
785          */
786         ret = usb_control_msg(ir->usbdev, usb_rcvctrlpipe(ir->usbdev, 0),
787                               USB_REQ_SET_ADDRESS, USB_TYPE_VENDOR, 0, 0,
788                               data, USB_CTRL_MSG_SZ, HZ * 3);
789         dev_dbg(dev, "%s - ret = %d\n", __func__, ret);
790         dev_dbg(dev, "%s - data[0] = %d, data[1] = %d\n",
791                 __func__, data[0], data[1]);
792
793         /* set feature: bit rate 38400 bps */
794         ret = usb_control_msg(ir->usbdev, usb_sndctrlpipe(ir->usbdev, 0),
795                               USB_REQ_SET_FEATURE, USB_TYPE_VENDOR,
796                               0xc04e, 0x0000, NULL, 0, HZ * 3);
797
798         dev_dbg(dev, "%s - ret = %d\n", __func__, ret);
799
800         /* bRequest 4: set char length to 8 bits */
801         ret = usb_control_msg(ir->usbdev, usb_sndctrlpipe(ir->usbdev, 0),
802                               4, USB_TYPE_VENDOR,
803                               0x0808, 0x0000, NULL, 0, HZ * 3);
804         dev_dbg(dev, "%s - retB = %d\n", __func__, ret);
805
806         /* bRequest 2: set handshaking to use DTR/DSR */
807         ret = usb_control_msg(ir->usbdev, usb_sndctrlpipe(ir->usbdev, 0),
808                               2, USB_TYPE_VENDOR,
809                               0x0000, 0x0100, NULL, 0, HZ * 3);
810         dev_dbg(dev, "%s - retC = %d\n", __func__, ret);
811
812         /* device reset */
813         mce_async_out(ir, DEVICE_RESET, sizeof(DEVICE_RESET));
814         mce_sync_in(ir, NULL, maxp);
815
816         /* get hw/sw revision? */
817         mce_async_out(ir, GET_REVISION, sizeof(GET_REVISION));
818         mce_sync_in(ir, NULL, maxp);
819
820         kfree(data);
821 };
822
823 static void mceusb_gen2_init(struct mceusb_dev *ir)
824 {
825         int maxp = ir->len_in;
826
827         /* device reset */
828         mce_async_out(ir, DEVICE_RESET, sizeof(DEVICE_RESET));
829         mce_sync_in(ir, NULL, maxp);
830
831         /* get hw/sw revision? */
832         mce_async_out(ir, GET_REVISION, sizeof(GET_REVISION));
833         mce_sync_in(ir, NULL, maxp);
834
835         /* unknown what the next two actually return... */
836         mce_async_out(ir, GET_UNKNOWN, sizeof(GET_UNKNOWN));
837         mce_sync_in(ir, NULL, maxp);
838         mce_async_out(ir, GET_UNKNOWN2, sizeof(GET_UNKNOWN2));
839         mce_sync_in(ir, NULL, maxp);
840 }
841
842 static void mceusb_get_parameters(struct mceusb_dev *ir)
843 {
844         int maxp = ir->len_in;
845
846         /* get the carrier and frequency */
847         mce_async_out(ir, GET_CARRIER_FREQ, sizeof(GET_CARRIER_FREQ));
848         mce_sync_in(ir, NULL, maxp);
849
850         /* get the transmitter bitmask */
851         mce_async_out(ir, GET_TX_BITMASK, sizeof(GET_TX_BITMASK));
852         mce_sync_in(ir, NULL, maxp);
853
854         /* get receiver timeout value */
855         mce_async_out(ir, GET_RX_TIMEOUT, sizeof(GET_RX_TIMEOUT));
856         mce_sync_in(ir, NULL, maxp);
857
858         /* get receiver sensor setting */
859         mce_async_out(ir, GET_RX_SENSOR, sizeof(GET_RX_SENSOR));
860         mce_sync_in(ir, NULL, maxp);
861 }
862
863 static struct input_dev *mceusb_init_input_dev(struct mceusb_dev *ir)
864 {
865         struct input_dev *idev;
866         struct ir_dev_props *props;
867         struct device *dev = ir->dev;
868         int ret = -ENODEV;
869
870         idev = input_allocate_device();
871         if (!idev) {
872                 dev_err(dev, "remote input dev allocation failed\n");
873                 goto idev_alloc_failed;
874         }
875
876         ret = -ENOMEM;
877         props = kzalloc(sizeof(struct ir_dev_props), GFP_KERNEL);
878         if (!props) {
879                 dev_err(dev, "remote ir dev props allocation failed\n");
880                 goto props_alloc_failed;
881         }
882
883         snprintf(ir->name, sizeof(ir->name), "Media Center Ed. eHome "
884                  "Infrared Remote Transceiver (%04x:%04x)",
885                  le16_to_cpu(ir->usbdev->descriptor.idVendor),
886                  le16_to_cpu(ir->usbdev->descriptor.idProduct));
887
888         idev->name = ir->name;
889         usb_make_path(ir->usbdev, ir->phys, sizeof(ir->phys));
890         strlcat(ir->phys, "/input0", sizeof(ir->phys));
891         idev->phys = ir->phys;
892
893         props->priv = ir;
894         props->driver_type = RC_DRIVER_IR_RAW;
895         props->allowed_protos = IR_TYPE_ALL;
896         props->s_tx_mask = mceusb_set_tx_mask;
897         props->s_tx_carrier = mceusb_set_tx_carrier;
898         props->tx_ir = mceusb_tx_ir;
899
900         ir->props = props;
901
902         ret = ir_input_register(idev, RC_MAP_RC6_MCE, props, DRIVER_NAME);
903         if (ret < 0) {
904                 dev_err(dev, "remote input device register failed\n");
905                 goto irdev_failed;
906         }
907
908         return idev;
909
910 irdev_failed:
911         kfree(props);
912 props_alloc_failed:
913         input_free_device(idev);
914 idev_alloc_failed:
915         return NULL;
916 }
917
918 static int __devinit mceusb_dev_probe(struct usb_interface *intf,
919                                       const struct usb_device_id *id)
920 {
921         struct usb_device *dev = interface_to_usbdev(intf);
922         struct usb_host_interface *idesc;
923         struct usb_endpoint_descriptor *ep = NULL;
924         struct usb_endpoint_descriptor *ep_in = NULL;
925         struct usb_endpoint_descriptor *ep_out = NULL;
926         struct mceusb_dev *ir = NULL;
927         int pipe, maxp, i;
928         char buf[63], name[128] = "";
929         bool is_gen3;
930         bool is_microsoft_gen1;
931         bool tx_mask_inverted;
932
933         dev_dbg(&intf->dev, ": %s called\n", __func__);
934
935         idesc  = intf->cur_altsetting;
936
937         is_gen3 = usb_match_id(intf, gen3_list) ? 1 : 0;
938         is_microsoft_gen1 = usb_match_id(intf, microsoft_gen1_list) ? 1 : 0;
939         tx_mask_inverted = usb_match_id(intf, std_tx_mask_list) ? 0 : 1;
940
941         /* step through the endpoints to find first bulk in and out endpoint */
942         for (i = 0; i < idesc->desc.bNumEndpoints; ++i) {
943                 ep = &idesc->endpoint[i].desc;
944
945                 if ((ep_in == NULL)
946                         && ((ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK)
947                             == USB_DIR_IN)
948                         && (((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
949                             == USB_ENDPOINT_XFER_BULK)
950                         || ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
951                             == USB_ENDPOINT_XFER_INT))) {
952
953                         ep_in = ep;
954                         ep_in->bmAttributes = USB_ENDPOINT_XFER_INT;
955                         ep_in->bInterval = 1;
956                         dev_dbg(&intf->dev, ": acceptable inbound endpoint "
957                                 "found\n");
958                 }
959
960                 if ((ep_out == NULL)
961                         && ((ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK)
962                             == USB_DIR_OUT)
963                         && (((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
964                             == USB_ENDPOINT_XFER_BULK)
965                         || ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
966                             == USB_ENDPOINT_XFER_INT))) {
967
968                         ep_out = ep;
969                         ep_out->bmAttributes = USB_ENDPOINT_XFER_INT;
970                         ep_out->bInterval = 1;
971                         dev_dbg(&intf->dev, ": acceptable outbound endpoint "
972                                 "found\n");
973                 }
974         }
975         if (ep_in == NULL) {
976                 dev_dbg(&intf->dev, ": inbound and/or endpoint not found\n");
977                 return -ENODEV;
978         }
979
980         pipe = usb_rcvintpipe(dev, ep_in->bEndpointAddress);
981         maxp = usb_maxpacket(dev, pipe, usb_pipeout(pipe));
982
983         ir = kzalloc(sizeof(struct mceusb_dev), GFP_KERNEL);
984         if (!ir)
985                 goto mem_alloc_fail;
986
987         ir->buf_in = usb_alloc_coherent(dev, maxp, GFP_ATOMIC, &ir->dma_in);
988         if (!ir->buf_in)
989                 goto buf_in_alloc_fail;
990
991         ir->urb_in = usb_alloc_urb(0, GFP_KERNEL);
992         if (!ir->urb_in)
993                 goto urb_in_alloc_fail;
994
995         ir->usbdev = dev;
996         ir->dev = &intf->dev;
997         ir->len_in = maxp;
998         ir->flags.microsoft_gen1 = is_microsoft_gen1;
999         ir->flags.tx_mask_inverted = tx_mask_inverted;
1000
1001         /* Saving usb interface data for use by the transmitter routine */
1002         ir->usb_ep_in = ep_in;
1003         ir->usb_ep_out = ep_out;
1004
1005         if (dev->descriptor.iManufacturer
1006             && usb_string(dev, dev->descriptor.iManufacturer,
1007                           buf, sizeof(buf)) > 0)
1008                 strlcpy(name, buf, sizeof(name));
1009         if (dev->descriptor.iProduct
1010             && usb_string(dev, dev->descriptor.iProduct,
1011                           buf, sizeof(buf)) > 0)
1012                 snprintf(name + strlen(name), sizeof(name) - strlen(name),
1013                          " %s", buf);
1014
1015         ir->idev = mceusb_init_input_dev(ir);
1016         if (!ir->idev)
1017                 goto input_dev_fail;
1018
1019         /* flush buffers on the device */
1020         mce_sync_in(ir, NULL, maxp);
1021         mce_sync_in(ir, NULL, maxp);
1022
1023         /* wire up inbound data handler */
1024         usb_fill_int_urb(ir->urb_in, dev, pipe, ir->buf_in,
1025                 maxp, (usb_complete_t) mceusb_dev_recv, ir, ep_in->bInterval);
1026         ir->urb_in->transfer_dma = ir->dma_in;
1027         ir->urb_in->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1028
1029         /* initialize device */
1030         if (ir->flags.microsoft_gen1)
1031                 mceusb_gen1_init(ir);
1032         else if (!is_gen3)
1033                 mceusb_gen2_init(ir);
1034
1035         mceusb_get_parameters(ir);
1036
1037         mceusb_set_tx_mask(ir, MCE_DEFAULT_TX_MASK);
1038
1039         usb_set_intfdata(intf, ir);
1040
1041         dev_info(&intf->dev, "Registered %s on usb%d:%d\n", name,
1042                  dev->bus->busnum, dev->devnum);
1043
1044         return 0;
1045
1046         /* Error-handling path */
1047 input_dev_fail:
1048         usb_free_urb(ir->urb_in);
1049 urb_in_alloc_fail:
1050         usb_free_coherent(dev, maxp, ir->buf_in, ir->dma_in);
1051 buf_in_alloc_fail:
1052         kfree(ir);
1053 mem_alloc_fail:
1054         dev_err(&intf->dev, "%s: device setup failed!\n", __func__);
1055
1056         return -ENOMEM;
1057 }
1058
1059
1060 static void __devexit mceusb_dev_disconnect(struct usb_interface *intf)
1061 {
1062         struct usb_device *dev = interface_to_usbdev(intf);
1063         struct mceusb_dev *ir = usb_get_intfdata(intf);
1064
1065         usb_set_intfdata(intf, NULL);
1066
1067         if (!ir)
1068                 return;
1069
1070         ir->usbdev = NULL;
1071         ir_input_unregister(ir->idev);
1072         usb_kill_urb(ir->urb_in);
1073         usb_free_urb(ir->urb_in);
1074         usb_free_coherent(dev, ir->len_in, ir->buf_in, ir->dma_in);
1075
1076         kfree(ir);
1077 }
1078
1079 static int mceusb_dev_suspend(struct usb_interface *intf, pm_message_t message)
1080 {
1081         struct mceusb_dev *ir = usb_get_intfdata(intf);
1082         dev_info(ir->dev, "suspend\n");
1083         usb_kill_urb(ir->urb_in);
1084         return 0;
1085 }
1086
1087 static int mceusb_dev_resume(struct usb_interface *intf)
1088 {
1089         struct mceusb_dev *ir = usb_get_intfdata(intf);
1090         dev_info(ir->dev, "resume\n");
1091         if (usb_submit_urb(ir->urb_in, GFP_ATOMIC))
1092                 return -EIO;
1093         return 0;
1094 }
1095
1096 static struct usb_driver mceusb_dev_driver = {
1097         .name =         DRIVER_NAME,
1098         .probe =        mceusb_dev_probe,
1099         .disconnect =   mceusb_dev_disconnect,
1100         .suspend =      mceusb_dev_suspend,
1101         .resume =       mceusb_dev_resume,
1102         .reset_resume = mceusb_dev_resume,
1103         .id_table =     mceusb_dev_table
1104 };
1105
1106 static int __init mceusb_dev_init(void)
1107 {
1108         int ret;
1109
1110         ret = usb_register(&mceusb_dev_driver);
1111         if (ret < 0)
1112                 printk(KERN_ERR DRIVER_NAME
1113                        ": usb register failed, result = %d\n", ret);
1114
1115         return ret;
1116 }
1117
1118 static void __exit mceusb_dev_exit(void)
1119 {
1120         usb_deregister(&mceusb_dev_driver);
1121 }
1122
1123 module_init(mceusb_dev_init);
1124 module_exit(mceusb_dev_exit);
1125
1126 MODULE_DESCRIPTION(DRIVER_DESC);
1127 MODULE_AUTHOR(DRIVER_AUTHOR);
1128 MODULE_LICENSE("GPL");
1129 MODULE_DEVICE_TABLE(usb, mceusb_dev_table);
1130
1131 module_param(debug, bool, S_IRUGO | S_IWUSR);
1132 MODULE_PARM_DESC(debug, "Debug enabled or not");