xref: /rk3399_rockchip-uboot/drivers/usb/gadget/ether.c (revision c85d70ef64ebe5c92811113108517eaacff47f7e)
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 <linux/usb/cdc.h>
28 #include <linux/usb/gadget.h>
29 #include <net.h>
30 #include <linux/ctype.h>
31 
32 #include "gadget_chips.h"
33 
34 #define USB_NET_NAME "usb_ether"
35 
36 #define atomic_read
37 extern struct platform_data brd;
38 #define spin_lock(x)
39 #define spin_unlock(x)
40 
41 
42 unsigned packet_received, packet_sent;
43 
44 #define DEV_CONFIG_CDC	1
45 #define GFP_ATOMIC ((gfp_t) 0)
46 #define GFP_KERNEL ((gfp_t) 0)
47 
48 /*
49  * Ethernet gadget driver -- with CDC and non-CDC options
50  * Builds on hardware support for a full duplex link.
51  *
52  * CDC Ethernet is the standard USB solution for sending Ethernet frames
53  * using USB.  Real hardware tends to use the same framing protocol but look
54  * different for control features.  This driver strongly prefers to use
55  * this USB-IF standard as its open-systems interoperability solution;
56  * most host side USB stacks (except from Microsoft) support it.
57  *
58  * This is sometimes called "CDC ECM" (Ethernet Control Model) to support
59  * TLA-soup.  "CDC ACM" (Abstract Control Model) is for modems, and a new
60  * "CDC EEM" (Ethernet Emulation Model) is starting to spread.
61  *
62  * There's some hardware that can't talk CDC ECM.  We make that hardware
63  * implement a "minimalist" vendor-agnostic CDC core:  same framing, but
64  * link-level setup only requires activating the configuration.  Only the
65  * endpoint descriptors, and product/vendor IDs, are relevant; no control
66  * operations are available.  Linux supports it, but other host operating
67  * systems may not.  (This is a subset of CDC Ethernet.)
68  *
69  * It turns out that if you add a few descriptors to that "CDC Subset",
70  * (Windows) host side drivers from MCCI can treat it as one submode of
71  * a proprietary scheme called "SAFE" ... without needing to know about
72  * specific product/vendor IDs.  So we do that, making it easier to use
73  * those MS-Windows drivers.  Those added descriptors make it resemble a
74  * CDC MDLM device, but they don't change device behavior at all.  (See
75  * MCCI Engineering report 950198 "SAFE Networking Functions".)
76  *
77  * A third option is also in use.  Rather than CDC Ethernet, or something
78  * simpler, Microsoft pushes their own approach: RNDIS.  The published
79  * RNDIS specs are ambiguous and appear to be incomplete, and are also
80  * needlessly complex.  They borrow more from CDC ACM than CDC ECM.
81  */
82 #define ETH_ALEN	6		/* Octets in one ethernet addr	 */
83 #define ETH_HLEN	14		/* Total octets in header.	 */
84 #define ETH_ZLEN	60		/* Min. octets in frame sans FCS */
85 #define ETH_DATA_LEN	1500		/* Max. octets in payload	 */
86 #define ETH_FRAME_LEN	PKTSIZE_ALIGN	/* Max. octets in frame sans FCS */
87 #define ETH_FCS_LEN	4		/* Octets in the FCS		 */
88 
89 #define DRIVER_DESC		"Ethernet Gadget"
90 /* Based on linux 2.6.27 version */
91 #define DRIVER_VERSION		"May Day 2005"
92 
93 static const char shortname[] = "ether";
94 static const char driver_desc[] = DRIVER_DESC;
95 
96 #define RX_EXTRA	20		/* guard against rx overflows */
97 
98 /* CDC support the same host-chosen outgoing packet filters. */
99 #define	DEFAULT_FILTER	(USB_CDC_PACKET_TYPE_BROADCAST \
100 			|USB_CDC_PACKET_TYPE_ALL_MULTICAST \
101 			|USB_CDC_PACKET_TYPE_PROMISCUOUS \
102 			|USB_CDC_PACKET_TYPE_DIRECTED)
103 
104 #define USB_CONNECT_TIMEOUT (3 * CONFIG_SYS_HZ)
105 
106 /*-------------------------------------------------------------------------*/
107 static struct eth_dev l_ethdev;
108 static struct eth_device l_netdev;
109 static struct usb_gadget_driver eth_driver;
110 
111 /*-------------------------------------------------------------------------*/
112 
113 /* "main" config is either CDC, or its simple subset */
114 static inline int is_cdc(struct eth_dev *dev)
115 {
116 #if	!defined(DEV_CONFIG_SUBSET)
117 	return 1;		/* only cdc possible */
118 #elif	!defined(DEV_CONFIG_CDC)
119 	return 0;		/* only subset possible */
120 #else
121 	return dev->cdc;	/* depends on what hardware we found */
122 #endif
123 }
124 
125 #define	subset_active(dev)	(!is_cdc(dev))
126 #define	cdc_active(dev)		(is_cdc(dev))
127 
128 #define DEFAULT_QLEN	2	/* double buffering by default */
129 
130 /* peak bulk transfer bits-per-second */
131 #define	HS_BPS		(13 * 512 * 8 * 1000 * 8)
132 #define	FS_BPS		(19 *  64 * 1 * 1000 * 8)
133 
134 #ifdef CONFIG_USB_GADGET_DUALSPEED
135 #define	DEVSPEED	USB_SPEED_HIGH
136 
137 #ifdef CONFIG_USB_ETH_QMULT
138 #define qmult CONFIG_USB_ETH_QMULT
139 #else
140 #define qmult 5
141 #endif
142 
143 /* for dual-speed hardware, use deeper queues at highspeed */
144 #define qlen(gadget) \
145 	(DEFAULT_QLEN*((gadget->speed == USB_SPEED_HIGH) ? qmult : 1))
146 
147 static inline int BITRATE(struct usb_gadget *g)
148 {
149 	return (g->speed == USB_SPEED_HIGH) ? HS_BPS : FS_BPS;
150 }
151 
152 #else	/* full speed (low speed doesn't do bulk) */
153 
154 #define qmult		1
155 
156 #define	DEVSPEED	USB_SPEED_FULL
157 
158 #define qlen(gadget) DEFAULT_QLEN
159 
160 static inline int BITRATE(struct usb_gadget *g)
161 {
162 	return FS_BPS;
163 }
164 #endif
165 
166 struct eth_dev {
167 	struct usb_gadget	*gadget;
168 	struct usb_request	*req;		/* for control responses */
169 	struct usb_request	*stat_req;	/* for cdc status */
170 
171 	u8			config;
172 	struct usb_ep		*in_ep, *out_ep, *status_ep;
173 	const struct usb_endpoint_descriptor
174 				*in, *out, *status;
175 
176 	struct usb_request	*tx_req, *rx_req;
177 
178 	struct eth_device	*net;
179 	struct net_device_stats	stats;
180 	unsigned int		tx_qlen;
181 
182 	unsigned		zlp:1;
183 	unsigned		cdc:1;
184 	unsigned		suspended:1;
185 	unsigned		network_started:1;
186 	u16			cdc_filter;
187 	unsigned long		todo;
188 	int			mtu;
189 #define	WORK_RX_MEMORY		0
190 	u8			host_mac[ETH_ALEN];
191 };
192 
193 /*
194  * This version autoconfigures as much as possible at run-time.
195  *
196  * It also ASSUMES a self-powered device, without remote wakeup,
197  * although remote wakeup support would make sense.
198  */
199 
200 /*-------------------------------------------------------------------------*/
201 
202 /*
203  * DO NOT REUSE THESE IDs with a protocol-incompatible driver!!  Ever!!
204  * Instead:  allocate your own, using normal USB-IF procedures.
205  */
206 
207 /*
208  * Thanks to NetChip Technologies for donating this product ID.
209  * It's for devices with only CDC Ethernet configurations.
210  */
211 #define CDC_VENDOR_NUM		0x0525	/* NetChip */
212 #define CDC_PRODUCT_NUM		0xa4a1	/* Linux-USB Ethernet Gadget */
213 
214 /*
215  * For hardware that can't talk CDC, we use the same vendor ID that
216  * ARM Linux has used for ethernet-over-usb, both with sa1100 and
217  * with pxa250.  We're protocol-compatible, if the host-side drivers
218  * use the endpoint descriptors.  bcdDevice (version) is nonzero, so
219  * drivers that need to hard-wire endpoint numbers have a hook.
220  *
221  * The protocol is a minimal subset of CDC Ether, which works on any bulk
222  * hardware that's not deeply broken ... even on hardware that can't talk
223  * RNDIS (like SA-1100, with no interrupt endpoint, or anything that
224  * doesn't handle control-OUT).
225  */
226 #define	SIMPLE_VENDOR_NUM	0x049f
227 #define	SIMPLE_PRODUCT_NUM	0x505a
228 
229 /*
230  * Some systems will want different product identifers published in the
231  * device descriptor, either numbers or strings or both.  These string
232  * parameters are in UTF-8 (superset of ASCII's 7 bit characters).
233  */
234 
235 static ushort bcdDevice;
236 #if defined(CONFIG_USBNET_MANUFACTURER)
237 static char *iManufacturer = CONFIG_USBNET_MANUFACTURER;
238 #else
239 static char *iManufacturer = "U-boot";
240 #endif
241 static char *iProduct;
242 static char *iSerialNumber;
243 static char dev_addr[18];
244 static char host_addr[18];
245 
246 /*-------------------------------------------------------------------------*/
247 
248 /*
249  * USB DRIVER HOOKUP (to the hardware driver, below us), mostly
250  * ep0 implementation:  descriptors, config management, setup().
251  * also optional class-specific notification interrupt transfer.
252  */
253 
254 /*
255  * DESCRIPTORS ... most are static, but strings and (full) configuration
256  * descriptors are built on demand.  For now we do either full CDC, or
257  * our simple subset.
258  */
259 
260 #define STRING_MANUFACTURER		1
261 #define STRING_PRODUCT			2
262 #define STRING_ETHADDR			3
263 #define STRING_DATA			4
264 #define STRING_CONTROL			5
265 #define STRING_CDC			7
266 #define STRING_SUBSET			8
267 #define STRING_SERIALNUMBER		10
268 
269 /* holds our biggest descriptor */
270 #define USB_BUFSIZ	256
271 
272 /*
273  * This device advertises one configuration, eth_config,
274  * on hardware supporting at least two configs.
275  *
276  * FIXME define some higher-powered configurations to make it easier
277  * to recharge batteries ...
278  */
279 
280 #define DEV_CONFIG_VALUE	1	/* cdc or subset */
281 
282 static struct usb_device_descriptor
283 device_desc = {
284 	.bLength =		sizeof device_desc,
285 	.bDescriptorType =	USB_DT_DEVICE,
286 
287 	.bcdUSB =		__constant_cpu_to_le16(0x0200),
288 
289 	.bDeviceClass =		USB_CLASS_COMM,
290 	.bDeviceSubClass =	0,
291 	.bDeviceProtocol =	0,
292 
293 	.idVendor =		__constant_cpu_to_le16(CDC_VENDOR_NUM),
294 	.idProduct =		__constant_cpu_to_le16(CDC_PRODUCT_NUM),
295 	.iManufacturer =	STRING_MANUFACTURER,
296 	.iProduct =		STRING_PRODUCT,
297 	.bNumConfigurations =	1,
298 };
299 
300 static struct usb_otg_descriptor
301 otg_descriptor = {
302 	.bLength =		sizeof otg_descriptor,
303 	.bDescriptorType =	USB_DT_OTG,
304 
305 	.bmAttributes =		USB_OTG_SRP,
306 };
307 
308 static struct usb_config_descriptor
309 eth_config = {
310 	.bLength =		sizeof eth_config,
311 	.bDescriptorType =	USB_DT_CONFIG,
312 
313 	/* compute wTotalLength on the fly */
314 	.bNumInterfaces =	2,
315 	.bConfigurationValue =	DEV_CONFIG_VALUE,
316 	.iConfiguration =	STRING_CDC,
317 	.bmAttributes =		USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
318 	.bMaxPower =		1,
319 };
320 
321 /*
322  * Compared to the simple CDC subset, the full CDC Ethernet model adds
323  * three class descriptors, two interface descriptors, optional status
324  * endpoint.  Both have a "data" interface and two bulk endpoints.
325  * There are also differences in how control requests are handled.
326  */
327 
328 #ifdef	DEV_CONFIG_CDC
329 static struct usb_interface_descriptor
330 control_intf = {
331 	.bLength =		sizeof control_intf,
332 	.bDescriptorType =	USB_DT_INTERFACE,
333 
334 	.bInterfaceNumber =	0,
335 	/* status endpoint is optional; this may be patched later */
336 	.bNumEndpoints =	1,
337 	.bInterfaceClass =	USB_CLASS_COMM,
338 	.bInterfaceSubClass =	USB_CDC_SUBCLASS_ETHERNET,
339 	.bInterfaceProtocol =	USB_CDC_PROTO_NONE,
340 	.iInterface =		STRING_CONTROL,
341 };
342 #endif
343 
344 static const struct usb_cdc_header_desc header_desc = {
345 	.bLength =		sizeof header_desc,
346 	.bDescriptorType =	USB_DT_CS_INTERFACE,
347 	.bDescriptorSubType =	USB_CDC_HEADER_TYPE,
348 
349 	.bcdCDC =		__constant_cpu_to_le16(0x0110),
350 };
351 
352 #if defined(DEV_CONFIG_CDC)
353 
354 static const struct usb_cdc_union_desc union_desc = {
355 	.bLength =		sizeof union_desc,
356 	.bDescriptorType =	USB_DT_CS_INTERFACE,
357 	.bDescriptorSubType =	USB_CDC_UNION_TYPE,
358 
359 	.bMasterInterface0 =	0,	/* index of control interface */
360 	.bSlaveInterface0 =	1,	/* index of DATA interface */
361 };
362 
363 #endif	/* CDC */
364 
365 #ifndef DEV_CONFIG_CDC
366 
367 /*
368  * "SAFE" loosely follows CDC WMC MDLM, violating the spec in various
369  * ways:  data endpoints live in the control interface, there's no data
370  * interface, and it's not used to talk to a cell phone radio.
371  */
372 
373 static const struct usb_cdc_mdlm_desc mdlm_desc = {
374 	.bLength =		sizeof mdlm_desc,
375 	.bDescriptorType =	USB_DT_CS_INTERFACE,
376 	.bDescriptorSubType =	USB_CDC_MDLM_TYPE,
377 
378 	.bcdVersion =		__constant_cpu_to_le16(0x0100),
379 	.bGUID = {
380 		0x5d, 0x34, 0xcf, 0x66, 0x11, 0x18, 0x11, 0xd6,
381 		0xa2, 0x1a, 0x00, 0x01, 0x02, 0xca, 0x9a, 0x7f,
382 	},
383 };
384 
385 /*
386  * since "usb_cdc_mdlm_detail_desc" is a variable length structure, we
387  * can't really use its struct.  All we do here is say that we're using
388  * the submode of "SAFE" which directly matches the CDC Subset.
389  */
390 static const u8 mdlm_detail_desc[] = {
391 	6,
392 	USB_DT_CS_INTERFACE,
393 	USB_CDC_MDLM_DETAIL_TYPE,
394 
395 	0,	/* "SAFE" */
396 	0,	/* network control capabilities (none) */
397 	0,	/* network data capabilities ("raw" encapsulation) */
398 };
399 
400 #endif
401 
402 static const struct usb_cdc_ether_desc ether_desc = {
403 	.bLength =		sizeof(ether_desc),
404 	.bDescriptorType =	USB_DT_CS_INTERFACE,
405 	.bDescriptorSubType =	USB_CDC_ETHERNET_TYPE,
406 
407 	/* this descriptor actually adds value, surprise! */
408 	.iMACAddress =		STRING_ETHADDR,
409 	.bmEthernetStatistics = __constant_cpu_to_le32(0), /* no statistics */
410 	.wMaxSegmentSize =	__constant_cpu_to_le16(ETH_FRAME_LEN),
411 	.wNumberMCFilters =	__constant_cpu_to_le16(0),
412 	.bNumberPowerFilters =	0,
413 };
414 
415 #if defined(DEV_CONFIG_CDC)
416 
417 /*
418  * include the status endpoint if we can, even where it's optional.
419  * use wMaxPacketSize big enough to fit CDC_NOTIFY_SPEED_CHANGE in one
420  * packet, to simplify cancellation; and a big transfer interval, to
421  * waste less bandwidth.
422  *
423  * some drivers (like Linux 2.4 cdc-ether!) "need" it to exist even
424  * if they ignore the connect/disconnect notifications that real aether
425  * can provide.  more advanced cdc configurations might want to support
426  * encapsulated commands (vendor-specific, using control-OUT).
427  */
428 
429 #define LOG2_STATUS_INTERVAL_MSEC	5	/* 1 << 5 == 32 msec */
430 #define STATUS_BYTECOUNT		16	/* 8 byte header + data */
431 
432 static struct usb_endpoint_descriptor
433 fs_status_desc = {
434 	.bLength =		USB_DT_ENDPOINT_SIZE,
435 	.bDescriptorType =	USB_DT_ENDPOINT,
436 
437 	.bEndpointAddress =	USB_DIR_IN,
438 	.bmAttributes =		USB_ENDPOINT_XFER_INT,
439 	.wMaxPacketSize =	__constant_cpu_to_le16(STATUS_BYTECOUNT),
440 	.bInterval =		1 << LOG2_STATUS_INTERVAL_MSEC,
441 };
442 #endif
443 
444 #ifdef	DEV_CONFIG_CDC
445 
446 /* the default data interface has no endpoints ... */
447 
448 static const struct usb_interface_descriptor
449 data_nop_intf = {
450 	.bLength =		sizeof data_nop_intf,
451 	.bDescriptorType =	USB_DT_INTERFACE,
452 
453 	.bInterfaceNumber =	1,
454 	.bAlternateSetting =	0,
455 	.bNumEndpoints =	0,
456 	.bInterfaceClass =	USB_CLASS_CDC_DATA,
457 	.bInterfaceSubClass =	0,
458 	.bInterfaceProtocol =	0,
459 };
460 
461 /* ... but the "real" data interface has two bulk endpoints */
462 
463 static const struct usb_interface_descriptor
464 data_intf = {
465 	.bLength =		sizeof data_intf,
466 	.bDescriptorType =	USB_DT_INTERFACE,
467 
468 	.bInterfaceNumber =	1,
469 	.bAlternateSetting =	1,
470 	.bNumEndpoints =	2,
471 	.bInterfaceClass =	USB_CLASS_CDC_DATA,
472 	.bInterfaceSubClass =	0,
473 	.bInterfaceProtocol =	0,
474 	.iInterface =		STRING_DATA,
475 };
476 
477 #endif
478 
479 #ifdef DEV_CONFIG_SUBSET
480 
481 /*
482  * "Simple" CDC-subset option is a simple vendor-neutral model that most
483  * full speed controllers can handle:  one interface, two bulk endpoints.
484  *
485  * To assist host side drivers, we fancy it up a bit, and add descriptors
486  * so some host side drivers will understand it as a "SAFE" variant.
487  */
488 
489 static const struct usb_interface_descriptor
490 subset_data_intf = {
491 	.bLength =		sizeof subset_data_intf,
492 	.bDescriptorType =	USB_DT_INTERFACE,
493 
494 	.bInterfaceNumber =	0,
495 	.bAlternateSetting =	0,
496 	.bNumEndpoints =	2,
497 	.bInterfaceClass =      USB_CLASS_COMM,
498 	.bInterfaceSubClass =	USB_CDC_SUBCLASS_MDLM,
499 	.bInterfaceProtocol =	0,
500 	.iInterface =		STRING_DATA,
501 };
502 
503 #endif	/* SUBSET */
504 
505 static struct usb_endpoint_descriptor
506 fs_source_desc = {
507 	.bLength =		USB_DT_ENDPOINT_SIZE,
508 	.bDescriptorType =	USB_DT_ENDPOINT,
509 
510 	.bEndpointAddress =	USB_DIR_IN,
511 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
512 };
513 
514 static struct usb_endpoint_descriptor
515 fs_sink_desc = {
516 	.bLength =		USB_DT_ENDPOINT_SIZE,
517 	.bDescriptorType =	USB_DT_ENDPOINT,
518 
519 	.bEndpointAddress =	USB_DIR_OUT,
520 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
521 };
522 
523 static const struct usb_descriptor_header *fs_eth_function[11] = {
524 	(struct usb_descriptor_header *) &otg_descriptor,
525 #ifdef DEV_CONFIG_CDC
526 	/* "cdc" mode descriptors */
527 	(struct usb_descriptor_header *) &control_intf,
528 	(struct usb_descriptor_header *) &header_desc,
529 	(struct usb_descriptor_header *) &union_desc,
530 	(struct usb_descriptor_header *) &ether_desc,
531 	/* NOTE: status endpoint may need to be removed */
532 	(struct usb_descriptor_header *) &fs_status_desc,
533 	/* data interface, with altsetting */
534 	(struct usb_descriptor_header *) &data_nop_intf,
535 	(struct usb_descriptor_header *) &data_intf,
536 	(struct usb_descriptor_header *) &fs_source_desc,
537 	(struct usb_descriptor_header *) &fs_sink_desc,
538 	NULL,
539 #endif /* DEV_CONFIG_CDC */
540 };
541 
542 static inline void fs_subset_descriptors(void)
543 {
544 #ifdef DEV_CONFIG_SUBSET
545 	/* behavior is "CDC Subset"; extra descriptors say "SAFE" */
546 	fs_eth_function[1] = (struct usb_descriptor_header *) &subset_data_intf;
547 	fs_eth_function[2] = (struct usb_descriptor_header *) &header_desc;
548 	fs_eth_function[3] = (struct usb_descriptor_header *) &mdlm_desc;
549 	fs_eth_function[4] = (struct usb_descriptor_header *) &mdlm_detail_desc;
550 	fs_eth_function[5] = (struct usb_descriptor_header *) &ether_desc;
551 	fs_eth_function[6] = (struct usb_descriptor_header *) &fs_source_desc;
552 	fs_eth_function[7] = (struct usb_descriptor_header *) &fs_sink_desc;
553 	fs_eth_function[8] = NULL;
554 #else
555 	fs_eth_function[1] = NULL;
556 #endif
557 }
558 
559 /*
560  * usb 2.0 devices need to expose both high speed and full speed
561  * descriptors, unless they only run at full speed.
562  */
563 
564 #if defined(DEV_CONFIG_CDC)
565 static struct usb_endpoint_descriptor
566 hs_status_desc = {
567 	.bLength =		USB_DT_ENDPOINT_SIZE,
568 	.bDescriptorType =	USB_DT_ENDPOINT,
569 
570 	.bmAttributes =		USB_ENDPOINT_XFER_INT,
571 	.wMaxPacketSize =	__constant_cpu_to_le16(STATUS_BYTECOUNT),
572 	.bInterval =		LOG2_STATUS_INTERVAL_MSEC + 4,
573 };
574 #endif /* DEV_CONFIG_CDC */
575 
576 static struct usb_endpoint_descriptor
577 hs_source_desc = {
578 	.bLength =		USB_DT_ENDPOINT_SIZE,
579 	.bDescriptorType =	USB_DT_ENDPOINT,
580 
581 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
582 	.wMaxPacketSize =	__constant_cpu_to_le16(512),
583 };
584 
585 static struct usb_endpoint_descriptor
586 hs_sink_desc = {
587 	.bLength =		USB_DT_ENDPOINT_SIZE,
588 	.bDescriptorType =	USB_DT_ENDPOINT,
589 
590 	.bmAttributes =		USB_ENDPOINT_XFER_BULK,
591 	.wMaxPacketSize =	__constant_cpu_to_le16(512),
592 };
593 
594 static struct usb_qualifier_descriptor
595 dev_qualifier = {
596 	.bLength =		sizeof dev_qualifier,
597 	.bDescriptorType =	USB_DT_DEVICE_QUALIFIER,
598 
599 	.bcdUSB =		__constant_cpu_to_le16(0x0200),
600 	.bDeviceClass =		USB_CLASS_COMM,
601 
602 	.bNumConfigurations =	1,
603 };
604 
605 static const struct usb_descriptor_header *hs_eth_function[11] = {
606 	(struct usb_descriptor_header *) &otg_descriptor,
607 #ifdef DEV_CONFIG_CDC
608 	/* "cdc" mode descriptors */
609 	(struct usb_descriptor_header *) &control_intf,
610 	(struct usb_descriptor_header *) &header_desc,
611 	(struct usb_descriptor_header *) &union_desc,
612 	(struct usb_descriptor_header *) &ether_desc,
613 	/* NOTE: status endpoint may need to be removed */
614 	(struct usb_descriptor_header *) &hs_status_desc,
615 	/* data interface, with altsetting */
616 	(struct usb_descriptor_header *) &data_nop_intf,
617 	(struct usb_descriptor_header *) &data_intf,
618 	(struct usb_descriptor_header *) &hs_source_desc,
619 	(struct usb_descriptor_header *) &hs_sink_desc,
620 	NULL,
621 #endif /* DEV_CONFIG_CDC */
622 };
623 
624 static inline void hs_subset_descriptors(void)
625 {
626 #ifdef DEV_CONFIG_SUBSET
627 	/* behavior is "CDC Subset"; extra descriptors say "SAFE" */
628 	hs_eth_function[1] = (struct usb_descriptor_header *) &subset_data_intf;
629 	hs_eth_function[2] = (struct usb_descriptor_header *) &header_desc;
630 	hs_eth_function[3] = (struct usb_descriptor_header *) &mdlm_desc;
631 	hs_eth_function[4] = (struct usb_descriptor_header *) &mdlm_detail_desc;
632 	hs_eth_function[5] = (struct usb_descriptor_header *) &ether_desc;
633 	hs_eth_function[6] = (struct usb_descriptor_header *) &hs_source_desc;
634 	hs_eth_function[7] = (struct usb_descriptor_header *) &hs_sink_desc;
635 	hs_eth_function[8] = NULL;
636 #else
637 	hs_eth_function[1] = NULL;
638 #endif
639 }
640 
641 /* maxpacket and other transfer characteristics vary by speed. */
642 static inline struct usb_endpoint_descriptor *
643 ep_desc(struct usb_gadget *g, struct usb_endpoint_descriptor *hs,
644 		struct usb_endpoint_descriptor *fs)
645 {
646 	if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
647 		return hs;
648 	return fs;
649 }
650 
651 /*-------------------------------------------------------------------------*/
652 
653 /* descriptors that are built on-demand */
654 
655 static char manufacturer[50];
656 static char product_desc[40] = DRIVER_DESC;
657 static char serial_number[20];
658 
659 /* address that the host will use ... usually assigned at random */
660 static char ethaddr[2 * ETH_ALEN + 1];
661 
662 /* static strings, in UTF-8 */
663 static struct usb_string		strings[] = {
664 	{ STRING_MANUFACTURER,	manufacturer, },
665 	{ STRING_PRODUCT,	product_desc, },
666 	{ STRING_SERIALNUMBER,	serial_number, },
667 	{ STRING_DATA,		"Ethernet Data", },
668 	{ STRING_ETHADDR,	ethaddr, },
669 #ifdef	DEV_CONFIG_CDC
670 	{ STRING_CDC,		"CDC Ethernet", },
671 	{ STRING_CONTROL,	"CDC Communications Control", },
672 #endif
673 #ifdef	DEV_CONFIG_SUBSET
674 	{ STRING_SUBSET,	"CDC Ethernet Subset", },
675 #endif
676 	{  }		/* end of list */
677 };
678 
679 static struct usb_gadget_strings	stringtab = {
680 	.language	= 0x0409,	/* en-us */
681 	.strings	= strings,
682 };
683 
684 /*============================================================================*/
685 static u8 control_req[USB_BUFSIZ];
686 static u8 status_req[STATUS_BYTECOUNT] __attribute__ ((aligned(4)));
687 
688 
689 /**
690  * strlcpy - Copy a %NUL terminated string into a sized buffer
691  * @dest: Where to copy the string to
692  * @src: Where to copy the string from
693  * @size: size of destination buffer
694  *
695  * Compatible with *BSD: the result is always a valid
696  * NUL-terminated string that fits in the buffer (unless,
697  * of course, the buffer size is zero). It does not pad
698  * out the result like strncpy() does.
699  */
700 size_t strlcpy(char *dest, const char *src, size_t size)
701 {
702 	size_t ret = strlen(src);
703 
704 	if (size) {
705 		size_t len = (ret >= size) ? size - 1 : ret;
706 		memcpy(dest, src, len);
707 		dest[len] = '\0';
708 	}
709 	return ret;
710 }
711 
712 /*============================================================================*/
713 
714 /*
715  * one config, two interfaces:  control, data.
716  * complications: class descriptors, and an altsetting.
717  */
718 static int
719 config_buf(struct usb_gadget *g, u8 *buf, u8 type, unsigned index, int is_otg)
720 {
721 	int					len;
722 	const struct usb_config_descriptor	*config;
723 	const struct usb_descriptor_header	**function;
724 	int					hs = 0;
725 
726 	if (gadget_is_dualspeed(g)) {
727 		hs = (g->speed == USB_SPEED_HIGH);
728 		if (type == USB_DT_OTHER_SPEED_CONFIG)
729 			hs = !hs;
730 	}
731 #define which_fn(t)	(hs ? hs_ ## t ## _function : fs_ ## t ## _function)
732 
733 	if (index >= device_desc.bNumConfigurations)
734 		return -EINVAL;
735 
736 	config = &eth_config;
737 	function = which_fn(eth);
738 
739 	/* for now, don't advertise srp-only devices */
740 	if (!is_otg)
741 		function++;
742 
743 	len = usb_gadget_config_buf(config, buf, USB_BUFSIZ, function);
744 	if (len < 0)
745 		return len;
746 	((struct usb_config_descriptor *) buf)->bDescriptorType = type;
747 	return len;
748 }
749 
750 /*-------------------------------------------------------------------------*/
751 
752 static int alloc_requests(struct eth_dev *dev, unsigned n, gfp_t gfp_flags);
753 
754 static int
755 set_ether_config(struct eth_dev *dev, gfp_t gfp_flags)
756 {
757 	int					result = 0;
758 	struct usb_gadget			*gadget = dev->gadget;
759 
760 #if defined(DEV_CONFIG_CDC)
761 	/* status endpoint used for (optionally) CDC */
762 	if (!subset_active(dev) && dev->status_ep) {
763 		dev->status = ep_desc(gadget, &hs_status_desc,
764 						&fs_status_desc);
765 		dev->status_ep->driver_data = dev;
766 
767 		result = usb_ep_enable(dev->status_ep, dev->status);
768 		if (result != 0) {
769 			debug("enable %s --> %d\n",
770 				dev->status_ep->name, result);
771 			goto done;
772 		}
773 	}
774 #endif
775 
776 	dev->in = ep_desc(gadget, &hs_source_desc, &fs_source_desc);
777 	dev->in_ep->driver_data = dev;
778 
779 	dev->out = ep_desc(gadget, &hs_sink_desc, &fs_sink_desc);
780 	dev->out_ep->driver_data = dev;
781 
782 	/*
783 	 * With CDC,  the host isn't allowed to use these two data
784 	 * endpoints in the default altsetting for the interface.
785 	 * so we don't activate them yet.  Reset from SET_INTERFACE.
786 	 */
787 	if (!cdc_active(dev)) {
788 		result = usb_ep_enable(dev->in_ep, dev->in);
789 		if (result != 0) {
790 			debug("enable %s --> %d\n",
791 				dev->in_ep->name, result);
792 			goto done;
793 		}
794 
795 		result = usb_ep_enable(dev->out_ep, dev->out);
796 		if (result != 0) {
797 			debug("enable %s --> %d\n",
798 				dev->out_ep->name, result);
799 			goto done;
800 		}
801 	}
802 
803 done:
804 	if (result == 0)
805 		result = alloc_requests(dev, qlen(gadget), gfp_flags);
806 
807 	/* on error, disable any endpoints  */
808 	if (result < 0) {
809 		if (!subset_active(dev) && dev->status_ep)
810 			(void) usb_ep_disable(dev->status_ep);
811 		dev->status = NULL;
812 		(void) usb_ep_disable(dev->in_ep);
813 		(void) usb_ep_disable(dev->out_ep);
814 		dev->in = NULL;
815 		dev->out = NULL;
816 	}
817 
818 	/* caller is responsible for cleanup on error */
819 	return result;
820 }
821 
822 static void eth_reset_config(struct eth_dev *dev)
823 {
824 	if (dev->config == 0)
825 		return;
826 
827 	debug("%s\n", __func__);
828 
829 	/*
830 	 * disable endpoints, forcing (synchronous) completion of
831 	 * pending i/o.  then free the requests.
832 	 */
833 
834 	if (dev->in) {
835 		usb_ep_disable(dev->in_ep);
836 		if (dev->tx_req) {
837 			usb_ep_free_request(dev->in_ep, dev->tx_req);
838 			dev->tx_req = NULL;
839 		}
840 	}
841 	if (dev->out) {
842 		usb_ep_disable(dev->out_ep);
843 		if (dev->rx_req) {
844 			usb_ep_free_request(dev->out_ep, dev->rx_req);
845 			dev->rx_req = NULL;
846 		}
847 	}
848 	if (dev->status)
849 		usb_ep_disable(dev->status_ep);
850 
851 	dev->cdc_filter = 0;
852 	dev->config = 0;
853 }
854 
855 /*
856  * change our operational config.  must agree with the code
857  * that returns config descriptors, and altsetting code.
858  */
859 static int eth_set_config(struct eth_dev *dev, unsigned number,
860 				gfp_t gfp_flags)
861 {
862 	int			result = 0;
863 	struct usb_gadget	*gadget = dev->gadget;
864 
865 	if (gadget_is_sa1100(gadget)
866 			&& dev->config
867 			&& dev->tx_qlen != 0) {
868 		/* tx fifo is full, but we can't clear it...*/
869 		error("can't change configurations");
870 		return -ESPIPE;
871 	}
872 	eth_reset_config(dev);
873 
874 	switch (number) {
875 	case DEV_CONFIG_VALUE:
876 		result = set_ether_config(dev, gfp_flags);
877 		break;
878 	default:
879 		result = -EINVAL;
880 		/* FALL THROUGH */
881 	case 0:
882 		break;
883 	}
884 
885 	if (result) {
886 		if (number)
887 			eth_reset_config(dev);
888 		usb_gadget_vbus_draw(dev->gadget,
889 				gadget_is_otg(dev->gadget) ? 8 : 100);
890 	} else {
891 		char *speed;
892 		unsigned power;
893 
894 		power = 2 * eth_config.bMaxPower;
895 		usb_gadget_vbus_draw(dev->gadget, power);
896 
897 		switch (gadget->speed) {
898 		case USB_SPEED_FULL:
899 			speed = "full"; break;
900 #ifdef CONFIG_USB_GADGET_DUALSPEED
901 		case USB_SPEED_HIGH:
902 			speed = "high"; break;
903 #endif
904 		default:
905 			speed = "?"; break;
906 		}
907 
908 		dev->config = number;
909 		printf("%s speed config #%d: %d mA, %s, using %s\n",
910 				speed, number, power, driver_desc,
911 				(cdc_active(dev) ? "CDC Ethernet"
912 						: "CDC Ethernet Subset"));
913 	}
914 	return result;
915 }
916 
917 /*-------------------------------------------------------------------------*/
918 
919 #ifdef	DEV_CONFIG_CDC
920 
921 /*
922  * The interrupt endpoint is used in CDC networking models (Ethernet, ATM)
923  * only to notify the host about link status changes (which we support) or
924  * report completion of some encapsulated command.  Since
925  * we want this CDC Ethernet code to be vendor-neutral, we don't use that
926  * command mechanism; and only one status request is ever queued.
927  */
928 static void eth_status_complete(struct usb_ep *ep, struct usb_request *req)
929 {
930 	struct usb_cdc_notification	*event = req->buf;
931 	int				value = req->status;
932 	struct eth_dev			*dev = ep->driver_data;
933 
934 	/* issue the second notification if host reads the first */
935 	if (event->bNotificationType == USB_CDC_NOTIFY_NETWORK_CONNECTION
936 			&& value == 0) {
937 		__le32	*data = req->buf + sizeof *event;
938 
939 		event->bmRequestType = 0xA1;
940 		event->bNotificationType = USB_CDC_NOTIFY_SPEED_CHANGE;
941 		event->wValue = __constant_cpu_to_le16(0);
942 		event->wIndex = __constant_cpu_to_le16(1);
943 		event->wLength = __constant_cpu_to_le16(8);
944 
945 		/* SPEED_CHANGE data is up/down speeds in bits/sec */
946 		data[0] = data[1] = cpu_to_le32(BITRATE(dev->gadget));
947 
948 		req->length = STATUS_BYTECOUNT;
949 		value = usb_ep_queue(ep, req, GFP_ATOMIC);
950 		debug("send SPEED_CHANGE --> %d\n", value);
951 		if (value == 0)
952 			return;
953 	} else if (value != -ECONNRESET) {
954 		debug("event %02x --> %d\n",
955 			event->bNotificationType, value);
956 		if (event->bNotificationType ==
957 				USB_CDC_NOTIFY_SPEED_CHANGE) {
958 			l_ethdev.network_started = 1;
959 			printf("USB network up!\n");
960 		}
961 	}
962 	req->context = NULL;
963 }
964 
965 static void issue_start_status(struct eth_dev *dev)
966 {
967 	struct usb_request		*req = dev->stat_req;
968 	struct usb_cdc_notification	*event;
969 	int				value;
970 
971 	/*
972 	 * flush old status
973 	 *
974 	 * FIXME ugly idiom, maybe we'd be better with just
975 	 * a "cancel the whole queue" primitive since any
976 	 * unlink-one primitive has way too many error modes.
977 	 * here, we "know" toggle is already clear...
978 	 *
979 	 * FIXME iff req->context != null just dequeue it
980 	 */
981 	usb_ep_disable(dev->status_ep);
982 	usb_ep_enable(dev->status_ep, dev->status);
983 
984 	/*
985 	 * 3.8.1 says to issue first NETWORK_CONNECTION, then
986 	 * a SPEED_CHANGE.  could be useful in some configs.
987 	 */
988 	event = req->buf;
989 	event->bmRequestType = 0xA1;
990 	event->bNotificationType = USB_CDC_NOTIFY_NETWORK_CONNECTION;
991 	event->wValue = __constant_cpu_to_le16(1);	/* connected */
992 	event->wIndex = __constant_cpu_to_le16(1);
993 	event->wLength = 0;
994 
995 	req->length = sizeof *event;
996 	req->complete = eth_status_complete;
997 	req->context = dev;
998 
999 	value = usb_ep_queue(dev->status_ep, req, GFP_ATOMIC);
1000 	if (value < 0)
1001 		debug("status buf queue --> %d\n", value);
1002 }
1003 
1004 #endif
1005 
1006 /*-------------------------------------------------------------------------*/
1007 
1008 static void eth_setup_complete(struct usb_ep *ep, struct usb_request *req)
1009 {
1010 	if (req->status || req->actual != req->length)
1011 		debug("setup complete --> %d, %d/%d\n",
1012 				req->status, req->actual, req->length);
1013 }
1014 
1015 /*
1016  * The setup() callback implements all the ep0 functionality that's not
1017  * handled lower down.  CDC has a number of less-common features:
1018  *
1019  *  - two interfaces:  control, and ethernet data
1020  *  - Ethernet data interface has two altsettings:  default, and active
1021  *  - class-specific descriptors for the control interface
1022  *  - class-specific control requests
1023  */
1024 static int
1025 eth_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1026 {
1027 	struct eth_dev		*dev = get_gadget_data(gadget);
1028 	struct usb_request	*req = dev->req;
1029 	int			value = -EOPNOTSUPP;
1030 	u16			wIndex = le16_to_cpu(ctrl->wIndex);
1031 	u16			wValue = le16_to_cpu(ctrl->wValue);
1032 	u16			wLength = le16_to_cpu(ctrl->wLength);
1033 
1034 	/*
1035 	 * descriptors just go into the pre-allocated ep0 buffer,
1036 	 * while config change events may enable network traffic.
1037 	 */
1038 
1039 	debug("%s\n", __func__);
1040 
1041 	req->complete = eth_setup_complete;
1042 	switch (ctrl->bRequest) {
1043 
1044 	case USB_REQ_GET_DESCRIPTOR:
1045 		if (ctrl->bRequestType != USB_DIR_IN)
1046 			break;
1047 		switch (wValue >> 8) {
1048 
1049 		case USB_DT_DEVICE:
1050 			value = min(wLength, (u16) sizeof device_desc);
1051 			memcpy(req->buf, &device_desc, value);
1052 			break;
1053 		case USB_DT_DEVICE_QUALIFIER:
1054 			if (!gadget_is_dualspeed(gadget))
1055 				break;
1056 			value = min(wLength, (u16) sizeof dev_qualifier);
1057 			memcpy(req->buf, &dev_qualifier, value);
1058 			break;
1059 
1060 		case USB_DT_OTHER_SPEED_CONFIG:
1061 			if (!gadget_is_dualspeed(gadget))
1062 				break;
1063 			/* FALLTHROUGH */
1064 		case USB_DT_CONFIG:
1065 			value = config_buf(gadget, req->buf,
1066 					wValue >> 8,
1067 					wValue & 0xff,
1068 					gadget_is_otg(gadget));
1069 			if (value >= 0)
1070 				value = min(wLength, (u16) value);
1071 			break;
1072 
1073 		case USB_DT_STRING:
1074 			value = usb_gadget_get_string(&stringtab,
1075 					wValue & 0xff, req->buf);
1076 
1077 			if (value >= 0)
1078 				value = min(wLength, (u16) value);
1079 
1080 			break;
1081 		}
1082 		break;
1083 
1084 	case USB_REQ_SET_CONFIGURATION:
1085 		if (ctrl->bRequestType != 0)
1086 			break;
1087 		if (gadget->a_hnp_support)
1088 			debug("HNP available\n");
1089 		else if (gadget->a_alt_hnp_support)
1090 			debug("HNP needs a different root port\n");
1091 		value = eth_set_config(dev, wValue, GFP_ATOMIC);
1092 		break;
1093 	case USB_REQ_GET_CONFIGURATION:
1094 		if (ctrl->bRequestType != USB_DIR_IN)
1095 			break;
1096 		*(u8 *)req->buf = dev->config;
1097 		value = min(wLength, (u16) 1);
1098 		break;
1099 
1100 	case USB_REQ_SET_INTERFACE:
1101 		if (ctrl->bRequestType != USB_RECIP_INTERFACE
1102 				|| !dev->config
1103 				|| wIndex > 1)
1104 			break;
1105 		if (!cdc_active(dev) && wIndex != 0)
1106 			break;
1107 
1108 		/*
1109 		 * PXA hardware partially handles SET_INTERFACE;
1110 		 * we need to kluge around that interference.
1111 		 */
1112 		if (gadget_is_pxa(gadget)) {
1113 			value = eth_set_config(dev, DEV_CONFIG_VALUE,
1114 						GFP_ATOMIC);
1115 			goto done_set_intf;
1116 		}
1117 
1118 #ifdef DEV_CONFIG_CDC
1119 		switch (wIndex) {
1120 		case 0:		/* control/master intf */
1121 			if (wValue != 0)
1122 				break;
1123 			if (dev->status) {
1124 				usb_ep_disable(dev->status_ep);
1125 				usb_ep_enable(dev->status_ep, dev->status);
1126 			}
1127 			value = 0;
1128 			break;
1129 		case 1:		/* data intf */
1130 			if (wValue > 1)
1131 				break;
1132 			usb_ep_disable(dev->in_ep);
1133 			usb_ep_disable(dev->out_ep);
1134 
1135 			/*
1136 			 * CDC requires the data transfers not be done from
1137 			 * the default interface setting ... also, setting
1138 			 * the non-default interface resets filters etc.
1139 			 */
1140 			if (wValue == 1) {
1141 				if (!cdc_active(dev))
1142 					break;
1143 				usb_ep_enable(dev->in_ep, dev->in);
1144 				usb_ep_enable(dev->out_ep, dev->out);
1145 				dev->cdc_filter = DEFAULT_FILTER;
1146 				if (dev->status)
1147 					issue_start_status(dev);
1148 			}
1149 
1150 			value = 0;
1151 			break;
1152 		}
1153 #else
1154 		/*
1155 		 * FIXME this is wrong, as is the assumption that
1156 		 * all non-PXA hardware talks real CDC ...
1157 		 */
1158 		debug("set_interface ignored!\n");
1159 #endif /* DEV_CONFIG_CDC */
1160 
1161 done_set_intf:
1162 		break;
1163 	case USB_REQ_GET_INTERFACE:
1164 		if (ctrl->bRequestType != (USB_DIR_IN|USB_RECIP_INTERFACE)
1165 				|| !dev->config
1166 				|| wIndex > 1)
1167 			break;
1168 		if (!(cdc_active(dev)) && wIndex != 0)
1169 			break;
1170 
1171 		/* for CDC, iff carrier is on, data interface is active. */
1172 		if (wIndex != 1)
1173 			*(u8 *)req->buf = 0;
1174 		else {
1175 			/* *(u8 *)req->buf = netif_carrier_ok (dev->net) ? 1 : 0; */
1176 			/* carrier always ok ...*/
1177 			*(u8 *)req->buf = 1 ;
1178 		}
1179 		value = min(wLength, (u16) 1);
1180 		break;
1181 
1182 #ifdef DEV_CONFIG_CDC
1183 	case USB_CDC_SET_ETHERNET_PACKET_FILTER:
1184 		/*
1185 		 * see 6.2.30: no data, wIndex = interface,
1186 		 * wValue = packet filter bitmap
1187 		 */
1188 		if (ctrl->bRequestType != (USB_TYPE_CLASS|USB_RECIP_INTERFACE)
1189 				|| !cdc_active(dev)
1190 				|| wLength != 0
1191 				|| wIndex > 1)
1192 			break;
1193 		debug("packet filter %02x\n", wValue);
1194 		dev->cdc_filter = wValue;
1195 		value = 0;
1196 		break;
1197 
1198 	/*
1199 	 * and potentially:
1200 	 * case USB_CDC_SET_ETHERNET_MULTICAST_FILTERS:
1201 	 * case USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER:
1202 	 * case USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER:
1203 	 * case USB_CDC_GET_ETHERNET_STATISTIC:
1204 	 */
1205 
1206 #endif /* DEV_CONFIG_CDC */
1207 
1208 	default:
1209 		debug("unknown control req%02x.%02x v%04x i%04x l%d\n",
1210 			ctrl->bRequestType, ctrl->bRequest,
1211 			wValue, wIndex, wLength);
1212 	}
1213 
1214 	/* respond with data transfer before status phase? */
1215 	if (value >= 0) {
1216 		debug("respond with data transfer before status phase\n");
1217 		req->length = value;
1218 		req->zero = value < wLength
1219 				&& (value % gadget->ep0->maxpacket) == 0;
1220 		value = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);
1221 		if (value < 0) {
1222 			debug("ep_queue --> %d\n", value);
1223 			req->status = 0;
1224 			eth_setup_complete(gadget->ep0, req);
1225 		}
1226 	}
1227 
1228 	/* host either stalls (value < 0) or reports success */
1229 	return value;
1230 }
1231 
1232 /*-------------------------------------------------------------------------*/
1233 
1234 static void rx_complete(struct usb_ep *ep, struct usb_request *req);
1235 
1236 static int rx_submit(struct eth_dev *dev, struct usb_request *req,
1237 				gfp_t gfp_flags)
1238 {
1239 	int			retval = -ENOMEM;
1240 	size_t			size;
1241 
1242 	/*
1243 	 * Padding up to RX_EXTRA handles minor disagreements with host.
1244 	 * Normally we use the USB "terminate on short read" convention;
1245 	 * so allow up to (N*maxpacket), since that memory is normally
1246 	 * already allocated.  Some hardware doesn't deal well with short
1247 	 * reads (e.g. DMA must be N*maxpacket), so for now don't trim a
1248 	 * byte off the end (to force hardware errors on overflow).
1249 	 */
1250 
1251 	debug("%s\n", __func__);
1252 
1253 	size = (ETHER_HDR_SIZE + dev->mtu + RX_EXTRA);
1254 	size += dev->out_ep->maxpacket - 1;
1255 	size -= size % dev->out_ep->maxpacket;
1256 
1257 	/*
1258 	 * Some platforms perform better when IP packets are aligned,
1259 	 * but on at least one, checksumming fails otherwise.
1260 	 */
1261 
1262 	req->buf = (u8 *) NetRxPackets[0];
1263 	req->length = size;
1264 	req->complete = rx_complete;
1265 
1266 	retval = usb_ep_queue(dev->out_ep, req, gfp_flags);
1267 
1268 	if (retval)
1269 		error("rx submit --> %d", retval);
1270 
1271 	return retval;
1272 }
1273 
1274 static void rx_complete(struct usb_ep *ep, struct usb_request *req)
1275 {
1276 	struct eth_dev	*dev = ep->driver_data;
1277 
1278 	debug("%s: status %d\n", __func__, req->status);
1279 	switch (req->status) {
1280 	/* normal completion */
1281 	case 0:
1282 		dev->stats.rx_packets++;
1283 		dev->stats.rx_bytes += req->length;
1284 		break;
1285 
1286 	/* software-driven interface shutdown */
1287 	case -ECONNRESET:		/* unlink */
1288 	case -ESHUTDOWN:		/* disconnect etc */
1289 	/* for hardware automagic (such as pxa) */
1290 	case -ECONNABORTED:		/* endpoint reset */
1291 		break;
1292 
1293 	/* data overrun */
1294 	case -EOVERFLOW:
1295 		dev->stats.rx_over_errors++;
1296 		/* FALLTHROUGH */
1297 	default:
1298 		dev->stats.rx_errors++;
1299 		break;
1300 	}
1301 
1302 	packet_received = 1;
1303 }
1304 
1305 static int alloc_requests(struct eth_dev *dev, unsigned n, gfp_t gfp_flags)
1306 {
1307 
1308 	dev->tx_req = usb_ep_alloc_request(dev->in_ep, 0);
1309 
1310 	if (!dev->tx_req)
1311 		goto fail1;
1312 
1313 	dev->rx_req = usb_ep_alloc_request(dev->out_ep, 0);
1314 
1315 	if (!dev->rx_req)
1316 		goto fail2;
1317 
1318 	return 0;
1319 
1320 fail2:
1321 	usb_ep_free_request(dev->in_ep, dev->tx_req);
1322 fail1:
1323 	error("can't alloc requests");
1324 	return -1;
1325 }
1326 
1327 static void tx_complete(struct usb_ep *ep, struct usb_request *req)
1328 {
1329 	struct eth_dev	*dev = ep->driver_data;
1330 
1331 	debug("%s: status %s\n", __func__, (req->status) ? "failed" : "ok");
1332 	switch (req->status) {
1333 	default:
1334 		dev->stats.tx_errors++;
1335 		debug("tx err %d\n", req->status);
1336 		/* FALLTHROUGH */
1337 	case -ECONNRESET:		/* unlink */
1338 	case -ESHUTDOWN:		/* disconnect etc */
1339 		break;
1340 	case 0:
1341 		dev->stats.tx_bytes += req->length;
1342 	}
1343 	dev->stats.tx_packets++;
1344 
1345 	packet_sent = 1;
1346 }
1347 
1348 static inline int eth_is_promisc(struct eth_dev *dev)
1349 {
1350 	/* no filters for the CDC subset; always promisc */
1351 	if (subset_active(dev))
1352 		return 1;
1353 	return dev->cdc_filter & USB_CDC_PACKET_TYPE_PROMISCUOUS;
1354 }
1355 
1356 #if 0
1357 static int eth_start_xmit (struct sk_buff *skb, struct net_device *net)
1358 {
1359 	struct eth_dev		*dev = netdev_priv(net);
1360 	int			length = skb->len;
1361 	int			retval;
1362 	struct usb_request	*req = NULL;
1363 	unsigned long		flags;
1364 
1365 	/* apply outgoing CDC or RNDIS filters */
1366 	if (!eth_is_promisc (dev)) {
1367 		u8		*dest = skb->data;
1368 
1369 		if (is_multicast_ether_addr(dest)) {
1370 			u16	type;
1371 
1372 			/* ignores USB_CDC_PACKET_TYPE_MULTICAST and host
1373 			 * SET_ETHERNET_MULTICAST_FILTERS requests
1374 			 */
1375 			if (is_broadcast_ether_addr(dest))
1376 				type = USB_CDC_PACKET_TYPE_BROADCAST;
1377 			else
1378 				type = USB_CDC_PACKET_TYPE_ALL_MULTICAST;
1379 			if (!(dev->cdc_filter & type)) {
1380 				dev_kfree_skb_any (skb);
1381 				return 0;
1382 			}
1383 		}
1384 		/* ignores USB_CDC_PACKET_TYPE_DIRECTED */
1385 	}
1386 
1387 	spin_lock_irqsave(&dev->req_lock, flags);
1388 	/*
1389 	 * this freelist can be empty if an interrupt triggered disconnect()
1390 	 * and reconfigured the gadget (shutting down this queue) after the
1391 	 * network stack decided to xmit but before we got the spinlock.
1392 	 */
1393 	if (list_empty(&dev->tx_reqs)) {
1394 		spin_unlock_irqrestore(&dev->req_lock, flags);
1395 		return 1;
1396 	}
1397 
1398 	req = container_of (dev->tx_reqs.next, struct usb_request, list);
1399 	list_del (&req->list);
1400 
1401 	/* temporarily stop TX queue when the freelist empties */
1402 	if (list_empty (&dev->tx_reqs))
1403 		netif_stop_queue (net);
1404 	spin_unlock_irqrestore(&dev->req_lock, flags);
1405 
1406 	/* no buffer copies needed, unless the network stack did it
1407 	 * or the hardware can't use skb buffers.
1408 	 * or there's not enough space for any RNDIS headers we need
1409 	 */
1410 	if (rndis_active(dev)) {
1411 		struct sk_buff	*skb_rndis;
1412 
1413 		skb_rndis = skb_realloc_headroom (skb,
1414 				sizeof (struct rndis_packet_msg_type));
1415 		if (!skb_rndis)
1416 			goto drop;
1417 
1418 		dev_kfree_skb_any (skb);
1419 		skb = skb_rndis;
1420 		rndis_add_hdr (skb);
1421 		length = skb->len;
1422 	}
1423 	req->buf = skb->data;
1424 	req->context = skb;
1425 	req->complete = tx_complete;
1426 
1427 	/* use zlp framing on tx for strict CDC-Ether conformance,
1428 	 * though any robust network rx path ignores extra padding.
1429 	 * and some hardware doesn't like to write zlps.
1430 	 */
1431 	req->zero = 1;
1432 	if (!dev->zlp && (length % dev->in_ep->maxpacket) == 0)
1433 		length++;
1434 
1435 	req->length = length;
1436 
1437 	/* throttle highspeed IRQ rate back slightly */
1438 	if (gadget_is_dualspeed(dev->gadget))
1439 		req->no_interrupt = (dev->gadget->speed == USB_SPEED_HIGH)
1440 			? ((atomic_read(&dev->tx_qlen) % qmult) != 0)
1441 			: 0;
1442 
1443 	retval = usb_ep_queue (dev->in_ep, req, GFP_ATOMIC);
1444 	switch (retval) {
1445 	default:
1446 		DEBUG (dev, "tx queue err %d\n", retval);
1447 		break;
1448 	case 0:
1449 		net->trans_start = jiffies;
1450 		atomic_inc (&dev->tx_qlen);
1451 	}
1452 
1453 	if (retval) {
1454 drop:
1455 		dev->stats.tx_dropped++;
1456 		dev_kfree_skb_any (skb);
1457 		spin_lock_irqsave(&dev->req_lock, flags);
1458 		if (list_empty (&dev->tx_reqs))
1459 			netif_start_queue (net);
1460 		list_add (&req->list, &dev->tx_reqs);
1461 		spin_unlock_irqrestore(&dev->req_lock, flags);
1462 	}
1463 	return 0;
1464 }
1465 
1466 /*-------------------------------------------------------------------------*/
1467 #endif
1468 
1469 static void eth_unbind(struct usb_gadget *gadget)
1470 {
1471 	struct eth_dev *dev = get_gadget_data(gadget);
1472 
1473 	debug("%s...\n", __func__);
1474 
1475 	/* we've already been disconnected ... no i/o is active */
1476 	if (dev->req) {
1477 		usb_ep_free_request(gadget->ep0, dev->req);
1478 		dev->req = NULL;
1479 	}
1480 	if (dev->stat_req) {
1481 		usb_ep_free_request(dev->status_ep, dev->stat_req);
1482 		dev->stat_req = NULL;
1483 	}
1484 
1485 	if (dev->tx_req) {
1486 		usb_ep_free_request(dev->in_ep, dev->tx_req);
1487 		dev->tx_req = NULL;
1488 	}
1489 
1490 	if (dev->rx_req) {
1491 		usb_ep_free_request(dev->out_ep, dev->rx_req);
1492 		dev->rx_req = NULL;
1493 	}
1494 
1495 /*	unregister_netdev (dev->net);*/
1496 /*	free_netdev(dev->net);*/
1497 
1498 	dev->gadget = NULL;
1499 	set_gadget_data(gadget, NULL);
1500 }
1501 
1502 static void eth_disconnect(struct usb_gadget *gadget)
1503 {
1504 	eth_reset_config(get_gadget_data(gadget));
1505 }
1506 
1507 static void eth_suspend(struct usb_gadget *gadget)
1508 {
1509 	/* Not used */
1510 }
1511 
1512 static void eth_resume(struct usb_gadget *gadget)
1513 {
1514 	/* Not used */
1515 }
1516 
1517 /*-------------------------------------------------------------------------*/
1518 
1519 static int is_eth_addr_valid(char *str)
1520 {
1521 	if (strlen(str) == 17) {
1522 		int i;
1523 		char *p, *q;
1524 		uchar ea[6];
1525 
1526 		/* see if it looks like an ethernet address */
1527 
1528 		p = str;
1529 
1530 		for (i = 0; i < 6; i++) {
1531 			char term = (i == 5 ? '\0' : ':');
1532 
1533 			ea[i] = simple_strtol(p, &q, 16);
1534 
1535 			if ((q - p) != 2 || *q++ != term)
1536 				break;
1537 
1538 			p = q;
1539 		}
1540 
1541 		if (i == 6) /* it looks ok */
1542 			return 1;
1543 	}
1544 	return 0;
1545 }
1546 
1547 static u8 nibble(unsigned char c)
1548 {
1549 	if (likely(isdigit(c)))
1550 		return c - '0';
1551 	c = toupper(c);
1552 	if (likely(isxdigit(c)))
1553 		return 10 + c - 'A';
1554 	return 0;
1555 }
1556 
1557 static int get_ether_addr(const char *str, u8 *dev_addr)
1558 {
1559 	if (str) {
1560 		unsigned	i;
1561 
1562 		for (i = 0; i < 6; i++) {
1563 			unsigned char num;
1564 
1565 			if ((*str == '.') || (*str == ':'))
1566 				str++;
1567 			num = nibble(*str++) << 4;
1568 			num |= (nibble(*str++));
1569 			dev_addr[i] = num;
1570 		}
1571 		if (is_valid_ether_addr(dev_addr))
1572 			return 0;
1573 	}
1574 	return 1;
1575 }
1576 
1577 static int eth_bind(struct usb_gadget *gadget)
1578 {
1579 	struct eth_dev		*dev = &l_ethdev;
1580 	u8			cdc = 1, zlp = 1;
1581 	struct usb_ep		*in_ep, *out_ep, *status_ep = NULL;
1582 	int			gcnum;
1583 	u8			tmp[7];
1584 
1585 	/* these flags are only ever cleared; compiler take note */
1586 #ifndef	DEV_CONFIG_CDC
1587 	cdc = 0;
1588 #endif
1589 	/*
1590 	 * Because most host side USB stacks handle CDC Ethernet, that
1591 	 * standard protocol is _strongly_ preferred for interop purposes.
1592 	 * (By everyone except Microsoft.)
1593 	 */
1594 	if (gadget_is_pxa(gadget)) {
1595 		/* pxa doesn't support altsettings */
1596 		cdc = 0;
1597 	} else if (gadget_is_musbhdrc(gadget)) {
1598 		/* reduce tx dma overhead by avoiding special cases */
1599 		zlp = 0;
1600 	} else if (gadget_is_sh(gadget)) {
1601 		/* sh doesn't support multiple interfaces or configs */
1602 		cdc = 0;
1603 	} else if (gadget_is_sa1100(gadget)) {
1604 		/* hardware can't write zlps */
1605 		zlp = 0;
1606 		/*
1607 		 * sa1100 CAN do CDC, without status endpoint ... we use
1608 		 * non-CDC to be compatible with ARM Linux-2.4 "usb-eth".
1609 		 */
1610 		cdc = 0;
1611 	}
1612 
1613 	gcnum = usb_gadget_controller_number(gadget);
1614 	if (gcnum >= 0)
1615 		device_desc.bcdDevice = cpu_to_le16(0x0300 + gcnum);
1616 	else {
1617 		/*
1618 		 * can't assume CDC works.  don't want to default to
1619 		 * anything less functional on CDC-capable hardware,
1620 		 * so we fail in this case.
1621 		 */
1622 		error("controller '%s' not recognized",
1623 			gadget->name);
1624 		return -ENODEV;
1625 	}
1626 
1627 	/*
1628 	 * CDC subset ... recognized by Linux since 2.4.10, but Windows
1629 	 * drivers aren't widely available.  (That may be improved by
1630 	 * supporting one submode of the "SAFE" variant of MDLM.)
1631 	 */
1632 	if (!cdc) {
1633 		device_desc.idVendor =
1634 			__constant_cpu_to_le16(SIMPLE_VENDOR_NUM);
1635 		device_desc.idProduct =
1636 			__constant_cpu_to_le16(SIMPLE_PRODUCT_NUM);
1637 	}
1638 
1639 	/* support optional vendor/distro customization */
1640 #if defined(CONFIG_USB_CDC_VENDOR_ID) && defined(CONFIG_USB_CDC_PRODUCT_ID)
1641 	device_desc.idVendor = cpu_to_le16(CONFIG_USB_CDC_VENDOR_ID);
1642 	device_desc.idProduct = cpu_to_le16(CONFIG_USB_CDC_PRODUCT_ID);
1643 #endif
1644 	if (bcdDevice)
1645 		device_desc.bcdDevice = cpu_to_le16(bcdDevice);
1646 	if (iManufacturer)
1647 		strlcpy(manufacturer, iManufacturer, sizeof manufacturer);
1648 	if (iProduct)
1649 		strlcpy(product_desc, iProduct, sizeof product_desc);
1650 	if (iSerialNumber) {
1651 		device_desc.iSerialNumber = STRING_SERIALNUMBER,
1652 		strlcpy(serial_number, iSerialNumber, sizeof serial_number);
1653 	}
1654 
1655 	/* all we really need is bulk IN/OUT */
1656 	usb_ep_autoconfig_reset(gadget);
1657 	in_ep = usb_ep_autoconfig(gadget, &fs_source_desc);
1658 	if (!in_ep) {
1659 autoconf_fail:
1660 		error("can't autoconfigure on %s\n",
1661 			gadget->name);
1662 		return -ENODEV;
1663 	}
1664 	in_ep->driver_data = in_ep;	/* claim */
1665 
1666 	out_ep = usb_ep_autoconfig(gadget, &fs_sink_desc);
1667 	if (!out_ep)
1668 		goto autoconf_fail;
1669 	out_ep->driver_data = out_ep;	/* claim */
1670 
1671 #if defined(DEV_CONFIG_CDC)
1672 	/*
1673 	 * CDC Ethernet control interface doesn't require a status endpoint.
1674 	 * Since some hosts expect one, try to allocate one anyway.
1675 	 */
1676 	if (cdc) {
1677 		status_ep = usb_ep_autoconfig(gadget, &fs_status_desc);
1678 		if (status_ep) {
1679 			status_ep->driver_data = status_ep;	/* claim */
1680 		} else if (cdc) {
1681 			control_intf.bNumEndpoints = 0;
1682 			/* FIXME remove endpoint from descriptor list */
1683 		}
1684 	}
1685 #endif
1686 
1687 	/* one config:  cdc, else minimal subset */
1688 	if (!cdc) {
1689 		eth_config.bNumInterfaces = 1;
1690 		eth_config.iConfiguration = STRING_SUBSET;
1691 
1692 		/*
1693 		 * use functions to set these up, in case we're built to work
1694 		 * with multiple controllers and must override CDC Ethernet.
1695 		 */
1696 		fs_subset_descriptors();
1697 		hs_subset_descriptors();
1698 	}
1699 
1700 	device_desc.bMaxPacketSize0 = gadget->ep0->maxpacket;
1701 	usb_gadget_set_selfpowered(gadget);
1702 
1703 	if (gadget_is_dualspeed(gadget)) {
1704 		if (!cdc)
1705 			dev_qualifier.bDeviceClass = USB_CLASS_VENDOR_SPEC;
1706 
1707 		/* assumes ep0 uses the same value for both speeds ... */
1708 		dev_qualifier.bMaxPacketSize0 = device_desc.bMaxPacketSize0;
1709 
1710 		/* and that all endpoints are dual-speed */
1711 		hs_source_desc.bEndpointAddress =
1712 				fs_source_desc.bEndpointAddress;
1713 		hs_sink_desc.bEndpointAddress =
1714 				fs_sink_desc.bEndpointAddress;
1715 #if defined(DEV_CONFIG_CDC)
1716 		if (status_ep)
1717 			hs_status_desc.bEndpointAddress =
1718 					fs_status_desc.bEndpointAddress;
1719 #endif
1720 	}
1721 
1722 	if (gadget_is_otg(gadget)) {
1723 		otg_descriptor.bmAttributes |= USB_OTG_HNP,
1724 		eth_config.bmAttributes |= USB_CONFIG_ATT_WAKEUP;
1725 		eth_config.bMaxPower = 4;
1726 	}
1727 
1728 	dev->net = &l_netdev;
1729 
1730 	dev->cdc = cdc;
1731 	dev->zlp = zlp;
1732 
1733 	dev->in_ep = in_ep;
1734 	dev->out_ep = out_ep;
1735 	dev->status_ep = status_ep;
1736 
1737 	/*
1738 	 * Module params for these addresses should come from ID proms.
1739 	 * The host side address is used with CDC, and commonly
1740 	 * ends up in a persistent config database.  It's not clear if
1741 	 * host side code for the SAFE thing cares -- its original BLAN
1742 	 * thing didn't, Sharp never assigned those addresses on Zaurii.
1743 	 */
1744 	get_ether_addr(dev_addr, dev->net->enetaddr);
1745 
1746 	memset(tmp, 0, sizeof(tmp));
1747 	memcpy(tmp, dev->net->enetaddr, sizeof(dev->net->enetaddr));
1748 
1749 	get_ether_addr(host_addr, dev->host_mac);
1750 
1751 	sprintf(ethaddr, "%02X%02X%02X%02X%02X%02X",
1752 		dev->host_mac[0], dev->host_mac[1],
1753 			dev->host_mac[2], dev->host_mac[3],
1754 			dev->host_mac[4], dev->host_mac[5]);
1755 
1756 	printf("using %s, OUT %s IN %s%s%s\n", gadget->name,
1757 		out_ep->name, in_ep->name,
1758 		status_ep ? " STATUS " : "",
1759 		status_ep ? status_ep->name : ""
1760 		);
1761 	printf("MAC %02x:%02x:%02x:%02x:%02x:%02x\n",
1762 		dev->net->enetaddr[0], dev->net->enetaddr[1],
1763 		dev->net->enetaddr[2], dev->net->enetaddr[3],
1764 		dev->net->enetaddr[4], dev->net->enetaddr[5]);
1765 
1766 	if (cdc) {
1767 		printf("HOST MAC %02x:%02x:%02x:%02x:%02x:%02x\n",
1768 			dev->host_mac[0], dev->host_mac[1],
1769 			dev->host_mac[2], dev->host_mac[3],
1770 			dev->host_mac[4], dev->host_mac[5]);
1771 	}
1772 
1773 	/*
1774 	 * use PKTSIZE (or aligned... from u-boot) and set
1775 	 * wMaxSegmentSize accordingly
1776 	 */
1777 	dev->mtu = PKTSIZE_ALIGN; /* RNDIS does not like this, only 1514, TODO*/
1778 
1779 	/* preallocate control message data and buffer */
1780 	dev->req = usb_ep_alloc_request(gadget->ep0, GFP_KERNEL);
1781 	if (!dev->req)
1782 		goto fail;
1783 	dev->req->buf = control_req;
1784 	dev->req->complete = eth_setup_complete;
1785 
1786 	/* ... and maybe likewise for status transfer */
1787 #if defined(DEV_CONFIG_CDC)
1788 	if (dev->status_ep) {
1789 		dev->stat_req = usb_ep_alloc_request(dev->status_ep,
1790 							GFP_KERNEL);
1791 		if (!dev->stat_req) {
1792 			usb_ep_free_request(dev->status_ep, dev->req);
1793 
1794 			goto fail;
1795 		}
1796 		dev->stat_req->buf = status_req;
1797 		dev->stat_req->context = NULL;
1798 	}
1799 #endif
1800 
1801 	/* finish hookup to lower layer ... */
1802 	dev->gadget = gadget;
1803 	set_gadget_data(gadget, dev);
1804 	gadget->ep0->driver_data = dev;
1805 
1806 	/*
1807 	 * two kinds of host-initiated state changes:
1808 	 *  - iff DATA transfer is active, carrier is "on"
1809 	 *  - tx queueing enabled if open *and* carrier is "on"
1810 	 */
1811 	return 0;
1812 
1813 fail:
1814 	error("%s failed", __func__);
1815 	eth_unbind(gadget);
1816 	return -ENOMEM;
1817 }
1818 
1819 static int usb_eth_init(struct eth_device *netdev, bd_t *bd)
1820 {
1821 	struct eth_dev *dev = &l_ethdev;
1822 	struct usb_gadget *gadget;
1823 	unsigned long ts;
1824 	unsigned long timeout = USB_CONNECT_TIMEOUT;
1825 
1826 	if (!netdev) {
1827 		error("received NULL ptr");
1828 		goto fail;
1829 	}
1830 
1831 	/* Configure default mac-addresses for the USB ethernet device */
1832 #ifdef CONFIG_USBNET_DEV_ADDR
1833 	strlcpy(dev_addr, CONFIG_USBNET_DEV_ADDR, sizeof(dev_addr));
1834 #endif
1835 #ifdef CONFIG_USBNET_HOST_ADDR
1836 	strlcpy(host_addr, CONFIG_USBNET_HOST_ADDR, sizeof(host_addr));
1837 #endif
1838 	/* Check if the user overruled the MAC addresses */
1839 	if (getenv("usbnet_devaddr"))
1840 		strlcpy(dev_addr, getenv("usbnet_devaddr"),
1841 			sizeof(dev_addr));
1842 
1843 	if (getenv("usbnet_hostaddr"))
1844 		strlcpy(host_addr, getenv("usbnet_hostaddr"),
1845 			sizeof(host_addr));
1846 
1847 	if (!is_eth_addr_valid(dev_addr)) {
1848 		error("Need valid 'usbnet_devaddr' to be set");
1849 		goto fail;
1850 	}
1851 	if (!is_eth_addr_valid(host_addr)) {
1852 		error("Need valid 'usbnet_hostaddr' to be set");
1853 		goto fail;
1854 	}
1855 
1856 	if (usb_gadget_register_driver(&eth_driver) < 0)
1857 		goto fail;
1858 
1859 	dev->network_started = 0;
1860 
1861 	packet_received = 0;
1862 	packet_sent = 0;
1863 
1864 	gadget = dev->gadget;
1865 	usb_gadget_connect(gadget);
1866 
1867 	if (getenv("cdc_connect_timeout"))
1868 		timeout = simple_strtoul(getenv("cdc_connect_timeout"),
1869 						NULL, 10) * CONFIG_SYS_HZ;
1870 	ts = get_timer(0);
1871 	while (!l_ethdev.network_started) {
1872 		/* Handle control-c and timeouts */
1873 		if (ctrlc() || (get_timer(ts) > timeout)) {
1874 			error("The remote end did not respond in time.");
1875 			goto fail;
1876 		}
1877 		usb_gadget_handle_interrupts();
1878 	}
1879 
1880 	packet_received = 0;
1881 	rx_submit(dev, dev->rx_req, 0);
1882 	return 0;
1883 fail:
1884 	return -1;
1885 }
1886 
1887 static int usb_eth_send(struct eth_device *netdev,
1888 			volatile void *packet, int length)
1889 {
1890 	int			retval;
1891 	struct eth_dev		*dev = &l_ethdev;
1892 	struct usb_request	*req = dev->tx_req;
1893 	unsigned long ts;
1894 	unsigned long timeout = USB_CONNECT_TIMEOUT;
1895 
1896 	debug("%s:...\n", __func__);
1897 
1898 	req->buf = (void *)packet;
1899 	req->context = NULL;
1900 	req->complete = tx_complete;
1901 
1902 	/*
1903 	 * use zlp framing on tx for strict CDC-Ether conformance,
1904 	 * though any robust network rx path ignores extra padding.
1905 	 * and some hardware doesn't like to write zlps.
1906 	 */
1907 	req->zero = 1;
1908 	if (!dev->zlp && (length % dev->in_ep->maxpacket) == 0)
1909 		length++;
1910 
1911 	req->length = length;
1912 #if 0
1913 	/* throttle highspeed IRQ rate back slightly */
1914 	if (gadget_is_dualspeed(dev->gadget))
1915 		req->no_interrupt = (dev->gadget->speed == USB_SPEED_HIGH)
1916 			? ((dev->tx_qlen % qmult) != 0) : 0;
1917 #endif
1918 	dev->tx_qlen = 1;
1919 	ts = get_timer(0);
1920 	packet_sent = 0;
1921 
1922 	retval = usb_ep_queue(dev->in_ep, req, GFP_ATOMIC);
1923 
1924 	if (!retval)
1925 		debug("%s: packet queued\n", __func__);
1926 	while (!packet_sent) {
1927 		if (get_timer(ts) > timeout) {
1928 			printf("timeout sending packets to usb ethernet\n");
1929 			return -1;
1930 		}
1931 		usb_gadget_handle_interrupts();
1932 	}
1933 
1934 	return 0;
1935 }
1936 
1937 static int usb_eth_recv(struct eth_device *netdev)
1938 {
1939 	struct eth_dev *dev = &l_ethdev;
1940 
1941 	usb_gadget_handle_interrupts();
1942 
1943 	if (packet_received) {
1944 		debug("%s: packet received\n", __func__);
1945 		if (dev->rx_req) {
1946 			NetReceive(NetRxPackets[0], dev->rx_req->length);
1947 			packet_received = 0;
1948 
1949 			rx_submit(dev, dev->rx_req, 0);
1950 		} else
1951 			error("dev->rx_req invalid");
1952 	}
1953 	return 0;
1954 }
1955 
1956 void usb_eth_halt(struct eth_device *netdev)
1957 {
1958 	struct eth_dev *dev = &l_ethdev;
1959 
1960 	if (!netdev) {
1961 		error("received NULL ptr");
1962 		return;
1963 	}
1964 
1965 	/* If the gadget not registered, simple return */
1966 	if (!dev->gadget)
1967 		return;
1968 
1969 	usb_gadget_disconnect(dev->gadget);
1970 
1971 	/* Clear pending interrupt */
1972 	if (dev->network_started) {
1973 		usb_gadget_handle_interrupts();
1974 		dev->network_started = 0;
1975 	}
1976 
1977 	usb_gadget_unregister_driver(&eth_driver);
1978 }
1979 
1980 static struct usb_gadget_driver eth_driver = {
1981 	.speed		= DEVSPEED,
1982 
1983 	.bind		= eth_bind,
1984 	.unbind		= eth_unbind,
1985 
1986 	.setup		= eth_setup,
1987 	.disconnect	= eth_disconnect,
1988 
1989 	.suspend	= eth_suspend,
1990 	.resume		= eth_resume,
1991 };
1992 
1993 int usb_eth_initialize(bd_t *bi)
1994 {
1995 	struct eth_device *netdev = &l_netdev;
1996 
1997 	strlcpy(netdev->name, USB_NET_NAME, sizeof(netdev->name));
1998 
1999 	netdev->init = usb_eth_init;
2000 	netdev->send = usb_eth_send;
2001 	netdev->recv = usb_eth_recv;
2002 	netdev->halt = usb_eth_halt;
2003 
2004 #ifdef CONFIG_MCAST_TFTP
2005   #error not supported
2006 #endif
2007 	eth_register(netdev);
2008 	return 0;
2009 }
2010