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