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