Merge branch 'origin'
[pandora-kernel.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         int             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         netif_rx(dataskb);
855
856         /* Keep stats up to date */
857         self->stats.rx_bytes += dataskb->len;
858         self->stats.rx_packets++;
859         self->netdev->last_rx = jiffies;
860
861 done:
862         /* Note : at this point, the URB we've just received (urb)
863          * is still referenced by the USB layer. For example, if we
864          * have received a -ECONNRESET, uhci_cleanup_unlink() will
865          * continue to process it (in fact, cleaning it up).
866          * If we were to submit this URB, disaster would ensue.
867          * Therefore, we submit our idle URB, and put this URB in our
868          * idle slot....
869          * Jean II */
870         /* Note : with this scheme, we could submit the idle URB before
871          * processing the Rx URB. I don't think it would buy us anything as
872          * we are running in the USB thread context. Jean II */
873         next_urb = self->idle_rx_urb;
874
875         /* Recycle Rx URB : Now, the idle URB is the present one */
876         urb->context = NULL;
877         self->idle_rx_urb = urb;
878
879         /* Submit the idle URB to replace the URB we've just received.
880          * Do it last to avoid race conditions... Jean II */
881         irda_usb_submit(self, skb, next_urb);
882 }
883
884 /*------------------------------------------------------------------*/
885 /*
886  * In case of errors, we want the USB layer to have time to recover.
887  * Now, it is time to resubmit ouur Rx URB...
888  */
889 static void irda_usb_rx_defer_expired(unsigned long data)
890 {
891         struct urb *urb = (struct urb *) data;
892         struct sk_buff *skb = (struct sk_buff *) urb->context;
893         struct irda_usb_cb *self; 
894         struct irda_skb_cb *cb;
895         struct urb *next_urb;
896
897         IRDA_DEBUG(2, "%s()\n", __FUNCTION__);
898
899         /* Find ourselves */
900         cb = (struct irda_skb_cb *) skb->cb;
901         IRDA_ASSERT(cb != NULL, return;);
902         self = (struct irda_usb_cb *) cb->context;
903         IRDA_ASSERT(self != NULL, return;);
904
905         /* Same stuff as when Rx is done, see above... */
906         next_urb = self->idle_rx_urb;
907         urb->context = NULL;
908         self->idle_rx_urb = urb;
909         irda_usb_submit(self, skb, next_urb);
910 }
911
912 /*------------------------------------------------------------------*/
913 /*
914  * Callbak from IrDA layer. IrDA wants to know if we have
915  * started receiving anything.
916  */
917 static int irda_usb_is_receiving(struct irda_usb_cb *self)
918 {
919         /* Note : because of the way UHCI works, it's almost impossible
920          * to get this info. The Controller DMA directly to memory and
921          * signal only when the whole frame is finished. To know if the
922          * first TD of the URB has been filled or not seems hard work...
923          *
924          * The other solution would be to use the "receiving" command
925          * on the default decriptor with a usb_control_msg(), but that
926          * would add USB traffic and would return result only in the
927          * next USB frame (~1ms).
928          *
929          * I've been told that current dongles send status info on their
930          * interrupt endpoint, and that's what the Windows driver uses
931          * to know this info. Unfortunately, this is not yet in the spec...
932          *
933          * Jean II
934          */
935
936         return 0; /* For now */
937 }
938
939 /********************** IRDA DEVICE CALLBACKS **********************/
940 /*
941  * Main calls from the IrDA/Network subsystem.
942  * Mostly registering a new irda-usb device and removing it....
943  * We only deal with the IrDA side of the business, the USB side will
944  * be dealt with below...
945  */
946
947
948 /*------------------------------------------------------------------*/
949 /*
950  * Function irda_usb_net_open (dev)
951  *
952  *    Network device is taken up. Usually this is done by "ifconfig irda0 up" 
953  *   
954  * Note : don't mess with self->netopen - Jean II
955  */
956 static int irda_usb_net_open(struct net_device *netdev)
957 {
958         struct irda_usb_cb *self;
959         char    hwname[16];
960         int i;
961         
962         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
963
964         IRDA_ASSERT(netdev != NULL, return -1;);
965         self = (struct irda_usb_cb *) netdev->priv;
966         IRDA_ASSERT(self != NULL, return -1;);
967
968         /* Can only open the device if it's there */
969         if(!self->present) {
970                 IRDA_WARNING("%s(), device not present!\n", __FUNCTION__);
971                 return -1;
972         }
973
974         /* Initialise default speed and xbofs value
975          * (IrLAP will change that soon) */
976         self->speed = -1;
977         self->xbofs = -1;
978         self->new_speed = -1;
979         self->new_xbofs = -1;
980
981         /* To do *before* submitting Rx urbs and starting net Tx queue
982          * Jean II */
983         self->netopen = 1;
984
985         /* 
986          * Now that everything should be initialized properly,
987          * Open new IrLAP layer instance to take care of us...
988          * Note : will send immediately a speed change...
989          */
990         sprintf(hwname, "usb#%d", self->usbdev->devnum);
991         self->irlap = irlap_open(netdev, &self->qos, hwname);
992         IRDA_ASSERT(self->irlap != NULL, return -1;);
993
994         /* Allow IrLAP to send data to us */
995         netif_start_queue(netdev);
996
997         /* We submit all the Rx URB except for one that we keep idle.
998          * Need to be initialised before submitting other USBs, because
999          * in some cases as soon as we submit the URBs the USB layer
1000          * will trigger a dummy receive - Jean II */
1001         self->idle_rx_urb = self->rx_urb[IU_MAX_ACTIVE_RX_URBS];
1002         self->idle_rx_urb->context = NULL;
1003
1004         /* Now that we can pass data to IrLAP, allow the USB layer
1005          * to send us some data... */
1006         for (i = 0; i < IU_MAX_ACTIVE_RX_URBS; i++) {
1007                 struct sk_buff *skb = dev_alloc_skb(IRDA_SKB_MAX_MTU);
1008                 if (!skb) {
1009                         /* If this ever happen, we are in deep s***.
1010                          * Basically, we can't start the Rx path... */
1011                         IRDA_WARNING("%s(), Failed to allocate Rx skb\n",
1012                                      __FUNCTION__);
1013                         return -1;
1014                 }
1015                 //skb_reserve(newskb, USB_IRDA_HEADER - 1);
1016                 irda_usb_submit(self, skb, self->rx_urb[i]);
1017         }
1018
1019         /* Ready to play !!! */
1020         return 0;
1021 }
1022
1023 /*------------------------------------------------------------------*/
1024 /*
1025  * Function irda_usb_net_close (self)
1026  *
1027  *    Network device is taken down. Usually this is done by 
1028  *    "ifconfig irda0 down" 
1029  */
1030 static int irda_usb_net_close(struct net_device *netdev)
1031 {
1032         struct irda_usb_cb *self;
1033         int     i;
1034
1035         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
1036
1037         IRDA_ASSERT(netdev != NULL, return -1;);
1038         self = (struct irda_usb_cb *) netdev->priv;
1039         IRDA_ASSERT(self != NULL, return -1;);
1040
1041         /* Clear this flag *before* unlinking the urbs and *before*
1042          * stopping the network Tx queue - Jean II */
1043         self->netopen = 0;
1044
1045         /* Stop network Tx queue */
1046         netif_stop_queue(netdev);
1047
1048         /* Kill defered Rx URB */
1049         del_timer(&self->rx_defer_timer);
1050
1051         /* Deallocate all the Rx path buffers (URBs and skb) */
1052         for (i = 0; i < IU_MAX_RX_URBS; i++) {
1053                 struct urb *urb = self->rx_urb[i];
1054                 struct sk_buff *skb = (struct sk_buff *) urb->context;
1055                 /* Cancel the receive command */
1056                 usb_kill_urb(urb);
1057                 /* The skb is ours, free it */
1058                 if(skb) {
1059                         dev_kfree_skb(skb);
1060                         urb->context = NULL;
1061                 }
1062         }
1063         /* Cancel Tx and speed URB - need to be synchronous to avoid races */
1064         usb_kill_urb(self->tx_urb);
1065         usb_kill_urb(self->speed_urb);
1066
1067         /* Stop and remove instance of IrLAP */
1068         if (self->irlap)
1069                 irlap_close(self->irlap);
1070         self->irlap = NULL;
1071
1072         return 0;
1073 }
1074
1075 /*------------------------------------------------------------------*/
1076 /*
1077  * IOCTLs : Extra out-of-band network commands...
1078  */
1079 static int irda_usb_net_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
1080 {
1081         unsigned long flags;
1082         struct if_irda_req *irq = (struct if_irda_req *) rq;
1083         struct irda_usb_cb *self;
1084         int ret = 0;
1085
1086         IRDA_ASSERT(dev != NULL, return -1;);
1087         self = dev->priv;
1088         IRDA_ASSERT(self != NULL, return -1;);
1089
1090         IRDA_DEBUG(2, "%s(), %s, (cmd=0x%X)\n", __FUNCTION__, dev->name, cmd);
1091
1092         switch (cmd) {
1093         case SIOCSBANDWIDTH: /* Set bandwidth */
1094                 if (!capable(CAP_NET_ADMIN))
1095                         return -EPERM;
1096                 /* Protect us from USB callbacks, net watchdog and else. */
1097                 spin_lock_irqsave(&self->lock, flags);
1098                 /* Check if the device is still there */
1099                 if(self->present) {
1100                         /* Set the desired speed */
1101                         self->new_speed = irq->ifr_baudrate;
1102                         irda_usb_change_speed_xbofs(self);
1103                 }
1104                 spin_unlock_irqrestore(&self->lock, flags);
1105                 break;
1106         case SIOCSMEDIABUSY: /* Set media busy */
1107                 if (!capable(CAP_NET_ADMIN))
1108                         return -EPERM;
1109                 /* Check if the IrDA stack is still there */
1110                 if(self->netopen)
1111                         irda_device_set_media_busy(self->netdev, TRUE);
1112                 break;
1113         case SIOCGRECEIVING: /* Check if we are receiving right now */
1114                 irq->ifr_receiving = irda_usb_is_receiving(self);
1115                 break;
1116         default:
1117                 ret = -EOPNOTSUPP;
1118         }
1119         
1120         return ret;
1121 }
1122
1123 /*------------------------------------------------------------------*/
1124 /*
1125  * Get device stats (for /proc/net/dev and ifconfig)
1126  */
1127 static struct net_device_stats *irda_usb_net_get_stats(struct net_device *dev)
1128 {
1129         struct irda_usb_cb *self = dev->priv;
1130         return &self->stats;
1131 }
1132
1133 /********************* IRDA CONFIG SUBROUTINES *********************/
1134 /*
1135  * Various subroutines dealing with IrDA and network stuff we use to
1136  * configure and initialise each irda-usb instance.
1137  * These functions are used below in the main calls of the driver...
1138  */
1139
1140 /*------------------------------------------------------------------*/
1141 /*
1142  * Set proper values in the IrDA QOS structure
1143  */
1144 static inline void irda_usb_init_qos(struct irda_usb_cb *self)
1145 {
1146         struct irda_class_desc *desc;
1147
1148         IRDA_DEBUG(3, "%s()\n", __FUNCTION__);
1149         
1150         desc = self->irda_desc;
1151         
1152         /* Initialize QoS for this device */
1153         irda_init_max_qos_capabilies(&self->qos);
1154
1155         /* See spec section 7.2 for meaning.
1156          * Values are little endian (as most USB stuff), the IrDA stack
1157          * use it in native order (see parameters.c). - Jean II */
1158         self->qos.baud_rate.bits       = le16_to_cpu(desc->wBaudRate);
1159         self->qos.min_turn_time.bits   = desc->bmMinTurnaroundTime;
1160         self->qos.additional_bofs.bits = desc->bmAdditionalBOFs;
1161         self->qos.window_size.bits     = desc->bmWindowSize;
1162         self->qos.data_size.bits       = desc->bmDataSize;
1163
1164         IRDA_DEBUG(0, "%s(), dongle says speed=0x%X, size=0x%X, window=0x%X, bofs=0x%X, turn=0x%X\n", 
1165                 __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);
1166
1167         /* Don't always trust what the dongle tell us */
1168         if(self->capability & IUC_SIR_ONLY)
1169                 self->qos.baud_rate.bits        &= 0x00ff;
1170         if(self->capability & IUC_SMALL_PKT)
1171                 self->qos.data_size.bits         = 0x07;
1172         if(self->capability & IUC_NO_WINDOW)
1173                 self->qos.window_size.bits       = 0x01;
1174         if(self->capability & IUC_MAX_WINDOW)
1175                 self->qos.window_size.bits       = 0x7f;
1176         if(self->capability & IUC_MAX_XBOFS)
1177                 self->qos.additional_bofs.bits   = 0x01;
1178
1179 #if 1
1180         /* Module parameter can override the rx window size */
1181         if (qos_mtt_bits)
1182                 self->qos.min_turn_time.bits = qos_mtt_bits;
1183 #endif      
1184         /* 
1185          * Note : most of those values apply only for the receive path,
1186          * the transmit path will be set differently - Jean II 
1187          */
1188         irda_qos_bits_to_value(&self->qos);
1189 }
1190
1191 /*------------------------------------------------------------------*/
1192 /*
1193  * Initialise the network side of the irda-usb instance
1194  * Called when a new USB instance is registered in irda_usb_probe()
1195  */
1196 static inline int irda_usb_open(struct irda_usb_cb *self)
1197 {
1198         struct net_device *netdev = self->netdev;
1199
1200         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
1201
1202         irda_usb_init_qos(self);
1203
1204         /* Override the network functions we need to use */
1205         netdev->hard_start_xmit = irda_usb_hard_xmit;
1206         netdev->tx_timeout      = irda_usb_net_timeout;
1207         netdev->watchdog_timeo  = 250*HZ/1000;  /* 250 ms > USB timeout */
1208         netdev->open            = irda_usb_net_open;
1209         netdev->stop            = irda_usb_net_close;
1210         netdev->get_stats       = irda_usb_net_get_stats;
1211         netdev->do_ioctl        = irda_usb_net_ioctl;
1212
1213         return register_netdev(netdev);
1214 }
1215
1216 /*------------------------------------------------------------------*/
1217 /*
1218  * Cleanup the network side of the irda-usb instance
1219  * Called when a USB instance is removed in irda_usb_disconnect()
1220  */
1221 static inline void irda_usb_close(struct irda_usb_cb *self)
1222 {
1223         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
1224
1225         /* Remove netdevice */
1226         unregister_netdev(self->netdev);
1227
1228         /* Remove the speed buffer */
1229         kfree(self->speed_buff);
1230         self->speed_buff = NULL;
1231 }
1232
1233 /********************** USB CONFIG SUBROUTINES **********************/
1234 /*
1235  * Various subroutines dealing with USB stuff we use to configure and
1236  * initialise each irda-usb instance.
1237  * These functions are used below in the main calls of the driver...
1238  */
1239
1240 /*------------------------------------------------------------------*/
1241 /*
1242  * Function irda_usb_parse_endpoints(dev, ifnum)
1243  *
1244  *    Parse the various endpoints and find the one we need.
1245  *
1246  * The endpoint are the pipes used to communicate with the USB device.
1247  * The spec defines 2 endpoints of type bulk transfer, one in, and one out.
1248  * These are used to pass frames back and forth with the dongle.
1249  * Most dongle have also an interrupt endpoint, that will be probably
1250  * documented in the next spec...
1251  */
1252 static inline int irda_usb_parse_endpoints(struct irda_usb_cb *self, struct usb_host_endpoint *endpoint, int ennum)
1253 {
1254         int i;          /* Endpoint index in table */
1255                 
1256         /* Init : no endpoints */
1257         self->bulk_in_ep = 0;
1258         self->bulk_out_ep = 0;
1259         self->bulk_int_ep = 0;
1260
1261         /* Let's look at all those endpoints */
1262         for(i = 0; i < ennum; i++) {
1263                 /* All those variables will get optimised by the compiler,
1264                  * so let's aim for clarity... - Jean II */
1265                 __u8 ep;        /* Endpoint address */
1266                 __u8 dir;       /* Endpoint direction */
1267                 __u8 attr;      /* Endpoint attribute */
1268                 __u16 psize;    /* Endpoint max packet size in bytes */
1269
1270                 /* Get endpoint address, direction and attribute */
1271                 ep = endpoint[i].desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1272                 dir = endpoint[i].desc.bEndpointAddress & USB_ENDPOINT_DIR_MASK;
1273                 attr = endpoint[i].desc.bmAttributes;
1274                 psize = le16_to_cpu(endpoint[i].desc.wMaxPacketSize);
1275
1276                 /* Is it a bulk endpoint ??? */
1277                 if(attr == USB_ENDPOINT_XFER_BULK) {
1278                         /* We need to find an IN and an OUT */
1279                         if(dir == USB_DIR_IN) {
1280                                 /* This is our Rx endpoint */
1281                                 self->bulk_in_ep = ep;
1282                         } else {
1283                                 /* This is our Tx endpoint */
1284                                 self->bulk_out_ep = ep;
1285                                 self->bulk_out_mtu = psize;
1286                         }
1287                 } else {
1288                         if((attr == USB_ENDPOINT_XFER_INT) &&
1289                            (dir == USB_DIR_IN)) {
1290                                 /* This is our interrupt endpoint */
1291                                 self->bulk_int_ep = ep;
1292                         } else {
1293                                 IRDA_ERROR("%s(), Unrecognised endpoint %02X.\n", __FUNCTION__, ep);
1294                         }
1295                 }
1296         }
1297
1298         IRDA_DEBUG(0, "%s(), And our endpoints are : in=%02X, out=%02X (%d), int=%02X\n",
1299                 __FUNCTION__, self->bulk_in_ep, self->bulk_out_ep, self->bulk_out_mtu, self->bulk_int_ep);
1300         /* Should be 8, 16, 32 or 64 bytes */
1301         IRDA_ASSERT(self->bulk_out_mtu == 64, ;);
1302
1303         return((self->bulk_in_ep != 0) && (self->bulk_out_ep != 0));
1304 }
1305
1306 #ifdef IU_DUMP_CLASS_DESC
1307 /*------------------------------------------------------------------*/
1308 /*
1309  * Function usb_irda_dump_class_desc(desc)
1310  *
1311  *    Prints out the contents of the IrDA class descriptor
1312  *
1313  */
1314 static inline void irda_usb_dump_class_desc(struct irda_class_desc *desc)
1315 {
1316         /* Values are little endian */
1317         printk("bLength=%x\n", desc->bLength);
1318         printk("bDescriptorType=%x\n", desc->bDescriptorType);
1319         printk("bcdSpecRevision=%x\n", le16_to_cpu(desc->bcdSpecRevision)); 
1320         printk("bmDataSize=%x\n", desc->bmDataSize);
1321         printk("bmWindowSize=%x\n", desc->bmWindowSize);
1322         printk("bmMinTurnaroundTime=%d\n", desc->bmMinTurnaroundTime);
1323         printk("wBaudRate=%x\n", le16_to_cpu(desc->wBaudRate));
1324         printk("bmAdditionalBOFs=%x\n", desc->bmAdditionalBOFs);
1325         printk("bIrdaRateSniff=%x\n", desc->bIrdaRateSniff);
1326         printk("bMaxUnicastList=%x\n", desc->bMaxUnicastList);
1327 }
1328 #endif /* IU_DUMP_CLASS_DESC */
1329
1330 /*------------------------------------------------------------------*/
1331 /*
1332  * Function irda_usb_find_class_desc(intf)
1333  *
1334  *    Returns instance of IrDA class descriptor, or NULL if not found
1335  *
1336  * The class descriptor is some extra info that IrDA USB devices will
1337  * offer to us, describing their IrDA characteristics. We will use that in
1338  * irda_usb_init_qos()
1339  */
1340 static inline struct irda_class_desc *irda_usb_find_class_desc(struct usb_interface *intf)
1341 {
1342         struct usb_device *dev = interface_to_usbdev (intf);
1343         struct irda_class_desc *desc;
1344         int ret;
1345
1346         desc = kmalloc(sizeof (*desc), GFP_KERNEL);
1347         if (desc == NULL) 
1348                 return NULL;
1349         memset(desc, 0, sizeof(*desc));
1350
1351         /* USB-IrDA class spec 1.0:
1352          *      6.1.3: Standard "Get Descriptor" Device Request is not
1353          *             appropriate to retrieve class-specific descriptor
1354          *      6.2.5: Class Specific "Get Class Descriptor" Interface Request
1355          *             is mandatory and returns the USB-IrDA class descriptor
1356          */
1357
1358         ret = usb_control_msg(dev, usb_rcvctrlpipe(dev,0),
1359                 IU_REQ_GET_CLASS_DESC,
1360                 USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
1361                 0, intf->altsetting->desc.bInterfaceNumber, desc,
1362                 sizeof(*desc), 500);
1363         
1364         IRDA_DEBUG(1, "%s(), ret=%d\n", __FUNCTION__, ret);
1365         if (ret < sizeof(*desc)) {
1366                 IRDA_WARNING("usb-irda: class_descriptor read %s (%d)\n",
1367                              (ret<0) ? "failed" : "too short", ret);
1368         }
1369         else if (desc->bDescriptorType != USB_DT_IRDA) {
1370                 IRDA_WARNING("usb-irda: bad class_descriptor type\n");
1371         }
1372         else {
1373 #ifdef IU_DUMP_CLASS_DESC
1374                 irda_usb_dump_class_desc(desc);
1375 #endif  /* IU_DUMP_CLASS_DESC */
1376
1377                 return desc;
1378         }
1379         kfree(desc);
1380         return NULL;
1381 }
1382
1383 /*********************** USB DEVICE CALLBACKS ***********************/
1384 /*
1385  * Main calls from the USB subsystem.
1386  * Mostly registering a new irda-usb device and removing it....
1387  */
1388
1389 /*------------------------------------------------------------------*/
1390 /*
1391  * This routine is called by the USB subsystem for each new device
1392  * in the system. We need to check if the device is ours, and in
1393  * this case start handling it.
1394  * The USB layer protect us from reentrancy (via BKL), so we don't need
1395  * to spinlock in there... Jean II
1396  */
1397 static int irda_usb_probe(struct usb_interface *intf,
1398                           const struct usb_device_id *id)
1399 {
1400         struct net_device *net;
1401         struct usb_device *dev = interface_to_usbdev(intf);
1402         struct irda_usb_cb *self = NULL;
1403         struct usb_host_interface *interface;
1404         struct irda_class_desc *irda_desc;
1405         int ret = -ENOMEM;
1406         int i;          /* Driver instance index / Rx URB index */
1407
1408         /* Note : the probe make sure to call us only for devices that
1409          * matches the list of dongle (top of the file). So, we
1410          * don't need to check if the dongle is really ours.
1411          * Jean II */
1412
1413         IRDA_MESSAGE("IRDA-USB found at address %d, Vendor: %x, Product: %x\n",
1414                      dev->devnum, le16_to_cpu(dev->descriptor.idVendor),
1415                      le16_to_cpu(dev->descriptor.idProduct));
1416
1417         net = alloc_irdadev(sizeof(*self));
1418         if (!net) 
1419                 goto err_out;
1420
1421         SET_MODULE_OWNER(net);
1422         SET_NETDEV_DEV(net, &intf->dev);
1423         self = net->priv;
1424         self->netdev = net;
1425         spin_lock_init(&self->lock);
1426         init_timer(&self->rx_defer_timer);
1427
1428         /* Create all of the needed urbs */
1429         for (i = 0; i < IU_MAX_RX_URBS; i++) {
1430                 self->rx_urb[i] = usb_alloc_urb(0, GFP_KERNEL);
1431                 if (!self->rx_urb[i]) {
1432                         goto err_out_1;
1433                 }
1434         }
1435         self->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
1436         if (!self->tx_urb) {
1437                 goto err_out_1;
1438         }
1439         self->speed_urb = usb_alloc_urb(0, GFP_KERNEL);
1440         if (!self->speed_urb) {
1441                 goto err_out_2;
1442         }
1443
1444         /* Is this really necessary? (no, except maybe for broken devices) */
1445         if (usb_reset_configuration (dev) < 0) {
1446                 err("reset_configuration failed");
1447                 ret = -EIO;
1448                 goto err_out_3;
1449         }
1450
1451         /* Is this really necessary? */
1452         /* Note : some driver do hardcode the interface number, some others
1453          * specify an alternate, but very few driver do like this.
1454          * Jean II */
1455         ret = usb_set_interface(dev, intf->altsetting->desc.bInterfaceNumber, 0);
1456         IRDA_DEBUG(1, "usb-irda: set interface %d result %d\n", intf->altsetting->desc.bInterfaceNumber, ret);
1457         switch (ret) {
1458                 case 0:
1459                         break;
1460                 case -EPIPE:            /* -EPIPE = -32 */
1461                         /* Martin Diehl says if we get a -EPIPE we should
1462                          * be fine and we don't need to do a usb_clear_halt().
1463                          * - Jean II */
1464                         IRDA_DEBUG(0, "%s(), Received -EPIPE, ignoring...\n", __FUNCTION__);
1465                         break;
1466                 default:
1467                         IRDA_DEBUG(0, "%s(), Unknown error %d\n", __FUNCTION__, ret);
1468                         ret = -EIO;
1469                         goto err_out_3;
1470         }
1471
1472         /* Find our endpoints */
1473         interface = intf->cur_altsetting;
1474         if(!irda_usb_parse_endpoints(self, interface->endpoint,
1475                                      interface->desc.bNumEndpoints)) {
1476                 IRDA_ERROR("%s(), Bogus endpoints...\n", __FUNCTION__);
1477                 ret = -EIO;
1478                 goto err_out_3;
1479         }
1480
1481         /* Find IrDA class descriptor */
1482         irda_desc = irda_usb_find_class_desc(intf);
1483         ret = -ENODEV;
1484         if (irda_desc == NULL)
1485                 goto err_out_3;
1486
1487         self->irda_desc =  irda_desc;
1488         self->present = 1;
1489         self->netopen = 0;
1490         self->capability = id->driver_info;
1491         self->usbdev = dev;
1492         self->usbintf = intf;
1493
1494         /* Allocate the buffer for speed changes */
1495         /* Don't change this buffer size and allocation without doing
1496          * some heavy and complete testing. Don't ask why :-(
1497          * Jean II */
1498         self->speed_buff = (char *) kmalloc(IRDA_USB_SPEED_MTU, GFP_KERNEL);
1499         if (self->speed_buff == NULL) 
1500                 goto err_out_3;
1501
1502         memset(self->speed_buff, 0, IRDA_USB_SPEED_MTU);
1503
1504         ret = irda_usb_open(self);
1505         if (ret) 
1506                 goto err_out_4;
1507
1508         IRDA_MESSAGE("IrDA: Registered device %s\n", net->name);
1509         usb_set_intfdata(intf, self);
1510         return 0;
1511
1512 err_out_4:
1513         kfree(self->speed_buff);
1514 err_out_3:
1515         /* Free all urbs that we may have created */
1516         usb_free_urb(self->speed_urb);
1517 err_out_2:
1518         usb_free_urb(self->tx_urb);
1519 err_out_1:
1520         for (i = 0; i < IU_MAX_RX_URBS; i++) {
1521                 if (self->rx_urb[i])
1522                         usb_free_urb(self->rx_urb[i]);
1523         }
1524         free_netdev(net);
1525 err_out:
1526         return ret;
1527 }
1528
1529 /*------------------------------------------------------------------*/
1530 /*
1531  * The current irda-usb device is removed, the USB layer tell us
1532  * to shut it down...
1533  * One of the constraints is that when we exit this function,
1534  * we cannot use the usb_device no more. Gone. Destroyed. kfree().
1535  * Most other subsystem allow you to destroy the instance at a time
1536  * when it's convenient to you, to postpone it to a later date, but
1537  * not the USB subsystem.
1538  * So, we must make bloody sure that everything gets deactivated.
1539  * Jean II
1540  */
1541 static void irda_usb_disconnect(struct usb_interface *intf)
1542 {
1543         unsigned long flags;
1544         struct irda_usb_cb *self = usb_get_intfdata(intf);
1545         int i;
1546
1547         IRDA_DEBUG(1, "%s()\n", __FUNCTION__);
1548
1549         usb_set_intfdata(intf, NULL);
1550         if (!self)
1551                 return;
1552
1553         /* Make sure that the Tx path is not executing. - Jean II */
1554         spin_lock_irqsave(&self->lock, flags);
1555
1556         /* Oups ! We are not there any more.
1557          * This will stop/desactivate the Tx path. - Jean II */
1558         self->present = 0;
1559
1560         /* Kill defered Rx URB */
1561         del_timer(&self->rx_defer_timer);
1562
1563         /* We need to have irq enabled to unlink the URBs. That's OK,
1564          * at this point the Tx path is gone - Jean II */
1565         spin_unlock_irqrestore(&self->lock, flags);
1566
1567         /* Hum... Check if networking is still active (avoid races) */
1568         if((self->netopen) || (self->irlap)) {
1569                 /* Accept no more transmissions */
1570                 /*netif_device_detach(self->netdev);*/
1571                 netif_stop_queue(self->netdev);
1572                 /* Stop all the receive URBs. Must be synchronous. */
1573                 for (i = 0; i < IU_MAX_RX_URBS; i++)
1574                         usb_kill_urb(self->rx_urb[i]);
1575                 /* Cancel Tx and speed URB.
1576                  * Make sure it's synchronous to avoid races. */
1577                 usb_kill_urb(self->tx_urb);
1578                 usb_kill_urb(self->speed_urb);
1579         }
1580
1581         /* Cleanup the device stuff */
1582         irda_usb_close(self);
1583         /* No longer attached to USB bus */
1584         self->usbdev = NULL;
1585         self->usbintf = NULL;
1586
1587         /* Clean up our urbs */
1588         for (i = 0; i < IU_MAX_RX_URBS; i++)
1589                 usb_free_urb(self->rx_urb[i]);
1590         /* Clean up Tx and speed URB */
1591         usb_free_urb(self->tx_urb);
1592         usb_free_urb(self->speed_urb);
1593
1594         /* Free self and network device */
1595         free_netdev(self->netdev);
1596         IRDA_DEBUG(0, "%s(), USB IrDA Disconnected\n", __FUNCTION__);
1597 }
1598
1599 /*------------------------------------------------------------------*/
1600 /*
1601  * USB device callbacks
1602  */
1603 static struct usb_driver irda_driver = {
1604         .name           = "irda-usb",
1605         .probe          = irda_usb_probe,
1606         .disconnect     = irda_usb_disconnect,
1607         .id_table       = dongles,
1608 };
1609
1610 /************************* MODULE CALLBACKS *************************/
1611 /*
1612  * Deal with module insertion/removal
1613  * Mostly tell USB about our existence
1614  */
1615
1616 /*------------------------------------------------------------------*/
1617 /*
1618  * Module insertion
1619  */
1620 static int __init usb_irda_init(void)
1621 {
1622         int     ret;
1623
1624         ret = usb_register(&irda_driver);
1625         if (ret < 0)
1626                 return ret;
1627
1628         IRDA_MESSAGE("USB IrDA support registered\n");
1629         return 0;
1630 }
1631 module_init(usb_irda_init);
1632
1633 /*------------------------------------------------------------------*/
1634 /*
1635  * Module removal
1636  */
1637 static void __exit usb_irda_cleanup(void)
1638 {
1639         /* Deregister the driver and remove all pending instances */
1640         usb_deregister(&irda_driver);
1641 }
1642 module_exit(usb_irda_cleanup);
1643
1644 /*------------------------------------------------------------------*/
1645 /*
1646  * Module parameters
1647  */
1648 module_param(qos_mtt_bits, int, 0);
1649 MODULE_PARM_DESC(qos_mtt_bits, "Minimum Turn Time");
1650 MODULE_AUTHOR("Roman Weissgaerber <weissg@vienna.at>, Dag Brattli <dag@brattli.net> and Jean Tourrilhes <jt@hpl.hp.com>");
1651 MODULE_DESCRIPTION("IrDA-USB Dongle Driver"); 
1652 MODULE_LICENSE("GPL");