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