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