xref: /linux/drivers/net/usb/usbnet.c (revision 0c8a32eed1625a65798286fb73fea8710a908545)
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_dbg(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 int usbnet_get_link_ksettings(struct net_device *net,
948 			      struct ethtool_link_ksettings *cmd)
949 {
950 	struct usbnet *dev = netdev_priv(net);
951 
952 	if (!dev->mii.mdio_read)
953 		return -EOPNOTSUPP;
954 
955 	mii_ethtool_get_link_ksettings(&dev->mii, cmd);
956 
957 	return 0;
958 }
959 EXPORT_SYMBOL_GPL(usbnet_get_link_ksettings);
960 
961 int usbnet_set_link_ksettings(struct net_device *net,
962 			      const struct ethtool_link_ksettings *cmd)
963 {
964 	struct usbnet *dev = netdev_priv(net);
965 	int retval;
966 
967 	if (!dev->mii.mdio_write)
968 		return -EOPNOTSUPP;
969 
970 	retval = mii_ethtool_set_link_ksettings(&dev->mii, cmd);
971 
972 	/* link speed/duplex might have changed */
973 	if (dev->driver_info->link_reset)
974 		dev->driver_info->link_reset(dev);
975 
976 	/* hard_mtu or rx_urb_size may change in link_reset() */
977 	usbnet_update_max_qlen(dev);
978 
979 	return retval;
980 }
981 EXPORT_SYMBOL_GPL(usbnet_set_link_ksettings);
982 
983 u32 usbnet_get_link (struct net_device *net)
984 {
985 	struct usbnet *dev = netdev_priv(net);
986 
987 	/* If a check_connect is defined, return its result */
988 	if (dev->driver_info->check_connect)
989 		return dev->driver_info->check_connect (dev) == 0;
990 
991 	/* if the device has mii operations, use those */
992 	if (dev->mii.mdio_read)
993 		return mii_link_ok(&dev->mii);
994 
995 	/* Otherwise, dtrt for drivers calling netif_carrier_{on,off} */
996 	return ethtool_op_get_link(net);
997 }
998 EXPORT_SYMBOL_GPL(usbnet_get_link);
999 
1000 int usbnet_nway_reset(struct net_device *net)
1001 {
1002 	struct usbnet *dev = netdev_priv(net);
1003 
1004 	if (!dev->mii.mdio_write)
1005 		return -EOPNOTSUPP;
1006 
1007 	return mii_nway_restart(&dev->mii);
1008 }
1009 EXPORT_SYMBOL_GPL(usbnet_nway_reset);
1010 
1011 void usbnet_get_drvinfo (struct net_device *net, struct ethtool_drvinfo *info)
1012 {
1013 	struct usbnet *dev = netdev_priv(net);
1014 
1015 	strlcpy (info->driver, dev->driver_name, sizeof info->driver);
1016 	strlcpy (info->fw_version, dev->driver_info->description,
1017 		sizeof info->fw_version);
1018 	usb_make_path (dev->udev, info->bus_info, sizeof info->bus_info);
1019 }
1020 EXPORT_SYMBOL_GPL(usbnet_get_drvinfo);
1021 
1022 u32 usbnet_get_msglevel (struct net_device *net)
1023 {
1024 	struct usbnet *dev = netdev_priv(net);
1025 
1026 	return dev->msg_enable;
1027 }
1028 EXPORT_SYMBOL_GPL(usbnet_get_msglevel);
1029 
1030 void usbnet_set_msglevel (struct net_device *net, u32 level)
1031 {
1032 	struct usbnet *dev = netdev_priv(net);
1033 
1034 	dev->msg_enable = level;
1035 }
1036 EXPORT_SYMBOL_GPL(usbnet_set_msglevel);
1037 
1038 /* drivers may override default ethtool_ops in their bind() routine */
1039 static const struct ethtool_ops usbnet_ethtool_ops = {
1040 	.get_link		= usbnet_get_link,
1041 	.nway_reset		= usbnet_nway_reset,
1042 	.get_drvinfo		= usbnet_get_drvinfo,
1043 	.get_msglevel		= usbnet_get_msglevel,
1044 	.set_msglevel		= usbnet_set_msglevel,
1045 	.get_ts_info		= ethtool_op_get_ts_info,
1046 	.get_link_ksettings	= usbnet_get_link_ksettings,
1047 	.set_link_ksettings	= usbnet_set_link_ksettings,
1048 };
1049 
1050 /*-------------------------------------------------------------------------*/
1051 
1052 static void __handle_link_change(struct usbnet *dev)
1053 {
1054 	if (!test_bit(EVENT_DEV_OPEN, &dev->flags))
1055 		return;
1056 
1057 	if (!netif_carrier_ok(dev->net)) {
1058 		/* kill URBs for reading packets to save bus bandwidth */
1059 		unlink_urbs(dev, &dev->rxq);
1060 
1061 		/*
1062 		 * tx_timeout will unlink URBs for sending packets and
1063 		 * tx queue is stopped by netcore after link becomes off
1064 		 */
1065 	} else {
1066 		/* submitting URBs for reading packets */
1067 		tasklet_schedule(&dev->bh);
1068 	}
1069 
1070 	/* hard_mtu or rx_urb_size may change during link change */
1071 	usbnet_update_max_qlen(dev);
1072 
1073 	clear_bit(EVENT_LINK_CHANGE, &dev->flags);
1074 }
1075 
1076 void usbnet_set_rx_mode(struct net_device *net)
1077 {
1078 	struct usbnet		*dev = netdev_priv(net);
1079 
1080 	usbnet_defer_kevent(dev, EVENT_SET_RX_MODE);
1081 }
1082 EXPORT_SYMBOL_GPL(usbnet_set_rx_mode);
1083 
1084 static void __handle_set_rx_mode(struct usbnet *dev)
1085 {
1086 	if (dev->driver_info->set_rx_mode)
1087 		(dev->driver_info->set_rx_mode)(dev);
1088 
1089 	clear_bit(EVENT_SET_RX_MODE, &dev->flags);
1090 }
1091 
1092 /* work that cannot be done in interrupt context uses keventd.
1093  *
1094  * NOTE:  with 2.5 we could do more of this using completion callbacks,
1095  * especially now that control transfers can be queued.
1096  */
1097 static void
1098 usbnet_deferred_kevent (struct work_struct *work)
1099 {
1100 	struct usbnet		*dev =
1101 		container_of(work, struct usbnet, kevent);
1102 	int			status;
1103 
1104 	/* usb_clear_halt() needs a thread context */
1105 	if (test_bit (EVENT_TX_HALT, &dev->flags)) {
1106 		unlink_urbs (dev, &dev->txq);
1107 		status = usb_autopm_get_interface(dev->intf);
1108 		if (status < 0)
1109 			goto fail_pipe;
1110 		status = usb_clear_halt (dev->udev, dev->out);
1111 		usb_autopm_put_interface(dev->intf);
1112 		if (status < 0 &&
1113 		    status != -EPIPE &&
1114 		    status != -ESHUTDOWN) {
1115 			if (netif_msg_tx_err (dev))
1116 fail_pipe:
1117 				netdev_err(dev->net, "can't clear tx halt, status %d\n",
1118 					   status);
1119 		} else {
1120 			clear_bit (EVENT_TX_HALT, &dev->flags);
1121 			if (status != -ESHUTDOWN)
1122 				netif_wake_queue (dev->net);
1123 		}
1124 	}
1125 	if (test_bit (EVENT_RX_HALT, &dev->flags)) {
1126 		unlink_urbs (dev, &dev->rxq);
1127 		status = usb_autopm_get_interface(dev->intf);
1128 		if (status < 0)
1129 			goto fail_halt;
1130 		status = usb_clear_halt (dev->udev, dev->in);
1131 		usb_autopm_put_interface(dev->intf);
1132 		if (status < 0 &&
1133 		    status != -EPIPE &&
1134 		    status != -ESHUTDOWN) {
1135 			if (netif_msg_rx_err (dev))
1136 fail_halt:
1137 				netdev_err(dev->net, "can't clear rx halt, status %d\n",
1138 					   status);
1139 		} else {
1140 			clear_bit (EVENT_RX_HALT, &dev->flags);
1141 			tasklet_schedule (&dev->bh);
1142 		}
1143 	}
1144 
1145 	/* tasklet could resubmit itself forever if memory is tight */
1146 	if (test_bit (EVENT_RX_MEMORY, &dev->flags)) {
1147 		struct urb	*urb = NULL;
1148 		int resched = 1;
1149 
1150 		if (netif_running (dev->net))
1151 			urb = usb_alloc_urb (0, GFP_KERNEL);
1152 		else
1153 			clear_bit (EVENT_RX_MEMORY, &dev->flags);
1154 		if (urb != NULL) {
1155 			clear_bit (EVENT_RX_MEMORY, &dev->flags);
1156 			status = usb_autopm_get_interface(dev->intf);
1157 			if (status < 0) {
1158 				usb_free_urb(urb);
1159 				goto fail_lowmem;
1160 			}
1161 			if (rx_submit (dev, urb, GFP_KERNEL) == -ENOLINK)
1162 				resched = 0;
1163 			usb_autopm_put_interface(dev->intf);
1164 fail_lowmem:
1165 			if (resched)
1166 				tasklet_schedule (&dev->bh);
1167 		}
1168 	}
1169 
1170 	if (test_bit (EVENT_LINK_RESET, &dev->flags)) {
1171 		const struct driver_info *info = dev->driver_info;
1172 		int			retval = 0;
1173 
1174 		clear_bit (EVENT_LINK_RESET, &dev->flags);
1175 		status = usb_autopm_get_interface(dev->intf);
1176 		if (status < 0)
1177 			goto skip_reset;
1178 		if(info->link_reset && (retval = info->link_reset(dev)) < 0) {
1179 			usb_autopm_put_interface(dev->intf);
1180 skip_reset:
1181 			netdev_info(dev->net, "link reset failed (%d) usbnet usb-%s-%s, %s\n",
1182 				    retval,
1183 				    dev->udev->bus->bus_name,
1184 				    dev->udev->devpath,
1185 				    info->description);
1186 		} else {
1187 			usb_autopm_put_interface(dev->intf);
1188 		}
1189 
1190 		/* handle link change from link resetting */
1191 		__handle_link_change(dev);
1192 	}
1193 
1194 	if (test_bit (EVENT_LINK_CHANGE, &dev->flags))
1195 		__handle_link_change(dev);
1196 
1197 	if (test_bit (EVENT_SET_RX_MODE, &dev->flags))
1198 		__handle_set_rx_mode(dev);
1199 
1200 
1201 	if (dev->flags)
1202 		netdev_dbg(dev->net, "kevent done, flags = 0x%lx\n", dev->flags);
1203 }
1204 
1205 /*-------------------------------------------------------------------------*/
1206 
1207 static void tx_complete (struct urb *urb)
1208 {
1209 	struct sk_buff		*skb = (struct sk_buff *) urb->context;
1210 	struct skb_data		*entry = (struct skb_data *) skb->cb;
1211 	struct usbnet		*dev = entry->dev;
1212 
1213 	if (urb->status == 0) {
1214 		struct pcpu_sw_netstats *stats64 = this_cpu_ptr(dev->net->tstats);
1215 		unsigned long flags;
1216 
1217 		flags = u64_stats_update_begin_irqsave(&stats64->syncp);
1218 		stats64->tx_packets += entry->packets;
1219 		stats64->tx_bytes += entry->length;
1220 		u64_stats_update_end_irqrestore(&stats64->syncp, flags);
1221 	} else {
1222 		dev->net->stats.tx_errors++;
1223 
1224 		switch (urb->status) {
1225 		case -EPIPE:
1226 			usbnet_defer_kevent (dev, EVENT_TX_HALT);
1227 			break;
1228 
1229 		/* software-driven interface shutdown */
1230 		case -ECONNRESET:		// async unlink
1231 		case -ESHUTDOWN:		// hardware gone
1232 			break;
1233 
1234 		/* like rx, tx gets controller i/o faults during hub_wq
1235 		 * delays and so it uses the same throttling mechanism.
1236 		 */
1237 		case -EPROTO:
1238 		case -ETIME:
1239 		case -EILSEQ:
1240 			usb_mark_last_busy(dev->udev);
1241 			if (!timer_pending (&dev->delay)) {
1242 				mod_timer (&dev->delay,
1243 					jiffies + THROTTLE_JIFFIES);
1244 				netif_dbg(dev, link, dev->net,
1245 					  "tx throttle %d\n", urb->status);
1246 			}
1247 			netif_stop_queue (dev->net);
1248 			break;
1249 		default:
1250 			netif_dbg(dev, tx_err, dev->net,
1251 				  "tx err %d\n", entry->urb->status);
1252 			break;
1253 		}
1254 	}
1255 
1256 	usb_autopm_put_interface_async(dev->intf);
1257 	(void) defer_bh(dev, skb, &dev->txq, tx_done);
1258 }
1259 
1260 /*-------------------------------------------------------------------------*/
1261 
1262 void usbnet_tx_timeout (struct net_device *net, unsigned int txqueue)
1263 {
1264 	struct usbnet		*dev = netdev_priv(net);
1265 
1266 	unlink_urbs (dev, &dev->txq);
1267 	tasklet_schedule (&dev->bh);
1268 	/* this needs to be handled individually because the generic layer
1269 	 * doesn't know what is sufficient and could not restore private
1270 	 * information if a remedy of an unconditional reset were used.
1271 	 */
1272 	if (dev->driver_info->recover)
1273 		(dev->driver_info->recover)(dev);
1274 }
1275 EXPORT_SYMBOL_GPL(usbnet_tx_timeout);
1276 
1277 /*-------------------------------------------------------------------------*/
1278 
1279 static int build_dma_sg(const struct sk_buff *skb, struct urb *urb)
1280 {
1281 	unsigned num_sgs, total_len = 0;
1282 	int i, s = 0;
1283 
1284 	num_sgs = skb_shinfo(skb)->nr_frags + 1;
1285 	if (num_sgs == 1)
1286 		return 0;
1287 
1288 	/* reserve one for zero packet */
1289 	urb->sg = kmalloc_array(num_sgs + 1, sizeof(struct scatterlist),
1290 				GFP_ATOMIC);
1291 	if (!urb->sg)
1292 		return -ENOMEM;
1293 
1294 	urb->num_sgs = num_sgs;
1295 	sg_init_table(urb->sg, urb->num_sgs + 1);
1296 
1297 	sg_set_buf(&urb->sg[s++], skb->data, skb_headlen(skb));
1298 	total_len += skb_headlen(skb);
1299 
1300 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1301 		skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1302 
1303 		total_len += skb_frag_size(f);
1304 		sg_set_page(&urb->sg[i + s], skb_frag_page(f), skb_frag_size(f),
1305 			    skb_frag_off(f));
1306 	}
1307 	urb->transfer_buffer_length = total_len;
1308 
1309 	return 1;
1310 }
1311 
1312 netdev_tx_t usbnet_start_xmit (struct sk_buff *skb,
1313 				     struct net_device *net)
1314 {
1315 	struct usbnet		*dev = netdev_priv(net);
1316 	unsigned int			length;
1317 	struct urb		*urb = NULL;
1318 	struct skb_data		*entry;
1319 	const struct driver_info *info = dev->driver_info;
1320 	unsigned long		flags;
1321 	int retval;
1322 
1323 	if (skb)
1324 		skb_tx_timestamp(skb);
1325 
1326 	// some devices want funky USB-level framing, for
1327 	// win32 driver (usually) and/or hardware quirks
1328 	if (info->tx_fixup) {
1329 		skb = info->tx_fixup (dev, skb, GFP_ATOMIC);
1330 		if (!skb) {
1331 			/* packet collected; minidriver waiting for more */
1332 			if (info->flags & FLAG_MULTI_PACKET)
1333 				goto not_drop;
1334 			netif_dbg(dev, tx_err, dev->net, "can't tx_fixup skb\n");
1335 			goto drop;
1336 		}
1337 	}
1338 
1339 	if (!(urb = usb_alloc_urb (0, GFP_ATOMIC))) {
1340 		netif_dbg(dev, tx_err, dev->net, "no urb\n");
1341 		goto drop;
1342 	}
1343 
1344 	entry = (struct skb_data *) skb->cb;
1345 	entry->urb = urb;
1346 	entry->dev = dev;
1347 
1348 	usb_fill_bulk_urb (urb, dev->udev, dev->out,
1349 			skb->data, skb->len, tx_complete, skb);
1350 	if (dev->can_dma_sg) {
1351 		if (build_dma_sg(skb, urb) < 0)
1352 			goto drop;
1353 	}
1354 	length = urb->transfer_buffer_length;
1355 
1356 	/* don't assume the hardware handles USB_ZERO_PACKET
1357 	 * NOTE:  strictly conforming cdc-ether devices should expect
1358 	 * the ZLP here, but ignore the one-byte packet.
1359 	 * NOTE2: CDC NCM specification is different from CDC ECM when
1360 	 * handling ZLP/short packets, so cdc_ncm driver will make short
1361 	 * packet itself if needed.
1362 	 */
1363 	if (length % dev->maxpacket == 0) {
1364 		if (!(info->flags & FLAG_SEND_ZLP)) {
1365 			if (!(info->flags & FLAG_MULTI_PACKET)) {
1366 				length++;
1367 				if (skb_tailroom(skb) && !urb->num_sgs) {
1368 					skb->data[skb->len] = 0;
1369 					__skb_put(skb, 1);
1370 				} else if (urb->num_sgs)
1371 					sg_set_buf(&urb->sg[urb->num_sgs++],
1372 							dev->padding_pkt, 1);
1373 			}
1374 		} else
1375 			urb->transfer_flags |= URB_ZERO_PACKET;
1376 	}
1377 	urb->transfer_buffer_length = length;
1378 
1379 	if (info->flags & FLAG_MULTI_PACKET) {
1380 		/* Driver has set number of packets and a length delta.
1381 		 * Calculate the complete length and ensure that it's
1382 		 * positive.
1383 		 */
1384 		entry->length += length;
1385 		if (WARN_ON_ONCE(entry->length <= 0))
1386 			entry->length = length;
1387 	} else {
1388 		usbnet_set_skb_tx_stats(skb, 1, length);
1389 	}
1390 
1391 	spin_lock_irqsave(&dev->txq.lock, flags);
1392 	retval = usb_autopm_get_interface_async(dev->intf);
1393 	if (retval < 0) {
1394 		spin_unlock_irqrestore(&dev->txq.lock, flags);
1395 		goto drop;
1396 	}
1397 	if (netif_queue_stopped(net)) {
1398 		usb_autopm_put_interface_async(dev->intf);
1399 		spin_unlock_irqrestore(&dev->txq.lock, flags);
1400 		goto drop;
1401 	}
1402 
1403 #ifdef CONFIG_PM
1404 	/* if this triggers the device is still a sleep */
1405 	if (test_bit(EVENT_DEV_ASLEEP, &dev->flags)) {
1406 		/* transmission will be done in resume */
1407 		usb_anchor_urb(urb, &dev->deferred);
1408 		/* no use to process more packets */
1409 		netif_stop_queue(net);
1410 		usb_put_urb(urb);
1411 		spin_unlock_irqrestore(&dev->txq.lock, flags);
1412 		netdev_dbg(dev->net, "Delaying transmission for resumption\n");
1413 		goto deferred;
1414 	}
1415 #endif
1416 
1417 	switch ((retval = usb_submit_urb (urb, GFP_ATOMIC))) {
1418 	case -EPIPE:
1419 		netif_stop_queue (net);
1420 		usbnet_defer_kevent (dev, EVENT_TX_HALT);
1421 		usb_autopm_put_interface_async(dev->intf);
1422 		break;
1423 	default:
1424 		usb_autopm_put_interface_async(dev->intf);
1425 		netif_dbg(dev, tx_err, dev->net,
1426 			  "tx: submit urb err %d\n", retval);
1427 		break;
1428 	case 0:
1429 		netif_trans_update(net);
1430 		__usbnet_queue_skb(&dev->txq, skb, tx_start);
1431 		if (dev->txq.qlen >= TX_QLEN (dev))
1432 			netif_stop_queue (net);
1433 	}
1434 	spin_unlock_irqrestore (&dev->txq.lock, flags);
1435 
1436 	if (retval) {
1437 		netif_dbg(dev, tx_err, dev->net, "drop, code %d\n", retval);
1438 drop:
1439 		dev->net->stats.tx_dropped++;
1440 not_drop:
1441 		if (skb)
1442 			dev_kfree_skb_any (skb);
1443 		if (urb) {
1444 			kfree(urb->sg);
1445 			usb_free_urb(urb);
1446 		}
1447 	} else
1448 		netif_dbg(dev, tx_queued, dev->net,
1449 			  "> tx, len %u, type 0x%x\n", length, skb->protocol);
1450 #ifdef CONFIG_PM
1451 deferred:
1452 #endif
1453 	return NETDEV_TX_OK;
1454 }
1455 EXPORT_SYMBOL_GPL(usbnet_start_xmit);
1456 
1457 static int rx_alloc_submit(struct usbnet *dev, gfp_t flags)
1458 {
1459 	struct urb	*urb;
1460 	int		i;
1461 	int		ret = 0;
1462 
1463 	/* don't refill the queue all at once */
1464 	for (i = 0; i < 10 && dev->rxq.qlen < RX_QLEN(dev); i++) {
1465 		urb = usb_alloc_urb(0, flags);
1466 		if (urb != NULL) {
1467 			ret = rx_submit(dev, urb, flags);
1468 			if (ret)
1469 				goto err;
1470 		} else {
1471 			ret = -ENOMEM;
1472 			goto err;
1473 		}
1474 	}
1475 err:
1476 	return ret;
1477 }
1478 
1479 /*-------------------------------------------------------------------------*/
1480 
1481 // tasklet (work deferred from completions, in_irq) or timer
1482 
1483 static void usbnet_bh (struct timer_list *t)
1484 {
1485 	struct usbnet		*dev = from_timer(dev, t, delay);
1486 	struct sk_buff		*skb;
1487 	struct skb_data		*entry;
1488 
1489 	while ((skb = skb_dequeue (&dev->done))) {
1490 		entry = (struct skb_data *) skb->cb;
1491 		switch (entry->state) {
1492 		case rx_done:
1493 			entry->state = rx_cleanup;
1494 			rx_process (dev, skb);
1495 			continue;
1496 		case tx_done:
1497 			kfree(entry->urb->sg);
1498 			fallthrough;
1499 		case rx_cleanup:
1500 			usb_free_urb (entry->urb);
1501 			dev_kfree_skb (skb);
1502 			continue;
1503 		default:
1504 			netdev_dbg(dev->net, "bogus skb state %d\n", entry->state);
1505 		}
1506 	}
1507 
1508 	/* restart RX again after disabling due to high error rate */
1509 	clear_bit(EVENT_RX_KILL, &dev->flags);
1510 
1511 	/* waiting for all pending urbs to complete?
1512 	 * only then can we forgo submitting anew
1513 	 */
1514 	if (waitqueue_active(&dev->wait)) {
1515 		if (dev->txq.qlen + dev->rxq.qlen + dev->done.qlen == 0)
1516 			wake_up_all(&dev->wait);
1517 
1518 	// or are we maybe short a few urbs?
1519 	} else if (netif_running (dev->net) &&
1520 		   netif_device_present (dev->net) &&
1521 		   netif_carrier_ok(dev->net) &&
1522 		   !timer_pending(&dev->delay) &&
1523 		   !test_bit(EVENT_RX_PAUSED, &dev->flags) &&
1524 		   !test_bit(EVENT_RX_HALT, &dev->flags)) {
1525 		int	temp = dev->rxq.qlen;
1526 
1527 		if (temp < RX_QLEN(dev)) {
1528 			if (rx_alloc_submit(dev, GFP_ATOMIC) == -ENOLINK)
1529 				return;
1530 			if (temp != dev->rxq.qlen)
1531 				netif_dbg(dev, link, dev->net,
1532 					  "rxqlen %d --> %d\n",
1533 					  temp, dev->rxq.qlen);
1534 			if (dev->rxq.qlen < RX_QLEN(dev))
1535 				tasklet_schedule (&dev->bh);
1536 		}
1537 		if (dev->txq.qlen < TX_QLEN (dev))
1538 			netif_wake_queue (dev->net);
1539 	}
1540 }
1541 
1542 static void usbnet_bh_tasklet(unsigned long data)
1543 {
1544 	struct timer_list *t = (struct timer_list *)data;
1545 
1546 	usbnet_bh(t);
1547 }
1548 
1549 
1550 /*-------------------------------------------------------------------------
1551  *
1552  * USB Device Driver support
1553  *
1554  *-------------------------------------------------------------------------*/
1555 
1556 // precondition: never called in_interrupt
1557 
1558 void usbnet_disconnect (struct usb_interface *intf)
1559 {
1560 	struct usbnet		*dev;
1561 	struct usb_device	*xdev;
1562 	struct net_device	*net;
1563 
1564 	dev = usb_get_intfdata(intf);
1565 	usb_set_intfdata(intf, NULL);
1566 	if (!dev)
1567 		return;
1568 
1569 	xdev = interface_to_usbdev (intf);
1570 
1571 	netif_info(dev, probe, dev->net, "unregister '%s' usb-%s-%s, %s\n",
1572 		   intf->dev.driver->name,
1573 		   xdev->bus->bus_name, xdev->devpath,
1574 		   dev->driver_info->description);
1575 
1576 	net = dev->net;
1577 	unregister_netdev (net);
1578 
1579 	cancel_work_sync(&dev->kevent);
1580 
1581 	usb_scuttle_anchored_urbs(&dev->deferred);
1582 
1583 	if (dev->driver_info->unbind)
1584 		dev->driver_info->unbind (dev, intf);
1585 
1586 	usb_kill_urb(dev->interrupt);
1587 	usb_free_urb(dev->interrupt);
1588 	kfree(dev->padding_pkt);
1589 
1590 	free_percpu(net->tstats);
1591 	free_netdev(net);
1592 }
1593 EXPORT_SYMBOL_GPL(usbnet_disconnect);
1594 
1595 static const struct net_device_ops usbnet_netdev_ops = {
1596 	.ndo_open		= usbnet_open,
1597 	.ndo_stop		= usbnet_stop,
1598 	.ndo_start_xmit		= usbnet_start_xmit,
1599 	.ndo_tx_timeout		= usbnet_tx_timeout,
1600 	.ndo_set_rx_mode	= usbnet_set_rx_mode,
1601 	.ndo_change_mtu		= usbnet_change_mtu,
1602 	.ndo_get_stats64	= dev_get_tstats64,
1603 	.ndo_set_mac_address 	= eth_mac_addr,
1604 	.ndo_validate_addr	= eth_validate_addr,
1605 };
1606 
1607 /*-------------------------------------------------------------------------*/
1608 
1609 // precondition: never called in_interrupt
1610 
1611 static struct device_type wlan_type = {
1612 	.name	= "wlan",
1613 };
1614 
1615 static struct device_type wwan_type = {
1616 	.name	= "wwan",
1617 };
1618 
1619 int
1620 usbnet_probe (struct usb_interface *udev, const struct usb_device_id *prod)
1621 {
1622 	struct usbnet			*dev;
1623 	struct net_device		*net;
1624 	struct usb_host_interface	*interface;
1625 	const struct driver_info	*info;
1626 	struct usb_device		*xdev;
1627 	int				status;
1628 	const char			*name;
1629 	struct usb_driver 	*driver = to_usb_driver(udev->dev.driver);
1630 
1631 	/* usbnet already took usb runtime pm, so have to enable the feature
1632 	 * for usb interface, otherwise usb_autopm_get_interface may return
1633 	 * failure if RUNTIME_PM is enabled.
1634 	 */
1635 	if (!driver->supports_autosuspend) {
1636 		driver->supports_autosuspend = 1;
1637 		pm_runtime_enable(&udev->dev);
1638 	}
1639 
1640 	name = udev->dev.driver->name;
1641 	info = (const struct driver_info *) prod->driver_info;
1642 	if (!info) {
1643 		dev_dbg (&udev->dev, "blacklisted by %s\n", name);
1644 		return -ENODEV;
1645 	}
1646 	xdev = interface_to_usbdev (udev);
1647 	interface = udev->cur_altsetting;
1648 
1649 	status = -ENOMEM;
1650 
1651 	// set up our own records
1652 	net = alloc_etherdev(sizeof(*dev));
1653 	if (!net)
1654 		goto out;
1655 
1656 	/* netdev_printk() needs this so do it as early as possible */
1657 	SET_NETDEV_DEV(net, &udev->dev);
1658 
1659 	dev = netdev_priv(net);
1660 	dev->udev = xdev;
1661 	dev->intf = udev;
1662 	dev->driver_info = info;
1663 	dev->driver_name = name;
1664 
1665 	net->tstats = netdev_alloc_pcpu_stats(struct pcpu_sw_netstats);
1666 	if (!net->tstats)
1667 		goto out0;
1668 
1669 	dev->msg_enable = netif_msg_init (msg_level, NETIF_MSG_DRV
1670 				| NETIF_MSG_PROBE | NETIF_MSG_LINK);
1671 	init_waitqueue_head(&dev->wait);
1672 	skb_queue_head_init (&dev->rxq);
1673 	skb_queue_head_init (&dev->txq);
1674 	skb_queue_head_init (&dev->done);
1675 	skb_queue_head_init(&dev->rxq_pause);
1676 	dev->bh.func = usbnet_bh_tasklet;
1677 	dev->bh.data = (unsigned long)&dev->delay;
1678 	INIT_WORK (&dev->kevent, usbnet_deferred_kevent);
1679 	init_usb_anchor(&dev->deferred);
1680 	timer_setup(&dev->delay, usbnet_bh, 0);
1681 	mutex_init (&dev->phy_mutex);
1682 	mutex_init(&dev->interrupt_mutex);
1683 	dev->interrupt_count = 0;
1684 
1685 	dev->net = net;
1686 	strcpy (net->name, "usb%d");
1687 	memcpy (net->dev_addr, node_id, sizeof node_id);
1688 
1689 	/* rx and tx sides can use different message sizes;
1690 	 * bind() should set rx_urb_size in that case.
1691 	 */
1692 	dev->hard_mtu = net->mtu + net->hard_header_len;
1693 	net->min_mtu = 0;
1694 	net->max_mtu = ETH_MAX_MTU;
1695 
1696 	net->netdev_ops = &usbnet_netdev_ops;
1697 	net->watchdog_timeo = TX_TIMEOUT_JIFFIES;
1698 	net->ethtool_ops = &usbnet_ethtool_ops;
1699 
1700 	// allow device-specific bind/init procedures
1701 	// NOTE net->name still not usable ...
1702 	if (info->bind) {
1703 		status = info->bind (dev, udev);
1704 		if (status < 0)
1705 			goto out1;
1706 
1707 		// heuristic:  "usb%d" for links we know are two-host,
1708 		// else "eth%d" when there's reasonable doubt.  userspace
1709 		// can rename the link if it knows better.
1710 		if ((dev->driver_info->flags & FLAG_ETHER) != 0 &&
1711 		    ((dev->driver_info->flags & FLAG_POINTTOPOINT) == 0 ||
1712 		     (net->dev_addr [0] & 0x02) == 0))
1713 			strcpy (net->name, "eth%d");
1714 		/* WLAN devices should always be named "wlan%d" */
1715 		if ((dev->driver_info->flags & FLAG_WLAN) != 0)
1716 			strcpy(net->name, "wlan%d");
1717 		/* WWAN devices should always be named "wwan%d" */
1718 		if ((dev->driver_info->flags & FLAG_WWAN) != 0)
1719 			strcpy(net->name, "wwan%d");
1720 
1721 		/* devices that cannot do ARP */
1722 		if ((dev->driver_info->flags & FLAG_NOARP) != 0)
1723 			net->flags |= IFF_NOARP;
1724 
1725 		/* maybe the remote can't receive an Ethernet MTU */
1726 		if (net->mtu > (dev->hard_mtu - net->hard_header_len))
1727 			net->mtu = dev->hard_mtu - net->hard_header_len;
1728 	} else if (!info->in || !info->out)
1729 		status = usbnet_get_endpoints (dev, udev);
1730 	else {
1731 		dev->in = usb_rcvbulkpipe (xdev, info->in);
1732 		dev->out = usb_sndbulkpipe (xdev, info->out);
1733 		if (!(info->flags & FLAG_NO_SETINT))
1734 			status = usb_set_interface (xdev,
1735 				interface->desc.bInterfaceNumber,
1736 				interface->desc.bAlternateSetting);
1737 		else
1738 			status = 0;
1739 
1740 	}
1741 	if (status >= 0 && dev->status)
1742 		status = init_status (dev, udev);
1743 	if (status < 0)
1744 		goto out3;
1745 
1746 	if (!dev->rx_urb_size)
1747 		dev->rx_urb_size = dev->hard_mtu;
1748 	dev->maxpacket = usb_maxpacket (dev->udev, dev->out, 1);
1749 
1750 	/* let userspace know we have a random address */
1751 	if (ether_addr_equal(net->dev_addr, node_id))
1752 		net->addr_assign_type = NET_ADDR_RANDOM;
1753 
1754 	if ((dev->driver_info->flags & FLAG_WLAN) != 0)
1755 		SET_NETDEV_DEVTYPE(net, &wlan_type);
1756 	if ((dev->driver_info->flags & FLAG_WWAN) != 0)
1757 		SET_NETDEV_DEVTYPE(net, &wwan_type);
1758 
1759 	/* initialize max rx_qlen and tx_qlen */
1760 	usbnet_update_max_qlen(dev);
1761 
1762 	if (dev->can_dma_sg && !(info->flags & FLAG_SEND_ZLP) &&
1763 		!(info->flags & FLAG_MULTI_PACKET)) {
1764 		dev->padding_pkt = kzalloc(1, GFP_KERNEL);
1765 		if (!dev->padding_pkt) {
1766 			status = -ENOMEM;
1767 			goto out4;
1768 		}
1769 	}
1770 
1771 	status = register_netdev (net);
1772 	if (status)
1773 		goto out5;
1774 	netif_info(dev, probe, dev->net,
1775 		   "register '%s' at usb-%s-%s, %s, %pM\n",
1776 		   udev->dev.driver->name,
1777 		   xdev->bus->bus_name, xdev->devpath,
1778 		   dev->driver_info->description,
1779 		   net->dev_addr);
1780 
1781 	// ok, it's ready to go.
1782 	usb_set_intfdata (udev, dev);
1783 
1784 	netif_device_attach (net);
1785 
1786 	if (dev->driver_info->flags & FLAG_LINK_INTR)
1787 		usbnet_link_change(dev, 0, 0);
1788 
1789 	return 0;
1790 
1791 out5:
1792 	kfree(dev->padding_pkt);
1793 out4:
1794 	usb_free_urb(dev->interrupt);
1795 out3:
1796 	if (info->unbind)
1797 		info->unbind (dev, udev);
1798 out1:
1799 	/* subdrivers must undo all they did in bind() if they
1800 	 * fail it, but we may fail later and a deferred kevent
1801 	 * may trigger an error resubmitting itself and, worse,
1802 	 * schedule a timer. So we kill it all just in case.
1803 	 */
1804 	cancel_work_sync(&dev->kevent);
1805 	del_timer_sync(&dev->delay);
1806 	free_percpu(net->tstats);
1807 out0:
1808 	free_netdev(net);
1809 out:
1810 	return status;
1811 }
1812 EXPORT_SYMBOL_GPL(usbnet_probe);
1813 
1814 /*-------------------------------------------------------------------------*/
1815 
1816 /*
1817  * suspend the whole driver as soon as the first interface is suspended
1818  * resume only when the last interface is resumed
1819  */
1820 
1821 int usbnet_suspend (struct usb_interface *intf, pm_message_t message)
1822 {
1823 	struct usbnet		*dev = usb_get_intfdata(intf);
1824 
1825 	if (!dev->suspend_count++) {
1826 		spin_lock_irq(&dev->txq.lock);
1827 		/* don't autosuspend while transmitting */
1828 		if (dev->txq.qlen && PMSG_IS_AUTO(message)) {
1829 			dev->suspend_count--;
1830 			spin_unlock_irq(&dev->txq.lock);
1831 			return -EBUSY;
1832 		} else {
1833 			set_bit(EVENT_DEV_ASLEEP, &dev->flags);
1834 			spin_unlock_irq(&dev->txq.lock);
1835 		}
1836 		/*
1837 		 * accelerate emptying of the rx and queues, to avoid
1838 		 * having everything error out.
1839 		 */
1840 		netif_device_detach (dev->net);
1841 		usbnet_terminate_urbs(dev);
1842 		__usbnet_status_stop_force(dev);
1843 
1844 		/*
1845 		 * reattach so runtime management can use and
1846 		 * wake the device
1847 		 */
1848 		netif_device_attach (dev->net);
1849 	}
1850 	return 0;
1851 }
1852 EXPORT_SYMBOL_GPL(usbnet_suspend);
1853 
1854 int usbnet_resume (struct usb_interface *intf)
1855 {
1856 	struct usbnet		*dev = usb_get_intfdata(intf);
1857 	struct sk_buff          *skb;
1858 	struct urb              *res;
1859 	int                     retval;
1860 
1861 	if (!--dev->suspend_count) {
1862 		/* resume interrupt URB if it was previously submitted */
1863 		__usbnet_status_start_force(dev, GFP_NOIO);
1864 
1865 		spin_lock_irq(&dev->txq.lock);
1866 		while ((res = usb_get_from_anchor(&dev->deferred))) {
1867 
1868 			skb = (struct sk_buff *)res->context;
1869 			retval = usb_submit_urb(res, GFP_ATOMIC);
1870 			if (retval < 0) {
1871 				dev_kfree_skb_any(skb);
1872 				kfree(res->sg);
1873 				usb_free_urb(res);
1874 				usb_autopm_put_interface_async(dev->intf);
1875 			} else {
1876 				netif_trans_update(dev->net);
1877 				__skb_queue_tail(&dev->txq, skb);
1878 			}
1879 		}
1880 
1881 		smp_mb();
1882 		clear_bit(EVENT_DEV_ASLEEP, &dev->flags);
1883 		spin_unlock_irq(&dev->txq.lock);
1884 
1885 		if (test_bit(EVENT_DEV_OPEN, &dev->flags)) {
1886 			/* handle remote wakeup ASAP
1887 			 * we cannot race against stop
1888 			 */
1889 			if (netif_device_present(dev->net) &&
1890 				!timer_pending(&dev->delay) &&
1891 				!test_bit(EVENT_RX_HALT, &dev->flags))
1892 					rx_alloc_submit(dev, GFP_NOIO);
1893 
1894 			if (!(dev->txq.qlen >= TX_QLEN(dev)))
1895 				netif_tx_wake_all_queues(dev->net);
1896 			tasklet_schedule (&dev->bh);
1897 		}
1898 	}
1899 
1900 	if (test_and_clear_bit(EVENT_DEVICE_REPORT_IDLE, &dev->flags))
1901 		usb_autopm_get_interface_no_resume(intf);
1902 
1903 	return 0;
1904 }
1905 EXPORT_SYMBOL_GPL(usbnet_resume);
1906 
1907 /*
1908  * Either a subdriver implements manage_power, then it is assumed to always
1909  * be ready to be suspended or it reports the readiness to be suspended
1910  * explicitly
1911  */
1912 void usbnet_device_suggests_idle(struct usbnet *dev)
1913 {
1914 	if (!test_and_set_bit(EVENT_DEVICE_REPORT_IDLE, &dev->flags)) {
1915 		dev->intf->needs_remote_wakeup = 1;
1916 		usb_autopm_put_interface_async(dev->intf);
1917 	}
1918 }
1919 EXPORT_SYMBOL(usbnet_device_suggests_idle);
1920 
1921 /*
1922  * For devices that can do without special commands
1923  */
1924 int usbnet_manage_power(struct usbnet *dev, int on)
1925 {
1926 	dev->intf->needs_remote_wakeup = on;
1927 	return 0;
1928 }
1929 EXPORT_SYMBOL(usbnet_manage_power);
1930 
1931 void usbnet_link_change(struct usbnet *dev, bool link, bool need_reset)
1932 {
1933 	/* update link after link is reseted */
1934 	if (link && !need_reset)
1935 		netif_carrier_on(dev->net);
1936 	else
1937 		netif_carrier_off(dev->net);
1938 
1939 	if (need_reset && link)
1940 		usbnet_defer_kevent(dev, EVENT_LINK_RESET);
1941 	else
1942 		usbnet_defer_kevent(dev, EVENT_LINK_CHANGE);
1943 }
1944 EXPORT_SYMBOL(usbnet_link_change);
1945 
1946 /*-------------------------------------------------------------------------*/
1947 static int __usbnet_read_cmd(struct usbnet *dev, u8 cmd, u8 reqtype,
1948 			     u16 value, u16 index, void *data, u16 size)
1949 {
1950 	void *buf = NULL;
1951 	int err = -ENOMEM;
1952 
1953 	netdev_dbg(dev->net, "usbnet_read_cmd cmd=0x%02x reqtype=%02x"
1954 		   " value=0x%04x index=0x%04x size=%d\n",
1955 		   cmd, reqtype, value, index, size);
1956 
1957 	if (size) {
1958 		buf = kmalloc(size, GFP_KERNEL);
1959 		if (!buf)
1960 			goto out;
1961 	}
1962 
1963 	err = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
1964 			      cmd, reqtype, value, index, buf, size,
1965 			      USB_CTRL_GET_TIMEOUT);
1966 	if (err > 0 && err <= size) {
1967         if (data)
1968             memcpy(data, buf, err);
1969         else
1970             netdev_dbg(dev->net,
1971                 "Huh? Data requested but thrown away.\n");
1972     }
1973 	kfree(buf);
1974 out:
1975 	return err;
1976 }
1977 
1978 static int __usbnet_write_cmd(struct usbnet *dev, u8 cmd, u8 reqtype,
1979 			      u16 value, u16 index, const void *data,
1980 			      u16 size)
1981 {
1982 	void *buf = NULL;
1983 	int err = -ENOMEM;
1984 
1985 	netdev_dbg(dev->net, "usbnet_write_cmd cmd=0x%02x reqtype=%02x"
1986 		   " value=0x%04x index=0x%04x size=%d\n",
1987 		   cmd, reqtype, value, index, size);
1988 
1989 	if (data) {
1990 		buf = kmemdup(data, size, GFP_KERNEL);
1991 		if (!buf)
1992 			goto out;
1993 	} else {
1994         if (size) {
1995             WARN_ON_ONCE(1);
1996             err = -EINVAL;
1997             goto out;
1998         }
1999     }
2000 
2001 	err = usb_control_msg(dev->udev, usb_sndctrlpipe(dev->udev, 0),
2002 			      cmd, reqtype, value, index, buf, size,
2003 			      USB_CTRL_SET_TIMEOUT);
2004 	kfree(buf);
2005 
2006 out:
2007 	return err;
2008 }
2009 
2010 /*
2011  * The function can't be called inside suspend/resume callback,
2012  * otherwise deadlock will be caused.
2013  */
2014 int usbnet_read_cmd(struct usbnet *dev, u8 cmd, u8 reqtype,
2015 		    u16 value, u16 index, void *data, u16 size)
2016 {
2017 	int ret;
2018 
2019 	if (usb_autopm_get_interface(dev->intf) < 0)
2020 		return -ENODEV;
2021 	ret = __usbnet_read_cmd(dev, cmd, reqtype, value, index,
2022 				data, size);
2023 	usb_autopm_put_interface(dev->intf);
2024 	return ret;
2025 }
2026 EXPORT_SYMBOL_GPL(usbnet_read_cmd);
2027 
2028 /*
2029  * The function can't be called inside suspend/resume callback,
2030  * otherwise deadlock will be caused.
2031  */
2032 int usbnet_write_cmd(struct usbnet *dev, u8 cmd, u8 reqtype,
2033 		     u16 value, u16 index, const void *data, u16 size)
2034 {
2035 	int ret;
2036 
2037 	if (usb_autopm_get_interface(dev->intf) < 0)
2038 		return -ENODEV;
2039 	ret = __usbnet_write_cmd(dev, cmd, reqtype, value, index,
2040 				 data, size);
2041 	usb_autopm_put_interface(dev->intf);
2042 	return ret;
2043 }
2044 EXPORT_SYMBOL_GPL(usbnet_write_cmd);
2045 
2046 /*
2047  * The function can be called inside suspend/resume callback safely
2048  * and should only be called by suspend/resume callback generally.
2049  */
2050 int usbnet_read_cmd_nopm(struct usbnet *dev, u8 cmd, u8 reqtype,
2051 			  u16 value, u16 index, void *data, u16 size)
2052 {
2053 	return __usbnet_read_cmd(dev, cmd, reqtype, value, index,
2054 				 data, size);
2055 }
2056 EXPORT_SYMBOL_GPL(usbnet_read_cmd_nopm);
2057 
2058 /*
2059  * The function can be called inside suspend/resume callback safely
2060  * and should only be called by suspend/resume callback generally.
2061  */
2062 int usbnet_write_cmd_nopm(struct usbnet *dev, u8 cmd, u8 reqtype,
2063 			  u16 value, u16 index, const void *data,
2064 			  u16 size)
2065 {
2066 	return __usbnet_write_cmd(dev, cmd, reqtype, value, index,
2067 				  data, size);
2068 }
2069 EXPORT_SYMBOL_GPL(usbnet_write_cmd_nopm);
2070 
2071 static void usbnet_async_cmd_cb(struct urb *urb)
2072 {
2073 	struct usb_ctrlrequest *req = (struct usb_ctrlrequest *)urb->context;
2074 	int status = urb->status;
2075 
2076 	if (status < 0)
2077 		dev_dbg(&urb->dev->dev, "%s failed with %d",
2078 			__func__, status);
2079 
2080 	kfree(req);
2081 	usb_free_urb(urb);
2082 }
2083 
2084 /*
2085  * The caller must make sure that device can't be put into suspend
2086  * state until the control URB completes.
2087  */
2088 int usbnet_write_cmd_async(struct usbnet *dev, u8 cmd, u8 reqtype,
2089 			   u16 value, u16 index, const void *data, u16 size)
2090 {
2091 	struct usb_ctrlrequest *req = NULL;
2092 	struct urb *urb;
2093 	int err = -ENOMEM;
2094 	void *buf = NULL;
2095 
2096 	netdev_dbg(dev->net, "usbnet_write_cmd cmd=0x%02x reqtype=%02x"
2097 		   " value=0x%04x index=0x%04x size=%d\n",
2098 		   cmd, reqtype, value, index, size);
2099 
2100 	urb = usb_alloc_urb(0, GFP_ATOMIC);
2101 	if (!urb)
2102 		goto fail;
2103 
2104 	if (data) {
2105 		buf = kmemdup(data, size, GFP_ATOMIC);
2106 		if (!buf) {
2107 			netdev_err(dev->net, "Error allocating buffer"
2108 				   " in %s!\n", __func__);
2109 			goto fail_free;
2110 		}
2111 	}
2112 
2113 	req = kmalloc(sizeof(struct usb_ctrlrequest), GFP_ATOMIC);
2114 	if (!req)
2115 		goto fail_free_buf;
2116 
2117 	req->bRequestType = reqtype;
2118 	req->bRequest = cmd;
2119 	req->wValue = cpu_to_le16(value);
2120 	req->wIndex = cpu_to_le16(index);
2121 	req->wLength = cpu_to_le16(size);
2122 
2123 	usb_fill_control_urb(urb, dev->udev,
2124 			     usb_sndctrlpipe(dev->udev, 0),
2125 			     (void *)req, buf, size,
2126 			     usbnet_async_cmd_cb, req);
2127 	urb->transfer_flags |= URB_FREE_BUFFER;
2128 
2129 	err = usb_submit_urb(urb, GFP_ATOMIC);
2130 	if (err < 0) {
2131 		netdev_err(dev->net, "Error submitting the control"
2132 			   " message: status=%d\n", err);
2133 		goto fail_free;
2134 	}
2135 	return 0;
2136 
2137 fail_free_buf:
2138 	kfree(buf);
2139 fail_free:
2140 	kfree(req);
2141 	usb_free_urb(urb);
2142 fail:
2143 	return err;
2144 
2145 }
2146 EXPORT_SYMBOL_GPL(usbnet_write_cmd_async);
2147 /*-------------------------------------------------------------------------*/
2148 
2149 static int __init usbnet_init(void)
2150 {
2151 	/* Compiler should optimize this out. */
2152 	BUILD_BUG_ON(
2153 		sizeof_field(struct sk_buff, cb) < sizeof(struct skb_data));
2154 
2155 	eth_random_addr(node_id);
2156 	return 0;
2157 }
2158 module_init(usbnet_init);
2159 
2160 static void __exit usbnet_exit(void)
2161 {
2162 }
2163 module_exit(usbnet_exit);
2164 
2165 MODULE_AUTHOR("David Brownell");
2166 MODULE_DESCRIPTION("USB network driver framework");
2167 MODULE_LICENSE("GPL");
2168