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