linux/drivers/usb/gadget/f_ncm.c
<<
>>
Prefs
   1/*
   2 * f_ncm.c -- USB CDC Network (NCM) link function driver
   3 *
   4 * Copyright (C) 2010 Nokia Corporation
   5 * Contact: Yauheni Kaliuta <yauheni.kaliuta@nokia.com>
   6 *
   7 * The driver borrows from f_ecm.c which is:
   8 *
   9 * Copyright (C) 2003-2005,2008 David Brownell
  10 * Copyright (C) 2008 Nokia Corporation
  11 *
  12 * This program is free software; you can redistribute it and/or modify
  13 * it under the terms of the GNU General Public License as published by
  14 * the Free Software Foundation; either version 2 of the License, or
  15 * (at your option) any later version.
  16 */
  17
  18#include <linux/kernel.h>
  19#include <linux/module.h>
  20#include <linux/device.h>
  21#include <linux/etherdevice.h>
  22#include <linux/crc32.h>
  23
  24#include <linux/usb/cdc.h>
  25
  26#include "u_ether.h"
  27#include "u_ether_configfs.h"
  28#include "u_ncm.h"
  29
  30/*
  31 * This function is a "CDC Network Control Model" (CDC NCM) Ethernet link.
  32 * NCM is intended to be used with high-speed network attachments.
  33 *
  34 * Note that NCM requires the use of "alternate settings" for its data
  35 * interface.  This means that the set_alt() method has real work to do,
  36 * and also means that a get_alt() method is required.
  37 */
  38
  39/* to trigger crc/non-crc ndp signature */
  40
  41#define NCM_NDP_HDR_CRC_MASK    0x01000000
  42#define NCM_NDP_HDR_CRC         0x01000000
  43#define NCM_NDP_HDR_NOCRC       0x00000000
  44
  45enum ncm_notify_state {
  46        NCM_NOTIFY_NONE,                /* don't notify */
  47        NCM_NOTIFY_CONNECT,             /* issue CONNECT next */
  48        NCM_NOTIFY_SPEED,               /* issue SPEED_CHANGE next */
  49};
  50
  51struct f_ncm {
  52        struct gether                   port;
  53        u8                              ctrl_id, data_id;
  54
  55        char                            ethaddr[14];
  56
  57        struct usb_ep                   *notify;
  58        struct usb_request              *notify_req;
  59        u8                              notify_state;
  60        bool                            is_open;
  61
  62        const struct ndp_parser_opts    *parser_opts;
  63        bool                            is_crc;
  64        u32                             ndp_sign;
  65
  66        /*
  67         * for notification, it is accessed from both
  68         * callback and ethernet open/close
  69         */
  70        spinlock_t                      lock;
  71};
  72
  73static inline struct f_ncm *func_to_ncm(struct usb_function *f)
  74{
  75        return container_of(f, struct f_ncm, port.func);
  76}
  77
  78/* peak (theoretical) bulk transfer rate in bits-per-second */
  79static inline unsigned ncm_bitrate(struct usb_gadget *g)
  80{
  81        if (gadget_is_dualspeed(g) && g->speed == USB_SPEED_HIGH)
  82                return 13 * 512 * 8 * 1000 * 8;
  83        else
  84                return 19 *  64 * 1 * 1000 * 8;
  85}
  86
  87/*-------------------------------------------------------------------------*/
  88
  89/*
  90 * We cannot group frames so use just the minimal size which ok to put
  91 * one max-size ethernet frame.
  92 * If the host can group frames, allow it to do that, 16K is selected,
  93 * because it's used by default by the current linux host driver
  94 */
  95#define NTB_DEFAULT_IN_SIZE     USB_CDC_NCM_NTB_MIN_IN_SIZE
  96#define NTB_OUT_SIZE            16384
  97
  98/*
  99 * skbs of size less than that will not be aligned
 100 * to NCM's dwNtbInMaxSize to save bus bandwidth
 101 */
 102
 103#define MAX_TX_NONFIXED         (512 * 3)
 104
 105#define FORMATS_SUPPORTED       (USB_CDC_NCM_NTB16_SUPPORTED |  \
 106                                 USB_CDC_NCM_NTB32_SUPPORTED)
 107
 108static struct usb_cdc_ncm_ntb_parameters ntb_parameters = {
 109        .wLength = cpu_to_le16(sizeof(ntb_parameters)),
 110        .bmNtbFormatsSupported = cpu_to_le16(FORMATS_SUPPORTED),
 111        .dwNtbInMaxSize = cpu_to_le32(NTB_DEFAULT_IN_SIZE),
 112        .wNdpInDivisor = cpu_to_le16(4),
 113        .wNdpInPayloadRemainder = cpu_to_le16(0),
 114        .wNdpInAlignment = cpu_to_le16(4),
 115
 116        .dwNtbOutMaxSize = cpu_to_le32(NTB_OUT_SIZE),
 117        .wNdpOutDivisor = cpu_to_le16(4),
 118        .wNdpOutPayloadRemainder = cpu_to_le16(0),
 119        .wNdpOutAlignment = cpu_to_le16(4),
 120};
 121
 122/*
 123 * Use wMaxPacketSize big enough to fit CDC_NOTIFY_SPEED_CHANGE in one
 124 * packet, to simplify cancellation; and a big transfer interval, to
 125 * waste less bandwidth.
 126 */
 127
 128#define NCM_STATUS_INTERVAL_MS          32
 129#define NCM_STATUS_BYTECOUNT            16      /* 8 byte header + data */
 130
 131static struct usb_interface_assoc_descriptor ncm_iad_desc = {
 132        .bLength =              sizeof ncm_iad_desc,
 133        .bDescriptorType =      USB_DT_INTERFACE_ASSOCIATION,
 134
 135        /* .bFirstInterface =   DYNAMIC, */
 136        .bInterfaceCount =      2,      /* control + data */
 137        .bFunctionClass =       USB_CLASS_COMM,
 138        .bFunctionSubClass =    USB_CDC_SUBCLASS_NCM,
 139        .bFunctionProtocol =    USB_CDC_PROTO_NONE,
 140        /* .iFunction =         DYNAMIC */
 141};
 142
 143/* interface descriptor: */
 144
 145static struct usb_interface_descriptor ncm_control_intf = {
 146        .bLength =              sizeof ncm_control_intf,
 147        .bDescriptorType =      USB_DT_INTERFACE,
 148
 149        /* .bInterfaceNumber = DYNAMIC */
 150        .bNumEndpoints =        1,
 151        .bInterfaceClass =      USB_CLASS_COMM,
 152        .bInterfaceSubClass =   USB_CDC_SUBCLASS_NCM,
 153        .bInterfaceProtocol =   USB_CDC_PROTO_NONE,
 154        /* .iInterface = DYNAMIC */
 155};
 156
 157static struct usb_cdc_header_desc ncm_header_desc = {
 158        .bLength =              sizeof ncm_header_desc,
 159        .bDescriptorType =      USB_DT_CS_INTERFACE,
 160        .bDescriptorSubType =   USB_CDC_HEADER_TYPE,
 161
 162        .bcdCDC =               cpu_to_le16(0x0110),
 163};
 164
 165static struct usb_cdc_union_desc ncm_union_desc = {
 166        .bLength =              sizeof(ncm_union_desc),
 167        .bDescriptorType =      USB_DT_CS_INTERFACE,
 168        .bDescriptorSubType =   USB_CDC_UNION_TYPE,
 169        /* .bMasterInterface0 = DYNAMIC */
 170        /* .bSlaveInterface0 =  DYNAMIC */
 171};
 172
 173static struct usb_cdc_ether_desc ecm_desc = {
 174        .bLength =              sizeof ecm_desc,
 175        .bDescriptorType =      USB_DT_CS_INTERFACE,
 176        .bDescriptorSubType =   USB_CDC_ETHERNET_TYPE,
 177
 178        /* this descriptor actually adds value, surprise! */
 179        /* .iMACAddress = DYNAMIC */
 180        .bmEthernetStatistics = cpu_to_le32(0), /* no statistics */
 181        .wMaxSegmentSize =      cpu_to_le16(ETH_FRAME_LEN),
 182        .wNumberMCFilters =     cpu_to_le16(0),
 183        .bNumberPowerFilters =  0,
 184};
 185
 186#define NCAPS   (USB_CDC_NCM_NCAP_ETH_FILTER | USB_CDC_NCM_NCAP_CRC_MODE)
 187
 188static struct usb_cdc_ncm_desc ncm_desc = {
 189        .bLength =              sizeof ncm_desc,
 190        .bDescriptorType =      USB_DT_CS_INTERFACE,
 191        .bDescriptorSubType =   USB_CDC_NCM_TYPE,
 192
 193        .bcdNcmVersion =        cpu_to_le16(0x0100),
 194        /* can process SetEthernetPacketFilter */
 195        .bmNetworkCapabilities = NCAPS,
 196};
 197
 198/* the default data interface has no endpoints ... */
 199
 200static struct usb_interface_descriptor ncm_data_nop_intf = {
 201        .bLength =              sizeof ncm_data_nop_intf,
 202        .bDescriptorType =      USB_DT_INTERFACE,
 203
 204        .bInterfaceNumber =     1,
 205        .bAlternateSetting =    0,
 206        .bNumEndpoints =        0,
 207        .bInterfaceClass =      USB_CLASS_CDC_DATA,
 208        .bInterfaceSubClass =   0,
 209        .bInterfaceProtocol =   USB_CDC_NCM_PROTO_NTB,
 210        /* .iInterface = DYNAMIC */
 211};
 212
 213/* ... but the "real" data interface has two bulk endpoints */
 214
 215static struct usb_interface_descriptor ncm_data_intf = {
 216        .bLength =              sizeof ncm_data_intf,
 217        .bDescriptorType =      USB_DT_INTERFACE,
 218
 219        .bInterfaceNumber =     1,
 220        .bAlternateSetting =    1,
 221        .bNumEndpoints =        2,
 222        .bInterfaceClass =      USB_CLASS_CDC_DATA,
 223        .bInterfaceSubClass =   0,
 224        .bInterfaceProtocol =   USB_CDC_NCM_PROTO_NTB,
 225        /* .iInterface = DYNAMIC */
 226};
 227
 228/* full speed support: */
 229
 230static struct usb_endpoint_descriptor fs_ncm_notify_desc = {
 231        .bLength =              USB_DT_ENDPOINT_SIZE,
 232        .bDescriptorType =      USB_DT_ENDPOINT,
 233
 234        .bEndpointAddress =     USB_DIR_IN,
 235        .bmAttributes =         USB_ENDPOINT_XFER_INT,
 236        .wMaxPacketSize =       cpu_to_le16(NCM_STATUS_BYTECOUNT),
 237        .bInterval =            NCM_STATUS_INTERVAL_MS,
 238};
 239
 240static struct usb_endpoint_descriptor fs_ncm_in_desc = {
 241        .bLength =              USB_DT_ENDPOINT_SIZE,
 242        .bDescriptorType =      USB_DT_ENDPOINT,
 243
 244        .bEndpointAddress =     USB_DIR_IN,
 245        .bmAttributes =         USB_ENDPOINT_XFER_BULK,
 246};
 247
 248static struct usb_endpoint_descriptor fs_ncm_out_desc = {
 249        .bLength =              USB_DT_ENDPOINT_SIZE,
 250        .bDescriptorType =      USB_DT_ENDPOINT,
 251
 252        .bEndpointAddress =     USB_DIR_OUT,
 253        .bmAttributes =         USB_ENDPOINT_XFER_BULK,
 254};
 255
 256static struct usb_descriptor_header *ncm_fs_function[] = {
 257        (struct usb_descriptor_header *) &ncm_iad_desc,
 258        /* CDC NCM control descriptors */
 259        (struct usb_descriptor_header *) &ncm_control_intf,
 260        (struct usb_descriptor_header *) &ncm_header_desc,
 261        (struct usb_descriptor_header *) &ncm_union_desc,
 262        (struct usb_descriptor_header *) &ecm_desc,
 263        (struct usb_descriptor_header *) &ncm_desc,
 264        (struct usb_descriptor_header *) &fs_ncm_notify_desc,
 265        /* data interface, altsettings 0 and 1 */
 266        (struct usb_descriptor_header *) &ncm_data_nop_intf,
 267        (struct usb_descriptor_header *) &ncm_data_intf,
 268        (struct usb_descriptor_header *) &fs_ncm_in_desc,
 269        (struct usb_descriptor_header *) &fs_ncm_out_desc,
 270        NULL,
 271};
 272
 273/* high speed support: */
 274
 275static struct usb_endpoint_descriptor hs_ncm_notify_desc = {
 276        .bLength =              USB_DT_ENDPOINT_SIZE,
 277        .bDescriptorType =      USB_DT_ENDPOINT,
 278
 279        .bEndpointAddress =     USB_DIR_IN,
 280        .bmAttributes =         USB_ENDPOINT_XFER_INT,
 281        .wMaxPacketSize =       cpu_to_le16(NCM_STATUS_BYTECOUNT),
 282        .bInterval =            USB_MS_TO_HS_INTERVAL(NCM_STATUS_INTERVAL_MS),
 283};
 284static struct usb_endpoint_descriptor hs_ncm_in_desc = {
 285        .bLength =              USB_DT_ENDPOINT_SIZE,
 286        .bDescriptorType =      USB_DT_ENDPOINT,
 287
 288        .bEndpointAddress =     USB_DIR_IN,
 289        .bmAttributes =         USB_ENDPOINT_XFER_BULK,
 290        .wMaxPacketSize =       cpu_to_le16(512),
 291};
 292
 293static struct usb_endpoint_descriptor hs_ncm_out_desc = {
 294        .bLength =              USB_DT_ENDPOINT_SIZE,
 295        .bDescriptorType =      USB_DT_ENDPOINT,
 296
 297        .bEndpointAddress =     USB_DIR_OUT,
 298        .bmAttributes =         USB_ENDPOINT_XFER_BULK,
 299        .wMaxPacketSize =       cpu_to_le16(512),
 300};
 301
 302static struct usb_descriptor_header *ncm_hs_function[] = {
 303        (struct usb_descriptor_header *) &ncm_iad_desc,
 304        /* CDC NCM control descriptors */
 305        (struct usb_descriptor_header *) &ncm_control_intf,
 306        (struct usb_descriptor_header *) &ncm_header_desc,
 307        (struct usb_descriptor_header *) &ncm_union_desc,
 308        (struct usb_descriptor_header *) &ecm_desc,
 309        (struct usb_descriptor_header *) &ncm_desc,
 310        (struct usb_descriptor_header *) &hs_ncm_notify_desc,
 311        /* data interface, altsettings 0 and 1 */
 312        (struct usb_descriptor_header *) &ncm_data_nop_intf,
 313        (struct usb_descriptor_header *) &ncm_data_intf,
 314        (struct usb_descriptor_header *) &hs_ncm_in_desc,
 315        (struct usb_descriptor_header *) &hs_ncm_out_desc,
 316        NULL,
 317};
 318
 319/* string descriptors: */
 320
 321#define STRING_CTRL_IDX 0
 322#define STRING_MAC_IDX  1
 323#define STRING_DATA_IDX 2
 324#define STRING_IAD_IDX  3
 325
 326static struct usb_string ncm_string_defs[] = {
 327        [STRING_CTRL_IDX].s = "CDC Network Control Model (NCM)",
 328        [STRING_MAC_IDX].s = "",
 329        [STRING_DATA_IDX].s = "CDC Network Data",
 330        [STRING_IAD_IDX].s = "CDC NCM",
 331        {  } /* end of list */
 332};
 333
 334static struct usb_gadget_strings ncm_string_table = {
 335        .language =             0x0409, /* en-us */
 336        .strings =              ncm_string_defs,
 337};
 338
 339static struct usb_gadget_strings *ncm_strings[] = {
 340        &ncm_string_table,
 341        NULL,
 342};
 343
 344/*
 345 * Here are options for NCM Datagram Pointer table (NDP) parser.
 346 * There are 2 different formats: NDP16 and NDP32 in the spec (ch. 3),
 347 * in NDP16 offsets and sizes fields are 1 16bit word wide,
 348 * in NDP32 -- 2 16bit words wide. Also signatures are different.
 349 * To make the parser code the same, put the differences in the structure,
 350 * and switch pointers to the structures when the format is changed.
 351 */
 352
 353struct ndp_parser_opts {
 354        u32             nth_sign;
 355        u32             ndp_sign;
 356        unsigned        nth_size;
 357        unsigned        ndp_size;
 358        unsigned        ndplen_align;
 359        /* sizes in u16 units */
 360        unsigned        dgram_item_len; /* index or length */
 361        unsigned        block_length;
 362        unsigned        fp_index;
 363        unsigned        reserved1;
 364        unsigned        reserved2;
 365        unsigned        next_fp_index;
 366};
 367
 368#define INIT_NDP16_OPTS {                                       \
 369                .nth_sign = USB_CDC_NCM_NTH16_SIGN,             \
 370                .ndp_sign = USB_CDC_NCM_NDP16_NOCRC_SIGN,       \
 371                .nth_size = sizeof(struct usb_cdc_ncm_nth16),   \
 372                .ndp_size = sizeof(struct usb_cdc_ncm_ndp16),   \
 373                .ndplen_align = 4,                              \
 374                .dgram_item_len = 1,                            \
 375                .block_length = 1,                              \
 376                .fp_index = 1,                                  \
 377                .reserved1 = 0,                                 \
 378                .reserved2 = 0,                                 \
 379                .next_fp_index = 1,                             \
 380        }
 381
 382
 383#define INIT_NDP32_OPTS {                                       \
 384                .nth_sign = USB_CDC_NCM_NTH32_SIGN,             \
 385                .ndp_sign = USB_CDC_NCM_NDP32_NOCRC_SIGN,       \
 386                .nth_size = sizeof(struct usb_cdc_ncm_nth32),   \
 387                .ndp_size = sizeof(struct usb_cdc_ncm_ndp32),   \
 388                .ndplen_align = 8,                              \
 389                .dgram_item_len = 2,                            \
 390                .block_length = 2,                              \
 391                .fp_index = 2,                                  \
 392                .reserved1 = 1,                                 \
 393                .reserved2 = 2,                                 \
 394                .next_fp_index = 2,                             \
 395        }
 396
 397static const struct ndp_parser_opts ndp16_opts = INIT_NDP16_OPTS;
 398static const struct ndp_parser_opts ndp32_opts = INIT_NDP32_OPTS;
 399
 400static inline void put_ncm(__le16 **p, unsigned size, unsigned val)
 401{
 402        switch (size) {
 403        case 1:
 404                put_unaligned_le16((u16)val, *p);
 405                break;
 406        case 2:
 407                put_unaligned_le32((u32)val, *p);
 408
 409                break;
 410        default:
 411                BUG();
 412        }
 413
 414        *p += size;
 415}
 416
 417static inline unsigned get_ncm(__le16 **p, unsigned size)
 418{
 419        unsigned tmp;
 420
 421        switch (size) {
 422        case 1:
 423                tmp = get_unaligned_le16(*p);
 424                break;
 425        case 2:
 426                tmp = get_unaligned_le32(*p);
 427                break;
 428        default:
 429                BUG();
 430        }
 431
 432        *p += size;
 433        return tmp;
 434}
 435
 436/*-------------------------------------------------------------------------*/
 437
 438static inline void ncm_reset_values(struct f_ncm *ncm)
 439{
 440        ncm->parser_opts = &ndp16_opts;
 441        ncm->is_crc = false;
 442        ncm->port.cdc_filter = DEFAULT_FILTER;
 443
 444        /* doesn't make sense for ncm, fixed size used */
 445        ncm->port.header_len = 0;
 446
 447        ncm->port.fixed_out_len = le32_to_cpu(ntb_parameters.dwNtbOutMaxSize);
 448        ncm->port.fixed_in_len = NTB_DEFAULT_IN_SIZE;
 449}
 450
 451/*
 452 * Context: ncm->lock held
 453 */
 454static void ncm_do_notify(struct f_ncm *ncm)
 455{
 456        struct usb_request              *req = ncm->notify_req;
 457        struct usb_cdc_notification     *event;
 458        struct usb_composite_dev        *cdev = ncm->port.func.config->cdev;
 459        __le32                          *data;
 460        int                             status;
 461
 462        /* notification already in flight? */
 463        if (!req)
 464                return;
 465
 466        event = req->buf;
 467        switch (ncm->notify_state) {
 468        case NCM_NOTIFY_NONE:
 469                return;
 470
 471        case NCM_NOTIFY_CONNECT:
 472                event->bNotificationType = USB_CDC_NOTIFY_NETWORK_CONNECTION;
 473                if (ncm->is_open)
 474                        event->wValue = cpu_to_le16(1);
 475                else
 476                        event->wValue = cpu_to_le16(0);
 477                event->wLength = 0;
 478                req->length = sizeof *event;
 479
 480                DBG(cdev, "notify connect %s\n",
 481                                ncm->is_open ? "true" : "false");
 482                ncm->notify_state = NCM_NOTIFY_NONE;
 483                break;
 484
 485        case NCM_NOTIFY_SPEED:
 486                event->bNotificationType = USB_CDC_NOTIFY_SPEED_CHANGE;
 487                event->wValue = cpu_to_le16(0);
 488                event->wLength = cpu_to_le16(8);
 489                req->length = NCM_STATUS_BYTECOUNT;
 490
 491                /* SPEED_CHANGE data is up/down speeds in bits/sec */
 492                data = req->buf + sizeof *event;
 493                data[0] = cpu_to_le32(ncm_bitrate(cdev->gadget));
 494                data[1] = data[0];
 495
 496                DBG(cdev, "notify speed %d\n", ncm_bitrate(cdev->gadget));
 497                ncm->notify_state = NCM_NOTIFY_CONNECT;
 498                break;
 499        }
 500        event->bmRequestType = 0xA1;
 501        event->wIndex = cpu_to_le16(ncm->ctrl_id);
 502
 503        ncm->notify_req = NULL;
 504        /*
 505         * In double buffering if there is a space in FIFO,
 506         * completion callback can be called right after the call,
 507         * so unlocking
 508         */
 509        spin_unlock(&ncm->lock);
 510        status = usb_ep_queue(ncm->notify, req, GFP_ATOMIC);
 511        spin_lock(&ncm->lock);
 512        if (status < 0) {
 513                ncm->notify_req = req;
 514                DBG(cdev, "notify --> %d\n", status);
 515        }
 516}
 517
 518/*
 519 * Context: ncm->lock held
 520 */
 521static void ncm_notify(struct f_ncm *ncm)
 522{
 523        /*
 524         * NOTE on most versions of Linux, host side cdc-ethernet
 525         * won't listen for notifications until its netdevice opens.
 526         * The first notification then sits in the FIFO for a long
 527         * time, and the second one is queued.
 528         *
 529         * If ncm_notify() is called before the second (CONNECT)
 530         * notification is sent, then it will reset to send the SPEED
 531         * notificaion again (and again, and again), but it's not a problem
 532         */
 533        ncm->notify_state = NCM_NOTIFY_SPEED;
 534        ncm_do_notify(ncm);
 535}
 536
 537static void ncm_notify_complete(struct usb_ep *ep, struct usb_request *req)
 538{
 539        struct f_ncm                    *ncm = req->context;
 540        struct usb_composite_dev        *cdev = ncm->port.func.config->cdev;
 541        struct usb_cdc_notification     *event = req->buf;
 542
 543        spin_lock(&ncm->lock);
 544        switch (req->status) {
 545        case 0:
 546                VDBG(cdev, "Notification %02x sent\n",
 547                     event->bNotificationType);
 548                break;
 549        case -ECONNRESET:
 550        case -ESHUTDOWN:
 551                ncm->notify_state = NCM_NOTIFY_NONE;
 552                break;
 553        default:
 554                DBG(cdev, "event %02x --> %d\n",
 555                        event->bNotificationType, req->status);
 556                break;
 557        }
 558        ncm->notify_req = req;
 559        ncm_do_notify(ncm);
 560        spin_unlock(&ncm->lock);
 561}
 562
 563static void ncm_ep0out_complete(struct usb_ep *ep, struct usb_request *req)
 564{
 565        /* now for SET_NTB_INPUT_SIZE only */
 566        unsigned                in_size;
 567        struct usb_function     *f = req->context;
 568        struct f_ncm            *ncm = func_to_ncm(f);
 569        struct usb_composite_dev *cdev = ep->driver_data;
 570
 571        req->context = NULL;
 572        if (req->status || req->actual != req->length) {
 573                DBG(cdev, "Bad control-OUT transfer\n");
 574                goto invalid;
 575        }
 576
 577        in_size = get_unaligned_le32(req->buf);
 578        if (in_size < USB_CDC_NCM_NTB_MIN_IN_SIZE ||
 579            in_size > le32_to_cpu(ntb_parameters.dwNtbInMaxSize)) {
 580                DBG(cdev, "Got wrong INPUT SIZE (%d) from host\n", in_size);
 581                goto invalid;
 582        }
 583
 584        ncm->port.fixed_in_len = in_size;
 585        VDBG(cdev, "Set NTB INPUT SIZE %d\n", in_size);
 586        return;
 587
 588invalid:
 589        usb_ep_set_halt(ep);
 590        return;
 591}
 592
 593static int ncm_setup(struct usb_function *f, const struct usb_ctrlrequest *ctrl)
 594{
 595        struct f_ncm            *ncm = func_to_ncm(f);
 596        struct usb_composite_dev *cdev = f->config->cdev;
 597        struct usb_request      *req = cdev->req;
 598        int                     value = -EOPNOTSUPP;
 599        u16                     w_index = le16_to_cpu(ctrl->wIndex);
 600        u16                     w_value = le16_to_cpu(ctrl->wValue);
 601        u16                     w_length = le16_to_cpu(ctrl->wLength);
 602
 603        /*
 604         * composite driver infrastructure handles everything except
 605         * CDC class messages; interface activation uses set_alt().
 606         */
 607        switch ((ctrl->bRequestType << 8) | ctrl->bRequest) {
 608        case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
 609                        | USB_CDC_SET_ETHERNET_PACKET_FILTER:
 610                /*
 611                 * see 6.2.30: no data, wIndex = interface,
 612                 * wValue = packet filter bitmap
 613                 */
 614                if (w_length != 0 || w_index != ncm->ctrl_id)
 615                        goto invalid;
 616                DBG(cdev, "packet filter %02x\n", w_value);
 617                /*
 618                 * REVISIT locking of cdc_filter.  This assumes the UDC
 619                 * driver won't have a concurrent packet TX irq running on
 620                 * another CPU; or that if it does, this write is atomic...
 621                 */
 622                ncm->port.cdc_filter = w_value;
 623                value = 0;
 624                break;
 625        /*
 626         * and optionally:
 627         * case USB_CDC_SEND_ENCAPSULATED_COMMAND:
 628         * case USB_CDC_GET_ENCAPSULATED_RESPONSE:
 629         * case USB_CDC_SET_ETHERNET_MULTICAST_FILTERS:
 630         * case USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER:
 631         * case USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER:
 632         * case USB_CDC_GET_ETHERNET_STATISTIC:
 633         */
 634
 635        case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
 636                | USB_CDC_GET_NTB_PARAMETERS:
 637
 638                if (w_length == 0 || w_value != 0 || w_index != ncm->ctrl_id)
 639                        goto invalid;
 640                value = w_length > sizeof ntb_parameters ?
 641                        sizeof ntb_parameters : w_length;
 642                memcpy(req->buf, &ntb_parameters, value);
 643                VDBG(cdev, "Host asked NTB parameters\n");
 644                break;
 645
 646        case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
 647                | USB_CDC_GET_NTB_INPUT_SIZE:
 648
 649                if (w_length < 4 || w_value != 0 || w_index != ncm->ctrl_id)
 650                        goto invalid;
 651                put_unaligned_le32(ncm->port.fixed_in_len, req->buf);
 652                value = 4;
 653                VDBG(cdev, "Host asked INPUT SIZE, sending %d\n",
 654                     ncm->port.fixed_in_len);
 655                break;
 656
 657        case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
 658                | USB_CDC_SET_NTB_INPUT_SIZE:
 659        {
 660                if (w_length != 4 || w_value != 0 || w_index != ncm->ctrl_id)
 661                        goto invalid;
 662                req->complete = ncm_ep0out_complete;
 663                req->length = w_length;
 664                req->context = f;
 665
 666                value = req->length;
 667                break;
 668        }
 669
 670        case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
 671                | USB_CDC_GET_NTB_FORMAT:
 672        {
 673                uint16_t format;
 674
 675                if (w_length < 2 || w_value != 0 || w_index != ncm->ctrl_id)
 676                        goto invalid;
 677                format = (ncm->parser_opts == &ndp16_opts) ? 0x0000 : 0x0001;
 678                put_unaligned_le16(format, req->buf);
 679                value = 2;
 680                VDBG(cdev, "Host asked NTB FORMAT, sending %d\n", format);
 681                break;
 682        }
 683
 684        case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
 685                | USB_CDC_SET_NTB_FORMAT:
 686        {
 687                if (w_length != 0 || w_index != ncm->ctrl_id)
 688                        goto invalid;
 689                switch (w_value) {
 690                case 0x0000:
 691                        ncm->parser_opts = &ndp16_opts;
 692                        DBG(cdev, "NCM16 selected\n");
 693                        break;
 694                case 0x0001:
 695                        ncm->parser_opts = &ndp32_opts;
 696                        DBG(cdev, "NCM32 selected\n");
 697                        break;
 698                default:
 699                        goto invalid;
 700                }
 701                value = 0;
 702                break;
 703        }
 704        case ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
 705                | USB_CDC_GET_CRC_MODE:
 706        {
 707                uint16_t is_crc;
 708
 709                if (w_length < 2 || w_value != 0 || w_index != ncm->ctrl_id)
 710                        goto invalid;
 711                is_crc = ncm->is_crc ? 0x0001 : 0x0000;
 712                put_unaligned_le16(is_crc, req->buf);
 713                value = 2;
 714                VDBG(cdev, "Host asked CRC MODE, sending %d\n", is_crc);
 715                break;
 716        }
 717
 718        case ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
 719                | USB_CDC_SET_CRC_MODE:
 720        {
 721                int ndp_hdr_crc = 0;
 722
 723                if (w_length != 0 || w_index != ncm->ctrl_id)
 724                        goto invalid;
 725                switch (w_value) {
 726                case 0x0000:
 727                        ncm->is_crc = false;
 728                        ndp_hdr_crc = NCM_NDP_HDR_NOCRC;
 729                        DBG(cdev, "non-CRC mode selected\n");
 730                        break;
 731                case 0x0001:
 732                        ncm->is_crc = true;
 733                        ndp_hdr_crc = NCM_NDP_HDR_CRC;
 734                        DBG(cdev, "CRC mode selected\n");
 735                        break;
 736                default:
 737                        goto invalid;
 738                }
 739                ncm->ndp_sign = ncm->parser_opts->ndp_sign | ndp_hdr_crc;
 740                value = 0;
 741                break;
 742        }
 743
 744        /* and disabled in ncm descriptor: */
 745        /* case USB_CDC_GET_NET_ADDRESS: */
 746        /* case USB_CDC_SET_NET_ADDRESS: */
 747        /* case USB_CDC_GET_MAX_DATAGRAM_SIZE: */
 748        /* case USB_CDC_SET_MAX_DATAGRAM_SIZE: */
 749
 750        default:
 751invalid:
 752                DBG(cdev, "invalid control req%02x.%02x v%04x i%04x l%d\n",
 753                        ctrl->bRequestType, ctrl->bRequest,
 754                        w_value, w_index, w_length);
 755        }
 756
 757        /* respond with data transfer or status phase? */
 758        if (value >= 0) {
 759                DBG(cdev, "ncm req%02x.%02x v%04x i%04x l%d\n",
 760                        ctrl->bRequestType, ctrl->bRequest,
 761                        w_value, w_index, w_length);
 762                req->zero = 0;
 763                req->length = value;
 764                value = usb_ep_queue(cdev->gadget->ep0, req, GFP_ATOMIC);
 765                if (value < 0)
 766                        ERROR(cdev, "ncm req %02x.%02x response err %d\n",
 767                                        ctrl->bRequestType, ctrl->bRequest,
 768                                        value);
 769        }
 770
 771        /* device either stalls (value < 0) or reports success */
 772        return value;
 773}
 774
 775
 776static int ncm_set_alt(struct usb_function *f, unsigned intf, unsigned alt)
 777{
 778        struct f_ncm            *ncm = func_to_ncm(f);
 779        struct usb_composite_dev *cdev = f->config->cdev;
 780
 781        /* Control interface has only altsetting 0 */
 782        if (intf == ncm->ctrl_id) {
 783                if (alt != 0)
 784                        goto fail;
 785
 786                if (ncm->notify->driver_data) {
 787                        DBG(cdev, "reset ncm control %d\n", intf);
 788                        usb_ep_disable(ncm->notify);
 789                }
 790
 791                if (!(ncm->notify->desc)) {
 792                        DBG(cdev, "init ncm ctrl %d\n", intf);
 793                        if (config_ep_by_speed(cdev->gadget, f, ncm->notify))
 794                                goto fail;
 795                }
 796                usb_ep_enable(ncm->notify);
 797                ncm->notify->driver_data = ncm;
 798
 799        /* Data interface has two altsettings, 0 and 1 */
 800        } else if (intf == ncm->data_id) {
 801                if (alt > 1)
 802                        goto fail;
 803
 804                if (ncm->port.in_ep->driver_data) {
 805                        DBG(cdev, "reset ncm\n");
 806                        gether_disconnect(&ncm->port);
 807                        ncm_reset_values(ncm);
 808                }
 809
 810                /*
 811                 * CDC Network only sends data in non-default altsettings.
 812                 * Changing altsettings resets filters, statistics, etc.
 813                 */
 814                if (alt == 1) {
 815                        struct net_device       *net;
 816
 817                        if (!ncm->port.in_ep->desc ||
 818                            !ncm->port.out_ep->desc) {
 819                                DBG(cdev, "init ncm\n");
 820                                if (config_ep_by_speed(cdev->gadget, f,
 821                                                       ncm->port.in_ep) ||
 822                                    config_ep_by_speed(cdev->gadget, f,
 823                                                       ncm->port.out_ep)) {
 824                                        ncm->port.in_ep->desc = NULL;
 825                                        ncm->port.out_ep->desc = NULL;
 826                                        goto fail;
 827                                }
 828                        }
 829
 830                        /* TODO */
 831                        /* Enable zlps by default for NCM conformance;
 832                         * override for musb_hdrc (avoids txdma ovhead)
 833                         */
 834                        ncm->port.is_zlp_ok = !(
 835                                gadget_is_musbhdrc(cdev->gadget)
 836                                );
 837                        ncm->port.cdc_filter = DEFAULT_FILTER;
 838                        DBG(cdev, "activate ncm\n");
 839                        net = gether_connect(&ncm->port);
 840                        if (IS_ERR(net))
 841                                return PTR_ERR(net);
 842                }
 843
 844                spin_lock(&ncm->lock);
 845                ncm_notify(ncm);
 846                spin_unlock(&ncm->lock);
 847        } else
 848                goto fail;
 849
 850        return 0;
 851fail:
 852        return -EINVAL;
 853}
 854
 855/*
 856 * Because the data interface supports multiple altsettings,
 857 * this NCM function *MUST* implement a get_alt() method.
 858 */
 859static int ncm_get_alt(struct usb_function *f, unsigned intf)
 860{
 861        struct f_ncm            *ncm = func_to_ncm(f);
 862
 863        if (intf == ncm->ctrl_id)
 864                return 0;
 865        return ncm->port.in_ep->driver_data ? 1 : 0;
 866}
 867
 868static struct sk_buff *ncm_wrap_ntb(struct gether *port,
 869                                    struct sk_buff *skb)
 870{
 871        struct f_ncm    *ncm = func_to_ncm(&port->func);
 872        struct sk_buff  *skb2;
 873        int             ncb_len = 0;
 874        __le16          *tmp;
 875        int             div;
 876        int             rem;
 877        int             pad;
 878        int             ndp_align;
 879        int             ndp_pad;
 880        unsigned        max_size = ncm->port.fixed_in_len;
 881        const struct ndp_parser_opts *opts = ncm->parser_opts;
 882        unsigned        crc_len = ncm->is_crc ? sizeof(uint32_t) : 0;
 883
 884        div = le16_to_cpu(ntb_parameters.wNdpInDivisor);
 885        rem = le16_to_cpu(ntb_parameters.wNdpInPayloadRemainder);
 886        ndp_align = le16_to_cpu(ntb_parameters.wNdpInAlignment);
 887
 888        ncb_len += opts->nth_size;
 889        ndp_pad = ALIGN(ncb_len, ndp_align) - ncb_len;
 890        ncb_len += ndp_pad;
 891        ncb_len += opts->ndp_size;
 892        ncb_len += 2 * 2 * opts->dgram_item_len; /* Datagram entry */
 893        ncb_len += 2 * 2 * opts->dgram_item_len; /* Zero datagram entry */
 894        pad = ALIGN(ncb_len, div) + rem - ncb_len;
 895        ncb_len += pad;
 896
 897        if (ncb_len + skb->len + crc_len > max_size) {
 898                dev_kfree_skb_any(skb);
 899                return NULL;
 900        }
 901
 902        skb2 = skb_copy_expand(skb, ncb_len,
 903                               max_size - skb->len - ncb_len - crc_len,
 904                               GFP_ATOMIC);
 905        dev_kfree_skb_any(skb);
 906        if (!skb2)
 907                return NULL;
 908
 909        skb = skb2;
 910
 911        tmp = (void *) skb_push(skb, ncb_len);
 912        memset(tmp, 0, ncb_len);
 913
 914        put_unaligned_le32(opts->nth_sign, tmp); /* dwSignature */
 915        tmp += 2;
 916        /* wHeaderLength */
 917        put_unaligned_le16(opts->nth_size, tmp++);
 918        tmp++; /* skip wSequence */
 919        put_ncm(&tmp, opts->block_length, skb->len); /* (d)wBlockLength */
 920        /* (d)wFpIndex */
 921        /* the first pointer is right after the NTH + align */
 922        put_ncm(&tmp, opts->fp_index, opts->nth_size + ndp_pad);
 923
 924        tmp = (void *)tmp + ndp_pad;
 925
 926        /* NDP */
 927        put_unaligned_le32(ncm->ndp_sign, tmp); /* dwSignature */
 928        tmp += 2;
 929        /* wLength */
 930        put_unaligned_le16(ncb_len - opts->nth_size - pad, tmp++);
 931
 932        tmp += opts->reserved1;
 933        tmp += opts->next_fp_index; /* skip reserved (d)wNextFpIndex */
 934        tmp += opts->reserved2;
 935
 936        if (ncm->is_crc) {
 937                uint32_t crc;
 938
 939                crc = ~crc32_le(~0,
 940                                skb->data + ncb_len,
 941                                skb->len - ncb_len);
 942                put_unaligned_le32(crc, skb->data + skb->len);
 943                skb_put(skb, crc_len);
 944        }
 945
 946        /* (d)wDatagramIndex[0] */
 947        put_ncm(&tmp, opts->dgram_item_len, ncb_len);
 948        /* (d)wDatagramLength[0] */
 949        put_ncm(&tmp, opts->dgram_item_len, skb->len - ncb_len);
 950        /* (d)wDatagramIndex[1] and  (d)wDatagramLength[1] already zeroed */
 951
 952        if (skb->len > MAX_TX_NONFIXED)
 953                memset(skb_put(skb, max_size - skb->len),
 954                       0, max_size - skb->len);
 955
 956        return skb;
 957}
 958
 959static int ncm_unwrap_ntb(struct gether *port,
 960                          struct sk_buff *skb,
 961                          struct sk_buff_head *list)
 962{
 963        struct f_ncm    *ncm = func_to_ncm(&port->func);
 964        __le16          *tmp = (void *) skb->data;
 965        unsigned        index, index2;
 966        unsigned        dg_len, dg_len2;
 967        unsigned        ndp_len;
 968        struct sk_buff  *skb2;
 969        int             ret = -EINVAL;
 970        unsigned        max_size = le32_to_cpu(ntb_parameters.dwNtbOutMaxSize);
 971        const struct ndp_parser_opts *opts = ncm->parser_opts;
 972        unsigned        crc_len = ncm->is_crc ? sizeof(uint32_t) : 0;
 973        int             dgram_counter;
 974
 975        /* dwSignature */
 976        if (get_unaligned_le32(tmp) != opts->nth_sign) {
 977                INFO(port->func.config->cdev, "Wrong NTH SIGN, skblen %d\n",
 978                        skb->len);
 979                print_hex_dump(KERN_INFO, "HEAD:", DUMP_PREFIX_ADDRESS, 32, 1,
 980                               skb->data, 32, false);
 981
 982                goto err;
 983        }
 984        tmp += 2;
 985        /* wHeaderLength */
 986        if (get_unaligned_le16(tmp++) != opts->nth_size) {
 987                INFO(port->func.config->cdev, "Wrong NTB headersize\n");
 988                goto err;
 989        }
 990        tmp++; /* skip wSequence */
 991
 992        /* (d)wBlockLength */
 993        if (get_ncm(&tmp, opts->block_length) > max_size) {
 994                INFO(port->func.config->cdev, "OUT size exceeded\n");
 995                goto err;
 996        }
 997
 998        index = get_ncm(&tmp, opts->fp_index);
 999        /* NCM 3.2 */
1000        if (((index % 4) != 0) && (index < opts->nth_size)) {
1001                INFO(port->func.config->cdev, "Bad index: %x\n",
1002                        index);
1003                goto err;
1004        }
1005
1006        /* walk through NDP */
1007        tmp = ((void *)skb->data) + index;
1008        if (get_unaligned_le32(tmp) != ncm->ndp_sign) {
1009                INFO(port->func.config->cdev, "Wrong NDP SIGN\n");
1010                goto err;
1011        }
1012        tmp += 2;
1013
1014        ndp_len = get_unaligned_le16(tmp++);
1015        /*
1016         * NCM 3.3.1
1017         * entry is 2 items
1018         * item size is 16/32 bits, opts->dgram_item_len * 2 bytes
1019         * minimal: struct usb_cdc_ncm_ndpX + normal entry + zero entry
1020         */
1021        if ((ndp_len < opts->ndp_size + 2 * 2 * (opts->dgram_item_len * 2))
1022            || (ndp_len % opts->ndplen_align != 0)) {
1023                INFO(port->func.config->cdev, "Bad NDP length: %x\n", ndp_len);
1024                goto err;
1025        }
1026        tmp += opts->reserved1;
1027        tmp += opts->next_fp_index; /* skip reserved (d)wNextFpIndex */
1028        tmp += opts->reserved2;
1029
1030        ndp_len -= opts->ndp_size;
1031        index2 = get_ncm(&tmp, opts->dgram_item_len);
1032        dg_len2 = get_ncm(&tmp, opts->dgram_item_len);
1033        dgram_counter = 0;
1034
1035        do {
1036                index = index2;
1037                dg_len = dg_len2;
1038                if (dg_len < 14 + crc_len) { /* ethernet header + crc */
1039                        INFO(port->func.config->cdev, "Bad dgram length: %x\n",
1040                             dg_len);
1041                        goto err;
1042                }
1043                if (ncm->is_crc) {
1044                        uint32_t crc, crc2;
1045
1046                        crc = get_unaligned_le32(skb->data +
1047                                                 index + dg_len - crc_len);
1048                        crc2 = ~crc32_le(~0,
1049                                         skb->data + index,
1050                                         dg_len - crc_len);
1051                        if (crc != crc2) {
1052                                INFO(port->func.config->cdev, "Bad CRC\n");
1053                                goto err;
1054                        }
1055                }
1056
1057                index2 = get_ncm(&tmp, opts->dgram_item_len);
1058                dg_len2 = get_ncm(&tmp, opts->dgram_item_len);
1059
1060                if (index2 == 0 || dg_len2 == 0) {
1061                        skb2 = skb;
1062                } else {
1063                        skb2 = skb_clone(skb, GFP_ATOMIC);
1064                        if (skb2 == NULL)
1065                                goto err;
1066                }
1067
1068                if (!skb_pull(skb2, index)) {
1069                        ret = -EOVERFLOW;
1070                        goto err;
1071                }
1072
1073                skb_trim(skb2, dg_len - crc_len);
1074                skb_queue_tail(list, skb2);
1075
1076                ndp_len -= 2 * (opts->dgram_item_len * 2);
1077
1078                dgram_counter++;
1079
1080                if (index2 == 0 || dg_len2 == 0)
1081                        break;
1082        } while (ndp_len > 2 * (opts->dgram_item_len * 2)); /* zero entry */
1083
1084        VDBG(port->func.config->cdev,
1085             "Parsed NTB with %d frames\n", dgram_counter);
1086        return 0;
1087err:
1088        skb_queue_purge(list);
1089        dev_kfree_skb_any(skb);
1090        return ret;
1091}
1092
1093static void ncm_disable(struct usb_function *f)
1094{
1095        struct f_ncm            *ncm = func_to_ncm(f);
1096        struct usb_composite_dev *cdev = f->config->cdev;
1097
1098        DBG(cdev, "ncm deactivated\n");
1099
1100        if (ncm->port.in_ep->driver_data)
1101                gether_disconnect(&ncm->port);
1102
1103        if (ncm->notify->driver_data) {
1104                usb_ep_disable(ncm->notify);
1105                ncm->notify->driver_data = NULL;
1106                ncm->notify->desc = NULL;
1107        }
1108}
1109
1110/*-------------------------------------------------------------------------*/
1111
1112/*
1113 * Callbacks let us notify the host about connect/disconnect when the
1114 * net device is opened or closed.
1115 *
1116 * For testing, note that link states on this side include both opened
1117 * and closed variants of:
1118 *
1119 *   - disconnected/unconfigured
1120 *   - configured but inactive (data alt 0)
1121 *   - configured and active (data alt 1)
1122 *
1123 * Each needs to be tested with unplug, rmmod, SET_CONFIGURATION, and
1124 * SET_INTERFACE (altsetting).  Remember also that "configured" doesn't
1125 * imply the host is actually polling the notification endpoint, and
1126 * likewise that "active" doesn't imply it's actually using the data
1127 * endpoints for traffic.
1128 */
1129
1130static void ncm_open(struct gether *geth)
1131{
1132        struct f_ncm            *ncm = func_to_ncm(&geth->func);
1133
1134        DBG(ncm->port.func.config->cdev, "%s\n", __func__);
1135
1136        spin_lock(&ncm->lock);
1137        ncm->is_open = true;
1138        ncm_notify(ncm);
1139        spin_unlock(&ncm->lock);
1140}
1141
1142static void ncm_close(struct gether *geth)
1143{
1144        struct f_ncm            *ncm = func_to_ncm(&geth->func);
1145
1146        DBG(ncm->port.func.config->cdev, "%s\n", __func__);
1147
1148        spin_lock(&ncm->lock);
1149        ncm->is_open = false;
1150        ncm_notify(ncm);
1151        spin_unlock(&ncm->lock);
1152}
1153
1154/*-------------------------------------------------------------------------*/
1155
1156/* ethernet function driver setup/binding */
1157
1158static int ncm_bind(struct usb_configuration *c, struct usb_function *f)
1159{
1160        struct usb_composite_dev *cdev = c->cdev;
1161        struct f_ncm            *ncm = func_to_ncm(f);
1162        struct usb_string       *us;
1163        int                     status;
1164        struct usb_ep           *ep;
1165        struct f_ncm_opts       *ncm_opts;
1166
1167        if (!can_support_ecm(cdev->gadget))
1168                return -EINVAL;
1169
1170        ncm_opts = container_of(f->fi, struct f_ncm_opts, func_inst);
1171        /*
1172         * in drivers/usb/gadget/configfs.c:configfs_composite_bind()
1173         * configurations are bound in sequence with list_for_each_entry,
1174         * in each configuration its functions are bound in sequence
1175         * with list_for_each_entry, so we assume no race condition
1176         * with regard to ncm_opts->bound access
1177         */
1178        if (!ncm_opts->bound) {
1179                mutex_lock(&ncm_opts->lock);
1180                gether_set_gadget(ncm_opts->net, cdev->gadget);
1181                status = gether_register_netdev(ncm_opts->net);
1182                mutex_unlock(&ncm_opts->lock);
1183                if (status)
1184                        return status;
1185                ncm_opts->bound = true;
1186        }
1187        us = usb_gstrings_attach(cdev, ncm_strings,
1188                                 ARRAY_SIZE(ncm_string_defs));
1189        if (IS_ERR(us))
1190                return PTR_ERR(us);
1191        ncm_control_intf.iInterface = us[STRING_CTRL_IDX].id;
1192        ncm_data_nop_intf.iInterface = us[STRING_DATA_IDX].id;
1193        ncm_data_intf.iInterface = us[STRING_DATA_IDX].id;
1194        ecm_desc.iMACAddress = us[STRING_MAC_IDX].id;
1195        ncm_iad_desc.iFunction = us[STRING_IAD_IDX].id;
1196
1197        /* allocate instance-specific interface IDs */
1198        status = usb_interface_id(c, f);
1199        if (status < 0)
1200                goto fail;
1201        ncm->ctrl_id = status;
1202        ncm_iad_desc.bFirstInterface = status;
1203
1204        ncm_control_intf.bInterfaceNumber = status;
1205        ncm_union_desc.bMasterInterface0 = status;
1206
1207        status = usb_interface_id(c, f);
1208        if (status < 0)
1209                goto fail;
1210        ncm->data_id = status;
1211
1212        ncm_data_nop_intf.bInterfaceNumber = status;
1213        ncm_data_intf.bInterfaceNumber = status;
1214        ncm_union_desc.bSlaveInterface0 = status;
1215
1216        status = -ENODEV;
1217
1218        /* allocate instance-specific endpoints */
1219        ep = usb_ep_autoconfig(cdev->gadget, &fs_ncm_in_desc);
1220        if (!ep)
1221                goto fail;
1222        ncm->port.in_ep = ep;
1223        ep->driver_data = cdev; /* claim */
1224
1225        ep = usb_ep_autoconfig(cdev->gadget, &fs_ncm_out_desc);
1226        if (!ep)
1227                goto fail;
1228        ncm->port.out_ep = ep;
1229        ep->driver_data = cdev; /* claim */
1230
1231        ep = usb_ep_autoconfig(cdev->gadget, &fs_ncm_notify_desc);
1232        if (!ep)
1233                goto fail;
1234        ncm->notify = ep;
1235        ep->driver_data = cdev; /* claim */
1236
1237        status = -ENOMEM;
1238
1239        /* allocate notification request and buffer */
1240        ncm->notify_req = usb_ep_alloc_request(ep, GFP_KERNEL);
1241        if (!ncm->notify_req)
1242                goto fail;
1243        ncm->notify_req->buf = kmalloc(NCM_STATUS_BYTECOUNT, GFP_KERNEL);
1244        if (!ncm->notify_req->buf)
1245                goto fail;
1246        ncm->notify_req->context = ncm;
1247        ncm->notify_req->complete = ncm_notify_complete;
1248
1249        /*
1250         * support all relevant hardware speeds... we expect that when
1251         * hardware is dual speed, all bulk-capable endpoints work at
1252         * both speeds
1253         */
1254        hs_ncm_in_desc.bEndpointAddress = fs_ncm_in_desc.bEndpointAddress;
1255        hs_ncm_out_desc.bEndpointAddress = fs_ncm_out_desc.bEndpointAddress;
1256        hs_ncm_notify_desc.bEndpointAddress =
1257                fs_ncm_notify_desc.bEndpointAddress;
1258
1259        status = usb_assign_descriptors(f, ncm_fs_function, ncm_hs_function,
1260                        NULL);
1261        /*
1262         * NOTE:  all that is done without knowing or caring about
1263         * the network link ... which is unavailable to this code
1264         * until we're activated via set_alt().
1265         */
1266
1267        ncm->port.open = ncm_open;
1268        ncm->port.close = ncm_close;
1269
1270        DBG(cdev, "CDC Network: %s speed IN/%s OUT/%s NOTIFY/%s\n",
1271                        gadget_is_dualspeed(c->cdev->gadget) ? "dual" : "full",
1272                        ncm->port.in_ep->name, ncm->port.out_ep->name,
1273                        ncm->notify->name);
1274        return 0;
1275
1276fail:
1277        usb_free_all_descriptors(f);
1278        if (ncm->notify_req) {
1279                kfree(ncm->notify_req->buf);
1280                usb_ep_free_request(ncm->notify, ncm->notify_req);
1281        }
1282
1283        /* we might as well release our claims on endpoints */
1284        if (ncm->notify)
1285                ncm->notify->driver_data = NULL;
1286        if (ncm->port.out_ep)
1287                ncm->port.out_ep->driver_data = NULL;
1288        if (ncm->port.in_ep)
1289                ncm->port.in_ep->driver_data = NULL;
1290
1291        ERROR(cdev, "%s: can't bind, err %d\n", f->name, status);
1292
1293        return status;
1294}
1295
1296static inline struct f_ncm_opts *to_f_ncm_opts(struct config_item *item)
1297{
1298        return container_of(to_config_group(item), struct f_ncm_opts,
1299                            func_inst.group);
1300}
1301
1302/* f_ncm_item_ops */
1303USB_ETHERNET_CONFIGFS_ITEM(ncm);
1304
1305/* f_ncm_opts_dev_addr */
1306USB_ETHERNET_CONFIGFS_ITEM_ATTR_DEV_ADDR(ncm);
1307
1308/* f_ncm_opts_host_addr */
1309USB_ETHERNET_CONFIGFS_ITEM_ATTR_HOST_ADDR(ncm);
1310
1311/* f_ncm_opts_qmult */
1312USB_ETHERNET_CONFIGFS_ITEM_ATTR_QMULT(ncm);
1313
1314/* f_ncm_opts_ifname */
1315USB_ETHERNET_CONFIGFS_ITEM_ATTR_IFNAME(ncm);
1316
1317static struct configfs_attribute *ncm_attrs[] = {
1318        &f_ncm_opts_dev_addr.attr,
1319        &f_ncm_opts_host_addr.attr,
1320        &f_ncm_opts_qmult.attr,
1321        &f_ncm_opts_ifname.attr,
1322        NULL,
1323};
1324
1325static struct config_item_type ncm_func_type = {
1326        .ct_item_ops    = &ncm_item_ops,
1327        .ct_attrs       = ncm_attrs,
1328        .ct_owner       = THIS_MODULE,
1329};
1330
1331static void ncm_free_inst(struct usb_function_instance *f)
1332{
1333        struct f_ncm_opts *opts;
1334
1335        opts = container_of(f, struct f_ncm_opts, func_inst);
1336        if (opts->bound)
1337                gether_cleanup(netdev_priv(opts->net));
1338        else
1339                free_netdev(opts->net);
1340        kfree(opts);
1341}
1342
1343static struct usb_function_instance *ncm_alloc_inst(void)
1344{
1345        struct f_ncm_opts *opts;
1346
1347        opts = kzalloc(sizeof(*opts), GFP_KERNEL);
1348        if (!opts)
1349                return ERR_PTR(-ENOMEM);
1350        mutex_init(&opts->lock);
1351        opts->func_inst.free_func_inst = ncm_free_inst;
1352        opts->net = gether_setup_default();
1353        if (IS_ERR(opts->net)) {
1354                struct net_device *net = opts->net;
1355                kfree(opts);
1356                return ERR_CAST(net);
1357        }
1358
1359        config_group_init_type_name(&opts->func_inst.group, "", &ncm_func_type);
1360
1361        return &opts->func_inst;
1362}
1363
1364static void ncm_free(struct usb_function *f)
1365{
1366        struct f_ncm *ncm;
1367        struct f_ncm_opts *opts;
1368
1369        ncm = func_to_ncm(f);
1370        opts = container_of(f->fi, struct f_ncm_opts, func_inst);
1371        kfree(ncm);
1372        mutex_lock(&opts->lock);
1373        opts->refcnt--;
1374        mutex_unlock(&opts->lock);
1375}
1376
1377static void ncm_unbind(struct usb_configuration *c, struct usb_function *f)
1378{
1379        struct f_ncm *ncm = func_to_ncm(f);
1380
1381        DBG(c->cdev, "ncm unbind\n");
1382
1383        usb_free_all_descriptors(f);
1384
1385        kfree(ncm->notify_req->buf);
1386        usb_ep_free_request(ncm->notify, ncm->notify_req);
1387}
1388
1389struct usb_function *ncm_alloc(struct usb_function_instance *fi)
1390{
1391        struct f_ncm            *ncm;
1392        struct f_ncm_opts       *opts;
1393        int status;
1394
1395        /* allocate and initialize one new instance */
1396        ncm = kzalloc(sizeof(*ncm), GFP_KERNEL);
1397        if (!ncm)
1398                return ERR_PTR(-ENOMEM);
1399
1400        opts = container_of(fi, struct f_ncm_opts, func_inst);
1401        mutex_lock(&opts->lock);
1402        opts->refcnt++;
1403
1404        /* export host's Ethernet address in CDC format */
1405        status = gether_get_host_addr_cdc(opts->net, ncm->ethaddr,
1406                                      sizeof(ncm->ethaddr));
1407        if (status < 12) { /* strlen("01234567890a") */
1408                kfree(ncm);
1409                mutex_unlock(&opts->lock);
1410                return ERR_PTR(-EINVAL);
1411        }
1412        ncm_string_defs[STRING_MAC_IDX].s = ncm->ethaddr;
1413
1414        spin_lock_init(&ncm->lock);
1415        ncm_reset_values(ncm);
1416        ncm->port.ioport = netdev_priv(opts->net);
1417        mutex_unlock(&opts->lock);
1418        ncm->port.is_fixed = true;
1419
1420        ncm->port.func.name = "cdc_network";
1421        /* descriptors are per-instance copies */
1422        ncm->port.func.bind = ncm_bind;
1423        ncm->port.func.unbind = ncm_unbind;
1424        ncm->port.func.set_alt = ncm_set_alt;
1425        ncm->port.func.get_alt = ncm_get_alt;
1426        ncm->port.func.setup = ncm_setup;
1427        ncm->port.func.disable = ncm_disable;
1428        ncm->port.func.free_func = ncm_free;
1429
1430        ncm->port.wrap = ncm_wrap_ntb;
1431        ncm->port.unwrap = ncm_unwrap_ntb;
1432
1433        return &ncm->port.func;
1434}
1435
1436DECLARE_USB_FUNCTION_INIT(ncm, ncm_alloc_inst, ncm_alloc);
1437MODULE_LICENSE("GPL");
1438MODULE_AUTHOR("Yauheni Kaliuta");
1439