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