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