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