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