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