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