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