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