GNU Linux-libre 4.14.332-gnu1
[releases.git] / drivers / usb / gadget / function / 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
14 /* #define VERBOSE_DEBUG */
15
16 #include <linux/kernel.h>
17 #include <linux/module.h>
18 #include <linux/gfp.h>
19 #include <linux/device.h>
20 #include <linux/ctype.h>
21 #include <linux/etherdevice.h>
22 #include <linux/ethtool.h>
23 #include <linux/if_vlan.h>
24
25 #include "u_ether.h"
26
27
28 /*
29  * This component encapsulates the Ethernet link glue needed to provide
30  * one (!) network link through the USB gadget stack, normally "usb0".
31  *
32  * The control and data models are handled by the function driver which
33  * connects to this code; such as CDC Ethernet (ECM or EEM),
34  * "CDC Subset", or RNDIS.  That includes all descriptor and endpoint
35  * management.
36  *
37  * Link level addressing is handled by this component using module
38  * parameters; if no such parameters are provided, random link level
39  * addresses are used.  Each end of the link uses one address.  The
40  * host end address is exported in various ways, and is often recorded
41  * in configuration databases.
42  *
43  * The driver which assembles each configuration using such a link is
44  * responsible for ensuring that each configuration includes at most one
45  * instance of is network link.  (The network layer provides ways for
46  * this single "physical" link to be used by multiple virtual links.)
47  */
48
49 #define UETH__VERSION   "29-May-2008"
50
51 /* Experiments show that both Linux and Windows hosts allow up to 16k
52  * frame sizes. Set the max MTU size to 15k+52 to prevent allocating 32k
53  * blocks and still have efficient handling. */
54 #define GETHER_MAX_MTU_SIZE 15412
55 #define GETHER_MAX_ETH_FRAME_LEN (GETHER_MAX_MTU_SIZE + ETH_HLEN)
56
57 struct eth_dev {
58         /* lock is held while accessing port_usb
59          */
60         spinlock_t              lock;
61         struct gether           *port_usb;
62
63         struct net_device       *net;
64         struct usb_gadget       *gadget;
65
66         spinlock_t              req_lock;       /* guard {rx,tx}_reqs */
67         struct list_head        tx_reqs, rx_reqs;
68         atomic_t                tx_qlen;
69
70         struct sk_buff_head     rx_frames;
71
72         unsigned                qmult;
73
74         unsigned                header_len;
75         struct sk_buff          *(*wrap)(struct gether *, struct sk_buff *skb);
76         int                     (*unwrap)(struct gether *,
77                                                 struct sk_buff *skb,
78                                                 struct sk_buff_head *list);
79
80         struct work_struct      work;
81
82         unsigned long           todo;
83 #define WORK_RX_MEMORY          0
84
85         bool                    zlp;
86         bool                    no_skb_reserve;
87         u8                      host_mac[ETH_ALEN];
88         u8                      dev_mac[ETH_ALEN];
89 };
90
91 /*-------------------------------------------------------------------------*/
92
93 #define RX_EXTRA        20      /* bytes guarding against rx overflows */
94
95 #define DEFAULT_QLEN    2       /* double buffering by default */
96
97 /* for dual-speed hardware, use deeper queues at high/super speed */
98 static inline int qlen(struct usb_gadget *gadget, unsigned qmult)
99 {
100         if (gadget_is_dualspeed(gadget) && (gadget->speed == USB_SPEED_HIGH ||
101                                             gadget->speed >= USB_SPEED_SUPER))
102                 return qmult * DEFAULT_QLEN;
103         else
104                 return DEFAULT_QLEN;
105 }
106
107 /*-------------------------------------------------------------------------*/
108
109 /* REVISIT there must be a better way than having two sets
110  * of debug calls ...
111  */
112
113 #undef DBG
114 #undef VDBG
115 #undef ERROR
116 #undef INFO
117
118 #define xprintk(d, level, fmt, args...) \
119         printk(level "%s: " fmt , (d)->net->name , ## args)
120
121 #ifdef DEBUG
122 #undef DEBUG
123 #define DBG(dev, fmt, args...) \
124         xprintk(dev , KERN_DEBUG , fmt , ## args)
125 #else
126 #define DBG(dev, fmt, args...) \
127         do { } while (0)
128 #endif /* DEBUG */
129
130 #ifdef VERBOSE_DEBUG
131 #define VDBG    DBG
132 #else
133 #define VDBG(dev, fmt, args...) \
134         do { } while (0)
135 #endif /* DEBUG */
136
137 #define ERROR(dev, fmt, args...) \
138         xprintk(dev , KERN_ERR , fmt , ## args)
139 #define INFO(dev, fmt, args...) \
140         xprintk(dev , KERN_INFO , fmt , ## args)
141
142 /*-------------------------------------------------------------------------*/
143
144 /* NETWORK DRIVER HOOKUP (to the layer above this driver) */
145
146 static void eth_get_drvinfo(struct net_device *net, struct ethtool_drvinfo *p)
147 {
148         struct eth_dev *dev = netdev_priv(net);
149
150         strlcpy(p->driver, "g_ether", sizeof(p->driver));
151         strlcpy(p->version, UETH__VERSION, sizeof(p->version));
152         strlcpy(p->fw_version, dev->gadget->name, sizeof(p->fw_version));
153         strlcpy(p->bus_info, dev_name(&dev->gadget->dev), sizeof(p->bus_info));
154 }
155
156 /* REVISIT can also support:
157  *   - WOL (by tracking suspends and issuing remote wakeup)
158  *   - msglevel (implies updated messaging)
159  *   - ... probably more ethtool ops
160  */
161
162 static const struct ethtool_ops ops = {
163         .get_drvinfo = eth_get_drvinfo,
164         .get_link = ethtool_op_get_link,
165 };
166
167 static void defer_kevent(struct eth_dev *dev, int flag)
168 {
169         if (test_and_set_bit(flag, &dev->todo))
170                 return;
171         if (!schedule_work(&dev->work))
172                 ERROR(dev, "kevent %d may have been dropped\n", flag);
173         else
174                 DBG(dev, "kevent %d scheduled\n", flag);
175 }
176
177 static void rx_complete(struct usb_ep *ep, struct usb_request *req);
178
179 static int
180 rx_submit(struct eth_dev *dev, struct usb_request *req, gfp_t gfp_flags)
181 {
182         struct usb_gadget *g = dev->gadget;
183         struct sk_buff  *skb;
184         int             retval = -ENOMEM;
185         size_t          size = 0;
186         struct usb_ep   *out;
187         unsigned long   flags;
188
189         spin_lock_irqsave(&dev->lock, flags);
190         if (dev->port_usb)
191                 out = dev->port_usb->out_ep;
192         else
193                 out = NULL;
194
195         if (!out)
196         {
197                 spin_unlock_irqrestore(&dev->lock, flags);
198                 return -ENOTCONN;
199         }
200
201         /* Padding up to RX_EXTRA handles minor disagreements with host.
202          * Normally we use the USB "terminate on short read" convention;
203          * so allow up to (N*maxpacket), since that memory is normally
204          * already allocated.  Some hardware doesn't deal well with short
205          * reads (e.g. DMA must be N*maxpacket), so for now don't trim a
206          * byte off the end (to force hardware errors on overflow).
207          *
208          * RNDIS uses internal framing, and explicitly allows senders to
209          * pad to end-of-packet.  That's potentially nice for speed, but
210          * means receivers can't recover lost synch on their own (because
211          * new packets don't only start after a short RX).
212          */
213         size += sizeof(struct ethhdr) + dev->net->mtu + RX_EXTRA;
214         size += dev->port_usb->header_len;
215
216         if (g->quirk_ep_out_aligned_size) {
217                 size += out->maxpacket - 1;
218                 size -= size % out->maxpacket;
219         }
220
221         if (dev->port_usb->is_fixed)
222                 size = max_t(size_t, size, dev->port_usb->fixed_out_len);
223         spin_unlock_irqrestore(&dev->lock, flags);
224
225         skb = __netdev_alloc_skb(dev->net, size + NET_IP_ALIGN, gfp_flags);
226         if (skb == NULL) {
227                 DBG(dev, "no rx skb\n");
228                 goto enomem;
229         }
230
231         /* Some platforms perform better when IP packets are aligned,
232          * but on at least one, checksumming fails otherwise.  Note:
233          * RNDIS headers involve variable numbers of LE32 values.
234          */
235         if (likely(!dev->no_skb_reserve))
236                 skb_reserve(skb, NET_IP_ALIGN);
237
238         req->buf = skb->data;
239         req->length = size;
240         req->complete = rx_complete;
241         req->context = skb;
242
243         retval = usb_ep_queue(out, req, gfp_flags);
244         if (retval == -ENOMEM)
245 enomem:
246                 defer_kevent(dev, WORK_RX_MEMORY);
247         if (retval) {
248                 DBG(dev, "rx submit --> %d\n", retval);
249                 if (skb)
250                         dev_kfree_skb_any(skb);
251                 spin_lock_irqsave(&dev->req_lock, flags);
252                 list_add(&req->list, &dev->rx_reqs);
253                 spin_unlock_irqrestore(&dev->req_lock, flags);
254         }
255         return retval;
256 }
257
258 static void rx_complete(struct usb_ep *ep, struct usb_request *req)
259 {
260         struct sk_buff  *skb = req->context, *skb2;
261         struct eth_dev  *dev = ep->driver_data;
262         int             status = req->status;
263
264         switch (status) {
265
266         /* normal completion */
267         case 0:
268                 skb_put(skb, req->actual);
269
270                 if (dev->unwrap) {
271                         unsigned long   flags;
272
273                         spin_lock_irqsave(&dev->lock, flags);
274                         if (dev->port_usb) {
275                                 status = dev->unwrap(dev->port_usb,
276                                                         skb,
277                                                         &dev->rx_frames);
278                         } else {
279                                 dev_kfree_skb_any(skb);
280                                 status = -ENOTCONN;
281                         }
282                         spin_unlock_irqrestore(&dev->lock, flags);
283                 } else {
284                         skb_queue_tail(&dev->rx_frames, skb);
285                 }
286                 skb = NULL;
287
288                 skb2 = skb_dequeue(&dev->rx_frames);
289                 while (skb2) {
290                         if (status < 0
291                                         || ETH_HLEN > skb2->len
292                                         || skb2->len > GETHER_MAX_ETH_FRAME_LEN) {
293                                 dev->net->stats.rx_errors++;
294                                 dev->net->stats.rx_length_errors++;
295                                 DBG(dev, "rx length %d\n", skb2->len);
296                                 dev_kfree_skb_any(skb2);
297                                 goto next_frame;
298                         }
299                         skb2->protocol = eth_type_trans(skb2, dev->net);
300                         dev->net->stats.rx_packets++;
301                         dev->net->stats.rx_bytes += skb2->len;
302
303                         /* no buffer copies needed, unless hardware can't
304                          * use skb buffers.
305                          */
306                         status = netif_rx(skb2);
307 next_frame:
308                         skb2 = skb_dequeue(&dev->rx_frames);
309                 }
310                 break;
311
312         /* software-driven interface shutdown */
313         case -ECONNRESET:               /* unlink */
314         case -ESHUTDOWN:                /* disconnect etc */
315                 VDBG(dev, "rx shutdown, code %d\n", status);
316                 goto quiesce;
317
318         /* for hardware automagic (such as pxa) */
319         case -ECONNABORTED:             /* endpoint reset */
320                 DBG(dev, "rx %s reset\n", ep->name);
321                 defer_kevent(dev, WORK_RX_MEMORY);
322 quiesce:
323                 dev_kfree_skb_any(skb);
324                 goto clean;
325
326         /* data overrun */
327         case -EOVERFLOW:
328                 dev->net->stats.rx_over_errors++;
329                 /* FALLTHROUGH */
330
331         default:
332                 dev->net->stats.rx_errors++;
333                 DBG(dev, "rx status %d\n", status);
334                 break;
335         }
336
337         if (skb)
338                 dev_kfree_skb_any(skb);
339         if (!netif_running(dev->net)) {
340 clean:
341                 spin_lock(&dev->req_lock);
342                 list_add(&req->list, &dev->rx_reqs);
343                 spin_unlock(&dev->req_lock);
344                 req = NULL;
345         }
346         if (req)
347                 rx_submit(dev, req, GFP_ATOMIC);
348 }
349
350 static int prealloc(struct list_head *list, struct usb_ep *ep, unsigned n)
351 {
352         unsigned                i;
353         struct usb_request      *req;
354
355         if (!n)
356                 return -ENOMEM;
357
358         /* queue/recycle up to N requests */
359         i = n;
360         list_for_each_entry(req, list, list) {
361                 if (i-- == 0)
362                         goto extra;
363         }
364         while (i--) {
365                 req = usb_ep_alloc_request(ep, GFP_ATOMIC);
366                 if (!req)
367                         return list_empty(list) ? -ENOMEM : 0;
368                 list_add(&req->list, list);
369         }
370         return 0;
371
372 extra:
373         /* free extras */
374         for (;;) {
375                 struct list_head        *next;
376
377                 next = req->list.next;
378                 list_del(&req->list);
379                 usb_ep_free_request(ep, req);
380
381                 if (next == list)
382                         break;
383
384                 req = container_of(next, struct usb_request, list);
385         }
386         return 0;
387 }
388
389 static int alloc_requests(struct eth_dev *dev, struct gether *link, unsigned n)
390 {
391         int     status;
392
393         spin_lock(&dev->req_lock);
394         status = prealloc(&dev->tx_reqs, link->in_ep, n);
395         if (status < 0)
396                 goto fail;
397         status = prealloc(&dev->rx_reqs, link->out_ep, n);
398         if (status < 0)
399                 goto fail;
400         goto done;
401 fail:
402         DBG(dev, "can't alloc requests\n");
403 done:
404         spin_unlock(&dev->req_lock);
405         return status;
406 }
407
408 static void rx_fill(struct eth_dev *dev, gfp_t gfp_flags)
409 {
410         struct usb_request      *req;
411         unsigned long           flags;
412
413         /* fill unused rxq slots with some skb */
414         spin_lock_irqsave(&dev->req_lock, flags);
415         while (!list_empty(&dev->rx_reqs)) {
416                 req = list_first_entry(&dev->rx_reqs, struct usb_request, list);
417                 list_del_init(&req->list);
418                 spin_unlock_irqrestore(&dev->req_lock, flags);
419
420                 if (rx_submit(dev, req, gfp_flags) < 0) {
421                         defer_kevent(dev, WORK_RX_MEMORY);
422                         return;
423                 }
424
425                 spin_lock_irqsave(&dev->req_lock, flags);
426         }
427         spin_unlock_irqrestore(&dev->req_lock, flags);
428 }
429
430 static void eth_work(struct work_struct *work)
431 {
432         struct eth_dev  *dev = container_of(work, struct eth_dev, work);
433
434         if (test_and_clear_bit(WORK_RX_MEMORY, &dev->todo)) {
435                 if (netif_running(dev->net))
436                         rx_fill(dev, GFP_KERNEL);
437         }
438
439         if (dev->todo)
440                 DBG(dev, "work done, flags = 0x%lx\n", dev->todo);
441 }
442
443 static void tx_complete(struct usb_ep *ep, struct usb_request *req)
444 {
445         struct sk_buff  *skb = req->context;
446         struct eth_dev  *dev = ep->driver_data;
447
448         switch (req->status) {
449         default:
450                 dev->net->stats.tx_errors++;
451                 VDBG(dev, "tx err %d\n", req->status);
452                 /* FALLTHROUGH */
453         case -ECONNRESET:               /* unlink */
454         case -ESHUTDOWN:                /* disconnect etc */
455                 dev_kfree_skb_any(skb);
456                 break;
457         case 0:
458                 dev->net->stats.tx_bytes += skb->len;
459                 dev_consume_skb_any(skb);
460         }
461         dev->net->stats.tx_packets++;
462
463         spin_lock(&dev->req_lock);
464         list_add(&req->list, &dev->tx_reqs);
465         spin_unlock(&dev->req_lock);
466
467         atomic_dec(&dev->tx_qlen);
468         if (netif_carrier_ok(dev->net))
469                 netif_wake_queue(dev->net);
470 }
471
472 static inline int is_promisc(u16 cdc_filter)
473 {
474         return cdc_filter & USB_CDC_PACKET_TYPE_PROMISCUOUS;
475 }
476
477 static netdev_tx_t eth_start_xmit(struct sk_buff *skb,
478                                         struct net_device *net)
479 {
480         struct eth_dev          *dev = netdev_priv(net);
481         int                     length = 0;
482         int                     retval;
483         struct usb_request      *req = NULL;
484         unsigned long           flags;
485         struct usb_ep           *in;
486         u16                     cdc_filter;
487
488         spin_lock_irqsave(&dev->lock, flags);
489         if (dev->port_usb) {
490                 in = dev->port_usb->in_ep;
491                 cdc_filter = dev->port_usb->cdc_filter;
492         } else {
493                 in = NULL;
494                 cdc_filter = 0;
495         }
496         spin_unlock_irqrestore(&dev->lock, flags);
497
498         if (!in) {
499                 if (skb)
500                         dev_kfree_skb_any(skb);
501                 return NETDEV_TX_OK;
502         }
503
504         /* apply outgoing CDC or RNDIS filters */
505         if (skb && !is_promisc(cdc_filter)) {
506                 u8              *dest = skb->data;
507
508                 if (is_multicast_ether_addr(dest)) {
509                         u16     type;
510
511                         /* ignores USB_CDC_PACKET_TYPE_MULTICAST and host
512                          * SET_ETHERNET_MULTICAST_FILTERS requests
513                          */
514                         if (is_broadcast_ether_addr(dest))
515                                 type = USB_CDC_PACKET_TYPE_BROADCAST;
516                         else
517                                 type = USB_CDC_PACKET_TYPE_ALL_MULTICAST;
518                         if (!(cdc_filter & type)) {
519                                 dev_kfree_skb_any(skb);
520                                 return NETDEV_TX_OK;
521                         }
522                 }
523                 /* ignores USB_CDC_PACKET_TYPE_DIRECTED */
524         }
525
526         spin_lock_irqsave(&dev->req_lock, flags);
527         /*
528          * this freelist can be empty if an interrupt triggered disconnect()
529          * and reconfigured the gadget (shutting down this queue) after the
530          * network stack decided to xmit but before we got the spinlock.
531          */
532         if (list_empty(&dev->tx_reqs)) {
533                 spin_unlock_irqrestore(&dev->req_lock, flags);
534                 return NETDEV_TX_BUSY;
535         }
536
537         req = list_first_entry(&dev->tx_reqs, struct usb_request, list);
538         list_del(&req->list);
539
540         /* temporarily stop TX queue when the freelist empties */
541         if (list_empty(&dev->tx_reqs))
542                 netif_stop_queue(net);
543         spin_unlock_irqrestore(&dev->req_lock, flags);
544
545         /* no buffer copies needed, unless the network stack did it
546          * or the hardware can't use skb buffers.
547          * or there's not enough space for extra headers we need
548          */
549         if (dev->wrap) {
550                 unsigned long   flags;
551
552                 spin_lock_irqsave(&dev->lock, flags);
553                 if (dev->port_usb)
554                         skb = dev->wrap(dev->port_usb, skb);
555                 spin_unlock_irqrestore(&dev->lock, flags);
556                 if (!skb) {
557                         /* Multi frame CDC protocols may store the frame for
558                          * later which is not a dropped frame.
559                          */
560                         if (dev->port_usb &&
561                                         dev->port_usb->supports_multi_frame)
562                                 goto multiframe;
563                         goto drop;
564                 }
565         }
566
567         length = skb->len;
568         req->buf = skb->data;
569         req->context = skb;
570         req->complete = tx_complete;
571
572         /* NCM requires no zlp if transfer is dwNtbInMaxSize */
573         if (dev->port_usb &&
574             dev->port_usb->is_fixed &&
575             length == dev->port_usb->fixed_in_len &&
576             (length % in->maxpacket) == 0)
577                 req->zero = 0;
578         else
579                 req->zero = 1;
580
581         /* use zlp framing on tx for strict CDC-Ether conformance,
582          * though any robust network rx path ignores extra padding.
583          * and some hardware doesn't like to write zlps.
584          */
585         if (req->zero && !dev->zlp && (length % in->maxpacket) == 0)
586                 length++;
587
588         req->length = length;
589
590         retval = usb_ep_queue(in, req, GFP_ATOMIC);
591         switch (retval) {
592         default:
593                 DBG(dev, "tx queue err %d\n", retval);
594                 break;
595         case 0:
596                 netif_trans_update(net);
597                 atomic_inc(&dev->tx_qlen);
598         }
599
600         if (retval) {
601                 dev_kfree_skb_any(skb);
602 drop:
603                 dev->net->stats.tx_dropped++;
604 multiframe:
605                 spin_lock_irqsave(&dev->req_lock, flags);
606                 if (list_empty(&dev->tx_reqs))
607                         netif_start_queue(net);
608                 list_add(&req->list, &dev->tx_reqs);
609                 spin_unlock_irqrestore(&dev->req_lock, flags);
610         }
611         return NETDEV_TX_OK;
612 }
613
614 /*-------------------------------------------------------------------------*/
615
616 static void eth_start(struct eth_dev *dev, gfp_t gfp_flags)
617 {
618         DBG(dev, "%s\n", __func__);
619
620         /* fill the rx queue */
621         rx_fill(dev, gfp_flags);
622
623         /* and open the tx floodgates */
624         atomic_set(&dev->tx_qlen, 0);
625         netif_wake_queue(dev->net);
626 }
627
628 static int eth_open(struct net_device *net)
629 {
630         struct eth_dev  *dev = netdev_priv(net);
631         struct gether   *link;
632
633         DBG(dev, "%s\n", __func__);
634         if (netif_carrier_ok(dev->net))
635                 eth_start(dev, GFP_KERNEL);
636
637         spin_lock_irq(&dev->lock);
638         link = dev->port_usb;
639         if (link && link->open)
640                 link->open(link);
641         spin_unlock_irq(&dev->lock);
642
643         return 0;
644 }
645
646 static int eth_stop(struct net_device *net)
647 {
648         struct eth_dev  *dev = netdev_priv(net);
649         unsigned long   flags;
650
651         VDBG(dev, "%s\n", __func__);
652         netif_stop_queue(net);
653
654         DBG(dev, "stop stats: rx/tx %ld/%ld, errs %ld/%ld\n",
655                 dev->net->stats.rx_packets, dev->net->stats.tx_packets,
656                 dev->net->stats.rx_errors, dev->net->stats.tx_errors
657                 );
658
659         /* ensure there are no more active requests */
660         spin_lock_irqsave(&dev->lock, flags);
661         if (dev->port_usb) {
662                 struct gether   *link = dev->port_usb;
663                 const struct usb_endpoint_descriptor *in;
664                 const struct usb_endpoint_descriptor *out;
665
666                 if (link->close)
667                         link->close(link);
668
669                 /* NOTE:  we have no abort-queue primitive we could use
670                  * to cancel all pending I/O.  Instead, we disable then
671                  * reenable the endpoints ... this idiom may leave toggle
672                  * wrong, but that's a self-correcting error.
673                  *
674                  * REVISIT:  we *COULD* just let the transfers complete at
675                  * their own pace; the network stack can handle old packets.
676                  * For the moment we leave this here, since it works.
677                  */
678                 in = link->in_ep->desc;
679                 out = link->out_ep->desc;
680                 usb_ep_disable(link->in_ep);
681                 usb_ep_disable(link->out_ep);
682                 if (netif_carrier_ok(net)) {
683                         DBG(dev, "host still using in/out endpoints\n");
684                         link->in_ep->desc = in;
685                         link->out_ep->desc = out;
686                         usb_ep_enable(link->in_ep);
687                         usb_ep_enable(link->out_ep);
688                 }
689         }
690         spin_unlock_irqrestore(&dev->lock, flags);
691
692         return 0;
693 }
694
695 /*-------------------------------------------------------------------------*/
696
697 static int get_ether_addr(const char *str, u8 *dev_addr)
698 {
699         if (str) {
700                 unsigned        i;
701
702                 for (i = 0; i < 6; i++) {
703                         unsigned char num;
704
705                         if ((*str == '.') || (*str == ':'))
706                                 str++;
707                         num = hex_to_bin(*str++) << 4;
708                         num |= hex_to_bin(*str++);
709                         dev_addr [i] = num;
710                 }
711                 if (is_valid_ether_addr(dev_addr))
712                         return 0;
713         }
714         eth_random_addr(dev_addr);
715         return 1;
716 }
717
718 static int get_ether_addr_str(u8 dev_addr[ETH_ALEN], char *str, int len)
719 {
720         if (len < 18)
721                 return -EINVAL;
722
723         snprintf(str, len, "%pM", dev_addr);
724         return 18;
725 }
726
727 static const struct net_device_ops eth_netdev_ops = {
728         .ndo_open               = eth_open,
729         .ndo_stop               = eth_stop,
730         .ndo_start_xmit         = eth_start_xmit,
731         .ndo_set_mac_address    = eth_mac_addr,
732         .ndo_validate_addr      = eth_validate_addr,
733 };
734
735 static struct device_type gadget_type = {
736         .name   = "gadget",
737 };
738
739 /**
740  * gether_setup_name - initialize one ethernet-over-usb link
741  * @g: gadget to associated with these links
742  * @ethaddr: NULL, or a buffer in which the ethernet address of the
743  *      host side of the link is recorded
744  * @netname: name for network device (for example, "usb")
745  * Context: may sleep
746  *
747  * This sets up the single network link that may be exported by a
748  * gadget driver using this framework.  The link layer addresses are
749  * set up using module parameters.
750  *
751  * Returns an eth_dev pointer on success, or an ERR_PTR on failure.
752  */
753 struct eth_dev *gether_setup_name(struct usb_gadget *g,
754                 const char *dev_addr, const char *host_addr,
755                 u8 ethaddr[ETH_ALEN], unsigned qmult, const char *netname)
756 {
757         struct eth_dev          *dev;
758         struct net_device       *net;
759         int                     status;
760
761         net = alloc_etherdev(sizeof *dev);
762         if (!net)
763                 return ERR_PTR(-ENOMEM);
764
765         dev = netdev_priv(net);
766         spin_lock_init(&dev->lock);
767         spin_lock_init(&dev->req_lock);
768         INIT_WORK(&dev->work, eth_work);
769         INIT_LIST_HEAD(&dev->tx_reqs);
770         INIT_LIST_HEAD(&dev->rx_reqs);
771
772         skb_queue_head_init(&dev->rx_frames);
773
774         /* network device setup */
775         dev->net = net;
776         dev->qmult = qmult;
777         snprintf(net->name, sizeof(net->name), "%s%%d", netname);
778
779         if (get_ether_addr(dev_addr, net->dev_addr)) {
780                 net->addr_assign_type = NET_ADDR_RANDOM;
781                 dev_warn(&g->dev,
782                         "using random %s ethernet address\n", "self");
783         } else {
784                 net->addr_assign_type = NET_ADDR_SET;
785         }
786         if (get_ether_addr(host_addr, dev->host_mac))
787                 dev_warn(&g->dev,
788                         "using random %s ethernet address\n", "host");
789
790         if (ethaddr)
791                 memcpy(ethaddr, dev->host_mac, ETH_ALEN);
792
793         net->netdev_ops = &eth_netdev_ops;
794
795         net->ethtool_ops = &ops;
796
797         /* MTU range: 14 - 15412 */
798         net->min_mtu = ETH_HLEN;
799         net->max_mtu = GETHER_MAX_MTU_SIZE;
800
801         dev->gadget = g;
802         SET_NETDEV_DEV(net, &g->dev);
803         SET_NETDEV_DEVTYPE(net, &gadget_type);
804
805         status = register_netdev(net);
806         if (status < 0) {
807                 dev_dbg(&g->dev, "register_netdev failed, %d\n", status);
808                 free_netdev(net);
809                 dev = ERR_PTR(status);
810         } else {
811                 INFO(dev, "MAC %pM\n", net->dev_addr);
812                 INFO(dev, "HOST MAC %pM\n", dev->host_mac);
813
814                 /*
815                  * two kinds of host-initiated state changes:
816                  *  - iff DATA transfer is active, carrier is "on"
817                  *  - tx queueing enabled if open *and* carrier is "on"
818                  */
819                 netif_carrier_off(net);
820         }
821
822         return dev;
823 }
824 EXPORT_SYMBOL_GPL(gether_setup_name);
825
826 struct net_device *gether_setup_name_default(const char *netname)
827 {
828         struct net_device       *net;
829         struct eth_dev          *dev;
830
831         net = alloc_etherdev(sizeof(*dev));
832         if (!net)
833                 return ERR_PTR(-ENOMEM);
834
835         dev = netdev_priv(net);
836         spin_lock_init(&dev->lock);
837         spin_lock_init(&dev->req_lock);
838         INIT_WORK(&dev->work, eth_work);
839         INIT_LIST_HEAD(&dev->tx_reqs);
840         INIT_LIST_HEAD(&dev->rx_reqs);
841
842         /* by default we always have a random MAC address */
843         net->addr_assign_type = NET_ADDR_RANDOM;
844
845         skb_queue_head_init(&dev->rx_frames);
846
847         /* network device setup */
848         dev->net = net;
849         dev->qmult = QMULT_DEFAULT;
850         snprintf(net->name, sizeof(net->name), "%s%%d", netname);
851
852         eth_random_addr(dev->dev_mac);
853         pr_warn("using random %s ethernet address\n", "self");
854         eth_random_addr(dev->host_mac);
855         pr_warn("using random %s ethernet address\n", "host");
856
857         net->netdev_ops = &eth_netdev_ops;
858
859         net->ethtool_ops = &ops;
860         SET_NETDEV_DEVTYPE(net, &gadget_type);
861
862         /* MTU range: 14 - 15412 */
863         net->min_mtu = ETH_HLEN;
864         net->max_mtu = GETHER_MAX_MTU_SIZE;
865
866         return net;
867 }
868 EXPORT_SYMBOL_GPL(gether_setup_name_default);
869
870 int gether_register_netdev(struct net_device *net)
871 {
872         struct eth_dev *dev;
873         struct usb_gadget *g;
874         int status;
875
876         if (!net->dev.parent)
877                 return -EINVAL;
878         dev = netdev_priv(net);
879         g = dev->gadget;
880
881         memcpy(net->dev_addr, dev->dev_mac, ETH_ALEN);
882
883         status = register_netdev(net);
884         if (status < 0) {
885                 dev_dbg(&g->dev, "register_netdev failed, %d\n", status);
886                 return status;
887         } else {
888                 INFO(dev, "HOST MAC %pM\n", dev->host_mac);
889                 INFO(dev, "MAC %pM\n", dev->dev_mac);
890
891                 /* two kinds of host-initiated state changes:
892                  *  - iff DATA transfer is active, carrier is "on"
893                  *  - tx queueing enabled if open *and* carrier is "on"
894                  */
895                 netif_carrier_off(net);
896         }
897
898         return status;
899 }
900 EXPORT_SYMBOL_GPL(gether_register_netdev);
901
902 void gether_set_gadget(struct net_device *net, struct usb_gadget *g)
903 {
904         struct eth_dev *dev;
905
906         dev = netdev_priv(net);
907         dev->gadget = g;
908         SET_NETDEV_DEV(net, &g->dev);
909 }
910 EXPORT_SYMBOL_GPL(gether_set_gadget);
911
912 int gether_set_dev_addr(struct net_device *net, const char *dev_addr)
913 {
914         struct eth_dev *dev;
915         u8 new_addr[ETH_ALEN];
916
917         dev = netdev_priv(net);
918         if (get_ether_addr(dev_addr, new_addr))
919                 return -EINVAL;
920         memcpy(dev->dev_mac, new_addr, ETH_ALEN);
921         net->addr_assign_type = NET_ADDR_SET;
922         return 0;
923 }
924 EXPORT_SYMBOL_GPL(gether_set_dev_addr);
925
926 int gether_get_dev_addr(struct net_device *net, char *dev_addr, int len)
927 {
928         struct eth_dev *dev;
929         int ret;
930
931         dev = netdev_priv(net);
932         ret = get_ether_addr_str(dev->dev_mac, dev_addr, len);
933         if (ret + 1 < len) {
934                 dev_addr[ret++] = '\n';
935                 dev_addr[ret] = '\0';
936         }
937
938         return ret;
939 }
940 EXPORT_SYMBOL_GPL(gether_get_dev_addr);
941
942 int gether_set_host_addr(struct net_device *net, const char *host_addr)
943 {
944         struct eth_dev *dev;
945         u8 new_addr[ETH_ALEN];
946
947         dev = netdev_priv(net);
948         if (get_ether_addr(host_addr, new_addr))
949                 return -EINVAL;
950         memcpy(dev->host_mac, new_addr, ETH_ALEN);
951         return 0;
952 }
953 EXPORT_SYMBOL_GPL(gether_set_host_addr);
954
955 int gether_get_host_addr(struct net_device *net, char *host_addr, int len)
956 {
957         struct eth_dev *dev;
958         int ret;
959
960         dev = netdev_priv(net);
961         ret = get_ether_addr_str(dev->host_mac, host_addr, len);
962         if (ret + 1 < len) {
963                 host_addr[ret++] = '\n';
964                 host_addr[ret] = '\0';
965         }
966
967         return ret;
968 }
969 EXPORT_SYMBOL_GPL(gether_get_host_addr);
970
971 int gether_get_host_addr_cdc(struct net_device *net, char *host_addr, int len)
972 {
973         struct eth_dev *dev;
974
975         if (len < 13)
976                 return -EINVAL;
977
978         dev = netdev_priv(net);
979         snprintf(host_addr, len, "%pm", dev->host_mac);
980
981         return strlen(host_addr);
982 }
983 EXPORT_SYMBOL_GPL(gether_get_host_addr_cdc);
984
985 void gether_get_host_addr_u8(struct net_device *net, u8 host_mac[ETH_ALEN])
986 {
987         struct eth_dev *dev;
988
989         dev = netdev_priv(net);
990         memcpy(host_mac, dev->host_mac, ETH_ALEN);
991 }
992 EXPORT_SYMBOL_GPL(gether_get_host_addr_u8);
993
994 void gether_set_qmult(struct net_device *net, unsigned qmult)
995 {
996         struct eth_dev *dev;
997
998         dev = netdev_priv(net);
999         dev->qmult = qmult;
1000 }
1001 EXPORT_SYMBOL_GPL(gether_set_qmult);
1002
1003 unsigned gether_get_qmult(struct net_device *net)
1004 {
1005         struct eth_dev *dev;
1006
1007         dev = netdev_priv(net);
1008         return dev->qmult;
1009 }
1010 EXPORT_SYMBOL_GPL(gether_get_qmult);
1011
1012 int gether_get_ifname(struct net_device *net, char *name, int len)
1013 {
1014         int ret;
1015
1016         rtnl_lock();
1017         ret = snprintf(name, len, "%s\n", netdev_name(net));
1018         rtnl_unlock();
1019         return ret < len ? ret : len;
1020 }
1021 EXPORT_SYMBOL_GPL(gether_get_ifname);
1022
1023 /**
1024  * gether_cleanup - remove Ethernet-over-USB device
1025  * Context: may sleep
1026  *
1027  * This is called to free all resources allocated by @gether_setup().
1028  */
1029 void gether_cleanup(struct eth_dev *dev)
1030 {
1031         if (!dev)
1032                 return;
1033
1034         unregister_netdev(dev->net);
1035         flush_work(&dev->work);
1036         free_netdev(dev->net);
1037 }
1038 EXPORT_SYMBOL_GPL(gether_cleanup);
1039
1040 /**
1041  * gether_connect - notify network layer that USB link is active
1042  * @link: the USB link, set up with endpoints, descriptors matching
1043  *      current device speed, and any framing wrapper(s) set up.
1044  * Context: irqs blocked
1045  *
1046  * This is called to activate endpoints and let the network layer know
1047  * the connection is active ("carrier detect").  It may cause the I/O
1048  * queues to open and start letting network packets flow, but will in
1049  * any case activate the endpoints so that they respond properly to the
1050  * USB host.
1051  *
1052  * Verify net_device pointer returned using IS_ERR().  If it doesn't
1053  * indicate some error code (negative errno), ep->driver_data values
1054  * have been overwritten.
1055  */
1056 struct net_device *gether_connect(struct gether *link)
1057 {
1058         struct eth_dev          *dev = link->ioport;
1059         int                     result = 0;
1060
1061         if (!dev)
1062                 return ERR_PTR(-EINVAL);
1063
1064         link->in_ep->driver_data = dev;
1065         result = usb_ep_enable(link->in_ep);
1066         if (result != 0) {
1067                 DBG(dev, "enable %s --> %d\n",
1068                         link->in_ep->name, result);
1069                 goto fail0;
1070         }
1071
1072         link->out_ep->driver_data = dev;
1073         result = usb_ep_enable(link->out_ep);
1074         if (result != 0) {
1075                 DBG(dev, "enable %s --> %d\n",
1076                         link->out_ep->name, result);
1077                 goto fail1;
1078         }
1079
1080         if (result == 0)
1081                 result = alloc_requests(dev, link, qlen(dev->gadget,
1082                                         dev->qmult));
1083
1084         if (result == 0) {
1085                 dev->zlp = link->is_zlp_ok;
1086                 dev->no_skb_reserve = gadget_avoids_skb_reserve(dev->gadget);
1087                 DBG(dev, "qlen %d\n", qlen(dev->gadget, dev->qmult));
1088
1089                 dev->header_len = link->header_len;
1090                 dev->unwrap = link->unwrap;
1091                 dev->wrap = link->wrap;
1092
1093                 spin_lock(&dev->lock);
1094                 dev->port_usb = link;
1095                 if (netif_running(dev->net)) {
1096                         if (link->open)
1097                                 link->open(link);
1098                 } else {
1099                         if (link->close)
1100                                 link->close(link);
1101                 }
1102                 spin_unlock(&dev->lock);
1103
1104                 netif_carrier_on(dev->net);
1105                 if (netif_running(dev->net))
1106                         eth_start(dev, GFP_ATOMIC);
1107
1108         /* on error, disable any endpoints  */
1109         } else {
1110                 (void) usb_ep_disable(link->out_ep);
1111 fail1:
1112                 (void) usb_ep_disable(link->in_ep);
1113         }
1114 fail0:
1115         /* caller is responsible for cleanup on error */
1116         if (result < 0)
1117                 return ERR_PTR(result);
1118         return dev->net;
1119 }
1120 EXPORT_SYMBOL_GPL(gether_connect);
1121
1122 /**
1123  * gether_disconnect - notify network layer that USB link is inactive
1124  * @link: the USB link, on which gether_connect() was called
1125  * Context: irqs blocked
1126  *
1127  * This is called to deactivate endpoints and let the network layer know
1128  * the connection went inactive ("no carrier").
1129  *
1130  * On return, the state is as if gether_connect() had never been called.
1131  * The endpoints are inactive, and accordingly without active USB I/O.
1132  * Pointers to endpoint descriptors and endpoint private data are nulled.
1133  */
1134 void gether_disconnect(struct gether *link)
1135 {
1136         struct eth_dev          *dev = link->ioport;
1137         struct usb_request      *req;
1138
1139         WARN_ON(!dev);
1140         if (!dev)
1141                 return;
1142
1143         DBG(dev, "%s\n", __func__);
1144
1145         netif_stop_queue(dev->net);
1146         netif_carrier_off(dev->net);
1147
1148         /* disable endpoints, forcing (synchronous) completion
1149          * of all pending i/o.  then free the request objects
1150          * and forget about the endpoints.
1151          */
1152         usb_ep_disable(link->in_ep);
1153         spin_lock(&dev->req_lock);
1154         while (!list_empty(&dev->tx_reqs)) {
1155                 req = list_first_entry(&dev->tx_reqs, struct usb_request, list);
1156                 list_del(&req->list);
1157
1158                 spin_unlock(&dev->req_lock);
1159                 usb_ep_free_request(link->in_ep, req);
1160                 spin_lock(&dev->req_lock);
1161         }
1162         spin_unlock(&dev->req_lock);
1163         link->in_ep->desc = NULL;
1164
1165         usb_ep_disable(link->out_ep);
1166         spin_lock(&dev->req_lock);
1167         while (!list_empty(&dev->rx_reqs)) {
1168                 req = list_first_entry(&dev->rx_reqs, struct usb_request, list);
1169                 list_del(&req->list);
1170
1171                 spin_unlock(&dev->req_lock);
1172                 usb_ep_free_request(link->out_ep, req);
1173                 spin_lock(&dev->req_lock);
1174         }
1175         spin_unlock(&dev->req_lock);
1176         link->out_ep->desc = NULL;
1177
1178         /* finish forgetting about this USB link episode */
1179         dev->header_len = 0;
1180         dev->unwrap = NULL;
1181         dev->wrap = NULL;
1182
1183         spin_lock(&dev->lock);
1184         dev->port_usb = NULL;
1185         spin_unlock(&dev->lock);
1186 }
1187 EXPORT_SYMBOL_GPL(gether_disconnect);
1188
1189 MODULE_LICENSE("GPL");
1190 MODULE_AUTHOR("David Brownell");