]> git.karo-electronics.de Git - linux-beck.git/blob - drivers/media/rc/redrat3.c
610c15ef4ae66926d999781a80cd32f31f7dcaaf
[linux-beck.git] / drivers / media / rc / redrat3.c
1 /*
2  * USB RedRat3 IR Transceiver rc-core driver
3  *
4  * Copyright (c) 2011 by Jarod Wilson <jarod@redhat.com>
5  *  based heavily on the work of Stephen Cox, with additional
6  *  help from RedRat Ltd.
7  *
8  * This driver began life based an an old version of the first-generation
9  * lirc_mceusb driver from the lirc 0.7.2 distribution. It was then
10  * significantly rewritten by Stephen Cox with the aid of RedRat Ltd's
11  * Chris Dodge.
12  *
13  * The driver was then ported to rc-core and significantly rewritten again,
14  * by Jarod, using the in-kernel mceusb driver as a guide, after an initial
15  * port effort was started by Stephen.
16  *
17  * TODO LIST:
18  * - fix lirc not showing repeats properly
19  * --
20  *
21  * The RedRat3 is a USB transceiver with both send & receive,
22  * with 2 separate sensors available for receive to enable
23  * both good long range reception for general use, and good
24  * short range reception when required for learning a signal.
25  *
26  * http://www.redrat.co.uk/
27  *
28  * It uses its own little protocol to communicate, the required
29  * parts of which are embedded within this driver.
30  * --
31  *
32  * This program is free software; you can redistribute it and/or modify
33  * it under the terms of the GNU General Public License as published by
34  * the Free Software Foundation; either version 2 of the License, or
35  * (at your option) any later version.
36  *
37  * This program is distributed in the hope that it will be useful,
38  * but WITHOUT ANY WARRANTY; without even the implied warranty of
39  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
40  * GNU General Public License for more details.
41  *
42  * You should have received a copy of the GNU General Public License
43  * along with this program; if not, write to the Free Software
44  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
45  *
46  */
47
48 #include <asm/unaligned.h>
49 #include <linux/device.h>
50 #include <linux/leds.h>
51 #include <linux/module.h>
52 #include <linux/slab.h>
53 #include <linux/usb.h>
54 #include <linux/usb/input.h>
55 #include <media/rc-core.h>
56
57 /* Driver Information */
58 #define DRIVER_AUTHOR "Jarod Wilson <jarod@redhat.com>"
59 #define DRIVER_AUTHOR2 "The Dweller, Stephen Cox"
60 #define DRIVER_DESC "RedRat3 USB IR Transceiver Driver"
61 #define DRIVER_NAME "redrat3"
62
63 /* module parameters */
64 #ifdef CONFIG_USB_DEBUG
65 static int debug = 1;
66 #else
67 static int debug;
68 #endif
69
70 #define RR3_DEBUG_STANDARD              0x1
71 #define RR3_DEBUG_FUNCTION_TRACE        0x2
72
73 #define rr3_dbg(dev, fmt, ...)                                  \
74         do {                                                    \
75                 if (debug & RR3_DEBUG_STANDARD)                 \
76                         dev_info(dev, fmt, ## __VA_ARGS__);     \
77         } while (0)
78
79 /* bulk data transfer types */
80 #define RR3_ERROR               0x01
81 #define RR3_MOD_SIGNAL_IN       0x20
82 #define RR3_MOD_SIGNAL_OUT      0x21
83
84 /* Get the RR firmware version */
85 #define RR3_FW_VERSION          0xb1
86 #define RR3_FW_VERSION_LEN      64
87 /* Send encoded signal bulk-sent earlier*/
88 #define RR3_TX_SEND_SIGNAL      0xb3
89 #define RR3_SET_IR_PARAM        0xb7
90 #define RR3_GET_IR_PARAM        0xb8
91 /* Blink the red LED on the device */
92 #define RR3_BLINK_LED           0xb9
93 /* Read serial number of device */
94 #define RR3_READ_SER_NO         0xba
95 #define RR3_SER_NO_LEN          4
96 /* Start capture with the RC receiver */
97 #define RR3_RC_DET_ENABLE       0xbb
98 /* Stop capture with the RC receiver */
99 #define RR3_RC_DET_DISABLE      0xbc
100 /* Return the status of RC detector capture */
101 #define RR3_RC_DET_STATUS       0xbd
102 /* Reset redrat */
103 #define RR3_RESET               0xa0
104
105 /* Max number of lengths in the signal. */
106 #define RR3_IR_IO_MAX_LENGTHS   0x01
107 /* Periods to measure mod. freq. */
108 #define RR3_IR_IO_PERIODS_MF    0x02
109 /* Size of memory for main signal data */
110 #define RR3_IR_IO_SIG_MEM_SIZE  0x03
111 /* Delta value when measuring lengths */
112 #define RR3_IR_IO_LENGTH_FUZZ   0x04
113 /* Timeout for end of signal detection */
114 #define RR3_IR_IO_SIG_TIMEOUT   0x05
115 /* Minimum value for pause recognition. */
116 #define RR3_IR_IO_MIN_PAUSE     0x06
117
118 /* Clock freq. of EZ-USB chip */
119 #define RR3_CLK                 24000000
120 /* Clock periods per timer count */
121 #define RR3_CLK_PER_COUNT       12
122 /* (RR3_CLK / RR3_CLK_PER_COUNT) */
123 #define RR3_CLK_CONV_FACTOR     2000000
124 /* USB bulk-in IR data endpoint address */
125 #define RR3_BULK_IN_EP_ADDR     0x82
126
127 /* Size of the fixed-length portion of the signal */
128 #define RR3_DRIVER_MAXLENS      128
129 #define RR3_MAX_SIG_SIZE        512
130 #define RR3_TIME_UNIT           50
131 #define RR3_END_OF_SIGNAL       0x7f
132 #define RR3_TX_TRAILER_LEN      2
133 #define RR3_RX_MIN_TIMEOUT      5
134 #define RR3_RX_MAX_TIMEOUT      2000
135
136 /* The 8051's CPUCS Register address */
137 #define RR3_CPUCS_REG_ADDR      0x7f92
138
139 #define USB_RR3USB_VENDOR_ID    0x112a
140 #define USB_RR3USB_PRODUCT_ID   0x0001
141 #define USB_RR3IIUSB_PRODUCT_ID 0x0005
142
143 struct redrat3_header {
144         __be16 length;
145         __be16 transfer_type;
146 } __packed;
147
148 /* sending and receiving irdata */
149 struct redrat3_irdata {
150         struct redrat3_header header;
151         __be32 pause;
152         __be16 mod_freq_count;
153         __be16 num_periods;
154         __u8 max_lengths;
155         __u8 no_lengths;
156         __be16 max_sig_size;
157         __be16 sig_size;
158         __u8 no_repeats;
159         __be16 lens[RR3_DRIVER_MAXLENS]; /* not aligned */
160         __u8 sigdata[RR3_MAX_SIG_SIZE];
161 } __packed;
162
163 /* firmware errors */
164 struct redrat3_error {
165         struct redrat3_header header;
166         __be16 fw_error;
167 } __packed;
168
169 /* table of devices that work with this driver */
170 static struct usb_device_id redrat3_dev_table[] = {
171         /* Original version of the RedRat3 */
172         {USB_DEVICE(USB_RR3USB_VENDOR_ID, USB_RR3USB_PRODUCT_ID)},
173         /* Second Version/release of the RedRat3 - RetRat3-II */
174         {USB_DEVICE(USB_RR3USB_VENDOR_ID, USB_RR3IIUSB_PRODUCT_ID)},
175         {}                      /* Terminating entry */
176 };
177
178 /* Structure to hold all of our device specific stuff */
179 struct redrat3_dev {
180         /* core device bits */
181         struct rc_dev *rc;
182         struct device *dev;
183
184         /* led control */
185         struct led_classdev led;
186         atomic_t flash;
187         struct usb_ctrlrequest flash_control;
188         struct urb *flash_urb;
189         u8 flash_in_buf;
190
191         /* save off the usb device pointer */
192         struct usb_device *udev;
193
194         /* the receive endpoint */
195         struct usb_endpoint_descriptor *ep_in;
196         /* the buffer to receive data */
197         void *bulk_in_buf;
198         /* urb used to read ir data */
199         struct urb *read_urb;
200
201         /* the send endpoint */
202         struct usb_endpoint_descriptor *ep_out;
203
204         /* usb dma */
205         dma_addr_t dma_in;
206
207         /* rx signal timeout timer */
208         struct timer_list rx_timeout;
209         u32 hw_timeout;
210
211         /* Is the device currently transmitting?*/
212         bool transmitting;
213
214         /* store for current packet */
215         struct redrat3_irdata irdata;
216         u16 bytes_read;
217
218         u32 carrier;
219
220         char name[64];
221         char phys[64];
222 };
223
224 /*
225  * redrat3_issue_async
226  *
227  *  Issues an async read to the ir data in port..
228  *  sets the callback to be redrat3_handle_async
229  */
230 static void redrat3_issue_async(struct redrat3_dev *rr3)
231 {
232         int res;
233
234         res = usb_submit_urb(rr3->read_urb, GFP_ATOMIC);
235         if (res)
236                 rr3_dbg(rr3->dev, "%s: receive request FAILED! "
237                         "(res %d, len %d)\n", __func__, res,
238                         rr3->read_urb->transfer_buffer_length);
239 }
240
241 static void redrat3_dump_fw_error(struct redrat3_dev *rr3, int code)
242 {
243         if (!rr3->transmitting && (code != 0x40))
244                 dev_info(rr3->dev, "fw error code 0x%02x: ", code);
245
246         switch (code) {
247         case 0x00:
248                 pr_cont("No Error\n");
249                 break;
250
251         /* Codes 0x20 through 0x2f are IR Firmware Errors */
252         case 0x20:
253                 pr_cont("Initial signal pulse not long enough "
254                         "to measure carrier frequency\n");
255                 break;
256         case 0x21:
257                 pr_cont("Not enough length values allocated for signal\n");
258                 break;
259         case 0x22:
260                 pr_cont("Not enough memory allocated for signal data\n");
261                 break;
262         case 0x23:
263                 pr_cont("Too many signal repeats\n");
264                 break;
265         case 0x28:
266                 pr_cont("Insufficient memory available for IR signal "
267                         "data memory allocation\n");
268                 break;
269         case 0x29:
270                 pr_cont("Insufficient memory available "
271                         "for IrDa signal data memory allocation\n");
272                 break;
273
274         /* Codes 0x30 through 0x3f are USB Firmware Errors */
275         case 0x30:
276                 pr_cont("Insufficient memory available for bulk "
277                         "transfer structure\n");
278                 break;
279
280         /*
281          * Other error codes... These are primarily errors that can occur in
282          * the control messages sent to the redrat
283          */
284         case 0x40:
285                 if (!rr3->transmitting)
286                         pr_cont("Signal capture has been terminated\n");
287                 break;
288         case 0x41:
289                 pr_cont("Attempt to set/get and unknown signal I/O "
290                         "algorithm parameter\n");
291                 break;
292         case 0x42:
293                 pr_cont("Signal capture already started\n");
294                 break;
295
296         default:
297                 pr_cont("Unknown Error\n");
298                 break;
299         }
300 }
301
302 static u32 redrat3_val_to_mod_freq(struct redrat3_irdata *irdata)
303 {
304         u32 mod_freq = 0;
305         u16 mod_freq_count = be16_to_cpu(irdata->mod_freq_count);
306
307         if (mod_freq_count != 0)
308                 mod_freq = (RR3_CLK * be16_to_cpu(irdata->num_periods)) /
309                         (mod_freq_count * RR3_CLK_PER_COUNT);
310
311         return mod_freq;
312 }
313
314 /* this function scales down the figures for the same result... */
315 static u32 redrat3_len_to_us(u32 length)
316 {
317         u32 biglen = length * 1000;
318         u32 divisor = (RR3_CLK_CONV_FACTOR) / 1000;
319         u32 result = (u32) (biglen / divisor);
320
321         /* don't allow zero lengths to go back, breaks lirc */
322         return result ? result : 1;
323 }
324
325 /*
326  * convert us back into redrat3 lengths
327  *
328  * length * 1000   length * 1000000
329  * ------------- = ---------------- = micro
330  * rr3clk / 1000       rr3clk
331
332  * 6 * 2       4 * 3        micro * rr3clk          micro * rr3clk / 1000
333  * ----- = 4   ----- = 6    -------------- = len    ---------------------
334  *   3           2             1000000                    1000
335  */
336 static u32 redrat3_us_to_len(u32 microsec)
337 {
338         u32 result;
339         u32 divisor;
340
341         microsec &= IR_MAX_DURATION;
342         divisor = (RR3_CLK_CONV_FACTOR / 1000);
343         result = (u32)(microsec * divisor) / 1000;
344
345         /* don't allow zero lengths to go back, breaks lirc */
346         return result ? result : 1;
347 }
348
349 /* timer callback to send reset event */
350 static void redrat3_rx_timeout(unsigned long data)
351 {
352         struct redrat3_dev *rr3 = (struct redrat3_dev *)data;
353
354         rr3_dbg(rr3->dev, "calling ir_raw_event_reset\n");
355         ir_raw_event_reset(rr3->rc);
356 }
357
358 static void redrat3_process_ir_data(struct redrat3_dev *rr3)
359 {
360         DEFINE_IR_RAW_EVENT(rawir);
361         struct device *dev;
362         unsigned i, trailer = 0;
363         unsigned sig_size, single_len, offset, val;
364         unsigned long delay;
365         u32 mod_freq;
366
367         if (!rr3) {
368                 pr_err("%s called with no context!\n", __func__);
369                 return;
370         }
371
372         dev = rr3->dev;
373
374         /* Make sure we reset the IR kfifo after a bit of inactivity */
375         delay = usecs_to_jiffies(rr3->hw_timeout);
376         mod_timer(&rr3->rx_timeout, jiffies + delay);
377
378         mod_freq = redrat3_val_to_mod_freq(&rr3->irdata);
379         rr3_dbg(dev, "Got mod_freq of %u\n", mod_freq);
380
381         /* process each rr3 encoded byte into an int */
382         sig_size = be16_to_cpu(rr3->irdata.sig_size);
383         for (i = 0; i < sig_size; i++) {
384                 offset = rr3->irdata.sigdata[i];
385                 val = get_unaligned_be16(&rr3->irdata.lens[offset]);
386                 single_len = redrat3_len_to_us(val);
387
388                 /* we should always get pulse/space/pulse/space samples */
389                 if (i % 2)
390                         rawir.pulse = false;
391                 else
392                         rawir.pulse = true;
393
394                 rawir.duration = US_TO_NS(single_len);
395                 /* Save initial pulse length to fudge trailer */
396                 if (i == 0)
397                         trailer = rawir.duration;
398                 /* cap the value to IR_MAX_DURATION */
399                 rawir.duration &= IR_MAX_DURATION;
400
401                 rr3_dbg(dev, "storing %s with duration %d (i: %d)\n",
402                         rawir.pulse ? "pulse" : "space", rawir.duration, i);
403                 ir_raw_event_store_with_filter(rr3->rc, &rawir);
404         }
405
406         /* add a trailing space, if need be */
407         if (i % 2) {
408                 rawir.pulse = false;
409                 /* this duration is made up, and may not be ideal... */
410                 if (trailer < US_TO_NS(1000))
411                         rawir.duration = US_TO_NS(2800);
412                 else
413                         rawir.duration = trailer;
414                 rr3_dbg(dev, "storing trailing space with duration %d\n",
415                         rawir.duration);
416                 ir_raw_event_store_with_filter(rr3->rc, &rawir);
417         }
418
419         rr3_dbg(dev, "calling ir_raw_event_handle\n");
420         ir_raw_event_handle(rr3->rc);
421 }
422
423 /* Util fn to send rr3 cmds */
424 static u8 redrat3_send_cmd(int cmd, struct redrat3_dev *rr3)
425 {
426         struct usb_device *udev;
427         u8 *data;
428         int res;
429
430         data = kzalloc(sizeof(u8), GFP_KERNEL);
431         if (!data)
432                 return -ENOMEM;
433
434         udev = rr3->udev;
435         res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), cmd,
436                               USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
437                               0x0000, 0x0000, data, sizeof(u8), HZ * 10);
438
439         if (res < 0) {
440                 dev_err(rr3->dev, "%s: Error sending rr3 cmd res %d, data %d",
441                         __func__, res, *data);
442                 res = -EIO;
443         } else
444                 res = data[0];
445
446         kfree(data);
447
448         return res;
449 }
450
451 /* Enables the long range detector and starts async receive */
452 static int redrat3_enable_detector(struct redrat3_dev *rr3)
453 {
454         struct device *dev = rr3->dev;
455         u8 ret;
456
457         ret = redrat3_send_cmd(RR3_RC_DET_ENABLE, rr3);
458         if (ret != 0)
459                 dev_dbg(dev, "%s: unexpected ret of %d\n",
460                         __func__, ret);
461
462         ret = redrat3_send_cmd(RR3_RC_DET_STATUS, rr3);
463         if (ret != 1) {
464                 dev_err(dev, "%s: detector status: %d, should be 1\n",
465                         __func__, ret);
466                 return -EIO;
467         }
468
469         redrat3_issue_async(rr3);
470
471         return 0;
472 }
473
474 static inline void redrat3_delete(struct redrat3_dev *rr3,
475                                   struct usb_device *udev)
476 {
477         usb_kill_urb(rr3->read_urb);
478         usb_kill_urb(rr3->flash_urb);
479         usb_free_urb(rr3->read_urb);
480         usb_free_urb(rr3->flash_urb);
481         usb_free_coherent(udev, le16_to_cpu(rr3->ep_in->wMaxPacketSize),
482                           rr3->bulk_in_buf, rr3->dma_in);
483
484         kfree(rr3);
485 }
486
487 static u32 redrat3_get_timeout(struct redrat3_dev *rr3)
488 {
489         __be32 *tmp;
490         u32 timeout = MS_TO_US(150); /* a sane default, if things go haywire */
491         int len, ret, pipe;
492
493         len = sizeof(*tmp);
494         tmp = kzalloc(len, GFP_KERNEL);
495         if (!tmp) {
496                 dev_warn(rr3->dev, "Memory allocation faillure\n");
497                 return timeout;
498         }
499
500         pipe = usb_rcvctrlpipe(rr3->udev, 0);
501         ret = usb_control_msg(rr3->udev, pipe, RR3_GET_IR_PARAM,
502                               USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
503                               RR3_IR_IO_SIG_TIMEOUT, 0, tmp, len, HZ * 5);
504         if (ret != len)
505                 dev_warn(rr3->dev, "Failed to read timeout from hardware\n");
506         else {
507                 timeout = redrat3_len_to_us(be32_to_cpup(tmp));
508
509                 rr3_dbg(rr3->dev, "Got timeout of %d ms\n", timeout / 1000);
510         }
511
512         kfree(tmp);
513
514         return timeout;
515 }
516
517 static void redrat3_reset(struct redrat3_dev *rr3)
518 {
519         struct usb_device *udev = rr3->udev;
520         struct device *dev = rr3->dev;
521         int rc, rxpipe, txpipe;
522         u8 *val;
523         int len = sizeof(u8);
524
525         rxpipe = usb_rcvctrlpipe(udev, 0);
526         txpipe = usb_sndctrlpipe(udev, 0);
527
528         val = kmalloc(len, GFP_KERNEL);
529         if (!val) {
530                 dev_err(dev, "Memory allocation failure\n");
531                 return;
532         }
533
534         *val = 0x01;
535         rc = usb_control_msg(udev, rxpipe, RR3_RESET,
536                              USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
537                              RR3_CPUCS_REG_ADDR, 0, val, len, HZ * 25);
538         rr3_dbg(dev, "reset returned 0x%02x\n", rc);
539
540         *val = 5;
541         rc = usb_control_msg(udev, txpipe, RR3_SET_IR_PARAM,
542                              USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
543                              RR3_IR_IO_LENGTH_FUZZ, 0, val, len, HZ * 25);
544         rr3_dbg(dev, "set ir parm len fuzz %d rc 0x%02x\n", *val, rc);
545
546         *val = RR3_DRIVER_MAXLENS;
547         rc = usb_control_msg(udev, txpipe, RR3_SET_IR_PARAM,
548                              USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
549                              RR3_IR_IO_MAX_LENGTHS, 0, val, len, HZ * 25);
550         rr3_dbg(dev, "set ir parm max lens %d rc 0x%02x\n", *val, rc);
551
552         kfree(val);
553 }
554
555 static void redrat3_get_firmware_rev(struct redrat3_dev *rr3)
556 {
557         int rc = 0;
558         char *buffer;
559
560         buffer = kzalloc(sizeof(char) * (RR3_FW_VERSION_LEN + 1), GFP_KERNEL);
561         if (!buffer) {
562                 dev_err(rr3->dev, "Memory allocation failure\n");
563                 return;
564         }
565
566         rc = usb_control_msg(rr3->udev, usb_rcvctrlpipe(rr3->udev, 0),
567                              RR3_FW_VERSION,
568                              USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
569                              0, 0, buffer, RR3_FW_VERSION_LEN, HZ * 5);
570
571         if (rc >= 0)
572                 dev_info(rr3->dev, "Firmware rev: %s", buffer);
573         else
574                 dev_err(rr3->dev, "Problem fetching firmware ID\n");
575
576         kfree(buffer);
577 }
578
579 static void redrat3_read_packet_start(struct redrat3_dev *rr3, unsigned len)
580 {
581         struct redrat3_header *header = rr3->bulk_in_buf;
582         unsigned pktlen, pkttype;
583
584         /* grab the Length and type of transfer */
585         pktlen = be16_to_cpu(header->length);
586         pkttype = be16_to_cpu(header->transfer_type);
587
588         if (pktlen > sizeof(rr3->irdata)) {
589                 dev_warn(rr3->dev, "packet length %u too large\n", pktlen);
590                 return;
591         }
592
593         switch (pkttype) {
594         case RR3_ERROR:
595                 if (len >= sizeof(struct redrat3_error)) {
596                         struct redrat3_error *error = rr3->bulk_in_buf;
597                         unsigned fw_error = be16_to_cpu(error->fw_error);
598                         redrat3_dump_fw_error(rr3, fw_error);
599                 }
600                 break;
601
602         case RR3_MOD_SIGNAL_IN:
603                 memcpy(&rr3->irdata, rr3->bulk_in_buf, len);
604                 rr3->bytes_read = len;
605                 rr3_dbg(rr3->dev, "bytes_read %d, pktlen %d\n",
606                         rr3->bytes_read, pktlen);
607                 break;
608
609         default:
610                 rr3_dbg(rr3->dev, "ignoring packet with type 0x%02x, len of %d, 0x%02x\n",
611                                                 pkttype, len, pktlen);
612                 break;
613         }
614 }
615
616 static void redrat3_read_packet_continue(struct redrat3_dev *rr3, unsigned len)
617 {
618         void *irdata = &rr3->irdata;
619
620         if (len + rr3->bytes_read > sizeof(rr3->irdata)) {
621                 dev_warn(rr3->dev, "too much data for packet\n");
622                 rr3->bytes_read = 0;
623                 return;
624         }
625
626         memcpy(irdata + rr3->bytes_read, rr3->bulk_in_buf, len);
627
628         rr3->bytes_read += len;
629         rr3_dbg(rr3->dev, "bytes_read %d, pktlen %d\n", rr3->bytes_read,
630                                  be16_to_cpu(rr3->irdata.header.length));
631 }
632
633 /* gather IR data from incoming urb, process it when we have enough */
634 static int redrat3_get_ir_data(struct redrat3_dev *rr3, unsigned len)
635 {
636         struct device *dev = rr3->dev;
637         unsigned pkttype;
638         int ret = 0;
639
640         if (rr3->bytes_read == 0 && len >= sizeof(struct redrat3_header)) {
641                 redrat3_read_packet_start(rr3, len);
642         } else if (rr3->bytes_read != 0) {
643                 redrat3_read_packet_continue(rr3, len);
644         } else if (rr3->bytes_read == 0) {
645                 dev_err(dev, "error: no packet data read\n");
646                 ret = -ENODATA;
647                 goto out;
648         }
649
650         if (rr3->bytes_read < be16_to_cpu(rr3->irdata.header.length) +
651                                                 sizeof(struct redrat3_header))
652                 /* we're still accumulating data */
653                 return 0;
654
655         /* if we get here, we've got IR data to decode */
656         pkttype = be16_to_cpu(rr3->irdata.header.transfer_type);
657         if (pkttype == RR3_MOD_SIGNAL_IN)
658                 redrat3_process_ir_data(rr3);
659         else
660                 rr3_dbg(dev, "discarding non-signal data packet (type 0x%02x)\n",
661                                                                 pkttype);
662
663 out:
664         rr3->bytes_read = 0;
665         return ret;
666 }
667
668 /* callback function from USB when async USB request has completed */
669 static void redrat3_handle_async(struct urb *urb)
670 {
671         struct redrat3_dev *rr3;
672         int ret;
673
674         if (!urb)
675                 return;
676
677         rr3 = urb->context;
678         if (!rr3) {
679                 pr_err("%s called with invalid context!\n", __func__);
680                 usb_unlink_urb(urb);
681                 return;
682         }
683
684         switch (urb->status) {
685         case 0:
686                 ret = redrat3_get_ir_data(rr3, urb->actual_length);
687                 if (!ret) {
688                         /* no error, prepare to read more */
689                         redrat3_issue_async(rr3);
690                 }
691                 break;
692
693         case -ECONNRESET:
694         case -ENOENT:
695         case -ESHUTDOWN:
696                 usb_unlink_urb(urb);
697                 return;
698
699         case -EPIPE:
700         default:
701                 dev_warn(rr3->dev, "Error: urb status = %d\n", urb->status);
702                 rr3->bytes_read = 0;
703                 break;
704         }
705 }
706
707 static u16 mod_freq_to_val(unsigned int mod_freq)
708 {
709         int mult = 6000000;
710
711         /* Clk used in mod. freq. generation is CLK24/4. */
712         return 65536 - (mult / mod_freq);
713 }
714
715 static int redrat3_set_tx_carrier(struct rc_dev *rcdev, u32 carrier)
716 {
717         struct redrat3_dev *rr3 = rcdev->priv;
718         struct device *dev = rr3->dev;
719
720         rr3_dbg(dev, "Setting modulation frequency to %u", carrier);
721         if (carrier == 0)
722                 return -EINVAL;
723
724         rr3->carrier = carrier;
725
726         return carrier;
727 }
728
729 static int redrat3_transmit_ir(struct rc_dev *rcdev, unsigned *txbuf,
730                                 unsigned count)
731 {
732         struct redrat3_dev *rr3 = rcdev->priv;
733         struct device *dev = rr3->dev;
734         struct redrat3_irdata *irdata = NULL;
735         int ret, ret_len;
736         int lencheck, cur_sample_len, pipe;
737         int *sample_lens = NULL;
738         u8 curlencheck = 0;
739         unsigned i, sendbuf_len;
740
741         if (rr3->transmitting) {
742                 dev_warn(dev, "%s: transmitter already in use\n", __func__);
743                 return -EAGAIN;
744         }
745
746         if (count > RR3_MAX_SIG_SIZE - RR3_TX_TRAILER_LEN)
747                 return -EINVAL;
748
749         /* rr3 will disable rc detector on transmit */
750         rr3->transmitting = true;
751
752         sample_lens = kzalloc(sizeof(int) * RR3_DRIVER_MAXLENS, GFP_KERNEL);
753         if (!sample_lens) {
754                 ret = -ENOMEM;
755                 goto out;
756         }
757
758         irdata = kzalloc(sizeof(*irdata), GFP_KERNEL);
759         if (!irdata) {
760                 ret = -ENOMEM;
761                 goto out;
762         }
763
764         for (i = 0; i < count; i++) {
765                 cur_sample_len = redrat3_us_to_len(txbuf[i]);
766                 if (cur_sample_len > 0xffff) {
767                         dev_warn(dev, "transmit period of %uus truncated to %uus\n",
768                                         txbuf[i], redrat3_len_to_us(0xffff));
769                         cur_sample_len = 0xffff;
770                 }
771                 for (lencheck = 0; lencheck < curlencheck; lencheck++) {
772                         if (sample_lens[lencheck] == cur_sample_len)
773                                 break;
774                 }
775                 if (lencheck == curlencheck) {
776                         rr3_dbg(dev, "txbuf[%d]=%u, pos %d, enc %u\n",
777                                 i, txbuf[i], curlencheck, cur_sample_len);
778                         if (curlencheck < RR3_DRIVER_MAXLENS) {
779                                 /* now convert the value to a proper
780                                  * rr3 value.. */
781                                 sample_lens[curlencheck] = cur_sample_len;
782                                 put_unaligned_be16(cur_sample_len,
783                                                 &irdata->lens[curlencheck]);
784                                 curlencheck++;
785                         } else {
786                                 ret = -EINVAL;
787                                 goto out;
788                         }
789                 }
790                 irdata->sigdata[i] = lencheck;
791         }
792
793         irdata->sigdata[count] = RR3_END_OF_SIGNAL;
794         irdata->sigdata[count + 1] = RR3_END_OF_SIGNAL;
795
796         sendbuf_len = offsetof(struct redrat3_irdata,
797                                         sigdata[count + RR3_TX_TRAILER_LEN]);
798         /* fill in our packet header */
799         irdata->header.length = cpu_to_be16(sendbuf_len -
800                                                 sizeof(struct redrat3_header));
801         irdata->header.transfer_type = cpu_to_be16(RR3_MOD_SIGNAL_OUT);
802         irdata->pause = cpu_to_be32(redrat3_len_to_us(100));
803         irdata->mod_freq_count = cpu_to_be16(mod_freq_to_val(rr3->carrier));
804         irdata->no_lengths = curlencheck;
805         irdata->sig_size = cpu_to_be16(count + RR3_TX_TRAILER_LEN);
806
807         pipe = usb_sndbulkpipe(rr3->udev, rr3->ep_out->bEndpointAddress);
808         ret = usb_bulk_msg(rr3->udev, pipe, irdata,
809                             sendbuf_len, &ret_len, 10 * HZ);
810         rr3_dbg(dev, "sent %d bytes, (ret %d)\n", ret_len, ret);
811
812         /* now tell the hardware to transmit what we sent it */
813         pipe = usb_rcvctrlpipe(rr3->udev, 0);
814         ret = usb_control_msg(rr3->udev, pipe, RR3_TX_SEND_SIGNAL,
815                               USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
816                               0, 0, irdata, 2, HZ * 10);
817
818         if (ret < 0)
819                 dev_err(dev, "Error: control msg send failed, rc %d\n", ret);
820         else
821                 ret = count;
822
823 out:
824         kfree(sample_lens);
825         kfree(irdata);
826
827         rr3->transmitting = false;
828         /* rr3 re-enables rc detector because it was enabled before */
829
830         return ret;
831 }
832
833 static void redrat3_brightness_set(struct led_classdev *led_dev, enum
834                                                 led_brightness brightness)
835 {
836         struct redrat3_dev *rr3 = container_of(led_dev, struct redrat3_dev,
837                                                                         led);
838
839         if (brightness != LED_OFF && atomic_cmpxchg(&rr3->flash, 0, 1) == 0) {
840                 int ret = usb_submit_urb(rr3->flash_urb, GFP_ATOMIC);
841                 if (ret != 0) {
842                         dev_dbg(rr3->dev, "%s: unexpected ret of %d\n",
843                                 __func__, ret);
844                         atomic_set(&rr3->flash, 0);
845                 }
846         }
847 }
848
849 static void redrat3_led_complete(struct urb *urb)
850 {
851         struct redrat3_dev *rr3 = urb->context;
852
853         switch (urb->status) {
854         case 0:
855                 break;
856         case -ECONNRESET:
857         case -ENOENT:
858         case -ESHUTDOWN:
859                 usb_unlink_urb(urb);
860                 return;
861         case -EPIPE:
862         default:
863                 dev_dbg(rr3->dev, "Error: urb status = %d\n", urb->status);
864                 break;
865         }
866
867         rr3->led.brightness = LED_OFF;
868         atomic_dec(&rr3->flash);
869 }
870
871 static struct rc_dev *redrat3_init_rc_dev(struct redrat3_dev *rr3)
872 {
873         struct device *dev = rr3->dev;
874         struct rc_dev *rc;
875         int ret = -ENODEV;
876         u16 prod = le16_to_cpu(rr3->udev->descriptor.idProduct);
877
878         rc = rc_allocate_device();
879         if (!rc) {
880                 dev_err(dev, "remote input dev allocation failed\n");
881                 goto out;
882         }
883
884         snprintf(rr3->name, sizeof(rr3->name), "RedRat3%s "
885                  "Infrared Remote Transceiver (%04x:%04x)",
886                  prod == USB_RR3IIUSB_PRODUCT_ID ? "-II" : "",
887                  le16_to_cpu(rr3->udev->descriptor.idVendor), prod);
888
889         usb_make_path(rr3->udev, rr3->phys, sizeof(rr3->phys));
890
891         rc->input_name = rr3->name;
892         rc->input_phys = rr3->phys;
893         usb_to_input_id(rr3->udev, &rc->input_id);
894         rc->dev.parent = dev;
895         rc->priv = rr3;
896         rc->driver_type = RC_DRIVER_IR_RAW;
897         rc_set_allowed_protocols(rc, RC_BIT_ALL);
898         rc->timeout = US_TO_NS(2750);
899         rc->tx_ir = redrat3_transmit_ir;
900         rc->s_tx_carrier = redrat3_set_tx_carrier;
901         rc->driver_name = DRIVER_NAME;
902         rc->rx_resolution = US_TO_NS(2);
903         rc->map_name = RC_MAP_HAUPPAUGE;
904
905         ret = rc_register_device(rc);
906         if (ret < 0) {
907                 dev_err(dev, "remote dev registration failed\n");
908                 goto out;
909         }
910
911         return rc;
912
913 out:
914         rc_free_device(rc);
915         return NULL;
916 }
917
918 static int redrat3_dev_probe(struct usb_interface *intf,
919                              const struct usb_device_id *id)
920 {
921         struct usb_device *udev = interface_to_usbdev(intf);
922         struct device *dev = &intf->dev;
923         struct usb_host_interface *uhi;
924         struct redrat3_dev *rr3;
925         struct usb_endpoint_descriptor *ep;
926         struct usb_endpoint_descriptor *ep_in = NULL;
927         struct usb_endpoint_descriptor *ep_out = NULL;
928         u8 addr, attrs;
929         int pipe, i;
930         int retval = -ENOMEM;
931
932         uhi = intf->cur_altsetting;
933
934         /* find our bulk-in and bulk-out endpoints */
935         for (i = 0; i < uhi->desc.bNumEndpoints; ++i) {
936                 ep = &uhi->endpoint[i].desc;
937                 addr = ep->bEndpointAddress;
938                 attrs = ep->bmAttributes;
939
940                 if ((ep_in == NULL) &&
941                     ((addr & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN) &&
942                     ((attrs & USB_ENDPOINT_XFERTYPE_MASK) ==
943                      USB_ENDPOINT_XFER_BULK)) {
944                         rr3_dbg(dev, "found bulk-in endpoint at 0x%02x\n",
945                                 ep->bEndpointAddress);
946                         /* data comes in on 0x82, 0x81 is for other data... */
947                         if (ep->bEndpointAddress == RR3_BULK_IN_EP_ADDR)
948                                 ep_in = ep;
949                 }
950
951                 if ((ep_out == NULL) &&
952                     ((addr & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) &&
953                     ((attrs & USB_ENDPOINT_XFERTYPE_MASK) ==
954                      USB_ENDPOINT_XFER_BULK)) {
955                         rr3_dbg(dev, "found bulk-out endpoint at 0x%02x\n",
956                                 ep->bEndpointAddress);
957                         ep_out = ep;
958                 }
959         }
960
961         if (!ep_in || !ep_out) {
962                 dev_err(dev, "Couldn't find both in and out endpoints\n");
963                 retval = -ENODEV;
964                 goto no_endpoints;
965         }
966
967         /* allocate memory for our device state and initialize it */
968         rr3 = kzalloc(sizeof(*rr3), GFP_KERNEL);
969         if (rr3 == NULL) {
970                 dev_err(dev, "Memory allocation failure\n");
971                 goto no_endpoints;
972         }
973
974         rr3->dev = &intf->dev;
975
976         /* set up bulk-in endpoint */
977         rr3->read_urb = usb_alloc_urb(0, GFP_KERNEL);
978         if (!rr3->read_urb) {
979                 dev_err(dev, "Read urb allocation failure\n");
980                 goto error;
981         }
982
983         rr3->ep_in = ep_in;
984         rr3->bulk_in_buf = usb_alloc_coherent(udev,
985                 le16_to_cpu(ep_in->wMaxPacketSize), GFP_ATOMIC, &rr3->dma_in);
986         if (!rr3->bulk_in_buf) {
987                 dev_err(dev, "Read buffer allocation failure\n");
988                 goto error;
989         }
990
991         pipe = usb_rcvbulkpipe(udev, ep_in->bEndpointAddress);
992         usb_fill_bulk_urb(rr3->read_urb, udev, pipe, rr3->bulk_in_buf,
993                 le16_to_cpu(ep_in->wMaxPacketSize), redrat3_handle_async, rr3);
994
995         rr3->ep_out = ep_out;
996         rr3->udev = udev;
997
998         redrat3_reset(rr3);
999         redrat3_get_firmware_rev(rr3);
1000
1001         /* might be all we need to do? */
1002         retval = redrat3_enable_detector(rr3);
1003         if (retval < 0)
1004                 goto error;
1005
1006         /* store current hardware timeout, in us, will use for kfifo resets */
1007         rr3->hw_timeout = redrat3_get_timeout(rr3);
1008
1009         /* default.. will get overridden by any sends with a freq defined */
1010         rr3->carrier = 38000;
1011
1012         /* led control */
1013         rr3->led.name = "redrat3:red:feedback";
1014         rr3->led.default_trigger = "rc-feedback";
1015         rr3->led.brightness_set = redrat3_brightness_set;
1016         retval = led_classdev_register(&intf->dev, &rr3->led);
1017         if (retval)
1018                 goto error;
1019
1020         atomic_set(&rr3->flash, 0);
1021         rr3->flash_urb = usb_alloc_urb(0, GFP_KERNEL);
1022         if (!rr3->flash_urb) {
1023                 retval = -ENOMEM;
1024                 goto led_free_error;
1025         }
1026
1027         /* setup packet is 'c0 b9 0000 0000 0001' */
1028         rr3->flash_control.bRequestType = 0xc0;
1029         rr3->flash_control.bRequest = RR3_BLINK_LED;
1030         rr3->flash_control.wLength = cpu_to_le16(1);
1031
1032         usb_fill_control_urb(rr3->flash_urb, udev, usb_rcvctrlpipe(udev, 0),
1033                         (unsigned char *)&rr3->flash_control,
1034                         &rr3->flash_in_buf, sizeof(rr3->flash_in_buf),
1035                         redrat3_led_complete, rr3);
1036
1037         rr3->rc = redrat3_init_rc_dev(rr3);
1038         if (!rr3->rc) {
1039                 retval = -ENOMEM;
1040                 goto led_free_error;
1041         }
1042         setup_timer(&rr3->rx_timeout, redrat3_rx_timeout, (unsigned long)rr3);
1043
1044         /* we can register the device now, as it is ready */
1045         usb_set_intfdata(intf, rr3);
1046
1047         return 0;
1048
1049 led_free_error:
1050         led_classdev_unregister(&rr3->led);
1051 error:
1052         redrat3_delete(rr3, rr3->udev);
1053
1054 no_endpoints:
1055         dev_err(dev, "%s: retval = %x", __func__, retval);
1056
1057         return retval;
1058 }
1059
1060 static void redrat3_dev_disconnect(struct usb_interface *intf)
1061 {
1062         struct usb_device *udev = interface_to_usbdev(intf);
1063         struct redrat3_dev *rr3 = usb_get_intfdata(intf);
1064
1065         if (!rr3)
1066                 return;
1067
1068         usb_set_intfdata(intf, NULL);
1069         rc_unregister_device(rr3->rc);
1070         led_classdev_unregister(&rr3->led);
1071         del_timer_sync(&rr3->rx_timeout);
1072         redrat3_delete(rr3, udev);
1073 }
1074
1075 static int redrat3_dev_suspend(struct usb_interface *intf, pm_message_t message)
1076 {
1077         struct redrat3_dev *rr3 = usb_get_intfdata(intf);
1078
1079         led_classdev_suspend(&rr3->led);
1080         usb_kill_urb(rr3->read_urb);
1081         usb_kill_urb(rr3->flash_urb);
1082         return 0;
1083 }
1084
1085 static int redrat3_dev_resume(struct usb_interface *intf)
1086 {
1087         struct redrat3_dev *rr3 = usb_get_intfdata(intf);
1088
1089         if (usb_submit_urb(rr3->read_urb, GFP_ATOMIC))
1090                 return -EIO;
1091         led_classdev_resume(&rr3->led);
1092         return 0;
1093 }
1094
1095 static struct usb_driver redrat3_dev_driver = {
1096         .name           = DRIVER_NAME,
1097         .probe          = redrat3_dev_probe,
1098         .disconnect     = redrat3_dev_disconnect,
1099         .suspend        = redrat3_dev_suspend,
1100         .resume         = redrat3_dev_resume,
1101         .reset_resume   = redrat3_dev_resume,
1102         .id_table       = redrat3_dev_table
1103 };
1104
1105 module_usb_driver(redrat3_dev_driver);
1106
1107 MODULE_DESCRIPTION(DRIVER_DESC);
1108 MODULE_AUTHOR(DRIVER_AUTHOR);
1109 MODULE_AUTHOR(DRIVER_AUTHOR2);
1110 MODULE_LICENSE("GPL");
1111 MODULE_DEVICE_TABLE(usb, redrat3_dev_table);
1112
1113 module_param(debug, int, S_IRUGO | S_IWUSR);
1114 MODULE_PARM_DESC(debug, "Enable module debug spew. 0 = no debugging (default) "
1115                  "0x1 = standard debug messages, 0x2 = function tracing debug. "
1116                  "Flag bits are addative (i.e., 0x3 for both debug types).");