]> Pileus Git - ~andy/linux/blob - drivers/media/rc/redrat3.c
[media] redrat3: errors on unplug
[~andy/linux] / 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/module.h>
51 #include <linux/slab.h>
52 #include <linux/usb.h>
53 #include <linux/usb/input.h>
54 #include <media/rc-core.h>
55
56 /* Driver Information */
57 #define DRIVER_AUTHOR "Jarod Wilson <jarod@redhat.com>"
58 #define DRIVER_AUTHOR2 "The Dweller, Stephen Cox"
59 #define DRIVER_DESC "RedRat3 USB IR Transceiver Driver"
60 #define DRIVER_NAME "redrat3"
61
62 /* module parameters */
63 #ifdef CONFIG_USB_DEBUG
64 static int debug = 1;
65 #else
66 static int debug;
67 #endif
68
69 #define RR3_DEBUG_STANDARD              0x1
70 #define RR3_DEBUG_FUNCTION_TRACE        0x2
71
72 #define rr3_dbg(dev, fmt, ...)                                  \
73         do {                                                    \
74                 if (debug & RR3_DEBUG_STANDARD)                 \
75                         dev_info(dev, fmt, ## __VA_ARGS__);     \
76         } while (0)
77
78 #define rr3_ftr(dev, fmt, ...)                                  \
79         do {                                                    \
80                 if (debug & RR3_DEBUG_FUNCTION_TRACE)           \
81                         dev_info(dev, fmt, ## __VA_ARGS__);     \
82         } while (0)
83
84 /* bulk data transfer types */
85 #define RR3_ERROR               0x01
86 #define RR3_MOD_SIGNAL_IN       0x20
87 #define RR3_MOD_SIGNAL_OUT      0x21
88
89 /* Get the RR firmware version */
90 #define RR3_FW_VERSION          0xb1
91 #define RR3_FW_VERSION_LEN      64
92 /* Send encoded signal bulk-sent earlier*/
93 #define RR3_TX_SEND_SIGNAL      0xb3
94 #define RR3_SET_IR_PARAM        0xb7
95 #define RR3_GET_IR_PARAM        0xb8
96 /* Blink the red LED on the device */
97 #define RR3_BLINK_LED           0xb9
98 /* Read serial number of device */
99 #define RR3_READ_SER_NO         0xba
100 #define RR3_SER_NO_LEN          4
101 /* Start capture with the RC receiver */
102 #define RR3_RC_DET_ENABLE       0xbb
103 /* Stop capture with the RC receiver */
104 #define RR3_RC_DET_DISABLE      0xbc
105 /* Return the status of RC detector capture */
106 #define RR3_RC_DET_STATUS       0xbd
107 /* Reset redrat */
108 #define RR3_RESET               0xa0
109
110 /* Max number of lengths in the signal. */
111 #define RR3_IR_IO_MAX_LENGTHS   0x01
112 /* Periods to measure mod. freq. */
113 #define RR3_IR_IO_PERIODS_MF    0x02
114 /* Size of memory for main signal data */
115 #define RR3_IR_IO_SIG_MEM_SIZE  0x03
116 /* Delta value when measuring lengths */
117 #define RR3_IR_IO_LENGTH_FUZZ   0x04
118 /* Timeout for end of signal detection */
119 #define RR3_IR_IO_SIG_TIMEOUT   0x05
120 /* Minumum value for pause recognition. */
121 #define RR3_IR_IO_MIN_PAUSE     0x06
122
123 /* Clock freq. of EZ-USB chip */
124 #define RR3_CLK                 24000000
125 /* Clock periods per timer count */
126 #define RR3_CLK_PER_COUNT       12
127 /* (RR3_CLK / RR3_CLK_PER_COUNT) */
128 #define RR3_CLK_CONV_FACTOR     2000000
129 /* USB bulk-in IR data endpoint address */
130 #define RR3_BULK_IN_EP_ADDR     0x82
131
132 /* Size of the fixed-length portion of the signal */
133 #define RR3_DRIVER_MAXLENS      128
134 #define RR3_MAX_SIG_SIZE        512
135 #define RR3_TIME_UNIT           50
136 #define RR3_END_OF_SIGNAL       0x7f
137 #define RR3_TX_TRAILER_LEN      2
138 #define RR3_RX_MIN_TIMEOUT      5
139 #define RR3_RX_MAX_TIMEOUT      2000
140
141 /* The 8051's CPUCS Register address */
142 #define RR3_CPUCS_REG_ADDR      0x7f92
143
144 #define USB_RR3USB_VENDOR_ID    0x112a
145 #define USB_RR3USB_PRODUCT_ID   0x0001
146 #define USB_RR3IIUSB_PRODUCT_ID 0x0005
147
148 struct redrat3_header {
149         __be16 length;
150         __be16 transfer_type;
151 } __packed;
152
153 /* sending and receiving irdata */
154 struct redrat3_irdata {
155         struct redrat3_header header;
156         __be32 pause;
157         __be16 mod_freq_count;
158         __be16 num_periods;
159         __u8 max_lengths;
160         __u8 no_lengths;
161         __be16 max_sig_size;
162         __be16 sig_size;
163         __u8 no_repeats;
164         __be16 lens[RR3_DRIVER_MAXLENS]; /* not aligned */
165         __u8 sigdata[RR3_MAX_SIG_SIZE];
166 } __packed;
167
168 /* firmware errors */
169 struct redrat3_error {
170         struct redrat3_header header;
171         __be16 fw_error;
172 } __packed;
173
174 /* table of devices that work with this driver */
175 static struct usb_device_id redrat3_dev_table[] = {
176         /* Original version of the RedRat3 */
177         {USB_DEVICE(USB_RR3USB_VENDOR_ID, USB_RR3USB_PRODUCT_ID)},
178         /* Second Version/release of the RedRat3 - RetRat3-II */
179         {USB_DEVICE(USB_RR3USB_VENDOR_ID, USB_RR3IIUSB_PRODUCT_ID)},
180         {}                      /* Terminating entry */
181 };
182
183 /* Structure to hold all of our device specific stuff */
184 struct redrat3_dev {
185         /* core device bits */
186         struct rc_dev *rc;
187         struct device *dev;
188
189         /* save off the usb device pointer */
190         struct usb_device *udev;
191
192         /* the receive endpoint */
193         struct usb_endpoint_descriptor *ep_in;
194         /* the buffer to receive data */
195         void *bulk_in_buf;
196         /* urb used to read ir data */
197         struct urb *read_urb;
198
199         /* the send endpoint */
200         struct usb_endpoint_descriptor *ep_out;
201
202         /* usb dma */
203         dma_addr_t dma_in;
204
205         /* rx signal timeout timer */
206         struct timer_list rx_timeout;
207         u32 hw_timeout;
208
209         /* Is the device currently transmitting?*/
210         bool transmitting;
211
212         /* store for current packet */
213         struct redrat3_irdata irdata;
214         u16 bytes_read;
215
216         u32 carrier;
217
218         char name[64];
219         char phys[64];
220 };
221
222 /*
223  * redrat3_issue_async
224  *
225  *  Issues an async read to the ir data in port..
226  *  sets the callback to be redrat3_handle_async
227  */
228 static void redrat3_issue_async(struct redrat3_dev *rr3)
229 {
230         int res;
231
232         rr3_ftr(rr3->dev, "Entering %s\n", __func__);
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         rr3_ftr(rr3->dev, "Entered %s\n", __func__);
373
374         dev = rr3->dev;
375
376         /* Make sure we reset the IR kfifo after a bit of inactivity */
377         delay = usecs_to_jiffies(rr3->hw_timeout);
378         mod_timer(&rr3->rx_timeout, jiffies + delay);
379
380         mod_freq = redrat3_val_to_mod_freq(&rr3->irdata);
381         rr3_dbg(dev, "Got mod_freq of %u\n", mod_freq);
382
383         /* process each rr3 encoded byte into an int */
384         sig_size = be16_to_cpu(rr3->irdata.sig_size);
385         for (i = 0; i < sig_size; i++) {
386                 offset = rr3->irdata.sigdata[i];
387                 val = get_unaligned_be16(&rr3->irdata.lens[offset]);
388                 single_len = redrat3_len_to_us(val);
389
390                 /* we should always get pulse/space/pulse/space samples */
391                 if (i % 2)
392                         rawir.pulse = false;
393                 else
394                         rawir.pulse = true;
395
396                 rawir.duration = US_TO_NS(single_len);
397                 /* Save initial pulse length to fudge trailer */
398                 if (i == 0)
399                         trailer = rawir.duration;
400                 /* cap the value to IR_MAX_DURATION */
401                 rawir.duration &= IR_MAX_DURATION;
402
403                 rr3_dbg(dev, "storing %s with duration %d (i: %d)\n",
404                         rawir.pulse ? "pulse" : "space", rawir.duration, i);
405                 ir_raw_event_store_with_filter(rr3->rc, &rawir);
406         }
407
408         /* add a trailing space, if need be */
409         if (i % 2) {
410                 rawir.pulse = false;
411                 /* this duration is made up, and may not be ideal... */
412                 if (trailer < US_TO_NS(1000))
413                         rawir.duration = US_TO_NS(2800);
414                 else
415                         rawir.duration = trailer;
416                 rr3_dbg(dev, "storing trailing space with duration %d\n",
417                         rawir.duration);
418                 ir_raw_event_store_with_filter(rr3->rc, &rawir);
419         }
420
421         rr3_dbg(dev, "calling ir_raw_event_handle\n");
422         ir_raw_event_handle(rr3->rc);
423 }
424
425 /* Util fn to send rr3 cmds */
426 static u8 redrat3_send_cmd(int cmd, struct redrat3_dev *rr3)
427 {
428         struct usb_device *udev;
429         u8 *data;
430         int res;
431
432         data = kzalloc(sizeof(u8), GFP_KERNEL);
433         if (!data)
434                 return -ENOMEM;
435
436         udev = rr3->udev;
437         res = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), cmd,
438                               USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
439                               0x0000, 0x0000, data, sizeof(u8), HZ * 10);
440
441         if (res < 0) {
442                 dev_err(rr3->dev, "%s: Error sending rr3 cmd res %d, data %d",
443                         __func__, res, *data);
444                 res = -EIO;
445         } else
446                 res = data[0];
447
448         kfree(data);
449
450         return res;
451 }
452
453 /* Enables the long range detector and starts async receive */
454 static int redrat3_enable_detector(struct redrat3_dev *rr3)
455 {
456         struct device *dev = rr3->dev;
457         u8 ret;
458
459         rr3_ftr(dev, "Entering %s\n", __func__);
460
461         ret = redrat3_send_cmd(RR3_RC_DET_ENABLE, rr3);
462         if (ret != 0)
463                 dev_dbg(dev, "%s: unexpected ret of %d\n",
464                         __func__, ret);
465
466         ret = redrat3_send_cmd(RR3_RC_DET_STATUS, rr3);
467         if (ret != 1) {
468                 dev_err(dev, "%s: detector status: %d, should be 1\n",
469                         __func__, ret);
470                 return -EIO;
471         }
472
473         redrat3_issue_async(rr3);
474
475         return 0;
476 }
477
478 static inline void redrat3_delete(struct redrat3_dev *rr3,
479                                   struct usb_device *udev)
480 {
481         rr3_ftr(rr3->dev, "%s cleaning up\n", __func__);
482         usb_kill_urb(rr3->read_urb);
483
484         usb_free_urb(rr3->read_urb);
485
486         usb_free_coherent(udev, le16_to_cpu(rr3->ep_in->wMaxPacketSize),
487                           rr3->bulk_in_buf, rr3->dma_in);
488
489         kfree(rr3);
490 }
491
492 static u32 redrat3_get_timeout(struct redrat3_dev *rr3)
493 {
494         __be32 *tmp;
495         u32 timeout = MS_TO_US(150); /* a sane default, if things go haywire */
496         int len, ret, pipe;
497
498         len = sizeof(*tmp);
499         tmp = kzalloc(len, GFP_KERNEL);
500         if (!tmp) {
501                 dev_warn(rr3->dev, "Memory allocation faillure\n");
502                 return timeout;
503         }
504
505         pipe = usb_rcvctrlpipe(rr3->udev, 0);
506         ret = usb_control_msg(rr3->udev, pipe, RR3_GET_IR_PARAM,
507                               USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
508                               RR3_IR_IO_SIG_TIMEOUT, 0, tmp, len, HZ * 5);
509         if (ret != len)
510                 dev_warn(rr3->dev, "Failed to read timeout from hardware\n");
511         else {
512                 timeout = redrat3_len_to_us(be32_to_cpup(tmp));
513
514                 rr3_dbg(rr3->dev, "Got timeout of %d ms\n", timeout / 1000);
515         }
516
517         kfree(tmp);
518
519         return timeout;
520 }
521
522 static void redrat3_reset(struct redrat3_dev *rr3)
523 {
524         struct usb_device *udev = rr3->udev;
525         struct device *dev = rr3->dev;
526         int rc, rxpipe, txpipe;
527         u8 *val;
528         int len = sizeof(u8);
529
530         rr3_ftr(dev, "Entering %s\n", __func__);
531
532         rxpipe = usb_rcvctrlpipe(udev, 0);
533         txpipe = usb_sndctrlpipe(udev, 0);
534
535         val = kmalloc(len, GFP_KERNEL);
536         if (!val) {
537                 dev_err(dev, "Memory allocation failure\n");
538                 return;
539         }
540
541         *val = 0x01;
542         rc = usb_control_msg(udev, rxpipe, RR3_RESET,
543                              USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
544                              RR3_CPUCS_REG_ADDR, 0, val, len, HZ * 25);
545         rr3_dbg(dev, "reset returned 0x%02x\n", rc);
546
547         *val = 5;
548         rc = usb_control_msg(udev, txpipe, RR3_SET_IR_PARAM,
549                              USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
550                              RR3_IR_IO_LENGTH_FUZZ, 0, val, len, HZ * 25);
551         rr3_dbg(dev, "set ir parm len fuzz %d rc 0x%02x\n", *val, rc);
552
553         *val = RR3_DRIVER_MAXLENS;
554         rc = usb_control_msg(udev, txpipe, RR3_SET_IR_PARAM,
555                              USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_OUT,
556                              RR3_IR_IO_MAX_LENGTHS, 0, val, len, HZ * 25);
557         rr3_dbg(dev, "set ir parm max lens %d rc 0x%02x\n", *val, rc);
558
559         kfree(val);
560 }
561
562 static void redrat3_get_firmware_rev(struct redrat3_dev *rr3)
563 {
564         int rc = 0;
565         char *buffer;
566
567         rr3_ftr(rr3->dev, "Entering %s\n", __func__);
568
569         buffer = kzalloc(sizeof(char) * (RR3_FW_VERSION_LEN + 1), GFP_KERNEL);
570         if (!buffer) {
571                 dev_err(rr3->dev, "Memory allocation failure\n");
572                 return;
573         }
574
575         rc = usb_control_msg(rr3->udev, usb_rcvctrlpipe(rr3->udev, 0),
576                              RR3_FW_VERSION,
577                              USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
578                              0, 0, buffer, RR3_FW_VERSION_LEN, HZ * 5);
579
580         if (rc >= 0)
581                 dev_info(rr3->dev, "Firmware rev: %s", buffer);
582         else
583                 dev_err(rr3->dev, "Problem fetching firmware ID\n");
584
585         kfree(buffer);
586         rr3_ftr(rr3->dev, "Exiting %s\n", __func__);
587 }
588
589 static void redrat3_read_packet_start(struct redrat3_dev *rr3, unsigned len)
590 {
591         struct redrat3_header *header = rr3->bulk_in_buf;
592         unsigned pktlen, pkttype;
593
594         rr3_ftr(rr3->dev, "Entering %s\n", __func__);
595
596         /* grab the Length and type of transfer */
597         pktlen = be16_to_cpu(header->length);
598         pkttype = be16_to_cpu(header->transfer_type);
599
600         if (pktlen > sizeof(rr3->irdata)) {
601                 dev_warn(rr3->dev, "packet length %u too large\n", pktlen);
602                 return;
603         }
604
605         switch (pkttype) {
606         case RR3_ERROR:
607                 if (len >= sizeof(struct redrat3_error)) {
608                         struct redrat3_error *error = rr3->bulk_in_buf;
609                         unsigned fw_error = be16_to_cpu(error->fw_error);
610                         redrat3_dump_fw_error(rr3, fw_error);
611                 }
612                 break;
613
614         case RR3_MOD_SIGNAL_IN:
615                 memcpy(&rr3->irdata, rr3->bulk_in_buf, len);
616                 rr3->bytes_read = len;
617                 rr3_dbg(rr3->dev, "bytes_read %d, pktlen %d\n",
618                         rr3->bytes_read, pktlen);
619                 break;
620
621         default:
622                 rr3_dbg(rr3->dev, "ignoring packet with type 0x%02x, len of %d, 0x%02x\n",
623                                                 pkttype, len, pktlen);
624                 break;
625         }
626 }
627
628 static void redrat3_read_packet_continue(struct redrat3_dev *rr3, unsigned len)
629 {
630         void *irdata = &rr3->irdata;
631
632         rr3_ftr(rr3->dev, "Entering %s\n", __func__);
633
634         if (len + rr3->bytes_read > sizeof(rr3->irdata)) {
635                 dev_warn(rr3->dev, "too much data for packet\n");
636                 rr3->bytes_read = 0;
637                 return;
638         }
639
640         memcpy(irdata + rr3->bytes_read, rr3->bulk_in_buf, len);
641
642         rr3->bytes_read += len;
643         rr3_dbg(rr3->dev, "bytes_read %d, pktlen %d\n", rr3->bytes_read,
644                                  be16_to_cpu(rr3->irdata.header.length));
645 }
646
647 /* gather IR data from incoming urb, process it when we have enough */
648 static int redrat3_get_ir_data(struct redrat3_dev *rr3, unsigned len)
649 {
650         struct device *dev = rr3->dev;
651         unsigned pkttype;
652         int ret = 0;
653
654         rr3_ftr(dev, "Entering %s\n", __func__);
655
656         if (rr3->bytes_read == 0 && len >= sizeof(struct redrat3_header)) {
657                 redrat3_read_packet_start(rr3, len);
658         } else if (rr3->bytes_read != 0) {
659                 redrat3_read_packet_continue(rr3, len);
660         } else if (rr3->bytes_read == 0) {
661                 dev_err(dev, "error: no packet data read\n");
662                 ret = -ENODATA;
663                 goto out;
664         }
665
666         if (rr3->bytes_read < be16_to_cpu(rr3->irdata.header.length))
667                 /* we're still accumulating data */
668                 return 0;
669
670         /* if we get here, we've got IR data to decode */
671         pkttype = be16_to_cpu(rr3->irdata.header.transfer_type);
672         if (pkttype == RR3_MOD_SIGNAL_IN)
673                 redrat3_process_ir_data(rr3);
674         else
675                 rr3_dbg(dev, "discarding non-signal data packet (type 0x%02x)\n",
676                                                                 pkttype);
677
678 out:
679         rr3->bytes_read = 0;
680         return ret;
681 }
682
683 /* callback function from USB when async USB request has completed */
684 static void redrat3_handle_async(struct urb *urb)
685 {
686         struct redrat3_dev *rr3;
687         int ret;
688
689         if (!urb)
690                 return;
691
692         rr3 = urb->context;
693         if (!rr3) {
694                 pr_err("%s called with invalid context!\n", __func__);
695                 usb_unlink_urb(urb);
696                 return;
697         }
698
699         rr3_ftr(rr3->dev, "Entering %s\n", __func__);
700
701         switch (urb->status) {
702         case 0:
703                 ret = redrat3_get_ir_data(rr3, urb->actual_length);
704                 if (!ret) {
705                         /* no error, prepare to read more */
706                         redrat3_issue_async(rr3);
707                 }
708                 break;
709
710         case -ECONNRESET:
711         case -ENOENT:
712         case -ESHUTDOWN:
713                 usb_unlink_urb(urb);
714                 return;
715
716         case -EPIPE:
717         default:
718                 dev_warn(rr3->dev, "Error: urb status = %d\n", urb->status);
719                 rr3->bytes_read = 0;
720                 break;
721         }
722 }
723
724 static u16 mod_freq_to_val(unsigned int mod_freq)
725 {
726         int mult = 6000000;
727
728         /* Clk used in mod. freq. generation is CLK24/4. */
729         return 65536 - (mult / mod_freq);
730 }
731
732 static int redrat3_set_tx_carrier(struct rc_dev *rcdev, u32 carrier)
733 {
734         struct redrat3_dev *rr3 = rcdev->priv;
735         struct device *dev = rr3->dev;
736
737         rr3_dbg(dev, "Setting modulation frequency to %u", carrier);
738         if (carrier == 0)
739                 return -EINVAL;
740
741         rr3->carrier = carrier;
742
743         return carrier;
744 }
745
746 static int redrat3_transmit_ir(struct rc_dev *rcdev, unsigned *txbuf,
747                                 unsigned count)
748 {
749         struct redrat3_dev *rr3 = rcdev->priv;
750         struct device *dev = rr3->dev;
751         struct redrat3_irdata *irdata = NULL;
752         int ret, ret_len;
753         int lencheck, cur_sample_len, pipe;
754         int *sample_lens = NULL;
755         u8 curlencheck = 0;
756         unsigned i, sendbuf_len;
757
758         rr3_ftr(dev, "Entering %s\n", __func__);
759
760         if (rr3->transmitting) {
761                 dev_warn(dev, "%s: transmitter already in use\n", __func__);
762                 return -EAGAIN;
763         }
764
765         count = min_t(unsigned, count, RR3_MAX_SIG_SIZE - RR3_TX_TRAILER_LEN);
766
767         /* rr3 will disable rc detector on transmit */
768         rr3->transmitting = true;
769
770         sample_lens = kzalloc(sizeof(int) * RR3_DRIVER_MAXLENS, GFP_KERNEL);
771         if (!sample_lens) {
772                 ret = -ENOMEM;
773                 goto out;
774         }
775
776         irdata = kzalloc(sizeof(*irdata), GFP_KERNEL);
777         if (!irdata) {
778                 ret = -ENOMEM;
779                 goto out;
780         }
781
782         for (i = 0; i < count; i++) {
783                 cur_sample_len = redrat3_us_to_len(txbuf[i]);
784                 if (cur_sample_len > 0xffff) {
785                         dev_warn(dev, "transmit period of %uus truncated to %uus\n",
786                                         txbuf[i], redrat3_len_to_us(0xffff));
787                         cur_sample_len = 0xffff;
788                 }
789                 for (lencheck = 0; lencheck < curlencheck; lencheck++) {
790                         if (sample_lens[lencheck] == cur_sample_len)
791                                 break;
792                 }
793                 if (lencheck == curlencheck) {
794                         rr3_dbg(dev, "txbuf[%d]=%u, pos %d, enc %u\n",
795                                 i, txbuf[i], curlencheck, cur_sample_len);
796                         if (curlencheck < RR3_DRIVER_MAXLENS) {
797                                 /* now convert the value to a proper
798                                  * rr3 value.. */
799                                 sample_lens[curlencheck] = cur_sample_len;
800                                 put_unaligned_be16(cur_sample_len,
801                                                 &irdata->lens[curlencheck]);
802                                 curlencheck++;
803                         } else {
804                                 count = i - 1;
805                                 break;
806                         }
807                 }
808                 irdata->sigdata[i] = lencheck;
809         }
810
811         irdata->sigdata[count] = RR3_END_OF_SIGNAL;
812         irdata->sigdata[count + 1] = RR3_END_OF_SIGNAL;
813
814         sendbuf_len = offsetof(struct redrat3_irdata,
815                                         sigdata[count + RR3_TX_TRAILER_LEN]);
816         /* fill in our packet header */
817         irdata->header.length = cpu_to_be16(sendbuf_len -
818                                                 sizeof(struct redrat3_header));
819         irdata->header.transfer_type = cpu_to_be16(RR3_MOD_SIGNAL_OUT);
820         irdata->pause = cpu_to_be32(redrat3_len_to_us(100));
821         irdata->mod_freq_count = cpu_to_be16(mod_freq_to_val(rr3->carrier));
822         irdata->no_lengths = curlencheck;
823         irdata->sig_size = cpu_to_be16(count + RR3_TX_TRAILER_LEN);
824
825         pipe = usb_sndbulkpipe(rr3->udev, rr3->ep_out->bEndpointAddress);
826         ret = usb_bulk_msg(rr3->udev, pipe, irdata,
827                             sendbuf_len, &ret_len, 10 * HZ);
828         rr3_dbg(dev, "sent %d bytes, (ret %d)\n", ret_len, ret);
829
830         /* now tell the hardware to transmit what we sent it */
831         pipe = usb_rcvctrlpipe(rr3->udev, 0);
832         ret = usb_control_msg(rr3->udev, pipe, RR3_TX_SEND_SIGNAL,
833                               USB_TYPE_VENDOR | USB_RECIP_DEVICE | USB_DIR_IN,
834                               0, 0, irdata, 2, HZ * 10);
835
836         if (ret < 0)
837                 dev_err(dev, "Error: control msg send failed, rc %d\n", ret);
838         else
839                 ret = count;
840
841 out:
842         kfree(sample_lens);
843         kfree(irdata);
844
845         rr3->transmitting = false;
846         /* rr3 re-enables rc detector because it was enabled before */
847
848         return ret;
849 }
850
851 static struct rc_dev *redrat3_init_rc_dev(struct redrat3_dev *rr3)
852 {
853         struct device *dev = rr3->dev;
854         struct rc_dev *rc;
855         int ret = -ENODEV;
856         u16 prod = le16_to_cpu(rr3->udev->descriptor.idProduct);
857
858         rc = rc_allocate_device();
859         if (!rc) {
860                 dev_err(dev, "remote input dev allocation failed\n");
861                 goto out;
862         }
863
864         snprintf(rr3->name, sizeof(rr3->name), "RedRat3%s "
865                  "Infrared Remote Transceiver (%04x:%04x)",
866                  prod == USB_RR3IIUSB_PRODUCT_ID ? "-II" : "",
867                  le16_to_cpu(rr3->udev->descriptor.idVendor), prod);
868
869         usb_make_path(rr3->udev, rr3->phys, sizeof(rr3->phys));
870
871         rc->input_name = rr3->name;
872         rc->input_phys = rr3->phys;
873         usb_to_input_id(rr3->udev, &rc->input_id);
874         rc->dev.parent = dev;
875         rc->priv = rr3;
876         rc->driver_type = RC_DRIVER_IR_RAW;
877         rc->allowed_protos = RC_BIT_ALL;
878         rc->timeout = US_TO_NS(2750);
879         rc->tx_ir = redrat3_transmit_ir;
880         rc->s_tx_carrier = redrat3_set_tx_carrier;
881         rc->driver_name = DRIVER_NAME;
882         rc->rx_resolution = US_TO_NS(2);
883         rc->map_name = RC_MAP_HAUPPAUGE;
884
885         ret = rc_register_device(rc);
886         if (ret < 0) {
887                 dev_err(dev, "remote dev registration failed\n");
888                 goto out;
889         }
890
891         return rc;
892
893 out:
894         rc_free_device(rc);
895         return NULL;
896 }
897
898 static int redrat3_dev_probe(struct usb_interface *intf,
899                              const struct usb_device_id *id)
900 {
901         struct usb_device *udev = interface_to_usbdev(intf);
902         struct device *dev = &intf->dev;
903         struct usb_host_interface *uhi;
904         struct redrat3_dev *rr3;
905         struct usb_endpoint_descriptor *ep;
906         struct usb_endpoint_descriptor *ep_in = NULL;
907         struct usb_endpoint_descriptor *ep_out = NULL;
908         u8 addr, attrs;
909         int pipe, i;
910         int retval = -ENOMEM;
911
912         rr3_ftr(dev, "%s called\n", __func__);
913
914         uhi = intf->cur_altsetting;
915
916         /* find our bulk-in and bulk-out endpoints */
917         for (i = 0; i < uhi->desc.bNumEndpoints; ++i) {
918                 ep = &uhi->endpoint[i].desc;
919                 addr = ep->bEndpointAddress;
920                 attrs = ep->bmAttributes;
921
922                 if ((ep_in == NULL) &&
923                     ((addr & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN) &&
924                     ((attrs & USB_ENDPOINT_XFERTYPE_MASK) ==
925                      USB_ENDPOINT_XFER_BULK)) {
926                         rr3_dbg(dev, "found bulk-in endpoint at 0x%02x\n",
927                                 ep->bEndpointAddress);
928                         /* data comes in on 0x82, 0x81 is for other data... */
929                         if (ep->bEndpointAddress == RR3_BULK_IN_EP_ADDR)
930                                 ep_in = ep;
931                 }
932
933                 if ((ep_out == NULL) &&
934                     ((addr & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT) &&
935                     ((attrs & USB_ENDPOINT_XFERTYPE_MASK) ==
936                      USB_ENDPOINT_XFER_BULK)) {
937                         rr3_dbg(dev, "found bulk-out endpoint at 0x%02x\n",
938                                 ep->bEndpointAddress);
939                         ep_out = ep;
940                 }
941         }
942
943         if (!ep_in || !ep_out) {
944                 dev_err(dev, "Couldn't find both in and out endpoints\n");
945                 retval = -ENODEV;
946                 goto no_endpoints;
947         }
948
949         /* allocate memory for our device state and initialize it */
950         rr3 = kzalloc(sizeof(*rr3), GFP_KERNEL);
951         if (rr3 == NULL) {
952                 dev_err(dev, "Memory allocation failure\n");
953                 goto no_endpoints;
954         }
955
956         rr3->dev = &intf->dev;
957
958         /* set up bulk-in endpoint */
959         rr3->read_urb = usb_alloc_urb(0, GFP_KERNEL);
960         if (!rr3->read_urb) {
961                 dev_err(dev, "Read urb allocation failure\n");
962                 goto error;
963         }
964
965         rr3->ep_in = ep_in;
966         rr3->bulk_in_buf = usb_alloc_coherent(udev,
967                 le16_to_cpu(ep_in->wMaxPacketSize), GFP_ATOMIC, &rr3->dma_in);
968         if (!rr3->bulk_in_buf) {
969                 dev_err(dev, "Read buffer allocation failure\n");
970                 goto error;
971         }
972
973         pipe = usb_rcvbulkpipe(udev, ep_in->bEndpointAddress);
974         usb_fill_bulk_urb(rr3->read_urb, udev, pipe, rr3->bulk_in_buf,
975                 le16_to_cpu(ep_in->wMaxPacketSize), redrat3_handle_async, rr3);
976
977         rr3->ep_out = ep_out;
978         rr3->udev = udev;
979
980         redrat3_reset(rr3);
981         redrat3_get_firmware_rev(rr3);
982
983         /* might be all we need to do? */
984         retval = redrat3_enable_detector(rr3);
985         if (retval < 0)
986                 goto error;
987
988         /* store current hardware timeout, in us, will use for kfifo resets */
989         rr3->hw_timeout = redrat3_get_timeout(rr3);
990
991         /* default.. will get overridden by any sends with a freq defined */
992         rr3->carrier = 38000;
993
994         rr3->rc = redrat3_init_rc_dev(rr3);
995         if (!rr3->rc) {
996                 retval = -ENOMEM;
997                 goto error;
998         }
999         setup_timer(&rr3->rx_timeout, redrat3_rx_timeout, (unsigned long)rr3);
1000
1001         /* we can register the device now, as it is ready */
1002         usb_set_intfdata(intf, rr3);
1003
1004         rr3_ftr(dev, "Exiting %s\n", __func__);
1005         return 0;
1006
1007 error:
1008         redrat3_delete(rr3, rr3->udev);
1009
1010 no_endpoints:
1011         dev_err(dev, "%s: retval = %x", __func__, retval);
1012
1013         return retval;
1014 }
1015
1016 static void redrat3_dev_disconnect(struct usb_interface *intf)
1017 {
1018         struct usb_device *udev = interface_to_usbdev(intf);
1019         struct redrat3_dev *rr3 = usb_get_intfdata(intf);
1020
1021         rr3_ftr(&intf->dev, "Entering %s\n", __func__);
1022
1023         if (!rr3)
1024                 return;
1025
1026         usb_set_intfdata(intf, NULL);
1027         rc_unregister_device(rr3->rc);
1028         del_timer_sync(&rr3->rx_timeout);
1029         redrat3_delete(rr3, udev);
1030
1031         rr3_ftr(&intf->dev, "RedRat3 IR Transceiver now disconnected\n");
1032 }
1033
1034 static int redrat3_dev_suspend(struct usb_interface *intf, pm_message_t message)
1035 {
1036         struct redrat3_dev *rr3 = usb_get_intfdata(intf);
1037         rr3_ftr(rr3->dev, "suspend\n");
1038         usb_kill_urb(rr3->read_urb);
1039         return 0;
1040 }
1041
1042 static int redrat3_dev_resume(struct usb_interface *intf)
1043 {
1044         struct redrat3_dev *rr3 = usb_get_intfdata(intf);
1045         rr3_ftr(rr3->dev, "resume\n");
1046         if (usb_submit_urb(rr3->read_urb, GFP_ATOMIC))
1047                 return -EIO;
1048         return 0;
1049 }
1050
1051 static struct usb_driver redrat3_dev_driver = {
1052         .name           = DRIVER_NAME,
1053         .probe          = redrat3_dev_probe,
1054         .disconnect     = redrat3_dev_disconnect,
1055         .suspend        = redrat3_dev_suspend,
1056         .resume         = redrat3_dev_resume,
1057         .reset_resume   = redrat3_dev_resume,
1058         .id_table       = redrat3_dev_table
1059 };
1060
1061 module_usb_driver(redrat3_dev_driver);
1062
1063 MODULE_DESCRIPTION(DRIVER_DESC);
1064 MODULE_AUTHOR(DRIVER_AUTHOR);
1065 MODULE_AUTHOR(DRIVER_AUTHOR2);
1066 MODULE_LICENSE("GPL");
1067 MODULE_DEVICE_TABLE(usb, redrat3_dev_table);
1068
1069 module_param(debug, int, S_IRUGO | S_IWUSR);
1070 MODULE_PARM_DESC(debug, "Enable module debug spew. 0 = no debugging (default) "
1071                  "0x1 = standard debug messages, 0x2 = function tracing debug. "
1072                  "Flag bits are addative (i.e., 0x3 for both debug types).");