Merge branch 'master' of ssh://oss.sgi.com/oss/git/xfs/xfs into for-linus
[pandora-kernel.git] / drivers / net / irda / kingsun-sir.c
1 /*****************************************************************************
2 *
3 * Filename:      kingsun-sir.c
4 * Version:       0.1.1
5 * Description:   Irda KingSun/DonShine USB Dongle
6 * Status:        Experimental
7 * Author:        Alex Villacís Lasso <a_villacis@palosanto.com>
8 *
9 *       Based on stir4200 and mcs7780 drivers, with (strange?) differences
10 *
11 *       This program is free software; you can redistribute it and/or modify
12 *       it under the terms of the GNU General Public License as published by
13 *       the Free Software Foundation; either version 2 of the License.
14 *
15 *       This program is distributed in the hope that it will be useful,
16 *       but WITHOUT ANY WARRANTY; without even the implied warranty of
17 *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 *       GNU General Public License for more details.
19 *
20 *       You should have received a copy of the GNU General Public License
21 *       along with this program; if not, write to the Free Software
22 *       Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 *
24 *****************************************************************************/
25
26 /*
27  * This is my current (2007-04-25) understanding of how this dongle is supposed
28  * to work. This is based on reverse-engineering and examination of the packet
29  * data sent and received by the WinXP driver using USBSnoopy. Feel free to
30  * update here as more of this dongle is known:
31  *
32  * General: Unlike the other USB IrDA dongles, this particular dongle exposes,
33  * not two bulk (in and out) endpoints, but two *interrupt* ones. This dongle,
34  * like the bulk based ones (stir4200.c and mcs7780.c), requires polling in
35  * order to receive data.
36  * Transmission: Just like stir4200, this dongle uses a raw stream of data,
37  * which needs to be wrapped and escaped in a similar way as in stir4200.c.
38  * Reception: Poll-based, as in stir4200. Each read returns the contents of a
39  * 8-byte buffer, of which the first byte (LSB) indicates the number of bytes
40  * (1-7) of valid data contained within the remaining 7 bytes. For example, if
41  * the buffer had the following contents:
42  *  06 ff ff ff c0 01 04 aa
43  * This means that (06) there are 6 bytes of valid data. The byte 0xaa at the
44  * end is garbage (left over from a previous reception) and is discarded.
45  * If a read returns an "impossible" value as the length of valid data (such as
46  * 0x36) in the first byte, then the buffer is uninitialized (as is the case of
47  * first plug-in) and its contents should be discarded. There is currently no
48  * evidence that the top 5 bits of the 1st byte of the buffer can have values
49  * other than 0 once reception begins.
50  * Once valid bytes are collected, the assembled stream is a sequence of
51  * wrapped IrDA frames that is unwrapped and unescaped as in stir4200.c.
52  * BIG FAT WARNING: the dongle does *not* reset the RX buffer in any way after
53  * a successful read from the host, which means that in absence of further
54  * reception, repeated reads from the dongle will return the exact same
55  * contents repeatedly. Attempts to be smart and cache a previous read seem
56  * to result in corrupted packets, so this driver depends on the unwrap logic
57  * to sort out any repeated reads.
58  * Speed change: no commands observed so far to change speed, assumed fixed
59  * 9600bps (SIR).
60  */
61
62 #include <linux/module.h>
63 #include <linux/moduleparam.h>
64 #include <linux/kernel.h>
65 #include <linux/types.h>
66 #include <linux/errno.h>
67 #include <linux/init.h>
68 #include <linux/slab.h>
69 #include <linux/kref.h>
70 #include <linux/usb.h>
71 #include <linux/device.h>
72 #include <linux/crc32.h>
73
74 #include <asm/unaligned.h>
75 #include <asm/byteorder.h>
76 #include <asm/uaccess.h>
77
78 #include <net/irda/irda.h>
79 #include <net/irda/wrapper.h>
80 #include <net/irda/crc.h>
81
82 /*
83  * According to lsusb, 0x07c0 is assigned to
84  * "Code Mercenaries Hard- und Software GmbH"
85  */
86 #define KING_VENDOR_ID 0x07c0
87 #define KING_PRODUCT_ID 0x4200
88
89 /* These are the currently known USB ids */
90 static struct usb_device_id dongles[] = {
91     /* KingSun Co,Ltd  IrDA/USB Bridge */
92     { USB_DEVICE(KING_VENDOR_ID, KING_PRODUCT_ID) },
93     { }
94 };
95
96 MODULE_DEVICE_TABLE(usb, dongles);
97
98 #define KINGSUN_MTT 0x07
99
100 #define KINGSUN_FIFO_SIZE               4096
101 #define KINGSUN_EP_IN                   0
102 #define KINGSUN_EP_OUT                  1
103
104 struct kingsun_cb {
105         struct usb_device *usbdev;      /* init: probe_irda */
106         struct net_device *netdev;      /* network layer */
107         struct irlap_cb   *irlap;       /* The link layer we are binded to */
108
109         struct qos_info   qos;
110
111         __u8              *in_buf;      /* receive buffer */
112         __u8              *out_buf;     /* transmit buffer */
113         __u8              max_rx;       /* max. atomic read from dongle
114                                            (usually 8), also size of in_buf */
115         __u8              max_tx;       /* max. atomic write to dongle
116                                            (usually 8) */
117
118         iobuff_t          rx_buff;      /* receive unwrap state machine */
119         struct timeval    rx_time;
120         spinlock_t lock;
121         int receiving;
122
123         __u8 ep_in;
124         __u8 ep_out;
125
126         struct urb       *tx_urb;
127         struct urb       *rx_urb;
128 };
129
130 /* Callback transmission routine */
131 static void kingsun_send_irq(struct urb *urb)
132 {
133         struct kingsun_cb *kingsun = urb->context;
134         struct net_device *netdev = kingsun->netdev;
135
136         /* in process of stopping, just drop data */
137         if (!netif_running(kingsun->netdev)) {
138                 err("kingsun_send_irq: Network not running!");
139                 return;
140         }
141
142         /* unlink, shutdown, unplug, other nasties */
143         if (urb->status != 0) {
144                 err("kingsun_send_irq: urb asynchronously failed - %d",
145                     urb->status);
146         }
147         netif_wake_queue(netdev);
148 }
149
150 /*
151  * Called from net/core when new frame is available.
152  */
153 static netdev_tx_t kingsun_hard_xmit(struct sk_buff *skb,
154                                            struct net_device *netdev)
155 {
156         struct kingsun_cb *kingsun;
157         int wraplen;
158         int ret = 0;
159
160         netif_stop_queue(netdev);
161
162         /* the IRDA wrapping routines don't deal with non linear skb */
163         SKB_LINEAR_ASSERT(skb);
164
165         kingsun = netdev_priv(netdev);
166
167         spin_lock(&kingsun->lock);
168
169         /* Append data to the end of whatever data remains to be transmitted */
170         wraplen = async_wrap_skb(skb,
171                 kingsun->out_buf,
172                 KINGSUN_FIFO_SIZE);
173
174         /* Calculate how much data can be transmitted in this urb */
175         usb_fill_int_urb(kingsun->tx_urb, kingsun->usbdev,
176                 usb_sndintpipe(kingsun->usbdev, kingsun->ep_out),
177                 kingsun->out_buf, wraplen, kingsun_send_irq,
178                 kingsun, 1);
179
180         if ((ret = usb_submit_urb(kingsun->tx_urb, GFP_ATOMIC))) {
181                 err("kingsun_hard_xmit: failed tx_urb submit: %d", ret);
182                 switch (ret) {
183                 case -ENODEV:
184                 case -EPIPE:
185                         break;
186                 default:
187                         netdev->stats.tx_errors++;
188                         netif_start_queue(netdev);
189                 }
190         } else {
191                 netdev->stats.tx_packets++;
192                 netdev->stats.tx_bytes += skb->len;
193         }
194
195         dev_kfree_skb(skb);
196         spin_unlock(&kingsun->lock);
197
198         return NETDEV_TX_OK;
199 }
200
201 /* Receive callback function */
202 static void kingsun_rcv_irq(struct urb *urb)
203 {
204         struct kingsun_cb *kingsun = urb->context;
205         int ret;
206
207         /* in process of stopping, just drop data */
208         if (!netif_running(kingsun->netdev)) {
209                 kingsun->receiving = 0;
210                 return;
211         }
212
213         /* unlink, shutdown, unplug, other nasties */
214         if (urb->status != 0) {
215                 err("kingsun_rcv_irq: urb asynchronously failed - %d",
216                     urb->status);
217                 kingsun->receiving = 0;
218                 return;
219         }
220
221         if (urb->actual_length == kingsun->max_rx) {
222                 __u8 *bytes = urb->transfer_buffer;
223                 int i;
224
225                 /* The very first byte in the buffer indicates the length of
226                    valid data in the read. This byte must be in the range
227                    1..kingsun->max_rx -1 . Values outside this range indicate
228                    an uninitialized Rx buffer when the dongle has just been
229                    plugged in. */
230                 if (bytes[0] >= 1 && bytes[0] < kingsun->max_rx) {
231                         for (i = 1; i <= bytes[0]; i++) {
232                                 async_unwrap_char(kingsun->netdev,
233                                                   &kingsun->netdev->stats,
234                                                   &kingsun->rx_buff, bytes[i]);
235                         }
236                         do_gettimeofday(&kingsun->rx_time);
237                         kingsun->receiving =
238                                 (kingsun->rx_buff.state != OUTSIDE_FRAME)
239                                 ? 1 : 0;
240                 }
241         } else if (urb->actual_length > 0) {
242                 err("%s(): Unexpected response length, expected %d got %d",
243                     __func__, kingsun->max_rx, urb->actual_length);
244         }
245         /* This urb has already been filled in kingsun_net_open */
246         ret = usb_submit_urb(urb, GFP_ATOMIC);
247 }
248
249 /*
250  * Function kingsun_net_open (dev)
251  *
252  *    Network device is taken up. Usually this is done by "ifconfig irda0 up"
253  */
254 static int kingsun_net_open(struct net_device *netdev)
255 {
256         struct kingsun_cb *kingsun = netdev_priv(netdev);
257         int err = -ENOMEM;
258         char hwname[16];
259
260         /* At this point, urbs are NULL, and skb is NULL (see kingsun_probe) */
261         kingsun->receiving = 0;
262
263         /* Initialize for SIR to copy data directly into skb.  */
264         kingsun->rx_buff.in_frame = FALSE;
265         kingsun->rx_buff.state = OUTSIDE_FRAME;
266         kingsun->rx_buff.truesize = IRDA_SKB_MAX_MTU;
267         kingsun->rx_buff.skb = dev_alloc_skb(IRDA_SKB_MAX_MTU);
268         if (!kingsun->rx_buff.skb)
269                 goto free_mem;
270
271         skb_reserve(kingsun->rx_buff.skb, 1);
272         kingsun->rx_buff.head = kingsun->rx_buff.skb->data;
273         do_gettimeofday(&kingsun->rx_time);
274
275         kingsun->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
276         if (!kingsun->rx_urb)
277                 goto free_mem;
278
279         kingsun->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
280         if (!kingsun->tx_urb)
281                 goto free_mem;
282
283         /*
284          * Now that everything should be initialized properly,
285          * Open new IrLAP layer instance to take care of us...
286          */
287         sprintf(hwname, "usb#%d", kingsun->usbdev->devnum);
288         kingsun->irlap = irlap_open(netdev, &kingsun->qos, hwname);
289         if (!kingsun->irlap) {
290                 err("kingsun-sir: irlap_open failed");
291                 goto free_mem;
292         }
293
294         /* Start first reception */
295         usb_fill_int_urb(kingsun->rx_urb, kingsun->usbdev,
296                           usb_rcvintpipe(kingsun->usbdev, kingsun->ep_in),
297                           kingsun->in_buf, kingsun->max_rx,
298                           kingsun_rcv_irq, kingsun, 1);
299         kingsun->rx_urb->status = 0;
300         err = usb_submit_urb(kingsun->rx_urb, GFP_KERNEL);
301         if (err) {
302                 err("kingsun-sir: first urb-submit failed: %d", err);
303                 goto close_irlap;
304         }
305
306         netif_start_queue(netdev);
307
308         /* Situation at this point:
309            - all work buffers allocated
310            - urbs allocated and ready to fill
311            - max rx packet known (in max_rx)
312            - unwrap state machine initialized, in state outside of any frame
313            - receive request in progress
314            - IrLAP layer started, about to hand over packets to send
315          */
316
317         return 0;
318
319  close_irlap:
320         irlap_close(kingsun->irlap);
321  free_mem:
322         if (kingsun->tx_urb) {
323                 usb_free_urb(kingsun->tx_urb);
324                 kingsun->tx_urb = NULL;
325         }
326         if (kingsun->rx_urb) {
327                 usb_free_urb(kingsun->rx_urb);
328                 kingsun->rx_urb = NULL;
329         }
330         if (kingsun->rx_buff.skb) {
331                 kfree_skb(kingsun->rx_buff.skb);
332                 kingsun->rx_buff.skb = NULL;
333                 kingsun->rx_buff.head = NULL;
334         }
335         return err;
336 }
337
338 /*
339  * Function kingsun_net_close (kingsun)
340  *
341  *    Network device is taken down. Usually this is done by
342  *    "ifconfig irda0 down"
343  */
344 static int kingsun_net_close(struct net_device *netdev)
345 {
346         struct kingsun_cb *kingsun = netdev_priv(netdev);
347
348         /* Stop transmit processing */
349         netif_stop_queue(netdev);
350
351         /* Mop up receive && transmit urb's */
352         usb_kill_urb(kingsun->tx_urb);
353         usb_kill_urb(kingsun->rx_urb);
354
355         usb_free_urb(kingsun->tx_urb);
356         usb_free_urb(kingsun->rx_urb);
357
358         kingsun->tx_urb = NULL;
359         kingsun->rx_urb = NULL;
360
361         kfree_skb(kingsun->rx_buff.skb);
362         kingsun->rx_buff.skb = NULL;
363         kingsun->rx_buff.head = NULL;
364         kingsun->rx_buff.in_frame = FALSE;
365         kingsun->rx_buff.state = OUTSIDE_FRAME;
366         kingsun->receiving = 0;
367
368         /* Stop and remove instance of IrLAP */
369         if (kingsun->irlap)
370                 irlap_close(kingsun->irlap);
371
372         kingsun->irlap = NULL;
373
374         return 0;
375 }
376
377 /*
378  * IOCTLs : Extra out-of-band network commands...
379  */
380 static int kingsun_net_ioctl(struct net_device *netdev, struct ifreq *rq,
381                              int cmd)
382 {
383         struct if_irda_req *irq = (struct if_irda_req *) rq;
384         struct kingsun_cb *kingsun = netdev_priv(netdev);
385         int ret = 0;
386
387         switch (cmd) {
388         case SIOCSBANDWIDTH: /* Set bandwidth */
389                 if (!capable(CAP_NET_ADMIN))
390                         return -EPERM;
391
392                 /* Check if the device is still there */
393                 if (netif_device_present(kingsun->netdev))
394                         /* No observed commands for speed change */
395                         ret = -EOPNOTSUPP;
396                 break;
397
398         case SIOCSMEDIABUSY: /* Set media busy */
399                 if (!capable(CAP_NET_ADMIN))
400                         return -EPERM;
401
402                 /* Check if the IrDA stack is still there */
403                 if (netif_running(kingsun->netdev))
404                         irda_device_set_media_busy(kingsun->netdev, TRUE);
405                 break;
406
407         case SIOCGRECEIVING:
408                 /* Only approximately true */
409                 irq->ifr_receiving = kingsun->receiving;
410                 break;
411
412         default:
413                 ret = -EOPNOTSUPP;
414         }
415
416         return ret;
417 }
418
419 static const struct net_device_ops kingsun_ops = {
420         .ndo_start_xmit      = kingsun_hard_xmit,
421         .ndo_open            = kingsun_net_open,
422         .ndo_stop            = kingsun_net_close,
423         .ndo_do_ioctl        = kingsun_net_ioctl,
424 };
425
426 /*
427  * This routine is called by the USB subsystem for each new device
428  * in the system. We need to check if the device is ours, and in
429  * this case start handling it.
430  */
431 static int kingsun_probe(struct usb_interface *intf,
432                       const struct usb_device_id *id)
433 {
434         struct usb_host_interface *interface;
435         struct usb_endpoint_descriptor *endpoint;
436
437         struct usb_device *dev = interface_to_usbdev(intf);
438         struct kingsun_cb *kingsun = NULL;
439         struct net_device *net = NULL;
440         int ret = -ENOMEM;
441         int pipe, maxp_in, maxp_out;
442         __u8 ep_in;
443         __u8 ep_out;
444
445         /* Check that there really are two interrupt endpoints.
446            Check based on the one in drivers/usb/input/usbmouse.c
447          */
448         interface = intf->cur_altsetting;
449         if (interface->desc.bNumEndpoints != 2) {
450                 err("kingsun-sir: expected 2 endpoints, found %d",
451                     interface->desc.bNumEndpoints);
452                 return -ENODEV;
453         }
454         endpoint = &interface->endpoint[KINGSUN_EP_IN].desc;
455         if (!usb_endpoint_is_int_in(endpoint)) {
456                 err("kingsun-sir: endpoint 0 is not interrupt IN");
457                 return -ENODEV;
458         }
459
460         ep_in = endpoint->bEndpointAddress;
461         pipe = usb_rcvintpipe(dev, ep_in);
462         maxp_in = usb_maxpacket(dev, pipe, usb_pipeout(pipe));
463         if (maxp_in > 255 || maxp_in <= 1) {
464                 err("%s: endpoint 0 has max packet size %d not in range",
465                     __FILE__, maxp_in);
466                 return -ENODEV;
467         }
468
469         endpoint = &interface->endpoint[KINGSUN_EP_OUT].desc;
470         if (!usb_endpoint_is_int_out(endpoint)) {
471                 err("kingsun-sir: endpoint 1 is not interrupt OUT");
472                 return -ENODEV;
473         }
474
475         ep_out = endpoint->bEndpointAddress;
476         pipe = usb_sndintpipe(dev, ep_out);
477         maxp_out = usb_maxpacket(dev, pipe, usb_pipeout(pipe));
478
479         /* Allocate network device container. */
480         net = alloc_irdadev(sizeof(*kingsun));
481         if(!net)
482                 goto err_out1;
483
484         SET_NETDEV_DEV(net, &intf->dev);
485         kingsun = netdev_priv(net);
486         kingsun->irlap = NULL;
487         kingsun->tx_urb = NULL;
488         kingsun->rx_urb = NULL;
489         kingsun->ep_in = ep_in;
490         kingsun->ep_out = ep_out;
491         kingsun->in_buf = NULL;
492         kingsun->out_buf = NULL;
493         kingsun->max_rx = (__u8)maxp_in;
494         kingsun->max_tx = (__u8)maxp_out;
495         kingsun->netdev = net;
496         kingsun->usbdev = dev;
497         kingsun->rx_buff.in_frame = FALSE;
498         kingsun->rx_buff.state = OUTSIDE_FRAME;
499         kingsun->rx_buff.skb = NULL;
500         kingsun->receiving = 0;
501         spin_lock_init(&kingsun->lock);
502
503         /* Allocate input buffer */
504         kingsun->in_buf = kmalloc(kingsun->max_rx, GFP_KERNEL);
505         if (!kingsun->in_buf)
506                 goto free_mem;
507
508         /* Allocate output buffer */
509         kingsun->out_buf = kmalloc(KINGSUN_FIFO_SIZE, GFP_KERNEL);
510         if (!kingsun->out_buf)
511                 goto free_mem;
512
513         printk(KERN_INFO "KingSun/DonShine IRDA/USB found at address %d, "
514                 "Vendor: %x, Product: %x\n",
515                dev->devnum, le16_to_cpu(dev->descriptor.idVendor),
516                le16_to_cpu(dev->descriptor.idProduct));
517
518         /* Initialize QoS for this device */
519         irda_init_max_qos_capabilies(&kingsun->qos);
520
521         /* That's the Rx capability. */
522         kingsun->qos.baud_rate.bits       &= IR_9600;
523         kingsun->qos.min_turn_time.bits   &= KINGSUN_MTT;
524         irda_qos_bits_to_value(&kingsun->qos);
525
526         /* Override the network functions we need to use */
527         net->netdev_ops = &kingsun_ops;
528
529         ret = register_netdev(net);
530         if (ret != 0)
531                 goto free_mem;
532
533         dev_info(&net->dev, "IrDA: Registered KingSun/DonShine device %s\n",
534                  net->name);
535
536         usb_set_intfdata(intf, kingsun);
537
538         /* Situation at this point:
539            - all work buffers allocated
540            - urbs not allocated, set to NULL
541            - max rx packet known (in max_rx)
542            - unwrap state machine (partially) initialized, but skb == NULL
543          */
544
545         return 0;
546
547 free_mem:
548         if (kingsun->out_buf) kfree(kingsun->out_buf);
549         if (kingsun->in_buf) kfree(kingsun->in_buf);
550         free_netdev(net);
551 err_out1:
552         return ret;
553 }
554
555 /*
556  * The current device is removed, the USB layer tell us to shut it down...
557  */
558 static void kingsun_disconnect(struct usb_interface *intf)
559 {
560         struct kingsun_cb *kingsun = usb_get_intfdata(intf);
561
562         if (!kingsun)
563                 return;
564
565         unregister_netdev(kingsun->netdev);
566
567         /* Mop up receive && transmit urb's */
568         if (kingsun->tx_urb != NULL) {
569                 usb_kill_urb(kingsun->tx_urb);
570                 usb_free_urb(kingsun->tx_urb);
571                 kingsun->tx_urb = NULL;
572         }
573         if (kingsun->rx_urb != NULL) {
574                 usb_kill_urb(kingsun->rx_urb);
575                 usb_free_urb(kingsun->rx_urb);
576                 kingsun->rx_urb = NULL;
577         }
578
579         kfree(kingsun->out_buf);
580         kfree(kingsun->in_buf);
581         free_netdev(kingsun->netdev);
582
583         usb_set_intfdata(intf, NULL);
584 }
585
586 #ifdef CONFIG_PM
587 /* USB suspend, so power off the transmitter/receiver */
588 static int kingsun_suspend(struct usb_interface *intf, pm_message_t message)
589 {
590         struct kingsun_cb *kingsun = usb_get_intfdata(intf);
591
592         netif_device_detach(kingsun->netdev);
593         if (kingsun->tx_urb != NULL) usb_kill_urb(kingsun->tx_urb);
594         if (kingsun->rx_urb != NULL) usb_kill_urb(kingsun->rx_urb);
595         return 0;
596 }
597
598 /* Coming out of suspend, so reset hardware */
599 static int kingsun_resume(struct usb_interface *intf)
600 {
601         struct kingsun_cb *kingsun = usb_get_intfdata(intf);
602
603         if (kingsun->rx_urb != NULL)
604                 usb_submit_urb(kingsun->rx_urb, GFP_KERNEL);
605         netif_device_attach(kingsun->netdev);
606
607         return 0;
608 }
609 #endif
610
611 /*
612  * USB device callbacks
613  */
614 static struct usb_driver irda_driver = {
615         .name           = "kingsun-sir",
616         .probe          = kingsun_probe,
617         .disconnect     = kingsun_disconnect,
618         .id_table       = dongles,
619 #ifdef CONFIG_PM
620         .suspend        = kingsun_suspend,
621         .resume         = kingsun_resume,
622 #endif
623 };
624
625 /*
626  * Module insertion
627  */
628 static int __init kingsun_init(void)
629 {
630         return usb_register(&irda_driver);
631 }
632 module_init(kingsun_init);
633
634 /*
635  * Module removal
636  */
637 static void __exit kingsun_cleanup(void)
638 {
639         /* Deregister the driver and remove all pending instances */
640         usb_deregister(&irda_driver);
641 }
642 module_exit(kingsun_cleanup);
643
644 MODULE_AUTHOR("Alex Villacís Lasso <a_villacis@palosanto.com>");
645 MODULE_DESCRIPTION("IrDA-USB Dongle Driver for KingSun/DonShine");
646 MODULE_LICENSE("GPL");