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