xref: /openbmc/linux/drivers/net/usb/usbnet.c (revision d58f75de)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * USB Network driver infrastructure
4  * Copyright (C) 2000-2005 by David Brownell
5  * Copyright (C) 2003-2005 David Hollis <dhollis@davehollis.com>
6  */
7 
8 /*
9  * This is a generic "USB networking" framework that works with several
10  * kinds of full and high speed networking devices:  host-to-host cables,
11  * smart usb peripherals, and actual Ethernet adapters.
12  *
13  * These devices usually differ in terms of control protocols (if they
14  * even have one!) and sometimes they define new framing to wrap or batch
15  * Ethernet packets.  Otherwise, they talk to USB pretty much the same,
16  * so interface (un)binding, endpoint I/O queues, fault handling, and other
17  * issues can usefully be addressed by this framework.
18  */
19 
20 // #define	DEBUG			// error path messages, extra info
21 // #define	VERBOSE			// more; success messages
22 
23 #include <linux/module.h>
24 #include <linux/init.h>
25 #include <linux/netdevice.h>
26 #include <linux/etherdevice.h>
27 #include <linux/ctype.h>
28 #include <linux/ethtool.h>
29 #include <linux/workqueue.h>
30 #include <linux/mii.h>
31 #include <linux/usb.h>
32 #include <linux/usb/usbnet.h>
33 #include <linux/slab.h>
34 #include <linux/kernel.h>
35 #include <linux/pm_runtime.h>
36 
37 /*-------------------------------------------------------------------------*/
38 
39 /*
40  * Nineteen USB 1.1 max size bulk transactions per frame (ms), max.
41  * Several dozen bytes of IPv4 data can fit in two such transactions.
42  * One maximum size Ethernet packet takes twenty four of them.
43  * For high speed, each frame comfortably fits almost 36 max size
44  * Ethernet packets (so queues should be bigger).
45  *
46  * The goal is to let the USB host controller be busy for 5msec or
47  * more before an irq is required, under load.  Jumbograms change
48  * the equation.
49  */
50 #define	MAX_QUEUE_MEMORY	(60 * 1518)
51 #define	RX_QLEN(dev)		((dev)->rx_qlen)
52 #define	TX_QLEN(dev)		((dev)->tx_qlen)
53 
54 // reawaken network queue this soon after stopping; else watchdog barks
55 #define TX_TIMEOUT_JIFFIES	(5*HZ)
56 
57 /* throttle rx/tx briefly after some faults, so hub_wq might disconnect()
58  * us (it polls at HZ/4 usually) before we report too many false errors.
59  */
60 #define THROTTLE_JIFFIES	(HZ/8)
61 
62 // between wakeups
63 #define UNLINK_TIMEOUT_MS	3
64 
65 /*-------------------------------------------------------------------------*/
66 
67 // randomly generated ethernet address
68 static u8	node_id [ETH_ALEN];
69 
70 /* use ethtool to change the level for any given device */
71 static int msg_level = -1;
72 module_param (msg_level, int, 0);
73 MODULE_PARM_DESC (msg_level, "Override default message level");
74 
75 /*-------------------------------------------------------------------------*/
76 
77 /* handles CDC Ethernet and many other network "bulk data" interfaces */
78 int usbnet_get_endpoints(struct usbnet *dev, struct usb_interface *intf)
79 {
80 	int				tmp;
81 	struct usb_host_interface	*alt = NULL;
82 	struct usb_host_endpoint	*in = NULL, *out = NULL;
83 	struct usb_host_endpoint	*status = NULL;
84 
85 	for (tmp = 0; tmp < intf->num_altsetting; tmp++) {
86 		unsigned	ep;
87 
88 		in = out = status = NULL;
89 		alt = intf->altsetting + tmp;
90 
91 		/* take the first altsetting with in-bulk + out-bulk;
92 		 * remember any status endpoint, just in case;
93 		 * ignore other endpoints and altsettings.
94 		 */
95 		for (ep = 0; ep < alt->desc.bNumEndpoints; ep++) {
96 			struct usb_host_endpoint	*e;
97 			int				intr = 0;
98 
99 			e = alt->endpoint + ep;
100 
101 			/* ignore endpoints which cannot transfer data */
102 			if (!usb_endpoint_maxp(&e->desc))
103 				continue;
104 
105 			switch (e->desc.bmAttributes) {
106 			case USB_ENDPOINT_XFER_INT:
107 				if (!usb_endpoint_dir_in(&e->desc))
108 					continue;
109 				intr = 1;
110 				fallthrough;
111 			case USB_ENDPOINT_XFER_BULK:
112 				break;
113 			default:
114 				continue;
115 			}
116 			if (usb_endpoint_dir_in(&e->desc)) {
117 				if (!intr && !in)
118 					in = e;
119 				else if (intr && !status)
120 					status = e;
121 			} else {
122 				if (!out)
123 					out = e;
124 			}
125 		}
126 		if (in && out)
127 			break;
128 	}
129 	if (!alt || !in || !out)
130 		return -EINVAL;
131 
132 	if (alt->desc.bAlternateSetting != 0 ||
133 	    !(dev->driver_info->flags & FLAG_NO_SETINT)) {
134 		tmp = usb_set_interface (dev->udev, alt->desc.bInterfaceNumber,
135 				alt->desc.bAlternateSetting);
136 		if (tmp < 0)
137 			return tmp;
138 	}
139 
140 	dev->in = usb_rcvbulkpipe (dev->udev,
141 			in->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
142 	dev->out = usb_sndbulkpipe (dev->udev,
143 			out->desc.bEndpointAddress & USB_ENDPOINT_NUMBER_MASK);
144 	dev->status = status;
145 	return 0;
146 }
147 EXPORT_SYMBOL_GPL(usbnet_get_endpoints);
148 
149 int usbnet_get_ethernet_addr(struct usbnet *dev, int iMACAddress)
150 {
151 	int 		tmp = -1, ret;
152 	unsigned char	buf [13];
153 
154 	ret = usb_string(dev->udev, iMACAddress, buf, sizeof buf);
155 	if (ret == 12)
156 		tmp = hex2bin(dev->net->dev_addr, buf, 6);
157 	if (tmp < 0) {
158 		dev_dbg(&dev->udev->dev,
159 			"bad MAC string %d fetch, %d\n", iMACAddress, tmp);
160 		if (ret >= 0)
161 			ret = -EINVAL;
162 		return ret;
163 	}
164 	return 0;
165 }
166 EXPORT_SYMBOL_GPL(usbnet_get_ethernet_addr);
167 
168 static void intr_complete (struct urb *urb)
169 {
170 	struct usbnet	*dev = urb->context;
171 	int		status = urb->status;
172 
173 	switch (status) {
174 	/* success */
175 	case 0:
176 		dev->driver_info->status(dev, urb);
177 		break;
178 
179 	/* software-driven interface shutdown */
180 	case -ENOENT:		/* urb killed */
181 	case -ESHUTDOWN:	/* hardware gone */
182 		netif_dbg(dev, ifdown, dev->net,
183 			  "intr shutdown, code %d\n", status);
184 		return;
185 
186 	/* NOTE:  not throttling like RX/TX, since this endpoint
187 	 * already polls infrequently
188 	 */
189 	default:
190 		netdev_dbg(dev->net, "intr status %d\n", status);
191 		break;
192 	}
193 
194 	status = usb_submit_urb (urb, GFP_ATOMIC);
195 	if (status != 0)
196 		netif_err(dev, timer, dev->net,
197 			  "intr resubmit --> %d\n", status);
198 }
199 
200 static int init_status (struct usbnet *dev, struct usb_interface *intf)
201 {
202 	char		*buf = NULL;
203 	unsigned	pipe = 0;
204 	unsigned	maxp;
205 	unsigned	period;
206 
207 	if (!dev->driver_info->status)
208 		return 0;
209 
210 	pipe = usb_rcvintpipe (dev->udev,
211 			dev->status->desc.bEndpointAddress
212 				& USB_ENDPOINT_NUMBER_MASK);
213 	maxp = usb_maxpacket (dev->udev, pipe, 0);
214 
215 	/* avoid 1 msec chatter:  min 8 msec poll rate */
216 	period = max ((int) dev->status->desc.bInterval,
217 		(dev->udev->speed == USB_SPEED_HIGH) ? 7 : 3);
218 
219 	buf = kmalloc (maxp, GFP_KERNEL);
220 	if (buf) {
221 		dev->interrupt = usb_alloc_urb (0, GFP_KERNEL);
222 		if (!dev->interrupt) {
223 			kfree (buf);
224 			return -ENOMEM;
225 		} else {
226 			usb_fill_int_urb(dev->interrupt, dev->udev, pipe,
227 				buf, maxp, intr_complete, dev, period);
228 			dev->interrupt->transfer_flags |= URB_FREE_BUFFER;
229 			dev_dbg(&intf->dev,
230 				"status ep%din, %d bytes period %d\n",
231 				usb_pipeendpoint(pipe), maxp, period);
232 		}
233 	}
234 	return 0;
235 }
236 
237 /* Submit the interrupt URB if not previously submitted, increasing refcount */
238 int usbnet_status_start(struct usbnet *dev, gfp_t mem_flags)
239 {
240 	int ret = 0;
241 
242 	WARN_ON_ONCE(dev->interrupt == NULL);
243 	if (dev->interrupt) {
244 		mutex_lock(&dev->interrupt_mutex);
245 
246 		if (++dev->interrupt_count == 1)
247 			ret = usb_submit_urb(dev->interrupt, mem_flags);
248 
249 		dev_dbg(&dev->udev->dev, "incremented interrupt URB count to %d\n",
250 			dev->interrupt_count);
251 		mutex_unlock(&dev->interrupt_mutex);
252 	}
253 	return ret;
254 }
255 EXPORT_SYMBOL_GPL(usbnet_status_start);
256 
257 /* For resume; submit interrupt URB if previously submitted */
258 static int __usbnet_status_start_force(struct usbnet *dev, gfp_t mem_flags)
259 {
260 	int ret = 0;
261 
262 	mutex_lock(&dev->interrupt_mutex);
263 	if (dev->interrupt_count) {
264 		ret = usb_submit_urb(dev->interrupt, mem_flags);
265 		dev_dbg(&dev->udev->dev,
266 			"submitted interrupt URB for resume\n");
267 	}
268 	mutex_unlock(&dev->interrupt_mutex);
269 	return ret;
270 }
271 
272 /* Kill the interrupt URB if all submitters want it killed */
273 void usbnet_status_stop(struct usbnet *dev)
274 {
275 	if (dev->interrupt) {
276 		mutex_lock(&dev->interrupt_mutex);
277 		WARN_ON(dev->interrupt_count == 0);
278 
279 		if (dev->interrupt_count && --dev->interrupt_count == 0)
280 			usb_kill_urb(dev->interrupt);
281 
282 		dev_dbg(&dev->udev->dev,
283 			"decremented interrupt URB count to %d\n",
284 			dev->interrupt_count);
285 		mutex_unlock(&dev->interrupt_mutex);
286 	}
287 }
288 EXPORT_SYMBOL_GPL(usbnet_status_stop);
289 
290 /* For suspend; always kill interrupt URB */
291 static void __usbnet_status_stop_force(struct usbnet *dev)
292 {
293 	if (dev->interrupt) {
294 		mutex_lock(&dev->interrupt_mutex);
295 		usb_kill_urb(dev->interrupt);
296 		dev_dbg(&dev->udev->dev, "killed interrupt URB for suspend\n");
297 		mutex_unlock(&dev->interrupt_mutex);
298 	}
299 }
300 
301 /* Passes this packet up the stack, updating its accounting.
302  * Some link protocols batch packets, so their rx_fixup paths
303  * can return clones as well as just modify the original skb.
304  */
305 void usbnet_skb_return (struct usbnet *dev, struct sk_buff *skb)
306 {
307 	struct pcpu_sw_netstats *stats64 = this_cpu_ptr(dev->net->tstats);
308 	unsigned long flags;
309 	int	status;
310 
311 	if (test_bit(EVENT_RX_PAUSED, &dev->flags)) {
312 		skb_queue_tail(&dev->rxq_pause, skb);
313 		return;
314 	}
315 
316 	/* only update if unset to allow minidriver rx_fixup override */
317 	if (skb->protocol == 0)
318 		skb->protocol = eth_type_trans (skb, dev->net);
319 
320 	flags = u64_stats_update_begin_irqsave(&stats64->syncp);
321 	stats64->rx_packets++;
322 	stats64->rx_bytes += skb->len;
323 	u64_stats_update_end_irqrestore(&stats64->syncp, flags);
324 
325 	netif_dbg(dev, rx_status, dev->net, "< rx, len %zu, type 0x%x\n",
326 		  skb->len + sizeof (struct ethhdr), skb->protocol);
327 	memset (skb->cb, 0, sizeof (struct skb_data));
328 
329 	if (skb_defer_rx_timestamp(skb))
330 		return;
331 
332 	status = netif_rx (skb);
333 	if (status != NET_RX_SUCCESS)
334 		netif_dbg(dev, rx_err, dev->net,
335 			  "netif_rx status %d\n", status);
336 }
337 EXPORT_SYMBOL_GPL(usbnet_skb_return);
338 
339 /* must be called if hard_mtu or rx_urb_size changed */
340 void usbnet_update_max_qlen(struct usbnet *dev)
341 {
342 	enum usb_device_speed speed = dev->udev->speed;
343 
344 	if (!dev->rx_urb_size || !dev->hard_mtu)
345 		goto insanity;
346 	switch (speed) {
347 	case USB_SPEED_HIGH:
348 		dev->rx_qlen = MAX_QUEUE_MEMORY / dev->rx_urb_size;
349 		dev->tx_qlen = MAX_QUEUE_MEMORY / dev->hard_mtu;
350 		break;
351 	case USB_SPEED_SUPER:
352 	case USB_SPEED_SUPER_PLUS:
353 		/*
354 		 * Not take default 5ms qlen for super speed HC to
355 		 * save memory, and iperf tests show 2.5ms qlen can
356 		 * work well
357 		 */
358 		dev->rx_qlen = 5 * MAX_QUEUE_MEMORY / dev->rx_urb_size;
359 		dev->tx_qlen = 5 * MAX_QUEUE_MEMORY / dev->hard_mtu;
360 		break;
361 	default:
362 insanity:
363 		dev->rx_qlen = dev->tx_qlen = 4;
364 	}
365 }
366 EXPORT_SYMBOL_GPL(usbnet_update_max_qlen);
367 
368 
369 /*-------------------------------------------------------------------------
370  *
371  * Network Device Driver (peer link to "Host Device", from USB host)
372  *
373  *-------------------------------------------------------------------------*/
374 
375 int usbnet_change_mtu (struct net_device *net, int new_mtu)
376 {
377 	struct usbnet	*dev = netdev_priv(net);
378 	int		ll_mtu = new_mtu + net->hard_header_len;
379 	int		old_hard_mtu = dev->hard_mtu;
380 	int		old_rx_urb_size = dev->rx_urb_size;
381 
382 	// no second zero-length packet read wanted after mtu-sized packets
383 	if ((ll_mtu % dev->maxpacket) == 0)
384 		return -EDOM;
385 	net->mtu = new_mtu;
386 
387 	dev->hard_mtu = net->mtu + net->hard_header_len;
388 	if (dev->rx_urb_size == old_hard_mtu) {
389 		dev->rx_urb_size = dev->hard_mtu;
390 		if (dev->rx_urb_size > old_rx_urb_size) {
391 			usbnet_pause_rx(dev);
392 			usbnet_unlink_rx_urbs(dev);
393 			usbnet_resume_rx(dev);
394 		}
395 	}
396 
397 	/* max qlen depend on hard_mtu and rx_urb_size */
398 	usbnet_update_max_qlen(dev);
399 
400 	return 0;
401 }
402 EXPORT_SYMBOL_GPL(usbnet_change_mtu);
403 
404 /* The caller must hold list->lock */
405 static void __usbnet_queue_skb(struct sk_buff_head *list,
406 			struct sk_buff *newsk, enum skb_state state)
407 {
408 	struct skb_data *entry = (struct skb_data *) newsk->cb;
409 
410 	__skb_queue_tail(list, newsk);
411 	entry->state = state;
412 }
413 
414 /*-------------------------------------------------------------------------*/
415 
416 /* some LK 2.4 HCDs oopsed if we freed or resubmitted urbs from
417  * completion callbacks.  2.5 should have fixed those bugs...
418  */
419 
420 static enum skb_state defer_bh(struct usbnet *dev, struct sk_buff *skb,
421 		struct sk_buff_head *list, enum skb_state state)
422 {
423 	unsigned long		flags;
424 	enum skb_state 		old_state;
425 	struct skb_data *entry = (struct skb_data *) skb->cb;
426 
427 	spin_lock_irqsave(&list->lock, flags);
428 	old_state = entry->state;
429 	entry->state = state;
430 	__skb_unlink(skb, list);
431 
432 	/* defer_bh() is never called with list == &dev->done.
433 	 * spin_lock_nested() tells lockdep that it is OK to take
434 	 * dev->done.lock here with list->lock held.
435 	 */
436 	spin_lock_nested(&dev->done.lock, SINGLE_DEPTH_NESTING);
437 
438 	__skb_queue_tail(&dev->done, skb);
439 	if (dev->done.qlen == 1)
440 		tasklet_schedule(&dev->bh);
441 	spin_unlock(&dev->done.lock);
442 	spin_unlock_irqrestore(&list->lock, flags);
443 	return old_state;
444 }
445 
446 /* some work can't be done in tasklets, so we use keventd
447  *
448  * NOTE:  annoying asymmetry:  if it's active, schedule_work() fails,
449  * but tasklet_schedule() doesn't.  hope the failure is rare.
450  */
451 void usbnet_defer_kevent (struct usbnet *dev, int work)
452 {
453 	set_bit (work, &dev->flags);
454 	if (!schedule_work (&dev->kevent))
455 		netdev_dbg(dev->net, "kevent %d may have been dropped\n", work);
456 	else
457 		netdev_dbg(dev->net, "kevent %d scheduled\n", work);
458 }
459 EXPORT_SYMBOL_GPL(usbnet_defer_kevent);
460 
461 /*-------------------------------------------------------------------------*/
462 
463 static void rx_complete (struct urb *urb);
464 
465 static int rx_submit (struct usbnet *dev, struct urb *urb, gfp_t flags)
466 {
467 	struct sk_buff		*skb;
468 	struct skb_data		*entry;
469 	int			retval = 0;
470 	unsigned long		lockflags;
471 	size_t			size = dev->rx_urb_size;
472 
473 	/* prevent rx skb allocation when error ratio is high */
474 	if (test_bit(EVENT_RX_KILL, &dev->flags)) {
475 		usb_free_urb(urb);
476 		return -ENOLINK;
477 	}
478 
479 	if (test_bit(EVENT_NO_IP_ALIGN, &dev->flags))
480 		skb = __netdev_alloc_skb(dev->net, size, flags);
481 	else
482 		skb = __netdev_alloc_skb_ip_align(dev->net, size, flags);
483 	if (!skb) {
484 		netif_dbg(dev, rx_err, dev->net, "no rx skb\n");
485 		usbnet_defer_kevent (dev, EVENT_RX_MEMORY);
486 		usb_free_urb (urb);
487 		return -ENOMEM;
488 	}
489 
490 	entry = (struct skb_data *) skb->cb;
491 	entry->urb = urb;
492 	entry->dev = dev;
493 	entry->length = 0;
494 
495 	usb_fill_bulk_urb (urb, dev->udev, dev->in,
496 		skb->data, size, rx_complete, skb);
497 
498 	spin_lock_irqsave (&dev->rxq.lock, lockflags);
499 
500 	if (netif_running (dev->net) &&
501 	    netif_device_present (dev->net) &&
502 	    test_bit(EVENT_DEV_OPEN, &dev->flags) &&
503 	    !test_bit (EVENT_RX_HALT, &dev->flags) &&
504 	    !test_bit (EVENT_DEV_ASLEEP, &dev->flags)) {
505 		switch (retval = usb_submit_urb (urb, GFP_ATOMIC)) {
506 		case -EPIPE:
507 			usbnet_defer_kevent (dev, EVENT_RX_HALT);
508 			break;
509 		case -ENOMEM:
510 			usbnet_defer_kevent (dev, EVENT_RX_MEMORY);
511 			break;
512 		case -ENODEV:
513 			netif_dbg(dev, ifdown, dev->net, "device gone\n");
514 			netif_device_detach (dev->net);
515 			break;
516 		case -EHOSTUNREACH:
517 			retval = -ENOLINK;
518 			break;
519 		default:
520 			netif_dbg(dev, rx_err, dev->net,
521 				  "rx submit, %d\n", retval);
522 			tasklet_schedule (&dev->bh);
523 			break;
524 		case 0:
525 			__usbnet_queue_skb(&dev->rxq, skb, rx_start);
526 		}
527 	} else {
528 		netif_dbg(dev, ifdown, dev->net, "rx: stopped\n");
529 		retval = -ENOLINK;
530 	}
531 	spin_unlock_irqrestore (&dev->rxq.lock, lockflags);
532 	if (retval) {
533 		dev_kfree_skb_any (skb);
534 		usb_free_urb (urb);
535 	}
536 	return retval;
537 }
538 
539 
540 /*-------------------------------------------------------------------------*/
541 
542 static inline void rx_process (struct usbnet *dev, struct sk_buff *skb)
543 {
544 	if (dev->driver_info->rx_fixup &&
545 	    !dev->driver_info->rx_fixup (dev, skb)) {
546 		/* With RX_ASSEMBLE, rx_fixup() must update counters */
547 		if (!(dev->driver_info->flags & FLAG_RX_ASSEMBLE))
548 			dev->net->stats.rx_errors++;
549 		goto done;
550 	}
551 	// else network stack removes extra byte if we forced a short packet
552 
553 	/* all data was already cloned from skb inside the driver */
554 	if (dev->driver_info->flags & FLAG_MULTI_PACKET)
555 		goto done;
556 
557 	if (skb->len < ETH_HLEN) {
558 		dev->net->stats.rx_errors++;
559 		dev->net->stats.rx_length_errors++;
560 		netif_dbg(dev, rx_err, dev->net, "rx length %d\n", skb->len);
561 	} else {
562 		usbnet_skb_return(dev, skb);
563 		return;
564 	}
565 
566 done:
567 	skb_queue_tail(&dev->done, skb);
568 }
569 
570 /*-------------------------------------------------------------------------*/
571 
572 static void rx_complete (struct urb *urb)
573 {
574 	struct sk_buff		*skb = (struct sk_buff *) urb->context;
575 	struct skb_data		*entry = (struct skb_data *) skb->cb;
576 	struct usbnet		*dev = entry->dev;
577 	int			urb_status = urb->status;
578 	enum skb_state		state;
579 
580 	skb_put (skb, urb->actual_length);
581 	state = rx_done;
582 	entry->urb = NULL;
583 
584 	switch (urb_status) {
585 	/* success */
586 	case 0:
587 		break;
588 
589 	/* stalls need manual reset. this is rare ... except that
590 	 * when going through USB 2.0 TTs, unplug appears this way.
591 	 * we avoid the highspeed version of the ETIMEDOUT/EILSEQ
592 	 * storm, recovering as needed.
593 	 */
594 	case -EPIPE:
595 		dev->net->stats.rx_errors++;
596 		usbnet_defer_kevent (dev, EVENT_RX_HALT);
597 		fallthrough;
598 
599 	/* software-driven interface shutdown */
600 	case -ECONNRESET:		/* async unlink */
601 	case -ESHUTDOWN:		/* hardware gone */
602 		netif_dbg(dev, ifdown, dev->net,
603 			  "rx shutdown, code %d\n", urb_status);
604 		goto block;
605 
606 	/* we get controller i/o faults during hub_wq disconnect() delays.
607 	 * throttle down resubmits, to avoid log floods; just temporarily,
608 	 * so we still recover when the fault isn't a hub_wq delay.
609 	 */
610 	case -EPROTO:
611 	case -ETIME:
612 	case -EILSEQ:
613 		dev->net->stats.rx_errors++;
614 		if (!timer_pending (&dev->delay)) {
615 			mod_timer (&dev->delay, jiffies + THROTTLE_JIFFIES);
616 			netif_dbg(dev, link, dev->net,
617 				  "rx throttle %d\n", urb_status);
618 		}
619 block:
620 		state = rx_cleanup;
621 		entry->urb = urb;
622 		urb = NULL;
623 		break;
624 
625 	/* data overrun ... flush fifo? */
626 	case -EOVERFLOW:
627 		dev->net->stats.rx_over_errors++;
628 		fallthrough;
629 
630 	default:
631 		state = rx_cleanup;
632 		dev->net->stats.rx_errors++;
633 		netif_dbg(dev, rx_err, dev->net, "rx status %d\n", urb_status);
634 		break;
635 	}
636 
637 	/* stop rx if packet error rate is high */
638 	if (++dev->pkt_cnt > 30) {
639 		dev->pkt_cnt = 0;
640 		dev->pkt_err = 0;
641 	} else {
642 		if (state == rx_cleanup)
643 			dev->pkt_err++;
644 		if (dev->pkt_err > 20)
645 			set_bit(EVENT_RX_KILL, &dev->flags);
646 	}
647 
648 	state = defer_bh(dev, skb, &dev->rxq, state);
649 
650 	if (urb) {
651 		if (netif_running (dev->net) &&
652 		    !test_bit (EVENT_RX_HALT, &dev->flags) &&
653 		    state != unlink_start) {
654 			rx_submit (dev, urb, GFP_ATOMIC);
655 			usb_mark_last_busy(dev->udev);
656 			return;
657 		}
658 		usb_free_urb (urb);
659 	}
660 	netif_dbg(dev, rx_err, dev->net, "no read resubmitted\n");
661 }
662 
663 /*-------------------------------------------------------------------------*/
664 void usbnet_pause_rx(struct usbnet *dev)
665 {
666 	set_bit(EVENT_RX_PAUSED, &dev->flags);
667 
668 	netif_dbg(dev, rx_status, dev->net, "paused rx queue enabled\n");
669 }
670 EXPORT_SYMBOL_GPL(usbnet_pause_rx);
671 
672 void usbnet_resume_rx(struct usbnet *dev)
673 {
674 	struct sk_buff *skb;
675 	int num = 0;
676 
677 	clear_bit(EVENT_RX_PAUSED, &dev->flags);
678 
679 	while ((skb = skb_dequeue(&dev->rxq_pause)) != NULL) {
680 		usbnet_skb_return(dev, skb);
681 		num++;
682 	}
683 
684 	tasklet_schedule(&dev->bh);
685 
686 	netif_dbg(dev, rx_status, dev->net,
687 		  "paused rx queue disabled, %d skbs requeued\n", num);
688 }
689 EXPORT_SYMBOL_GPL(usbnet_resume_rx);
690 
691 void usbnet_purge_paused_rxq(struct usbnet *dev)
692 {
693 	skb_queue_purge(&dev->rxq_pause);
694 }
695 EXPORT_SYMBOL_GPL(usbnet_purge_paused_rxq);
696 
697 /*-------------------------------------------------------------------------*/
698 
699 // unlink pending rx/tx; completion handlers do all other cleanup
700 
701 static int unlink_urbs (struct usbnet *dev, struct sk_buff_head *q)
702 {
703 	unsigned long		flags;
704 	struct sk_buff		*skb;
705 	int			count = 0;
706 
707 	spin_lock_irqsave (&q->lock, flags);
708 	while (!skb_queue_empty(q)) {
709 		struct skb_data		*entry;
710 		struct urb		*urb;
711 		int			retval;
712 
713 		skb_queue_walk(q, skb) {
714 			entry = (struct skb_data *) skb->cb;
715 			if (entry->state != unlink_start)
716 				goto found;
717 		}
718 		break;
719 found:
720 		entry->state = unlink_start;
721 		urb = entry->urb;
722 
723 		/*
724 		 * Get reference count of the URB to avoid it to be
725 		 * freed during usb_unlink_urb, which may trigger
726 		 * use-after-free problem inside usb_unlink_urb since
727 		 * usb_unlink_urb is always racing with .complete
728 		 * handler(include defer_bh).
729 		 */
730 		usb_get_urb(urb);
731 		spin_unlock_irqrestore(&q->lock, flags);
732 		// during some PM-driven resume scenarios,
733 		// these (async) unlinks complete immediately
734 		retval = usb_unlink_urb (urb);
735 		if (retval != -EINPROGRESS && retval != 0)
736 			netdev_dbg(dev->net, "unlink urb err, %d\n", retval);
737 		else
738 			count++;
739 		usb_put_urb(urb);
740 		spin_lock_irqsave(&q->lock, flags);
741 	}
742 	spin_unlock_irqrestore (&q->lock, flags);
743 	return count;
744 }
745 
746 // Flush all pending rx urbs
747 // minidrivers may need to do this when the MTU changes
748 
749 void usbnet_unlink_rx_urbs(struct usbnet *dev)
750 {
751 	if (netif_running(dev->net)) {
752 		(void) unlink_urbs (dev, &dev->rxq);
753 		tasklet_schedule(&dev->bh);
754 	}
755 }
756 EXPORT_SYMBOL_GPL(usbnet_unlink_rx_urbs);
757 
758 /*-------------------------------------------------------------------------*/
759 
760 static void wait_skb_queue_empty(struct sk_buff_head *q)
761 {
762 	unsigned long flags;
763 
764 	spin_lock_irqsave(&q->lock, flags);
765 	while (!skb_queue_empty(q)) {
766 		spin_unlock_irqrestore(&q->lock, flags);
767 		schedule_timeout(msecs_to_jiffies(UNLINK_TIMEOUT_MS));
768 		set_current_state(TASK_UNINTERRUPTIBLE);
769 		spin_lock_irqsave(&q->lock, flags);
770 	}
771 	spin_unlock_irqrestore(&q->lock, flags);
772 }
773 
774 // precondition: never called in_interrupt
775 static void usbnet_terminate_urbs(struct usbnet *dev)
776 {
777 	DECLARE_WAITQUEUE(wait, current);
778 	int temp;
779 
780 	/* ensure there are no more active urbs */
781 	add_wait_queue(&dev->wait, &wait);
782 	set_current_state(TASK_UNINTERRUPTIBLE);
783 	temp = unlink_urbs(dev, &dev->txq) +
784 		unlink_urbs(dev, &dev->rxq);
785 
786 	/* maybe wait for deletions to finish. */
787 	wait_skb_queue_empty(&dev->rxq);
788 	wait_skb_queue_empty(&dev->txq);
789 	wait_skb_queue_empty(&dev->done);
790 	netif_dbg(dev, ifdown, dev->net,
791 		  "waited for %d urb completions\n", temp);
792 	set_current_state(TASK_RUNNING);
793 	remove_wait_queue(&dev->wait, &wait);
794 }
795 
796 int usbnet_stop (struct net_device *net)
797 {
798 	struct usbnet		*dev = netdev_priv(net);
799 	const struct driver_info *info = dev->driver_info;
800 	int			retval, pm, mpn;
801 
802 	clear_bit(EVENT_DEV_OPEN, &dev->flags);
803 	netif_stop_queue (net);
804 
805 	netif_info(dev, ifdown, dev->net,
806 		   "stop stats: rx/tx %lu/%lu, errs %lu/%lu\n",
807 		   net->stats.rx_packets, net->stats.tx_packets,
808 		   net->stats.rx_errors, net->stats.tx_errors);
809 
810 	/* to not race resume */
811 	pm = usb_autopm_get_interface(dev->intf);
812 	/* allow minidriver to stop correctly (wireless devices to turn off
813 	 * radio etc) */
814 	if (info->stop) {
815 		retval = info->stop(dev);
816 		if (retval < 0)
817 			netif_info(dev, ifdown, dev->net,
818 				   "stop fail (%d) usbnet usb-%s-%s, %s\n",
819 				   retval,
820 				   dev->udev->bus->bus_name, dev->udev->devpath,
821 				   info->description);
822 	}
823 
824 	if (!(info->flags & FLAG_AVOID_UNLINK_URBS))
825 		usbnet_terminate_urbs(dev);
826 
827 	usbnet_status_stop(dev);
828 
829 	usbnet_purge_paused_rxq(dev);
830 
831 	mpn = !test_and_clear_bit(EVENT_NO_RUNTIME_PM, &dev->flags);
832 
833 	/* deferred work (task, timer, softirq) must also stop.
834 	 * can't flush_scheduled_work() until we drop rtnl (later),
835 	 * else workers could deadlock; so make workers a NOP.
836 	 */
837 	dev->flags = 0;
838 	del_timer_sync (&dev->delay);
839 	tasklet_kill (&dev->bh);
840 	if (!pm)
841 		usb_autopm_put_interface(dev->intf);
842 
843 	if (info->manage_power && mpn)
844 		info->manage_power(dev, 0);
845 	else
846 		usb_autopm_put_interface(dev->intf);
847 
848 	return 0;
849 }
850 EXPORT_SYMBOL_GPL(usbnet_stop);
851 
852 /*-------------------------------------------------------------------------*/
853 
854 // posts reads, and enables write queuing
855 
856 // precondition: never called in_interrupt
857 
858 int usbnet_open (struct net_device *net)
859 {
860 	struct usbnet		*dev = netdev_priv(net);
861 	int			retval;
862 	const struct driver_info *info = dev->driver_info;
863 
864 	if ((retval = usb_autopm_get_interface(dev->intf)) < 0) {
865 		netif_info(dev, ifup, dev->net,
866 			   "resumption fail (%d) usbnet usb-%s-%s, %s\n",
867 			   retval,
868 			   dev->udev->bus->bus_name,
869 			   dev->udev->devpath,
870 			   info->description);
871 		goto done_nopm;
872 	}
873 
874 	// put into "known safe" state
875 	if (info->reset && (retval = info->reset (dev)) < 0) {
876 		netif_info(dev, ifup, dev->net,
877 			   "open reset fail (%d) usbnet usb-%s-%s, %s\n",
878 			   retval,
879 			   dev->udev->bus->bus_name,
880 			   dev->udev->devpath,
881 			   info->description);
882 		goto done;
883 	}
884 
885 	/* hard_mtu or rx_urb_size may change in reset() */
886 	usbnet_update_max_qlen(dev);
887 
888 	// insist peer be connected
889 	if (info->check_connect && (retval = info->check_connect (dev)) < 0) {
890 		netif_err(dev, ifup, dev->net, "can't open; %d\n", retval);
891 		goto done;
892 	}
893 
894 	/* start any status interrupt transfer */
895 	if (dev->interrupt) {
896 		retval = usbnet_status_start(dev, GFP_KERNEL);
897 		if (retval < 0) {
898 			netif_err(dev, ifup, dev->net,
899 				  "intr submit %d\n", retval);
900 			goto done;
901 		}
902 	}
903 
904 	set_bit(EVENT_DEV_OPEN, &dev->flags);
905 	netif_start_queue (net);
906 	netif_info(dev, ifup, dev->net,
907 		   "open: enable queueing (rx %d, tx %d) mtu %d %s framing\n",
908 		   (int)RX_QLEN(dev), (int)TX_QLEN(dev),
909 		   dev->net->mtu,
910 		   (dev->driver_info->flags & FLAG_FRAMING_NC) ? "NetChip" :
911 		   (dev->driver_info->flags & FLAG_FRAMING_GL) ? "GeneSys" :
912 		   (dev->driver_info->flags & FLAG_FRAMING_Z) ? "Zaurus" :
913 		   (dev->driver_info->flags & FLAG_FRAMING_RN) ? "RNDIS" :
914 		   (dev->driver_info->flags & FLAG_FRAMING_AX) ? "ASIX" :
915 		   "simple");
916 
917 	/* reset rx error state */
918 	dev->pkt_cnt = 0;
919 	dev->pkt_err = 0;
920 	clear_bit(EVENT_RX_KILL, &dev->flags);
921 
922 	// delay posting reads until we're fully open
923 	tasklet_schedule (&dev->bh);
924 	if (info->manage_power) {
925 		retval = info->manage_power(dev, 1);
926 		if (retval < 0) {
927 			retval = 0;
928 			set_bit(EVENT_NO_RUNTIME_PM, &dev->flags);
929 		} else {
930 			usb_autopm_put_interface(dev->intf);
931 		}
932 	}
933 	return retval;
934 done:
935 	usb_autopm_put_interface(dev->intf);
936 done_nopm:
937 	return retval;
938 }
939 EXPORT_SYMBOL_GPL(usbnet_open);
940 
941 /*-------------------------------------------------------------------------*/
942 
943 /* ethtool methods; minidrivers may need to add some more, but
944  * they'll probably want to use this base set.
945  */
946 
947 /* These methods are written on the assumption that the device
948  * uses MII
949  */
950 int usbnet_get_link_ksettings_mii(struct net_device *net,
951 			      struct ethtool_link_ksettings *cmd)
952 {
953 	struct usbnet *dev = netdev_priv(net);
954 
955 	if (!dev->mii.mdio_read)
956 		return -EOPNOTSUPP;
957 
958 	mii_ethtool_get_link_ksettings(&dev->mii, cmd);
959 
960 	return 0;
961 }
962 EXPORT_SYMBOL_GPL(usbnet_get_link_ksettings_mii);
963 
964 int usbnet_get_link_ksettings_internal(struct net_device *net,
965 					struct ethtool_link_ksettings *cmd)
966 {
967 	struct usbnet *dev = netdev_priv(net);
968 
969 	/* the assumption that speed is equal on tx and rx
970 	 * is deeply engrained into the networking layer.
971 	 * For wireless stuff it is not true.
972 	 * We assume that rx_speed matters more.
973 	 */
974 	if (dev->rx_speed != SPEED_UNSET)
975 		cmd->base.speed = dev->rx_speed / 1000000;
976 	else if (dev->tx_speed != SPEED_UNSET)
977 		cmd->base.speed = dev->tx_speed / 1000000;
978 	else
979 		cmd->base.speed = SPEED_UNKNOWN;
980 
981 	return 0;
982 }
983 EXPORT_SYMBOL_GPL(usbnet_get_link_ksettings_internal);
984 
985 int usbnet_set_link_ksettings_mii(struct net_device *net,
986 			      const struct ethtool_link_ksettings *cmd)
987 {
988 	struct usbnet *dev = netdev_priv(net);
989 	int retval;
990 
991 	if (!dev->mii.mdio_write)
992 		return -EOPNOTSUPP;
993 
994 	retval = mii_ethtool_set_link_ksettings(&dev->mii, cmd);
995 
996 	/* link speed/duplex might have changed */
997 	if (dev->driver_info->link_reset)
998 		dev->driver_info->link_reset(dev);
999 
1000 	/* hard_mtu or rx_urb_size may change in link_reset() */
1001 	usbnet_update_max_qlen(dev);
1002 
1003 	return retval;
1004 }
1005 EXPORT_SYMBOL_GPL(usbnet_set_link_ksettings_mii);
1006 
1007 u32 usbnet_get_link (struct net_device *net)
1008 {
1009 	struct usbnet *dev = netdev_priv(net);
1010 
1011 	/* If a check_connect is defined, return its result */
1012 	if (dev->driver_info->check_connect)
1013 		return dev->driver_info->check_connect (dev) == 0;
1014 
1015 	/* if the device has mii operations, use those */
1016 	if (dev->mii.mdio_read)
1017 		return mii_link_ok(&dev->mii);
1018 
1019 	/* Otherwise, dtrt for drivers calling netif_carrier_{on,off} */
1020 	return ethtool_op_get_link(net);
1021 }
1022 EXPORT_SYMBOL_GPL(usbnet_get_link);
1023 
1024 int usbnet_nway_reset(struct net_device *net)
1025 {
1026 	struct usbnet *dev = netdev_priv(net);
1027 
1028 	if (!dev->mii.mdio_write)
1029 		return -EOPNOTSUPP;
1030 
1031 	return mii_nway_restart(&dev->mii);
1032 }
1033 EXPORT_SYMBOL_GPL(usbnet_nway_reset);
1034 
1035 void usbnet_get_drvinfo (struct net_device *net, struct ethtool_drvinfo *info)
1036 {
1037 	struct usbnet *dev = netdev_priv(net);
1038 
1039 	strlcpy (info->driver, dev->driver_name, sizeof info->driver);
1040 	strlcpy (info->fw_version, dev->driver_info->description,
1041 		sizeof info->fw_version);
1042 	usb_make_path (dev->udev, info->bus_info, sizeof info->bus_info);
1043 }
1044 EXPORT_SYMBOL_GPL(usbnet_get_drvinfo);
1045 
1046 u32 usbnet_get_msglevel (struct net_device *net)
1047 {
1048 	struct usbnet *dev = netdev_priv(net);
1049 
1050 	return dev->msg_enable;
1051 }
1052 EXPORT_SYMBOL_GPL(usbnet_get_msglevel);
1053 
1054 void usbnet_set_msglevel (struct net_device *net, u32 level)
1055 {
1056 	struct usbnet *dev = netdev_priv(net);
1057 
1058 	dev->msg_enable = level;
1059 }
1060 EXPORT_SYMBOL_GPL(usbnet_set_msglevel);
1061 
1062 /* drivers may override default ethtool_ops in their bind() routine */
1063 static const struct ethtool_ops usbnet_ethtool_ops = {
1064 	.get_link		= usbnet_get_link,
1065 	.nway_reset		= usbnet_nway_reset,
1066 	.get_drvinfo		= usbnet_get_drvinfo,
1067 	.get_msglevel		= usbnet_get_msglevel,
1068 	.set_msglevel		= usbnet_set_msglevel,
1069 	.get_ts_info		= ethtool_op_get_ts_info,
1070 	.get_link_ksettings	= usbnet_get_link_ksettings_mii,
1071 	.set_link_ksettings	= usbnet_set_link_ksettings_mii,
1072 };
1073 
1074 /*-------------------------------------------------------------------------*/
1075 
1076 static void __handle_link_change(struct usbnet *dev)
1077 {
1078 	if (!test_bit(EVENT_DEV_OPEN, &dev->flags))
1079 		return;
1080 
1081 	if (!netif_carrier_ok(dev->net)) {
1082 		/* kill URBs for reading packets to save bus bandwidth */
1083 		unlink_urbs(dev, &dev->rxq);
1084 
1085 		/*
1086 		 * tx_timeout will unlink URBs for sending packets and
1087 		 * tx queue is stopped by netcore after link becomes off
1088 		 */
1089 	} else {
1090 		/* submitting URBs for reading packets */
1091 		tasklet_schedule(&dev->bh);
1092 	}
1093 
1094 	/* hard_mtu or rx_urb_size may change during link change */
1095 	usbnet_update_max_qlen(dev);
1096 
1097 	clear_bit(EVENT_LINK_CHANGE, &dev->flags);
1098 }
1099 
1100 void usbnet_set_rx_mode(struct net_device *net)
1101 {
1102 	struct usbnet		*dev = netdev_priv(net);
1103 
1104 	usbnet_defer_kevent(dev, EVENT_SET_RX_MODE);
1105 }
1106 EXPORT_SYMBOL_GPL(usbnet_set_rx_mode);
1107 
1108 static void __handle_set_rx_mode(struct usbnet *dev)
1109 {
1110 	if (dev->driver_info->set_rx_mode)
1111 		(dev->driver_info->set_rx_mode)(dev);
1112 
1113 	clear_bit(EVENT_SET_RX_MODE, &dev->flags);
1114 }
1115 
1116 /* work that cannot be done in interrupt context uses keventd.
1117  *
1118  * NOTE:  with 2.5 we could do more of this using completion callbacks,
1119  * especially now that control transfers can be queued.
1120  */
1121 static void
1122 usbnet_deferred_kevent (struct work_struct *work)
1123 {
1124 	struct usbnet		*dev =
1125 		container_of(work, struct usbnet, kevent);
1126 	int			status;
1127 
1128 	/* usb_clear_halt() needs a thread context */
1129 	if (test_bit (EVENT_TX_HALT, &dev->flags)) {
1130 		unlink_urbs (dev, &dev->txq);
1131 		status = usb_autopm_get_interface(dev->intf);
1132 		if (status < 0)
1133 			goto fail_pipe;
1134 		status = usb_clear_halt (dev->udev, dev->out);
1135 		usb_autopm_put_interface(dev->intf);
1136 		if (status < 0 &&
1137 		    status != -EPIPE &&
1138 		    status != -ESHUTDOWN) {
1139 			if (netif_msg_tx_err (dev))
1140 fail_pipe:
1141 				netdev_err(dev->net, "can't clear tx halt, status %d\n",
1142 					   status);
1143 		} else {
1144 			clear_bit (EVENT_TX_HALT, &dev->flags);
1145 			if (status != -ESHUTDOWN)
1146 				netif_wake_queue (dev->net);
1147 		}
1148 	}
1149 	if (test_bit (EVENT_RX_HALT, &dev->flags)) {
1150 		unlink_urbs (dev, &dev->rxq);
1151 		status = usb_autopm_get_interface(dev->intf);
1152 		if (status < 0)
1153 			goto fail_halt;
1154 		status = usb_clear_halt (dev->udev, dev->in);
1155 		usb_autopm_put_interface(dev->intf);
1156 		if (status < 0 &&
1157 		    status != -EPIPE &&
1158 		    status != -ESHUTDOWN) {
1159 			if (netif_msg_rx_err (dev))
1160 fail_halt:
1161 				netdev_err(dev->net, "can't clear rx halt, status %d\n",
1162 					   status);
1163 		} else {
1164 			clear_bit (EVENT_RX_HALT, &dev->flags);
1165 			tasklet_schedule (&dev->bh);
1166 		}
1167 	}
1168 
1169 	/* tasklet could resubmit itself forever if memory is tight */
1170 	if (test_bit (EVENT_RX_MEMORY, &dev->flags)) {
1171 		struct urb	*urb = NULL;
1172 		int resched = 1;
1173 
1174 		if (netif_running (dev->net))
1175 			urb = usb_alloc_urb (0, GFP_KERNEL);
1176 		else
1177 			clear_bit (EVENT_RX_MEMORY, &dev->flags);
1178 		if (urb != NULL) {
1179 			clear_bit (EVENT_RX_MEMORY, &dev->flags);
1180 			status = usb_autopm_get_interface(dev->intf);
1181 			if (status < 0) {
1182 				usb_free_urb(urb);
1183 				goto fail_lowmem;
1184 			}
1185 			if (rx_submit (dev, urb, GFP_KERNEL) == -ENOLINK)
1186 				resched = 0;
1187 			usb_autopm_put_interface(dev->intf);
1188 fail_lowmem:
1189 			if (resched)
1190 				tasklet_schedule (&dev->bh);
1191 		}
1192 	}
1193 
1194 	if (test_bit (EVENT_LINK_RESET, &dev->flags)) {
1195 		const struct driver_info *info = dev->driver_info;
1196 		int			retval = 0;
1197 
1198 		clear_bit (EVENT_LINK_RESET, &dev->flags);
1199 		status = usb_autopm_get_interface(dev->intf);
1200 		if (status < 0)
1201 			goto skip_reset;
1202 		if(info->link_reset && (retval = info->link_reset(dev)) < 0) {
1203 			usb_autopm_put_interface(dev->intf);
1204 skip_reset:
1205 			netdev_info(dev->net, "link reset failed (%d) usbnet usb-%s-%s, %s\n",
1206 				    retval,
1207 				    dev->udev->bus->bus_name,
1208 				    dev->udev->devpath,
1209 				    info->description);
1210 		} else {
1211 			usb_autopm_put_interface(dev->intf);
1212 		}
1213 
1214 		/* handle link change from link resetting */
1215 		__handle_link_change(dev);
1216 	}
1217 
1218 	if (test_bit (EVENT_LINK_CHANGE, &dev->flags))
1219 		__handle_link_change(dev);
1220 
1221 	if (test_bit (EVENT_SET_RX_MODE, &dev->flags))
1222 		__handle_set_rx_mode(dev);
1223 
1224 
1225 	if (dev->flags)
1226 		netdev_dbg(dev->net, "kevent done, flags = 0x%lx\n", dev->flags);
1227 }
1228 
1229 /*-------------------------------------------------------------------------*/
1230 
1231 static void tx_complete (struct urb *urb)
1232 {
1233 	struct sk_buff		*skb = (struct sk_buff *) urb->context;
1234 	struct skb_data		*entry = (struct skb_data *) skb->cb;
1235 	struct usbnet		*dev = entry->dev;
1236 
1237 	if (urb->status == 0) {
1238 		struct pcpu_sw_netstats *stats64 = this_cpu_ptr(dev->net->tstats);
1239 		unsigned long flags;
1240 
1241 		flags = u64_stats_update_begin_irqsave(&stats64->syncp);
1242 		stats64->tx_packets += entry->packets;
1243 		stats64->tx_bytes += entry->length;
1244 		u64_stats_update_end_irqrestore(&stats64->syncp, flags);
1245 	} else {
1246 		dev->net->stats.tx_errors++;
1247 
1248 		switch (urb->status) {
1249 		case -EPIPE:
1250 			usbnet_defer_kevent (dev, EVENT_TX_HALT);
1251 			break;
1252 
1253 		/* software-driven interface shutdown */
1254 		case -ECONNRESET:		// async unlink
1255 		case -ESHUTDOWN:		// hardware gone
1256 			break;
1257 
1258 		/* like rx, tx gets controller i/o faults during hub_wq
1259 		 * delays and so it uses the same throttling mechanism.
1260 		 */
1261 		case -EPROTO:
1262 		case -ETIME:
1263 		case -EILSEQ:
1264 			usb_mark_last_busy(dev->udev);
1265 			if (!timer_pending (&dev->delay)) {
1266 				mod_timer (&dev->delay,
1267 					jiffies + THROTTLE_JIFFIES);
1268 				netif_dbg(dev, link, dev->net,
1269 					  "tx throttle %d\n", urb->status);
1270 			}
1271 			netif_stop_queue (dev->net);
1272 			break;
1273 		default:
1274 			netif_dbg(dev, tx_err, dev->net,
1275 				  "tx err %d\n", entry->urb->status);
1276 			break;
1277 		}
1278 	}
1279 
1280 	usb_autopm_put_interface_async(dev->intf);
1281 	(void) defer_bh(dev, skb, &dev->txq, tx_done);
1282 }
1283 
1284 /*-------------------------------------------------------------------------*/
1285 
1286 void usbnet_tx_timeout (struct net_device *net, unsigned int txqueue)
1287 {
1288 	struct usbnet		*dev = netdev_priv(net);
1289 
1290 	unlink_urbs (dev, &dev->txq);
1291 	tasklet_schedule (&dev->bh);
1292 	/* this needs to be handled individually because the generic layer
1293 	 * doesn't know what is sufficient and could not restore private
1294 	 * information if a remedy of an unconditional reset were used.
1295 	 */
1296 	if (dev->driver_info->recover)
1297 		(dev->driver_info->recover)(dev);
1298 }
1299 EXPORT_SYMBOL_GPL(usbnet_tx_timeout);
1300 
1301 /*-------------------------------------------------------------------------*/
1302 
1303 static int build_dma_sg(const struct sk_buff *skb, struct urb *urb)
1304 {
1305 	unsigned num_sgs, total_len = 0;
1306 	int i, s = 0;
1307 
1308 	num_sgs = skb_shinfo(skb)->nr_frags + 1;
1309 	if (num_sgs == 1)
1310 		return 0;
1311 
1312 	/* reserve one for zero packet */
1313 	urb->sg = kmalloc_array(num_sgs + 1, sizeof(struct scatterlist),
1314 				GFP_ATOMIC);
1315 	if (!urb->sg)
1316 		return -ENOMEM;
1317 
1318 	urb->num_sgs = num_sgs;
1319 	sg_init_table(urb->sg, urb->num_sgs + 1);
1320 
1321 	sg_set_buf(&urb->sg[s++], skb->data, skb_headlen(skb));
1322 	total_len += skb_headlen(skb);
1323 
1324 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1325 		skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1326 
1327 		total_len += skb_frag_size(f);
1328 		sg_set_page(&urb->sg[i + s], skb_frag_page(f), skb_frag_size(f),
1329 			    skb_frag_off(f));
1330 	}
1331 	urb->transfer_buffer_length = total_len;
1332 
1333 	return 1;
1334 }
1335 
1336 netdev_tx_t usbnet_start_xmit (struct sk_buff *skb,
1337 				     struct net_device *net)
1338 {
1339 	struct usbnet		*dev = netdev_priv(net);
1340 	unsigned int			length;
1341 	struct urb		*urb = NULL;
1342 	struct skb_data		*entry;
1343 	const struct driver_info *info = dev->driver_info;
1344 	unsigned long		flags;
1345 	int retval;
1346 
1347 	if (skb)
1348 		skb_tx_timestamp(skb);
1349 
1350 	// some devices want funky USB-level framing, for
1351 	// win32 driver (usually) and/or hardware quirks
1352 	if (info->tx_fixup) {
1353 		skb = info->tx_fixup (dev, skb, GFP_ATOMIC);
1354 		if (!skb) {
1355 			/* packet collected; minidriver waiting for more */
1356 			if (info->flags & FLAG_MULTI_PACKET)
1357 				goto not_drop;
1358 			netif_dbg(dev, tx_err, dev->net, "can't tx_fixup skb\n");
1359 			goto drop;
1360 		}
1361 	}
1362 
1363 	if (!(urb = usb_alloc_urb (0, GFP_ATOMIC))) {
1364 		netif_dbg(dev, tx_err, dev->net, "no urb\n");
1365 		goto drop;
1366 	}
1367 
1368 	entry = (struct skb_data *) skb->cb;
1369 	entry->urb = urb;
1370 	entry->dev = dev;
1371 
1372 	usb_fill_bulk_urb (urb, dev->udev, dev->out,
1373 			skb->data, skb->len, tx_complete, skb);
1374 	if (dev->can_dma_sg) {
1375 		if (build_dma_sg(skb, urb) < 0)
1376 			goto drop;
1377 	}
1378 	length = urb->transfer_buffer_length;
1379 
1380 	/* don't assume the hardware handles USB_ZERO_PACKET
1381 	 * NOTE:  strictly conforming cdc-ether devices should expect
1382 	 * the ZLP here, but ignore the one-byte packet.
1383 	 * NOTE2: CDC NCM specification is different from CDC ECM when
1384 	 * handling ZLP/short packets, so cdc_ncm driver will make short
1385 	 * packet itself if needed.
1386 	 */
1387 	if (length % dev->maxpacket == 0) {
1388 		if (!(info->flags & FLAG_SEND_ZLP)) {
1389 			if (!(info->flags & FLAG_MULTI_PACKET)) {
1390 				length++;
1391 				if (skb_tailroom(skb) && !urb->num_sgs) {
1392 					skb->data[skb->len] = 0;
1393 					__skb_put(skb, 1);
1394 				} else if (urb->num_sgs)
1395 					sg_set_buf(&urb->sg[urb->num_sgs++],
1396 							dev->padding_pkt, 1);
1397 			}
1398 		} else
1399 			urb->transfer_flags |= URB_ZERO_PACKET;
1400 	}
1401 	urb->transfer_buffer_length = length;
1402 
1403 	if (info->flags & FLAG_MULTI_PACKET) {
1404 		/* Driver has set number of packets and a length delta.
1405 		 * Calculate the complete length and ensure that it's
1406 		 * positive.
1407 		 */
1408 		entry->length += length;
1409 		if (WARN_ON_ONCE(entry->length <= 0))
1410 			entry->length = length;
1411 	} else {
1412 		usbnet_set_skb_tx_stats(skb, 1, length);
1413 	}
1414 
1415 	spin_lock_irqsave(&dev->txq.lock, flags);
1416 	retval = usb_autopm_get_interface_async(dev->intf);
1417 	if (retval < 0) {
1418 		spin_unlock_irqrestore(&dev->txq.lock, flags);
1419 		goto drop;
1420 	}
1421 	if (netif_queue_stopped(net)) {
1422 		usb_autopm_put_interface_async(dev->intf);
1423 		spin_unlock_irqrestore(&dev->txq.lock, flags);
1424 		goto drop;
1425 	}
1426 
1427 #ifdef CONFIG_PM
1428 	/* if this triggers the device is still a sleep */
1429 	if (test_bit(EVENT_DEV_ASLEEP, &dev->flags)) {
1430 		/* transmission will be done in resume */
1431 		usb_anchor_urb(urb, &dev->deferred);
1432 		/* no use to process more packets */
1433 		netif_stop_queue(net);
1434 		usb_put_urb(urb);
1435 		spin_unlock_irqrestore(&dev->txq.lock, flags);
1436 		netdev_dbg(dev->net, "Delaying transmission for resumption\n");
1437 		goto deferred;
1438 	}
1439 #endif
1440 
1441 	switch ((retval = usb_submit_urb (urb, GFP_ATOMIC))) {
1442 	case -EPIPE:
1443 		netif_stop_queue (net);
1444 		usbnet_defer_kevent (dev, EVENT_TX_HALT);
1445 		usb_autopm_put_interface_async(dev->intf);
1446 		break;
1447 	default:
1448 		usb_autopm_put_interface_async(dev->intf);
1449 		netif_dbg(dev, tx_err, dev->net,
1450 			  "tx: submit urb err %d\n", retval);
1451 		break;
1452 	case 0:
1453 		netif_trans_update(net);
1454 		__usbnet_queue_skb(&dev->txq, skb, tx_start);
1455 		if (dev->txq.qlen >= TX_QLEN (dev))
1456 			netif_stop_queue (net);
1457 	}
1458 	spin_unlock_irqrestore (&dev->txq.lock, flags);
1459 
1460 	if (retval) {
1461 		netif_dbg(dev, tx_err, dev->net, "drop, code %d\n", retval);
1462 drop:
1463 		dev->net->stats.tx_dropped++;
1464 not_drop:
1465 		if (skb)
1466 			dev_kfree_skb_any (skb);
1467 		if (urb) {
1468 			kfree(urb->sg);
1469 			usb_free_urb(urb);
1470 		}
1471 	} else
1472 		netif_dbg(dev, tx_queued, dev->net,
1473 			  "> tx, len %u, type 0x%x\n", length, skb->protocol);
1474 #ifdef CONFIG_PM
1475 deferred:
1476 #endif
1477 	return NETDEV_TX_OK;
1478 }
1479 EXPORT_SYMBOL_GPL(usbnet_start_xmit);
1480 
1481 static int rx_alloc_submit(struct usbnet *dev, gfp_t flags)
1482 {
1483 	struct urb	*urb;
1484 	int		i;
1485 	int		ret = 0;
1486 
1487 	/* don't refill the queue all at once */
1488 	for (i = 0; i < 10 && dev->rxq.qlen < RX_QLEN(dev); i++) {
1489 		urb = usb_alloc_urb(0, flags);
1490 		if (urb != NULL) {
1491 			ret = rx_submit(dev, urb, flags);
1492 			if (ret)
1493 				goto err;
1494 		} else {
1495 			ret = -ENOMEM;
1496 			goto err;
1497 		}
1498 	}
1499 err:
1500 	return ret;
1501 }
1502 
1503 /*-------------------------------------------------------------------------*/
1504 
1505 // tasklet (work deferred from completions, in_irq) or timer
1506 
1507 static void usbnet_bh (struct timer_list *t)
1508 {
1509 	struct usbnet		*dev = from_timer(dev, t, delay);
1510 	struct sk_buff		*skb;
1511 	struct skb_data		*entry;
1512 
1513 	while ((skb = skb_dequeue (&dev->done))) {
1514 		entry = (struct skb_data *) skb->cb;
1515 		switch (entry->state) {
1516 		case rx_done:
1517 			entry->state = rx_cleanup;
1518 			rx_process (dev, skb);
1519 			continue;
1520 		case tx_done:
1521 			kfree(entry->urb->sg);
1522 			fallthrough;
1523 		case rx_cleanup:
1524 			usb_free_urb (entry->urb);
1525 			dev_kfree_skb (skb);
1526 			continue;
1527 		default:
1528 			netdev_dbg(dev->net, "bogus skb state %d\n", entry->state);
1529 		}
1530 	}
1531 
1532 	/* restart RX again after disabling due to high error rate */
1533 	clear_bit(EVENT_RX_KILL, &dev->flags);
1534 
1535 	/* waiting for all pending urbs to complete?
1536 	 * only then can we forgo submitting anew
1537 	 */
1538 	if (waitqueue_active(&dev->wait)) {
1539 		if (dev->txq.qlen + dev->rxq.qlen + dev->done.qlen == 0)
1540 			wake_up_all(&dev->wait);
1541 
1542 	// or are we maybe short a few urbs?
1543 	} else if (netif_running (dev->net) &&
1544 		   netif_device_present (dev->net) &&
1545 		   netif_carrier_ok(dev->net) &&
1546 		   !timer_pending(&dev->delay) &&
1547 		   !test_bit(EVENT_RX_PAUSED, &dev->flags) &&
1548 		   !test_bit(EVENT_RX_HALT, &dev->flags)) {
1549 		int	temp = dev->rxq.qlen;
1550 
1551 		if (temp < RX_QLEN(dev)) {
1552 			if (rx_alloc_submit(dev, GFP_ATOMIC) == -ENOLINK)
1553 				return;
1554 			if (temp != dev->rxq.qlen)
1555 				netif_dbg(dev, link, dev->net,
1556 					  "rxqlen %d --> %d\n",
1557 					  temp, dev->rxq.qlen);
1558 			if (dev->rxq.qlen < RX_QLEN(dev))
1559 				tasklet_schedule (&dev->bh);
1560 		}
1561 		if (dev->txq.qlen < TX_QLEN (dev))
1562 			netif_wake_queue (dev->net);
1563 	}
1564 }
1565 
1566 static void usbnet_bh_tasklet(struct tasklet_struct *t)
1567 {
1568 	struct usbnet *dev = from_tasklet(dev, t, bh);
1569 
1570 	usbnet_bh(&dev->delay);
1571 }
1572 
1573 
1574 /*-------------------------------------------------------------------------
1575  *
1576  * USB Device Driver support
1577  *
1578  *-------------------------------------------------------------------------*/
1579 
1580 // precondition: never called in_interrupt
1581 
1582 void usbnet_disconnect (struct usb_interface *intf)
1583 {
1584 	struct usbnet		*dev;
1585 	struct usb_device	*xdev;
1586 	struct net_device	*net;
1587 
1588 	dev = usb_get_intfdata(intf);
1589 	usb_set_intfdata(intf, NULL);
1590 	if (!dev)
1591 		return;
1592 
1593 	xdev = interface_to_usbdev (intf);
1594 
1595 	netif_info(dev, probe, dev->net, "unregister '%s' usb-%s-%s, %s\n",
1596 		   intf->dev.driver->name,
1597 		   xdev->bus->bus_name, xdev->devpath,
1598 		   dev->driver_info->description);
1599 
1600 	net = dev->net;
1601 	unregister_netdev (net);
1602 
1603 	cancel_work_sync(&dev->kevent);
1604 
1605 	usb_scuttle_anchored_urbs(&dev->deferred);
1606 
1607 	if (dev->driver_info->unbind)
1608 		dev->driver_info->unbind (dev, intf);
1609 
1610 	usb_kill_urb(dev->interrupt);
1611 	usb_free_urb(dev->interrupt);
1612 	kfree(dev->padding_pkt);
1613 
1614 	free_percpu(net->tstats);
1615 	free_netdev(net);
1616 }
1617 EXPORT_SYMBOL_GPL(usbnet_disconnect);
1618 
1619 static const struct net_device_ops usbnet_netdev_ops = {
1620 	.ndo_open		= usbnet_open,
1621 	.ndo_stop		= usbnet_stop,
1622 	.ndo_start_xmit		= usbnet_start_xmit,
1623 	.ndo_tx_timeout		= usbnet_tx_timeout,
1624 	.ndo_set_rx_mode	= usbnet_set_rx_mode,
1625 	.ndo_change_mtu		= usbnet_change_mtu,
1626 	.ndo_get_stats64	= dev_get_tstats64,
1627 	.ndo_set_mac_address 	= eth_mac_addr,
1628 	.ndo_validate_addr	= eth_validate_addr,
1629 };
1630 
1631 /*-------------------------------------------------------------------------*/
1632 
1633 // precondition: never called in_interrupt
1634 
1635 static struct device_type wlan_type = {
1636 	.name	= "wlan",
1637 };
1638 
1639 static struct device_type wwan_type = {
1640 	.name	= "wwan",
1641 };
1642 
1643 int
1644 usbnet_probe (struct usb_interface *udev, const struct usb_device_id *prod)
1645 {
1646 	struct usbnet			*dev;
1647 	struct net_device		*net;
1648 	struct usb_host_interface	*interface;
1649 	const struct driver_info	*info;
1650 	struct usb_device		*xdev;
1651 	int				status;
1652 	const char			*name;
1653 	struct usb_driver 	*driver = to_usb_driver(udev->dev.driver);
1654 
1655 	/* usbnet already took usb runtime pm, so have to enable the feature
1656 	 * for usb interface, otherwise usb_autopm_get_interface may return
1657 	 * failure if RUNTIME_PM is enabled.
1658 	 */
1659 	if (!driver->supports_autosuspend) {
1660 		driver->supports_autosuspend = 1;
1661 		pm_runtime_enable(&udev->dev);
1662 	}
1663 
1664 	name = udev->dev.driver->name;
1665 	info = (const struct driver_info *) prod->driver_info;
1666 	if (!info) {
1667 		dev_dbg (&udev->dev, "blacklisted by %s\n", name);
1668 		return -ENODEV;
1669 	}
1670 	xdev = interface_to_usbdev (udev);
1671 	interface = udev->cur_altsetting;
1672 
1673 	status = -ENOMEM;
1674 
1675 	// set up our own records
1676 	net = alloc_etherdev(sizeof(*dev));
1677 	if (!net)
1678 		goto out;
1679 
1680 	/* netdev_printk() needs this so do it as early as possible */
1681 	SET_NETDEV_DEV(net, &udev->dev);
1682 
1683 	dev = netdev_priv(net);
1684 	dev->udev = xdev;
1685 	dev->intf = udev;
1686 	dev->driver_info = info;
1687 	dev->driver_name = name;
1688 	dev->rx_speed = SPEED_UNSET;
1689 	dev->tx_speed = SPEED_UNSET;
1690 
1691 	net->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
1692 	if (!net->tstats)
1693 		goto out0;
1694 
1695 	dev->msg_enable = netif_msg_init (msg_level, NETIF_MSG_DRV
1696 				| NETIF_MSG_PROBE | NETIF_MSG_LINK);
1697 	init_waitqueue_head(&dev->wait);
1698 	skb_queue_head_init (&dev->rxq);
1699 	skb_queue_head_init (&dev->txq);
1700 	skb_queue_head_init (&dev->done);
1701 	skb_queue_head_init(&dev->rxq_pause);
1702 	tasklet_setup(&dev->bh, usbnet_bh_tasklet);
1703 	INIT_WORK (&dev->kevent, usbnet_deferred_kevent);
1704 	init_usb_anchor(&dev->deferred);
1705 	timer_setup(&dev->delay, usbnet_bh, 0);
1706 	mutex_init (&dev->phy_mutex);
1707 	mutex_init(&dev->interrupt_mutex);
1708 	dev->interrupt_count = 0;
1709 
1710 	dev->net = net;
1711 	strcpy (net->name, "usb%d");
1712 	memcpy (net->dev_addr, node_id, sizeof node_id);
1713 
1714 	/* rx and tx sides can use different message sizes;
1715 	 * bind() should set rx_urb_size in that case.
1716 	 */
1717 	dev->hard_mtu = net->mtu + net->hard_header_len;
1718 	net->min_mtu = 0;
1719 	net->max_mtu = ETH_MAX_MTU;
1720 
1721 	net->netdev_ops = &usbnet_netdev_ops;
1722 	net->watchdog_timeo = TX_TIMEOUT_JIFFIES;
1723 	net->ethtool_ops = &usbnet_ethtool_ops;
1724 
1725 	// allow device-specific bind/init procedures
1726 	// NOTE net->name still not usable ...
1727 	if (info->bind) {
1728 		status = info->bind (dev, udev);
1729 		if (status < 0)
1730 			goto out1;
1731 
1732 		// heuristic:  "usb%d" for links we know are two-host,
1733 		// else "eth%d" when there's reasonable doubt.  userspace
1734 		// can rename the link if it knows better.
1735 		if ((dev->driver_info->flags & FLAG_ETHER) != 0 &&
1736 		    ((dev->driver_info->flags & FLAG_POINTTOPOINT) == 0 ||
1737 		     (net->dev_addr [0] & 0x02) == 0))
1738 			strcpy (net->name, "eth%d");
1739 		/* WLAN devices should always be named "wlan%d" */
1740 		if ((dev->driver_info->flags & FLAG_WLAN) != 0)
1741 			strcpy(net->name, "wlan%d");
1742 		/* WWAN devices should always be named "wwan%d" */
1743 		if ((dev->driver_info->flags & FLAG_WWAN) != 0)
1744 			strcpy(net->name, "wwan%d");
1745 
1746 		/* devices that cannot do ARP */
1747 		if ((dev->driver_info->flags & FLAG_NOARP) != 0)
1748 			net->flags |= IFF_NOARP;
1749 
1750 		/* maybe the remote can't receive an Ethernet MTU */
1751 		if (net->mtu > (dev->hard_mtu - net->hard_header_len))
1752 			net->mtu = dev->hard_mtu - net->hard_header_len;
1753 	} else if (!info->in || !info->out)
1754 		status = usbnet_get_endpoints (dev, udev);
1755 	else {
1756 		dev->in = usb_rcvbulkpipe (xdev, info->in);
1757 		dev->out = usb_sndbulkpipe (xdev, info->out);
1758 		if (!(info->flags & FLAG_NO_SETINT))
1759 			status = usb_set_interface (xdev,
1760 				interface->desc.bInterfaceNumber,
1761 				interface->desc.bAlternateSetting);
1762 		else
1763 			status = 0;
1764 
1765 	}
1766 	if (status >= 0 && dev->status)
1767 		status = init_status (dev, udev);
1768 	if (status < 0)
1769 		goto out3;
1770 
1771 	if (!dev->rx_urb_size)
1772 		dev->rx_urb_size = dev->hard_mtu;
1773 	dev->maxpacket = usb_maxpacket (dev->udev, dev->out, 1);
1774 
1775 	/* let userspace know we have a random address */
1776 	if (ether_addr_equal(net->dev_addr, node_id))
1777 		net->addr_assign_type = NET_ADDR_RANDOM;
1778 
1779 	if ((dev->driver_info->flags & FLAG_WLAN) != 0)
1780 		SET_NETDEV_DEVTYPE(net, &wlan_type);
1781 	if ((dev->driver_info->flags & FLAG_WWAN) != 0)
1782 		SET_NETDEV_DEVTYPE(net, &wwan_type);
1783 
1784 	/* initialize max rx_qlen and tx_qlen */
1785 	usbnet_update_max_qlen(dev);
1786 
1787 	if (dev->can_dma_sg && !(info->flags & FLAG_SEND_ZLP) &&
1788 		!(info->flags & FLAG_MULTI_PACKET)) {
1789 		dev->padding_pkt = kzalloc(1, GFP_KERNEL);
1790 		if (!dev->padding_pkt) {
1791 			status = -ENOMEM;
1792 			goto out4;
1793 		}
1794 	}
1795 
1796 	status = register_netdev (net);
1797 	if (status)
1798 		goto out5;
1799 	netif_info(dev, probe, dev->net,
1800 		   "register '%s' at usb-%s-%s, %s, %pM\n",
1801 		   udev->dev.driver->name,
1802 		   xdev->bus->bus_name, xdev->devpath,
1803 		   dev->driver_info->description,
1804 		   net->dev_addr);
1805 
1806 	// ok, it's ready to go.
1807 	usb_set_intfdata (udev, dev);
1808 
1809 	netif_device_attach (net);
1810 
1811 	if (dev->driver_info->flags & FLAG_LINK_INTR)
1812 		usbnet_link_change(dev, 0, 0);
1813 
1814 	return 0;
1815 
1816 out5:
1817 	kfree(dev->padding_pkt);
1818 out4:
1819 	usb_free_urb(dev->interrupt);
1820 out3:
1821 	if (info->unbind)
1822 		info->unbind (dev, udev);
1823 out1:
1824 	/* subdrivers must undo all they did in bind() if they
1825 	 * fail it, but we may fail later and a deferred kevent
1826 	 * may trigger an error resubmitting itself and, worse,
1827 	 * schedule a timer. So we kill it all just in case.
1828 	 */
1829 	cancel_work_sync(&dev->kevent);
1830 	del_timer_sync(&dev->delay);
1831 	free_percpu(net->tstats);
1832 out0:
1833 	free_netdev(net);
1834 out:
1835 	return status;
1836 }
1837 EXPORT_SYMBOL_GPL(usbnet_probe);
1838 
1839 /*-------------------------------------------------------------------------*/
1840 
1841 /*
1842  * suspend the whole driver as soon as the first interface is suspended
1843  * resume only when the last interface is resumed
1844  */
1845 
1846 int usbnet_suspend (struct usb_interface *intf, pm_message_t message)
1847 {
1848 	struct usbnet		*dev = usb_get_intfdata(intf);
1849 
1850 	if (!dev->suspend_count++) {
1851 		spin_lock_irq(&dev->txq.lock);
1852 		/* don't autosuspend while transmitting */
1853 		if (dev->txq.qlen && PMSG_IS_AUTO(message)) {
1854 			dev->suspend_count--;
1855 			spin_unlock_irq(&dev->txq.lock);
1856 			return -EBUSY;
1857 		} else {
1858 			set_bit(EVENT_DEV_ASLEEP, &dev->flags);
1859 			spin_unlock_irq(&dev->txq.lock);
1860 		}
1861 		/*
1862 		 * accelerate emptying of the rx and queues, to avoid
1863 		 * having everything error out.
1864 		 */
1865 		netif_device_detach (dev->net);
1866 		usbnet_terminate_urbs(dev);
1867 		__usbnet_status_stop_force(dev);
1868 
1869 		/*
1870 		 * reattach so runtime management can use and
1871 		 * wake the device
1872 		 */
1873 		netif_device_attach (dev->net);
1874 	}
1875 	return 0;
1876 }
1877 EXPORT_SYMBOL_GPL(usbnet_suspend);
1878 
1879 int usbnet_resume (struct usb_interface *intf)
1880 {
1881 	struct usbnet		*dev = usb_get_intfdata(intf);
1882 	struct sk_buff          *skb;
1883 	struct urb              *res;
1884 	int                     retval;
1885 
1886 	if (!--dev->suspend_count) {
1887 		/* resume interrupt URB if it was previously submitted */
1888 		__usbnet_status_start_force(dev, GFP_NOIO);
1889 
1890 		spin_lock_irq(&dev->txq.lock);
1891 		while ((res = usb_get_from_anchor(&dev->deferred))) {
1892 
1893 			skb = (struct sk_buff *)res->context;
1894 			retval = usb_submit_urb(res, GFP_ATOMIC);
1895 			if (retval < 0) {
1896 				dev_kfree_skb_any(skb);
1897 				kfree(res->sg);
1898 				usb_free_urb(res);
1899 				usb_autopm_put_interface_async(dev->intf);
1900 			} else {
1901 				netif_trans_update(dev->net);
1902 				__skb_queue_tail(&dev->txq, skb);
1903 			}
1904 		}
1905 
1906 		smp_mb();
1907 		clear_bit(EVENT_DEV_ASLEEP, &dev->flags);
1908 		spin_unlock_irq(&dev->txq.lock);
1909 
1910 		if (test_bit(EVENT_DEV_OPEN, &dev->flags)) {
1911 			/* handle remote wakeup ASAP
1912 			 * we cannot race against stop
1913 			 */
1914 			if (netif_device_present(dev->net) &&
1915 				!timer_pending(&dev->delay) &&
1916 				!test_bit(EVENT_RX_HALT, &dev->flags))
1917 					rx_alloc_submit(dev, GFP_NOIO);
1918 
1919 			if (!(dev->txq.qlen >= TX_QLEN(dev)))
1920 				netif_tx_wake_all_queues(dev->net);
1921 			tasklet_schedule (&dev->bh);
1922 		}
1923 	}
1924 
1925 	if (test_and_clear_bit(EVENT_DEVICE_REPORT_IDLE, &dev->flags))
1926 		usb_autopm_get_interface_no_resume(intf);
1927 
1928 	return 0;
1929 }
1930 EXPORT_SYMBOL_GPL(usbnet_resume);
1931 
1932 /*
1933  * Either a subdriver implements manage_power, then it is assumed to always
1934  * be ready to be suspended or it reports the readiness to be suspended
1935  * explicitly
1936  */
1937 void usbnet_device_suggests_idle(struct usbnet *dev)
1938 {
1939 	if (!test_and_set_bit(EVENT_DEVICE_REPORT_IDLE, &dev->flags)) {
1940 		dev->intf->needs_remote_wakeup = 1;
1941 		usb_autopm_put_interface_async(dev->intf);
1942 	}
1943 }
1944 EXPORT_SYMBOL(usbnet_device_suggests_idle);
1945 
1946 /*
1947  * For devices that can do without special commands
1948  */
1949 int usbnet_manage_power(struct usbnet *dev, int on)
1950 {
1951 	dev->intf->needs_remote_wakeup = on;
1952 	return 0;
1953 }
1954 EXPORT_SYMBOL(usbnet_manage_power);
1955 
1956 void usbnet_link_change(struct usbnet *dev, bool link, bool need_reset)
1957 {
1958 	/* update link after link is reseted */
1959 	if (link && !need_reset)
1960 		netif_carrier_on(dev->net);
1961 	else
1962 		netif_carrier_off(dev->net);
1963 
1964 	if (need_reset && link)
1965 		usbnet_defer_kevent(dev, EVENT_LINK_RESET);
1966 	else
1967 		usbnet_defer_kevent(dev, EVENT_LINK_CHANGE);
1968 }
1969 EXPORT_SYMBOL(usbnet_link_change);
1970 
1971 /*-------------------------------------------------------------------------*/
1972 static int __usbnet_read_cmd(struct usbnet *dev, u8 cmd, u8 reqtype,
1973 			     u16 value, u16 index, void *data, u16 size)
1974 {
1975 	void *buf = NULL;
1976 	int err = -ENOMEM;
1977 
1978 	netdev_dbg(dev->net, "usbnet_read_cmd cmd=0x%02x reqtype=%02x"
1979 		   " value=0x%04x index=0x%04x size=%d\n",
1980 		   cmd, reqtype, value, index, size);
1981 
1982 	if (size) {
1983 		buf = kmalloc(size, GFP_KERNEL);
1984 		if (!buf)
1985 			goto out;
1986 	}
1987 
1988 	err = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
1989 			      cmd, reqtype, value, index, buf, size,
1990 			      USB_CTRL_GET_TIMEOUT);
1991 	if (err > 0 && err <= size) {
1992 		if (data)
1993 			memcpy(data, buf, err);
1994 		else
1995 			netdev_dbg(dev->net,
1996 				   "Huh? Data requested but thrown away.\n");
1997 	}
1998 	kfree(buf);
1999 out:
2000 	return err;
2001 }
2002 
2003 static int __usbnet_write_cmd(struct usbnet *dev, u8 cmd, u8 reqtype,
2004 			      u16 value, u16 index, const void *data,
2005 			      u16 size)
2006 {
2007 	void *buf = NULL;
2008 	int err = -ENOMEM;
2009 
2010 	netdev_dbg(dev->net, "usbnet_write_cmd cmd=0x%02x reqtype=%02x"
2011 		   " value=0x%04x index=0x%04x size=%d\n",
2012 		   cmd, reqtype, value, index, size);
2013 
2014 	if (data) {
2015 		buf = kmemdup(data, size, GFP_KERNEL);
2016 		if (!buf)
2017 			goto out;
2018 	} else {
2019         if (size) {
2020             WARN_ON_ONCE(1);
2021             err = -EINVAL;
2022             goto out;
2023         }
2024     }
2025 
2026 	err = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
2027 			      cmd, reqtype, value, index, buf, size,
2028 			      USB_CTRL_SET_TIMEOUT);
2029 	kfree(buf);
2030 
2031 out:
2032 	return err;
2033 }
2034 
2035 /*
2036  * The function can't be called inside suspend/resume callback,
2037  * otherwise deadlock will be caused.
2038  */
2039 int usbnet_read_cmd(struct usbnet *dev, u8 cmd, u8 reqtype,
2040 		    u16 value, u16 index, void *data, u16 size)
2041 {
2042 	int ret;
2043 
2044 	if (usb_autopm_get_interface(dev->intf) < 0)
2045 		return -ENODEV;
2046 	ret = __usbnet_read_cmd(dev, cmd, reqtype, value, index,
2047 				data, size);
2048 	usb_autopm_put_interface(dev->intf);
2049 	return ret;
2050 }
2051 EXPORT_SYMBOL_GPL(usbnet_read_cmd);
2052 
2053 /*
2054  * The function can't be called inside suspend/resume callback,
2055  * otherwise deadlock will be caused.
2056  */
2057 int usbnet_write_cmd(struct usbnet *dev, u8 cmd, u8 reqtype,
2058 		     u16 value, u16 index, const void *data, u16 size)
2059 {
2060 	int ret;
2061 
2062 	if (usb_autopm_get_interface(dev->intf) < 0)
2063 		return -ENODEV;
2064 	ret = __usbnet_write_cmd(dev, cmd, reqtype, value, index,
2065 				 data, size);
2066 	usb_autopm_put_interface(dev->intf);
2067 	return ret;
2068 }
2069 EXPORT_SYMBOL_GPL(usbnet_write_cmd);
2070 
2071 /*
2072  * The function can be called inside suspend/resume callback safely
2073  * and should only be called by suspend/resume callback generally.
2074  */
2075 int usbnet_read_cmd_nopm(struct usbnet *dev, u8 cmd, u8 reqtype,
2076 			  u16 value, u16 index, void *data, u16 size)
2077 {
2078 	return __usbnet_read_cmd(dev, cmd, reqtype, value, index,
2079 				 data, size);
2080 }
2081 EXPORT_SYMBOL_GPL(usbnet_read_cmd_nopm);
2082 
2083 /*
2084  * The function can be called inside suspend/resume callback safely
2085  * and should only be called by suspend/resume callback generally.
2086  */
2087 int usbnet_write_cmd_nopm(struct usbnet *dev, u8 cmd, u8 reqtype,
2088 			  u16 value, u16 index, const void *data,
2089 			  u16 size)
2090 {
2091 	return __usbnet_write_cmd(dev, cmd, reqtype, value, index,
2092 				  data, size);
2093 }
2094 EXPORT_SYMBOL_GPL(usbnet_write_cmd_nopm);
2095 
2096 static void usbnet_async_cmd_cb(struct urb *urb)
2097 {
2098 	struct usb_ctrlrequest *req = (struct usb_ctrlrequest *)urb->context;
2099 	int status = urb->status;
2100 
2101 	if (status < 0)
2102 		dev_dbg(&urb->dev->dev, "%s failed with %d",
2103 			__func__, status);
2104 
2105 	kfree(req);
2106 	usb_free_urb(urb);
2107 }
2108 
2109 /*
2110  * The caller must make sure that device can't be put into suspend
2111  * state until the control URB completes.
2112  */
2113 int usbnet_write_cmd_async(struct usbnet *dev, u8 cmd, u8 reqtype,
2114 			   u16 value, u16 index, const void *data, u16 size)
2115 {
2116 	struct usb_ctrlrequest *req = NULL;
2117 	struct urb *urb;
2118 	int err = -ENOMEM;
2119 	void *buf = NULL;
2120 
2121 	netdev_dbg(dev->net, "usbnet_write_cmd cmd=0x%02x reqtype=%02x"
2122 		   " value=0x%04x index=0x%04x size=%d\n",
2123 		   cmd, reqtype, value, index, size);
2124 
2125 	urb = usb_alloc_urb(0, GFP_ATOMIC);
2126 	if (!urb)
2127 		goto fail;
2128 
2129 	if (data) {
2130 		buf = kmemdup(data, size, GFP_ATOMIC);
2131 		if (!buf) {
2132 			netdev_err(dev->net, "Error allocating buffer"
2133 				   " in %s!\n", __func__);
2134 			goto fail_free;
2135 		}
2136 	}
2137 
2138 	req = kmalloc(sizeof(struct usb_ctrlrequest), GFP_ATOMIC);
2139 	if (!req)
2140 		goto fail_free_buf;
2141 
2142 	req->bRequestType = reqtype;
2143 	req->bRequest = cmd;
2144 	req->wValue = cpu_to_le16(value);
2145 	req->wIndex = cpu_to_le16(index);
2146 	req->wLength = cpu_to_le16(size);
2147 
2148 	usb_fill_control_urb(urb, dev->udev,
2149 			     usb_sndctrlpipe(dev->udev, 0),
2150 			     (void *)req, buf, size,
2151 			     usbnet_async_cmd_cb, req);
2152 	urb->transfer_flags |= URB_FREE_BUFFER;
2153 
2154 	err = usb_submit_urb(urb, GFP_ATOMIC);
2155 	if (err < 0) {
2156 		netdev_err(dev->net, "Error submitting the control"
2157 			   " message: status=%d\n", err);
2158 		goto fail_free;
2159 	}
2160 	return 0;
2161 
2162 fail_free_buf:
2163 	kfree(buf);
2164 fail_free:
2165 	kfree(req);
2166 	usb_free_urb(urb);
2167 fail:
2168 	return err;
2169 
2170 }
2171 EXPORT_SYMBOL_GPL(usbnet_write_cmd_async);
2172 /*-------------------------------------------------------------------------*/
2173 
2174 static int __init usbnet_init(void)
2175 {
2176 	/* Compiler should optimize this out. */
2177 	BUILD_BUG_ON(
2178 		sizeof_field(struct sk_buff, cb) < sizeof(struct skb_data));
2179 
2180 	eth_random_addr(node_id);
2181 	return 0;
2182 }
2183 module_init(usbnet_init);
2184 
2185 static void __exit usbnet_exit(void)
2186 {
2187 }
2188 module_exit(usbnet_exit);
2189 
2190 MODULE_AUTHOR("David Brownell");
2191 MODULE_DESCRIPTION("USB network driver framework");
2192 MODULE_LICENSE("GPL");
2193