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