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