]> git.sur5r.net Git - u-boot/blob - drivers/usb/gadget/ether.c
drivers: usb: gadget: ether: use net device priv to pass usb ether priv
[u-boot] / drivers / usb / gadget / ether.c
1 /*
2  * ether.c -- Ethernet gadget driver, with CDC and non-CDC options
3  *
4  * Copyright (C) 2003-2005,2008 David Brownell
5  * Copyright (C) 2003-2004 Robert Schwebel, Benedikt Spranger
6  * Copyright (C) 2008 Nokia Corporation
7  *
8  * SPDX-License-Identifier:     GPL-2.0+
9  */
10
11 #include <common.h>
12 #include <console.h>
13 #include <linux/errno.h>
14 #include <linux/netdevice.h>
15 #include <linux/usb/ch9.h>
16 #include <linux/usb/cdc.h>
17 #include <linux/usb/gadget.h>
18 #include <net.h>
19 #include <usb.h>
20 #include <malloc.h>
21 #include <memalign.h>
22 #include <linux/ctype.h>
23
24 #include "gadget_chips.h"
25 #include "rndis.h"
26
27 #include <dm.h>
28 #include <dm/uclass-internal.h>
29 #include <dm/device-internal.h>
30
31 #define USB_NET_NAME "usb_ether"
32
33 #define atomic_read
34 extern struct platform_data brd;
35
36
37 unsigned packet_received, packet_sent;
38
39 /*
40  * Ethernet gadget driver -- with CDC and non-CDC options
41  * Builds on hardware support for a full duplex link.
42  *
43  * CDC Ethernet is the standard USB solution for sending Ethernet frames
44  * using USB.  Real hardware tends to use the same framing protocol but look
45  * different for control features.  This driver strongly prefers to use
46  * this USB-IF standard as its open-systems interoperability solution;
47  * most host side USB stacks (except from Microsoft) support it.
48  *
49  * This is sometimes called "CDC ECM" (Ethernet Control Model) to support
50  * TLA-soup.  "CDC ACM" (Abstract Control Model) is for modems, and a new
51  * "CDC EEM" (Ethernet Emulation Model) is starting to spread.
52  *
53  * There's some hardware that can't talk CDC ECM.  We make that hardware
54  * implement a "minimalist" vendor-agnostic CDC core:  same framing, but
55  * link-level setup only requires activating the configuration.  Only the
56  * endpoint descriptors, and product/vendor IDs, are relevant; no control
57  * operations are available.  Linux supports it, but other host operating
58  * systems may not.  (This is a subset of CDC Ethernet.)
59  *
60  * It turns out that if you add a few descriptors to that "CDC Subset",
61  * (Windows) host side drivers from MCCI can treat it as one submode of
62  * a proprietary scheme called "SAFE" ... without needing to know about
63  * specific product/vendor IDs.  So we do that, making it easier to use
64  * those MS-Windows drivers.  Those added descriptors make it resemble a
65  * CDC MDLM device, but they don't change device behavior at all.  (See
66  * MCCI Engineering report 950198 "SAFE Networking Functions".)
67  *
68  * A third option is also in use.  Rather than CDC Ethernet, or something
69  * simpler, Microsoft pushes their own approach: RNDIS.  The published
70  * RNDIS specs are ambiguous and appear to be incomplete, and are also
71  * needlessly complex.  They borrow more from CDC ACM than CDC ECM.
72  */
73 #define ETH_ALEN        6               /* Octets in one ethernet addr   */
74 #define ETH_HLEN        14              /* Total octets in header.       */
75 #define ETH_ZLEN        60              /* Min. octets in frame sans FCS */
76 #define ETH_DATA_LEN    1500            /* Max. octets in payload        */
77 #define ETH_FRAME_LEN   PKTSIZE_ALIGN   /* Max. octets in frame sans FCS */
78
79 #define DRIVER_DESC             "Ethernet Gadget"
80 /* Based on linux 2.6.27 version */
81 #define DRIVER_VERSION          "May Day 2005"
82
83 static const char shortname[] = "ether";
84 static const char driver_desc[] = DRIVER_DESC;
85
86 #define RX_EXTRA        20              /* guard against rx overflows */
87
88 #ifndef CONFIG_USB_ETH_RNDIS
89 #define rndis_uninit(x)         do {} while (0)
90 #define rndis_deregister(c)     do {} while (0)
91 #define rndis_exit()            do {} while (0)
92 #endif
93
94 /* CDC and RNDIS support the same host-chosen outgoing packet filters. */
95 #define DEFAULT_FILTER  (USB_CDC_PACKET_TYPE_BROADCAST \
96                         |USB_CDC_PACKET_TYPE_ALL_MULTICAST \
97                         |USB_CDC_PACKET_TYPE_PROMISCUOUS \
98                         |USB_CDC_PACKET_TYPE_DIRECTED)
99
100 #define USB_CONNECT_TIMEOUT (3 * CONFIG_SYS_HZ)
101
102 /*-------------------------------------------------------------------------*/
103
104 struct eth_dev {
105         struct usb_gadget       *gadget;
106         struct usb_request      *req;           /* for control responses */
107         struct usb_request      *stat_req;      /* for cdc & rndis status */
108 #ifdef CONFIG_DM_USB
109         struct udevice          *usb_udev;
110 #endif
111
112         u8                      config;
113         struct usb_ep           *in_ep, *out_ep, *status_ep;
114         const struct usb_endpoint_descriptor
115                                 *in, *out, *status;
116
117         struct usb_request      *tx_req, *rx_req;
118
119         struct eth_device       *net;
120         struct net_device_stats stats;
121         unsigned int            tx_qlen;
122
123         unsigned                zlp:1;
124         unsigned                cdc:1;
125         unsigned                rndis:1;
126         unsigned                suspended:1;
127         unsigned                network_started:1;
128         u16                     cdc_filter;
129         unsigned long           todo;
130         int                     mtu;
131 #define WORK_RX_MEMORY          0
132         int                     rndis_config;
133         u8                      host_mac[ETH_ALEN];
134 };
135
136 /*
137  * This version autoconfigures as much as possible at run-time.
138  *
139  * It also ASSUMES a self-powered device, without remote wakeup,
140  * although remote wakeup support would make sense.
141  */
142
143 /*-------------------------------------------------------------------------*/
144 struct ether_priv {
145         struct eth_dev ethdev;
146         struct eth_device netdev;
147         struct usb_gadget_driver eth_driver;
148 };
149
150 struct ether_priv eth_priv;
151 struct ether_priv *l_priv = &eth_priv;
152
153 /*-------------------------------------------------------------------------*/
154
155 /* "main" config is either CDC, or its simple subset */
156 static inline int is_cdc(struct eth_dev *dev)
157 {
158 #if     !defined(CONFIG_USB_ETH_SUBSET)
159         return 1;               /* only cdc possible */
160 #elif   !defined(CONFIG_USB_ETH_CDC)
161         return 0;               /* only subset possible */
162 #else
163         return dev->cdc;        /* depends on what hardware we found */
164 #endif
165 }
166
167 /* "secondary" RNDIS config may sometimes be activated */
168 static inline int rndis_active(struct eth_dev *dev)
169 {
170 #ifdef  CONFIG_USB_ETH_RNDIS
171         return dev->rndis;
172 #else
173         return 0;
174 #endif
175 }
176
177 #define subset_active(dev)      (!is_cdc(dev) && !rndis_active(dev))
178 #define cdc_active(dev)         (is_cdc(dev) && !rndis_active(dev))
179
180 #define DEFAULT_QLEN    2       /* double buffering by default */
181
182 /* peak bulk transfer bits-per-second */
183 #define HS_BPS          (13 * 512 * 8 * 1000 * 8)
184 #define FS_BPS          (19 *  64 * 1 * 1000 * 8)
185
186 #ifdef CONFIG_USB_GADGET_DUALSPEED
187 #define DEVSPEED        USB_SPEED_HIGH
188
189 #ifdef CONFIG_USB_ETH_QMULT
190 #define qmult CONFIG_USB_ETH_QMULT
191 #else
192 #define qmult 5
193 #endif
194
195 /* for dual-speed hardware, use deeper queues at highspeed */
196 #define qlen(gadget) \
197         (DEFAULT_QLEN*((gadget->speed == USB_SPEED_HIGH) ? qmult : 1))
198
199 static inline int BITRATE(struct usb_gadget *g)
200 {
201         return (g->speed == USB_SPEED_HIGH) ? HS_BPS : FS_BPS;
202 }
203
204 #else   /* full speed (low speed doesn't do bulk) */
205
206 #define qmult           1
207
208 #define DEVSPEED        USB_SPEED_FULL
209
210 #define qlen(gadget) DEFAULT_QLEN
211
212 static inline int BITRATE(struct usb_gadget *g)
213 {
214         return FS_BPS;
215 }
216 #endif
217
218 /*-------------------------------------------------------------------------*/
219
220 /*
221  * DO NOT REUSE THESE IDs with a protocol-incompatible driver!!  Ever!!
222  * Instead:  allocate your own, using normal USB-IF procedures.
223  */
224
225 /*
226  * Thanks to NetChip Technologies for donating this product ID.
227  * It's for devices with only CDC Ethernet configurations.
228  */
229 #define CDC_VENDOR_NUM          0x0525  /* NetChip */
230 #define CDC_PRODUCT_NUM         0xa4a1  /* Linux-USB Ethernet Gadget */
231
232 /*
233  * For hardware that can't talk CDC, we use the same vendor ID that
234  * ARM Linux has used for ethernet-over-usb, both with sa1100 and
235  * with pxa250.  We're protocol-compatible, if the host-side drivers
236  * use the endpoint descriptors.  bcdDevice (version) is nonzero, so
237  * drivers that need to hard-wire endpoint numbers have a hook.
238  *
239  * The protocol is a minimal subset of CDC Ether, which works on any bulk
240  * hardware that's not deeply broken ... even on hardware that can't talk
241  * RNDIS (like SA-1100, with no interrupt endpoint, or anything that
242  * doesn't handle control-OUT).
243  */
244 #define SIMPLE_VENDOR_NUM       0x049f  /* Compaq Computer Corp. */
245 #define SIMPLE_PRODUCT_NUM      0x505a  /* Linux-USB "CDC Subset" Device */
246
247 /*
248  * For hardware that can talk RNDIS and either of the above protocols,
249  * use this ID ... the windows INF files will know it.  Unless it's
250  * used with CDC Ethernet, Linux 2.4 hosts will need updates to choose
251  * the non-RNDIS configuration.
252  */
253 #define RNDIS_VENDOR_NUM        0x0525  /* NetChip */
254 #define RNDIS_PRODUCT_NUM       0xa4a2  /* Ethernet/RNDIS Gadget */
255
256 /*
257  * Some systems will want different product identifers published in the
258  * device descriptor, either numbers or strings or both.  These string
259  * parameters are in UTF-8 (superset of ASCII's 7 bit characters).
260  */
261
262 /*
263  * Emulating them in eth_bind:
264  * static ushort idVendor;
265  * static ushort idProduct;
266  */
267
268 #if defined(CONFIG_USBNET_MANUFACTURER)
269 static char *iManufacturer = CONFIG_USBNET_MANUFACTURER;
270 #else
271 static char *iManufacturer = "U-Boot";
272 #endif
273
274 /* These probably need to be configurable. */
275 static ushort bcdDevice;
276 static char *iProduct;
277 static char *iSerialNumber;
278
279 static char dev_addr[18];
280
281 static char host_addr[18];
282
283
284 /*-------------------------------------------------------------------------*/
285
286 /*
287  * USB DRIVER HOOKUP (to the hardware driver, below us), mostly
288  * ep0 implementation:  descriptors, config management, setup().
289  * also optional class-specific notification interrupt transfer.
290  */
291
292 /*
293  * DESCRIPTORS ... most are static, but strings and (full) configuration
294  * descriptors are built on demand.  For now we do either full CDC, or
295  * our simple subset, with RNDIS as an optional second configuration.
296  *
297  * RNDIS includes some CDC ACM descriptors ... like CDC Ethernet.  But
298  * the class descriptors match a modem (they're ignored; it's really just
299  * Ethernet functionality), they don't need the NOP altsetting, and the
300  * status transfer endpoint isn't optional.
301  */
302
303 #define STRING_MANUFACTURER             1
304 #define STRING_PRODUCT                  2
305 #define STRING_ETHADDR                  3
306 #define STRING_DATA                     4
307 #define STRING_CONTROL                  5
308 #define STRING_RNDIS_CONTROL            6
309 #define STRING_CDC                      7
310 #define STRING_SUBSET                   8
311 #define STRING_RNDIS                    9
312 #define STRING_SERIALNUMBER             10
313
314 /* holds our biggest descriptor (or RNDIS response) */
315 #define USB_BUFSIZ      256
316
317 /*
318  * This device advertises one configuration, eth_config, unless RNDIS
319  * is enabled (rndis_config) on hardware supporting at least two configs.
320  *
321  * NOTE:  Controllers like superh_udc should probably be able to use
322  * an RNDIS-only configuration.
323  *
324  * FIXME define some higher-powered configurations to make it easier
325  * to recharge batteries ...
326  */
327
328 #define DEV_CONFIG_VALUE        1       /* cdc or subset */
329 #define DEV_RNDIS_CONFIG_VALUE  2       /* rndis; optional */
330
331 static struct usb_device_descriptor
332 device_desc = {
333         .bLength =              sizeof device_desc,
334         .bDescriptorType =      USB_DT_DEVICE,
335
336         .bcdUSB =               __constant_cpu_to_le16(0x0200),
337
338         .bDeviceClass =         USB_CLASS_COMM,
339         .bDeviceSubClass =      0,
340         .bDeviceProtocol =      0,
341
342         .idVendor =             __constant_cpu_to_le16(CDC_VENDOR_NUM),
343         .idProduct =            __constant_cpu_to_le16(CDC_PRODUCT_NUM),
344         .iManufacturer =        STRING_MANUFACTURER,
345         .iProduct =             STRING_PRODUCT,
346         .bNumConfigurations =   1,
347 };
348
349 static struct usb_otg_descriptor
350 otg_descriptor = {
351         .bLength =              sizeof otg_descriptor,
352         .bDescriptorType =      USB_DT_OTG,
353
354         .bmAttributes =         USB_OTG_SRP,
355 };
356
357 static struct usb_config_descriptor
358 eth_config = {
359         .bLength =              sizeof eth_config,
360         .bDescriptorType =      USB_DT_CONFIG,
361
362         /* compute wTotalLength on the fly */
363         .bNumInterfaces =       2,
364         .bConfigurationValue =  DEV_CONFIG_VALUE,
365         .iConfiguration =       STRING_CDC,
366         .bmAttributes =         USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
367         .bMaxPower =            1,
368 };
369
370 #ifdef  CONFIG_USB_ETH_RNDIS
371 static struct usb_config_descriptor
372 rndis_config = {
373         .bLength =              sizeof rndis_config,
374         .bDescriptorType =      USB_DT_CONFIG,
375
376         /* compute wTotalLength on the fly */
377         .bNumInterfaces =       2,
378         .bConfigurationValue =  DEV_RNDIS_CONFIG_VALUE,
379         .iConfiguration =       STRING_RNDIS,
380         .bmAttributes =         USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
381         .bMaxPower =            1,
382 };
383 #endif
384
385 /*
386  * Compared to the simple CDC subset, the full CDC Ethernet model adds
387  * three class descriptors, two interface descriptors, optional status
388  * endpoint.  Both have a "data" interface and two bulk endpoints.
389  * There are also differences in how control requests are handled.
390  *
391  * RNDIS shares a lot with CDC-Ethernet, since it's a variant of the
392  * CDC-ACM (modem) spec.  Unfortunately MSFT's RNDIS driver is buggy; it
393  * may hang or oops.  Since bugfixes (or accurate specs, letting Linux
394  * work around those bugs) are unlikely to ever come from MSFT, you may
395  * wish to avoid using RNDIS.
396  *
397  * MCCI offers an alternative to RNDIS if you need to connect to Windows
398  * but have hardware that can't support CDC Ethernet.   We add descriptors
399  * to present the CDC Subset as a (nonconformant) CDC MDLM variant called
400  * "SAFE".  That borrows from both CDC Ethernet and CDC MDLM.  You can
401  * get those drivers from MCCI, or bundled with various products.
402  */
403
404 #ifdef  CONFIG_USB_ETH_CDC
405 static struct usb_interface_descriptor
406 control_intf = {
407         .bLength =              sizeof control_intf,
408         .bDescriptorType =      USB_DT_INTERFACE,
409
410         .bInterfaceNumber =     0,
411         /* status endpoint is optional; this may be patched later */
412         .bNumEndpoints =        1,
413         .bInterfaceClass =      USB_CLASS_COMM,
414         .bInterfaceSubClass =   USB_CDC_SUBCLASS_ETHERNET,
415         .bInterfaceProtocol =   USB_CDC_PROTO_NONE,
416         .iInterface =           STRING_CONTROL,
417 };
418 #endif
419
420 #ifdef  CONFIG_USB_ETH_RNDIS
421 static const struct usb_interface_descriptor
422 rndis_control_intf = {
423         .bLength =              sizeof rndis_control_intf,
424         .bDescriptorType =      USB_DT_INTERFACE,
425
426         .bInterfaceNumber =     0,
427         .bNumEndpoints =        1,
428         .bInterfaceClass =      USB_CLASS_COMM,
429         .bInterfaceSubClass =   USB_CDC_SUBCLASS_ACM,
430         .bInterfaceProtocol =   USB_CDC_ACM_PROTO_VENDOR,
431         .iInterface =           STRING_RNDIS_CONTROL,
432 };
433 #endif
434
435 static const struct usb_cdc_header_desc header_desc = {
436         .bLength =              sizeof header_desc,
437         .bDescriptorType =      USB_DT_CS_INTERFACE,
438         .bDescriptorSubType =   USB_CDC_HEADER_TYPE,
439
440         .bcdCDC =               __constant_cpu_to_le16(0x0110),
441 };
442
443 #if defined(CONFIG_USB_ETH_CDC) || defined(CONFIG_USB_ETH_RNDIS)
444
445 static const struct usb_cdc_union_desc union_desc = {
446         .bLength =              sizeof union_desc,
447         .bDescriptorType =      USB_DT_CS_INTERFACE,
448         .bDescriptorSubType =   USB_CDC_UNION_TYPE,
449
450         .bMasterInterface0 =    0,      /* index of control interface */
451         .bSlaveInterface0 =     1,      /* index of DATA interface */
452 };
453
454 #endif  /* CDC || RNDIS */
455
456 #ifdef  CONFIG_USB_ETH_RNDIS
457
458 static const struct usb_cdc_call_mgmt_descriptor call_mgmt_descriptor = {
459         .bLength =              sizeof call_mgmt_descriptor,
460         .bDescriptorType =      USB_DT_CS_INTERFACE,
461         .bDescriptorSubType =   USB_CDC_CALL_MANAGEMENT_TYPE,
462
463         .bmCapabilities =       0x00,
464         .bDataInterface =       0x01,
465 };
466
467 static const struct usb_cdc_acm_descriptor acm_descriptor = {
468         .bLength =              sizeof acm_descriptor,
469         .bDescriptorType =      USB_DT_CS_INTERFACE,
470         .bDescriptorSubType =   USB_CDC_ACM_TYPE,
471
472         .bmCapabilities =       0x00,
473 };
474
475 #endif
476
477 #ifndef CONFIG_USB_ETH_CDC
478
479 /*
480  * "SAFE" loosely follows CDC WMC MDLM, violating the spec in various
481  * ways:  data endpoints live in the control interface, there's no data
482  * interface, and it's not used to talk to a cell phone radio.
483  */
484
485 static const struct usb_cdc_mdlm_desc mdlm_desc = {
486         .bLength =              sizeof mdlm_desc,
487         .bDescriptorType =      USB_DT_CS_INTERFACE,
488         .bDescriptorSubType =   USB_CDC_MDLM_TYPE,
489
490         .bcdVersion =           __constant_cpu_to_le16(0x0100),
491         .bGUID = {
492                 0x5d, 0x34, 0xcf, 0x66, 0x11, 0x18, 0x11, 0xd6,
493                 0xa2, 0x1a, 0x00, 0x01, 0x02, 0xca, 0x9a, 0x7f,
494         },
495 };
496
497 /*
498  * since "usb_cdc_mdlm_detail_desc" is a variable length structure, we
499  * can't really use its struct.  All we do here is say that we're using
500  * the submode of "SAFE" which directly matches the CDC Subset.
501  */
502 static const u8 mdlm_detail_desc[] = {
503         6,
504         USB_DT_CS_INTERFACE,
505         USB_CDC_MDLM_DETAIL_TYPE,
506
507         0,      /* "SAFE" */
508         0,      /* network control capabilities (none) */
509         0,      /* network data capabilities ("raw" encapsulation) */
510 };
511
512 #endif
513
514 static const struct usb_cdc_ether_desc ether_desc = {
515         .bLength =              sizeof(ether_desc),
516         .bDescriptorType =      USB_DT_CS_INTERFACE,
517         .bDescriptorSubType =   USB_CDC_ETHERNET_TYPE,
518
519         /* this descriptor actually adds value, surprise! */
520         .iMACAddress =          STRING_ETHADDR,
521         .bmEthernetStatistics = __constant_cpu_to_le32(0), /* no statistics */
522         .wMaxSegmentSize =      __constant_cpu_to_le16(ETH_FRAME_LEN),
523         .wNumberMCFilters =     __constant_cpu_to_le16(0),
524         .bNumberPowerFilters =  0,
525 };
526
527 #if defined(CONFIG_USB_ETH_CDC) || defined(CONFIG_USB_ETH_RNDIS)
528
529 /*
530  * include the status endpoint if we can, even where it's optional.
531  * use wMaxPacketSize big enough to fit CDC_NOTIFY_SPEED_CHANGE in one
532  * packet, to simplify cancellation; and a big transfer interval, to
533  * waste less bandwidth.
534  *
535  * some drivers (like Linux 2.4 cdc-ether!) "need" it to exist even
536  * if they ignore the connect/disconnect notifications that real aether
537  * can provide.  more advanced cdc configurations might want to support
538  * encapsulated commands (vendor-specific, using control-OUT).
539  *
540  * RNDIS requires the status endpoint, since it uses that encapsulation
541  * mechanism for its funky RPC scheme.
542  */
543
544 #define LOG2_STATUS_INTERVAL_MSEC       5       /* 1 << 5 == 32 msec */
545 #define STATUS_BYTECOUNT                16      /* 8 byte header + data */
546
547 static struct usb_endpoint_descriptor
548 fs_status_desc = {
549         .bLength =              USB_DT_ENDPOINT_SIZE,
550         .bDescriptorType =      USB_DT_ENDPOINT,
551
552         .bEndpointAddress =     USB_DIR_IN,
553         .bmAttributes =         USB_ENDPOINT_XFER_INT,
554         .wMaxPacketSize =       __constant_cpu_to_le16(STATUS_BYTECOUNT),
555         .bInterval =            1 << LOG2_STATUS_INTERVAL_MSEC,
556 };
557 #endif
558
559 #ifdef  CONFIG_USB_ETH_CDC
560
561 /* the default data interface has no endpoints ... */
562
563 static const struct usb_interface_descriptor
564 data_nop_intf = {
565         .bLength =              sizeof data_nop_intf,
566         .bDescriptorType =      USB_DT_INTERFACE,
567
568         .bInterfaceNumber =     1,
569         .bAlternateSetting =    0,
570         .bNumEndpoints =        0,
571         .bInterfaceClass =      USB_CLASS_CDC_DATA,
572         .bInterfaceSubClass =   0,
573         .bInterfaceProtocol =   0,
574 };
575
576 /* ... but the "real" data interface has two bulk endpoints */
577
578 static const struct usb_interface_descriptor
579 data_intf = {
580         .bLength =              sizeof data_intf,
581         .bDescriptorType =      USB_DT_INTERFACE,
582
583         .bInterfaceNumber =     1,
584         .bAlternateSetting =    1,
585         .bNumEndpoints =        2,
586         .bInterfaceClass =      USB_CLASS_CDC_DATA,
587         .bInterfaceSubClass =   0,
588         .bInterfaceProtocol =   0,
589         .iInterface =           STRING_DATA,
590 };
591
592 #endif
593
594 #ifdef  CONFIG_USB_ETH_RNDIS
595
596 /* RNDIS doesn't activate by changing to the "real" altsetting */
597
598 static const struct usb_interface_descriptor
599 rndis_data_intf = {
600         .bLength =              sizeof rndis_data_intf,
601         .bDescriptorType =      USB_DT_INTERFACE,
602
603         .bInterfaceNumber =     1,
604         .bAlternateSetting =    0,
605         .bNumEndpoints =        2,
606         .bInterfaceClass =      USB_CLASS_CDC_DATA,
607         .bInterfaceSubClass =   0,
608         .bInterfaceProtocol =   0,
609         .iInterface =           STRING_DATA,
610 };
611
612 #endif
613
614 #ifdef CONFIG_USB_ETH_SUBSET
615
616 /*
617  * "Simple" CDC-subset option is a simple vendor-neutral model that most
618  * full speed controllers can handle:  one interface, two bulk endpoints.
619  *
620  * To assist host side drivers, we fancy it up a bit, and add descriptors
621  * so some host side drivers will understand it as a "SAFE" variant.
622  */
623
624 static const struct usb_interface_descriptor
625 subset_data_intf = {
626         .bLength =              sizeof subset_data_intf,
627         .bDescriptorType =      USB_DT_INTERFACE,
628
629         .bInterfaceNumber =     0,
630         .bAlternateSetting =    0,
631         .bNumEndpoints =        2,
632         .bInterfaceClass =      USB_CLASS_COMM,
633         .bInterfaceSubClass =   USB_CDC_SUBCLASS_MDLM,
634         .bInterfaceProtocol =   0,
635         .iInterface =           STRING_DATA,
636 };
637
638 #endif  /* SUBSET */
639
640 static struct usb_endpoint_descriptor
641 fs_source_desc = {
642         .bLength =              USB_DT_ENDPOINT_SIZE,
643         .bDescriptorType =      USB_DT_ENDPOINT,
644
645         .bEndpointAddress =     USB_DIR_IN,
646         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
647         .wMaxPacketSize =       __constant_cpu_to_le16(64),
648 };
649
650 static struct usb_endpoint_descriptor
651 fs_sink_desc = {
652         .bLength =              USB_DT_ENDPOINT_SIZE,
653         .bDescriptorType =      USB_DT_ENDPOINT,
654
655         .bEndpointAddress =     USB_DIR_OUT,
656         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
657         .wMaxPacketSize =       __constant_cpu_to_le16(64),
658 };
659
660 static const struct usb_descriptor_header *fs_eth_function[11] = {
661         (struct usb_descriptor_header *) &otg_descriptor,
662 #ifdef CONFIG_USB_ETH_CDC
663         /* "cdc" mode descriptors */
664         (struct usb_descriptor_header *) &control_intf,
665         (struct usb_descriptor_header *) &header_desc,
666         (struct usb_descriptor_header *) &union_desc,
667         (struct usb_descriptor_header *) &ether_desc,
668         /* NOTE: status endpoint may need to be removed */
669         (struct usb_descriptor_header *) &fs_status_desc,
670         /* data interface, with altsetting */
671         (struct usb_descriptor_header *) &data_nop_intf,
672         (struct usb_descriptor_header *) &data_intf,
673         (struct usb_descriptor_header *) &fs_source_desc,
674         (struct usb_descriptor_header *) &fs_sink_desc,
675         NULL,
676 #endif /* CONFIG_USB_ETH_CDC */
677 };
678
679 static inline void fs_subset_descriptors(void)
680 {
681 #ifdef CONFIG_USB_ETH_SUBSET
682         /* behavior is "CDC Subset"; extra descriptors say "SAFE" */
683         fs_eth_function[1] = (struct usb_descriptor_header *) &subset_data_intf;
684         fs_eth_function[2] = (struct usb_descriptor_header *) &header_desc;
685         fs_eth_function[3] = (struct usb_descriptor_header *) &mdlm_desc;
686         fs_eth_function[4] = (struct usb_descriptor_header *) &mdlm_detail_desc;
687         fs_eth_function[5] = (struct usb_descriptor_header *) &ether_desc;
688         fs_eth_function[6] = (struct usb_descriptor_header *) &fs_source_desc;
689         fs_eth_function[7] = (struct usb_descriptor_header *) &fs_sink_desc;
690         fs_eth_function[8] = NULL;
691 #else
692         fs_eth_function[1] = NULL;
693 #endif
694 }
695
696 #ifdef  CONFIG_USB_ETH_RNDIS
697 static const struct usb_descriptor_header *fs_rndis_function[] = {
698         (struct usb_descriptor_header *) &otg_descriptor,
699         /* control interface matches ACM, not Ethernet */
700         (struct usb_descriptor_header *) &rndis_control_intf,
701         (struct usb_descriptor_header *) &header_desc,
702         (struct usb_descriptor_header *) &call_mgmt_descriptor,
703         (struct usb_descriptor_header *) &acm_descriptor,
704         (struct usb_descriptor_header *) &union_desc,
705         (struct usb_descriptor_header *) &fs_status_desc,
706         /* data interface has no altsetting */
707         (struct usb_descriptor_header *) &rndis_data_intf,
708         (struct usb_descriptor_header *) &fs_source_desc,
709         (struct usb_descriptor_header *) &fs_sink_desc,
710         NULL,
711 };
712 #endif
713
714 /*
715  * usb 2.0 devices need to expose both high speed and full speed
716  * descriptors, unless they only run at full speed.
717  */
718
719 #if defined(CONFIG_USB_ETH_CDC) || defined(CONFIG_USB_ETH_RNDIS)
720 static struct usb_endpoint_descriptor
721 hs_status_desc = {
722         .bLength =              USB_DT_ENDPOINT_SIZE,
723         .bDescriptorType =      USB_DT_ENDPOINT,
724
725         .bmAttributes =         USB_ENDPOINT_XFER_INT,
726         .wMaxPacketSize =       __constant_cpu_to_le16(STATUS_BYTECOUNT),
727         .bInterval =            LOG2_STATUS_INTERVAL_MSEC + 4,
728 };
729 #endif /* CONFIG_USB_ETH_CDC */
730
731 static struct usb_endpoint_descriptor
732 hs_source_desc = {
733         .bLength =              USB_DT_ENDPOINT_SIZE,
734         .bDescriptorType =      USB_DT_ENDPOINT,
735
736         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
737         .wMaxPacketSize =       __constant_cpu_to_le16(512),
738 };
739
740 static struct usb_endpoint_descriptor
741 hs_sink_desc = {
742         .bLength =              USB_DT_ENDPOINT_SIZE,
743         .bDescriptorType =      USB_DT_ENDPOINT,
744
745         .bmAttributes =         USB_ENDPOINT_XFER_BULK,
746         .wMaxPacketSize =       __constant_cpu_to_le16(512),
747 };
748
749 static struct usb_qualifier_descriptor
750 dev_qualifier = {
751         .bLength =              sizeof dev_qualifier,
752         .bDescriptorType =      USB_DT_DEVICE_QUALIFIER,
753
754         .bcdUSB =               __constant_cpu_to_le16(0x0200),
755         .bDeviceClass =         USB_CLASS_COMM,
756
757         .bNumConfigurations =   1,
758 };
759
760 static const struct usb_descriptor_header *hs_eth_function[11] = {
761         (struct usb_descriptor_header *) &otg_descriptor,
762 #ifdef CONFIG_USB_ETH_CDC
763         /* "cdc" mode descriptors */
764         (struct usb_descriptor_header *) &control_intf,
765         (struct usb_descriptor_header *) &header_desc,
766         (struct usb_descriptor_header *) &union_desc,
767         (struct usb_descriptor_header *) &ether_desc,
768         /* NOTE: status endpoint may need to be removed */
769         (struct usb_descriptor_header *) &hs_status_desc,
770         /* data interface, with altsetting */
771         (struct usb_descriptor_header *) &data_nop_intf,
772         (struct usb_descriptor_header *) &data_intf,
773         (struct usb_descriptor_header *) &hs_source_desc,
774         (struct usb_descriptor_header *) &hs_sink_desc,
775         NULL,
776 #endif /* CONFIG_USB_ETH_CDC */
777 };
778
779 static inline void hs_subset_descriptors(void)
780 {
781 #ifdef CONFIG_USB_ETH_SUBSET
782         /* behavior is "CDC Subset"; extra descriptors say "SAFE" */
783         hs_eth_function[1] = (struct usb_descriptor_header *) &subset_data_intf;
784         hs_eth_function[2] = (struct usb_descriptor_header *) &header_desc;
785         hs_eth_function[3] = (struct usb_descriptor_header *) &mdlm_desc;
786         hs_eth_function[4] = (struct usb_descriptor_header *) &mdlm_detail_desc;
787         hs_eth_function[5] = (struct usb_descriptor_header *) &ether_desc;
788         hs_eth_function[6] = (struct usb_descriptor_header *) &hs_source_desc;
789         hs_eth_function[7] = (struct usb_descriptor_header *) &hs_sink_desc;
790         hs_eth_function[8] = NULL;
791 #else
792         hs_eth_function[1] = NULL;
793 #endif
794 }
795
796 #ifdef  CONFIG_USB_ETH_RNDIS
797 static const struct usb_descriptor_header *hs_rndis_function[] = {
798         (struct usb_descriptor_header *) &otg_descriptor,
799         /* control interface matches ACM, not Ethernet */
800         (struct usb_descriptor_header *) &rndis_control_intf,
801         (struct usb_descriptor_header *) &header_desc,
802         (struct usb_descriptor_header *) &call_mgmt_descriptor,
803         (struct usb_descriptor_header *) &acm_descriptor,
804         (struct usb_descriptor_header *) &union_desc,
805         (struct usb_descriptor_header *) &hs_status_desc,
806         /* data interface has no altsetting */
807         (struct usb_descriptor_header *) &rndis_data_intf,
808         (struct usb_descriptor_header *) &hs_source_desc,
809         (struct usb_descriptor_header *) &hs_sink_desc,
810         NULL,
811 };
812 #endif
813
814
815 /* maxpacket and other transfer characteristics vary by speed. */
816 static inline struct usb_endpoint_descriptor *
817 ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *hs,
818                 struct usb_endpoint_descriptor *fs)
819 {
820         if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
821                 return hs;
822         return fs;
823 }
824
825 /*-------------------------------------------------------------------------*/
826
827 /* descriptors that are built on-demand */
828
829 static char manufacturer[50];
830 static char product_desc[40] = DRIVER_DESC;
831 static char serial_number[20];
832
833 /* address that the host will use ... usually assigned at random */
834 static char ethaddr[2 * ETH_ALEN + 1];
835
836 /* static strings, in UTF-8 */
837 static struct usb_string                strings[] = {
838         { STRING_MANUFACTURER,  manufacturer, },
839         { STRING_PRODUCT,       product_desc, },
840         { STRING_SERIALNUMBER,  serial_number, },
841         { STRING_DATA,          "Ethernet Data", },
842         { STRING_ETHADDR,       ethaddr, },
843 #ifdef  CONFIG_USB_ETH_CDC
844         { STRING_CDC,           "CDC Ethernet", },
845         { STRING_CONTROL,       "CDC Communications Control", },
846 #endif
847 #ifdef  CONFIG_USB_ETH_SUBSET
848         { STRING_SUBSET,        "CDC Ethernet Subset", },
849 #endif
850 #ifdef  CONFIG_USB_ETH_RNDIS
851         { STRING_RNDIS,         "RNDIS", },
852         { STRING_RNDIS_CONTROL, "RNDIS Communications Control", },
853 #endif
854         {  }            /* end of list */
855 };
856
857 static struct usb_gadget_strings        stringtab = {
858         .language       = 0x0409,       /* en-us */
859         .strings        = strings,
860 };
861
862 /*============================================================================*/
863 DEFINE_CACHE_ALIGN_BUFFER(u8, control_req, USB_BUFSIZ);
864
865 #if defined(CONFIG_USB_ETH_CDC) || defined(CONFIG_USB_ETH_RNDIS)
866 DEFINE_CACHE_ALIGN_BUFFER(u8, status_req, STATUS_BYTECOUNT);
867 #endif
868
869 /*============================================================================*/
870
871 /*
872  * one config, two interfaces:  control, data.
873  * complications: class descriptors, and an altsetting.
874  */
875 static int
876 config_buf(struct usb_gadget *g, u8 *buf, u8 type, unsigned index, int is_otg)
877 {
878         int                                     len;
879         const struct usb_config_descriptor      *config;
880         const struct usb_descriptor_header      **function;
881         int                                     hs = 0;
882
883         if (gadget_is_dualspeed(g)) {
884                 hs = (g->speed == USB_SPEED_HIGH);
885                 if (type == USB_DT_OTHER_SPEED_CONFIG)
886                         hs = !hs;
887         }
888 #define which_fn(t)     (hs ? hs_ ## t ## _function : fs_ ## t ## _function)
889
890         if (index >= device_desc.bNumConfigurations)
891                 return -EINVAL;
892
893 #ifdef  CONFIG_USB_ETH_RNDIS
894         /*
895          * list the RNDIS config first, to make Microsoft's drivers
896          * happy. DOCSIS 1.0 needs this too.
897          */
898         if (device_desc.bNumConfigurations == 2 && index == 0) {
899                 config = &rndis_config;
900                 function = which_fn(rndis);
901         } else
902 #endif
903         {
904                 config = &eth_config;
905                 function = which_fn(eth);
906         }
907
908         /* for now, don't advertise srp-only devices */
909         if (!is_otg)
910                 function++;
911
912         len = usb_gadget_config_buf(config, buf, USB_BUFSIZ, function);
913         if (len < 0)
914                 return len;
915         ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
916         return len;
917 }
918
919 /*-------------------------------------------------------------------------*/
920
921 static void eth_start(struct eth_dev *dev, gfp_t gfp_flags);
922 static int alloc_requests(struct eth_dev *dev, unsigned n, gfp_t gfp_flags);
923
924 static int
925 set_ether_config(struct eth_dev *dev, gfp_t gfp_flags)
926 {
927         int                                     result = 0;
928         struct usb_gadget                       *gadget = dev->gadget;
929
930 #if defined(CONFIG_USB_ETH_CDC) || defined(CONFIG_USB_ETH_RNDIS)
931         /* status endpoint used for RNDIS and (optionally) CDC */
932         if (!subset_active(dev) && dev->status_ep) {
933                 dev->status = ep_desc(gadget, &hs_status_desc,
934                                                 &fs_status_desc);
935                 dev->status_ep->driver_data = dev;
936
937                 result = usb_ep_enable(dev->status_ep, dev->status);
938                 if (result != 0) {
939                         debug("enable %s --> %d\n",
940                                 dev->status_ep->name, result);
941                         goto done;
942                 }
943         }
944 #endif
945
946         dev->in = ep_desc(gadget, &hs_source_desc, &fs_source_desc);
947         dev->in_ep->driver_data = dev;
948
949         dev->out = ep_desc(gadget, &hs_sink_desc, &fs_sink_desc);
950         dev->out_ep->driver_data = dev;
951
952         /*
953          * With CDC,  the host isn't allowed to use these two data
954          * endpoints in the default altsetting for the interface.
955          * so we don't activate them yet.  Reset from SET_INTERFACE.
956          *
957          * Strictly speaking RNDIS should work the same: activation is
958          * a side effect of setting a packet filter.  Deactivation is
959          * from REMOTE_NDIS_HALT_MSG, reset from REMOTE_NDIS_RESET_MSG.
960          */
961         if (!cdc_active(dev)) {
962                 result = usb_ep_enable(dev->in_ep, dev->in);
963                 if (result != 0) {
964                         debug("enable %s --> %d\n",
965                                 dev->in_ep->name, result);
966                         goto done;
967                 }
968
969                 result = usb_ep_enable(dev->out_ep, dev->out);
970                 if (result != 0) {
971                         debug("enable %s --> %d\n",
972                                 dev->out_ep->name, result);
973                         goto done;
974                 }
975         }
976
977 done:
978         if (result == 0)
979                 result = alloc_requests(dev, qlen(gadget), gfp_flags);
980
981         /* on error, disable any endpoints  */
982         if (result < 0) {
983                 if (!subset_active(dev) && dev->status_ep)
984                         (void) usb_ep_disable(dev->status_ep);
985                 dev->status = NULL;
986                 (void) usb_ep_disable(dev->in_ep);
987                 (void) usb_ep_disable(dev->out_ep);
988                 dev->in = NULL;
989                 dev->out = NULL;
990         } else if (!cdc_active(dev)) {
991                 /*
992                  * activate non-CDC configs right away
993                  * this isn't strictly according to the RNDIS spec
994                  */
995                 eth_start(dev, GFP_ATOMIC);
996         }
997
998         /* caller is responsible for cleanup on error */
999         return result;
1000 }
1001
1002 static void eth_reset_config(struct eth_dev *dev)
1003 {
1004         if (dev->config == 0)
1005                 return;
1006
1007         debug("%s\n", __func__);
1008
1009         rndis_uninit(dev->rndis_config);
1010
1011         /*
1012          * disable endpoints, forcing (synchronous) completion of
1013          * pending i/o.  then free the requests.
1014          */
1015
1016         if (dev->in) {
1017                 usb_ep_disable(dev->in_ep);
1018                 if (dev->tx_req) {
1019                         usb_ep_free_request(dev->in_ep, dev->tx_req);
1020                         dev->tx_req = NULL;
1021                 }
1022         }
1023         if (dev->out) {
1024                 usb_ep_disable(dev->out_ep);
1025                 if (dev->rx_req) {
1026                         usb_ep_free_request(dev->out_ep, dev->rx_req);
1027                         dev->rx_req = NULL;
1028                 }
1029         }
1030         if (dev->status)
1031                 usb_ep_disable(dev->status_ep);
1032
1033         dev->rndis = 0;
1034         dev->cdc_filter = 0;
1035         dev->config = 0;
1036 }
1037
1038 /*
1039  * change our operational config.  must agree with the code
1040  * that returns config descriptors, and altsetting code.
1041  */
1042 static int eth_set_config(struct eth_dev *dev, unsigned number,
1043                                 gfp_t gfp_flags)
1044 {
1045         int                     result = 0;
1046         struct usb_gadget       *gadget = dev->gadget;
1047
1048         if (gadget_is_sa1100(gadget)
1049                         && dev->config
1050                         && dev->tx_qlen != 0) {
1051                 /* tx fifo is full, but we can't clear it...*/
1052                 error("can't change configurations");
1053                 return -ESPIPE;
1054         }
1055         eth_reset_config(dev);
1056
1057         switch (number) {
1058         case DEV_CONFIG_VALUE:
1059                 result = set_ether_config(dev, gfp_flags);
1060                 break;
1061 #ifdef  CONFIG_USB_ETH_RNDIS
1062         case DEV_RNDIS_CONFIG_VALUE:
1063                 dev->rndis = 1;
1064                 result = set_ether_config(dev, gfp_flags);
1065                 break;
1066 #endif
1067         default:
1068                 result = -EINVAL;
1069                 /* FALL THROUGH */
1070         case 0:
1071                 break;
1072         }
1073
1074         if (result) {
1075                 if (number)
1076                         eth_reset_config(dev);
1077                 usb_gadget_vbus_draw(dev->gadget,
1078                                 gadget_is_otg(dev->gadget) ? 8 : 100);
1079         } else {
1080                 char *speed;
1081                 unsigned power;
1082
1083                 power = 2 * eth_config.bMaxPower;
1084                 usb_gadget_vbus_draw(dev->gadget, power);
1085
1086                 switch (gadget->speed) {
1087                 case USB_SPEED_FULL:
1088                         speed = "full"; break;
1089 #ifdef CONFIG_USB_GADGET_DUALSPEED
1090                 case USB_SPEED_HIGH:
1091                         speed = "high"; break;
1092 #endif
1093                 default:
1094                         speed = "?"; break;
1095                 }
1096
1097                 dev->config = number;
1098                 printf("%s speed config #%d: %d mA, %s, using %s\n",
1099                                 speed, number, power, driver_desc,
1100                                 rndis_active(dev)
1101                                         ? "RNDIS"
1102                                         : (cdc_active(dev)
1103                                                 ? "CDC Ethernet"
1104                                                 : "CDC Ethernet Subset"));
1105         }
1106         return result;
1107 }
1108
1109 /*-------------------------------------------------------------------------*/
1110
1111 #ifdef  CONFIG_USB_ETH_CDC
1112
1113 /*
1114  * The interrupt endpoint is used in CDC networking models (Ethernet, ATM)
1115  * only to notify the host about link status changes (which we support) or
1116  * report completion of some encapsulated command (as used in RNDIS).  Since
1117  * we want this CDC Ethernet code to be vendor-neutral, we don't use that
1118  * command mechanism; and only one status request is ever queued.
1119  */
1120 static void eth_status_complete(struct usb_ep *ep, struct usb_request *req)
1121 {
1122         struct usb_cdc_notification     *event = req->buf;
1123         int                             value = req->status;
1124         struct eth_dev                  *dev = ep->driver_data;
1125
1126         /* issue the second notification if host reads the first */
1127         if (event->bNotificationType == USB_CDC_NOTIFY_NETWORK_CONNECTION
1128                         && value == 0) {
1129                 __le32  *data = req->buf + sizeof *event;
1130
1131                 event->bmRequestType = 0xA1;
1132                 event->bNotificationType = USB_CDC_NOTIFY_SPEED_CHANGE;
1133                 event->wValue = __constant_cpu_to_le16(0);
1134                 event->wIndex = __constant_cpu_to_le16(1);
1135                 event->wLength = __constant_cpu_to_le16(8);
1136
1137                 /* SPEED_CHANGE data is up/down speeds in bits/sec */
1138                 data[0] = data[1] = cpu_to_le32(BITRATE(dev->gadget));
1139
1140                 req->length = STATUS_BYTECOUNT;
1141                 value = usb_ep_queue(ep, req, GFP_ATOMIC);
1142                 debug("send SPEED_CHANGE --> %d\n", value);
1143                 if (value == 0)
1144                         return;
1145         } else if (value != -ECONNRESET) {
1146                 debug("event %02x --> %d\n",
1147                         event->bNotificationType, value);
1148                 if (event->bNotificationType ==
1149                                 USB_CDC_NOTIFY_SPEED_CHANGE) {
1150                         dev->network_started = 1;
1151                         printf("USB network up!\n");
1152                 }
1153         }
1154         req->context = NULL;
1155 }
1156
1157 static void issue_start_status(struct eth_dev *dev)
1158 {
1159         struct usb_request              *req = dev->stat_req;
1160         struct usb_cdc_notification     *event;
1161         int                             value;
1162
1163         /*
1164          * flush old status
1165          *
1166          * FIXME ugly idiom, maybe we'd be better with just
1167          * a "cancel the whole queue" primitive since any
1168          * unlink-one primitive has way too many error modes.
1169          * here, we "know" toggle is already clear...
1170          *
1171          * FIXME iff req->context != null just dequeue it
1172          */
1173         usb_ep_disable(dev->status_ep);
1174         usb_ep_enable(dev->status_ep, dev->status);
1175
1176         /*
1177          * 3.8.1 says to issue first NETWORK_CONNECTION, then
1178          * a SPEED_CHANGE.  could be useful in some configs.
1179          */
1180         event = req->buf;
1181         event->bmRequestType = 0xA1;
1182         event->bNotificationType = USB_CDC_NOTIFY_NETWORK_CONNECTION;
1183         event->wValue = __constant_cpu_to_le16(1);      /* connected */
1184         event->wIndex = __constant_cpu_to_le16(1);
1185         event->wLength = 0;
1186
1187         req->length = sizeof *event;
1188         req->complete = eth_status_complete;
1189         req->context = dev;
1190
1191         value = usb_ep_queue(dev->status_ep, req, GFP_ATOMIC);
1192         if (value < 0)
1193                 debug("status buf queue --> %d\n", value);
1194 }
1195
1196 #endif
1197
1198 /*-------------------------------------------------------------------------*/
1199
1200 static void eth_setup_complete(struct usb_ep *ep, struct usb_request *req)
1201 {
1202         if (req->status || req->actual != req->length)
1203                 debug("setup complete --> %d, %d/%d\n",
1204                                 req->status, req->actual, req->length);
1205 }
1206
1207 #ifdef CONFIG_USB_ETH_RNDIS
1208
1209 static void rndis_response_complete(struct usb_ep *ep, struct usb_request *req)
1210 {
1211         if (req->status || req->actual != req->length)
1212                 debug("rndis response complete --> %d, %d/%d\n",
1213                         req->status, req->actual, req->length);
1214
1215         /* done sending after USB_CDC_GET_ENCAPSULATED_RESPONSE */
1216 }
1217
1218 static void rndis_command_complete(struct usb_ep *ep, struct usb_request *req)
1219 {
1220         struct eth_dev          *dev = ep->driver_data;
1221         int                     status;
1222
1223         /* received RNDIS command from USB_CDC_SEND_ENCAPSULATED_COMMAND */
1224         status = rndis_msg_parser(dev->rndis_config, (u8 *) req->buf);
1225         if (status < 0)
1226                 error("%s: rndis parse error %d", __func__, status);
1227 }
1228
1229 #endif  /* RNDIS */
1230
1231 /*
1232  * The setup() callback implements all the ep0 functionality that's not
1233  * handled lower down.  CDC has a number of less-common features:
1234  *
1235  *  - two interfaces:  control, and ethernet data
1236  *  - Ethernet data interface has two altsettings:  default, and active
1237  *  - class-specific descriptors for the control interface
1238  *  - class-specific control requests
1239  */
1240 static int
1241 eth_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1242 {
1243         struct eth_dev          *dev = get_gadget_data(gadget);
1244         struct usb_request      *req = dev->req;
1245         int                     value = -EOPNOTSUPP;
1246         u16                     wIndex = le16_to_cpu(ctrl->wIndex);
1247         u16                     wValue = le16_to_cpu(ctrl->wValue);
1248         u16                     wLength = le16_to_cpu(ctrl->wLength);
1249
1250         /*
1251          * descriptors just go into the pre-allocated ep0 buffer,
1252          * while config change events may enable network traffic.
1253          */
1254
1255         debug("%s\n", __func__);
1256
1257         req->complete = eth_setup_complete;
1258         switch (ctrl->bRequest) {
1259
1260         case USB_REQ_GET_DESCRIPTOR:
1261                 if (ctrl->bRequestType != USB_DIR_IN)
1262                         break;
1263                 switch (wValue >> 8) {
1264
1265                 case USB_DT_DEVICE:
1266                         device_desc.bMaxPacketSize0 = gadget->ep0->maxpacket;
1267                         value = min(wLength, (u16) sizeof device_desc);
1268                         memcpy(req->buf, &device_desc, value);
1269                         break;
1270                 case USB_DT_DEVICE_QUALIFIER:
1271                         if (!gadget_is_dualspeed(gadget))
1272                                 break;
1273                         value = min(wLength, (u16) sizeof dev_qualifier);
1274                         memcpy(req->buf, &dev_qualifier, value);
1275                         break;
1276
1277                 case USB_DT_OTHER_SPEED_CONFIG:
1278                         if (!gadget_is_dualspeed(gadget))
1279                                 break;
1280                         /* FALLTHROUGH */
1281                 case USB_DT_CONFIG:
1282                         value = config_buf(gadget, req->buf,
1283                                         wValue >> 8,
1284                                         wValue & 0xff,
1285                                         gadget_is_otg(gadget));
1286                         if (value >= 0)
1287                                 value = min(wLength, (u16) value);
1288                         break;
1289
1290                 case USB_DT_STRING:
1291                         value = usb_gadget_get_string(&stringtab,
1292                                         wValue & 0xff, req->buf);
1293
1294                         if (value >= 0)
1295                                 value = min(wLength, (u16) value);
1296
1297                         break;
1298                 }
1299                 break;
1300
1301         case USB_REQ_SET_CONFIGURATION:
1302                 if (ctrl->bRequestType != 0)
1303                         break;
1304                 if (gadget->a_hnp_support)
1305                         debug("HNP available\n");
1306                 else if (gadget->a_alt_hnp_support)
1307                         debug("HNP needs a different root port\n");
1308                 value = eth_set_config(dev, wValue, GFP_ATOMIC);
1309                 break;
1310         case USB_REQ_GET_CONFIGURATION:
1311                 if (ctrl->bRequestType != USB_DIR_IN)
1312                         break;
1313                 *(u8 *)req->buf = dev->config;
1314                 value = min(wLength, (u16) 1);
1315                 break;
1316
1317         case USB_REQ_SET_INTERFACE:
1318                 if (ctrl->bRequestType != USB_RECIP_INTERFACE
1319                                 || !dev->config
1320                                 || wIndex > 1)
1321                         break;
1322                 if (!cdc_active(dev) && wIndex != 0)
1323                         break;
1324
1325                 /*
1326                  * PXA hardware partially handles SET_INTERFACE;
1327                  * we need to kluge around that interference.
1328                  */
1329                 if (gadget_is_pxa(gadget)) {
1330                         value = eth_set_config(dev, DEV_CONFIG_VALUE,
1331                                                 GFP_ATOMIC);
1332                         /*
1333                          * PXA25x driver use non-CDC ethernet gadget.
1334                          * But only _CDC and _RNDIS code can signalize
1335                          * that network is working. So we signalize it
1336                          * here.
1337                          */
1338                         dev->network_started = 1;
1339                         debug("USB network up!\n");
1340                         goto done_set_intf;
1341                 }
1342
1343 #ifdef CONFIG_USB_ETH_CDC
1344                 switch (wIndex) {
1345                 case 0:         /* control/master intf */
1346                         if (wValue != 0)
1347                                 break;
1348                         if (dev->status) {
1349                                 usb_ep_disable(dev->status_ep);
1350                                 usb_ep_enable(dev->status_ep, dev->status);
1351                         }
1352
1353                         value = 0;
1354                         break;
1355                 case 1:         /* data intf */
1356                         if (wValue > 1)
1357                                 break;
1358                         usb_ep_disable(dev->in_ep);
1359                         usb_ep_disable(dev->out_ep);
1360
1361                         /*
1362                          * CDC requires the data transfers not be done from
1363                          * the default interface setting ... also, setting
1364                          * the non-default interface resets filters etc.
1365                          */
1366                         if (wValue == 1) {
1367                                 if (!cdc_active(dev))
1368                                         break;
1369                                 usb_ep_enable(dev->in_ep, dev->in);
1370                                 usb_ep_enable(dev->out_ep, dev->out);
1371                                 dev->cdc_filter = DEFAULT_FILTER;
1372                                 if (dev->status)
1373                                         issue_start_status(dev);
1374                                 eth_start(dev, GFP_ATOMIC);
1375                         }
1376                         value = 0;
1377                         break;
1378                 }
1379 #else
1380                 /*
1381                  * FIXME this is wrong, as is the assumption that
1382                  * all non-PXA hardware talks real CDC ...
1383                  */
1384                 debug("set_interface ignored!\n");
1385 #endif /* CONFIG_USB_ETH_CDC */
1386
1387 done_set_intf:
1388                 break;
1389         case USB_REQ_GET_INTERFACE:
1390                 if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE)
1391                                 || !dev->config
1392                                 || wIndex > 1)
1393                         break;
1394                 if (!(cdc_active(dev) || rndis_active(dev)) && wIndex != 0)
1395                         break;
1396
1397                 /* for CDC, iff carrier is on, data interface is active. */
1398                 if (rndis_active(dev) || wIndex != 1)
1399                         *(u8 *)req->buf = 0;
1400                 else {
1401                         /* *(u8 *)req->buf = netif_carrier_ok (dev->net) ? 1 : 0; */
1402                         /* carrier always ok ...*/
1403                         *(u8 *)req->buf = 1 ;
1404                 }
1405                 value = min(wLength, (u16) 1);
1406                 break;
1407
1408 #ifdef CONFIG_USB_ETH_CDC
1409         case USB_CDC_SET_ETHERNET_PACKET_FILTER:
1410                 /*
1411                  * see 6.2.30: no data, wIndex = interface,
1412                  * wValue = packet filter bitmap
1413                  */
1414                 if (ctrl->bRequestType != (USB_TYPE_CLASS|USB_RECIP_INTERFACE)
1415                                 || !cdc_active(dev)
1416                                 || wLength != 0
1417                                 || wIndex > 1)
1418                         break;
1419                 debug("packet filter %02x\n", wValue);
1420                 dev->cdc_filter = wValue;
1421                 value = 0;
1422                 break;
1423
1424         /*
1425          * and potentially:
1426          * case USB_CDC_SET_ETHERNET_MULTICAST_FILTERS:
1427          * case USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER:
1428          * case USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER:
1429          * case USB_CDC_GET_ETHERNET_STATISTIC:
1430          */
1431
1432 #endif /* CONFIG_USB_ETH_CDC */
1433
1434 #ifdef CONFIG_USB_ETH_RNDIS
1435         /*
1436          * RNDIS uses the CDC command encapsulation mechanism to implement
1437          * an RPC scheme, with much getting/setting of attributes by OID.
1438          */
1439         case USB_CDC_SEND_ENCAPSULATED_COMMAND:
1440                 if (ctrl->bRequestType != (USB_TYPE_CLASS|USB_RECIP_INTERFACE)
1441                                 || !rndis_active(dev)
1442                                 || wLength > USB_BUFSIZ
1443                                 || wValue
1444                                 || rndis_control_intf.bInterfaceNumber
1445                                         != wIndex)
1446                         break;
1447                 /* read the request, then process it */
1448                 value = wLength;
1449                 req->complete = rndis_command_complete;
1450                 /* later, rndis_control_ack () sends a notification */
1451                 break;
1452
1453         case USB_CDC_GET_ENCAPSULATED_RESPONSE:
1454                 if ((USB_DIR_IN|USB_TYPE_CLASS|USB_RECIP_INTERFACE)
1455                                         == ctrl->bRequestType
1456                                 && rndis_active(dev)
1457                                 /* && wLength >= 0x0400 */
1458                                 && !wValue
1459                                 && rndis_control_intf.bInterfaceNumber
1460                                         == wIndex) {
1461                         u8 *buf;
1462                         u32 n;
1463
1464                         /* return the result */
1465                         buf = rndis_get_next_response(dev->rndis_config, &n);
1466                         if (buf) {
1467                                 memcpy(req->buf, buf, n);
1468                                 req->complete = rndis_response_complete;
1469                                 rndis_free_response(dev->rndis_config, buf);
1470                                 value = n;
1471                         }
1472                         /* else stalls ... spec says to avoid that */
1473                 }
1474                 break;
1475 #endif  /* RNDIS */
1476
1477         default:
1478                 debug("unknown control req%02x.%02x v%04x i%04x l%d\n",
1479                         ctrl->bRequestType, ctrl->bRequest,
1480                         wValue, wIndex, wLength);
1481         }
1482
1483         /* respond with data transfer before status phase? */
1484         if (value >= 0) {
1485                 debug("respond with data transfer before status phase\n");
1486                 req->length = value;
1487                 req->zero = value < wLength
1488                                 && (value % gadget->ep0->maxpacket) == 0;
1489                 value = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);
1490                 if (value < 0) {
1491                         debug("ep_queue --> %d\n", value);
1492                         req->status = 0;
1493                         eth_setup_complete(gadget->ep0, req);
1494                 }
1495         }
1496
1497         /* host either stalls (value < 0) or reports success */
1498         return value;
1499 }
1500
1501 /*-------------------------------------------------------------------------*/
1502
1503 static void rx_complete(struct usb_ep *ep, struct usb_request *req);
1504
1505 static int rx_submit(struct eth_dev *dev, struct usb_request *req,
1506                                 gfp_t gfp_flags)
1507 {
1508         int                     retval = -ENOMEM;
1509         size_t                  size;
1510
1511         /*
1512          * Padding up to RX_EXTRA handles minor disagreements with host.
1513          * Normally we use the USB "terminate on short read" convention;
1514          * so allow up to (N*maxpacket), since that memory is normally
1515          * already allocated.  Some hardware doesn't deal well with short
1516          * reads (e.g. DMA must be N*maxpacket), so for now don't trim a
1517          * byte off the end (to force hardware errors on overflow).
1518          *
1519          * RNDIS uses internal framing, and explicitly allows senders to
1520          * pad to end-of-packet.  That's potentially nice for speed,
1521          * but means receivers can't recover synch on their own.
1522          */
1523
1524         debug("%s\n", __func__);
1525         if (!req)
1526                 return -EINVAL;
1527
1528         size = (ETHER_HDR_SIZE + dev->mtu + RX_EXTRA);
1529         size += dev->out_ep->maxpacket - 1;
1530         if (rndis_active(dev))
1531                 size += sizeof(struct rndis_packet_msg_type);
1532         size -= size % dev->out_ep->maxpacket;
1533
1534         /*
1535          * Some platforms perform better when IP packets are aligned,
1536          * but on at least one, checksumming fails otherwise.  Note:
1537          * RNDIS headers involve variable numbers of LE32 values.
1538          */
1539
1540         req->buf = (u8 *)net_rx_packets[0];
1541         req->length = size;
1542         req->complete = rx_complete;
1543
1544         retval = usb_ep_queue(dev->out_ep, req, gfp_flags);
1545
1546         if (retval)
1547                 error("rx submit --> %d", retval);
1548
1549         return retval;
1550 }
1551
1552 static void rx_complete(struct usb_ep *ep, struct usb_request *req)
1553 {
1554         struct eth_dev  *dev = ep->driver_data;
1555
1556         debug("%s: status %d\n", __func__, req->status);
1557         switch (req->status) {
1558         /* normal completion */
1559         case 0:
1560                 if (rndis_active(dev)) {
1561                         /* we know MaxPacketsPerTransfer == 1 here */
1562                         int length = rndis_rm_hdr(req->buf, req->actual);
1563                         if (length < 0)
1564                                 goto length_err;
1565                         req->length -= length;
1566                         req->actual -= length;
1567                 }
1568                 if (req->actual < ETH_HLEN || ETH_FRAME_LEN < req->actual) {
1569 length_err:
1570                         dev->stats.rx_errors++;
1571                         dev->stats.rx_length_errors++;
1572                         debug("rx length %d\n", req->length);
1573                         break;
1574                 }
1575
1576                 dev->stats.rx_packets++;
1577                 dev->stats.rx_bytes += req->length;
1578                 break;
1579
1580         /* software-driven interface shutdown */
1581         case -ECONNRESET:               /* unlink */
1582         case -ESHUTDOWN:                /* disconnect etc */
1583         /* for hardware automagic (such as pxa) */
1584         case -ECONNABORTED:             /* endpoint reset */
1585                 break;
1586
1587         /* data overrun */
1588         case -EOVERFLOW:
1589                 dev->stats.rx_over_errors++;
1590                 /* FALLTHROUGH */
1591         default:
1592                 dev->stats.rx_errors++;
1593                 break;
1594         }
1595
1596         packet_received = 1;
1597 }
1598
1599 static int alloc_requests(struct eth_dev *dev, unsigned n, gfp_t gfp_flags)
1600 {
1601
1602         dev->tx_req = usb_ep_alloc_request(dev->in_ep, 0);
1603
1604         if (!dev->tx_req)
1605                 goto fail1;
1606
1607         dev->rx_req = usb_ep_alloc_request(dev->out_ep, 0);
1608
1609         if (!dev->rx_req)
1610                 goto fail2;
1611
1612         return 0;
1613
1614 fail2:
1615         usb_ep_free_request(dev->in_ep, dev->tx_req);
1616 fail1:
1617         error("can't alloc requests");
1618         return -1;
1619 }
1620
1621 static void tx_complete(struct usb_ep *ep, struct usb_request *req)
1622 {
1623         struct eth_dev  *dev = ep->driver_data;
1624
1625         debug("%s: status %s\n", __func__, (req->status) ? "failed" : "ok");
1626         switch (req->status) {
1627         default:
1628                 dev->stats.tx_errors++;
1629                 debug("tx err %d\n", req->status);
1630                 /* FALLTHROUGH */
1631         case -ECONNRESET:               /* unlink */
1632         case -ESHUTDOWN:                /* disconnect etc */
1633                 break;
1634         case 0:
1635                 dev->stats.tx_bytes += req->length;
1636         }
1637         dev->stats.tx_packets++;
1638
1639         packet_sent = 1;
1640 }
1641
1642 static inline int eth_is_promisc(struct eth_dev *dev)
1643 {
1644         /* no filters for the CDC subset; always promisc */
1645         if (subset_active(dev))
1646                 return 1;
1647         return dev->cdc_filter & USB_CDC_PACKET_TYPE_PROMISCUOUS;
1648 }
1649
1650 #if 0
1651 static int eth_start_xmit (struct sk_buff *skb, struct net_device *net)
1652 {
1653         struct eth_dev          *dev = netdev_priv(net);
1654         int                     length = skb->len;
1655         int                     retval;
1656         struct usb_request      *req = NULL;
1657         unsigned long           flags;
1658
1659         /* apply outgoing CDC or RNDIS filters */
1660         if (!eth_is_promisc (dev)) {
1661                 u8              *dest = skb->data;
1662
1663                 if (is_multicast_ethaddr(dest)) {
1664                         u16     type;
1665
1666                         /* ignores USB_CDC_PACKET_TYPE_MULTICAST and host
1667                          * SET_ETHERNET_MULTICAST_FILTERS requests
1668                          */
1669                         if (is_broadcast_ethaddr(dest))
1670                                 type = USB_CDC_PACKET_TYPE_BROADCAST;
1671                         else
1672                                 type = USB_CDC_PACKET_TYPE_ALL_MULTICAST;
1673                         if (!(dev->cdc_filter & type)) {
1674                                 dev_kfree_skb_any (skb);
1675                                 return 0;
1676                         }
1677                 }
1678                 /* ignores USB_CDC_PACKET_TYPE_DIRECTED */
1679         }
1680
1681         spin_lock_irqsave(&dev->req_lock, flags);
1682         /*
1683          * this freelist can be empty if an interrupt triggered disconnect()
1684          * and reconfigured the gadget (shutting down this queue) after the
1685          * network stack decided to xmit but before we got the spinlock.
1686          */
1687         if (list_empty(&dev->tx_reqs)) {
1688                 spin_unlock_irqrestore(&dev->req_lock, flags);
1689                 return 1;
1690         }
1691
1692         req = container_of (dev->tx_reqs.next, struct usb_request, list);
1693         list_del (&req->list);
1694
1695         /* temporarily stop TX queue when the freelist empties */
1696         if (list_empty (&dev->tx_reqs))
1697                 netif_stop_queue (net);
1698         spin_unlock_irqrestore(&dev->req_lock, flags);
1699
1700         /* no buffer copies needed, unless the network stack did it
1701          * or the hardware can't use skb buffers.
1702          * or there's not enough space for any RNDIS headers we need
1703          */
1704         if (rndis_active(dev)) {
1705                 struct sk_buff  *skb_rndis;
1706
1707                 skb_rndis = skb_realloc_headroom (skb,
1708                                 sizeof (struct rndis_packet_msg_type));
1709                 if (!skb_rndis)
1710                         goto drop;
1711
1712                 dev_kfree_skb_any (skb);
1713                 skb = skb_rndis;
1714                 rndis_add_hdr (skb);
1715                 length = skb->len;
1716         }
1717         req->buf = skb->data;
1718         req->context = skb;
1719         req->complete = tx_complete;
1720
1721         /* use zlp framing on tx for strict CDC-Ether conformance,
1722          * though any robust network rx path ignores extra padding.
1723          * and some hardware doesn't like to write zlps.
1724          */
1725         req->zero = 1;
1726         if (!dev->zlp && (length % dev->in_ep->maxpacket) == 0)
1727                 length++;
1728
1729         req->length = length;
1730
1731         /* throttle highspeed IRQ rate back slightly */
1732         if (gadget_is_dualspeed(dev->gadget))
1733                 req->no_interrupt = (dev->gadget->speed == USB_SPEED_HIGH)
1734                         ? ((atomic_read(&dev->tx_qlen) % qmult) != 0)
1735                         : 0;
1736
1737         retval = usb_ep_queue (dev->in_ep, req, GFP_ATOMIC);
1738         switch (retval) {
1739         default:
1740                 DEBUG (dev, "tx queue err %d\n", retval);
1741                 break;
1742         case 0:
1743                 net->trans_start = jiffies;
1744                 atomic_inc (&dev->tx_qlen);
1745         }
1746
1747         if (retval) {
1748 drop:
1749                 dev->stats.tx_dropped++;
1750                 dev_kfree_skb_any (skb);
1751                 spin_lock_irqsave(&dev->req_lock, flags);
1752                 if (list_empty (&dev->tx_reqs))
1753                         netif_start_queue (net);
1754                 list_add (&req->list, &dev->tx_reqs);
1755                 spin_unlock_irqrestore(&dev->req_lock, flags);
1756         }
1757         return 0;
1758 }
1759
1760 /*-------------------------------------------------------------------------*/
1761 #endif
1762
1763 static void eth_unbind(struct usb_gadget *gadget)
1764 {
1765         struct eth_dev          *dev = get_gadget_data(gadget);
1766
1767         debug("%s...\n", __func__);
1768         rndis_deregister(dev->rndis_config);
1769         rndis_exit();
1770
1771         /* we've already been disconnected ... no i/o is active */
1772         if (dev->req) {
1773                 usb_ep_free_request(gadget->ep0, dev->req);
1774                 dev->req = NULL;
1775         }
1776         if (dev->stat_req) {
1777                 usb_ep_free_request(dev->status_ep, dev->stat_req);
1778                 dev->stat_req = NULL;
1779         }
1780
1781         if (dev->tx_req) {
1782                 usb_ep_free_request(dev->in_ep, dev->tx_req);
1783                 dev->tx_req = NULL;
1784         }
1785
1786         if (dev->rx_req) {
1787                 usb_ep_free_request(dev->out_ep, dev->rx_req);
1788                 dev->rx_req = NULL;
1789         }
1790
1791 /*      unregister_netdev (dev->net);*/
1792 /*      free_netdev(dev->net);*/
1793
1794         dev->gadget = NULL;
1795         set_gadget_data(gadget, NULL);
1796 }
1797
1798 static void eth_disconnect(struct usb_gadget *gadget)
1799 {
1800         eth_reset_config(get_gadget_data(gadget));
1801         /* FIXME RNDIS should enter RNDIS_UNINITIALIZED */
1802 }
1803
1804 static void eth_suspend(struct usb_gadget *gadget)
1805 {
1806         /* Not used */
1807 }
1808
1809 static void eth_resume(struct usb_gadget *gadget)
1810 {
1811         /* Not used */
1812 }
1813
1814 /*-------------------------------------------------------------------------*/
1815
1816 #ifdef CONFIG_USB_ETH_RNDIS
1817
1818 /*
1819  * The interrupt endpoint is used in RNDIS to notify the host when messages
1820  * other than data packets are available ... notably the REMOTE_NDIS_*_CMPLT
1821  * messages, but also REMOTE_NDIS_INDICATE_STATUS_MSG and potentially even
1822  * REMOTE_NDIS_KEEPALIVE_MSG.
1823  *
1824  * The RNDIS control queue is processed by GET_ENCAPSULATED_RESPONSE, and
1825  * normally just one notification will be queued.
1826  */
1827
1828 static void rndis_control_ack_complete(struct usb_ep *ep,
1829                                         struct usb_request *req)
1830 {
1831         struct eth_dev          *dev = ep->driver_data;
1832
1833         debug("%s...\n", __func__);
1834         if (req->status || req->actual != req->length)
1835                 debug("rndis control ack complete --> %d, %d/%d\n",
1836                         req->status, req->actual, req->length);
1837
1838         if (!dev->network_started) {
1839                 if (rndis_get_state(dev->rndis_config)
1840                                 == RNDIS_DATA_INITIALIZED) {
1841                         dev->network_started = 1;
1842                         printf("USB RNDIS network up!\n");
1843                 }
1844         }
1845
1846         req->context = NULL;
1847
1848         if (req != dev->stat_req)
1849                 usb_ep_free_request(ep, req);
1850 }
1851
1852 static char rndis_resp_buf[8] __attribute__((aligned(sizeof(__le32))));
1853
1854 static int rndis_control_ack(struct eth_device *net)
1855 {
1856         struct ether_priv       *priv = (struct ether_priv *)net->priv;
1857         struct eth_dev          *dev = &priv->ethdev;
1858         int                     length;
1859         struct usb_request      *resp = dev->stat_req;
1860
1861         /* in case RNDIS calls this after disconnect */
1862         if (!dev->status) {
1863                 debug("status ENODEV\n");
1864                 return -ENODEV;
1865         }
1866
1867         /* in case queue length > 1 */
1868         if (resp->context) {
1869                 resp = usb_ep_alloc_request(dev->status_ep, GFP_ATOMIC);
1870                 if (!resp)
1871                         return -ENOMEM;
1872                 resp->buf = rndis_resp_buf;
1873         }
1874
1875         /*
1876          * Send RNDIS RESPONSE_AVAILABLE notification;
1877          * USB_CDC_NOTIFY_RESPONSE_AVAILABLE should work too
1878          */
1879         resp->length = 8;
1880         resp->complete = rndis_control_ack_complete;
1881         resp->context = dev;
1882
1883         *((__le32 *) resp->buf) = __constant_cpu_to_le32(1);
1884         *((__le32 *) (resp->buf + 4)) = __constant_cpu_to_le32(0);
1885
1886         length = usb_ep_queue(dev->status_ep, resp, GFP_ATOMIC);
1887         if (length < 0) {
1888                 resp->status = 0;
1889                 rndis_control_ack_complete(dev->status_ep, resp);
1890         }
1891
1892         return 0;
1893 }
1894
1895 #else
1896
1897 #define rndis_control_ack       NULL
1898
1899 #endif  /* RNDIS */
1900
1901 static void eth_start(struct eth_dev *dev, gfp_t gfp_flags)
1902 {
1903         if (rndis_active(dev)) {
1904                 rndis_set_param_medium(dev->rndis_config,
1905                                         NDIS_MEDIUM_802_3,
1906                                         BITRATE(dev->gadget)/100);
1907                 rndis_signal_connect(dev->rndis_config);
1908         }
1909 }
1910
1911 static int eth_stop(struct eth_dev *dev)
1912 {
1913 #ifdef RNDIS_COMPLETE_SIGNAL_DISCONNECT
1914         unsigned long ts;
1915         unsigned long timeout = CONFIG_SYS_HZ; /* 1 sec to stop RNDIS */
1916 #endif
1917
1918         if (rndis_active(dev)) {
1919                 rndis_set_param_medium(dev->rndis_config, NDIS_MEDIUM_802_3, 0);
1920                 rndis_signal_disconnect(dev->rndis_config);
1921
1922 #ifdef RNDIS_COMPLETE_SIGNAL_DISCONNECT
1923                 /* Wait until host receives OID_GEN_MEDIA_CONNECT_STATUS */
1924                 ts = get_timer(0);
1925                 while (get_timer(ts) < timeout)
1926                         usb_gadget_handle_interrupts(0);
1927 #endif
1928
1929                 rndis_uninit(dev->rndis_config);
1930                 dev->rndis = 0;
1931         }
1932
1933         return 0;
1934 }
1935
1936 /*-------------------------------------------------------------------------*/
1937
1938 static int is_eth_addr_valid(char *str)
1939 {
1940         if (strlen(str) == 17) {
1941                 int i;
1942                 char *p, *q;
1943                 uchar ea[6];
1944
1945                 /* see if it looks like an ethernet address */
1946
1947                 p = str;
1948
1949                 for (i = 0; i < 6; i++) {
1950                         char term = (i == 5 ? '\0' : ':');
1951
1952                         ea[i] = simple_strtol(p, &q, 16);
1953
1954                         if ((q - p) != 2 || *q++ != term)
1955                                 break;
1956
1957                         p = q;
1958                 }
1959
1960                 /* Now check the contents. */
1961                 return is_valid_ethaddr(ea);
1962         }
1963         return 0;
1964 }
1965
1966 static u8 nibble(unsigned char c)
1967 {
1968         if (likely(isdigit(c)))
1969                 return c - '0';
1970         c = toupper(c);
1971         if (likely(isxdigit(c)))
1972                 return 10 + c - 'A';
1973         return 0;
1974 }
1975
1976 static int get_ether_addr(const char *str, u8 *dev_addr)
1977 {
1978         if (str) {
1979                 unsigned        i;
1980
1981                 for (i = 0; i < 6; i++) {
1982                         unsigned char num;
1983
1984                         if ((*str == '.') || (*str == ':'))
1985                                 str++;
1986                         num = nibble(*str++) << 4;
1987                         num |= (nibble(*str++));
1988                         dev_addr[i] = num;
1989                 }
1990                 if (is_valid_ethaddr(dev_addr))
1991                         return 0;
1992         }
1993         return 1;
1994 }
1995
1996 static int eth_bind(struct usb_gadget *gadget)
1997 {
1998         struct eth_dev          *dev = &l_priv->ethdev;
1999         u8                      cdc = 1, zlp = 1, rndis = 1;
2000         struct usb_ep           *in_ep, *out_ep, *status_ep = NULL;
2001         int                     status = -ENOMEM;
2002         int                     gcnum;
2003         u8                      tmp[7];
2004
2005         /* these flags are only ever cleared; compiler take note */
2006 #ifndef CONFIG_USB_ETH_CDC
2007         cdc = 0;
2008 #endif
2009 #ifndef CONFIG_USB_ETH_RNDIS
2010         rndis = 0;
2011 #endif
2012         /*
2013          * Because most host side USB stacks handle CDC Ethernet, that
2014          * standard protocol is _strongly_ preferred for interop purposes.
2015          * (By everyone except Microsoft.)
2016          */
2017         if (gadget_is_pxa(gadget)) {
2018                 /* pxa doesn't support altsettings */
2019                 cdc = 0;
2020         } else if (gadget_is_musbhdrc(gadget)) {
2021                 /* reduce tx dma overhead by avoiding special cases */
2022                 zlp = 0;
2023         } else if (gadget_is_sh(gadget)) {
2024                 /* sh doesn't support multiple interfaces or configs */
2025                 cdc = 0;
2026                 rndis = 0;
2027         } else if (gadget_is_sa1100(gadget)) {
2028                 /* hardware can't write zlps */
2029                 zlp = 0;
2030                 /*
2031                  * sa1100 CAN do CDC, without status endpoint ... we use
2032                  * non-CDC to be compatible with ARM Linux-2.4 "usb-eth".
2033                  */
2034                 cdc = 0;
2035         }
2036
2037         gcnum = usb_gadget_controller_number(gadget);
2038         if (gcnum >= 0)
2039                 device_desc.bcdDevice = cpu_to_le16(0x0300 + gcnum);
2040         else {
2041                 /*
2042                  * can't assume CDC works.  don't want to default to
2043                  * anything less functional on CDC-capable hardware,
2044                  * so we fail in this case.
2045                  */
2046                 error("controller '%s' not recognized",
2047                         gadget->name);
2048                 return -ENODEV;
2049         }
2050
2051         /*
2052          * If there's an RNDIS configuration, that's what Windows wants to
2053          * be using ... so use these product IDs here and in the "linux.inf"
2054          * needed to install MSFT drivers.  Current Linux kernels will use
2055          * the second configuration if it's CDC Ethernet, and need some help
2056          * to choose the right configuration otherwise.
2057          */
2058         if (rndis) {
2059 #if defined(CONFIG_USB_RNDIS_VENDOR_ID) && defined(CONFIG_USB_RNDIS_PRODUCT_ID)
2060                 device_desc.idVendor =
2061                         __constant_cpu_to_le16(CONFIG_USB_RNDIS_VENDOR_ID);
2062                 device_desc.idProduct =
2063                         __constant_cpu_to_le16(CONFIG_USB_RNDIS_PRODUCT_ID);
2064 #else
2065                 device_desc.idVendor =
2066                         __constant_cpu_to_le16(RNDIS_VENDOR_NUM);
2067                 device_desc.idProduct =
2068                         __constant_cpu_to_le16(RNDIS_PRODUCT_NUM);
2069 #endif
2070                 sprintf(product_desc, "RNDIS/%s", driver_desc);
2071
2072         /*
2073          * CDC subset ... recognized by Linux since 2.4.10, but Windows
2074          * drivers aren't widely available.  (That may be improved by
2075          * supporting one submode of the "SAFE" variant of MDLM.)
2076          */
2077         } else {
2078 #if defined(CONFIG_USB_CDC_VENDOR_ID) && defined(CONFIG_USB_CDC_PRODUCT_ID)
2079                 device_desc.idVendor = cpu_to_le16(CONFIG_USB_CDC_VENDOR_ID);
2080                 device_desc.idProduct = cpu_to_le16(CONFIG_USB_CDC_PRODUCT_ID);
2081 #else
2082                 if (!cdc) {
2083                         device_desc.idVendor =
2084                                 __constant_cpu_to_le16(SIMPLE_VENDOR_NUM);
2085                         device_desc.idProduct =
2086                                 __constant_cpu_to_le16(SIMPLE_PRODUCT_NUM);
2087                 }
2088 #endif
2089         }
2090         /* support optional vendor/distro customization */
2091         if (bcdDevice)
2092                 device_desc.bcdDevice = cpu_to_le16(bcdDevice);
2093         if (iManufacturer)
2094                 strlcpy(manufacturer, iManufacturer, sizeof manufacturer);
2095         if (iProduct)
2096                 strlcpy(product_desc, iProduct, sizeof product_desc);
2097         if (iSerialNumber) {
2098                 device_desc.iSerialNumber = STRING_SERIALNUMBER,
2099                 strlcpy(serial_number, iSerialNumber, sizeof serial_number);
2100         }
2101
2102         /* all we really need is bulk IN/OUT */
2103         usb_ep_autoconfig_reset(gadget);
2104         in_ep = usb_ep_autoconfig(gadget, &fs_source_desc);
2105         if (!in_ep) {
2106 autoconf_fail:
2107                 error("can't autoconfigure on %s\n",
2108                         gadget->name);
2109                 return -ENODEV;
2110         }
2111         in_ep->driver_data = in_ep;     /* claim */
2112
2113         out_ep = usb_ep_autoconfig(gadget, &fs_sink_desc);
2114         if (!out_ep)
2115                 goto autoconf_fail;
2116         out_ep->driver_data = out_ep;   /* claim */
2117
2118 #if defined(CONFIG_USB_ETH_CDC) || defined(CONFIG_USB_ETH_RNDIS)
2119         /*
2120          * CDC Ethernet control interface doesn't require a status endpoint.
2121          * Since some hosts expect one, try to allocate one anyway.
2122          */
2123         if (cdc || rndis) {
2124                 status_ep = usb_ep_autoconfig(gadget, &fs_status_desc);
2125                 if (status_ep) {
2126                         status_ep->driver_data = status_ep;     /* claim */
2127                 } else if (rndis) {
2128                         error("can't run RNDIS on %s", gadget->name);
2129                         return -ENODEV;
2130 #ifdef CONFIG_USB_ETH_CDC
2131                 } else if (cdc) {
2132                         control_intf.bNumEndpoints = 0;
2133                         /* FIXME remove endpoint from descriptor list */
2134 #endif
2135                 }
2136         }
2137 #endif
2138
2139         /* one config:  cdc, else minimal subset */
2140         if (!cdc) {
2141                 eth_config.bNumInterfaces = 1;
2142                 eth_config.iConfiguration = STRING_SUBSET;
2143
2144                 /*
2145                  * use functions to set these up, in case we're built to work
2146                  * with multiple controllers and must override CDC Ethernet.
2147                  */
2148                 fs_subset_descriptors();
2149                 hs_subset_descriptors();
2150         }
2151
2152         usb_gadget_set_selfpowered(gadget);
2153
2154         /* For now RNDIS is always a second config */
2155         if (rndis)
2156                 device_desc.bNumConfigurations = 2;
2157
2158         if (gadget_is_dualspeed(gadget)) {
2159                 if (rndis)
2160                         dev_qualifier.bNumConfigurations = 2;
2161                 else if (!cdc)
2162                         dev_qualifier.bDeviceClass = USB_CLASS_VENDOR_SPEC;
2163
2164                 /* assumes ep0 uses the same value for both speeds ... */
2165                 dev_qualifier.bMaxPacketSize0 = device_desc.bMaxPacketSize0;
2166
2167                 /* and that all endpoints are dual-speed */
2168                 hs_source_desc.bEndpointAddress =
2169                                 fs_source_desc.bEndpointAddress;
2170                 hs_sink_desc.bEndpointAddress =
2171                                 fs_sink_desc.bEndpointAddress;
2172 #if defined(CONFIG_USB_ETH_CDC) || defined(CONFIG_USB_ETH_RNDIS)
2173                 if (status_ep)
2174                         hs_status_desc.bEndpointAddress =
2175                                         fs_status_desc.bEndpointAddress;
2176 #endif
2177         }
2178
2179         if (gadget_is_otg(gadget)) {
2180                 otg_descriptor.bmAttributes |= USB_OTG_HNP,
2181                 eth_config.bmAttributes |= USB_CONFIG_ATT_WAKEUP;
2182                 eth_config.bMaxPower = 4;
2183 #ifdef  CONFIG_USB_ETH_RNDIS
2184                 rndis_config.bmAttributes |= USB_CONFIG_ATT_WAKEUP;
2185                 rndis_config.bMaxPower = 4;
2186 #endif
2187         }
2188
2189
2190         /* network device setup */
2191         dev->net = &l_priv->netdev;
2192
2193         dev->cdc = cdc;
2194         dev->zlp = zlp;
2195
2196         dev->in_ep = in_ep;
2197         dev->out_ep = out_ep;
2198         dev->status_ep = status_ep;
2199
2200         /*
2201          * Module params for these addresses should come from ID proms.
2202          * The host side address is used with CDC and RNDIS, and commonly
2203          * ends up in a persistent config database.  It's not clear if
2204          * host side code for the SAFE thing cares -- its original BLAN
2205          * thing didn't, Sharp never assigned those addresses on Zaurii.
2206          */
2207         get_ether_addr(dev_addr, dev->net->enetaddr);
2208
2209         memset(tmp, 0, sizeof(tmp));
2210         memcpy(tmp, dev->net->enetaddr, sizeof(dev->net->enetaddr));
2211
2212         get_ether_addr(host_addr, dev->host_mac);
2213
2214         sprintf(ethaddr, "%02X%02X%02X%02X%02X%02X",
2215                 dev->host_mac[0], dev->host_mac[1],
2216                         dev->host_mac[2], dev->host_mac[3],
2217                         dev->host_mac[4], dev->host_mac[5]);
2218
2219         if (rndis) {
2220                 status = rndis_init();
2221                 if (status < 0) {
2222                         error("can't init RNDIS, %d", status);
2223                         goto fail;
2224                 }
2225         }
2226
2227         /*
2228          * use PKTSIZE (or aligned... from u-boot) and set
2229          * wMaxSegmentSize accordingly
2230          */
2231         dev->mtu = PKTSIZE_ALIGN; /* RNDIS does not like this, only 1514, TODO*/
2232
2233         /* preallocate control message data and buffer */
2234         dev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
2235         if (!dev->req)
2236                 goto fail;
2237         dev->req->buf = control_req;
2238         dev->req->complete = eth_setup_complete;
2239
2240         /* ... and maybe likewise for status transfer */
2241 #if defined(CONFIG_USB_ETH_CDC) || defined(CONFIG_USB_ETH_RNDIS)
2242         if (dev->status_ep) {
2243                 dev->stat_req = usb_ep_alloc_request(dev->status_ep,
2244                                                         GFP_KERNEL);
2245                 if (!dev->stat_req) {
2246                         usb_ep_free_request(dev->status_ep, dev->req);
2247
2248                         goto fail;
2249                 }
2250                 dev->stat_req->buf = status_req;
2251                 dev->stat_req->context = NULL;
2252         }
2253 #endif
2254
2255         /* finish hookup to lower layer ... */
2256         dev->gadget = gadget;
2257         set_gadget_data(gadget, dev);
2258         gadget->ep0->driver_data = dev;
2259
2260         /*
2261          * two kinds of host-initiated state changes:
2262          *  - iff DATA transfer is active, carrier is "on"
2263          *  - tx queueing enabled if open *and* carrier is "on"
2264          */
2265
2266         printf("using %s, OUT %s IN %s%s%s\n", gadget->name,
2267                 out_ep->name, in_ep->name,
2268                 status_ep ? " STATUS " : "",
2269                 status_ep ? status_ep->name : ""
2270                 );
2271         printf("MAC %02x:%02x:%02x:%02x:%02x:%02x\n",
2272                 dev->net->enetaddr[0], dev->net->enetaddr[1],
2273                 dev->net->enetaddr[2], dev->net->enetaddr[3],
2274                 dev->net->enetaddr[4], dev->net->enetaddr[5]);
2275
2276         if (cdc || rndis)
2277                 printf("HOST MAC %02x:%02x:%02x:%02x:%02x:%02x\n",
2278                         dev->host_mac[0], dev->host_mac[1],
2279                         dev->host_mac[2], dev->host_mac[3],
2280                         dev->host_mac[4], dev->host_mac[5]);
2281
2282         if (rndis) {
2283                 u32     vendorID = 0;
2284
2285                 /* FIXME RNDIS vendor id == "vendor NIC code" == ? */
2286
2287                 dev->rndis_config = rndis_register(rndis_control_ack);
2288                 if (dev->rndis_config < 0) {
2289 fail0:
2290                         eth_unbind(gadget);
2291                         debug("RNDIS setup failed\n");
2292                         status = -ENODEV;
2293                         goto fail;
2294                 }
2295
2296                 /* these set up a lot of the OIDs that RNDIS needs */
2297                 rndis_set_host_mac(dev->rndis_config, dev->host_mac);
2298                 if (rndis_set_param_dev(dev->rndis_config, dev->net, dev->mtu,
2299                                         &dev->stats, &dev->cdc_filter))
2300                         goto fail0;
2301                 if (rndis_set_param_vendor(dev->rndis_config, vendorID,
2302                                         manufacturer))
2303                         goto fail0;
2304                 if (rndis_set_param_medium(dev->rndis_config,
2305                                         NDIS_MEDIUM_802_3, 0))
2306                         goto fail0;
2307                 printf("RNDIS ready\n");
2308         }
2309         return 0;
2310
2311 fail:
2312         error("%s failed, status = %d", __func__, status);
2313         eth_unbind(gadget);
2314         return status;
2315 }
2316
2317 /*-------------------------------------------------------------------------*/
2318
2319 #ifdef CONFIG_DM_USB
2320 int dm_usb_init(struct eth_dev *e_dev)
2321 {
2322         struct udevice *dev = NULL;
2323         int ret;
2324
2325         ret = uclass_first_device(UCLASS_USB_DEV_GENERIC, &dev);
2326         if (!dev || ret) {
2327                 error("No USB device found\n");
2328                 return -ENODEV;
2329         }
2330
2331         e_dev->usb_udev = dev;
2332
2333         return ret;
2334 }
2335 #endif
2336
2337 static int usb_eth_init(struct eth_device *netdev, bd_t *bd)
2338 {
2339         struct ether_priv *priv = (struct ether_priv *)netdev->priv;
2340         struct eth_dev *dev = &priv->ethdev;
2341         struct usb_gadget *gadget;
2342         unsigned long ts;
2343         unsigned long timeout = USB_CONNECT_TIMEOUT;
2344
2345 #ifdef CONFIG_DM_USB
2346         if (dm_usb_init(dev)) {
2347                 error("USB ether not found\n");
2348                 return -ENODEV;
2349         }
2350 #else
2351         board_usb_init(0, USB_INIT_DEVICE);
2352 #endif
2353
2354         /* Configure default mac-addresses for the USB ethernet device */
2355 #ifdef CONFIG_USBNET_DEV_ADDR
2356         strlcpy(dev_addr, CONFIG_USBNET_DEV_ADDR, sizeof(dev_addr));
2357 #endif
2358 #ifdef CONFIG_USBNET_HOST_ADDR
2359         strlcpy(host_addr, CONFIG_USBNET_HOST_ADDR, sizeof(host_addr));
2360 #endif
2361         /* Check if the user overruled the MAC addresses */
2362         if (getenv("usbnet_devaddr"))
2363                 strlcpy(dev_addr, getenv("usbnet_devaddr"),
2364                         sizeof(dev_addr));
2365
2366         if (getenv("usbnet_hostaddr"))
2367                 strlcpy(host_addr, getenv("usbnet_hostaddr"),
2368                         sizeof(host_addr));
2369
2370         if (!is_eth_addr_valid(dev_addr)) {
2371                 error("Need valid 'usbnet_devaddr' to be set");
2372                 goto fail;
2373         }
2374         if (!is_eth_addr_valid(host_addr)) {
2375                 error("Need valid 'usbnet_hostaddr' to be set");
2376                 goto fail;
2377         }
2378
2379         priv->eth_driver.speed          = DEVSPEED;
2380         priv->eth_driver.bind           = eth_bind;
2381         priv->eth_driver.unbind         = eth_unbind;
2382         priv->eth_driver.setup          = eth_setup;
2383         priv->eth_driver.reset          = eth_disconnect;
2384         priv->eth_driver.disconnect     = eth_disconnect;
2385         priv->eth_driver.suspend        = eth_suspend;
2386         priv->eth_driver.resume         = eth_resume;
2387         if (usb_gadget_register_driver(&priv->eth_driver) < 0)
2388                 goto fail;
2389
2390         dev->network_started = 0;
2391
2392         packet_received = 0;
2393         packet_sent = 0;
2394
2395         gadget = dev->gadget;
2396         usb_gadget_connect(gadget);
2397
2398         if (getenv("cdc_connect_timeout"))
2399                 timeout = simple_strtoul(getenv("cdc_connect_timeout"),
2400                                                 NULL, 10) * CONFIG_SYS_HZ;
2401         ts = get_timer(0);
2402         while (!dev->network_started) {
2403                 /* Handle control-c and timeouts */
2404                 if (ctrlc() || (get_timer(ts) > timeout)) {
2405                         error("The remote end did not respond in time.");
2406                         goto fail;
2407                 }
2408                 usb_gadget_handle_interrupts(0);
2409         }
2410
2411         packet_received = 0;
2412         rx_submit(dev, dev->rx_req, 0);
2413         return 0;
2414 fail:
2415         return -1;
2416 }
2417
2418 static int usb_eth_send(struct eth_device *netdev, void *packet, int length)
2419 {
2420         int                     retval;
2421         void                    *rndis_pkt = NULL;
2422         struct ether_priv       *priv = (struct ether_priv *)netdev->priv;
2423         struct eth_dev          *dev = &priv->ethdev;
2424         struct usb_request      *req = dev->tx_req;
2425         unsigned long ts;
2426         unsigned long timeout = USB_CONNECT_TIMEOUT;
2427
2428         debug("%s:...\n", __func__);
2429
2430         /* new buffer is needed to include RNDIS header */
2431         if (rndis_active(dev)) {
2432                 rndis_pkt = malloc(length +
2433                                         sizeof(struct rndis_packet_msg_type));
2434                 if (!rndis_pkt) {
2435                         error("No memory to alloc RNDIS packet");
2436                         goto drop;
2437                 }
2438                 rndis_add_hdr(rndis_pkt, length);
2439                 memcpy(rndis_pkt + sizeof(struct rndis_packet_msg_type),
2440                                 packet, length);
2441                 packet = rndis_pkt;
2442                 length += sizeof(struct rndis_packet_msg_type);
2443         }
2444         req->buf = packet;
2445         req->context = NULL;
2446         req->complete = tx_complete;
2447
2448         /*
2449          * use zlp framing on tx for strict CDC-Ether conformance,
2450          * though any robust network rx path ignores extra padding.
2451          * and some hardware doesn't like to write zlps.
2452          */
2453         req->zero = 1;
2454         if (!dev->zlp && (length % dev->in_ep->maxpacket) == 0)
2455                 length++;
2456
2457         req->length = length;
2458 #if 0
2459         /* throttle highspeed IRQ rate back slightly */
2460         if (gadget_is_dualspeed(dev->gadget))
2461                 req->no_interrupt = (dev->gadget->speed == USB_SPEED_HIGH)
2462                         ? ((dev->tx_qlen % qmult) != 0) : 0;
2463 #endif
2464         dev->tx_qlen = 1;
2465         ts = get_timer(0);
2466         packet_sent = 0;
2467
2468         retval = usb_ep_queue(dev->in_ep, req, GFP_ATOMIC);
2469
2470         if (!retval)
2471                 debug("%s: packet queued\n", __func__);
2472         while (!packet_sent) {
2473                 if (get_timer(ts) > timeout) {
2474                         printf("timeout sending packets to usb ethernet\n");
2475                         return -1;
2476                 }
2477                 usb_gadget_handle_interrupts(0);
2478         }
2479         if (rndis_pkt)
2480                 free(rndis_pkt);
2481
2482         return 0;
2483 drop:
2484         dev->stats.tx_dropped++;
2485         return -ENOMEM;
2486 }
2487
2488 static int usb_eth_recv(struct eth_device *netdev)
2489 {
2490         struct ether_priv *priv = (struct ether_priv *)netdev->priv;
2491         struct eth_dev *dev = &priv->ethdev;
2492
2493         usb_gadget_handle_interrupts(0);
2494
2495         if (packet_received) {
2496                 debug("%s: packet received\n", __func__);
2497                 if (dev->rx_req) {
2498                         net_process_received_packet(net_rx_packets[0],
2499                                                     dev->rx_req->length);
2500                         packet_received = 0;
2501
2502                         rx_submit(dev, dev->rx_req, 0);
2503                 } else
2504                         error("dev->rx_req invalid");
2505         }
2506         return 0;
2507 }
2508
2509 void usb_eth_halt(struct eth_device *netdev)
2510 {
2511         struct ether_priv *priv = (struct ether_priv *)netdev->priv;
2512         struct eth_dev *dev = &priv->ethdev;
2513
2514         /* If the gadget not registered, simple return */
2515         if (!dev->gadget)
2516                 return;
2517
2518         /*
2519          * Some USB controllers may need additional deinitialization here
2520          * before dropping pull-up (also due to hardware issues).
2521          * For example: unhandled interrupt with status stage started may
2522          * bring the controller to fully broken state (until board reset).
2523          * There are some variants to debug and fix such cases:
2524          * 1) In the case of RNDIS connection eth_stop can perform additional
2525          * interrupt handling. See RNDIS_COMPLETE_SIGNAL_DISCONNECT definition.
2526          * 2) 'pullup' callback in your UDC driver can be improved to perform
2527          * this deinitialization.
2528          */
2529         eth_stop(dev);
2530
2531         usb_gadget_disconnect(dev->gadget);
2532
2533         /* Clear pending interrupt */
2534         if (dev->network_started) {
2535                 usb_gadget_handle_interrupts(0);
2536                 dev->network_started = 0;
2537         }
2538
2539         usb_gadget_unregister_driver(&priv->eth_driver);
2540 #ifdef CONFIG_DM_USB
2541         device_remove(dev->usb_udev);
2542 #else
2543         board_usb_cleanup(0, USB_INIT_DEVICE);
2544 #endif
2545 }
2546
2547 int usb_eth_initialize(bd_t *bi)
2548 {
2549         struct eth_device *netdev = &l_priv->netdev;
2550
2551         strlcpy(netdev->name, USB_NET_NAME, sizeof(netdev->name));
2552
2553         netdev->init = usb_eth_init;
2554         netdev->send = usb_eth_send;
2555         netdev->recv = usb_eth_recv;
2556         netdev->halt = usb_eth_halt;
2557         netdev->priv = l_priv;
2558
2559 #ifdef CONFIG_MCAST_TFTP
2560   #error not supported
2561 #endif
2562         eth_register(netdev);
2563         return 0;
2564 }