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