[PATCH] USB: usbnet (3/9) module for ASIX Ethernet adapters
[linux-2.6] / drivers / usb / net / usbnet.c
1 /*
2  * USB Networking Links
3  * Copyright (C) 2000-2005 by David Brownell
4  * Copyright (C) 2002 Pavel Machek <pavel@ucw.cz>
5  * Copyright (C) 2003-2005 David Hollis <dhollis@davehollis.com>
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 /*
23  * This is a generic "USB networking" framework that works with several
24  * kinds of full and high speed networking devices:
25  *
26  *   + USB host-to-host "network cables", used for IP-over-USB links.
27  *     These are often used for Laplink style connectivity products.
28  *      - AnchorChip 2720
29  *      - Belkin, eTEK (interops with Win32 drivers)
30  *      - GeneSys GL620USB-A
31  *      - NetChip 1080 (interoperates with NetChip Win32 drivers)
32  *      - Prolific PL-2301/2302 (replaces "plusb" driver)
33  *      - KC Technology KC2190
34  *
35  *   + Smart USB devices can support such links directly, using Internet
36  *     standard protocols instead of proprietary host-to-device links.
37  *      - Linux PDAs like iPaq, Yopy, and Zaurus
38  *      - The BLOB boot loader (for diskless booting)
39  *      - Linux "gadgets", perhaps using PXA-2xx or Net2280 controllers
40  *      - Devices using EPSON's sample USB firmware
41  *      - CDC-Ethernet class devices, such as many cable modems
42  *
43  *   + Adapters to networks such as Ethernet.
44  *      - AX8817X based USB 2.0 products
45  *
46  * Links to these devices can be bridged using Linux Ethernet bridging.
47  * With minor exceptions, these all use similar USB framing for network
48  * traffic, but need different protocols for control traffic.
49  *
50  * USB devices can implement their side of this protocol at the cost
51  * of two bulk endpoints; it's not restricted to "cable" applications.
52  * See the SA1110, Zaurus, or EPSON device/client support in this driver;
53  * slave/target drivers such as "usb-eth" (on most SA-1100 PDAs) or
54  * "g_ether" (in the Linux "gadget" framework) implement that behavior
55  * within devices.
56  *
57  *
58  * CHANGELOG:
59  *
60  * 13-sep-2000  experimental, new
61  * 10-oct-2000  usb_device_id table created. 
62  * 28-oct-2000  misc fixes; mostly, discard more TTL-mangled rx packets.
63  * 01-nov-2000  usb_device_id table and probing api update by
64  *              Adam J. Richter <adam@yggdrasil.com>.
65  * 18-dec-2000  (db) tx watchdog, "net1080" renaming to "usbnet", device_info
66  *              and prolific support, isolate net1080-specific bits, cleanup.
67  *              fix unlink_urbs oops in D3 PM resume code path.
68  *
69  * 02-feb-2001  (db) fix tx skb sharing, packet length, match_flags, ...
70  * 08-feb-2001  stubbed in "linuxdev", maybe the SA-1100 folk can use it;
71  *              AnchorChips 2720 support (from spec) for testing;
72  *              fix bit-ordering problem with ethernet multicast addr
73  * 19-feb-2001  Support for clearing halt conditions. SA1100 UDC support
74  *              updates. Oleg Drokin (green@iXcelerator.com)
75  * 25-mar-2001  More SA-1100 updates, including workaround for ip problem
76  *              expecting cleared skb->cb and framing change to match latest
77  *              handhelds.org version (Oleg).  Enable device IDs from the
78  *              Win32 Belkin driver; other cleanups (db).
79  * 16-jul-2001  Bugfixes for uhci oops-on-unplug, Belkin support, various
80  *              cleanups for problems not yet seen in the field. (db)
81  * 17-oct-2001  Handle "Advance USBNET" product, like Belkin/eTEK devices,
82  *              from Ioannis Mavroukakis <i.mavroukakis@btinternet.com>;
83  *              rx unlinks somehow weren't async; minor cleanup.
84  * 03-nov-2001  Merged GeneSys driver; original code from Jiun-Jie Huang
85  *              <huangjj@genesyslogic.com.tw>, updated by Stanislav Brabec
86  *              <utx@penguin.cz>.  Made framing options (NetChip/GeneSys)
87  *              tie mostly to (sub)driver info.  Workaround some PL-2302
88  *              chips that seem to reject SET_INTERFACE requests.
89  *
90  * 06-apr-2002  Added ethtool support, based on a patch from Brad Hards.
91  *              Level of diagnostics is more configurable; they use device
92  *              location (usb_device->devpath) instead of address (2.5).
93  *              For tx_fixup, memflags can't be NOIO.
94  * 07-may-2002  Generalize/cleanup keventd support, handling rx stalls (mostly
95  *              for USB 2.0 TTs) and memory shortages (potential) too. (db)
96  *              Use "locally assigned" IEEE802 address space. (Brad Hards)
97  * 18-oct-2002  Support for Zaurus (Pavel Machek), related cleanup (db).
98  * 14-dec-2002  Remove Zaurus-private crc32 code (Pavel); 2.5 oops fix,
99  *              cleanups and stubbed PXA-250 support (db), fix for framing
100  *              issues on Z, net1080, and gl620a (Toby Milne)
101  *
102  * 31-mar-2003  Use endpoint descriptors:  high speed support, simpler sa1100
103  *              vs pxa25x, and CDC Ethernet.  Throttle down log floods on
104  *              disconnect; other cleanups. (db)  Flush net1080 fifos
105  *              after several sequential framing errors. (Johannes Erdfelt)
106  * 22-aug-2003  AX8817X support (Dave Hollis).
107  * 14-jun-2004  Trivial patch for AX8817X based Buffalo LUA-U2-KTX in Japan
108  *              (Neil Bortnak)
109  * 03-nov-2004  Trivial patch for KC2190 (KC-190) chip. (Jonathan McDowell)
110  *
111  * 01-feb-2005  AX88772 support (Phil Chang & Dave Hollis)
112  *-------------------------------------------------------------------------*/
113
114 // #define      DEBUG                   // error path messages, extra info
115 // #define      VERBOSE                 // more; success messages
116
117 #include <linux/config.h>
118 #ifdef  CONFIG_USB_DEBUG
119 #   define DEBUG
120 #endif
121 #include <linux/module.h>
122 #include <linux/kmod.h>
123 #include <linux/sched.h>
124 #include <linux/init.h>
125 #include <linux/netdevice.h>
126 #include <linux/etherdevice.h>
127 #include <linux/ethtool.h>
128 #include <linux/workqueue.h>
129 #include <linux/mii.h>
130 #include <linux/usb.h>
131 #include <linux/mm.h>
132 #include <linux/dma-mapping.h>
133
134 #include <asm/unaligned.h>
135
136 #include "usbnet.h"
137
138 #define DRIVER_VERSION          "22-Aug-2005"
139
140
141 /*-------------------------------------------------------------------------*/
142
143 /*
144  * Nineteen USB 1.1 max size bulk transactions per frame (ms), max.
145  * Several dozen bytes of IPv4 data can fit in two such transactions.
146  * One maximum size Ethernet packet takes twenty four of them.
147  * For high speed, each frame comfortably fits almost 36 max size
148  * Ethernet packets (so queues should be bigger).
149  *
150  * REVISIT qlens should be members of 'struct usbnet'; the goal is to
151  * let the USB host controller be busy for 5msec or more before an irq
152  * is required, under load.  Jumbograms change the equation.
153  */
154 #define RX_QLEN(dev) (((dev)->udev->speed == USB_SPEED_HIGH) ? 60 : 4)
155 #define TX_QLEN(dev) (((dev)->udev->speed == USB_SPEED_HIGH) ? 60 : 4)
156
157 // reawaken network queue this soon after stopping; else watchdog barks
158 #define TX_TIMEOUT_JIFFIES      (5*HZ)
159
160 // throttle rx/tx briefly after some faults, so khubd might disconnect()
161 // us (it polls at HZ/4 usually) before we report too many false errors.
162 #define THROTTLE_JIFFIES        (HZ/8)
163
164 // for vendor-specific control operations
165 #define CONTROL_TIMEOUT_MS      USB_CTRL_GET_TIMEOUT
166
167 // between wakeups
168 #define UNLINK_TIMEOUT_MS       3
169
170 /*-------------------------------------------------------------------------*/
171
172 // randomly generated ethernet address
173 static u8       node_id [ETH_ALEN];
174
175 static const char driver_name [] = "usbnet";
176
177 /* use ethtool to change the level for any given device */
178 static int msg_level = -1;
179 module_param (msg_level, int, 0);
180 MODULE_PARM_DESC (msg_level, "Override default message level");
181
182 /*-------------------------------------------------------------------------*/
183
184 static u32 usbnet_get_link (struct net_device *);
185
186 /* mostly for PDA style devices, which are always connected if present */
187 static int always_connected (struct usbnet *dev)
188 {
189         return 0;
190 }
191
192 /* handles CDC Ethernet and many other network "bulk data" interfaces */
193 int usbnet_get_endpoints(struct usbnet *dev, struct usb_interface *intf)
194 {
195         int                             tmp;
196         struct usb_host_interface       *alt = NULL;
197         struct usb_host_endpoint        *in = NULL, *out = NULL;
198         struct usb_host_endpoint        *status = NULL;
199
200         for (tmp = 0; tmp < intf->num_altsetting; tmp++) {
201                 unsigned        ep;
202
203                 in = out = status = NULL;
204                 alt = intf->altsetting + tmp;
205
206                 /* take the first altsetting with in-bulk + out-bulk;
207                  * remember any status endpoint, just in case;
208                  * ignore other endpoints and altsetttings.
209                  */
210                 for (ep = 0; ep < alt->desc.bNumEndpoints; ep++) {
211                         struct usb_host_endpoint        *e;
212                         int                             intr = 0;
213
214                         e = alt->endpoint + ep;
215                         switch (e->desc.bmAttributes) {
216                         case USB_ENDPOINT_XFER_INT:
217                                 if (!(e->desc.bEndpointAddress & USB_DIR_IN))
218                                         continue;
219                                 intr = 1;
220                                 /* FALLTHROUGH */
221                         case USB_ENDPOINT_XFER_BULK:
222                                 break;
223                         default:
224                                 continue;
225                         }
226                         if (e->desc.bEndpointAddress & USB_DIR_IN) {
227                                 if (!intr && !in)
228                                         in = e;
229                                 else if (intr && !status)
230                                         status = e;
231                         } else {
232                                 if (!out)
233                                         out = e;
234                         }
235                 }
236                 if (in && out)
237                         break;
238         }
239         if (!alt || !in || !out)
240                 return -EINVAL;
241
242         if (alt->desc.bAlternateSetting != 0
243                         || !(dev->driver_info->flags & FLAG_NO_SETINT)) {
244                 tmp = usb_set_interface (dev->udev, alt->desc.bInterfaceNumber,
245                                 alt->desc.bAlternateSetting);
246                 if (tmp < 0)
247                         return tmp;
248         }
249         
250         dev->in = usb_rcvbulkpipe (dev->udev,
251                         in->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
252         dev->out = usb_sndbulkpipe (dev->udev,
253                         out->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
254         dev->status = status;
255         return 0;
256 }
257 EXPORT_SYMBOL_GPL(usbnet_get_endpoints);
258
259 static void intr_complete (struct urb *urb, struct pt_regs *regs);
260
261 static int init_status (struct usbnet *dev, struct usb_interface *intf)
262 {
263         char            *buf = NULL;
264         unsigned        pipe = 0;
265         unsigned        maxp;
266         unsigned        period;
267
268         if (!dev->driver_info->status)
269                 return 0;
270
271         pipe = usb_rcvintpipe (dev->udev,
272                         dev->status->desc.bEndpointAddress
273                                 & USB_ENDPOINT_NUMBER_MASK);
274         maxp = usb_maxpacket (dev->udev, pipe, 0);
275
276         /* avoid 1 msec chatter:  min 8 msec poll rate */
277         period = max ((int) dev->status->desc.bInterval,
278                 (dev->udev->speed == USB_SPEED_HIGH) ? 7 : 3);
279
280         buf = kmalloc (maxp, SLAB_KERNEL);
281         if (buf) {
282                 dev->interrupt = usb_alloc_urb (0, SLAB_KERNEL);
283                 if (!dev->interrupt) {
284                         kfree (buf);
285                         return -ENOMEM;
286                 } else {
287                         usb_fill_int_urb(dev->interrupt, dev->udev, pipe,
288                                 buf, maxp, intr_complete, dev, period);
289                         dev_dbg(&intf->dev,
290                                 "status ep%din, %d bytes period %d\n",
291                                 usb_pipeendpoint(pipe), maxp, period);
292                 }
293         }
294         return  0;
295 }
296
297 /* Passes this packet up the stack, updating its accounting.
298  * Some link protocols batch packets, so their rx_fixup paths
299  * can return clones as well as just modify the original skb.
300  */
301 void usbnet_skb_return (struct usbnet *dev, struct sk_buff *skb)
302 {
303         int     status;
304
305         skb->dev = dev->net;
306         skb->protocol = eth_type_trans (skb, dev->net);
307         dev->stats.rx_packets++;
308         dev->stats.rx_bytes += skb->len;
309
310         if (netif_msg_rx_status (dev))
311                 devdbg (dev, "< rx, len %zu, type 0x%x",
312                         skb->len + sizeof (struct ethhdr), skb->protocol);
313         memset (skb->cb, 0, sizeof (struct skb_data));
314         status = netif_rx (skb);
315         if (status != NET_RX_SUCCESS && netif_msg_rx_err (dev))
316                 devdbg (dev, "netif_rx status %d", status);
317 }
318 EXPORT_SYMBOL_GPL(usbnet_skb_return);
319
320 \f
321 /*-------------------------------------------------------------------------
322  *
323  * Communications Device Class declarations.
324  * Used by CDC Ethernet, and some CDC variants
325  *
326  *-------------------------------------------------------------------------*/
327
328 #ifdef  CONFIG_USB_CDCETHER
329 #define NEED_GENERIC_CDC
330 #endif
331
332 #ifdef  CONFIG_USB_ZAURUS
333 /* Ethernet variant uses funky framing, broken ethernet addressing */
334 #define NEED_GENERIC_CDC
335 #endif
336
337 #ifdef  CONFIG_USB_RNDIS
338 /* ACM variant uses even funkier framing, complex control RPC scheme */
339 #define NEED_GENERIC_CDC
340 #endif
341
342
343 #ifdef  NEED_GENERIC_CDC
344
345 #include <linux/usb_cdc.h>
346
347 struct cdc_state {
348         struct usb_cdc_header_desc      *header;
349         struct usb_cdc_union_desc       *u;
350         struct usb_cdc_ether_desc       *ether;
351         struct usb_interface            *control;
352         struct usb_interface            *data;
353 };
354
355 static struct usb_driver usbnet_driver;
356
357 /*
358  * probes control interface, claims data interface, collects the bulk
359  * endpoints, activates data interface (if needed), maybe sets MTU.
360  * all pure cdc, except for certain firmware workarounds.
361  */
362 static int generic_cdc_bind (struct usbnet *dev, struct usb_interface *intf)
363 {
364         u8                              *buf = intf->cur_altsetting->extra;
365         int                             len = intf->cur_altsetting->extralen;
366         struct usb_interface_descriptor *d;
367         struct cdc_state                *info = (void *) &dev->data;
368         int                             status;
369         int                             rndis;
370
371         if (sizeof dev->data < sizeof *info)
372                 return -EDOM;
373
374         /* expect strict spec conformance for the descriptors, but
375          * cope with firmware which stores them in the wrong place
376          */
377         if (len == 0 && dev->udev->actconfig->extralen) {
378                 /* Motorola SB4100 (and others: Brad Hards says it's
379                  * from a Broadcom design) put CDC descriptors here
380                  */
381                 buf = dev->udev->actconfig->extra;
382                 len = dev->udev->actconfig->extralen;
383                 if (len)
384                         dev_dbg (&intf->dev,
385                                 "CDC descriptors on config\n");
386         }
387
388         /* this assumes that if there's a non-RNDIS vendor variant
389          * of cdc-acm, it'll fail RNDIS requests cleanly.
390          */
391         rndis = (intf->cur_altsetting->desc.bInterfaceProtocol == 0xff);
392
393         memset (info, 0, sizeof *info);
394         info->control = intf;
395         while (len > 3) {
396                 if (buf [1] != USB_DT_CS_INTERFACE)
397                         goto next_desc;
398
399                 /* use bDescriptorSubType to identify the CDC descriptors.
400                  * We expect devices with CDC header and union descriptors.
401                  * For CDC Ethernet we need the ethernet descriptor.
402                  * For RNDIS, ignore two (pointless) CDC modem descriptors
403                  * in favor of a complicated OID-based RPC scheme doing what
404                  * CDC Ethernet achieves with a simple descriptor.
405                  */
406                 switch (buf [2]) {
407                 case USB_CDC_HEADER_TYPE:
408                         if (info->header) {
409                                 dev_dbg (&intf->dev, "extra CDC header\n");
410                                 goto bad_desc;
411                         }
412                         info->header = (void *) buf;
413                         if (info->header->bLength != sizeof *info->header) {
414                                 dev_dbg (&intf->dev, "CDC header len %u\n",
415                                         info->header->bLength);
416                                 goto bad_desc;
417                         }
418                         break;
419                 case USB_CDC_UNION_TYPE:
420                         if (info->u) {
421                                 dev_dbg (&intf->dev, "extra CDC union\n");
422                                 goto bad_desc;
423                         }
424                         info->u = (void *) buf;
425                         if (info->u->bLength != sizeof *info->u) {
426                                 dev_dbg (&intf->dev, "CDC union len %u\n",
427                                         info->u->bLength);
428                                 goto bad_desc;
429                         }
430
431                         /* we need a master/control interface (what we're
432                          * probed with) and a slave/data interface; union
433                          * descriptors sort this all out.
434                          */
435                         info->control = usb_ifnum_to_if(dev->udev,
436                                                 info->u->bMasterInterface0);
437                         info->data = usb_ifnum_to_if(dev->udev,
438                                                 info->u->bSlaveInterface0);
439                         if (!info->control || !info->data) {
440                                 dev_dbg (&intf->dev,
441                                         "master #%u/%p slave #%u/%p\n",
442                                         info->u->bMasterInterface0,
443                                         info->control,
444                                         info->u->bSlaveInterface0,
445                                         info->data);
446                                 goto bad_desc;
447                         }
448                         if (info->control != intf) {
449                                 dev_dbg (&intf->dev, "bogus CDC Union\n");
450                                 /* Ambit USB Cable Modem (and maybe others)
451                                  * interchanges master and slave interface.
452                                  */
453                                 if (info->data == intf) {
454                                         info->data = info->control;
455                                         info->control = intf;
456                                 } else
457                                         goto bad_desc;
458                         }
459
460                         /* a data interface altsetting does the real i/o */
461                         d = &info->data->cur_altsetting->desc;
462                         if (d->bInterfaceClass != USB_CLASS_CDC_DATA) {
463                                 dev_dbg (&intf->dev, "slave class %u\n",
464                                         d->bInterfaceClass);
465                                 goto bad_desc;
466                         }
467                         break;
468                 case USB_CDC_ETHERNET_TYPE:
469                         if (info->ether) {
470                                 dev_dbg (&intf->dev, "extra CDC ether\n");
471                                 goto bad_desc;
472                         }
473                         info->ether = (void *) buf;
474                         if (info->ether->bLength != sizeof *info->ether) {
475                                 dev_dbg (&intf->dev, "CDC ether len %u\n",
476                                         info->ether->bLength);
477                                 goto bad_desc;
478                         }
479                         dev->hard_mtu = le16_to_cpu(
480                                                 info->ether->wMaxSegmentSize);
481                         /* because of Zaurus, we may be ignoring the host
482                          * side link address we were given.
483                          */
484                         break;
485                 }
486 next_desc:
487                 len -= buf [0]; /* bLength */
488                 buf += buf [0];
489         }
490
491         if (!info->header || !info->u || (!rndis && !info->ether)) {
492                 dev_dbg (&intf->dev, "missing cdc %s%s%sdescriptor\n",
493                         info->header ? "" : "header ",
494                         info->u ? "" : "union ",
495                         info->ether ? "" : "ether ");
496                 goto bad_desc;
497         }
498
499         /* claim data interface and set it up ... with side effects.
500          * network traffic can't flow until an altsetting is enabled.
501          */
502         status = usb_driver_claim_interface (&usbnet_driver, info->data, dev);
503         if (status < 0)
504                 return status;
505         status = usbnet_get_endpoints (dev, info->data);
506         if (status < 0) {
507                 /* ensure immediate exit from usbnet_disconnect */
508                 usb_set_intfdata(info->data, NULL);
509                 usb_driver_release_interface (&usbnet_driver, info->data);
510                 return status;
511         }
512
513         /* status endpoint: optional for CDC Ethernet, not RNDIS (or ACM) */
514         dev->status = NULL;
515         if (info->control->cur_altsetting->desc.bNumEndpoints == 1) {
516                 struct usb_endpoint_descriptor  *desc;
517
518                 dev->status = &info->control->cur_altsetting->endpoint [0];
519                 desc = &dev->status->desc;
520                 if (desc->bmAttributes != USB_ENDPOINT_XFER_INT
521                                 || !(desc->bEndpointAddress & USB_DIR_IN)
522                                 || (le16_to_cpu(desc->wMaxPacketSize)
523                                         < sizeof (struct usb_cdc_notification))
524                                 || !desc->bInterval) {
525                         dev_dbg (&intf->dev, "bad notification endpoint\n");
526                         dev->status = NULL;
527                 }
528         }
529         if (rndis && !dev->status) {
530                 dev_dbg (&intf->dev, "missing RNDIS status endpoint\n");
531                 usb_set_intfdata(info->data, NULL);
532                 usb_driver_release_interface (&usbnet_driver, info->data);
533                 return -ENODEV;
534         }
535         return 0;
536
537 bad_desc:
538         dev_info (&dev->udev->dev, "bad CDC descriptors\n");
539         return -ENODEV;
540 }
541
542 static void cdc_unbind (struct usbnet *dev, struct usb_interface *intf)
543 {
544         struct cdc_state                *info = (void *) &dev->data;
545
546         /* disconnect master --> disconnect slave */
547         if (intf == info->control && info->data) {
548                 /* ensure immediate exit from usbnet_disconnect */
549                 usb_set_intfdata(info->data, NULL);
550                 usb_driver_release_interface (&usbnet_driver, info->data);
551                 info->data = NULL;
552         }
553
554         /* and vice versa (just in case) */
555         else if (intf == info->data && info->control) {
556                 /* ensure immediate exit from usbnet_disconnect */
557                 usb_set_intfdata(info->control, NULL);
558                 usb_driver_release_interface (&usbnet_driver, info->control);
559                 info->control = NULL;
560         }
561 }
562
563 #endif  /* NEED_GENERIC_CDC */
564
565 \f
566 #ifdef  CONFIG_USB_CDCETHER
567 #define HAVE_HARDWARE
568
569 /*-------------------------------------------------------------------------
570  *
571  * Communications Device Class, Ethernet Control model
572  *
573  * Takes two interfaces.  The DATA interface is inactive till an altsetting
574  * is selected.  Configuration data includes class descriptors.
575  *
576  * This should interop with whatever the 2.4 "CDCEther.c" driver
577  * (by Brad Hards) talked with.
578  *
579  *-------------------------------------------------------------------------*/
580
581 #include <linux/ctype.h>
582
583
584 static void dumpspeed (struct usbnet *dev, __le32 *speeds)
585 {
586         if (netif_msg_timer (dev))
587                 devinfo (dev, "link speeds: %u kbps up, %u kbps down",
588                         __le32_to_cpu(speeds[0]) / 1000,
589                 __le32_to_cpu(speeds[1]) / 1000);
590 }
591
592 static void cdc_status (struct usbnet *dev, struct urb *urb)
593 {
594         struct usb_cdc_notification     *event;
595
596         if (urb->actual_length < sizeof *event)
597                 return;
598         
599         /* SPEED_CHANGE can get split into two 8-byte packets */
600         if (test_and_clear_bit (EVENT_STS_SPLIT, &dev->flags)) {
601                 dumpspeed (dev, (__le32 *) urb->transfer_buffer);
602                 return;
603         }
604
605         event = urb->transfer_buffer;
606         switch (event->bNotificationType) {
607         case USB_CDC_NOTIFY_NETWORK_CONNECTION:
608                 if (netif_msg_timer (dev))
609                         devdbg (dev, "CDC: carrier %s",
610                                         event->wValue ? "on" : "off");
611                 if (event->wValue)
612                         netif_carrier_on(dev->net);
613                 else
614                         netif_carrier_off(dev->net);
615                 break;
616         case USB_CDC_NOTIFY_SPEED_CHANGE:       /* tx/rx rates */
617                 if (netif_msg_timer (dev))
618                         devdbg (dev, "CDC: speed change (len %d)",
619                                         urb->actual_length);
620                 if (urb->actual_length != (sizeof *event + 8))
621                         set_bit (EVENT_STS_SPLIT, &dev->flags);
622                 else
623                         dumpspeed (dev, (__le32 *) &event[1]);
624                 break;
625         // case USB_CDC_NOTIFY_RESPONSE_AVAILABLE:      /* RNDIS; or unsolicited */
626         default:
627                 deverr (dev, "CDC: unexpected notification %02x!",
628                                  event->bNotificationType);
629                 break;
630         }
631 }
632
633 static u8 nibble (unsigned char c)
634 {
635         if (likely (isdigit (c)))
636                 return c - '0';
637         c = toupper (c);
638         if (likely (isxdigit (c)))
639                 return 10 + c - 'A';
640         return 0;
641 }
642
643 static inline int
644 get_ethernet_addr (struct usbnet *dev, struct usb_cdc_ether_desc *e)
645 {
646         int             tmp, i;
647         unsigned char   buf [13];
648
649         tmp = usb_string (dev->udev, e->iMACAddress, buf, sizeof buf);
650         if (tmp != 12) {
651                 dev_dbg (&dev->udev->dev,
652                         "bad MAC string %d fetch, %d\n", e->iMACAddress, tmp);
653                 if (tmp >= 0)
654                         tmp = -EINVAL;
655                 return tmp;
656         }
657         for (i = tmp = 0; i < 6; i++, tmp += 2)
658                 dev->net->dev_addr [i] =
659                          (nibble (buf [tmp]) << 4) + nibble (buf [tmp + 1]);
660         return 0;
661 }
662
663 static int cdc_bind (struct usbnet *dev, struct usb_interface *intf)
664 {
665         int                             status;
666         struct cdc_state                *info = (void *) &dev->data;
667
668         status = generic_cdc_bind (dev, intf);
669         if (status < 0)
670                 return status;
671
672         status = get_ethernet_addr (dev, info->ether);
673         if (status < 0) {
674                 usb_set_intfdata(info->data, NULL);
675                 usb_driver_release_interface (&usbnet_driver, info->data);
676                 return status;
677         }
678
679         /* FIXME cdc-ether has some multicast code too, though it complains
680          * in routine cases.  info->ether describes the multicast support.
681          */
682         return 0;
683 }
684
685 static const struct driver_info cdc_info = {
686         .description =  "CDC Ethernet Device",
687         .flags =        FLAG_ETHER,
688         // .check_connect = cdc_check_connect,
689         .bind =         cdc_bind,
690         .unbind =       cdc_unbind,
691         .status =       cdc_status,
692 };
693
694 #endif  /* CONFIG_USB_CDCETHER */
695
696
697 \f
698 #ifdef CONFIG_USB_GENESYS
699 #define HAVE_HARDWARE
700
701 /*-------------------------------------------------------------------------
702  *
703  * GeneSys GL620USB-A (www.genesyslogic.com.tw)
704  *
705  * ... should partially interop with the Win32 driver for this hardware
706  * The GeneSys docs imply there's some NDIS issue motivating this framing.
707  *
708  * Some info from GeneSys:
709  *  - GL620USB-A is full duplex; GL620USB is only half duplex for bulk.
710  *    (Some cables, like the BAFO-100c, use the half duplex version.)
711  *  - For the full duplex model, the low bit of the version code says
712  *    which side is which ("left/right").
713  *  - For the half duplex type, a control/interrupt handshake settles
714  *    the transfer direction.  (That's disabled here, partially coded.)
715  *    A control URB would block until other side writes an interrupt.
716  *
717  * Original code from Jiun-Jie Huang <huangjj@genesyslogic.com.tw>
718  * and merged into "usbnet" by Stanislav Brabec <utx@penguin.cz>.
719  *
720  *-------------------------------------------------------------------------*/
721
722 // control msg write command
723 #define GENELINK_CONNECT_WRITE                  0xF0
724 // interrupt pipe index
725 #define GENELINK_INTERRUPT_PIPE                 0x03
726 // interrupt read buffer size
727 #define INTERRUPT_BUFSIZE                       0x08
728 // interrupt pipe interval value
729 #define GENELINK_INTERRUPT_INTERVAL             0x10
730 // max transmit packet number per transmit
731 #define GL_MAX_TRANSMIT_PACKETS                 32
732 // max packet length
733 #define GL_MAX_PACKET_LEN                       1514
734 // max receive buffer size 
735 #define GL_RCV_BUF_SIZE         \
736         (((GL_MAX_PACKET_LEN + 4) * GL_MAX_TRANSMIT_PACKETS) + 4)
737
738 struct gl_packet {
739         u32             packet_length;
740         char            packet_data [1];
741 };
742
743 struct gl_header {
744         u32                     packet_count;
745         struct gl_packet        packets;
746 };
747
748 #ifdef  GENELINK_ACK
749
750 // FIXME:  this code is incomplete, not debugged; it doesn't
751 // handle interrupts correctly.  interrupts should be generic
752 // code like all other device I/O, anyway.
753
754 struct gl_priv { 
755         struct urb      *irq_urb;
756         char            irq_buf [INTERRUPT_BUFSIZE];
757 };
758
759 static inline int gl_control_write (struct usbnet *dev, u8 request, u16 value)
760 {
761         int retval;
762
763         retval = usb_control_msg (dev->udev,
764                       usb_sndctrlpipe (dev->udev, 0),
765                       request,
766                       USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
767                       value, 
768                       0,                        // index
769                       0,                        // data buffer
770                       0,                        // size
771                       CONTROL_TIMEOUT_MS);
772         return retval;
773 }
774
775 static void gl_interrupt_complete (struct urb *urb, struct pt_regs *regs)
776 {
777         int status = urb->status;
778         
779         switch (status) {
780         case 0:
781                 /* success */
782                 break;
783         case -ECONNRESET:
784         case -ENOENT:
785         case -ESHUTDOWN:
786                 /* this urb is terminated, clean up */
787                 dbg("%s - urb shutting down with status: %d",
788                                 __FUNCTION__, status);
789                 return;
790         default:
791                 dbg("%s - nonzero urb status received: %d",
792                                 __FUNCTION__, urb->status);
793         }
794
795         status = usb_submit_urb (urb, GFP_ATOMIC);
796         if (status)
797                 err ("%s - usb_submit_urb failed with result %d",
798                      __FUNCTION__, status);
799 }
800
801 static int gl_interrupt_read (struct usbnet *dev)
802 {
803         struct gl_priv  *priv = dev->priv_data;
804         int             retval;
805
806         // issue usb interrupt read
807         if (priv && priv->irq_urb) {
808                 // submit urb
809                 if ((retval = usb_submit_urb (priv->irq_urb, GFP_KERNEL)) != 0)
810                         dbg ("gl_interrupt_read: submit fail - %X...", retval);
811                 else
812                         dbg ("gl_interrupt_read: submit success...");
813         }
814
815         return 0;
816 }
817
818 // check whether another side is connected
819 static int genelink_check_connect (struct usbnet *dev)
820 {
821         int                     retval;
822
823         dbg ("genelink_check_connect...");
824
825         // detect whether another side is connected
826         if ((retval = gl_control_write (dev, GENELINK_CONNECT_WRITE, 0)) != 0) {
827                 dbg ("%s: genelink_check_connect write fail - %X",
828                         dev->net->name, retval);
829                 return retval;
830         }
831
832         // usb interrupt read to ack another side 
833         if ((retval = gl_interrupt_read (dev)) != 0) {
834                 dbg ("%s: genelink_check_connect read fail - %X",
835                         dev->net->name, retval);
836                 return retval;
837         }
838
839         dbg ("%s: genelink_check_connect read success", dev->net->name);
840         return 0;
841 }
842
843 // allocate and initialize the private data for genelink
844 static int genelink_init (struct usbnet *dev)
845 {
846         struct gl_priv *priv;
847
848         // allocate the private data structure
849         if ((priv = kmalloc (sizeof *priv, GFP_KERNEL)) == 0) {
850                 dbg ("%s: cannot allocate private data per device",
851                         dev->net->name);
852                 return -ENOMEM;
853         }
854
855         // allocate irq urb
856         if ((priv->irq_urb = usb_alloc_urb (0, GFP_KERNEL)) == 0) {
857                 dbg ("%s: cannot allocate private irq urb per device",
858                         dev->net->name);
859                 kfree (priv);
860                 return -ENOMEM;
861         }
862
863         // fill irq urb
864         usb_fill_int_urb (priv->irq_urb, dev->udev,
865                 usb_rcvintpipe (dev->udev, GENELINK_INTERRUPT_PIPE),
866                 priv->irq_buf, INTERRUPT_BUFSIZE,
867                 gl_interrupt_complete, 0,
868                 GENELINK_INTERRUPT_INTERVAL);
869
870         // set private data pointer
871         dev->priv_data = priv;
872
873         return 0;
874 }
875
876 // release the private data
877 static int genelink_free (struct usbnet *dev)
878 {
879         struct gl_priv  *priv = dev->priv_data;
880
881         if (!priv) 
882                 return 0;
883
884 // FIXME:  can't cancel here; it's synchronous, and
885 // should have happened earlier in any case (interrupt
886 // handling needs to be generic)
887
888         // cancel irq urb first
889         usb_kill_urb (priv->irq_urb);
890
891         // free irq urb
892         usb_free_urb (priv->irq_urb);
893
894         // free the private data structure
895         kfree (priv);
896
897         return 0;
898 }
899
900 #endif
901
902 static int genelink_rx_fixup (struct usbnet *dev, struct sk_buff *skb)
903 {
904         struct gl_header        *header;
905         struct gl_packet        *packet;
906         struct sk_buff          *gl_skb;
907         u32                     size;
908
909         header = (struct gl_header *) skb->data;
910
911         // get the packet count of the received skb
912         le32_to_cpus (&header->packet_count);
913         if ((header->packet_count > GL_MAX_TRANSMIT_PACKETS)
914                         || (header->packet_count < 0)) {
915                 dbg ("genelink: invalid received packet count %d",
916                         header->packet_count);
917                 return 0;
918         }
919
920         // set the current packet pointer to the first packet
921         packet = &header->packets;
922
923         // decrement the length for the packet count size 4 bytes
924         skb_pull (skb, 4);
925
926         while (header->packet_count > 1) {
927                 // get the packet length
928                 size = packet->packet_length;
929
930                 // this may be a broken packet
931                 if (size > GL_MAX_PACKET_LEN) {
932                         dbg ("genelink: invalid rx length %d", size);
933                         return 0;
934                 }
935
936                 // allocate the skb for the individual packet
937                 gl_skb = alloc_skb (size, GFP_ATOMIC);
938                 if (gl_skb) {
939
940                         // copy the packet data to the new skb
941                         memcpy(skb_put(gl_skb, size), packet->packet_data, size);
942                         usbnet_skb_return (dev, gl_skb);
943                 }
944
945                 // advance to the next packet
946                 packet = (struct gl_packet *)
947                         &packet->packet_data [size];
948                 header->packet_count--;
949
950                 // shift the data pointer to the next gl_packet
951                 skb_pull (skb, size + 4);
952         }
953
954         // skip the packet length field 4 bytes
955         skb_pull (skb, 4);
956
957         if (skb->len > GL_MAX_PACKET_LEN) {
958                 dbg ("genelink: invalid rx length %d", skb->len);
959                 return 0;
960         }
961         return 1;
962 }
963
964 static struct sk_buff *
965 genelink_tx_fixup (struct usbnet *dev, struct sk_buff *skb, unsigned flags)
966 {
967         int     padlen;
968         int     length = skb->len;
969         int     headroom = skb_headroom (skb);
970         int     tailroom = skb_tailroom (skb);
971         u32     *packet_count;
972         u32     *packet_len;
973
974         // FIXME:  magic numbers, bleech
975         padlen = ((skb->len + (4 + 4*1)) % 64) ? 0 : 1;
976
977         if ((!skb_cloned (skb))
978                         && ((headroom + tailroom) >= (padlen + (4 + 4*1)))) {
979                 if ((headroom < (4 + 4*1)) || (tailroom < padlen)) {
980                         skb->data = memmove (skb->head + (4 + 4*1),
981                                              skb->data, skb->len);
982                         skb->tail = skb->data + skb->len;
983                 }
984         } else {
985                 struct sk_buff  *skb2;
986                 skb2 = skb_copy_expand (skb, (4 + 4*1) , padlen, flags);
987                 dev_kfree_skb_any (skb);
988                 skb = skb2;
989                 if (!skb)
990                         return NULL;
991         }
992
993         // attach the packet count to the header
994         packet_count = (u32 *) skb_push (skb, (4 + 4*1));
995         packet_len = packet_count + 1;
996
997         // FIXME little endian?
998         *packet_count = 1;
999         *packet_len = length;
1000
1001         // add padding byte
1002         if ((skb->len % dev->maxpacket) == 0)
1003                 skb_put (skb, 1);
1004
1005         return skb;
1006 }
1007
1008 static int genelink_bind (struct usbnet *dev, struct usb_interface *intf)
1009 {
1010         dev->hard_mtu = GL_RCV_BUF_SIZE;
1011         dev->net->hard_header_len += 4;
1012         return 0;
1013 }
1014
1015 static const struct driver_info genelink_info = {
1016         .description =  "Genesys GeneLink",
1017         .flags =        FLAG_FRAMING_GL | FLAG_NO_SETINT,
1018         .bind =         genelink_bind,
1019         .rx_fixup =     genelink_rx_fixup,
1020         .tx_fixup =     genelink_tx_fixup,
1021
1022         .in = 1, .out = 2,
1023
1024 #ifdef  GENELINK_ACK
1025         .check_connect =genelink_check_connect,
1026 #endif
1027 };
1028
1029 #endif /* CONFIG_USB_GENESYS */
1030
1031
1032 \f
1033 #ifdef  CONFIG_USB_NET1080
1034 #define HAVE_HARDWARE
1035
1036 /*-------------------------------------------------------------------------
1037  *
1038  * Netchip 1080 driver ... http://www.netchip.com
1039  * Used in LapLink cables
1040  *
1041  *-------------------------------------------------------------------------*/
1042
1043 #define frame_errors    data[1]
1044
1045 /*
1046  * NetChip framing of ethernet packets, supporting additional error
1047  * checks for links that may drop bulk packets from inside messages.
1048  * Odd USB length == always short read for last usb packet.
1049  *      - nc_header
1050  *      - Ethernet header (14 bytes)
1051  *      - payload
1052  *      - (optional padding byte, if needed so length becomes odd)
1053  *      - nc_trailer
1054  *
1055  * This framing is to be avoided for non-NetChip devices.
1056  */
1057
1058 struct nc_header {              // packed:
1059         __le16  hdr_len;                // sizeof nc_header (LE, all)
1060         __le16  packet_len;             // payload size (including ethhdr)
1061         __le16  packet_id;              // detects dropped packets
1062 #define MIN_HEADER      6
1063
1064         // all else is optional, and must start with:
1065         // u16  vendorId;               // from usb-if
1066         // u16  productId;
1067 } __attribute__((__packed__));
1068
1069 #define PAD_BYTE        ((unsigned char)0xAC)
1070
1071 struct nc_trailer {
1072         __le16  packet_id;
1073 } __attribute__((__packed__));
1074
1075 // packets may use FLAG_FRAMING_NC and optional pad
1076 #define FRAMED_SIZE(mtu) (sizeof (struct nc_header) \
1077                                 + sizeof (struct ethhdr) \
1078                                 + (mtu) \
1079                                 + 1 \
1080                                 + sizeof (struct nc_trailer))
1081
1082 #define MIN_FRAMED      FRAMED_SIZE(0)
1083
1084 /* packets _could_ be up to 64KB... */
1085 #define NC_MAX_PACKET   32767
1086
1087
1088 /*
1089  * Zero means no timeout; else, how long a 64 byte bulk packet may be queued
1090  * before the hardware drops it.  If that's done, the driver will need to
1091  * frame network packets to guard against the dropped USB packets.  The win32
1092  * driver sets this for both sides of the link.
1093  */
1094 #define NC_READ_TTL_MS  ((u8)255)       // ms
1095
1096 /*
1097  * We ignore most registers and EEPROM contents.
1098  */
1099 #define REG_USBCTL      ((u8)0x04)
1100 #define REG_TTL         ((u8)0x10)
1101 #define REG_STATUS      ((u8)0x11)
1102
1103 /*
1104  * Vendor specific requests to read/write data
1105  */
1106 #define REQUEST_REGISTER        ((u8)0x10)
1107 #define REQUEST_EEPROM          ((u8)0x11)
1108
1109 static int
1110 nc_vendor_read (struct usbnet *dev, u8 req, u8 regnum, u16 *retval_ptr)
1111 {
1112         int status = usb_control_msg (dev->udev,
1113                 usb_rcvctrlpipe (dev->udev, 0),
1114                 req,
1115                 USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
1116                 0, regnum,
1117                 retval_ptr, sizeof *retval_ptr,
1118                 CONTROL_TIMEOUT_MS);
1119         if (status > 0)
1120                 status = 0;
1121         if (!status)
1122                 le16_to_cpus (retval_ptr);
1123         return status;
1124 }
1125
1126 static inline int
1127 nc_register_read (struct usbnet *dev, u8 regnum, u16 *retval_ptr)
1128 {
1129         return nc_vendor_read (dev, REQUEST_REGISTER, regnum, retval_ptr);
1130 }
1131
1132 // no retval ... can become async, usable in_interrupt()
1133 static void
1134 nc_vendor_write (struct usbnet *dev, u8 req, u8 regnum, u16 value)
1135 {
1136         usb_control_msg (dev->udev,
1137                 usb_sndctrlpipe (dev->udev, 0),
1138                 req,
1139                 USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
1140                 value, regnum,
1141                 NULL, 0,                        // data is in setup packet
1142                 CONTROL_TIMEOUT_MS);
1143 }
1144
1145 static inline void
1146 nc_register_write (struct usbnet *dev, u8 regnum, u16 value)
1147 {
1148         nc_vendor_write (dev, REQUEST_REGISTER, regnum, value);
1149 }
1150
1151
1152 #if 0
1153 static void nc_dump_registers (struct usbnet *dev)
1154 {
1155         u8      reg;
1156         u16     *vp = kmalloc (sizeof (u16));
1157
1158         if (!vp) {
1159                 dbg ("no memory?");
1160                 return;
1161         }
1162
1163         dbg ("%s registers:", dev->net->name);
1164         for (reg = 0; reg < 0x20; reg++) {
1165                 int retval;
1166
1167                 // reading some registers is trouble
1168                 if (reg >= 0x08 && reg <= 0xf)
1169                         continue;
1170                 if (reg >= 0x12 && reg <= 0x1e)
1171                         continue;
1172
1173                 retval = nc_register_read (dev, reg, vp);
1174                 if (retval < 0)
1175                         dbg ("%s reg [0x%x] ==> error %d",
1176                                 dev->net->name, reg, retval);
1177                 else
1178                         dbg ("%s reg [0x%x] = 0x%x",
1179                                 dev->net->name, reg, *vp);
1180         }
1181         kfree (vp);
1182 }
1183 #endif
1184
1185
1186 /*-------------------------------------------------------------------------*/
1187
1188 /*
1189  * Control register
1190  */
1191
1192 #define USBCTL_WRITABLE_MASK    0x1f0f
1193 // bits 15-13 reserved, r/o
1194 #define USBCTL_ENABLE_LANG      (1 << 12)
1195 #define USBCTL_ENABLE_MFGR      (1 << 11)
1196 #define USBCTL_ENABLE_PROD      (1 << 10)
1197 #define USBCTL_ENABLE_SERIAL    (1 << 9)
1198 #define USBCTL_ENABLE_DEFAULTS  (1 << 8)
1199 // bits 7-4 reserved, r/o
1200 #define USBCTL_FLUSH_OTHER      (1 << 3)
1201 #define USBCTL_FLUSH_THIS       (1 << 2)
1202 #define USBCTL_DISCONN_OTHER    (1 << 1)
1203 #define USBCTL_DISCONN_THIS     (1 << 0)
1204
1205 static inline void nc_dump_usbctl (struct usbnet *dev, u16 usbctl)
1206 {
1207         if (!netif_msg_link (dev))
1208                 return;
1209         devdbg (dev, "net1080 %s-%s usbctl 0x%x:%s%s%s%s%s;"
1210                         " this%s%s;"
1211                         " other%s%s; r/o 0x%x",
1212                 dev->udev->bus->bus_name, dev->udev->devpath,
1213                 usbctl,
1214                 (usbctl & USBCTL_ENABLE_LANG) ? " lang" : "",
1215                 (usbctl & USBCTL_ENABLE_MFGR) ? " mfgr" : "",
1216                 (usbctl & USBCTL_ENABLE_PROD) ? " prod" : "",
1217                 (usbctl & USBCTL_ENABLE_SERIAL) ? " serial" : "",
1218                 (usbctl & USBCTL_ENABLE_DEFAULTS) ? " defaults" : "",
1219
1220                 (usbctl & USBCTL_FLUSH_OTHER) ? " FLUSH" : "",
1221                 (usbctl & USBCTL_DISCONN_OTHER) ? " DIS" : "",
1222                 (usbctl & USBCTL_FLUSH_THIS) ? " FLUSH" : "",
1223                 (usbctl & USBCTL_DISCONN_THIS) ? " DIS" : "",
1224                 usbctl & ~USBCTL_WRITABLE_MASK
1225                 );
1226 }
1227
1228 /*-------------------------------------------------------------------------*/
1229
1230 /*
1231  * Status register
1232  */
1233
1234 #define STATUS_PORT_A           (1 << 15)
1235
1236 #define STATUS_CONN_OTHER       (1 << 14)
1237 #define STATUS_SUSPEND_OTHER    (1 << 13)
1238 #define STATUS_MAILBOX_OTHER    (1 << 12)
1239 #define STATUS_PACKETS_OTHER(n) (((n) >> 8) && 0x03)
1240
1241 #define STATUS_CONN_THIS        (1 << 6)
1242 #define STATUS_SUSPEND_THIS     (1 << 5)
1243 #define STATUS_MAILBOX_THIS     (1 << 4)
1244 #define STATUS_PACKETS_THIS(n)  (((n) >> 0) && 0x03)
1245
1246 #define STATUS_UNSPEC_MASK      0x0c8c
1247 #define STATUS_NOISE_MASK       ((u16)~(0x0303|STATUS_UNSPEC_MASK))
1248
1249
1250 static inline void nc_dump_status (struct usbnet *dev, u16 status)
1251 {
1252         if (!netif_msg_link (dev))
1253                 return;
1254         devdbg (dev, "net1080 %s-%s status 0x%x:"
1255                         " this (%c) PKT=%d%s%s%s;"
1256                         " other PKT=%d%s%s%s; unspec 0x%x",
1257                 dev->udev->bus->bus_name, dev->udev->devpath,
1258                 status,
1259
1260                 // XXX the packet counts don't seem right
1261                 // (1 at reset, not 0); maybe UNSPEC too
1262
1263                 (status & STATUS_PORT_A) ? 'A' : 'B',
1264                 STATUS_PACKETS_THIS (status),
1265                 (status & STATUS_CONN_THIS) ? " CON" : "",
1266                 (status & STATUS_SUSPEND_THIS) ? " SUS" : "",
1267                 (status & STATUS_MAILBOX_THIS) ? " MBOX" : "",
1268
1269                 STATUS_PACKETS_OTHER (status),
1270                 (status & STATUS_CONN_OTHER) ? " CON" : "",
1271                 (status & STATUS_SUSPEND_OTHER) ? " SUS" : "",
1272                 (status & STATUS_MAILBOX_OTHER) ? " MBOX" : "",
1273
1274                 status & STATUS_UNSPEC_MASK
1275                 );
1276 }
1277
1278 /*-------------------------------------------------------------------------*/
1279
1280 /*
1281  * TTL register
1282  */
1283
1284 #define TTL_THIS(ttl)   (0x00ff & ttl)
1285 #define TTL_OTHER(ttl)  (0x00ff & (ttl >> 8))
1286 #define MK_TTL(this,other)      ((u16)(((other)<<8)|(0x00ff&(this))))
1287
1288 static inline void nc_dump_ttl (struct usbnet *dev, u16 ttl)
1289 {
1290         if (netif_msg_link (dev))
1291                 devdbg (dev, "net1080 %s-%s ttl 0x%x this = %d, other = %d",
1292                         dev->udev->bus->bus_name, dev->udev->devpath,
1293                         ttl, TTL_THIS (ttl), TTL_OTHER (ttl));
1294 }
1295
1296 /*-------------------------------------------------------------------------*/
1297
1298 static int net1080_reset (struct usbnet *dev)
1299 {
1300         u16             usbctl, status, ttl;
1301         u16             *vp = kmalloc (sizeof (u16), GFP_KERNEL);
1302         int             retval;
1303
1304         if (!vp)
1305                 return -ENOMEM;
1306
1307         // nc_dump_registers (dev);
1308
1309         if ((retval = nc_register_read (dev, REG_STATUS, vp)) < 0) {
1310                 dbg ("can't read %s-%s status: %d",
1311                         dev->udev->bus->bus_name, dev->udev->devpath, retval);
1312                 goto done;
1313         }
1314         status = *vp;
1315         nc_dump_status (dev, status);
1316
1317         if ((retval = nc_register_read (dev, REG_USBCTL, vp)) < 0) {
1318                 dbg ("can't read USBCTL, %d", retval);
1319                 goto done;
1320         }
1321         usbctl = *vp;
1322         nc_dump_usbctl (dev, usbctl);
1323
1324         nc_register_write (dev, REG_USBCTL,
1325                         USBCTL_FLUSH_THIS | USBCTL_FLUSH_OTHER);
1326
1327         if ((retval = nc_register_read (dev, REG_TTL, vp)) < 0) {
1328                 dbg ("can't read TTL, %d", retval);
1329                 goto done;
1330         }
1331         ttl = *vp;
1332         // nc_dump_ttl (dev, ttl);
1333
1334         nc_register_write (dev, REG_TTL,
1335                         MK_TTL (NC_READ_TTL_MS, TTL_OTHER (ttl)) );
1336         dbg ("%s: assigned TTL, %d ms", dev->net->name, NC_READ_TTL_MS);
1337
1338         if (netif_msg_link (dev))
1339                 devinfo (dev, "port %c, peer %sconnected",
1340                         (status & STATUS_PORT_A) ? 'A' : 'B',
1341                         (status & STATUS_CONN_OTHER) ? "" : "dis"
1342                         );
1343         retval = 0;
1344
1345 done:
1346         kfree (vp);
1347         return retval;
1348 }
1349
1350 static int net1080_check_connect (struct usbnet *dev)
1351 {
1352         int                     retval;
1353         u16                     status;
1354         u16                     *vp = kmalloc (sizeof (u16), GFP_KERNEL);
1355
1356         if (!vp)
1357                 return -ENOMEM;
1358         retval = nc_register_read (dev, REG_STATUS, vp);
1359         status = *vp;
1360         kfree (vp);
1361         if (retval != 0) {
1362                 dbg ("%s net1080_check_conn read - %d", dev->net->name, retval);
1363                 return retval;
1364         }
1365         if ((status & STATUS_CONN_OTHER) != STATUS_CONN_OTHER)
1366                 return -ENOLINK;
1367         return 0;
1368 }
1369
1370 static void nc_flush_complete (struct urb *urb, struct pt_regs *regs)
1371 {
1372         kfree (urb->context);
1373         usb_free_urb(urb);
1374 }
1375
1376 static void nc_ensure_sync (struct usbnet *dev)
1377 {
1378         dev->frame_errors++;
1379         if (dev->frame_errors > 5) {
1380                 struct urb              *urb;
1381                 struct usb_ctrlrequest  *req;
1382                 int                     status;
1383
1384                 /* Send a flush */
1385                 urb = usb_alloc_urb (0, SLAB_ATOMIC);
1386                 if (!urb)
1387                         return;
1388
1389                 req = kmalloc (sizeof *req, GFP_ATOMIC);
1390                 if (!req) {
1391                         usb_free_urb (urb);
1392                         return;
1393                 }
1394
1395                 req->bRequestType = USB_DIR_OUT
1396                         | USB_TYPE_VENDOR
1397                         | USB_RECIP_DEVICE;
1398                 req->bRequest = REQUEST_REGISTER;
1399                 req->wValue = cpu_to_le16 (USBCTL_FLUSH_THIS
1400                                 | USBCTL_FLUSH_OTHER);
1401                 req->wIndex = cpu_to_le16 (REG_USBCTL);
1402                 req->wLength = cpu_to_le16 (0);
1403
1404                 /* queue an async control request, we don't need
1405                  * to do anything when it finishes except clean up.
1406                  */
1407                 usb_fill_control_urb (urb, dev->udev,
1408                         usb_sndctrlpipe (dev->udev, 0),
1409                         (unsigned char *) req,
1410                         NULL, 0,
1411                         nc_flush_complete, req);
1412                 status = usb_submit_urb (urb, GFP_ATOMIC);
1413                 if (status) {
1414                         kfree (req);
1415                         usb_free_urb (urb);
1416                         return;
1417                 }
1418
1419                 if (netif_msg_rx_err (dev))
1420                         devdbg (dev, "flush net1080; too many framing errors");
1421                 dev->frame_errors = 0;
1422         }
1423 }
1424
1425 static int net1080_rx_fixup (struct usbnet *dev, struct sk_buff *skb)
1426 {
1427         struct nc_header        *header;
1428         struct net_device       *net = dev->net;
1429         struct nc_trailer       *trailer;
1430         u16                     hdr_len, packet_len;
1431
1432         if (!(skb->len & 0x01)) {
1433                 dev->stats.rx_frame_errors++;
1434                 dbg ("rx framesize %d range %d..%d mtu %d", skb->len,
1435                         net->hard_header_len, dev->hard_mtu, net->mtu);
1436                 nc_ensure_sync (dev);
1437                 return 0;
1438         }
1439
1440         header = (struct nc_header *) skb->data;
1441         hdr_len = le16_to_cpup (&header->hdr_len);
1442         packet_len = le16_to_cpup (&header->packet_len);
1443         if (FRAMED_SIZE (packet_len) > NC_MAX_PACKET) {
1444                 dev->stats.rx_frame_errors++;
1445                 dbg ("packet too big, %d", packet_len);
1446                 nc_ensure_sync (dev);
1447                 return 0;
1448         } else if (hdr_len < MIN_HEADER) {
1449                 dev->stats.rx_frame_errors++;
1450                 dbg ("header too short, %d", hdr_len);
1451                 nc_ensure_sync (dev);
1452                 return 0;
1453         } else if (hdr_len > MIN_HEADER) {
1454                 // out of band data for us?
1455                 dbg ("header OOB, %d bytes", hdr_len - MIN_HEADER);
1456                 nc_ensure_sync (dev);
1457                 // switch (vendor/product ids) { ... }
1458         }
1459         skb_pull (skb, hdr_len);
1460
1461         trailer = (struct nc_trailer *)
1462                 (skb->data + skb->len - sizeof *trailer);
1463         skb_trim (skb, skb->len - sizeof *trailer);
1464
1465         if ((packet_len & 0x01) == 0) {
1466                 if (skb->data [packet_len] != PAD_BYTE) {
1467                         dev->stats.rx_frame_errors++;
1468                         dbg ("bad pad");
1469                         return 0;
1470                 }
1471                 skb_trim (skb, skb->len - 1);
1472         }
1473         if (skb->len != packet_len) {
1474                 dev->stats.rx_frame_errors++;
1475                 dbg ("bad packet len %d (expected %d)",
1476                         skb->len, packet_len);
1477                 nc_ensure_sync (dev);
1478                 return 0;
1479         }
1480         if (header->packet_id != get_unaligned (&trailer->packet_id)) {
1481                 dev->stats.rx_fifo_errors++;
1482                 dbg ("(2+ dropped) rx packet_id mismatch 0x%x 0x%x",
1483                         le16_to_cpu (header->packet_id),
1484                         le16_to_cpu (trailer->packet_id));
1485                 return 0;
1486         }
1487 #if 0
1488         devdbg (dev, "frame <rx h %d p %d id %d", header->hdr_len,
1489                 header->packet_len, header->packet_id);
1490 #endif
1491         dev->frame_errors = 0;
1492         return 1;
1493 }
1494
1495 static struct sk_buff *
1496 net1080_tx_fixup (struct usbnet *dev, struct sk_buff *skb, unsigned flags)
1497 {
1498         int                     padlen;
1499         struct sk_buff          *skb2;
1500
1501         padlen = ((skb->len + sizeof (struct nc_header)
1502                         + sizeof (struct nc_trailer)) & 0x01) ? 0 : 1;
1503         if (!skb_cloned (skb)) {
1504                 int     headroom = skb_headroom (skb);
1505                 int     tailroom = skb_tailroom (skb);
1506
1507                 if ((padlen + sizeof (struct nc_trailer)) <= tailroom
1508                             && sizeof (struct nc_header) <= headroom)
1509                         /* There's enough head and tail room */
1510                         return skb;
1511
1512                 if ((sizeof (struct nc_header) + padlen
1513                                         + sizeof (struct nc_trailer)) <
1514                                 (headroom + tailroom)) {
1515                         /* There's enough total room, so just readjust */
1516                         skb->data = memmove (skb->head
1517                                                 + sizeof (struct nc_header),
1518                                             skb->data, skb->len);
1519                         skb->tail = skb->data + skb->len;
1520                         return skb;
1521                 }
1522         }
1523
1524         /* Create a new skb to use with the correct size */
1525         skb2 = skb_copy_expand (skb,
1526                                 sizeof (struct nc_header),
1527                                 sizeof (struct nc_trailer) + padlen,
1528                                 flags);
1529         dev_kfree_skb_any (skb);
1530         return skb2;
1531 }
1532
1533 static int net1080_bind (struct usbnet *dev, struct usb_interface *intf)
1534 {
1535         unsigned        extra = sizeof (struct nc_header)
1536                                 + 1
1537                                 + sizeof (struct nc_trailer);
1538
1539         dev->net->hard_header_len += extra;
1540         dev->hard_mtu = NC_MAX_PACKET;
1541         return 0;
1542 }
1543
1544 static const struct driver_info net1080_info = {
1545         .description =  "NetChip TurboCONNECT",
1546         .flags =        FLAG_FRAMING_NC,
1547         .bind =         net1080_bind,
1548         .reset =        net1080_reset,
1549         .check_connect = net1080_check_connect,
1550         .rx_fixup =     net1080_rx_fixup,
1551         .tx_fixup =     net1080_tx_fixup,
1552 };
1553
1554 #endif /* CONFIG_USB_NET1080 */
1555
1556
1557 \f
1558 #ifdef CONFIG_USB_PL2301
1559 #define HAVE_HARDWARE
1560
1561 /*-------------------------------------------------------------------------
1562  *
1563  * Prolific PL-2301/PL-2302 driver ... http://www.prolifictech.com
1564  *
1565  * The protocol and handshaking used here should be bug-compatible
1566  * with the Linux 2.2 "plusb" driver, by Deti Fliegl.
1567  *
1568  *-------------------------------------------------------------------------*/
1569
1570 /*
1571  * Bits 0-4 can be used for software handshaking; they're set from
1572  * one end, cleared from the other, "read" with the interrupt byte.
1573  */
1574 #define PL_S_EN         (1<<7)          /* (feature only) suspend enable */
1575 /* reserved bit -- rx ready (6) ? */
1576 #define PL_TX_READY     (1<<5)          /* (interrupt only) transmit ready */
1577 #define PL_RESET_OUT    (1<<4)          /* reset output pipe */
1578 #define PL_RESET_IN     (1<<3)          /* reset input pipe */
1579 #define PL_TX_C         (1<<2)          /* transmission complete */
1580 #define PL_TX_REQ       (1<<1)          /* transmission received */
1581 #define PL_PEER_E       (1<<0)          /* peer exists */
1582
1583 static inline int
1584 pl_vendor_req (struct usbnet *dev, u8 req, u8 val, u8 index)
1585 {
1586         return usb_control_msg (dev->udev,
1587                 usb_rcvctrlpipe (dev->udev, 0),
1588                 req,
1589                 USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
1590                 val, index,
1591                 NULL, 0,
1592                 CONTROL_TIMEOUT_MS);
1593 }
1594
1595 static inline int
1596 pl_clear_QuickLink_features (struct usbnet *dev, int val)
1597 {
1598         return pl_vendor_req (dev, 1, (u8) val, 0);
1599 }
1600
1601 static inline int
1602 pl_set_QuickLink_features (struct usbnet *dev, int val)
1603 {
1604         return pl_vendor_req (dev, 3, (u8) val, 0);
1605 }
1606
1607 /*-------------------------------------------------------------------------*/
1608
1609 static int pl_reset (struct usbnet *dev)
1610 {
1611         /* some units seem to need this reset, others reject it utterly.
1612          * FIXME be more like "naplink" or windows drivers.
1613          */
1614         (void) pl_set_QuickLink_features (dev,
1615                 PL_S_EN|PL_RESET_OUT|PL_RESET_IN|PL_PEER_E);
1616         return 0;
1617 }
1618
1619 static const struct driver_info prolific_info = {
1620         .description =  "Prolific PL-2301/PL-2302",
1621         .flags =        FLAG_NO_SETINT,
1622                 /* some PL-2302 versions seem to fail usb_set_interface() */
1623         .reset =        pl_reset,
1624 };
1625
1626 #endif /* CONFIG_USB_PL2301 */
1627
1628 \f
1629 #ifdef CONFIG_USB_ZAURUS
1630 #define HAVE_HARDWARE
1631
1632 #include <linux/crc32.h>
1633
1634 /*-------------------------------------------------------------------------
1635  *
1636  * Zaurus is also a SA-1110 based PDA, but one using a different driver
1637  * (and framing) for its USB slave/gadget controller than the case above.
1638  *
1639  * For the current version of that driver, the main way that framing is
1640  * nonstandard (also from perspective of the CDC ethernet model!) is a
1641  * crc32, added to help detect when some sa1100 usb-to-memory DMA errata
1642  * haven't been fully worked around.  Also, all Zaurii use the same
1643  * default Ethernet address.
1644  *
1645  * PXA based models use the same framing, and also can't implement
1646  * set_interface properly.
1647  *
1648  * All known Zaurii lie about their standards conformance.  Most lie by
1649  * saying they support CDC Ethernet.  Some lie and say they support CDC
1650  * MDLM (as if for access to cell phone modems).  Someone, please beat 
1651  * on Sharp (and other such vendors) for a while with a cluestick.
1652  *
1653  *-------------------------------------------------------------------------*/
1654
1655 static struct sk_buff *
1656 zaurus_tx_fixup (struct usbnet *dev, struct sk_buff *skb, unsigned flags)
1657 {
1658         int                     padlen;
1659         struct sk_buff          *skb2;
1660
1661         padlen = 2;
1662         if (!skb_cloned (skb)) {
1663                 int     tailroom = skb_tailroom (skb);
1664                 if ((padlen + 4) <= tailroom)
1665                         goto done;
1666         }
1667         skb2 = skb_copy_expand (skb, 0, 4 + padlen, flags);
1668         dev_kfree_skb_any (skb);
1669         skb = skb2;
1670         if (skb) {
1671                 u32             fcs;
1672 done:
1673                 fcs = crc32_le (~0, skb->data, skb->len);
1674                 fcs = ~fcs;
1675
1676                 *skb_put (skb, 1) = fcs       & 0xff;
1677                 *skb_put (skb, 1) = (fcs>> 8) & 0xff;
1678                 *skb_put (skb, 1) = (fcs>>16) & 0xff;
1679                 *skb_put (skb, 1) = (fcs>>24) & 0xff;
1680         }
1681         return skb;
1682 }
1683
1684 static int zaurus_bind (struct usbnet *dev, struct usb_interface *intf)
1685 {
1686         /* Belcarra's funky framing has other options; mostly
1687          * TRAILERS (!) with 4 bytes CRC, and maybe 2 pad bytes.
1688          */
1689         dev->net->hard_header_len += 6;
1690         return generic_cdc_bind(dev, intf);
1691 }
1692
1693 static const struct driver_info zaurus_sl5x00_info = {
1694         .description =  "Sharp Zaurus SL-5x00",
1695         .flags =        FLAG_FRAMING_Z,
1696         .check_connect = always_connected,
1697         .bind =         zaurus_bind,
1698         .unbind =       cdc_unbind,
1699         .tx_fixup =     zaurus_tx_fixup,
1700 };
1701 #define ZAURUS_STRONGARM_INFO   ((unsigned long)&zaurus_sl5x00_info)
1702
1703 static const struct driver_info zaurus_pxa_info = {
1704         .description =  "Sharp Zaurus, PXA-2xx based",
1705         .flags =        FLAG_FRAMING_Z,
1706         .check_connect = always_connected,
1707         .bind =         zaurus_bind,
1708         .unbind =       cdc_unbind,
1709         .tx_fixup =     zaurus_tx_fixup,
1710 };
1711 #define ZAURUS_PXA_INFO         ((unsigned long)&zaurus_pxa_info)
1712
1713 static const struct driver_info olympus_mxl_info = {
1714         .description =  "Olympus R1000",
1715         .flags =        FLAG_FRAMING_Z,
1716         .check_connect = always_connected,
1717         .bind =         zaurus_bind,
1718         .unbind =       cdc_unbind,
1719         .tx_fixup =     zaurus_tx_fixup,
1720 };
1721 #define OLYMPUS_MXL_INFO        ((unsigned long)&olympus_mxl_info)
1722
1723
1724 /* Some more recent products using Lineo/Belcarra code will wrongly claim
1725  * CDC MDLM conformance.  They aren't conformant:  data endpoints live
1726  * in the control interface, there's no data interface, and it's not used
1727  * to talk to a cell phone radio.  But at least we can detect these two
1728  * pseudo-classes, rather than growing this product list with entries for
1729  * each new nonconformant product (sigh).
1730  */
1731 static const u8 safe_guid[16] = {
1732         0x5d, 0x34, 0xcf, 0x66, 0x11, 0x18, 0x11, 0xd6,
1733         0xa2, 0x1a, 0x00, 0x01, 0x02, 0xca, 0x9a, 0x7f,
1734 };
1735 static const u8 blan_guid[16] = {
1736         0x74, 0xf0, 0x3d, 0xbd, 0x1e, 0xc1, 0x44, 0x70,
1737         0xa3, 0x67, 0x71, 0x34, 0xc9, 0xf5, 0x54, 0x37,
1738 };
1739
1740 static int blan_mdlm_bind (struct usbnet *dev, struct usb_interface *intf)
1741 {
1742         u8                              *buf = intf->cur_altsetting->extra;
1743         int                             len = intf->cur_altsetting->extralen;
1744         struct usb_cdc_mdlm_desc        *desc = NULL;
1745         struct usb_cdc_mdlm_detail_desc *detail = NULL;
1746
1747         while (len > 3) {
1748                 if (buf [1] != USB_DT_CS_INTERFACE)
1749                         goto next_desc;
1750
1751                 /* use bDescriptorSubType, and just verify that we get a
1752                  * "BLAN" (or "SAFE") descriptor.
1753                  */
1754                 switch (buf [2]) {
1755                 case USB_CDC_MDLM_TYPE:
1756                         if (desc) {
1757                                 dev_dbg (&intf->dev, "extra MDLM\n");
1758                                 goto bad_desc;
1759                         }
1760                         desc = (void *) buf;
1761                         if (desc->bLength != sizeof *desc) {
1762                                 dev_dbg (&intf->dev, "MDLM len %u\n",
1763                                         desc->bLength);
1764                                 goto bad_desc;
1765                         }
1766                         /* expect bcdVersion 1.0, ignore */
1767                         if (memcmp(&desc->bGUID, blan_guid, 16)
1768                                     && memcmp(&desc->bGUID, safe_guid, 16) ) {
1769                                 /* hey, this one might _really_ be MDLM! */
1770                                 dev_dbg (&intf->dev, "MDLM guid\n");
1771                                 goto bad_desc;
1772                         }
1773                         break;
1774                 case USB_CDC_MDLM_DETAIL_TYPE:
1775                         if (detail) {
1776                                 dev_dbg (&intf->dev, "extra MDLM detail\n");
1777                                 goto bad_desc;
1778                         }
1779                         detail = (void *) buf;
1780                         switch (detail->bGuidDescriptorType) {
1781                         case 0:                 /* "SAFE" */
1782                                 if (detail->bLength != (sizeof *detail + 2))
1783                                         goto bad_detail;
1784                                 break;
1785                         case 1:                 /* "BLAN" */
1786                                 if (detail->bLength != (sizeof *detail + 3))
1787                                         goto bad_detail;
1788                                 break;
1789                         default:
1790                                 goto bad_detail;
1791                         }
1792
1793                         /* assuming we either noticed BLAN already, or will
1794                          * find it soon, there are some data bytes here:
1795                          *  - bmNetworkCapabilities (unused)
1796                          *  - bmDataCapabilities (bits, see below)
1797                          *  - bPad (ignored, for PADAFTER -- BLAN-only)
1798                          * bits are:
1799                          *  - 0x01 -- Zaurus framing (add CRC)
1800                          *  - 0x02 -- PADBEFORE (CRC includes some padding)
1801                          *  - 0x04 -- PADAFTER (some padding after CRC)
1802                          *  - 0x08 -- "fermat" packet mangling (for hw bugs)
1803                          * the PADBEFORE appears not to matter; we interop
1804                          * with devices that use it and those that don't.
1805                          */
1806                         if ((detail->bDetailData[1] & ~02) != 0x01) {
1807                                 /* bmDataCapabilites == 0 would be fine too,
1808                                  * but framing is minidriver-coupled for now.
1809                                  */
1810 bad_detail:
1811                                 dev_dbg (&intf->dev,
1812                                                 "bad MDLM detail, %d %d %d\n",
1813                                                 detail->bLength,
1814                                                 detail->bDetailData[0],
1815                                                 detail->bDetailData[2]);
1816                                 goto bad_desc;
1817                         }
1818                         break;
1819                 }
1820 next_desc:
1821                 len -= buf [0]; /* bLength */
1822                 buf += buf [0];
1823         }
1824
1825         if (!desc || !detail) {
1826                 dev_dbg (&intf->dev, "missing cdc mdlm %s%sdescriptor\n",
1827                         desc ? "" : "func ",
1828                         detail ? "" : "detail ");
1829                 goto bad_desc;
1830         }
1831
1832         /* There's probably a CDC Ethernet descriptor there, but we can't
1833          * rely on the Ethernet address it provides since not all vendors
1834          * bother to make it unique.  Likewise there's no point in tracking
1835          * of the CDC event notifications.
1836          */
1837         return usbnet_get_endpoints (dev, intf);
1838
1839 bad_desc:
1840         dev_info (&dev->udev->dev, "unsupported MDLM descriptors\n");
1841         return -ENODEV;
1842 }
1843
1844 static const struct driver_info bogus_mdlm_info = {
1845         .description =  "pseudo-MDLM (BLAN) device",
1846         .flags =        FLAG_FRAMING_Z,
1847         .check_connect = always_connected,
1848         .tx_fixup =     zaurus_tx_fixup,
1849         .bind =         blan_mdlm_bind,
1850 };
1851
1852 #else
1853
1854 /* blacklist all those devices */
1855 #define ZAURUS_STRONGARM_INFO   0
1856 #define ZAURUS_PXA_INFO         0
1857 #define OLYMPUS_MXL_INFO        0
1858
1859 #endif
1860
1861 \f
1862 /*-------------------------------------------------------------------------
1863  *
1864  * Network Device Driver (peer link to "Host Device", from USB host)
1865  *
1866  *-------------------------------------------------------------------------*/
1867
1868 static int usbnet_change_mtu (struct net_device *net, int new_mtu)
1869 {
1870         struct usbnet   *dev = netdev_priv(net);
1871         int             ll_mtu = new_mtu + net->hard_header_len;
1872
1873         if (new_mtu <= 0 || ll_mtu > dev->hard_mtu)
1874                 return -EINVAL;
1875         // no second zero-length packet read wanted after mtu-sized packets
1876         if ((ll_mtu % dev->maxpacket) == 0)
1877                 return -EDOM;
1878         net->mtu = new_mtu;
1879         return 0;
1880 }
1881
1882 /*-------------------------------------------------------------------------*/
1883
1884 static struct net_device_stats *usbnet_get_stats (struct net_device *net)
1885 {
1886         struct usbnet   *dev = netdev_priv(net);
1887         return &dev->stats;
1888 }
1889
1890 /*-------------------------------------------------------------------------*/
1891
1892 /* some LK 2.4 HCDs oopsed if we freed or resubmitted urbs from
1893  * completion callbacks.  2.5 should have fixed those bugs...
1894  */
1895
1896 static void defer_bh(struct usbnet *dev, struct sk_buff *skb, struct sk_buff_head *list)
1897 {
1898         unsigned long           flags;
1899
1900         spin_lock_irqsave(&list->lock, flags);
1901         __skb_unlink(skb, list);
1902         spin_unlock(&list->lock);
1903         spin_lock(&dev->done.lock);
1904         __skb_queue_tail(&dev->done, skb);
1905         if (dev->done.qlen == 1)
1906                 tasklet_schedule(&dev->bh);
1907         spin_unlock_irqrestore(&dev->done.lock, flags);
1908 }
1909
1910 /* some work can't be done in tasklets, so we use keventd
1911  *
1912  * NOTE:  annoying asymmetry:  if it's active, schedule_work() fails,
1913  * but tasklet_schedule() doesn't.  hope the failure is rare.
1914  */
1915 void usbnet_defer_kevent (struct usbnet *dev, int work)
1916 {
1917         set_bit (work, &dev->flags);
1918         if (!schedule_work (&dev->kevent))
1919                 deverr (dev, "kevent %d may have been dropped", work);
1920         else
1921                 devdbg (dev, "kevent %d scheduled", work);
1922 }
1923 EXPORT_SYMBOL_GPL(usbnet_defer_kevent);
1924
1925 /*-------------------------------------------------------------------------*/
1926
1927 static void rx_complete (struct urb *urb, struct pt_regs *regs);
1928
1929 static void rx_submit (struct usbnet *dev, struct urb *urb, unsigned flags)
1930 {
1931         struct sk_buff          *skb;
1932         struct skb_data         *entry;
1933         int                     retval = 0;
1934         unsigned long           lockflags;
1935         size_t                  size = dev->rx_urb_size;
1936
1937         if ((skb = alloc_skb (size + NET_IP_ALIGN, flags)) == NULL) {
1938                 if (netif_msg_rx_err (dev))
1939                         devdbg (dev, "no rx skb");
1940                 usbnet_defer_kevent (dev, EVENT_RX_MEMORY);
1941                 usb_free_urb (urb);
1942                 return;
1943         }
1944         skb_reserve (skb, NET_IP_ALIGN);
1945
1946         entry = (struct skb_data *) skb->cb;
1947         entry->urb = urb;
1948         entry->dev = dev;
1949         entry->state = rx_start;
1950         entry->length = 0;
1951
1952         usb_fill_bulk_urb (urb, dev->udev, dev->in,
1953                 skb->data, size, rx_complete, skb);
1954
1955         spin_lock_irqsave (&dev->rxq.lock, lockflags);
1956
1957         if (netif_running (dev->net)
1958                         && netif_device_present (dev->net)
1959                         && !test_bit (EVENT_RX_HALT, &dev->flags)) {
1960                 switch (retval = usb_submit_urb (urb, GFP_ATOMIC)){ 
1961                 case -EPIPE:
1962                         usbnet_defer_kevent (dev, EVENT_RX_HALT);
1963                         break;
1964                 case -ENOMEM:
1965                         usbnet_defer_kevent (dev, EVENT_RX_MEMORY);
1966                         break;
1967                 case -ENODEV:
1968                         if (netif_msg_ifdown (dev))
1969                                 devdbg (dev, "device gone");
1970                         netif_device_detach (dev->net);
1971                         break;
1972                 default:
1973                         if (netif_msg_rx_err (dev))
1974                                 devdbg (dev, "rx submit, %d", retval);
1975                         tasklet_schedule (&dev->bh);
1976                         break;
1977                 case 0:
1978                         __skb_queue_tail (&dev->rxq, skb);
1979                 }
1980         } else {
1981                 if (netif_msg_ifdown (dev))
1982                         devdbg (dev, "rx: stopped");
1983                 retval = -ENOLINK;
1984         }
1985         spin_unlock_irqrestore (&dev->rxq.lock, lockflags);
1986         if (retval) {
1987                 dev_kfree_skb_any (skb);
1988                 usb_free_urb (urb);
1989         }
1990 }
1991
1992
1993 /*-------------------------------------------------------------------------*/
1994
1995 static inline void rx_process (struct usbnet *dev, struct sk_buff *skb)
1996 {
1997         if (dev->driver_info->rx_fixup
1998                         && !dev->driver_info->rx_fixup (dev, skb))
1999                 goto error;
2000         // else network stack removes extra byte if we forced a short packet
2001
2002         if (skb->len)
2003                 usbnet_skb_return (dev, skb);
2004         else {
2005                 if (netif_msg_rx_err (dev))
2006                         devdbg (dev, "drop");
2007 error:
2008                 dev->stats.rx_errors++;
2009                 skb_queue_tail (&dev->done, skb);
2010         }
2011 }
2012
2013 /*-------------------------------------------------------------------------*/
2014
2015 static void rx_complete (struct urb *urb, struct pt_regs *regs)
2016 {
2017         struct sk_buff          *skb = (struct sk_buff *) urb->context;
2018         struct skb_data         *entry = (struct skb_data *) skb->cb;
2019         struct usbnet           *dev = entry->dev;
2020         int                     urb_status = urb->status;
2021
2022         skb_put (skb, urb->actual_length);
2023         entry->state = rx_done;
2024         entry->urb = NULL;
2025
2026         switch (urb_status) {
2027             // success
2028             case 0:
2029                 if (skb->len < dev->net->hard_header_len) {
2030                         entry->state = rx_cleanup;
2031                         dev->stats.rx_errors++;
2032                         dev->stats.rx_length_errors++;
2033                         if (netif_msg_rx_err (dev))
2034                                 devdbg (dev, "rx length %d", skb->len);
2035                 }
2036                 break;
2037
2038             // stalls need manual reset. this is rare ... except that
2039             // when going through USB 2.0 TTs, unplug appears this way.
2040             // we avoid the highspeed version of the ETIMEOUT/EILSEQ
2041             // storm, recovering as needed.
2042             case -EPIPE:
2043                 dev->stats.rx_errors++;
2044                 usbnet_defer_kevent (dev, EVENT_RX_HALT);
2045                 // FALLTHROUGH
2046
2047             // software-driven interface shutdown
2048             case -ECONNRESET:           // async unlink
2049             case -ESHUTDOWN:            // hardware gone
2050                 if (netif_msg_ifdown (dev))
2051                         devdbg (dev, "rx shutdown, code %d", urb_status);
2052                 goto block;
2053
2054             // we get controller i/o faults during khubd disconnect() delays.
2055             // throttle down resubmits, to avoid log floods; just temporarily,
2056             // so we still recover when the fault isn't a khubd delay.
2057             case -EPROTO:               // ehci
2058             case -ETIMEDOUT:            // ohci
2059             case -EILSEQ:               // uhci
2060                 dev->stats.rx_errors++;
2061                 if (!timer_pending (&dev->delay)) {
2062                         mod_timer (&dev->delay, jiffies + THROTTLE_JIFFIES);
2063                         if (netif_msg_link (dev))
2064                                 devdbg (dev, "rx throttle %d", urb_status);
2065                 }
2066 block:
2067                 entry->state = rx_cleanup;
2068                 entry->urb = urb;
2069                 urb = NULL;
2070                 break;
2071
2072             // data overrun ... flush fifo?
2073             case -EOVERFLOW:
2074                 dev->stats.rx_over_errors++;
2075                 // FALLTHROUGH
2076             
2077             default:
2078                 entry->state = rx_cleanup;
2079                 dev->stats.rx_errors++;
2080                 if (netif_msg_rx_err (dev))
2081                         devdbg (dev, "rx status %d", urb_status);
2082                 break;
2083         }
2084
2085         defer_bh(dev, skb, &dev->rxq);
2086
2087         if (urb) {
2088                 if (netif_running (dev->net)
2089                                 && !test_bit (EVENT_RX_HALT, &dev->flags)) {
2090                         rx_submit (dev, urb, GFP_ATOMIC);
2091                         return;
2092                 }
2093                 usb_free_urb (urb);
2094         }
2095         if (netif_msg_rx_err (dev))
2096                 devdbg (dev, "no read resubmitted");
2097 }
2098
2099 static void intr_complete (struct urb *urb, struct pt_regs *regs)
2100 {
2101         struct usbnet   *dev = urb->context;
2102         int             status = urb->status;
2103
2104         switch (status) {
2105             /* success */
2106             case 0:
2107                 dev->driver_info->status(dev, urb);
2108                 break;
2109
2110             /* software-driven interface shutdown */
2111             case -ENOENT:               // urb killed
2112             case -ESHUTDOWN:            // hardware gone
2113                 if (netif_msg_ifdown (dev))
2114                         devdbg (dev, "intr shutdown, code %d", status);
2115                 return;
2116
2117             /* NOTE:  not throttling like RX/TX, since this endpoint
2118              * already polls infrequently
2119              */
2120             default:
2121                 devdbg (dev, "intr status %d", status);
2122                 break;
2123         }
2124
2125         if (!netif_running (dev->net))
2126                 return;
2127
2128         memset(urb->transfer_buffer, 0, urb->transfer_buffer_length);
2129         status = usb_submit_urb (urb, GFP_ATOMIC);
2130         if (status != 0 && netif_msg_timer (dev))
2131                 deverr(dev, "intr resubmit --> %d", status);
2132 }
2133
2134 /*-------------------------------------------------------------------------*/
2135
2136 // unlink pending rx/tx; completion handlers do all other cleanup
2137
2138 static int unlink_urbs (struct usbnet *dev, struct sk_buff_head *q)
2139 {
2140         unsigned long           flags;
2141         struct sk_buff          *skb, *skbnext;
2142         int                     count = 0;
2143
2144         spin_lock_irqsave (&q->lock, flags);
2145         for (skb = q->next; skb != (struct sk_buff *) q; skb = skbnext) {
2146                 struct skb_data         *entry;
2147                 struct urb              *urb;
2148                 int                     retval;
2149
2150                 entry = (struct skb_data *) skb->cb;
2151                 urb = entry->urb;
2152                 skbnext = skb->next;
2153
2154                 // during some PM-driven resume scenarios,
2155                 // these (async) unlinks complete immediately
2156                 retval = usb_unlink_urb (urb);
2157                 if (retval != -EINPROGRESS && retval != 0)
2158                         devdbg (dev, "unlink urb err, %d", retval);
2159                 else
2160                         count++;
2161         }
2162         spin_unlock_irqrestore (&q->lock, flags);
2163         return count;
2164 }
2165
2166
2167 /*-------------------------------------------------------------------------*/
2168
2169 // precondition: never called in_interrupt
2170
2171 static int usbnet_stop (struct net_device *net)
2172 {
2173         struct usbnet           *dev = netdev_priv(net);
2174         int                     temp;
2175         DECLARE_WAIT_QUEUE_HEAD (unlink_wakeup); 
2176         DECLARE_WAITQUEUE (wait, current);
2177
2178         netif_stop_queue (net);
2179
2180         if (netif_msg_ifdown (dev))
2181                 devinfo (dev, "stop stats: rx/tx %ld/%ld, errs %ld/%ld",
2182                         dev->stats.rx_packets, dev->stats.tx_packets, 
2183                         dev->stats.rx_errors, dev->stats.tx_errors
2184                         );
2185
2186         // ensure there are no more active urbs
2187         add_wait_queue (&unlink_wakeup, &wait);
2188         dev->wait = &unlink_wakeup;
2189         temp = unlink_urbs (dev, &dev->txq) + unlink_urbs (dev, &dev->rxq);
2190
2191         // maybe wait for deletions to finish.
2192         while (!skb_queue_empty(&dev->rxq) &&
2193                !skb_queue_empty(&dev->txq) &&
2194                !skb_queue_empty(&dev->done)) {
2195                 msleep(UNLINK_TIMEOUT_MS);
2196                 if (netif_msg_ifdown (dev))
2197                         devdbg (dev, "waited for %d urb completions", temp);
2198         }
2199         dev->wait = NULL;
2200         remove_wait_queue (&unlink_wakeup, &wait); 
2201
2202         usb_kill_urb(dev->interrupt);
2203
2204         /* deferred work (task, timer, softirq) must also stop.
2205          * can't flush_scheduled_work() until we drop rtnl (later),
2206          * else workers could deadlock; so make workers a NOP.
2207          */
2208         dev->flags = 0;
2209         del_timer_sync (&dev->delay);
2210         tasklet_kill (&dev->bh);
2211
2212         return 0;
2213 }
2214
2215 /*-------------------------------------------------------------------------*/
2216
2217 // posts reads, and enables write queuing
2218
2219 // precondition: never called in_interrupt
2220
2221 static int usbnet_open (struct net_device *net)
2222 {
2223         struct usbnet           *dev = netdev_priv(net);
2224         int                     retval = 0;
2225         struct driver_info      *info = dev->driver_info;
2226
2227         // put into "known safe" state
2228         if (info->reset && (retval = info->reset (dev)) < 0) {
2229                 if (netif_msg_ifup (dev))
2230                         devinfo (dev,
2231                                 "open reset fail (%d) usbnet usb-%s-%s, %s",
2232                                 retval,
2233                                 dev->udev->bus->bus_name, dev->udev->devpath,
2234                         info->description);
2235                 goto done;
2236         }
2237
2238         // insist peer be connected
2239         if (info->check_connect && (retval = info->check_connect (dev)) < 0) {
2240                 if (netif_msg_ifup (dev))
2241                         devdbg (dev, "can't open; %d", retval);
2242                 goto done;
2243         }
2244
2245         /* start any status interrupt transfer */
2246         if (dev->interrupt) {
2247                 retval = usb_submit_urb (dev->interrupt, GFP_KERNEL);
2248                 if (retval < 0) {
2249                         if (netif_msg_ifup (dev))
2250                                 deverr (dev, "intr submit %d", retval);
2251                         goto done;
2252                 }
2253         }
2254
2255         netif_start_queue (net);
2256         if (netif_msg_ifup (dev)) {
2257                 char    *framing;
2258
2259                 if (dev->driver_info->flags & FLAG_FRAMING_NC)
2260                         framing = "NetChip";
2261                 else if (dev->driver_info->flags & FLAG_FRAMING_GL)
2262                         framing = "GeneSys";
2263                 else if (dev->driver_info->flags & FLAG_FRAMING_Z)
2264                         framing = "Zaurus";
2265                 else if (dev->driver_info->flags & FLAG_FRAMING_RN)
2266                         framing = "RNDIS";
2267                 else if (dev->driver_info->flags & FLAG_FRAMING_AX)
2268                         framing = "ASIX";
2269                 else
2270                         framing = "simple";
2271
2272                 devinfo (dev, "open: enable queueing "
2273                                 "(rx %d, tx %d) mtu %d %s framing",
2274                         RX_QLEN (dev), TX_QLEN (dev), dev->net->mtu,
2275                         framing);
2276         }
2277
2278         // delay posting reads until we're fully open
2279         tasklet_schedule (&dev->bh);
2280 done:
2281         return retval;
2282 }
2283
2284 /*-------------------------------------------------------------------------*/
2285
2286 /* ethtool methods; minidrivers may need to add some more, but
2287  * they'll probably want to use this base set.
2288  */
2289
2290 void usbnet_get_drvinfo (struct net_device *net, struct ethtool_drvinfo *info)
2291 {
2292         struct usbnet *dev = netdev_priv(net);
2293
2294         /* REVISIT don't always return "usbnet" */
2295         strncpy (info->driver, driver_name, sizeof info->driver);
2296         strncpy (info->version, DRIVER_VERSION, sizeof info->version);
2297         strncpy (info->fw_version, dev->driver_info->description,
2298                 sizeof info->fw_version);
2299         usb_make_path (dev->udev, info->bus_info, sizeof info->bus_info);
2300 }
2301 EXPORT_SYMBOL_GPL(usbnet_get_drvinfo);
2302
2303 static u32 usbnet_get_link (struct net_device *net)
2304 {
2305         struct usbnet *dev = netdev_priv(net);
2306
2307         /* If a check_connect is defined, return its result */
2308         if (dev->driver_info->check_connect)
2309                 return dev->driver_info->check_connect (dev) == 0;
2310
2311         /* Otherwise, say we're up (to avoid breaking scripts) */
2312         return 1;
2313 }
2314
2315 u32 usbnet_get_msglevel (struct net_device *net)
2316 {
2317         struct usbnet *dev = netdev_priv(net);
2318
2319         return dev->msg_enable;
2320 }
2321 EXPORT_SYMBOL_GPL(usbnet_get_msglevel);
2322
2323 void usbnet_set_msglevel (struct net_device *net, u32 level)
2324 {
2325         struct usbnet *dev = netdev_priv(net);
2326
2327         dev->msg_enable = level;
2328 }
2329 EXPORT_SYMBOL_GPL(usbnet_set_msglevel);
2330
2331 /* drivers may override default ethtool_ops in their bind() routine */
2332 static struct ethtool_ops usbnet_ethtool_ops = {
2333         .get_drvinfo            = usbnet_get_drvinfo,
2334         .get_link               = usbnet_get_link,
2335         .get_msglevel           = usbnet_get_msglevel,
2336         .set_msglevel           = usbnet_set_msglevel,
2337 };
2338
2339 /*-------------------------------------------------------------------------*/
2340
2341 /* work that cannot be done in interrupt context uses keventd.
2342  *
2343  * NOTE:  with 2.5 we could do more of this using completion callbacks,
2344  * especially now that control transfers can be queued.
2345  */
2346 static void
2347 kevent (void *data)
2348 {
2349         struct usbnet           *dev = data;
2350         int                     status;
2351
2352         /* usb_clear_halt() needs a thread context */
2353         if (test_bit (EVENT_TX_HALT, &dev->flags)) {
2354                 unlink_urbs (dev, &dev->txq);
2355                 status = usb_clear_halt (dev->udev, dev->out);
2356                 if (status < 0
2357                                 && status != -EPIPE
2358                                 && status != -ESHUTDOWN) {
2359                         if (netif_msg_tx_err (dev))
2360                                 deverr (dev, "can't clear tx halt, status %d",
2361                                         status);
2362                 } else {
2363                         clear_bit (EVENT_TX_HALT, &dev->flags);
2364                         if (status != -ESHUTDOWN)
2365                                 netif_wake_queue (dev->net);
2366                 }
2367         }
2368         if (test_bit (EVENT_RX_HALT, &dev->flags)) {
2369                 unlink_urbs (dev, &dev->rxq);
2370                 status = usb_clear_halt (dev->udev, dev->in);
2371                 if (status < 0
2372                                 && status != -EPIPE
2373                                 && status != -ESHUTDOWN) {
2374                         if (netif_msg_rx_err (dev))
2375                                 deverr (dev, "can't clear rx halt, status %d",
2376                                         status);
2377                 } else {
2378                         clear_bit (EVENT_RX_HALT, &dev->flags);
2379                         tasklet_schedule (&dev->bh);
2380                 }
2381         }
2382
2383         /* tasklet could resubmit itself forever if memory is tight */
2384         if (test_bit (EVENT_RX_MEMORY, &dev->flags)) {
2385                 struct urb      *urb = NULL;
2386
2387                 if (netif_running (dev->net))
2388                         urb = usb_alloc_urb (0, GFP_KERNEL);
2389                 else
2390                         clear_bit (EVENT_RX_MEMORY, &dev->flags);
2391                 if (urb != NULL) {
2392                         clear_bit (EVENT_RX_MEMORY, &dev->flags);
2393                         rx_submit (dev, urb, GFP_KERNEL);
2394                         tasklet_schedule (&dev->bh);
2395                 }
2396         }
2397
2398         if (test_bit (EVENT_LINK_RESET, &dev->flags)) {
2399                 struct driver_info      *info = dev->driver_info;
2400                 int                     retval = 0;
2401
2402                 clear_bit (EVENT_LINK_RESET, &dev->flags);
2403                 if(info->link_reset && (retval = info->link_reset(dev)) < 0) {
2404                         devinfo(dev, "link reset failed (%d) usbnet usb-%s-%s, %s",
2405                                 retval,
2406                                 dev->udev->bus->bus_name, dev->udev->devpath,
2407                                 info->description);
2408                 }
2409         }
2410
2411         if (dev->flags)
2412                 devdbg (dev, "kevent done, flags = 0x%lx",
2413                         dev->flags);
2414 }
2415
2416 /*-------------------------------------------------------------------------*/
2417
2418 static void tx_complete (struct urb *urb, struct pt_regs *regs)
2419 {
2420         struct sk_buff          *skb = (struct sk_buff *) urb->context;
2421         struct skb_data         *entry = (struct skb_data *) skb->cb;
2422         struct usbnet           *dev = entry->dev;
2423
2424         if (urb->status == 0) {
2425                 dev->stats.tx_packets++;
2426                 dev->stats.tx_bytes += entry->length;
2427         } else {
2428                 dev->stats.tx_errors++;
2429
2430                 switch (urb->status) {
2431                 case -EPIPE:
2432                         usbnet_defer_kevent (dev, EVENT_TX_HALT);
2433                         break;
2434
2435                 /* software-driven interface shutdown */
2436                 case -ECONNRESET:               // async unlink
2437                 case -ESHUTDOWN:                // hardware gone
2438                         break;
2439
2440                 // like rx, tx gets controller i/o faults during khubd delays
2441                 // and so it uses the same throttling mechanism.
2442                 case -EPROTO:           // ehci
2443                 case -ETIMEDOUT:        // ohci
2444                 case -EILSEQ:           // uhci
2445                         if (!timer_pending (&dev->delay)) {
2446                                 mod_timer (&dev->delay,
2447                                         jiffies + THROTTLE_JIFFIES);
2448                                 if (netif_msg_link (dev))
2449                                         devdbg (dev, "tx throttle %d",
2450                                                         urb->status);
2451                         }
2452                         netif_stop_queue (dev->net);
2453                         break;
2454                 default:
2455                         if (netif_msg_tx_err (dev))
2456                                 devdbg (dev, "tx err %d", entry->urb->status);
2457                         break;
2458                 }
2459         }
2460
2461         urb->dev = NULL;
2462         entry->state = tx_done;
2463         defer_bh(dev, skb, &dev->txq);
2464 }
2465
2466 /*-------------------------------------------------------------------------*/
2467
2468 static void usbnet_tx_timeout (struct net_device *net)
2469 {
2470         struct usbnet           *dev = netdev_priv(net);
2471
2472         unlink_urbs (dev, &dev->txq);
2473         tasklet_schedule (&dev->bh);
2474
2475         // FIXME: device recovery -- reset?
2476 }
2477
2478 /*-------------------------------------------------------------------------*/
2479
2480 static int usbnet_start_xmit (struct sk_buff *skb, struct net_device *net)
2481 {
2482         struct usbnet           *dev = netdev_priv(net);
2483         int                     length;
2484         int                     retval = NET_XMIT_SUCCESS;
2485         struct urb              *urb = NULL;
2486         struct skb_data         *entry;
2487         struct driver_info      *info = dev->driver_info;
2488         unsigned long           flags;
2489 #ifdef  CONFIG_USB_NET1080
2490         struct nc_header        *header = NULL;
2491         struct nc_trailer       *trailer = NULL;
2492 #endif  /* CONFIG_USB_NET1080 */
2493
2494         // some devices want funky USB-level framing, for
2495         // win32 driver (usually) and/or hardware quirks
2496         if (info->tx_fixup) {
2497                 skb = info->tx_fixup (dev, skb, GFP_ATOMIC);
2498                 if (!skb) {
2499                         if (netif_msg_tx_err (dev))
2500                                 devdbg (dev, "can't tx_fixup skb");
2501                         goto drop;
2502                 }
2503         }
2504         length = skb->len;
2505
2506         if (!(urb = usb_alloc_urb (0, GFP_ATOMIC))) {
2507                 if (netif_msg_tx_err (dev))
2508                         devdbg (dev, "no urb");
2509                 goto drop;
2510         }
2511
2512         entry = (struct skb_data *) skb->cb;
2513         entry->urb = urb;
2514         entry->dev = dev;
2515         entry->state = tx_start;
2516         entry->length = length;
2517
2518         // FIXME: reorganize a bit, so that fixup() fills out NetChip
2519         // framing too. (Packet ID update needs the spinlock...)
2520         // [ BETTER:  we already own net->xmit_lock, that's enough ]
2521
2522 #ifdef  CONFIG_USB_NET1080
2523         if (info->flags & FLAG_FRAMING_NC) {
2524                 header = (struct nc_header *) skb_push (skb, sizeof *header);
2525                 header->hdr_len = cpu_to_le16 (sizeof (*header));
2526                 header->packet_len = cpu_to_le16 (length);
2527                 if (!((skb->len + sizeof *trailer) & 0x01))
2528                         *skb_put (skb, 1) = PAD_BYTE;
2529                 trailer = (struct nc_trailer *) skb_put (skb, sizeof *trailer);
2530         }
2531 #endif  /* CONFIG_USB_NET1080 */
2532
2533         usb_fill_bulk_urb (urb, dev->udev, dev->out,
2534                         skb->data, skb->len, tx_complete, skb);
2535
2536         /* don't assume the hardware handles USB_ZERO_PACKET
2537          * NOTE:  strictly conforming cdc-ether devices should expect
2538          * the ZLP here, but ignore the one-byte packet.
2539          *
2540          * FIXME zero that byte, if it doesn't require a new skb.
2541          */
2542         if ((length % dev->maxpacket) == 0)
2543                 urb->transfer_buffer_length++;
2544
2545         spin_lock_irqsave (&dev->txq.lock, flags);
2546
2547 #ifdef  CONFIG_USB_NET1080
2548         if (info->flags & FLAG_FRAMING_NC) {
2549                 header->packet_id = cpu_to_le16 ((u16)dev->xid++);
2550                 put_unaligned (header->packet_id, &trailer->packet_id);
2551 #if 0
2552                 devdbg (dev, "frame >tx h %d p %d id %d",
2553                         header->hdr_len, header->packet_len,
2554                         header->packet_id);
2555 #endif
2556         }
2557 #endif  /* CONFIG_USB_NET1080 */
2558
2559         switch ((retval = usb_submit_urb (urb, GFP_ATOMIC))) {
2560         case -EPIPE:
2561                 netif_stop_queue (net);
2562                 usbnet_defer_kevent (dev, EVENT_TX_HALT);
2563                 break;
2564         default:
2565                 if (netif_msg_tx_err (dev))
2566                         devdbg (dev, "tx: submit urb err %d", retval);
2567                 break;
2568         case 0:
2569                 net->trans_start = jiffies;
2570                 __skb_queue_tail (&dev->txq, skb);
2571                 if (dev->txq.qlen >= TX_QLEN (dev))
2572                         netif_stop_queue (net);
2573         }
2574         spin_unlock_irqrestore (&dev->txq.lock, flags);
2575
2576         if (retval) {
2577                 if (netif_msg_tx_err (dev))
2578                         devdbg (dev, "drop, code %d", retval);
2579 drop:
2580                 retval = NET_XMIT_SUCCESS;
2581                 dev->stats.tx_dropped++;
2582                 if (skb)
2583                         dev_kfree_skb_any (skb);
2584                 usb_free_urb (urb);
2585         } else if (netif_msg_tx_queued (dev)) {
2586                 devdbg (dev, "> tx, len %d, type 0x%x",
2587                         length, skb->protocol);
2588         }
2589         return retval;
2590 }
2591
2592
2593 /*-------------------------------------------------------------------------*/
2594
2595 // tasklet (work deferred from completions, in_irq) or timer
2596
2597 static void usbnet_bh (unsigned long param)
2598 {
2599         struct usbnet           *dev = (struct usbnet *) param;
2600         struct sk_buff          *skb;
2601         struct skb_data         *entry;
2602
2603         while ((skb = skb_dequeue (&dev->done))) {
2604                 entry = (struct skb_data *) skb->cb;
2605                 switch (entry->state) {
2606                     case rx_done:
2607                         entry->state = rx_cleanup;
2608                         rx_process (dev, skb);
2609                         continue;
2610                     case tx_done:
2611                     case rx_cleanup:
2612                         usb_free_urb (entry->urb);
2613                         dev_kfree_skb (skb);
2614                         continue;
2615                     default:
2616                         devdbg (dev, "bogus skb state %d", entry->state);
2617                 }
2618         }
2619
2620         // waiting for all pending urbs to complete?
2621         if (dev->wait) {
2622                 if ((dev->txq.qlen + dev->rxq.qlen + dev->done.qlen) == 0) {
2623                         wake_up (dev->wait);
2624                 }
2625
2626         // or are we maybe short a few urbs?
2627         } else if (netif_running (dev->net)
2628                         && netif_device_present (dev->net)
2629                         && !timer_pending (&dev->delay)
2630                         && !test_bit (EVENT_RX_HALT, &dev->flags)) {
2631                 int     temp = dev->rxq.qlen;
2632                 int     qlen = RX_QLEN (dev);
2633
2634                 if (temp < qlen) {
2635                         struct urb      *urb;
2636                         int             i;
2637
2638                         // don't refill the queue all at once
2639                         for (i = 0; i < 10 && dev->rxq.qlen < qlen; i++) {
2640                                 urb = usb_alloc_urb (0, GFP_ATOMIC);
2641                                 if (urb != NULL)
2642                                         rx_submit (dev, urb, GFP_ATOMIC);
2643                         }
2644                         if (temp != dev->rxq.qlen && netif_msg_link (dev))
2645                                 devdbg (dev, "rxqlen %d --> %d",
2646                                                 temp, dev->rxq.qlen);
2647                         if (dev->rxq.qlen < qlen)
2648                                 tasklet_schedule (&dev->bh);
2649                 }
2650                 if (dev->txq.qlen < TX_QLEN (dev))
2651                         netif_wake_queue (dev->net);
2652         }
2653 }
2654
2655
2656 \f
2657 /*-------------------------------------------------------------------------
2658  *
2659  * USB Device Driver support
2660  *
2661  *-------------------------------------------------------------------------*/
2662  
2663 // precondition: never called in_interrupt
2664
2665 void usbnet_disconnect (struct usb_interface *intf)
2666 {
2667         struct usbnet           *dev;
2668         struct usb_device       *xdev;
2669         struct net_device       *net;
2670
2671         dev = usb_get_intfdata(intf);
2672         usb_set_intfdata(intf, NULL);
2673         if (!dev)
2674                 return;
2675
2676         xdev = interface_to_usbdev (intf);
2677
2678         if (netif_msg_probe (dev))
2679                 devinfo (dev, "unregister '%s' usb-%s-%s, %s",
2680                         intf->dev.driver->name,
2681                         xdev->bus->bus_name, xdev->devpath,
2682                         dev->driver_info->description);
2683         
2684         net = dev->net;
2685         unregister_netdev (net);
2686
2687         /* we don't hold rtnl here ... */
2688         flush_scheduled_work ();
2689
2690         if (dev->driver_info->unbind)
2691                 dev->driver_info->unbind (dev, intf);
2692
2693         free_netdev(net);
2694         usb_put_dev (xdev);
2695 }
2696 EXPORT_SYMBOL_GPL(usbnet_disconnect);
2697
2698
2699 /*-------------------------------------------------------------------------*/
2700
2701 // precondition: never called in_interrupt
2702
2703 int
2704 usbnet_probe (struct usb_interface *udev, const struct usb_device_id *prod)
2705 {
2706         struct usbnet                   *dev;
2707         struct net_device               *net;
2708         struct usb_host_interface       *interface;
2709         struct driver_info              *info;
2710         struct usb_device               *xdev;
2711         int                             status;
2712
2713         info = (struct driver_info *) prod->driver_info;
2714         if (!info) {
2715                 dev_dbg (&udev->dev, "blacklisted by %s\n", driver_name);
2716                 return -ENODEV;
2717         }
2718         xdev = interface_to_usbdev (udev);
2719         interface = udev->cur_altsetting;
2720
2721         usb_get_dev (xdev);
2722
2723         status = -ENOMEM;
2724
2725         // set up our own records
2726         net = alloc_etherdev(sizeof(*dev));
2727         if (!net) {
2728                 dbg ("can't kmalloc dev");
2729                 goto out;
2730         }
2731
2732         dev = netdev_priv(net);
2733         dev->udev = xdev;
2734         dev->driver_info = info;
2735         dev->msg_enable = netif_msg_init (msg_level, NETIF_MSG_DRV
2736                                 | NETIF_MSG_PROBE | NETIF_MSG_LINK);
2737         skb_queue_head_init (&dev->rxq);
2738         skb_queue_head_init (&dev->txq);
2739         skb_queue_head_init (&dev->done);
2740         dev->bh.func = usbnet_bh;
2741         dev->bh.data = (unsigned long) dev;
2742         INIT_WORK (&dev->kevent, kevent, dev);
2743         dev->delay.function = usbnet_bh;
2744         dev->delay.data = (unsigned long) dev;
2745         init_timer (&dev->delay);
2746
2747         SET_MODULE_OWNER (net);
2748         dev->net = net;
2749         strcpy (net->name, "usb%d");
2750         memcpy (net->dev_addr, node_id, sizeof node_id);
2751
2752         /* rx and tx sides can use different message sizes;
2753          * bind() should set rx_urb_size in that case.
2754          */
2755         dev->hard_mtu = net->mtu + net->hard_header_len;
2756 #if 0
2757 // dma_supported() is deeply broken on almost all architectures
2758         // possible with some EHCI controllers
2759         if (dma_supported (&udev->dev, DMA_64BIT_MASK))
2760                 net->features |= NETIF_F_HIGHDMA;
2761 #endif
2762
2763         net->change_mtu = usbnet_change_mtu;
2764         net->get_stats = usbnet_get_stats;
2765         net->hard_start_xmit = usbnet_start_xmit;
2766         net->open = usbnet_open;
2767         net->stop = usbnet_stop;
2768         net->watchdog_timeo = TX_TIMEOUT_JIFFIES;
2769         net->tx_timeout = usbnet_tx_timeout;
2770         net->ethtool_ops = &usbnet_ethtool_ops;
2771
2772         // allow device-specific bind/init procedures
2773         // NOTE net->name still not usable ...
2774         if (info->bind) {
2775                 status = info->bind (dev, udev);
2776                 // heuristic:  "usb%d" for links we know are two-host,
2777                 // else "eth%d" when there's reasonable doubt.  userspace
2778                 // can rename the link if it knows better.
2779                 if ((dev->driver_info->flags & FLAG_ETHER) != 0
2780                                 && (net->dev_addr [0] & 0x02) == 0)
2781                         strcpy (net->name, "eth%d");
2782
2783                 /* maybe the remote can't receive an Ethernet MTU */
2784                 if (net->mtu > (dev->hard_mtu - net->hard_header_len))
2785                         net->mtu = dev->hard_mtu - net->hard_header_len;
2786         } else if (!info->in || !info->out)
2787                 status = usbnet_get_endpoints (dev, udev);
2788         else {
2789                 dev->in = usb_rcvbulkpipe (xdev, info->in);
2790                 dev->out = usb_sndbulkpipe (xdev, info->out);
2791                 if (!(info->flags & FLAG_NO_SETINT))
2792                         status = usb_set_interface (xdev,
2793                                 interface->desc.bInterfaceNumber,
2794                                 interface->desc.bAlternateSetting);
2795                 else
2796                         status = 0;
2797
2798         }
2799         if (status == 0 && dev->status)
2800                 status = init_status (dev, udev);
2801         if (status < 0)
2802                 goto out1;
2803
2804         if (!dev->rx_urb_size)
2805                 dev->rx_urb_size = dev->hard_mtu;
2806         dev->maxpacket = usb_maxpacket (dev->udev, dev->out, 1);
2807         
2808         SET_NETDEV_DEV(net, &udev->dev);
2809         status = register_netdev (net);
2810         if (status)
2811                 goto out3;
2812         if (netif_msg_probe (dev))
2813                 devinfo (dev, "register '%s' at usb-%s-%s, %s, "
2814                                 "%02x:%02x:%02x:%02x:%02x:%02x",
2815                         udev->dev.driver->name,
2816                         xdev->bus->bus_name, xdev->devpath,
2817                         dev->driver_info->description,
2818                         net->dev_addr [0], net->dev_addr [1],
2819                         net->dev_addr [2], net->dev_addr [3],
2820                         net->dev_addr [4], net->dev_addr [5]);
2821
2822         // ok, it's ready to go.
2823         usb_set_intfdata (udev, dev);
2824
2825         // start as if the link is up
2826         netif_device_attach (net);
2827
2828         return 0;
2829
2830 out3:
2831         if (info->unbind)
2832                 info->unbind (dev, udev);
2833 out1:
2834         free_netdev(net);
2835 out:
2836         usb_put_dev(xdev);
2837         return status;
2838 }
2839 EXPORT_SYMBOL_GPL(usbnet_probe);
2840
2841 /*-------------------------------------------------------------------------*/
2842
2843 /* FIXME these suspend/resume methods assume non-CDC style
2844  * devices, with only one interface.
2845  */
2846
2847 int usbnet_suspend (struct usb_interface *intf, pm_message_t message)
2848 {
2849         struct usbnet           *dev = usb_get_intfdata(intf);
2850         
2851         /* accelerate emptying of the rx and queues, to avoid
2852          * having everything error out.
2853          */
2854         netif_device_detach (dev->net);
2855         (void) unlink_urbs (dev, &dev->rxq);
2856         (void) unlink_urbs (dev, &dev->txq);
2857         intf->dev.power.power_state = PMSG_SUSPEND;
2858         return 0;
2859 }
2860 EXPORT_SYMBOL_GPL(usbnet_suspend);
2861
2862 int usbnet_resume (struct usb_interface *intf)
2863 {
2864         struct usbnet           *dev = usb_get_intfdata(intf);
2865
2866         intf->dev.power.power_state = PMSG_ON;
2867         netif_device_attach (dev->net);
2868         tasklet_schedule (&dev->bh);
2869         return 0;
2870 }
2871 EXPORT_SYMBOL_GPL(usbnet_resume);
2872
2873
2874 /*-------------------------------------------------------------------------*/
2875
2876 #ifndef HAVE_HARDWARE
2877 #error You need to configure some hardware for this driver
2878 #endif
2879
2880 /*
2881  * chip vendor names won't normally be on the cables, and
2882  * may not be on the device.
2883  */
2884
2885 static const struct usb_device_id       products [] = {
2886
2887 #ifdef  CONFIG_USB_GENESYS
2888 {
2889         USB_DEVICE (0x05e3, 0x0502),    // GL620USB-A
2890         .driver_info =  (unsigned long) &genelink_info,
2891 },
2892         /* NOT: USB_DEVICE (0x05e3, 0x0501),    // GL620USB
2893          * that's half duplex, not currently supported
2894          */
2895 #endif
2896
2897 #ifdef  CONFIG_USB_NET1080
2898 {
2899         USB_DEVICE (0x0525, 0x1080),    // NetChip ref design
2900         .driver_info =  (unsigned long) &net1080_info,
2901 }, {
2902         USB_DEVICE (0x06D0, 0x0622),    // Laplink Gold
2903         .driver_info =  (unsigned long) &net1080_info,
2904 },
2905 #endif
2906
2907 #ifdef CONFIG_USB_PL2301
2908 {
2909         USB_DEVICE (0x067b, 0x0000),    // PL-2301
2910         .driver_info =  (unsigned long) &prolific_info,
2911 }, {
2912         USB_DEVICE (0x067b, 0x0001),    // PL-2302
2913         .driver_info =  (unsigned long) &prolific_info,
2914 },
2915 #endif
2916
2917 #ifdef  CONFIG_USB_RNDIS
2918 {
2919         /* RNDIS is MSFT's un-official variant of CDC ACM */
2920         USB_INTERFACE_INFO (USB_CLASS_COMM, 2 /* ACM */, 0x0ff),
2921         .driver_info = (unsigned long) &rndis_info,
2922 },
2923 #endif
2924
2925 #if     defined(CONFIG_USB_ZAURUS) || defined(CONFIG_USB_CDCETHER)
2926 /*
2927  * SA-1100 based Sharp Zaurus ("collie"), or compatible.
2928  * Same idea as above, but different framing.
2929  *
2930  * PXA-2xx based models are also lying-about-cdc.
2931  * Some models don't even tell the same lies ...
2932  *
2933  * NOTE:  OpenZaurus versions with 2.6 kernels won't use these entries,
2934  * unlike the older ones with 2.4 "embedix" kernels.
2935  *
2936  * NOTE:  These entries do double-duty, serving as blacklist entries
2937  * whenever Zaurus support isn't enabled, but CDC Ethernet is.
2938  */
2939 #define ZAURUS_MASTER_INTERFACE \
2940         .bInterfaceClass        = USB_CLASS_COMM, \
2941         .bInterfaceSubClass     = USB_CDC_SUBCLASS_ETHERNET, \
2942         .bInterfaceProtocol     = USB_CDC_PROTO_NONE
2943 {
2944         .match_flags    =   USB_DEVICE_ID_MATCH_INT_INFO
2945                           | USB_DEVICE_ID_MATCH_DEVICE, 
2946         .idVendor               = 0x04DD,
2947         .idProduct              = 0x8004,
2948         ZAURUS_MASTER_INTERFACE,
2949         .driver_info = ZAURUS_STRONGARM_INFO,
2950 }, {
2951         .match_flags    =   USB_DEVICE_ID_MATCH_INT_INFO
2952                           | USB_DEVICE_ID_MATCH_DEVICE, 
2953         .idVendor               = 0x04DD,
2954         .idProduct              = 0x8005,       /* A-300 */
2955         ZAURUS_MASTER_INTERFACE,
2956         .driver_info = ZAURUS_PXA_INFO,
2957 }, {
2958         .match_flags    =   USB_DEVICE_ID_MATCH_INT_INFO
2959                           | USB_DEVICE_ID_MATCH_DEVICE, 
2960         .idVendor               = 0x04DD,
2961         .idProduct              = 0x8006,       /* B-500/SL-5600 */
2962         ZAURUS_MASTER_INTERFACE,
2963         .driver_info = ZAURUS_PXA_INFO,
2964 }, {
2965         .match_flags    =   USB_DEVICE_ID_MATCH_INT_INFO
2966                   | USB_DEVICE_ID_MATCH_DEVICE,
2967         .idVendor               = 0x04DD,
2968         .idProduct              = 0x8007,       /* C-700 */
2969         ZAURUS_MASTER_INTERFACE,
2970         .driver_info = ZAURUS_PXA_INFO,
2971 }, {
2972         .match_flags    =   USB_DEVICE_ID_MATCH_INT_INFO
2973                  | USB_DEVICE_ID_MATCH_DEVICE,
2974         .idVendor               = 0x04DD,
2975         .idProduct              = 0x9031,       /* C-750 C-760 */
2976         ZAURUS_MASTER_INTERFACE,
2977         .driver_info = ZAURUS_PXA_INFO,
2978 }, {
2979         .match_flags    =   USB_DEVICE_ID_MATCH_INT_INFO
2980                  | USB_DEVICE_ID_MATCH_DEVICE,
2981         .idVendor               = 0x04DD,
2982         .idProduct              = 0x9032,       /* SL-6000 */
2983         ZAURUS_MASTER_INTERFACE,
2984         .driver_info = ZAURUS_PXA_INFO,
2985 }, {
2986         .match_flags    =   USB_DEVICE_ID_MATCH_INT_INFO
2987                  | USB_DEVICE_ID_MATCH_DEVICE,
2988         .idVendor               = 0x04DD,
2989         /* reported with some C860 units */
2990         .idProduct              = 0x9050,       /* C-860 */
2991         ZAURUS_MASTER_INTERFACE,
2992         .driver_info = ZAURUS_PXA_INFO,
2993 },
2994
2995 #ifdef  CONFIG_USB_ZAURUS
2996         /* At least some (reports vary) PXA units have very different lies
2997          * about their standards support:  they claim to be cell phones with
2998          * direct access to their radios.  (They don't conform to CDC MDLM.)
2999          */
3000 {
3001         USB_INTERFACE_INFO (USB_CLASS_COMM, USB_CDC_SUBCLASS_MDLM,
3002                         USB_CDC_PROTO_NONE),
3003         .driver_info = (unsigned long) &bogus_mdlm_info,
3004 },
3005 #endif
3006
3007 /* Olympus has some models with a Zaurus-compatible option.
3008  * R-1000 uses a FreeScale i.MXL cpu (ARMv4T)
3009  */
3010 {
3011         .match_flags    =   USB_DEVICE_ID_MATCH_INT_INFO
3012                  | USB_DEVICE_ID_MATCH_DEVICE,
3013         .idVendor               = 0x07B4,
3014         .idProduct              = 0x0F02,       /* R-1000 */
3015         ZAURUS_MASTER_INTERFACE,
3016         .driver_info = OLYMPUS_MXL_INFO,
3017 },
3018 #endif
3019
3020 #ifdef  CONFIG_USB_CDCETHER
3021 {
3022         /* CDC Ether uses two interfaces, not necessarily consecutive.
3023          * We match the main interface, ignoring the optional device
3024          * class so we could handle devices that aren't exclusively
3025          * CDC ether.
3026          *
3027          * NOTE:  this match must come AFTER entries working around
3028          * bugs/quirks in a given product (like Zaurus, above).
3029          */
3030         USB_INTERFACE_INFO (USB_CLASS_COMM, USB_CDC_SUBCLASS_ETHERNET,
3031                         USB_CDC_PROTO_NONE),
3032         .driver_info = (unsigned long) &cdc_info,
3033 },
3034 #endif
3035
3036         { },            // END
3037 };
3038 MODULE_DEVICE_TABLE (usb, products);
3039
3040 static struct usb_driver usbnet_driver = {
3041         .owner =        THIS_MODULE,
3042         .name =         driver_name,
3043         .id_table =     products,
3044         .probe =        usbnet_probe,
3045         .disconnect =   usbnet_disconnect,
3046         .suspend =      usbnet_suspend,
3047         .resume =       usbnet_resume,
3048 };
3049
3050 /*-------------------------------------------------------------------------*/
3051
3052 static int __init usbnet_init(void)
3053 {
3054         // compiler should optimize these out
3055         BUG_ON (sizeof (((struct sk_buff *)0)->cb)
3056                         < sizeof (struct skb_data));
3057 #ifdef  CONFIG_USB_CDCETHER
3058         BUG_ON ((sizeof (((struct usbnet *)0)->data)
3059                         < sizeof (struct cdc_state)));
3060 #endif
3061
3062         random_ether_addr(node_id);
3063
3064         return usb_register(&usbnet_driver);
3065 }
3066 module_init(usbnet_init);
3067
3068 static void __exit usbnet_exit(void)
3069 {
3070         usb_deregister(&usbnet_driver);
3071 }
3072 module_exit(usbnet_exit);
3073
3074 MODULE_AUTHOR("David Brownell");
3075 MODULE_DESCRIPTION("USB Host-to-Host Link Drivers (numerous vendors)");
3076 MODULE_LICENSE("GPL");