OSDN Git Service

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