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