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