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