disable usbip; patch to 2.6.28.10
[kernel-power] / usbhost / usb / gadget / u_ether.c
1 /*
2  * u_ether.c -- Ethernet-over-USB link layer utilities for Gadget stack
3  *
4  * Copyright (C) 2003-2005,2008 David Brownell
5  * Copyright (C) 2003-2004 Robert Schwebel, Benedikt Spranger
6  * Copyright (C) 2008 Nokia Corporation
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 /* #define VERBOSE_DEBUG */
24
25 #include <linux/kernel.h>
26 #include <linux/utsname.h>
27 #include <linux/device.h>
28 #include <linux/ctype.h>
29 #include <linux/etherdevice.h>
30 #include <linux/ethtool.h>
31
32 #include "u_ether.h"
33
34
35 /*
36  * This component encapsulates the Ethernet link glue needed to provide
37  * one (!) network link through the USB gadget stack, normally "usb0".
38  *
39  * The control and data models are handled by the function driver which
40  * connects to this code; such as CDC Ethernet, "CDC Subset", or RNDIS.
41  * That includes all descriptor and endpoint management.
42  *
43  * Link level addressing is handled by this component using module
44  * parameters; if no such parameters are provided, random link level
45  * addresses are used.  Each end of the link uses one address.  The
46  * host end address is exported in various ways, and is often recorded
47  * in configuration databases.
48  *
49  * The driver which assembles each configuration using such a link is
50  * responsible for ensuring that each configuration includes at most one
51  * instance of is network link.  (The network layer provides ways for
52  * this single "physical" link to be used by multiple virtual links.)
53  */
54
55 #define UETH__VERSION   "29-May-2008"
56
57 struct eth_dev {
58         /* lock is held while accessing port_usb
59          * or updating its backlink port_usb->ioport
60          */
61         spinlock_t              lock;
62         struct gether           *port_usb;
63
64         struct net_device       *net;
65         struct usb_gadget       *gadget;
66
67         spinlock_t              req_lock;       /* guard {rx,tx}_reqs */
68         struct list_head        tx_reqs, rx_reqs;
69         atomic_t                tx_qlen;
70
71         unsigned                header_len;
72         struct sk_buff          *(*wrap)(struct sk_buff *skb);
73         int                     (*unwrap)(struct sk_buff *skb);
74
75         struct work_struct      work;
76
77         unsigned long           todo;
78 #define WORK_RX_MEMORY          0
79
80         bool                    zlp;
81         u8                      host_mac[ETH_ALEN];
82 };
83
84 /*-------------------------------------------------------------------------*/
85
86 #define RX_EXTRA        20      /* bytes guarding against rx overflows */
87
88 #define DEFAULT_QLEN    2       /* double buffering by default */
89
90
91 #ifdef CONFIG_USB_GADGET_DUALSPEED
92
93 static unsigned qmult = 5;
94 module_param(qmult, uint, S_IRUGO|S_IWUSR);
95 MODULE_PARM_DESC(qmult, "queue length multiplier at high speed");
96
97 #else   /* full speed (low speed doesn't do bulk) */
98 #define qmult           1
99 #endif
100
101 /* for dual-speed hardware, use deeper queues at highspeed */
102 static inline int qlen(struct usb_gadget *gadget)
103 {
104         if (gadget_is_dualspeed(gadget) && gadget->speed == USB_SPEED_HIGH)
105                 return qmult * DEFAULT_QLEN;
106         else
107                 return DEFAULT_QLEN;
108 }
109
110 /*-------------------------------------------------------------------------*/
111
112 /* REVISIT there must be a better way than having two sets
113  * of debug calls ...
114  */
115
116 #undef DBG
117 #undef VDBG
118 #undef ERROR
119
120 #define xprintk(d, level, fmt, args...) \
121         printk(level "%s: " fmt , (d)->net->name , ## args)
122
123 #ifdef DEBUG
124 #undef DEBUG
125 #define DBG(dev, fmt, args...) \
126         xprintk(dev , KERN_DEBUG , fmt , ## args)
127 #else
128 #define DBG(dev, fmt, args...) \
129         do { } while (0)
130 #endif /* DEBUG */
131
132 #ifdef VERBOSE_DEBUG
133 #define VDBG    DBG
134 #else
135 #define VDBG(dev, fmt, args...) \
136         do { } while (0)
137 #endif /* DEBUG */
138
139 #define ERROR(dev, fmt, args...) \
140         xprintk(dev , KERN_ERR , fmt , ## args)
141 #define ETH_INFO(dev, fmt, args...) \
142         xprintk(dev , KERN_INFO , fmt , ## args)
143
144 /*-------------------------------------------------------------------------*/
145
146 /* NETWORK DRIVER HOOKUP (to the layer above this driver) */
147
148 static int eth_change_mtu(struct net_device *net, int new_mtu)
149 {
150         struct eth_dev  *dev = netdev_priv(net);
151         unsigned long   flags;
152         int             status = 0;
153
154         /* don't change MTU on "live" link (peer won't know) */
155         spin_lock_irqsave(&dev->lock, flags);
156         if (dev->port_usb)
157                 status = -EBUSY;
158         else if (new_mtu <= ETH_HLEN || new_mtu > ETH_FRAME_LEN)
159                 status = -ERANGE;
160         else
161                 net->mtu = new_mtu;
162         spin_unlock_irqrestore(&dev->lock, flags);
163
164         return status;
165 }
166
167 static void eth_get_drvinfo(struct net_device *net, struct ethtool_drvinfo *p)
168 {
169         struct eth_dev  *dev = netdev_priv(net);
170
171         strlcpy(p->driver, "g_ether", sizeof p->driver);
172         strlcpy(p->version, UETH__VERSION, sizeof p->version);
173         strlcpy(p->fw_version, dev->gadget->name, sizeof p->fw_version);
174         strlcpy(p->bus_info, dev_name(&dev->gadget->dev), sizeof p->bus_info);
175 }
176
177 /* REVISIT can also support:
178  *   - WOL (by tracking suspends and issuing remote wakeup)
179  *   - msglevel (implies updated messaging)
180  *   - ... probably more ethtool ops
181  */
182
183 static struct ethtool_ops ops = {
184         .get_drvinfo = eth_get_drvinfo,
185         .get_link = ethtool_op_get_link,
186 };
187
188 static void defer_kevent(struct eth_dev *dev, int flag)
189 {
190         if (test_and_set_bit(flag, &dev->todo))
191                 return;
192         if (!schedule_work(&dev->work))
193                 ERROR(dev, "kevent %d may have been dropped\n", flag);
194         else
195                 DBG(dev, "kevent %d scheduled\n", flag);
196 }
197
198 static void rx_complete(struct usb_ep *ep, struct usb_request *req);
199
200 static int
201 rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags)
202 {
203         struct sk_buff  *skb;
204         int             retval = -ENOMEM;
205         size_t          size = 0;
206         struct usb_ep   *out;
207         unsigned long   flags;
208
209         spin_lock_irqsave(&dev->lock, flags);
210         if (dev->port_usb)
211                 out = dev->port_usb->out_ep;
212         else
213                 out = NULL;
214         spin_unlock_irqrestore(&dev->lock, flags);
215
216         if (!out)
217                 return -ENOTCONN;
218
219
220         /* Padding up to RX_EXTRA handles minor disagreements with host.
221          * Normally we use the USB "terminate on short read" convention;
222          * so allow up to (N*maxpacket), since that memory is normally
223          * already allocated.  Some hardware doesn't deal well with short
224          * reads (e.g. DMA must be N*maxpacket), so for now don't trim a
225          * byte off the end (to force hardware errors on overflow).
226          *
227          * RNDIS uses internal framing, and explicitly allows senders to
228          * pad to end-of-packet.  That's potentially nice for speed, but
229          * means receivers can't recover lost synch on their own (because
230          * new packets don't only start after a short RX).
231          */
232         size += sizeof(struct ethhdr) + dev->net->mtu + RX_EXTRA;
233         size += dev->port_usb->header_len;
234         size += out->maxpacket - 1;
235         size -= size % out->maxpacket;
236
237         skb = alloc_skb(size + NET_IP_ALIGN, gfp_flags);
238         if (skb == NULL) {
239                 DBG(dev, "no rx skb\n");
240                 goto enomem;
241         }
242
243         /* Some platforms perform better when IP packets are aligned,
244          * but on at least one, checksumming fails otherwise.  Note:
245          * RNDIS headers involve variable numbers of LE32 values.
246          */
247         skb_reserve(skb, NET_IP_ALIGN);
248
249         req->buf = skb->data;
250         req->length = size;
251         req->complete = rx_complete;
252         req->context = skb;
253
254         retval = usb_ep_queue(out, req, gfp_flags);
255         if (retval == -ENOMEM)
256 enomem:
257                 defer_kevent(dev, WORK_RX_MEMORY);
258         if (retval) {
259                 DBG(dev, "rx submit --> %d\n", retval);
260                 if (skb)
261                         dev_kfree_skb_any(skb);
262                 spin_lock_irqsave(&dev->req_lock, flags);
263                 list_add(&req->list, &dev->rx_reqs);
264                 spin_unlock_irqrestore(&dev->req_lock, flags);
265         }
266         return retval;
267 }
268
269 static void rx_complete(struct usb_ep *ep, struct usb_request *req)
270 {
271         struct sk_buff  *skb = req->context;
272         struct eth_dev  *dev = ep->driver_data;
273         int             status = req->status;
274
275         switch (status) {
276
277         /* normal completion */
278         case 0:
279                 skb_put(skb, req->actual);
280                 if (dev->unwrap)
281                         status = dev->unwrap(skb);
282                 if (status < 0
283                                 || ETH_HLEN > skb->len
284                                 || skb->len > ETH_FRAME_LEN) {
285                         dev->net->stats.rx_errors++;
286                         dev->net->stats.rx_length_errors++;
287                         DBG(dev, "rx length %d\n", skb->len);
288                         break;
289                 }
290
291                 skb->protocol = eth_type_trans(skb, dev->net);
292                 dev->net->stats.rx_packets++;
293                 dev->net->stats.rx_bytes += skb->len;
294
295                 /* no buffer copies needed, unless hardware can't
296                  * use skb buffers.
297                  */
298                 status = netif_rx(skb);
299                 skb = NULL;
300                 break;
301
302         /* software-driven interface shutdown */
303         case -ECONNRESET:               /* unlink */
304         case -ESHUTDOWN:                /* disconnect etc */
305                 VDBG(dev, "rx shutdown, code %d\n", status);
306                 goto quiesce;
307
308         /* for hardware automagic (such as pxa) */
309         case -ECONNABORTED:             /* endpoint reset */
310                 DBG(dev, "rx %s reset\n", ep->name);
311                 defer_kevent(dev, WORK_RX_MEMORY);
312 quiesce:
313                 dev_kfree_skb_any(skb);
314                 goto clean;
315
316         /* data overrun */
317         case -EOVERFLOW:
318                 dev->net->stats.rx_over_errors++;
319                 /* FALLTHROUGH */
320
321         default:
322                 dev->net->stats.rx_errors++;
323                 DBG(dev, "rx status %d\n", status);
324                 break;
325         }
326
327         if (skb)
328                 dev_kfree_skb_any(skb);
329         if (!netif_running(dev->net)) {
330 clean:
331                 spin_lock(&dev->req_lock);
332                 list_add(&req->list, &dev->rx_reqs);
333                 spin_unlock(&dev->req_lock);
334                 req = NULL;
335         }
336         if (req)
337                 rx_submit(dev, req, GFP_ATOMIC);
338 }
339
340 static int prealloc(struct list_head *list, struct usb_ep *ep, unsigned n)
341 {
342         unsigned                i;
343         struct usb_request      *req;
344
345         if (!n)
346                 return -ENOMEM;
347
348         /* queue/recycle up to N requests */
349         i = n;
350         list_for_each_entry(req, list, list) {
351                 if (i-- == 0)
352                         goto extra;
353         }
354         while (i--) {
355                 req = usb_ep_alloc_request(ep, GFP_ATOMIC);
356                 if (!req)
357                         return list_empty(list) ? -ENOMEM : 0;
358                 list_add(&req->list, list);
359         }
360         return 0;
361
362 extra:
363         /* free extras */
364         for (;;) {
365                 struct list_head        *next;
366
367                 next = req->list.next;
368                 list_del(&req->list);
369                 usb_ep_free_request(ep, req);
370
371                 if (next == list)
372                         break;
373
374                 req = container_of(next, struct usb_request, list);
375         }
376         return 0;
377 }
378
379 static int alloc_requests(struct eth_dev *dev, struct gether *link, unsigned n)
380 {
381         int     status;
382
383         spin_lock(&dev->req_lock);
384         status = prealloc(&dev->tx_reqs, link->in_ep, n);
385         if (status < 0)
386                 goto fail;
387         status = prealloc(&dev->rx_reqs, link->out_ep, n);
388         if (status < 0)
389                 goto fail;
390         goto done;
391 fail:
392         DBG(dev, "can't alloc requests\n");
393 done:
394         spin_unlock(&dev->req_lock);
395         return status;
396 }
397
398 static void rx_fill(struct eth_dev *dev, gfp_t gfp_flags)
399 {
400         struct usb_request      *req;
401         unsigned long           flags;
402
403         /* fill unused rxq slots with some skb */
404         spin_lock_irqsave(&dev->req_lock, flags);
405         while (!list_empty(&dev->rx_reqs)) {
406                 req = container_of(dev->rx_reqs.next,
407                                 struct usb_request, list);
408                 list_del_init(&req->list);
409                 spin_unlock_irqrestore(&dev->req_lock, flags);
410
411                 if (rx_submit(dev, req, gfp_flags) < 0) {
412                         defer_kevent(dev, WORK_RX_MEMORY);
413                         return;
414                 }
415
416                 spin_lock_irqsave(&dev->req_lock, flags);
417         }
418         spin_unlock_irqrestore(&dev->req_lock, flags);
419 }
420
421 static void eth_work(struct work_struct *work)
422 {
423         struct eth_dev  *dev = container_of(work, struct eth_dev, work);
424
425         if (test_and_clear_bit(WORK_RX_MEMORY, &dev->todo)) {
426                 if (netif_running(dev->net))
427                         rx_fill(dev, GFP_KERNEL);
428         }
429
430         if (dev->todo)
431                 DBG(dev, "work done, flags = 0x%lx\n", dev->todo);
432 }
433
434 static void tx_complete(struct usb_ep *ep, struct usb_request *req)
435 {
436         struct sk_buff  *skb = req->context;
437         struct eth_dev  *dev = ep->driver_data;
438
439         switch (req->status) {
440         default:
441                 dev->net->stats.tx_errors++;
442                 VDBG(dev, "tx err %d\n", req->status);
443                 /* FALLTHROUGH */
444         case -ECONNRESET:               /* unlink */
445         case -ESHUTDOWN:                /* disconnect etc */
446                 break;
447         case 0:
448                 dev->net->stats.tx_bytes += skb->len;
449         }
450         dev->net->stats.tx_packets++;
451
452         spin_lock(&dev->req_lock);
453         list_add(&req->list, &dev->tx_reqs);
454         spin_unlock(&dev->req_lock);
455         dev_kfree_skb_any(skb);
456
457         atomic_dec(&dev->tx_qlen);
458         if (netif_carrier_ok(dev->net))
459                 netif_wake_queue(dev->net);
460 }
461
462 static inline int is_promisc(u16 cdc_filter)
463 {
464         return cdc_filter & USB_CDC_PACKET_TYPE_PROMISCUOUS;
465 }
466
467 static int eth_start_xmit(struct sk_buff *skb, struct net_device *net)
468 {
469         struct eth_dev          *dev = netdev_priv(net);
470         int                     length = skb->len;
471         int                     retval;
472         struct usb_request      *req = NULL;
473         unsigned long           flags;
474         struct usb_ep           *in;
475         u16                     cdc_filter;
476
477         spin_lock_irqsave(&dev->lock, flags);
478         if (dev->port_usb) {
479                 in = dev->port_usb->in_ep;
480                 cdc_filter = dev->port_usb->cdc_filter;
481         } else {
482                 in = NULL;
483                 cdc_filter = 0;
484         }
485         spin_unlock_irqrestore(&dev->lock, flags);
486
487         if (!in) {
488                 dev_kfree_skb_any(skb);
489                 return 0;
490         }
491
492         /* apply outgoing CDC or RNDIS filters */
493         if (!is_promisc(cdc_filter)) {
494                 u8              *dest = skb->data;
495
496                 if (is_multicast_ether_addr(dest)) {
497                         u16     type;
498
499                         /* ignores USB_CDC_PACKET_TYPE_MULTICAST and host
500                          * SET_ETHERNET_MULTICAST_FILTERS requests
501                          */
502                         if (is_broadcast_ether_addr(dest))
503                                 type = USB_CDC_PACKET_TYPE_BROADCAST;
504                         else
505                                 type = USB_CDC_PACKET_TYPE_ALL_MULTICAST;
506                         if (!(cdc_filter & type)) {
507                                 dev_kfree_skb_any(skb);
508                                 return 0;
509                         }
510                 }
511                 /* ignores USB_CDC_PACKET_TYPE_DIRECTED */
512         }
513
514         spin_lock_irqsave(&dev->req_lock, flags);
515         /*
516          * this freelist can be empty if an interrupt triggered disconnect()
517          * and reconfigured the gadget (shutting down this queue) after the
518          * network stack decided to xmit but before we got the spinlock.
519          */
520         if (list_empty(&dev->tx_reqs)) {
521                 spin_unlock_irqrestore(&dev->req_lock, flags);
522                 return 1;
523         }
524
525         req = container_of(dev->tx_reqs.next, struct usb_request, list);
526         list_del(&req->list);
527
528         /* temporarily stop TX queue when the freelist empties */
529         if (list_empty(&dev->tx_reqs))
530                 netif_stop_queue(net);
531         spin_unlock_irqrestore(&dev->req_lock, flags);
532
533         /* no buffer copies needed, unless the network stack did it
534          * or the hardware can't use skb buffers.
535          * or there's not enough space for extra headers we need
536          */
537         if (dev->wrap) {
538                 struct sk_buff  *skb_new;
539
540                 skb_new = dev->wrap(skb);
541                 if (!skb_new)
542                         goto drop;
543
544                 dev_kfree_skb_any(skb);
545                 skb = skb_new;
546                 length = skb->len;
547         }
548         req->buf = skb->data;
549         req->context = skb;
550         req->complete = tx_complete;
551
552         /* use zlp framing on tx for strict CDC-Ether conformance,
553          * though any robust network rx path ignores extra padding.
554          * and some hardware doesn't like to write zlps.
555          */
556         req->zero = 1;
557         if (!dev->zlp && (length % in->maxpacket) == 0)
558                 length++;
559
560         req->length = length;
561
562         /* throttle highspeed IRQ rate back slightly */
563         if (gadget_is_dualspeed(dev->gadget))
564                 req->no_interrupt = (dev->gadget->speed == USB_SPEED_HIGH)
565                         ? ((atomic_read(&dev->tx_qlen) % qmult) != 0)
566                         : 0;
567
568         retval = usb_ep_queue(in, req, GFP_ATOMIC);
569         switch (retval) {
570         default:
571                 DBG(dev, "tx queue err %d\n", retval);
572                 break;
573         case 0:
574                 net->trans_start = jiffies;
575                 atomic_inc(&dev->tx_qlen);
576         }
577
578         if (retval) {
579 drop:
580                 dev->net->stats.tx_dropped++;
581                 dev_kfree_skb_any(skb);
582                 spin_lock_irqsave(&dev->req_lock, flags);
583                 if (list_empty(&dev->tx_reqs))
584                         netif_start_queue(net);
585                 list_add(&req->list, &dev->tx_reqs);
586                 spin_unlock_irqrestore(&dev->req_lock, flags);
587         }
588         return 0;
589 }
590
591 /*-------------------------------------------------------------------------*/
592
593 static void eth_start(struct eth_dev *dev, gfp_t gfp_flags)
594 {
595         DBG(dev, "%s\n", __func__);
596
597         /* fill the rx queue */
598         rx_fill(dev, gfp_flags);
599
600         /* and open the tx floodgates */
601         atomic_set(&dev->tx_qlen, 0);
602         netif_wake_queue(dev->net);
603 }
604
605 static int eth_open(struct net_device *net)
606 {
607         struct eth_dev  *dev = netdev_priv(net);
608         struct gether   *link;
609
610         DBG(dev, "%s\n", __func__);
611         if (netif_carrier_ok(dev->net))
612                 eth_start(dev, GFP_KERNEL);
613
614         spin_lock_irq(&dev->lock);
615         link = dev->port_usb;
616         if (link && link->open)
617                 link->open(link);
618         spin_unlock_irq(&dev->lock);
619
620         return 0;
621 }
622
623 static int eth_stop(struct net_device *net)
624 {
625         struct eth_dev  *dev = netdev_priv(net);
626         unsigned long   flags;
627
628         VDBG(dev, "%s\n", __func__);
629         netif_stop_queue(net);
630
631         DBG(dev, "stop stats: rx/tx %ld/%ld, errs %ld/%ld\n",
632                 dev->net->stats.rx_packets, dev->net->stats.tx_packets,
633                 dev->net->stats.rx_errors, dev->net->stats.tx_errors
634                 );
635
636         /* ensure there are no more active requests */
637         spin_lock_irqsave(&dev->lock, flags);
638         if (dev->port_usb) {
639                 struct gether   *link = dev->port_usb;
640
641                 if (link->close)
642                         link->close(link);
643
644                 /* NOTE:  we have no abort-queue primitive we could use
645                  * to cancel all pending I/O.  Instead, we disable then
646                  * reenable the endpoints ... this idiom may leave toggle
647                  * wrong, but that's a self-correcting error.
648                  *
649                  * REVISIT:  we *COULD* just let the transfers complete at
650                  * their own pace; the network stack can handle old packets.
651                  * For the moment we leave this here, since it works.
652                  */
653                 usb_ep_disable(link->in_ep);
654                 usb_ep_disable(link->out_ep);
655                 if (netif_carrier_ok(net)) {
656                         DBG(dev, "host still using in/out endpoints\n");
657                         usb_ep_enable(link->in_ep, link->in);
658                         usb_ep_enable(link->out_ep, link->out);
659                 }
660         }
661         spin_unlock_irqrestore(&dev->lock, flags);
662
663         return 0;
664 }
665
666 /*-------------------------------------------------------------------------*/
667
668 /* initial value, changed by "ifconfig usb0 hw ether xx:xx:xx:xx:xx:xx" */
669 static char *dev_addr;
670 module_param(dev_addr, charp, S_IRUGO);
671 MODULE_PARM_DESC(dev_addr, "Device Ethernet Address");
672
673 /* this address is invisible to ifconfig */
674 static char *host_addr;
675 module_param(host_addr, charp, S_IRUGO);
676 MODULE_PARM_DESC(host_addr, "Host Ethernet Address");
677
678
679 static u8 __init nibble(unsigned char c)
680 {
681         if (isdigit(c))
682                 return c - '0';
683         c = toupper(c);
684         if (isxdigit(c))
685                 return 10 + c - 'A';
686         return 0;
687 }
688
689 static int __init get_ether_addr(const char *str, u8 *dev_addr)
690 {
691         if (str) {
692                 unsigned        i;
693
694                 for (i = 0; i < 6; i++) {
695                         unsigned char num;
696
697                         if ((*str == '.') || (*str == ':'))
698                                 str++;
699                         num = nibble(*str++) << 4;
700                         num |= (nibble(*str++));
701                         dev_addr [i] = num;
702                 }
703                 if (is_valid_ether_addr(dev_addr))
704                         return 0;
705         }
706         random_ether_addr(dev_addr);
707         return 1;
708 }
709
710 static struct eth_dev *the_dev;
711
712
713 /**
714  * gether_setup - initialize one ethernet-over-usb link
715  * @g: gadget to associated with these links
716  * @ethaddr: NULL, or a buffer in which the ethernet address of the
717  *      host side of the link is recorded
718  * Context: may sleep
719  *
720  * This sets up the single network link that may be exported by a
721  * gadget driver using this framework.  The link layer addresses are
722  * set up using module parameters.
723  *
724  * Returns negative errno, or zero on success
725  */
726 int __init gether_setup(struct usb_gadget *g, u8 ethaddr[ETH_ALEN])
727 {
728         struct eth_dev          *dev;
729         struct net_device       *net;
730         int                     status;
731
732         if (the_dev)
733                 return -EBUSY;
734
735         net = alloc_etherdev(sizeof *dev);
736         if (!net)
737                 return -ENOMEM;
738
739         dev = netdev_priv(net);
740         spin_lock_init(&dev->lock);
741         spin_lock_init(&dev->req_lock);
742         INIT_WORK(&dev->work, eth_work);
743         INIT_LIST_HEAD(&dev->tx_reqs);
744         INIT_LIST_HEAD(&dev->rx_reqs);
745
746         /* network device setup */
747         dev->net = net;
748         strcpy(net->name, "usb%d");
749
750         if (get_ether_addr(dev_addr, net->dev_addr))
751                 dev_warn(&g->dev,
752                         "using random %s ethernet address\n", "self");
753         if (get_ether_addr(host_addr, dev->host_mac))
754                 dev_warn(&g->dev,
755                         "using random %s ethernet address\n", "host");
756
757         if (ethaddr)
758                 memcpy(ethaddr, dev->host_mac, ETH_ALEN);
759
760         net->change_mtu = eth_change_mtu;
761         net->hard_start_xmit = eth_start_xmit;
762         net->open = eth_open;
763         net->stop = eth_stop;
764         /* watchdog_timeo, tx_timeout ... */
765         /* set_multicast_list */
766         SET_ETHTOOL_OPS(net, &ops);
767
768         /* two kinds of host-initiated state changes:
769          *  - iff DATA transfer is active, carrier is "on"
770          *  - tx queueing enabled if open *and* carrier is "on"
771          */
772         netif_stop_queue(net);
773         netif_carrier_off(net);
774
775         dev->gadget = g;
776         SET_NETDEV_DEV(net, &g->dev);
777
778         status = register_netdev(net);
779         if (status < 0) {
780                 dev_dbg(&g->dev, "register_netdev failed, %d\n", status);
781                 free_netdev(net);
782         } else {
783                 DECLARE_MAC_BUF(tmp);
784
785                 ETH_INFO(dev, "MAC %s\n", print_mac(tmp, net->dev_addr));
786                 ETH_INFO(dev, "HOST MAC %s\n", print_mac(tmp, dev->host_mac));
787
788                 the_dev = dev;
789         }
790
791         return status;
792 }
793
794 /**
795  * gether_cleanup - remove Ethernet-over-USB device
796  * Context: may sleep
797  *
798  * This is called to free all resources allocated by @gether_setup().
799  */
800 void gether_cleanup(void)
801 {
802         if (!the_dev)
803                 return;
804
805         netif_stop_queue(the_dev->net);
806         netif_carrier_off(the_dev->net);
807         unregister_netdev(the_dev->net);
808         free_netdev(the_dev->net);
809
810         /* assuming we used keventd, it must quiesce too */
811         flush_scheduled_work();
812
813         the_dev = NULL;
814 }
815
816
817 /**
818  * gether_connect - notify network layer that USB link is active
819  * @link: the USB link, set up with endpoints, descriptors matching
820  *      current device speed, and any framing wrapper(s) set up.
821  * Context: irqs blocked
822  *
823  * This is called to activate endpoints and let the network layer know
824  * the connection is active ("carrier detect").  It may cause the I/O
825  * queues to open and start letting network packets flow, but will in
826  * any case activate the endpoints so that they respond properly to the
827  * USB host.
828  *
829  * Verify net_device pointer returned using IS_ERR().  If it doesn't
830  * indicate some error code (negative errno), ep->driver_data values
831  * have been overwritten.
832  */
833 struct net_device *gether_connect(struct gether *link)
834 {
835         struct eth_dev          *dev = the_dev;
836         int                     result = 0;
837
838         if (!dev)
839                 return ERR_PTR(-EINVAL);
840
841         link->in_ep->driver_data = dev;
842         result = usb_ep_enable(link->in_ep, link->in);
843         if (result != 0) {
844                 DBG(dev, "enable %s --> %d\n",
845                         link->in_ep->name, result);
846                 goto fail0;
847         }
848
849         link->out_ep->driver_data = dev;
850         result = usb_ep_enable(link->out_ep, link->out);
851         if (result != 0) {
852                 DBG(dev, "enable %s --> %d\n",
853                         link->out_ep->name, result);
854                 goto fail1;
855         }
856
857         if (result == 0)
858                 result = alloc_requests(dev, link, qlen(dev->gadget));
859
860         if (result == 0) {
861                 dev->zlp = link->is_zlp_ok;
862                 DBG(dev, "qlen %d\n", qlen(dev->gadget));
863
864                 dev->header_len = link->header_len;
865                 dev->unwrap = link->unwrap;
866                 dev->wrap = link->wrap;
867
868                 spin_lock(&dev->lock);
869                 dev->port_usb = link;
870                 link->ioport = dev;
871                 if (netif_running(dev->net)) {
872                         if (link->open)
873                                 link->open(link);
874                 } else {
875                         if (link->close)
876                                 link->close(link);
877                 }
878                 spin_unlock(&dev->lock);
879
880                 netif_carrier_on(dev->net);
881                 if (netif_running(dev->net))
882                         eth_start(dev, GFP_ATOMIC);
883
884         /* on error, disable any endpoints  */
885         } else {
886                 (void) usb_ep_disable(link->out_ep);
887 fail1:
888                 (void) usb_ep_disable(link->in_ep);
889         }
890 fail0:
891         /* caller is responsible for cleanup on error */
892         if (result < 0)
893                 return ERR_PTR(result);
894         return dev->net;
895 }
896
897 /**
898  * gether_disconnect - notify network layer that USB link is inactive
899  * @link: the USB link, on which gether_connect() was called
900  * Context: irqs blocked
901  *
902  * This is called to deactivate endpoints and let the network layer know
903  * the connection went inactive ("no carrier").
904  *
905  * On return, the state is as if gether_connect() had never been called.
906  * The endpoints are inactive, and accordingly without active USB I/O.
907  * Pointers to endpoint descriptors and endpoint private data are nulled.
908  */
909 void gether_disconnect(struct gether *link)
910 {
911         struct eth_dev          *dev = link->ioport;
912         struct usb_request      *req;
913
914         WARN_ON(!dev);
915         if (!dev)
916                 return;
917
918         DBG(dev, "%s\n", __func__);
919
920         netif_stop_queue(dev->net);
921         netif_carrier_off(dev->net);
922
923         /* disable endpoints, forcing (synchronous) completion
924          * of all pending i/o.  then free the request objects
925          * and forget about the endpoints.
926          */
927         usb_ep_disable(link->in_ep);
928         spin_lock(&dev->req_lock);
929         while (!list_empty(&dev->tx_reqs)) {
930                 req = container_of(dev->tx_reqs.next,
931                                         struct usb_request, list);
932                 list_del(&req->list);
933
934                 spin_unlock(&dev->req_lock);
935                 usb_ep_free_request(link->in_ep, req);
936                 spin_lock(&dev->req_lock);
937         }
938         spin_unlock(&dev->req_lock);
939         link->in_ep->driver_data = NULL;
940         link->in = NULL;
941
942         usb_ep_disable(link->out_ep);
943         spin_lock(&dev->req_lock);
944         while (!list_empty(&dev->rx_reqs)) {
945                 req = container_of(dev->rx_reqs.next,
946                                         struct usb_request, list);
947                 list_del(&req->list);
948
949                 spin_unlock(&dev->req_lock);
950                 usb_ep_free_request(link->out_ep, req);
951                 spin_lock(&dev->req_lock);
952         }
953         spin_unlock(&dev->req_lock);
954         link->out_ep->driver_data = NULL;
955         link->out = NULL;
956
957         /* finish forgetting about this USB link episode */
958         dev->header_len = 0;
959         dev->unwrap = NULL;
960         dev->wrap = NULL;
961
962         spin_lock(&dev->lock);
963         dev->port_usb = NULL;
964         link->ioport = NULL;
965         spin_unlock(&dev->lock);
966 }