Merge to Fedora kernel-2.6.18-1.2224_FC5 patched with stable patch-2.6.18.1-vs2.0...
[linux-2.6.git] / drivers / usb / net / usbnet.c
1 /*
2  * USB Network driver infrastructure
3  * Copyright (C) 2000-2005 by David Brownell
4  * Copyright (C) 2003-2005 David Hollis <dhollis@davehollis.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 /*
22  * This is a generic "USB networking" framework that works with several
23  * kinds of full and high speed networking devices:  host-to-host cables,
24  * smart usb peripherals, and actual Ethernet adapters.
25  *
26  * These devices usually differ in terms of control protocols (if they
27  * even have one!) and sometimes they define new framing to wrap or batch
28  * Ethernet packets.  Otherwise, they talk to USB pretty much the same,
29  * so interface (un)binding, endpoint I/O queues, fault handling, and other
30  * issues can usefully be addressed by this framework.
31  */
32
33 // #define      DEBUG                   // error path messages, extra info
34 // #define      VERBOSE                 // more; success messages
35
36 #include <linux/module.h>
37 #include <linux/sched.h>
38 #include <linux/init.h>
39 #include <linux/netdevice.h>
40 #include <linux/etherdevice.h>
41 #include <linux/ethtool.h>
42 #include <linux/workqueue.h>
43 #include <linux/mii.h>
44 #include <linux/usb.h>
45
46 #include "usbnet.h"
47
48 #define DRIVER_VERSION          "22-Aug-2005"
49
50
51 /*-------------------------------------------------------------------------*/
52
53 /*
54  * Nineteen USB 1.1 max size bulk transactions per frame (ms), max.
55  * Several dozen bytes of IPv4 data can fit in two such transactions.
56  * One maximum size Ethernet packet takes twenty four of them.
57  * For high speed, each frame comfortably fits almost 36 max size
58  * Ethernet packets (so queues should be bigger).
59  *
60  * REVISIT qlens should be members of 'struct usbnet'; the goal is to
61  * let the USB host controller be busy for 5msec or more before an irq
62  * is required, under load.  Jumbograms change the equation.
63  */
64 #define RX_QLEN(dev) (((dev)->udev->speed == USB_SPEED_HIGH) ? 60 : 4)
65 #define TX_QLEN(dev) (((dev)->udev->speed == USB_SPEED_HIGH) ? 60 : 4)
66
67 // reawaken network queue this soon after stopping; else watchdog barks
68 #define TX_TIMEOUT_JIFFIES      (5*HZ)
69
70 // throttle rx/tx briefly after some faults, so khubd might disconnect()
71 // us (it polls at HZ/4 usually) before we report too many false errors.
72 #define THROTTLE_JIFFIES        (HZ/8)
73
74 // between wakeups
75 #define UNLINK_TIMEOUT_MS       3
76
77 /*-------------------------------------------------------------------------*/
78
79 // randomly generated ethernet address
80 static u8       node_id [ETH_ALEN];
81
82 static const char driver_name [] = "usbnet";
83
84 /* use ethtool to change the level for any given device */
85 static int msg_level = -1;
86 module_param (msg_level, int, 0);
87 MODULE_PARM_DESC (msg_level, "Override default message level");
88
89 /*-------------------------------------------------------------------------*/
90
91 /* handles CDC Ethernet and many other network "bulk data" interfaces */
92 int usbnet_get_endpoints(struct usbnet *dev, struct usb_interface *intf)
93 {
94         int                             tmp;
95         struct usb_host_interface       *alt = NULL;
96         struct usb_host_endpoint        *in = NULL, *out = NULL;
97         struct usb_host_endpoint        *status = NULL;
98
99         for (tmp = 0; tmp < intf->num_altsetting; tmp++) {
100                 unsigned        ep;
101
102                 in = out = status = NULL;
103                 alt = intf->altsetting + tmp;
104
105                 /* take the first altsetting with in-bulk + out-bulk;
106                  * remember any status endpoint, just in case;
107                  * ignore other endpoints and altsetttings.
108                  */
109                 for (ep = 0; ep < alt->desc.bNumEndpoints; ep++) {
110                         struct usb_host_endpoint        *e;
111                         int                             intr = 0;
112
113                         e = alt->endpoint + ep;
114                         switch (e->desc.bmAttributes) {
115                         case USB_ENDPOINT_XFER_INT:
116                                 if (!(e->desc.bEndpointAddress & USB_DIR_IN))
117                                         continue;
118                                 intr = 1;
119                                 /* FALLTHROUGH */
120                         case USB_ENDPOINT_XFER_BULK:
121                                 break;
122                         default:
123                                 continue;
124                         }
125                         if (e->desc.bEndpointAddress & USB_DIR_IN) {
126                                 if (!intr && !in)
127                                         in = e;
128                                 else if (intr && !status)
129                                         status = e;
130                         } else {
131                                 if (!out)
132                                         out = e;
133                         }
134                 }
135                 if (in && out)
136                         break;
137         }
138         if (!alt || !in || !out)
139                 return -EINVAL;
140
141         if (alt->desc.bAlternateSetting != 0
142                         || !(dev->driver_info->flags & FLAG_NO_SETINT)) {
143                 tmp = usb_set_interface (dev->udev, alt->desc.bInterfaceNumber,
144                                 alt->desc.bAlternateSetting);
145                 if (tmp < 0)
146                         return tmp;
147         }
148         
149         dev->in = usb_rcvbulkpipe (dev->udev,
150                         in->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
151         dev->out = usb_sndbulkpipe (dev->udev,
152                         out->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
153         dev->status = status;
154         return 0;
155 }
156 EXPORT_SYMBOL_GPL(usbnet_get_endpoints);
157
158 static void intr_complete (struct urb *urb, struct pt_regs *regs);
159
160 static int init_status (struct usbnet *dev, struct usb_interface *intf)
161 {
162         char            *buf = NULL;
163         unsigned        pipe = 0;
164         unsigned        maxp;
165         unsigned        period;
166
167         if (!dev->driver_info->status)
168                 return 0;
169
170         pipe = usb_rcvintpipe (dev->udev,
171                         dev->status->desc.bEndpointAddress
172                                 & USB_ENDPOINT_NUMBER_MASK);
173         maxp = usb_maxpacket (dev->udev, pipe, 0);
174
175         /* avoid 1 msec chatter:  min 8 msec poll rate */
176         period = max ((int) dev->status->desc.bInterval,
177                 (dev->udev->speed == USB_SPEED_HIGH) ? 7 : 3);
178
179         buf = kmalloc (maxp, SLAB_KERNEL);
180         if (buf) {
181                 dev->interrupt = usb_alloc_urb (0, SLAB_KERNEL);
182                 if (!dev->interrupt) {
183                         kfree (buf);
184                         return -ENOMEM;
185                 } else {
186                         usb_fill_int_urb(dev->interrupt, dev->udev, pipe,
187                                 buf, maxp, intr_complete, dev, period);
188                         dev_dbg(&intf->dev,
189                                 "status ep%din, %d bytes period %d\n",
190                                 usb_pipeendpoint(pipe), maxp, period);
191                 }
192         }
193         return  0;
194 }
195
196 /* Passes this packet up the stack, updating its accounting.
197  * Some link protocols batch packets, so their rx_fixup paths
198  * can return clones as well as just modify the original skb.
199  */
200 void usbnet_skb_return (struct usbnet *dev, struct sk_buff *skb)
201 {
202         int     status;
203
204         skb->dev = dev->net;
205         skb->protocol = eth_type_trans (skb, dev->net);
206         dev->stats.rx_packets++;
207         dev->stats.rx_bytes += skb->len;
208
209         if (netif_msg_rx_status (dev))
210                 devdbg (dev, "< rx, len %zu, type 0x%x",
211                         skb->len + sizeof (struct ethhdr), skb->protocol);
212         memset (skb->cb, 0, sizeof (struct skb_data));
213         status = netif_rx (skb);
214         if (status != NET_RX_SUCCESS && netif_msg_rx_err (dev))
215                 devdbg (dev, "netif_rx status %d", status);
216 }
217 EXPORT_SYMBOL_GPL(usbnet_skb_return);
218
219 \f
220 /*-------------------------------------------------------------------------
221  *
222  * Network Device Driver (peer link to "Host Device", from USB host)
223  *
224  *-------------------------------------------------------------------------*/
225
226 static int usbnet_change_mtu (struct net_device *net, int new_mtu)
227 {
228         struct usbnet   *dev = netdev_priv(net);
229         int             ll_mtu = new_mtu + net->hard_header_len;
230
231         if (new_mtu <= 0 || ll_mtu > dev->hard_mtu)
232                 return -EINVAL;
233         // no second zero-length packet read wanted after mtu-sized packets
234         if ((ll_mtu % dev->maxpacket) == 0)
235                 return -EDOM;
236         net->mtu = new_mtu;
237         return 0;
238 }
239
240 /*-------------------------------------------------------------------------*/
241
242 static struct net_device_stats *usbnet_get_stats (struct net_device *net)
243 {
244         struct usbnet   *dev = netdev_priv(net);
245         return &dev->stats;
246 }
247
248 /*-------------------------------------------------------------------------*/
249
250 /* some LK 2.4 HCDs oopsed if we freed or resubmitted urbs from
251  * completion callbacks.  2.5 should have fixed those bugs...
252  */
253
254 static void defer_bh(struct usbnet *dev, struct sk_buff *skb, struct sk_buff_head *list)
255 {
256         unsigned long           flags;
257
258         spin_lock_irqsave(&list->lock, flags);
259         __skb_unlink(skb, list);
260         spin_unlock(&list->lock);
261         spin_lock(&dev->done.lock);
262         __skb_queue_tail(&dev->done, skb);
263         if (dev->done.qlen == 1)
264                 tasklet_schedule(&dev->bh);
265         spin_unlock_irqrestore(&dev->done.lock, flags);
266 }
267
268 /* some work can't be done in tasklets, so we use keventd
269  *
270  * NOTE:  annoying asymmetry:  if it's active, schedule_work() fails,
271  * but tasklet_schedule() doesn't.  hope the failure is rare.
272  */
273 void usbnet_defer_kevent (struct usbnet *dev, int work)
274 {
275         set_bit (work, &dev->flags);
276         if (!schedule_work (&dev->kevent))
277                 deverr (dev, "kevent %d may have been dropped", work);
278         else
279                 devdbg (dev, "kevent %d scheduled", work);
280 }
281 EXPORT_SYMBOL_GPL(usbnet_defer_kevent);
282
283 /*-------------------------------------------------------------------------*/
284
285 static void rx_complete (struct urb *urb, struct pt_regs *regs);
286
287 static void rx_submit (struct usbnet *dev, struct urb *urb, gfp_t flags)
288 {
289         struct sk_buff          *skb;
290         struct skb_data         *entry;
291         int                     retval = 0;
292         unsigned long           lockflags;
293         size_t                  size = dev->rx_urb_size;
294
295         if ((skb = alloc_skb (size + NET_IP_ALIGN, flags)) == NULL) {
296                 if (netif_msg_rx_err (dev))
297                         devdbg (dev, "no rx skb");
298                 usbnet_defer_kevent (dev, EVENT_RX_MEMORY);
299                 usb_free_urb (urb);
300                 return;
301         }
302         skb_reserve (skb, NET_IP_ALIGN);
303
304         entry = (struct skb_data *) skb->cb;
305         entry->urb = urb;
306         entry->dev = dev;
307         entry->state = rx_start;
308         entry->length = 0;
309
310         usb_fill_bulk_urb (urb, dev->udev, dev->in,
311                 skb->data, size, rx_complete, skb);
312
313         spin_lock_irqsave (&dev->rxq.lock, lockflags);
314
315         if (netif_running (dev->net)
316                         && netif_device_present (dev->net)
317                         && !test_bit (EVENT_RX_HALT, &dev->flags)) {
318                 switch (retval = usb_submit_urb (urb, GFP_ATOMIC)){ 
319                 case -EPIPE:
320                         usbnet_defer_kevent (dev, EVENT_RX_HALT);
321                         break;
322                 case -ENOMEM:
323                         usbnet_defer_kevent (dev, EVENT_RX_MEMORY);
324                         break;
325                 case -ENODEV:
326                         if (netif_msg_ifdown (dev))
327                                 devdbg (dev, "device gone");
328                         netif_device_detach (dev->net);
329                         break;
330                 default:
331                         if (netif_msg_rx_err (dev))
332                                 devdbg (dev, "rx submit, %d", retval);
333                         tasklet_schedule (&dev->bh);
334                         break;
335                 case 0:
336                         __skb_queue_tail (&dev->rxq, skb);
337                 }
338         } else {
339                 if (netif_msg_ifdown (dev))
340                         devdbg (dev, "rx: stopped");
341                 retval = -ENOLINK;
342         }
343         spin_unlock_irqrestore (&dev->rxq.lock, lockflags);
344         if (retval) {
345                 dev_kfree_skb_any (skb);
346                 usb_free_urb (urb);
347         }
348 }
349
350
351 /*-------------------------------------------------------------------------*/
352
353 static inline void rx_process (struct usbnet *dev, struct sk_buff *skb)
354 {
355         if (dev->driver_info->rx_fixup
356                         && !dev->driver_info->rx_fixup (dev, skb))
357                 goto error;
358         // else network stack removes extra byte if we forced a short packet
359
360         if (skb->len)
361                 usbnet_skb_return (dev, skb);
362         else {
363                 if (netif_msg_rx_err (dev))
364                         devdbg (dev, "drop");
365 error:
366                 dev->stats.rx_errors++;
367                 skb_queue_tail (&dev->done, skb);
368         }
369 }
370
371 /*-------------------------------------------------------------------------*/
372
373 static void rx_complete (struct urb *urb, struct pt_regs *regs)
374 {
375         struct sk_buff          *skb = (struct sk_buff *) urb->context;
376         struct skb_data         *entry = (struct skb_data *) skb->cb;
377         struct usbnet           *dev = entry->dev;
378         int                     urb_status = urb->status;
379
380         skb_put (skb, urb->actual_length);
381         entry->state = rx_done;
382         entry->urb = NULL;
383
384         switch (urb_status) {
385             // success
386             case 0:
387                 if (skb->len < dev->net->hard_header_len) {
388                         entry->state = rx_cleanup;
389                         dev->stats.rx_errors++;
390                         dev->stats.rx_length_errors++;
391                         if (netif_msg_rx_err (dev))
392                                 devdbg (dev, "rx length %d", skb->len);
393                 }
394                 break;
395
396             // stalls need manual reset. this is rare ... except that
397             // when going through USB 2.0 TTs, unplug appears this way.
398             // we avoid the highspeed version of the ETIMEOUT/EILSEQ
399             // storm, recovering as needed.
400             case -EPIPE:
401                 dev->stats.rx_errors++;
402                 usbnet_defer_kevent (dev, EVENT_RX_HALT);
403                 // FALLTHROUGH
404
405             // software-driven interface shutdown
406             case -ECONNRESET:           // async unlink
407             case -ESHUTDOWN:            // hardware gone
408                 if (netif_msg_ifdown (dev))
409                         devdbg (dev, "rx shutdown, code %d", urb_status);
410                 goto block;
411
412             // we get controller i/o faults during khubd disconnect() delays.
413             // throttle down resubmits, to avoid log floods; just temporarily,
414             // so we still recover when the fault isn't a khubd delay.
415             case -EPROTO:               // ehci
416             case -ETIMEDOUT:            // ohci
417             case -EILSEQ:               // uhci
418                 dev->stats.rx_errors++;
419                 if (!timer_pending (&dev->delay)) {
420                         mod_timer (&dev->delay, jiffies + THROTTLE_JIFFIES);
421                         if (netif_msg_link (dev))
422                                 devdbg (dev, "rx throttle %d", urb_status);
423                 }
424 block:
425                 entry->state = rx_cleanup;
426                 entry->urb = urb;
427                 urb = NULL;
428                 break;
429
430             // data overrun ... flush fifo?
431             case -EOVERFLOW:
432                 dev->stats.rx_over_errors++;
433                 // FALLTHROUGH
434             
435             default:
436                 entry->state = rx_cleanup;
437                 dev->stats.rx_errors++;
438                 if (netif_msg_rx_err (dev))
439                         devdbg (dev, "rx status %d", urb_status);
440                 break;
441         }
442
443         defer_bh(dev, skb, &dev->rxq);
444
445         if (urb) {
446                 if (netif_running (dev->net)
447                                 && !test_bit (EVENT_RX_HALT, &dev->flags)) {
448                         rx_submit (dev, urb, GFP_ATOMIC);
449                         return;
450                 }
451                 usb_free_urb (urb);
452         }
453         if (netif_msg_rx_err (dev))
454                 devdbg (dev, "no read resubmitted");
455 }
456
457 static void intr_complete (struct urb *urb, struct pt_regs *regs)
458 {
459         struct usbnet   *dev = urb->context;
460         int             status = urb->status;
461
462         switch (status) {
463             /* success */
464             case 0:
465                 dev->driver_info->status(dev, urb);
466                 break;
467
468             /* software-driven interface shutdown */
469             case -ENOENT:               // urb killed
470             case -ESHUTDOWN:            // hardware gone
471                 if (netif_msg_ifdown (dev))
472                         devdbg (dev, "intr shutdown, code %d", status);
473                 return;
474
475             /* NOTE:  not throttling like RX/TX, since this endpoint
476              * already polls infrequently
477              */
478             default:
479                 devdbg (dev, "intr status %d", status);
480                 break;
481         }
482
483         if (!netif_running (dev->net))
484                 return;
485
486         memset(urb->transfer_buffer, 0, urb->transfer_buffer_length);
487         status = usb_submit_urb (urb, GFP_ATOMIC);
488         if (status != 0 && netif_msg_timer (dev))
489                 deverr(dev, "intr resubmit --> %d", status);
490 }
491
492 /*-------------------------------------------------------------------------*/
493
494 // unlink pending rx/tx; completion handlers do all other cleanup
495
496 static int unlink_urbs (struct usbnet *dev, struct sk_buff_head *q)
497 {
498         unsigned long           flags;
499         struct sk_buff          *skb, *skbnext;
500         int                     count = 0;
501
502         spin_lock_irqsave (&q->lock, flags);
503         for (skb = q->next; skb != (struct sk_buff *) q; skb = skbnext) {
504                 struct skb_data         *entry;
505                 struct urb              *urb;
506                 int                     retval;
507
508                 entry = (struct skb_data *) skb->cb;
509                 urb = entry->urb;
510                 skbnext = skb->next;
511
512                 // during some PM-driven resume scenarios,
513                 // these (async) unlinks complete immediately
514                 retval = usb_unlink_urb (urb);
515                 if (retval != -EINPROGRESS && retval != 0)
516                         devdbg (dev, "unlink urb err, %d", retval);
517                 else
518                         count++;
519         }
520         spin_unlock_irqrestore (&q->lock, flags);
521         return count;
522 }
523
524 // Flush all pending rx urbs
525 // minidrivers may need to do this when the MTU changes
526
527 void usbnet_unlink_rx_urbs(struct usbnet *dev)
528 {
529         if (netif_running(dev->net)) {
530                 (void) unlink_urbs (dev, &dev->rxq);
531                 tasklet_schedule(&dev->bh);
532         }
533 }
534 EXPORT_SYMBOL_GPL(usbnet_unlink_rx_urbs);
535
536
537 /*-------------------------------------------------------------------------*/
538
539 // precondition: never called in_interrupt
540
541 static int usbnet_stop (struct net_device *net)
542 {
543         struct usbnet           *dev = netdev_priv(net);
544         int                     temp;
545         DECLARE_WAIT_QUEUE_HEAD (unlink_wakeup); 
546         DECLARE_WAITQUEUE (wait, current);
547
548         netif_stop_queue (net);
549
550         if (netif_msg_ifdown (dev))
551                 devinfo (dev, "stop stats: rx/tx %ld/%ld, errs %ld/%ld",
552                         dev->stats.rx_packets, dev->stats.tx_packets, 
553                         dev->stats.rx_errors, dev->stats.tx_errors
554                         );
555
556         // ensure there are no more active urbs
557         add_wait_queue (&unlink_wakeup, &wait);
558         dev->wait = &unlink_wakeup;
559         temp = unlink_urbs (dev, &dev->txq) + unlink_urbs (dev, &dev->rxq);
560
561         // maybe wait for deletions to finish.
562         while (!skb_queue_empty(&dev->rxq) &&
563                !skb_queue_empty(&dev->txq) &&
564                !skb_queue_empty(&dev->done)) {
565                 msleep(UNLINK_TIMEOUT_MS);
566                 if (netif_msg_ifdown (dev))
567                         devdbg (dev, "waited for %d urb completions", temp);
568         }
569         dev->wait = NULL;
570         remove_wait_queue (&unlink_wakeup, &wait); 
571
572         usb_kill_urb(dev->interrupt);
573
574         /* deferred work (task, timer, softirq) must also stop.
575          * can't flush_scheduled_work() until we drop rtnl (later),
576          * else workers could deadlock; so make workers a NOP.
577          */
578         dev->flags = 0;
579         del_timer_sync (&dev->delay);
580         tasklet_kill (&dev->bh);
581
582         return 0;
583 }
584
585 /*-------------------------------------------------------------------------*/
586
587 // posts reads, and enables write queuing
588
589 // precondition: never called in_interrupt
590
591 static int usbnet_open (struct net_device *net)
592 {
593         struct usbnet           *dev = netdev_priv(net);
594         int                     retval = 0;
595         struct driver_info      *info = dev->driver_info;
596
597         // put into "known safe" state
598         if (info->reset && (retval = info->reset (dev)) < 0) {
599                 if (netif_msg_ifup (dev))
600                         devinfo (dev,
601                                 "open reset fail (%d) usbnet usb-%s-%s, %s",
602                                 retval,
603                                 dev->udev->bus->bus_name, dev->udev->devpath,
604                         info->description);
605                 goto done;
606         }
607
608         // insist peer be connected
609         if (info->check_connect && (retval = info->check_connect (dev)) < 0) {
610                 if (netif_msg_ifup (dev))
611                         devdbg (dev, "can't open; %d", retval);
612                 goto done;
613         }
614
615         /* start any status interrupt transfer */
616         if (dev->interrupt) {
617                 retval = usb_submit_urb (dev->interrupt, GFP_KERNEL);
618                 if (retval < 0) {
619                         if (netif_msg_ifup (dev))
620                                 deverr (dev, "intr submit %d", retval);
621                         goto done;
622                 }
623         }
624
625         netif_start_queue (net);
626         if (netif_msg_ifup (dev)) {
627                 char    *framing;
628
629                 if (dev->driver_info->flags & FLAG_FRAMING_NC)
630                         framing = "NetChip";
631                 else if (dev->driver_info->flags & FLAG_FRAMING_GL)
632                         framing = "GeneSys";
633                 else if (dev->driver_info->flags & FLAG_FRAMING_Z)
634                         framing = "Zaurus";
635                 else if (dev->driver_info->flags & FLAG_FRAMING_RN)
636                         framing = "RNDIS";
637                 else if (dev->driver_info->flags & FLAG_FRAMING_AX)
638                         framing = "ASIX";
639                 else
640                         framing = "simple";
641
642                 devinfo (dev, "open: enable queueing "
643                                 "(rx %d, tx %d) mtu %d %s framing",
644                         RX_QLEN (dev), TX_QLEN (dev), dev->net->mtu,
645                         framing);
646         }
647
648         // delay posting reads until we're fully open
649         tasklet_schedule (&dev->bh);
650 done:
651         return retval;
652 }
653
654 /*-------------------------------------------------------------------------*/
655
656 /* ethtool methods; minidrivers may need to add some more, but
657  * they'll probably want to use this base set.
658  */
659
660 void usbnet_get_drvinfo (struct net_device *net, struct ethtool_drvinfo *info)
661 {
662         struct usbnet *dev = netdev_priv(net);
663
664         /* REVISIT don't always return "usbnet" */
665         strncpy (info->driver, driver_name, sizeof info->driver);
666         strncpy (info->version, DRIVER_VERSION, sizeof info->version);
667         strncpy (info->fw_version, dev->driver_info->description,
668                 sizeof info->fw_version);
669         usb_make_path (dev->udev, info->bus_info, sizeof info->bus_info);
670 }
671 EXPORT_SYMBOL_GPL(usbnet_get_drvinfo);
672
673 static u32 usbnet_get_link (struct net_device *net)
674 {
675         struct usbnet *dev = netdev_priv(net);
676
677         /* If a check_connect is defined, return its result */
678         if (dev->driver_info->check_connect)
679                 return dev->driver_info->check_connect (dev) == 0;
680
681         /* Otherwise, say we're up (to avoid breaking scripts) */
682         return 1;
683 }
684
685 u32 usbnet_get_msglevel (struct net_device *net)
686 {
687         struct usbnet *dev = netdev_priv(net);
688
689         return dev->msg_enable;
690 }
691 EXPORT_SYMBOL_GPL(usbnet_get_msglevel);
692
693 void usbnet_set_msglevel (struct net_device *net, u32 level)
694 {
695         struct usbnet *dev = netdev_priv(net);
696
697         dev->msg_enable = level;
698 }
699 EXPORT_SYMBOL_GPL(usbnet_set_msglevel);
700
701 /* drivers may override default ethtool_ops in their bind() routine */
702 static struct ethtool_ops usbnet_ethtool_ops = {
703         .get_drvinfo            = usbnet_get_drvinfo,
704         .get_link               = usbnet_get_link,
705         .get_msglevel           = usbnet_get_msglevel,
706         .set_msglevel           = usbnet_set_msglevel,
707 };
708
709 /*-------------------------------------------------------------------------*/
710
711 /* work that cannot be done in interrupt context uses keventd.
712  *
713  * NOTE:  with 2.5 we could do more of this using completion callbacks,
714  * especially now that control transfers can be queued.
715  */
716 static void
717 kevent (void *data)
718 {
719         struct usbnet           *dev = data;
720         int                     status;
721
722         /* usb_clear_halt() needs a thread context */
723         if (test_bit (EVENT_TX_HALT, &dev->flags)) {
724                 unlink_urbs (dev, &dev->txq);
725                 status = usb_clear_halt (dev->udev, dev->out);
726                 if (status < 0
727                                 && status != -EPIPE
728                                 && status != -ESHUTDOWN) {
729                         if (netif_msg_tx_err (dev))
730                                 deverr (dev, "can't clear tx halt, status %d",
731                                         status);
732                 } else {
733                         clear_bit (EVENT_TX_HALT, &dev->flags);
734                         if (status != -ESHUTDOWN)
735                                 netif_wake_queue (dev->net);
736                 }
737         }
738         if (test_bit (EVENT_RX_HALT, &dev->flags)) {
739                 unlink_urbs (dev, &dev->rxq);
740                 status = usb_clear_halt (dev->udev, dev->in);
741                 if (status < 0
742                                 && status != -EPIPE
743                                 && status != -ESHUTDOWN) {
744                         if (netif_msg_rx_err (dev))
745                                 deverr (dev, "can't clear rx halt, status %d",
746                                         status);
747                 } else {
748                         clear_bit (EVENT_RX_HALT, &dev->flags);
749                         tasklet_schedule (&dev->bh);
750                 }
751         }
752
753         /* tasklet could resubmit itself forever if memory is tight */
754         if (test_bit (EVENT_RX_MEMORY, &dev->flags)) {
755                 struct urb      *urb = NULL;
756
757                 if (netif_running (dev->net))
758                         urb = usb_alloc_urb (0, GFP_KERNEL);
759                 else
760                         clear_bit (EVENT_RX_MEMORY, &dev->flags);
761                 if (urb != NULL) {
762                         clear_bit (EVENT_RX_MEMORY, &dev->flags);
763                         rx_submit (dev, urb, GFP_KERNEL);
764                         tasklet_schedule (&dev->bh);
765                 }
766         }
767
768         if (test_bit (EVENT_LINK_RESET, &dev->flags)) {
769                 struct driver_info      *info = dev->driver_info;
770                 int                     retval = 0;
771
772                 clear_bit (EVENT_LINK_RESET, &dev->flags);
773                 if(info->link_reset && (retval = info->link_reset(dev)) < 0) {
774                         devinfo(dev, "link reset failed (%d) usbnet usb-%s-%s, %s",
775                                 retval,
776                                 dev->udev->bus->bus_name, dev->udev->devpath,
777                                 info->description);
778                 }
779         }
780
781         if (dev->flags)
782                 devdbg (dev, "kevent done, flags = 0x%lx",
783                         dev->flags);
784 }
785
786 /*-------------------------------------------------------------------------*/
787
788 static void tx_complete (struct urb *urb, struct pt_regs *regs)
789 {
790         struct sk_buff          *skb = (struct sk_buff *) urb->context;
791         struct skb_data         *entry = (struct skb_data *) skb->cb;
792         struct usbnet           *dev = entry->dev;
793
794         if (urb->status == 0) {
795                 dev->stats.tx_packets++;
796                 dev->stats.tx_bytes += entry->length;
797         } else {
798                 dev->stats.tx_errors++;
799
800                 switch (urb->status) {
801                 case -EPIPE:
802                         usbnet_defer_kevent (dev, EVENT_TX_HALT);
803                         break;
804
805                 /* software-driven interface shutdown */
806                 case -ECONNRESET:               // async unlink
807                 case -ESHUTDOWN:                // hardware gone
808                         break;
809
810                 // like rx, tx gets controller i/o faults during khubd delays
811                 // and so it uses the same throttling mechanism.
812                 case -EPROTO:           // ehci
813                 case -ETIMEDOUT:        // ohci
814                 case -EILSEQ:           // uhci
815                         if (!timer_pending (&dev->delay)) {
816                                 mod_timer (&dev->delay,
817                                         jiffies + THROTTLE_JIFFIES);
818                                 if (netif_msg_link (dev))
819                                         devdbg (dev, "tx throttle %d",
820                                                         urb->status);
821                         }
822                         netif_stop_queue (dev->net);
823                         break;
824                 default:
825                         if (netif_msg_tx_err (dev))
826                                 devdbg (dev, "tx err %d", entry->urb->status);
827                         break;
828                 }
829         }
830
831         urb->dev = NULL;
832         entry->state = tx_done;
833         defer_bh(dev, skb, &dev->txq);
834 }
835
836 /*-------------------------------------------------------------------------*/
837
838 static void usbnet_tx_timeout (struct net_device *net)
839 {
840         struct usbnet           *dev = netdev_priv(net);
841
842         unlink_urbs (dev, &dev->txq);
843         tasklet_schedule (&dev->bh);
844
845         // FIXME: device recovery -- reset?
846 }
847
848 /*-------------------------------------------------------------------------*/
849
850 static int usbnet_start_xmit (struct sk_buff *skb, struct net_device *net)
851 {
852         struct usbnet           *dev = netdev_priv(net);
853         int                     length;
854         int                     retval = NET_XMIT_SUCCESS;
855         struct urb              *urb = NULL;
856         struct skb_data         *entry;
857         struct driver_info      *info = dev->driver_info;
858         unsigned long           flags;
859
860         // some devices want funky USB-level framing, for
861         // win32 driver (usually) and/or hardware quirks
862         if (info->tx_fixup) {
863                 skb = info->tx_fixup (dev, skb, GFP_ATOMIC);
864                 if (!skb) {
865                         if (netif_msg_tx_err (dev))
866                                 devdbg (dev, "can't tx_fixup skb");
867                         goto drop;
868                 }
869         }
870         length = skb->len;
871
872         if (!(urb = usb_alloc_urb (0, GFP_ATOMIC))) {
873                 if (netif_msg_tx_err (dev))
874                         devdbg (dev, "no urb");
875                 goto drop;
876         }
877
878         entry = (struct skb_data *) skb->cb;
879         entry->urb = urb;
880         entry->dev = dev;
881         entry->state = tx_start;
882         entry->length = length;
883
884         usb_fill_bulk_urb (urb, dev->udev, dev->out,
885                         skb->data, skb->len, tx_complete, skb);
886
887         /* don't assume the hardware handles USB_ZERO_PACKET
888          * NOTE:  strictly conforming cdc-ether devices should expect
889          * the ZLP here, but ignore the one-byte packet.
890          *
891          * FIXME zero that byte, if it doesn't require a new skb.
892          */
893         if ((length % dev->maxpacket) == 0)
894                 urb->transfer_buffer_length++;
895
896         spin_lock_irqsave (&dev->txq.lock, flags);
897
898         switch ((retval = usb_submit_urb (urb, GFP_ATOMIC))) {
899         case -EPIPE:
900                 netif_stop_queue (net);
901                 usbnet_defer_kevent (dev, EVENT_TX_HALT);
902                 break;
903         default:
904                 if (netif_msg_tx_err (dev))
905                         devdbg (dev, "tx: submit urb err %d", retval);
906                 break;
907         case 0:
908                 net->trans_start = jiffies;
909                 __skb_queue_tail (&dev->txq, skb);
910                 if (dev->txq.qlen >= TX_QLEN (dev))
911                         netif_stop_queue (net);
912         }
913         spin_unlock_irqrestore (&dev->txq.lock, flags);
914
915         if (retval) {
916                 if (netif_msg_tx_err (dev))
917                         devdbg (dev, "drop, code %d", retval);
918 drop:
919                 retval = NET_XMIT_SUCCESS;
920                 dev->stats.tx_dropped++;
921                 if (skb)
922                         dev_kfree_skb_any (skb);
923                 usb_free_urb (urb);
924         } else if (netif_msg_tx_queued (dev)) {
925                 devdbg (dev, "> tx, len %d, type 0x%x",
926                         length, skb->protocol);
927         }
928         return retval;
929 }
930
931
932 /*-------------------------------------------------------------------------*/
933
934 // tasklet (work deferred from completions, in_irq) or timer
935
936 static void usbnet_bh (unsigned long param)
937 {
938         struct usbnet           *dev = (struct usbnet *) param;
939         struct sk_buff          *skb;
940         struct skb_data         *entry;
941
942         while ((skb = skb_dequeue (&dev->done))) {
943                 entry = (struct skb_data *) skb->cb;
944                 switch (entry->state) {
945                     case rx_done:
946                         entry->state = rx_cleanup;
947                         rx_process (dev, skb);
948                         continue;
949                     case tx_done:
950                     case rx_cleanup:
951                         usb_free_urb (entry->urb);
952                         dev_kfree_skb (skb);
953                         continue;
954                     default:
955                         devdbg (dev, "bogus skb state %d", entry->state);
956                 }
957         }
958
959         // waiting for all pending urbs to complete?
960         if (dev->wait) {
961                 if ((dev->txq.qlen + dev->rxq.qlen + dev->done.qlen) == 0) {
962                         wake_up (dev->wait);
963                 }
964
965         // or are we maybe short a few urbs?
966         } else if (netif_running (dev->net)
967                         && netif_device_present (dev->net)
968                         && !timer_pending (&dev->delay)
969                         && !test_bit (EVENT_RX_HALT, &dev->flags)) {
970                 int     temp = dev->rxq.qlen;
971                 int     qlen = RX_QLEN (dev);
972
973                 if (temp < qlen) {
974                         struct urb      *urb;
975                         int             i;
976
977                         // don't refill the queue all at once
978                         for (i = 0; i < 10 && dev->rxq.qlen < qlen; i++) {
979                                 urb = usb_alloc_urb (0, GFP_ATOMIC);
980                                 if (urb != NULL)
981                                         rx_submit (dev, urb, GFP_ATOMIC);
982                         }
983                         if (temp != dev->rxq.qlen && netif_msg_link (dev))
984                                 devdbg (dev, "rxqlen %d --> %d",
985                                                 temp, dev->rxq.qlen);
986                         if (dev->rxq.qlen < qlen)
987                                 tasklet_schedule (&dev->bh);
988                 }
989                 if (dev->txq.qlen < TX_QLEN (dev))
990                         netif_wake_queue (dev->net);
991         }
992 }
993
994
995 \f
996 /*-------------------------------------------------------------------------
997  *
998  * USB Device Driver support
999  *
1000  *-------------------------------------------------------------------------*/
1001  
1002 // precondition: never called in_interrupt
1003
1004 void usbnet_disconnect (struct usb_interface *intf)
1005 {
1006         struct usbnet           *dev;
1007         struct usb_device       *xdev;
1008         struct net_device       *net;
1009
1010         dev = usb_get_intfdata(intf);
1011         usb_set_intfdata(intf, NULL);
1012         if (!dev)
1013                 return;
1014
1015         xdev = interface_to_usbdev (intf);
1016
1017         if (netif_msg_probe (dev))
1018                 devinfo (dev, "unregister '%s' usb-%s-%s, %s",
1019                         intf->dev.driver->name,
1020                         xdev->bus->bus_name, xdev->devpath,
1021                         dev->driver_info->description);
1022         
1023         net = dev->net;
1024         unregister_netdev (net);
1025
1026         /* we don't hold rtnl here ... */
1027         flush_scheduled_work ();
1028
1029         if (dev->driver_info->unbind)
1030                 dev->driver_info->unbind (dev, intf);
1031
1032         free_netdev(net);
1033         usb_put_dev (xdev);
1034 }
1035 EXPORT_SYMBOL_GPL(usbnet_disconnect);
1036
1037
1038 /*-------------------------------------------------------------------------*/
1039
1040 // precondition: never called in_interrupt
1041
1042 int
1043 usbnet_probe (struct usb_interface *udev, const struct usb_device_id *prod)
1044 {
1045         struct usbnet                   *dev;
1046         struct net_device               *net;
1047         struct usb_host_interface       *interface;
1048         struct driver_info              *info;
1049         struct usb_device               *xdev;
1050         int                             status;
1051
1052         info = (struct driver_info *) prod->driver_info;
1053         if (!info) {
1054                 dev_dbg (&udev->dev, "blacklisted by %s\n", driver_name);
1055                 return -ENODEV;
1056         }
1057         xdev = interface_to_usbdev (udev);
1058         interface = udev->cur_altsetting;
1059
1060         usb_get_dev (xdev);
1061
1062         status = -ENOMEM;
1063
1064         // set up our own records
1065         net = alloc_etherdev(sizeof(*dev));
1066         if (!net) {
1067                 dbg ("can't kmalloc dev");
1068                 goto out;
1069         }
1070
1071         dev = netdev_priv(net);
1072         dev->udev = xdev;
1073         dev->driver_info = info;
1074         dev->msg_enable = netif_msg_init (msg_level, NETIF_MSG_DRV
1075                                 | NETIF_MSG_PROBE | NETIF_MSG_LINK);
1076         skb_queue_head_init (&dev->rxq);
1077         skb_queue_head_init (&dev->txq);
1078         skb_queue_head_init (&dev->done);
1079         dev->bh.func = usbnet_bh;
1080         dev->bh.data = (unsigned long) dev;
1081         INIT_WORK (&dev->kevent, kevent, dev);
1082         dev->delay.function = usbnet_bh;
1083         dev->delay.data = (unsigned long) dev;
1084         init_timer (&dev->delay);
1085
1086         SET_MODULE_OWNER (net);
1087         dev->net = net;
1088         strcpy (net->name, "usb%d");
1089         memcpy (net->dev_addr, node_id, sizeof node_id);
1090
1091         /* rx and tx sides can use different message sizes;
1092          * bind() should set rx_urb_size in that case.
1093          */
1094         dev->hard_mtu = net->mtu + net->hard_header_len;
1095 #if 0
1096 // dma_supported() is deeply broken on almost all architectures
1097         // possible with some EHCI controllers
1098         if (dma_supported (&udev->dev, DMA_64BIT_MASK))
1099                 net->features |= NETIF_F_HIGHDMA;
1100 #endif
1101
1102         net->change_mtu = usbnet_change_mtu;
1103         net->get_stats = usbnet_get_stats;
1104         net->hard_start_xmit = usbnet_start_xmit;
1105         net->open = usbnet_open;
1106         net->stop = usbnet_stop;
1107         net->watchdog_timeo = TX_TIMEOUT_JIFFIES;
1108         net->tx_timeout = usbnet_tx_timeout;
1109         net->ethtool_ops = &usbnet_ethtool_ops;
1110
1111         // allow device-specific bind/init procedures
1112         // NOTE net->name still not usable ...
1113         if (info->bind) {
1114                 status = info->bind (dev, udev);
1115                 // heuristic:  "usb%d" for links we know are two-host,
1116                 // else "eth%d" when there's reasonable doubt.  userspace
1117                 // can rename the link if it knows better.
1118                 if ((dev->driver_info->flags & FLAG_ETHER) != 0
1119                                 && (net->dev_addr [0] & 0x02) == 0)
1120                         strcpy (net->name, "eth%d");
1121
1122                 /* maybe the remote can't receive an Ethernet MTU */
1123                 if (net->mtu > (dev->hard_mtu - net->hard_header_len))
1124                         net->mtu = dev->hard_mtu - net->hard_header_len;
1125         } else if (!info->in || !info->out)
1126                 status = usbnet_get_endpoints (dev, udev);
1127         else {
1128                 dev->in = usb_rcvbulkpipe (xdev, info->in);
1129                 dev->out = usb_sndbulkpipe (xdev, info->out);
1130                 if (!(info->flags & FLAG_NO_SETINT))
1131                         status = usb_set_interface (xdev,
1132                                 interface->desc.bInterfaceNumber,
1133                                 interface->desc.bAlternateSetting);
1134                 else
1135                         status = 0;
1136
1137         }
1138         if (status == 0 && dev->status)
1139                 status = init_status (dev, udev);
1140         if (status < 0)
1141                 goto out1;
1142
1143         if (!dev->rx_urb_size)
1144                 dev->rx_urb_size = dev->hard_mtu;
1145         dev->maxpacket = usb_maxpacket (dev->udev, dev->out, 1);
1146         
1147         SET_NETDEV_DEV(net, &udev->dev);
1148         status = register_netdev (net);
1149         if (status)
1150                 goto out3;
1151         if (netif_msg_probe (dev))
1152                 devinfo (dev, "register '%s' at usb-%s-%s, %s, "
1153                                 "%02x:%02x:%02x:%02x:%02x:%02x",
1154                         udev->dev.driver->name,
1155                         xdev->bus->bus_name, xdev->devpath,
1156                         dev->driver_info->description,
1157                         net->dev_addr [0], net->dev_addr [1],
1158                         net->dev_addr [2], net->dev_addr [3],
1159                         net->dev_addr [4], net->dev_addr [5]);
1160
1161         // ok, it's ready to go.
1162         usb_set_intfdata (udev, dev);
1163
1164         // start as if the link is up
1165         netif_device_attach (net);
1166
1167         return 0;
1168
1169 out3:
1170         if (info->unbind)
1171                 info->unbind (dev, udev);
1172 out1:
1173         free_netdev(net);
1174 out:
1175         usb_put_dev(xdev);
1176         return status;
1177 }
1178 EXPORT_SYMBOL_GPL(usbnet_probe);
1179
1180 /*-------------------------------------------------------------------------*/
1181
1182 /* FIXME these suspend/resume methods assume non-CDC style
1183  * devices, with only one interface.
1184  */
1185
1186 int usbnet_suspend (struct usb_interface *intf, pm_message_t message)
1187 {
1188         struct usbnet           *dev = usb_get_intfdata(intf);
1189         
1190         /* accelerate emptying of the rx and queues, to avoid
1191          * having everything error out.
1192          */
1193         netif_device_detach (dev->net);
1194         (void) unlink_urbs (dev, &dev->rxq);
1195         (void) unlink_urbs (dev, &dev->txq);
1196         return 0;
1197 }
1198 EXPORT_SYMBOL_GPL(usbnet_suspend);
1199
1200 int usbnet_resume (struct usb_interface *intf)
1201 {
1202         struct usbnet           *dev = usb_get_intfdata(intf);
1203
1204         netif_device_attach (dev->net);
1205         tasklet_schedule (&dev->bh);
1206         return 0;
1207 }
1208 EXPORT_SYMBOL_GPL(usbnet_resume);
1209
1210
1211 /*-------------------------------------------------------------------------*/
1212
1213 static int __init usbnet_init(void)
1214 {
1215         /* compiler should optimize this out */
1216         BUG_ON (sizeof (((struct sk_buff *)0)->cb)
1217                         < sizeof (struct skb_data));
1218
1219         random_ether_addr(node_id);
1220         return 0;
1221 }
1222 module_init(usbnet_init);
1223
1224 static void __exit usbnet_exit(void)
1225 {
1226 }
1227 module_exit(usbnet_exit);
1228
1229 MODULE_AUTHOR("David Brownell");
1230 MODULE_DESCRIPTION("USB network driver framework");
1231 MODULE_LICENSE("GPL");