6e2ec56cde0b1042d4c5b65289295abeca74a4a8
[linux-2.6.git] / drivers / net / irda / irda-usb.c
1 /*****************************************************************************
2  *
3  * Filename:      irda-usb.c
4  * Version:       0.9b
5  * Description:   IrDA-USB Driver
6  * Status:        Experimental 
7  * Author:        Dag Brattli <dag@brattli.net>
8  *
9  *      Copyright (C) 2000, Roman Weissgaerber <weissg@vienna.at>
10  *      Copyright (C) 2001, Dag Brattli <dag@brattli.net>
11  *      Copyright (C) 2001, Jean Tourrilhes <jt@hpl.hp.com>
12  *          
13  *      This program is free software; you can redistribute it and/or modify
14  *      it under the terms of the GNU General Public License as published by
15  *      the Free Software Foundation; either version 2 of the License, or
16  *      (at your option) any later version.
17  *
18  *      This program is distributed in the hope that it will be useful,
19  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
20  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  *      GNU General Public License for more details.
22  *
23  *      You should have received a copy of the GNU General Public License
24  *      along with this program; if not, write to the Free Software
25  *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
26  *
27  *****************************************************************************/
28
29 /*
30  *                          IMPORTANT NOTE
31  *                          --------------
32  *
33  * As of kernel 2.5.20, this is the state of compliance and testing of
34  * this driver (irda-usb) with regards to the USB low level drivers...
35  *
36  * This driver has been tested SUCCESSFULLY with the following drivers :
37  *      o usb-uhci-hcd  (For Intel/Via USB controllers)
38  *      o uhci-hcd      (Alternate/JE driver for Intel/Via USB controllers)
39  *      o ohci-hcd      (For other USB controllers)
40  *
41  * This driver has NOT been tested with the following drivers :
42  *      o ehci-hcd      (USB 2.0 controllers)
43  *
44  * Note that all HCD drivers do URB_ZERO_PACKET and timeout properly,
45  * so we don't have to worry about that anymore.
46  * One common problem is the failure to set the address on the dongle,
47  * but this happens before the driver gets loaded...
48  *
49  * Jean II
50  */
51
52 /*------------------------------------------------------------------*/
53
54 #include <linux/module.h>
55 #include <linux/moduleparam.h>
56 #include <linux/kernel.h>
57 #include <linux/types.h>
58 #include <linux/init.h>
59 #include <linux/skbuff.h>
60 #include <linux/netdevice.h>
61 #include <linux/slab.h>
62 #include <linux/rtnetlink.h>
63 #include <linux/usb.h>
64
65 #include "irda-usb.h"
66
67 /*------------------------------------------------------------------*/
68
69 static int qos_mtt_bits = 0;
70
71 /* These are the currently known IrDA USB dongles. Add new dongles here */
72 static struct usb_device_id dongles[] = {
73         /* ACTiSYS Corp.,  ACT-IR2000U FIR-USB Adapter */
74         { USB_DEVICE(0x9c4, 0x011), .driver_info = IUC_SPEED_BUG | IUC_NO_WINDOW },
75         /* Look like ACTiSYS, Report : IBM Corp., IBM UltraPort IrDA */
76         { USB_DEVICE(0x4428, 0x012), .driver_info = IUC_SPEED_BUG | IUC_NO_WINDOW },
77         /* KC Technology Inc.,  KC-180 USB IrDA Device */
78         { USB_DEVICE(0x50f, 0x180), .driver_info = IUC_SPEED_BUG | IUC_NO_WINDOW },
79         /* Extended Systems, Inc.,  XTNDAccess IrDA USB (ESI-9685) */
80         { USB_DEVICE(0x8e9, 0x100), .driver_info = IUC_SPEED_BUG | IUC_NO_WINDOW },
81         { .match_flags = USB_DEVICE_ID_MATCH_INT_CLASS |
82                        USB_DEVICE_ID_MATCH_INT_SUBCLASS,
83           .bInterfaceClass = USB_CLASS_APP_SPEC,
84           .bInterfaceSubClass = USB_CLASS_IRDA,
85           .driver_info = IUC_DEFAULT, },
86         { }, /* The end */
87 };
88
89 /*
90  * Important note :
91  * Devices based on the SigmaTel chipset (0x66f, 0x4200) are not designed
92  * using the "USB-IrDA specification" (yes, there exist such a thing), and
93  * therefore not supported by this driver (don't add them above).
94  * There is a Linux driver, stir4200, that support those USB devices.
95  * Jean II
96  */
97
98 MODULE_DEVICE_TABLE(usb, dongles);
99
100 /*------------------------------------------------------------------*/
101
102 static struct irda_class_desc *irda_usb_find_class_desc(struct usb_interface *intf);
103 static void irda_usb_disconnect(struct usb_interface *intf);
104 static void irda_usb_change_speed_xbofs(struct irda_usb_cb *self);
105 static int irda_usb_hard_xmit(struct sk_buff *skb, struct net_device *dev);
106 static int irda_usb_open(struct irda_usb_cb *self);
107 static void irda_usb_close(struct irda_usb_cb *self);
108 static void speed_bulk_callback(struct urb *urb, struct pt_regs *regs);
109 static void write_bulk_callback(struct urb *urb, struct pt_regs *regs);
110 static void irda_usb_receive(struct urb *urb, struct pt_regs *regs);
111 static void irda_usb_rx_defer_expired(unsigned long data);
112 static int irda_usb_net_open(struct net_device *dev);
113 static int irda_usb_net_close(struct net_device *dev);
114 static int irda_usb_net_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
115 static void irda_usb_net_timeout(struct net_device *dev);
116 static struct net_device_stats *irda_usb_net_get_stats(struct net_device *dev);
117
118 /************************ TRANSMIT ROUTINES ************************/
119 /*
120  * Receive packets from the IrDA stack and send them on the USB pipe.
121  * Handle speed change, timeout and lot's of ugliness...
122  */
123
124 /*------------------------------------------------------------------*/
125 /*
126  * Function irda_usb_build_header(self, skb, header)
127  *
128  *   Builds USB-IrDA outbound header
129  *
130  * When we send an IrDA frame over an USB pipe, we add to it a 1 byte
131  * header. This function create this header with the proper values.
132  *
133  * Important note : the USB-IrDA spec 1.0 say very clearly in chapter 5.4.2.2
134  * that the setting of the link speed and xbof number in this outbound header
135  * should be applied *AFTER* the frame has been sent.
136  * Unfortunately, some devices are not compliant with that... It seems that
137  * reading the spec is far too difficult...
138  * Jean II
139  */
140 static void irda_usb_build_header(struct irda_usb_cb *self,
141                                   __u8 *header,
142                                   int   force)
143 {
144         /* Set the negotiated link speed */
145         if (self->new_speed != -1) {
146                 /* Hum... Ugly hack :-(
147                  * Some device are not compliant with the spec and change
148                  * parameters *before* sending the frame. - Jean II
149                  */
150                 if ((self->capability & IUC_SPEED_BUG) &&
151                     (!force) && (self->speed != -1)) {
152                         /* No speed and xbofs change here
153                          * (we'll do it later in the write callback) */
154                         IRDA_DEBUG(2, "%s(), not changing speed yet\n", __FUNCTION__);
155                         *header = 0;
156                         return;
157                 }
158
159                 IRDA_DEBUG(2, "%s(), changing speed to %d\n", __FUNCTION__, self->new_speed);
160                 self->speed = self->new_speed;
161                 /* We will do ` self->new_speed = -1; ' in the completion
162                  * handler just in case the current URB fail - Jean II */
163
164                 switch (self->speed) {
165                 case 2400:
166                         *header = SPEED_2400;
167                         break;
168                 default:
169                 case 9600:
170                         *header = SPEED_9600;
171                         break;
172                 case 19200:
173                         *header = SPEED_19200;
174                         break;
175                 case 38400:
176                         *header = SPEED_38400;
177                         break;
178                 case 57600:
179                         *header = SPEED_57600;
180                         break;
181                 case 115200:
182                         *header = SPEED_115200;
183                         break;
184                 case 576000:
185                         *header = SPEED_576000;
186                         break;
187                 case 1152000:
188                         *header = SPEED_1152000;
189                         break;
190                 case 4000000:
191                         *header = SPEED_4000000;
192                         self->new_xbofs = 0;
193                         break;
194                 }
195         } else
196                 /* No change */
197                 *header = 0;
198         
199         /* Set the negotiated additional XBOFS */
200         if (self->new_xbofs != -1) {
201                 IRDA_DEBUG(2, "%s(), changing xbofs to %d\n", __FUNCTION__, self->new_xbofs);
202                 self->xbofs = self->new_xbofs;
203                 /* We will do ` self->new_xbofs = -1; ' in the completion
204                  * handler just in case the current URB fail - Jean II */
205
206                 switch (self->xbofs) {
207                 case 48:
208                         *header |= 0x10;
209                         break;
210                 case 28:
211                 case 24:        /* USB spec 1.0 says 24 */
212                         *header |= 0x20;
213                         break;
214                 default:
215                 case 12:
216                         *header |= 0x30;
217                         break;
218                 case 5: /* Bug in IrLAP spec? (should be 6) */
219                 case 6:
220                         *header |= 0x40;
221                         break;
222                 case 3:
223                         *header |= 0x50;
224                         break;
225                 case 2:
226                         *header |= 0x60;
227                         break;
228                 case 1:
229                         *header |= 0x70;
230                         break;
231                 case 0:
232                         *header |= 0x80;
233                         break;
234                 }
235         }
236 }
237
238 /*------------------------------------------------------------------*/
239 /*
240  * Send a command to change the speed of the dongle
241  * Need to be called with spinlock on.
242  */
243 static void irda_usb_change_speed_xbofs(struct irda_usb_cb *self)
244 {
245         __u8 *frame;
246         struct urb *urb;
247         int ret;
248
249         IRDA_DEBUG(2, "%s(), speed=%d, xbofs=%d\n", __FUNCTION__,
250                    self->new_speed, self->new_xbofs);
251
252         /* Grab the speed URB */
253         urb = self->speed_urb;
254         if (urb->status != 0) {
255                 IRDA_WARNING("%s(), URB still in use!\n", __FUNCTION__);
256                 return;
257         }
258
259         /* Allocate the fake frame */
260         frame = self->speed_buff;
261
262         /* Set the new speed and xbofs in this fake frame */
263         irda_usb_build_header(self, frame, 1);
264
265         /* Submit the 0 length IrDA frame to trigger new speed settings */
266         usb_fill_bulk_urb(urb, self->usbdev,
267                       usb_sndbulkpipe(self->usbdev, self->bulk_out_ep),
268                       frame, IRDA_USB_SPEED_MTU,
269                       speed_bulk_callback, self);
270         urb->transfer_buffer_length = USB_IRDA_HEADER;
271         urb->transfer_flags = 0;
272
273         /* Irq disabled -> GFP_ATOMIC */
274         if ((ret = usb_submit_urb(urb, GFP_ATOMIC))) {
275                 IRDA_WARNING("%s(), failed Speed URB\n", __FUNCTION__);
276         }
277 }
278
279 /*------------------------------------------------------------------*/
280 /*
281  * Speed URB callback
282  * Now, we can only get called for the speed URB.
283  */
284 static void speed_bulk_callback(struct urb *urb, struct pt_regs *regs)
285 {
286         struct irda_usb_cb *self = urb->context;
287         
288         IRDA_DEBUG(2, "%s()\n", __FUNCTION__);
289
290         /* We should always have a context */
291         IRDA_ASSERT(self != NULL, return;);
292         /* We should always be called for the speed URB */
293         IRDA_ASSERT(urb == self->speed_urb, return;);
294
295         /* Check for timeout and other USB nasties */
296         if (urb->status != 0) {
297                 /* I get a lot of -ECONNABORTED = -103 here - Jean II */
298                 IRDA_DEBUG(0, "%s(), URB complete status %d, transfer_flags 0x%04X\n", __FUNCTION__, urb->status, urb->transfer_flags);
299
300                 /* Don't do anything here, that might confuse the USB layer.
301                  * Instead, we will wait for irda_usb_net_timeout(), the
302                  * network layer watchdog, to fix the situation.
303                  * Jean II */
304                 /* A reset of the dongle might be welcomed here - Jean II */
305                 return;
306         }
307
308         /* urb is now available */
309         //urb->status = 0; -> tested above
310
311         /* New speed and xbof is now commited in hardware */
312         self->new_speed = -1;
313         self->new_xbofs = -1;
314
315         /* Allow the stack to send more packets */
316         netif_wake_queue(self->netdev);
317 }
318
319 /*------------------------------------------------------------------*/
320 /*
321  * Send an IrDA frame to the USB dongle (for transmission)
322  */
323 static int irda_usb_hard_xmit(struct sk_buff *skb, struct net_device *netdev)
324 {
325         struct irda_usb_cb *self = netdev->priv;
326         struct urb *urb = self->tx_urb;
327         unsigned long flags;
328         s32 speed;
329         s16 xbofs;
330         int res, mtt;
331         int     err = 1;        /* Failed */
332
333         IRDA_DEBUG(4, "%s() on %s\n", __FUNCTION__, netdev->name);
334
335         netif_stop_queue(netdev);
336
337         /* Protect us from USB callbacks, net watchdog and else. */
338         spin_lock_irqsave(&self->lock, flags);
339
340         /* Check if the device is still there.
341          * We need to check self->present under the spinlock because
342          * of irda_usb_disconnect() is synchronous - Jean II */
343         if (!self->present) {
344                 IRDA_DEBUG(0, "%s(), Device is gone...\n", __FUNCTION__);
345                 goto drop;
346         }
347
348         /* Check if we need to change the number of xbofs */
349         xbofs = irda_get_next_xbofs(skb);
350         if ((xbofs != self->xbofs) && (xbofs != -1)) {
351                 self->new_xbofs = xbofs;
352         }
353
354         /* Check if we need to change the speed */
355         speed = irda_get_next_speed(skb);
356         if ((speed != self->speed) && (speed != -1)) {
357                 /* Set the desired speed */
358                 self->new_speed = speed;
359
360                 /* Check for empty frame */
361                 if (!skb->len) {
362                         /* IrLAP send us an empty frame to make us change the
363                          * speed. Changing speed with the USB adapter is in
364                          * fact sending an empty frame to the adapter, so we
365                          * could just let the present function do its job.
366                          * However, we would wait for min turn time,
367                          * do an extra memcpy and increment packet counters...
368                          * Jean II */
369                         irda_usb_change_speed_xbofs(self);
370                         netdev->trans_start = jiffies;
371                         /* Will netif_wake_queue() in callback */
372                         err = 0;        /* No error */
373                         goto drop;
374                 }
375         }
376
377         if (urb->status != 0) {
378                 IRDA_WARNING("%s(), URB still in use!\n", __FUNCTION__);
379                 goto drop;
380         }
381
382         /* Make sure there is room for IrDA-USB header. The actual
383          * allocation will be done lower in skb_push().
384          * Also, we don't use directly skb_cow(), because it require
385          * headroom >= 16, which force unnecessary copies - Jean II */
386         if (skb_headroom(skb) < USB_IRDA_HEADER) {
387                 IRDA_DEBUG(0, "%s(), Insuficient skb headroom.\n", __FUNCTION__);
388                 if (skb_cow(skb, USB_IRDA_HEADER)) {
389                         IRDA_WARNING("%s(), failed skb_cow() !!!\n", __FUNCTION__);
390                         goto drop;
391                 }
392         }
393
394         /* Change setting for next frame */
395         irda_usb_build_header(self, skb_push(skb, USB_IRDA_HEADER), 0);
396
397         /* FIXME: Make macro out of this one */
398         ((struct irda_skb_cb *)skb->cb)->context = self;
399
400         usb_fill_bulk_urb(urb, self->usbdev, 
401                       usb_sndbulkpipe(self->usbdev, self->bulk_out_ep),
402                       skb->data, IRDA_SKB_MAX_MTU,
403                       write_bulk_callback, skb);
404         urb->transfer_buffer_length = skb->len;
405         /* This flag (URB_ZERO_PACKET) indicates that what we send is not
406          * a continuous stream of data but separate packets.
407          * In this case, the USB layer will insert an empty USB frame (TD)
408          * after each of our packets that is exact multiple of the frame size.
409          * This is how the dongle will detect the end of packet - Jean II */
410         urb->transfer_flags = URB_ZERO_PACKET;
411
412         /* Generate min turn time. FIXME: can we do better than this? */
413         /* Trying to a turnaround time at this level is trying to measure
414          * processor clock cycle with a wrist-watch, approximate at best...
415          *
416          * What we know is the last time we received a frame over USB.
417          * Due to latency over USB that depend on the USB load, we don't
418          * know when this frame was received over IrDA (a few ms before ?)
419          * Then, same story for our outgoing frame...
420          *
421          * In theory, the USB dongle is supposed to handle the turnaround
422          * by itself (spec 1.0, chater 4, page 6). Who knows ??? That's
423          * why this code is enabled only for dongles that doesn't meet
424          * the spec.
425          * Jean II */
426         if (self->capability & IUC_NO_TURN) {
427                 mtt = irda_get_mtt(skb);
428                 if (mtt) {
429                         int diff;
430                         do_gettimeofday(&self->now);
431                         diff = self->now.tv_usec - self->stamp.tv_usec;
432 #ifdef IU_USB_MIN_RTT
433                         /* Factor in USB delays -> Get rid of udelay() that
434                          * would be lost in the noise - Jean II */
435                         diff += IU_USB_MIN_RTT;
436 #endif /* IU_USB_MIN_RTT */
437                         /* If the usec counter did wraparound, the diff will
438                          * go negative (tv_usec is a long), so we need to
439                          * correct it by one second. Jean II */
440                         if (diff < 0)
441                                 diff += 1000000;
442
443                         /* Check if the mtt is larger than the time we have
444                          * already used by all the protocol processing
445                          */
446                         if (mtt > diff) {
447                                 mtt -= diff;
448                                 if (mtt > 1000)
449                                         mdelay(mtt/1000);
450                                 else
451                                         udelay(mtt);
452                         }
453                 }
454         }
455         
456         /* Ask USB to send the packet - Irq disabled -> GFP_ATOMIC */
457         if ((res = usb_submit_urb(urb, GFP_ATOMIC))) {
458                 IRDA_WARNING("%s(), failed Tx URB\n", __FUNCTION__);
459                 self->stats.tx_errors++;
460                 /* Let USB recover : We will catch that in the watchdog */
461                 /*netif_start_queue(netdev);*/
462         } else {
463                 /* Increment packet stats */
464                 self->stats.tx_packets++;
465                 self->stats.tx_bytes += skb->len;
466                 
467                 netdev->trans_start = jiffies;
468         }
469         spin_unlock_irqrestore(&self->lock, flags);
470         
471         return 0;
472
473 drop:
474         /* Drop silently the skb and exit */
475         dev_kfree_skb(skb);
476         spin_unlock_irqrestore(&self->lock, flags);
477         return err;             /* Usually 1 */
478 }
479
480 /*------------------------------------------------------------------*/
481 /*
482  * Note : this function will be called only for tx_urb...
483  */
484 static void write_bulk_callback(struct urb *urb, struct pt_regs *regs)
485 {
486         unsigned long flags;
487         struct sk_buff *skb = urb->context;
488         struct irda_usb_cb *self = ((struct irda_skb_cb *) skb->cb)->context;
489         
490         IRDA_DEBUG(2, "%s()\n", __FUNCTION__);
491
492         /* We should always have a context */
493         IRDA_ASSERT(self != NULL, return;);
494         /* We should always be called for the speed URB */
495         IRDA_ASSERT(urb == self->tx_urb, return;);
496
497         /* Free up the skb */
498         dev_kfree_skb_any(skb);
499         urb->context = NULL;
500
501         /* Check for timeout and other USB nasties */
502         if (urb->status != 0) {
503                 /* I get a lot of -ECONNABORTED = -103 here - Jean II */
504                 IRDA_DEBUG(0, "%s(), URB complete status %d, transfer_flags 0x%04X\n", __FUNCTION__, urb->status, urb->transfer_flags);
505
506                 /* Don't do anything here, that might confuse the USB layer,
507                  * and we could go in recursion and blow the kernel stack...
508                  * Instead, we will wait for irda_usb_net_timeout(), the
509                  * network layer watchdog, to fix the situation.
510                  * Jean II */
511                 /* A reset of the dongle might be welcomed here - Jean II */
512                 return;
513         }
514
515         /* urb is now available */
516         //urb->status = 0; -> tested above
517
518         /* Make sure we read self->present properly */
519         spin_lock_irqsave(&self->lock, flags);
520
521         /* If the network is closed, stop everything */
522         if ((!self->netopen) || (!self->present)) {
523                 IRDA_DEBUG(0, "%s(), Network is gone...\n", __FUNCTION__);
524                 spin_unlock_irqrestore(&self->lock, flags);
525                 return;
526         }
527
528         /* If changes to speed or xbofs is pending... */
529         if ((self->new_speed != -1) || (self->new_xbofs != -1)) {
530                 if ((self->new_speed != self->speed) ||
531                     (self->new_xbofs != self->xbofs)) {
532                         /* We haven't changed speed yet (because of
533                          * IUC_SPEED_BUG), so do it now - Jean II */
534                         IRDA_DEBUG(1, "%s(), Changing speed now...\n", __FUNCTION__);
535                         irda_usb_change_speed_xbofs(self);
536                 } else {
537                         /* New speed and xbof is now commited in hardware */
538                         self->new_speed = -1;
539                         self->new_xbofs = -1;
540                         /* Done, waiting for next packet */
541                         netif_wake_queue(self->netdev);
542                 }
543         } else {
544                 /* Otherwise, allow the stack to send more packets */
545                 netif_wake_queue(self->netdev);
546         }
547         spin_unlock_irqrestore(&self->lock, flags);
548 }
549
550 /*------------------------------------------------------------------*/
551 /*
552  * Watchdog timer from the network layer.
553  * After a predetermined timeout, if we don't give confirmation that
554  * the packet has been sent (i.e. no call to netif_wake_queue()),
555  * the network layer will call this function.
556  * Note that URB that we submit have also a timeout. When the URB timeout
557  * expire, the normal URB callback is called (write_bulk_callback()).
558  */
559 static void irda_usb_net_timeout(struct net_device *netdev)
560 {
561         unsigned long flags;
562         struct irda_usb_cb *self = netdev->priv;
563         struct urb *urb;
564         int     done = 0;       /* If we have made any progress */
565
566         IRDA_DEBUG(0, "%s(), Network layer thinks we timed out!\n", __FUNCTION__);
567         IRDA_ASSERT(self != NULL, return;);
568
569         /* Protect us from USB callbacks, net Tx and else. */
570         spin_lock_irqsave(&self->lock, flags);
571
572         /* self->present *MUST* be read under spinlock */
573         if (!self->present) {
574                 IRDA_WARNING("%s(), device not present!\n", __FUNCTION__);
575                 netif_stop_queue(netdev);
576                 spin_unlock_irqrestore(&self->lock, flags);
577                 return;
578         }
579
580         /* Check speed URB */
581         urb = self->speed_urb;
582         if (urb->status != 0) {
583                 IRDA_DEBUG(0, "%s: Speed change timed out, urb->status=%d, urb->transfer_flags=0x%04X\n", netdev->name, urb->status, urb->transfer_flags);
584
585                 switch (urb->status) {
586                 case -EINPROGRESS:
587                         usb_unlink_urb(urb);
588                         /* Note : above will  *NOT* call netif_wake_queue()
589                          * in completion handler, we will come back here.
590                          * Jean II */
591                         done = 1;
592                         break;
593                 case -ECONNABORTED:             /* -103 */
594                 case -ECONNRESET:               /* -104 */
595                 case -ETIMEDOUT:                /* -110 */
596                 case -ENOENT:                   /* -2 (urb unlinked by us)  */
597                 default:                        /* ??? - Play safe */
598                         urb->status = 0;
599                         netif_wake_queue(self->netdev);
600                         done = 1;
601                         break;
602                 }
603         }
604
605         /* Check Tx URB */
606         urb = self->tx_urb;
607         if (urb->status != 0) {
608                 struct sk_buff *skb = urb->context;
609
610                 IRDA_DEBUG(0, "%s: Tx timed out, urb->status=%d, urb->transfer_flags=0x%04X\n", netdev->name, urb->status, urb->transfer_flags);
611
612                 /* Increase error count */
613                 self->stats.tx_errors++;
614
615 #ifdef IU_BUG_KICK_TIMEOUT
616                 /* Can't be a bad idea to reset the speed ;-) - Jean II */
617                 if(self->new_speed == -1)
618                         self->new_speed = self->speed;
619                 if(self->new_xbofs == -1)
620                         self->new_xbofs = self->xbofs;
621                 irda_usb_change_speed_xbofs(self);
622 #endif /* IU_BUG_KICK_TIMEOUT */
623
624                 switch (urb->status) {
625                 case -EINPROGRESS:
626                         usb_unlink_urb(urb);
627                         /* Note : above will  *NOT* call netif_wake_queue()
628                          * in completion handler, because urb->status will
629                          * be -ENOENT. We will fix that at the next watchdog,
630                          * leaving more time to USB to recover...
631                          * Jean II */
632                         done = 1;
633                         break;
634                 case -ECONNABORTED:             /* -103 */
635                 case -ECONNRESET:               /* -104 */
636                 case -ETIMEDOUT:                /* -110 */
637                 case -ENOENT:                   /* -2 (urb unlinked by us)  */
638                 default:                        /* ??? - Play safe */
639                         if(skb != NULL) {
640                                 dev_kfree_skb_any(skb);
641                                 urb->context = NULL;
642                         }
643                         urb->status = 0;
644                         netif_wake_queue(self->netdev);
645                         done = 1;
646                         break;
647                 }
648         }
649         spin_unlock_irqrestore(&self->lock, flags);
650
651         /* Maybe we need a reset */
652         /* Note : Some drivers seem to use a usb_set_interface() when they
653          * need to reset the hardware. Hum...
654          */
655
656         /* if(done == 0) */
657 }
658
659 /************************* RECEIVE ROUTINES *************************/
660 /*
661  * Receive packets from the USB layer stack and pass them to the IrDA stack.
662  * Try to work around USB failures...
663  */
664
665 /*
666  * Note :
667  * Some of you may have noticed that most dongle have an interrupt in pipe
668  * that we don't use. Here is the little secret...
669  * When we hang a Rx URB on the bulk in pipe, it generates some USB traffic
670  * in every USB frame. This is unnecessary overhead.
671  * The interrupt in pipe will generate an event every time a packet is
672  * received. Reading an interrupt pipe adds minimal overhead, but has some
673  * latency (~1ms).
674  * If we are connected (speed != 9600), we want to minimise latency, so
675  * we just always hang the Rx URB and ignore the interrupt.
676  * If we are not connected (speed == 9600), there is usually no Rx traffic,
677  * and we want to minimise the USB overhead. In this case we should wait
678  * on the interrupt pipe and hang the Rx URB only when an interrupt is
679  * received.
680  * Jean II
681  *
682  * Note : don't read the above as what we are currently doing, but as
683  * something we could do with KC dongle. Also don't forget that the
684  * interrupt pipe is not part of the original standard, so this would
685  * need to be optional...
686  * Jean II
687  */
688
689 /*------------------------------------------------------------------*/
690 /*
691  * Submit a Rx URB to the USB layer to handle reception of a frame
692  * Mostly called by the completion callback of the previous URB.
693  *
694  * Jean II
695  */
696 static void irda_usb_submit(struct irda_usb_cb *self, struct sk_buff *skb, struct urb *urb)
697 {
698         struct irda_skb_cb *cb;
699         int ret;
700
701         IRDA_DEBUG(2, "%s()\n", __FUNCTION__);
702
703         /* This should never happen */
704         IRDA_ASSERT(skb != NULL, return;);
705         IRDA_ASSERT(urb != NULL, return;);
706
707         /* Save ourselves in the skb */
708         cb = (struct irda_skb_cb *) skb->cb;
709         cb->context = self;
710
711         /* Reinitialize URB */
712         usb_fill_bulk_urb(urb, self->usbdev, 
713                       usb_rcvbulkpipe(self->usbdev, self->bulk_in_ep), 
714                       skb->data, IRDA_SKB_MAX_MTU,
715                       irda_usb_receive, skb);
716         urb->status = 0;
717
718         /* Can be called from irda_usb_receive (irq handler) -> GFP_ATOMIC */
719         ret = usb_submit_urb(urb, GFP_ATOMIC);
720         if (ret) {
721                 /* If this ever happen, we are in deep s***.
722                  * Basically, the Rx path will stop... */
723                 IRDA_WARNING("%s(), Failed to submit Rx URB %d\n",
724                              __FUNCTION__, ret);
725         }
726 }
727
728 /*------------------------------------------------------------------*/
729 /*
730  * Function irda_usb_receive(urb)
731  *
732  *     Called by the USB subsystem when a frame has been received
733  *
734  */
735 static void irda_usb_receive(struct urb *urb, struct pt_regs *regs)
736 {
737         struct sk_buff *skb = (struct sk_buff *) urb->context;
738         struct irda_usb_cb *self; 
739         struct irda_skb_cb *cb;
740         struct sk_buff *newskb;
741         struct sk_buff *dataskb;
742         struct urb *next_urb;
743         unsigned int len, docopy;
744
745         IRDA_DEBUG(2, "%s(), len=%d\n", __FUNCTION__, urb->actual_length);
746         
747         /* Find ourselves */
748         cb = (struct irda_skb_cb *) skb->cb;
749         IRDA_ASSERT(cb != NULL, return;);
750         self = (struct irda_usb_cb *) cb->context;
751         IRDA_ASSERT(self != NULL, return;);
752
753         /* If the network is closed or the device gone, stop everything */
754         if ((!self->netopen) || (!self->present)) {
755                 IRDA_DEBUG(0, "%s(), Network is gone!\n", __FUNCTION__);
756                 /* Don't re-submit the URB : will stall the Rx path */
757                 return;
758         }
759         
760         /* Check the status */
761         if (urb->status != 0) {
762                 switch (urb->status) {
763                 case -EILSEQ:
764                         self->stats.rx_crc_errors++;    
765                         /* Also precursor to a hot-unplug on UHCI. */
766                         /* Fallthrough... */
767                 case -ECONNRESET:               /* -104 */
768                         /* Random error, if I remember correctly */
769                         /* uhci_cleanup_unlink() is going to kill the Rx
770                          * URB just after we return. No problem, at this
771                          * point the URB will be idle ;-) - Jean II */
772                 case -ESHUTDOWN:                /* -108 */
773                         /* That's usually a hot-unplug. Submit will fail... */
774                 case -ETIMEDOUT:                /* -110 */
775                         /* Usually precursor to a hot-unplug on OHCI. */
776                 default:
777                         self->stats.rx_errors++;
778                         IRDA_DEBUG(0, "%s(), RX status %d, transfer_flags 0x%04X \n", __FUNCTION__, urb->status, urb->transfer_flags);
779                         break;
780                 }
781                 /* If we received an error, we don't want to resubmit the
782                  * Rx URB straight away but to give the USB layer a little
783                  * bit of breathing room.
784                  * We are in the USB thread context, therefore there is a
785                  * danger of recursion (new URB we submit fails, we come
786                  * back here).
787                  * With recent USB stack (2.6.15+), I'm seeing that on
788                  * hot unplug of the dongle...
789                  * Lowest effective timer is 10ms...
790                  * Jean II */
791                 self->rx_defer_timer.function = &irda_usb_rx_defer_expired;
792                 self->rx_defer_timer.data = (unsigned long) urb;
793                 mod_timer(&self->rx_defer_timer, jiffies + (10 * HZ / 1000));
794                 return;
795         }
796         
797         /* Check for empty frames */
798         if (urb->actual_length <= USB_IRDA_HEADER) {
799                 IRDA_WARNING("%s(), empty frame!\n", __FUNCTION__);
800                 goto done;
801         }
802
803         /*  
804          * Remember the time we received this frame, so we can
805          * reduce the min turn time a bit since we will know
806          * how much time we have used for protocol processing
807          */
808         do_gettimeofday(&self->stamp);
809
810         /* Check if we need to copy the data to a new skb or not.
811          * For most frames, we use ZeroCopy and pass the already
812          * allocated skb up the stack.
813          * If the frame is small, it is more efficient to copy it
814          * to save memory (copy will be fast anyway - that's
815          * called Rx-copy-break). Jean II */
816         docopy = (urb->actual_length < IRDA_RX_COPY_THRESHOLD);
817
818         /* Allocate a new skb */
819         newskb = dev_alloc_skb(docopy ? urb->actual_length : IRDA_SKB_MAX_MTU);
820         if (!newskb)  {
821                 self->stats.rx_dropped++;
822                 /* We could deliver the current skb, but this would stall
823                  * the Rx path. Better drop the packet... Jean II */
824                 goto done;  
825         }
826
827         /* Make sure IP header get aligned (IrDA header is 5 bytes) */
828         /* But IrDA-USB header is 1 byte. Jean II */
829         //skb_reserve(newskb, USB_IRDA_HEADER - 1);
830
831         if(docopy) {
832                 /* Copy packet, so we can recycle the original */
833                 memcpy(newskb->data, skb->data, urb->actual_length);
834                 /* Deliver this new skb */
835                 dataskb = newskb;
836                 /* And hook the old skb to the URB
837                  * Note : we don't need to "clean up" the old skb,
838                  * as we never touched it. Jean II */
839         } else {
840                 /* We are using ZeroCopy. Deliver old skb */
841                 dataskb = skb;
842                 /* And hook the new skb to the URB */
843                 skb = newskb;
844         }
845
846         /* Set proper length on skb & remove USB-IrDA header */
847         skb_put(dataskb, urb->actual_length);
848         skb_pull(dataskb, USB_IRDA_HEADER);
849
850         /* Ask the networking layer to queue the packet for the IrDA stack */
851         dataskb->dev = self->netdev;
852         dataskb->mac.raw  = dataskb->data;
853         dataskb->protocol = htons(ETH_P_IRDA);
854         len = dataskb->len;
855         netif_rx(dataskb);
856
857         /* Keep stats up to date */
858         self->stats.rx_bytes += len;
859         self->stats.rx_packets++;
860         self->netdev->last_rx = jiffies;
861
862 done:
863         /* Note : at this point, the URB we've just received (urb)
864          * is still referenced by the USB layer. For example, if we
865          * have received a -ECONNRESET, uhci_cleanup_unlink() will
866          * continue to process it (in fact, cleaning it up).
867          * If we were to submit this URB, disaster would ensue.
868          * Therefore, we submit our idle URB, and put this URB in our
869          * idle slot....
870          * Jean II */
871         /* Note : with this scheme, we could submit the idle URB before
872          * processing the Rx URB. I don't think it would buy us anything as
873          * we are running in the USB thread context. Jean II */
874         next_urb = self->idle_rx_urb;
875
876         /* Recycle Rx URB : Now, the idle URB is the present one */
877         urb->context = NULL;
878         self->idle_rx_urb = urb;
879
880         /* Submit the idle URB to replace the URB we've just received.
881          * Do it last to avoid race conditions... Jean II */
882         irda_usb_submit(self, skb, next_urb);
883 }
884
885 /*------------------------------------------------------------------*/
886 /*
887  * In case of errors, we want the USB layer to have time to recover.
888  * Now, it is time to resubmit ouur Rx URB...
889  */
890 static void irda_usb_rx_defer_expired(unsigned long data)
891 {
892         struct urb *urb = (struct urb *) data;
893         struct sk_buff *skb = (struct sk_buff *) urb->context;
894         struct irda_usb_cb *self; 
895         struct irda_skb_cb *cb;
896         struct urb *next_urb;
897
898         IRDA_DEBUG(2, "%s()\n", __FUNCTION__);
899
900         /* Find ourselves */
901         cb = (struct irda_skb_cb *) skb->cb;
902         IRDA_ASSERT(cb != NULL, return;);
903         self = (struct irda_usb_cb *) cb->context;
904         IRDA_ASSERT(self != NULL, return;);
905
906         /* Same stuff as when Rx is done, see above... */
907         next_urb = self->idle_rx_urb;
908         urb->context = NULL;
909         self->idle_rx_urb = urb;
910         irda_usb_submit(self, skb, next_urb);
911 }
912
913 /*------------------------------------------------------------------*/
914 /*
915  * Callbak from IrDA layer. IrDA wants to know if we have
916  * started receiving anything.
917  */
918 static int irda_usb_is_receiving(struct irda_usb_cb *self)
919 {
920         /* Note : because of the way UHCI works, it's almost impossible
921          * to get this info. The Controller DMA directly to memory and
922          * signal only when the whole frame is finished. To know if the
923          * first TD of the URB has been filled or not seems hard work...
924          *
925          * The other solution would be to use the "receiving" command
926          * on the default decriptor with a usb_control_msg(), but that
927          * would add USB traffic and would return result only in the
928          * next USB frame (~1ms).
929          *
930          * I've been told that current dongles send status info on their
931          * interrupt endpoint, and that's what the Windows driver uses
932          * to know this info. Unfortunately, this is not yet in the spec...
933          *
934          * Jean II
935          */
936
937         return 0; /* For now */
938 }
939
940 /********************** IRDA DEVICE CALLBACKS **********************/
941 /*
942  * Main calls from the IrDA/Network subsystem.
943  * Mostly registering a new irda-usb device and removing it....
944  * We only deal with the IrDA side of the business, the USB side will
945  * be dealt with below...
946  */
947
948
949 /*------------------------------------------------------------------*/
950 /*
951  * Function irda_usb_net_open (dev)
952  *
953  *    Network device is taken up. Usually this is done by "ifconfig irda0 up" 
954  *   
955  * Note : don't mess with self->netopen - Jean II
956  */
957 static int irda_usb_net_open(struct net_device *netdev)
958 {
959         struct irda_usb_cb *self;
960         char    hwname[16];
961         int i;
962         
963         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
964
965         IRDA_ASSERT(netdev != NULL, return -1;);
966         self = (struct irda_usb_cb *) netdev->priv;
967         IRDA_ASSERT(self != NULL, return -1;);
968
969         /* Can only open the device if it's there */
970         if(!self->present) {
971                 IRDA_WARNING("%s(), device not present!\n", __FUNCTION__);
972                 return -1;
973         }
974
975         /* Initialise default speed and xbofs value
976          * (IrLAP will change that soon) */
977         self->speed = -1;
978         self->xbofs = -1;
979         self->new_speed = -1;
980         self->new_xbofs = -1;
981
982         /* To do *before* submitting Rx urbs and starting net Tx queue
983          * Jean II */
984         self->netopen = 1;
985
986         /* 
987          * Now that everything should be initialized properly,
988          * Open new IrLAP layer instance to take care of us...
989          * Note : will send immediately a speed change...
990          */
991         sprintf(hwname, "usb#%d", self->usbdev->devnum);
992         self->irlap = irlap_open(netdev, &self->qos, hwname);
993         IRDA_ASSERT(self->irlap != NULL, return -1;);
994
995         /* Allow IrLAP to send data to us */
996         netif_start_queue(netdev);
997
998         /* We submit all the Rx URB except for one that we keep idle.
999          * Need to be initialised before submitting other USBs, because
1000          * in some cases as soon as we submit the URBs the USB layer
1001          * will trigger a dummy receive - Jean II */
1002         self->idle_rx_urb = self->rx_urb[IU_MAX_ACTIVE_RX_URBS];
1003         self->idle_rx_urb->context = NULL;
1004
1005         /* Now that we can pass data to IrLAP, allow the USB layer
1006          * to send us some data... */
1007         for (i = 0; i < IU_MAX_ACTIVE_RX_URBS; i++) {
1008                 struct sk_buff *skb = dev_alloc_skb(IRDA_SKB_MAX_MTU);
1009                 if (!skb) {
1010                         /* If this ever happen, we are in deep s***.
1011                          * Basically, we can't start the Rx path... */
1012                         IRDA_WARNING("%s(), Failed to allocate Rx skb\n",
1013                                      __FUNCTION__);
1014                         return -1;
1015                 }
1016                 //skb_reserve(newskb, USB_IRDA_HEADER - 1);
1017                 irda_usb_submit(self, skb, self->rx_urb[i]);
1018         }
1019
1020         /* Ready to play !!! */
1021         return 0;
1022 }
1023
1024 /*------------------------------------------------------------------*/
1025 /*
1026  * Function irda_usb_net_close (self)
1027  *
1028  *    Network device is taken down. Usually this is done by 
1029  *    "ifconfig irda0 down" 
1030  */
1031 static int irda_usb_net_close(struct net_device *netdev)
1032 {
1033         struct irda_usb_cb *self;
1034         int     i;
1035
1036         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
1037
1038         IRDA_ASSERT(netdev != NULL, return -1;);
1039         self = (struct irda_usb_cb *) netdev->priv;
1040         IRDA_ASSERT(self != NULL, return -1;);
1041
1042         /* Clear this flag *before* unlinking the urbs and *before*
1043          * stopping the network Tx queue - Jean II */
1044         self->netopen = 0;
1045
1046         /* Stop network Tx queue */
1047         netif_stop_queue(netdev);
1048
1049         /* Kill defered Rx URB */
1050         del_timer(&self->rx_defer_timer);
1051
1052         /* Deallocate all the Rx path buffers (URBs and skb) */
1053         for (i = 0; i < IU_MAX_RX_URBS; i++) {
1054                 struct urb *urb = self->rx_urb[i];
1055                 struct sk_buff *skb = (struct sk_buff *) urb->context;
1056                 /* Cancel the receive command */
1057                 usb_kill_urb(urb);
1058                 /* The skb is ours, free it */
1059                 if(skb) {
1060                         dev_kfree_skb(skb);
1061                         urb->context = NULL;
1062                 }
1063         }
1064         /* Cancel Tx and speed URB - need to be synchronous to avoid races */
1065         usb_kill_urb(self->tx_urb);
1066         usb_kill_urb(self->speed_urb);
1067
1068         /* Stop and remove instance of IrLAP */
1069         if (self->irlap)
1070                 irlap_close(self->irlap);
1071         self->irlap = NULL;
1072
1073         return 0;
1074 }
1075
1076 /*------------------------------------------------------------------*/
1077 /*
1078  * IOCTLs : Extra out-of-band network commands...
1079  */
1080 static int irda_usb_net_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
1081 {
1082         unsigned long flags;
1083         struct if_irda_req *irq = (struct if_irda_req *) rq;
1084         struct irda_usb_cb *self;
1085         int ret = 0;
1086
1087         IRDA_ASSERT(dev != NULL, return -1;);
1088         self = dev->priv;
1089         IRDA_ASSERT(self != NULL, return -1;);
1090
1091         IRDA_DEBUG(2, "%s(), %s, (cmd=0x%X)\n", __FUNCTION__, dev->name, cmd);
1092
1093         switch (cmd) {
1094         case SIOCSBANDWIDTH: /* Set bandwidth */
1095                 if (!capable(CAP_NET_ADMIN))
1096                         return -EPERM;
1097                 /* Protect us from USB callbacks, net watchdog and else. */
1098                 spin_lock_irqsave(&self->lock, flags);
1099                 /* Check if the device is still there */
1100                 if(self->present) {
1101                         /* Set the desired speed */
1102                         self->new_speed = irq->ifr_baudrate;
1103                         irda_usb_change_speed_xbofs(self);
1104                 }
1105                 spin_unlock_irqrestore(&self->lock, flags);
1106                 break;
1107         case SIOCSMEDIABUSY: /* Set media busy */
1108                 if (!capable(CAP_NET_ADMIN))
1109                         return -EPERM;
1110                 /* Check if the IrDA stack is still there */
1111                 if(self->netopen)
1112                         irda_device_set_media_busy(self->netdev, TRUE);
1113                 break;
1114         case SIOCGRECEIVING: /* Check if we are receiving right now */
1115                 irq->ifr_receiving = irda_usb_is_receiving(self);
1116                 break;
1117         default:
1118                 ret = -EOPNOTSUPP;
1119         }
1120         
1121         return ret;
1122 }
1123
1124 /*------------------------------------------------------------------*/
1125 /*
1126  * Get device stats (for /proc/net/dev and ifconfig)
1127  */
1128 static struct net_device_stats *irda_usb_net_get_stats(struct net_device *dev)
1129 {
1130         struct irda_usb_cb *self = dev->priv;
1131         return &self->stats;
1132 }
1133
1134 /********************* IRDA CONFIG SUBROUTINES *********************/
1135 /*
1136  * Various subroutines dealing with IrDA and network stuff we use to
1137  * configure and initialise each irda-usb instance.
1138  * These functions are used below in the main calls of the driver...
1139  */
1140
1141 /*------------------------------------------------------------------*/
1142 /*
1143  * Set proper values in the IrDA QOS structure
1144  */
1145 static inline void irda_usb_init_qos(struct irda_usb_cb *self)
1146 {
1147         struct irda_class_desc *desc;
1148
1149         IRDA_DEBUG(3, "%s()\n", __FUNCTION__);
1150         
1151         desc = self->irda_desc;
1152         
1153         /* Initialize QoS for this device */
1154         irda_init_max_qos_capabilies(&self->qos);
1155
1156         /* See spec section 7.2 for meaning.
1157          * Values are little endian (as most USB stuff), the IrDA stack
1158          * use it in native order (see parameters.c). - Jean II */
1159         self->qos.baud_rate.bits       = le16_to_cpu(desc->wBaudRate);
1160         self->qos.min_turn_time.bits   = desc->bmMinTurnaroundTime;
1161         self->qos.additional_bofs.bits = desc->bmAdditionalBOFs;
1162         self->qos.window_size.bits     = desc->bmWindowSize;
1163         self->qos.data_size.bits       = desc->bmDataSize;
1164
1165         IRDA_DEBUG(0, "%s(), dongle says speed=0x%X, size=0x%X, window=0x%X, bofs=0x%X, turn=0x%X\n", 
1166                 __FUNCTION__, self->qos.baud_rate.bits, self->qos.data_size.bits, self->qos.window_size.bits, self->qos.additional_bofs.bits, self->qos.min_turn_time.bits);
1167
1168         /* Don't always trust what the dongle tell us */
1169         if(self->capability & IUC_SIR_ONLY)
1170                 self->qos.baud_rate.bits        &= 0x00ff;
1171         if(self->capability & IUC_SMALL_PKT)
1172                 self->qos.data_size.bits         = 0x07;
1173         if(self->capability & IUC_NO_WINDOW)
1174                 self->qos.window_size.bits       = 0x01;
1175         if(self->capability & IUC_MAX_WINDOW)
1176                 self->qos.window_size.bits       = 0x7f;
1177         if(self->capability & IUC_MAX_XBOFS)
1178                 self->qos.additional_bofs.bits   = 0x01;
1179
1180 #if 1
1181         /* Module parameter can override the rx window size */
1182         if (qos_mtt_bits)
1183                 self->qos.min_turn_time.bits = qos_mtt_bits;
1184 #endif      
1185         /* 
1186          * Note : most of those values apply only for the receive path,
1187          * the transmit path will be set differently - Jean II 
1188          */
1189         irda_qos_bits_to_value(&self->qos);
1190 }
1191
1192 /*------------------------------------------------------------------*/
1193 /*
1194  * Initialise the network side of the irda-usb instance
1195  * Called when a new USB instance is registered in irda_usb_probe()
1196  */
1197 static inline int irda_usb_open(struct irda_usb_cb *self)
1198 {
1199         struct net_device *netdev = self->netdev;
1200
1201         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
1202
1203         irda_usb_init_qos(self);
1204
1205         /* Override the network functions we need to use */
1206         netdev->hard_start_xmit = irda_usb_hard_xmit;
1207         netdev->tx_timeout      = irda_usb_net_timeout;
1208         netdev->watchdog_timeo  = 250*HZ/1000;  /* 250 ms > USB timeout */
1209         netdev->open            = irda_usb_net_open;
1210         netdev->stop            = irda_usb_net_close;
1211         netdev->get_stats       = irda_usb_net_get_stats;
1212         netdev->do_ioctl        = irda_usb_net_ioctl;
1213
1214         return register_netdev(netdev);
1215 }
1216
1217 /*------------------------------------------------------------------*/
1218 /*
1219  * Cleanup the network side of the irda-usb instance
1220  * Called when a USB instance is removed in irda_usb_disconnect()
1221  */
1222 static inline void irda_usb_close(struct irda_usb_cb *self)
1223 {
1224         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
1225
1226         /* Remove netdevice */
1227         unregister_netdev(self->netdev);
1228
1229         /* Remove the speed buffer */
1230         kfree(self->speed_buff);
1231         self->speed_buff = NULL;
1232 }
1233
1234 /********************** USB CONFIG SUBROUTINES **********************/
1235 /*
1236  * Various subroutines dealing with USB stuff we use to configure and
1237  * initialise each irda-usb instance.
1238  * These functions are used below in the main calls of the driver...
1239  */
1240
1241 /*------------------------------------------------------------------*/
1242 /*
1243  * Function irda_usb_parse_endpoints(dev, ifnum)
1244  *
1245  *    Parse the various endpoints and find the one we need.
1246  *
1247  * The endpoint are the pipes used to communicate with the USB device.
1248  * The spec defines 2 endpoints of type bulk transfer, one in, and one out.
1249  * These are used to pass frames back and forth with the dongle.
1250  * Most dongle have also an interrupt endpoint, that will be probably
1251  * documented in the next spec...
1252  */
1253 static inline int irda_usb_parse_endpoints(struct irda_usb_cb *self, struct usb_host_endpoint *endpoint, int ennum)
1254 {
1255         int i;          /* Endpoint index in table */
1256                 
1257         /* Init : no endpoints */
1258         self->bulk_in_ep = 0;
1259         self->bulk_out_ep = 0;
1260         self->bulk_int_ep = 0;
1261
1262         /* Let's look at all those endpoints */
1263         for(i = 0; i < ennum; i++) {
1264                 /* All those variables will get optimised by the compiler,
1265                  * so let's aim for clarity... - Jean II */
1266                 __u8 ep;        /* Endpoint address */
1267                 __u8 dir;       /* Endpoint direction */
1268                 __u8 attr;      /* Endpoint attribute */
1269                 __u16 psize;    /* Endpoint max packet size in bytes */
1270
1271                 /* Get endpoint address, direction and attribute */
1272                 ep = endpoint[i].desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1273                 dir = endpoint[i].desc.bEndpointAddress & USB_ENDPOINT_DIR_MASK;
1274                 attr = endpoint[i].desc.bmAttributes;
1275                 psize = le16_to_cpu(endpoint[i].desc.wMaxPacketSize);
1276
1277                 /* Is it a bulk endpoint ??? */
1278                 if(attr == USB_ENDPOINT_XFER_BULK) {
1279                         /* We need to find an IN and an OUT */
1280                         if(dir == USB_DIR_IN) {
1281                                 /* This is our Rx endpoint */
1282                                 self->bulk_in_ep = ep;
1283                         } else {
1284                                 /* This is our Tx endpoint */
1285                                 self->bulk_out_ep = ep;
1286                                 self->bulk_out_mtu = psize;
1287                         }
1288                 } else {
1289                         if((attr == USB_ENDPOINT_XFER_INT) &&
1290                            (dir == USB_DIR_IN)) {
1291                                 /* This is our interrupt endpoint */
1292                                 self->bulk_int_ep = ep;
1293                         } else {
1294                                 IRDA_ERROR("%s(), Unrecognised endpoint %02X.\n", __FUNCTION__, ep);
1295                         }
1296                 }
1297         }
1298
1299         IRDA_DEBUG(0, "%s(), And our endpoints are : in=%02X, out=%02X (%d), int=%02X\n",
1300                 __FUNCTION__, self->bulk_in_ep, self->bulk_out_ep, self->bulk_out_mtu, self->bulk_int_ep);
1301         /* Should be 8, 16, 32 or 64 bytes */
1302         IRDA_ASSERT(self->bulk_out_mtu == 64, ;);
1303
1304         return((self->bulk_in_ep != 0) && (self->bulk_out_ep != 0));
1305 }
1306
1307 #ifdef IU_DUMP_CLASS_DESC
1308 /*------------------------------------------------------------------*/
1309 /*
1310  * Function usb_irda_dump_class_desc(desc)
1311  *
1312  *    Prints out the contents of the IrDA class descriptor
1313  *
1314  */
1315 static inline void irda_usb_dump_class_desc(struct irda_class_desc *desc)
1316 {
1317         /* Values are little endian */
1318         printk("bLength=%x\n", desc->bLength);
1319         printk("bDescriptorType=%x\n", desc->bDescriptorType);
1320         printk("bcdSpecRevision=%x\n", le16_to_cpu(desc->bcdSpecRevision)); 
1321         printk("bmDataSize=%x\n", desc->bmDataSize);
1322         printk("bmWindowSize=%x\n", desc->bmWindowSize);
1323         printk("bmMinTurnaroundTime=%d\n", desc->bmMinTurnaroundTime);
1324         printk("wBaudRate=%x\n", le16_to_cpu(desc->wBaudRate));
1325         printk("bmAdditionalBOFs=%x\n", desc->bmAdditionalBOFs);
1326         printk("bIrdaRateSniff=%x\n", desc->bIrdaRateSniff);
1327         printk("bMaxUnicastList=%x\n", desc->bMaxUnicastList);
1328 }
1329 #endif /* IU_DUMP_CLASS_DESC */
1330
1331 /*------------------------------------------------------------------*/
1332 /*
1333  * Function irda_usb_find_class_desc(intf)
1334  *
1335  *    Returns instance of IrDA class descriptor, or NULL if not found
1336  *
1337  * The class descriptor is some extra info that IrDA USB devices will
1338  * offer to us, describing their IrDA characteristics. We will use that in
1339  * irda_usb_init_qos()
1340  */
1341 static inline struct irda_class_desc *irda_usb_find_class_desc(struct usb_interface *intf)
1342 {
1343         struct usb_device *dev = interface_to_usbdev (intf);
1344         struct irda_class_desc *desc;
1345         int ret;
1346
1347         desc = kmalloc(sizeof (*desc), GFP_KERNEL);
1348         if (desc == NULL) 
1349                 return NULL;
1350         memset(desc, 0, sizeof(*desc));
1351
1352         /* USB-IrDA class spec 1.0:
1353          *      6.1.3: Standard "Get Descriptor" Device Request is not
1354          *             appropriate to retrieve class-specific descriptor
1355          *      6.2.5: Class Specific "Get Class Descriptor" Interface Request
1356          *             is mandatory and returns the USB-IrDA class descriptor
1357          */
1358
1359         ret = usb_control_msg(dev, usb_rcvctrlpipe(dev,0),
1360                 IU_REQ_GET_CLASS_DESC,
1361                 USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1362                 0, intf->altsetting->desc.bInterfaceNumber, desc,
1363                 sizeof(*desc), 500);
1364         
1365         IRDA_DEBUG(1, "%s(), ret=%d\n", __FUNCTION__, ret);
1366         if (ret < sizeof(*desc)) {
1367                 IRDA_WARNING("usb-irda: class_descriptor read %s (%d)\n",
1368                              (ret<0) ? "failed" : "too short", ret);
1369         }
1370         else if (desc->bDescriptorType != USB_DT_IRDA) {
1371                 IRDA_WARNING("usb-irda: bad class_descriptor type\n");
1372         }
1373         else {
1374 #ifdef IU_DUMP_CLASS_DESC
1375                 irda_usb_dump_class_desc(desc);
1376 #endif  /* IU_DUMP_CLASS_DESC */
1377
1378                 return desc;
1379         }
1380         kfree(desc);
1381         return NULL;
1382 }
1383
1384 /*********************** USB DEVICE CALLBACKS ***********************/
1385 /*
1386  * Main calls from the USB subsystem.
1387  * Mostly registering a new irda-usb device and removing it....
1388  */
1389
1390 /*------------------------------------------------------------------*/
1391 /*
1392  * This routine is called by the USB subsystem for each new device
1393  * in the system. We need to check if the device is ours, and in
1394  * this case start handling it.
1395  * The USB layer protect us from reentrancy (via BKL), so we don't need
1396  * to spinlock in there... Jean II
1397  */
1398 static int irda_usb_probe(struct usb_interface *intf,
1399                           const struct usb_device_id *id)
1400 {
1401         struct net_device *net;
1402         struct usb_device *dev = interface_to_usbdev(intf);
1403         struct irda_usb_cb *self = NULL;
1404         struct usb_host_interface *interface;
1405         struct irda_class_desc *irda_desc;
1406         int ret = -ENOMEM;
1407         int i;          /* Driver instance index / Rx URB index */
1408
1409         /* Note : the probe make sure to call us only for devices that
1410          * matches the list of dongle (top of the file). So, we
1411          * don't need to check if the dongle is really ours.
1412          * Jean II */
1413
1414         IRDA_MESSAGE("IRDA-USB found at address %d, Vendor: %x, Product: %x\n",
1415                      dev->devnum, le16_to_cpu(dev->descriptor.idVendor),
1416                      le16_to_cpu(dev->descriptor.idProduct));
1417
1418         net = alloc_irdadev(sizeof(*self));
1419         if (!net) 
1420                 goto err_out;
1421
1422         SET_MODULE_OWNER(net);
1423         SET_NETDEV_DEV(net, &intf->dev);
1424         self = net->priv;
1425         self->netdev = net;
1426         spin_lock_init(&self->lock);
1427         init_timer(&self->rx_defer_timer);
1428
1429         /* Create all of the needed urbs */
1430         for (i = 0; i < IU_MAX_RX_URBS; i++) {
1431                 self->rx_urb[i] = usb_alloc_urb(0, GFP_KERNEL);
1432                 if (!self->rx_urb[i]) {
1433                         goto err_out_1;
1434                 }
1435         }
1436         self->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
1437         if (!self->tx_urb) {
1438                 goto err_out_1;
1439         }
1440         self->speed_urb = usb_alloc_urb(0, GFP_KERNEL);
1441         if (!self->speed_urb) {
1442                 goto err_out_2;
1443         }
1444
1445         /* Is this really necessary? (no, except maybe for broken devices) */
1446         if (usb_reset_configuration (dev) < 0) {
1447                 err("reset_configuration failed");
1448                 ret = -EIO;
1449                 goto err_out_3;
1450         }
1451
1452         /* Is this really necessary? */
1453         /* Note : some driver do hardcode the interface number, some others
1454          * specify an alternate, but very few driver do like this.
1455          * Jean II */
1456         ret = usb_set_interface(dev, intf->altsetting->desc.bInterfaceNumber, 0);
1457         IRDA_DEBUG(1, "usb-irda: set interface %d result %d\n", intf->altsetting->desc.bInterfaceNumber, ret);
1458         switch (ret) {
1459                 case 0:
1460                         break;
1461                 case -EPIPE:            /* -EPIPE = -32 */
1462                         /* Martin Diehl says if we get a -EPIPE we should
1463                          * be fine and we don't need to do a usb_clear_halt().
1464                          * - Jean II */
1465                         IRDA_DEBUG(0, "%s(), Received -EPIPE, ignoring...\n", __FUNCTION__);
1466                         break;
1467                 default:
1468                         IRDA_DEBUG(0, "%s(), Unknown error %d\n", __FUNCTION__, ret);
1469                         ret = -EIO;
1470                         goto err_out_3;
1471         }
1472
1473         /* Find our endpoints */
1474         interface = intf->cur_altsetting;
1475         if(!irda_usb_parse_endpoints(self, interface->endpoint,
1476                                      interface->desc.bNumEndpoints)) {
1477                 IRDA_ERROR("%s(), Bogus endpoints...\n", __FUNCTION__);
1478                 ret = -EIO;
1479                 goto err_out_3;
1480         }
1481
1482         /* Find IrDA class descriptor */
1483         irda_desc = irda_usb_find_class_desc(intf);
1484         ret = -ENODEV;
1485         if (irda_desc == NULL)
1486                 goto err_out_3;
1487
1488         self->irda_desc =  irda_desc;
1489         self->present = 1;
1490         self->netopen = 0;
1491         self->capability = id->driver_info;
1492         self->usbdev = dev;
1493         self->usbintf = intf;
1494
1495         /* Allocate the buffer for speed changes */
1496         /* Don't change this buffer size and allocation without doing
1497          * some heavy and complete testing. Don't ask why :-(
1498          * Jean II */
1499         self->speed_buff = (char *) kmalloc(IRDA_USB_SPEED_MTU, GFP_KERNEL);
1500         if (self->speed_buff == NULL) 
1501                 goto err_out_3;
1502
1503         memset(self->speed_buff, 0, IRDA_USB_SPEED_MTU);
1504
1505         ret = irda_usb_open(self);
1506         if (ret) 
1507                 goto err_out_4;
1508
1509         IRDA_MESSAGE("IrDA: Registered device %s\n", net->name);
1510         usb_set_intfdata(intf, self);
1511         return 0;
1512
1513 err_out_4:
1514         kfree(self->speed_buff);
1515 err_out_3:
1516         /* Free all urbs that we may have created */
1517         usb_free_urb(self->speed_urb);
1518 err_out_2:
1519         usb_free_urb(self->tx_urb);
1520 err_out_1:
1521         for (i = 0; i < IU_MAX_RX_URBS; i++) {
1522                 if (self->rx_urb[i])
1523                         usb_free_urb(self->rx_urb[i]);
1524         }
1525         free_netdev(net);
1526 err_out:
1527         return ret;
1528 }
1529
1530 /*------------------------------------------------------------------*/
1531 /*
1532  * The current irda-usb device is removed, the USB layer tell us
1533  * to shut it down...
1534  * One of the constraints is that when we exit this function,
1535  * we cannot use the usb_device no more. Gone. Destroyed. kfree().
1536  * Most other subsystem allow you to destroy the instance at a time
1537  * when it's convenient to you, to postpone it to a later date, but
1538  * not the USB subsystem.
1539  * So, we must make bloody sure that everything gets deactivated.
1540  * Jean II
1541  */
1542 static void irda_usb_disconnect(struct usb_interface *intf)
1543 {
1544         unsigned long flags;
1545         struct irda_usb_cb *self = usb_get_intfdata(intf);
1546         int i;
1547
1548         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
1549
1550         usb_set_intfdata(intf, NULL);
1551         if (!self)
1552                 return;
1553
1554         /* Make sure that the Tx path is not executing. - Jean II */
1555         spin_lock_irqsave(&self->lock, flags);
1556
1557         /* Oups ! We are not there any more.
1558          * This will stop/desactivate the Tx path. - Jean II */
1559         self->present = 0;
1560
1561         /* Kill defered Rx URB */
1562         del_timer(&self->rx_defer_timer);
1563
1564         /* We need to have irq enabled to unlink the URBs. That's OK,
1565          * at this point the Tx path is gone - Jean II */
1566         spin_unlock_irqrestore(&self->lock, flags);
1567
1568         /* Hum... Check if networking is still active (avoid races) */
1569         if((self->netopen) || (self->irlap)) {
1570                 /* Accept no more transmissions */
1571                 /*netif_device_detach(self->netdev);*/
1572                 netif_stop_queue(self->netdev);
1573                 /* Stop all the receive URBs. Must be synchronous. */
1574                 for (i = 0; i < IU_MAX_RX_URBS; i++)
1575                         usb_kill_urb(self->rx_urb[i]);
1576                 /* Cancel Tx and speed URB.
1577                  * Make sure it's synchronous to avoid races. */
1578                 usb_kill_urb(self->tx_urb);
1579                 usb_kill_urb(self->speed_urb);
1580         }
1581
1582         /* Cleanup the device stuff */
1583         irda_usb_close(self);
1584         /* No longer attached to USB bus */
1585         self->usbdev = NULL;
1586         self->usbintf = NULL;
1587
1588         /* Clean up our urbs */
1589         for (i = 0; i < IU_MAX_RX_URBS; i++)
1590                 usb_free_urb(self->rx_urb[i]);
1591         /* Clean up Tx and speed URB */
1592         usb_free_urb(self->tx_urb);
1593         usb_free_urb(self->speed_urb);
1594
1595         /* Free self and network device */
1596         free_netdev(self->netdev);
1597         IRDA_DEBUG(0, "%s(), USB IrDA Disconnected\n", __FUNCTION__);
1598 }
1599
1600 /*------------------------------------------------------------------*/
1601 /*
1602  * USB device callbacks
1603  */
1604 static struct usb_driver irda_driver = {
1605         .name           = "irda-usb",
1606         .probe          = irda_usb_probe,
1607         .disconnect     = irda_usb_disconnect,
1608         .id_table       = dongles,
1609 };
1610
1611 /************************* MODULE CALLBACKS *************************/
1612 /*
1613  * Deal with module insertion/removal
1614  * Mostly tell USB about our existence
1615  */
1616
1617 /*------------------------------------------------------------------*/
1618 /*
1619  * Module insertion
1620  */
1621 static int __init usb_irda_init(void)
1622 {
1623         int     ret;
1624
1625         ret = usb_register(&irda_driver);
1626         if (ret < 0)
1627                 return ret;
1628
1629         IRDA_MESSAGE("USB IrDA support registered\n");
1630         return 0;
1631 }
1632 module_init(usb_irda_init);
1633
1634 /*------------------------------------------------------------------*/
1635 /*
1636  * Module removal
1637  */
1638 static void __exit usb_irda_cleanup(void)
1639 {
1640         /* Deregister the driver and remove all pending instances */
1641         usb_deregister(&irda_driver);
1642 }
1643 module_exit(usb_irda_cleanup);
1644
1645 /*------------------------------------------------------------------*/
1646 /*
1647  * Module parameters
1648  */
1649 module_param(qos_mtt_bits, int, 0);
1650 MODULE_PARM_DESC(qos_mtt_bits, "Minimum Turn Time");
1651 MODULE_AUTHOR("Roman Weissgaerber <weissg@vienna.at>, Dag Brattli <dag@brattli.net> and Jean Tourrilhes <jt@hpl.hp.com>");
1652 MODULE_DESCRIPTION("IrDA-USB Dongle Driver"); 
1653 MODULE_LICENSE("GPL");