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