qemu/hw/usb/dev-network.c
<<
>>
Prefs
   1/*
   2 * QEMU USB Net devices
   3 *
   4 * Copyright (c) 2006 Thomas Sailer
   5 * Copyright (c) 2008 Andrzej Zaborowski
   6 *
   7 * Permission is hereby granted, free of charge, to any person obtaining a copy
   8 * of this software and associated documentation files (the "Software"), to deal
   9 * in the Software without restriction, including without limitation the rights
  10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11 * copies of the Software, and to permit persons to whom the Software is
  12 * furnished to do so, subject to the following conditions:
  13 *
  14 * The above copyright notice and this permission notice shall be included in
  15 * all copies or substantial portions of the Software.
  16 *
  17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23 * THE SOFTWARE.
  24 */
  25
  26#include "qemu/osdep.h"
  27#include "qapi/error.h"
  28#include "hw/qdev-properties.h"
  29#include "hw/usb.h"
  30#include "migration/vmstate.h"
  31#include "desc.h"
  32#include "net/net.h"
  33#include "qemu/error-report.h"
  34#include "qemu/queue.h"
  35#include "qemu/config-file.h"
  36#include "sysemu/sysemu.h"
  37#include "qemu/iov.h"
  38#include "qemu/module.h"
  39#include "qemu/cutils.h"
  40#include "qom/object.h"
  41
  42/*#define TRAFFIC_DEBUG*/
  43/* Thanks to NetChip Technologies for donating this product ID.
  44 * It's for devices with only CDC Ethernet configurations.
  45 */
  46#define CDC_VENDOR_NUM          0x0525  /* NetChip */
  47#define CDC_PRODUCT_NUM         0xa4a1  /* Linux-USB Ethernet Gadget */
  48/* For hardware that can talk RNDIS and either of the above protocols,
  49 * use this ID ... the windows INF files will know it.
  50 */
  51#define RNDIS_VENDOR_NUM        0x0525  /* NetChip */
  52#define RNDIS_PRODUCT_NUM       0xa4a2  /* Ethernet/RNDIS Gadget */
  53
  54enum usbstring_idx {
  55    STRING_MANUFACTURER         = 1,
  56    STRING_PRODUCT,
  57    STRING_ETHADDR,
  58    STRING_DATA,
  59    STRING_CONTROL,
  60    STRING_RNDIS_CONTROL,
  61    STRING_CDC,
  62    STRING_SUBSET,
  63    STRING_RNDIS,
  64    STRING_SERIALNUMBER,
  65};
  66
  67#define DEV_CONFIG_VALUE                1       /* CDC or a subset */
  68#define DEV_RNDIS_CONFIG_VALUE          2       /* RNDIS; optional */
  69
  70#define USB_CDC_SUBCLASS_ACM            0x02
  71#define USB_CDC_SUBCLASS_ETHERNET       0x06
  72
  73#define USB_CDC_PROTO_NONE              0
  74#define USB_CDC_ACM_PROTO_VENDOR        0xff
  75
  76#define USB_CDC_HEADER_TYPE             0x00    /* header_desc */
  77#define USB_CDC_CALL_MANAGEMENT_TYPE    0x01    /* call_mgmt_descriptor */
  78#define USB_CDC_ACM_TYPE                0x02    /* acm_descriptor */
  79#define USB_CDC_UNION_TYPE              0x06    /* union_desc */
  80#define USB_CDC_ETHERNET_TYPE           0x0f    /* ether_desc */
  81
  82#define USB_CDC_SEND_ENCAPSULATED_COMMAND       0x00
  83#define USB_CDC_GET_ENCAPSULATED_RESPONSE       0x01
  84#define USB_CDC_REQ_SET_LINE_CODING             0x20
  85#define USB_CDC_REQ_GET_LINE_CODING             0x21
  86#define USB_CDC_REQ_SET_CONTROL_LINE_STATE      0x22
  87#define USB_CDC_REQ_SEND_BREAK                  0x23
  88#define USB_CDC_SET_ETHERNET_MULTICAST_FILTERS  0x40
  89#define USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER  0x41
  90#define USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER  0x42
  91#define USB_CDC_SET_ETHERNET_PACKET_FILTER      0x43
  92#define USB_CDC_GET_ETHERNET_STATISTIC          0x44
  93
  94#define LOG2_STATUS_INTERVAL_MSEC       5    /* 1 << 5 == 32 msec */
  95#define STATUS_BYTECOUNT                16   /* 8 byte header + data */
  96
  97#define ETH_FRAME_LEN                   1514 /* Max. octets in frame sans FCS */
  98
  99static const USBDescStrings usb_net_stringtable = {
 100    [STRING_MANUFACTURER]       = "QEMU",
 101    [STRING_PRODUCT]            = "RNDIS/QEMU USB Network Device",
 102    [STRING_ETHADDR]            = "400102030405",
 103    [STRING_DATA]               = "QEMU USB Net Data Interface",
 104    [STRING_CONTROL]            = "QEMU USB Net Control Interface",
 105    [STRING_RNDIS_CONTROL]      = "QEMU USB Net RNDIS Control Interface",
 106    [STRING_CDC]                = "QEMU USB Net CDC",
 107    [STRING_SUBSET]             = "QEMU USB Net Subset",
 108    [STRING_RNDIS]              = "QEMU USB Net RNDIS",
 109    [STRING_SERIALNUMBER]       = "1",
 110};
 111
 112static const USBDescIface desc_iface_rndis[] = {
 113    {
 114        /* RNDIS Control Interface */
 115        .bInterfaceNumber              = 0,
 116        .bNumEndpoints                 = 1,
 117        .bInterfaceClass               = USB_CLASS_COMM,
 118        .bInterfaceSubClass            = USB_CDC_SUBCLASS_ACM,
 119        .bInterfaceProtocol            = USB_CDC_ACM_PROTO_VENDOR,
 120        .iInterface                    = STRING_RNDIS_CONTROL,
 121        .ndesc                         = 4,
 122        .descs = (USBDescOther[]) {
 123            {
 124                /* Header Descriptor */
 125                .data = (uint8_t[]) {
 126                    0x05,                       /*  u8    bLength */
 127                    USB_DT_CS_INTERFACE,        /*  u8    bDescriptorType */
 128                    USB_CDC_HEADER_TYPE,        /*  u8    bDescriptorSubType */
 129                    0x10, 0x01,                 /*  le16  bcdCDC */
 130                },
 131            },{
 132                /* Call Management Descriptor */
 133                .data = (uint8_t[]) {
 134                    0x05,                       /*  u8    bLength */
 135                    USB_DT_CS_INTERFACE,        /*  u8    bDescriptorType */
 136                    USB_CDC_CALL_MANAGEMENT_TYPE, /*  u8    bDescriptorSubType */
 137                    0x00,                       /*  u8    bmCapabilities */
 138                    0x01,                       /*  u8    bDataInterface */
 139                },
 140            },{
 141                /* ACM Descriptor */
 142                .data = (uint8_t[]) {
 143                    0x04,                       /*  u8    bLength */
 144                    USB_DT_CS_INTERFACE,        /*  u8    bDescriptorType */
 145                    USB_CDC_ACM_TYPE,           /*  u8    bDescriptorSubType */
 146                    0x00,                       /*  u8    bmCapabilities */
 147                },
 148            },{
 149                /* Union Descriptor */
 150                .data = (uint8_t[]) {
 151                    0x05,                       /*  u8    bLength */
 152                    USB_DT_CS_INTERFACE,        /*  u8    bDescriptorType */
 153                    USB_CDC_UNION_TYPE,         /*  u8    bDescriptorSubType */
 154                    0x00,                       /*  u8    bMasterInterface0 */
 155                    0x01,                       /*  u8    bSlaveInterface0 */
 156                },
 157            },
 158        },
 159        .eps = (USBDescEndpoint[]) {
 160            {
 161                .bEndpointAddress      = USB_DIR_IN | 0x01,
 162                .bmAttributes          = USB_ENDPOINT_XFER_INT,
 163                .wMaxPacketSize        = STATUS_BYTECOUNT,
 164                .bInterval             = 1 << LOG2_STATUS_INTERVAL_MSEC,
 165            },
 166        }
 167    },{
 168        /* RNDIS Data Interface */
 169        .bInterfaceNumber              = 1,
 170        .bNumEndpoints                 = 2,
 171        .bInterfaceClass               = USB_CLASS_CDC_DATA,
 172        .iInterface                    = STRING_DATA,
 173        .eps = (USBDescEndpoint[]) {
 174            {
 175                .bEndpointAddress      = USB_DIR_IN | 0x02,
 176                .bmAttributes          = USB_ENDPOINT_XFER_BULK,
 177                .wMaxPacketSize        = 0x40,
 178            },{
 179                .bEndpointAddress      = USB_DIR_OUT | 0x02,
 180                .bmAttributes          = USB_ENDPOINT_XFER_BULK,
 181                .wMaxPacketSize        = 0x40,
 182            }
 183        }
 184    }
 185};
 186
 187static const USBDescIface desc_iface_cdc[] = {
 188    {
 189        /* CDC Control Interface */
 190        .bInterfaceNumber              = 0,
 191        .bNumEndpoints                 = 1,
 192        .bInterfaceClass               = USB_CLASS_COMM,
 193        .bInterfaceSubClass            = USB_CDC_SUBCLASS_ETHERNET,
 194        .bInterfaceProtocol            = USB_CDC_PROTO_NONE,
 195        .iInterface                    = STRING_CONTROL,
 196        .ndesc                         = 3,
 197        .descs = (USBDescOther[]) {
 198            {
 199                /* Header Descriptor */
 200                .data = (uint8_t[]) {
 201                    0x05,                       /*  u8    bLength */
 202                    USB_DT_CS_INTERFACE,        /*  u8    bDescriptorType */
 203                    USB_CDC_HEADER_TYPE,        /*  u8    bDescriptorSubType */
 204                    0x10, 0x01,                 /*  le16  bcdCDC */
 205                },
 206            },{
 207                /* Union Descriptor */
 208                .data = (uint8_t[]) {
 209                    0x05,                       /*  u8    bLength */
 210                    USB_DT_CS_INTERFACE,        /*  u8    bDescriptorType */
 211                    USB_CDC_UNION_TYPE,         /*  u8    bDescriptorSubType */
 212                    0x00,                       /*  u8    bMasterInterface0 */
 213                    0x01,                       /*  u8    bSlaveInterface0 */
 214                },
 215            },{
 216                /* Ethernet Descriptor */
 217                .data = (uint8_t[]) {
 218                    0x0d,                       /*  u8    bLength */
 219                    USB_DT_CS_INTERFACE,        /*  u8    bDescriptorType */
 220                    USB_CDC_ETHERNET_TYPE,      /*  u8    bDescriptorSubType */
 221                    STRING_ETHADDR,             /*  u8    iMACAddress */
 222                    0x00, 0x00, 0x00, 0x00,     /*  le32  bmEthernetStatistics */
 223                    ETH_FRAME_LEN & 0xff,
 224                    ETH_FRAME_LEN >> 8,         /*  le16  wMaxSegmentSize */
 225                    0x00, 0x00,                 /*  le16  wNumberMCFilters */
 226                    0x00,                       /*  u8    bNumberPowerFilters */
 227                },
 228            },
 229        },
 230        .eps = (USBDescEndpoint[]) {
 231            {
 232                .bEndpointAddress      = USB_DIR_IN | 0x01,
 233                .bmAttributes          = USB_ENDPOINT_XFER_INT,
 234                .wMaxPacketSize        = STATUS_BYTECOUNT,
 235                .bInterval             = 1 << LOG2_STATUS_INTERVAL_MSEC,
 236            },
 237        }
 238    },{
 239        /* CDC Data Interface (off) */
 240        .bInterfaceNumber              = 1,
 241        .bAlternateSetting             = 0,
 242        .bNumEndpoints                 = 0,
 243        .bInterfaceClass               = USB_CLASS_CDC_DATA,
 244    },{
 245        /* CDC Data Interface */
 246        .bInterfaceNumber              = 1,
 247        .bAlternateSetting             = 1,
 248        .bNumEndpoints                 = 2,
 249        .bInterfaceClass               = USB_CLASS_CDC_DATA,
 250        .iInterface                    = STRING_DATA,
 251        .eps = (USBDescEndpoint[]) {
 252            {
 253                .bEndpointAddress      = USB_DIR_IN | 0x02,
 254                .bmAttributes          = USB_ENDPOINT_XFER_BULK,
 255                .wMaxPacketSize        = 0x40,
 256            },{
 257                .bEndpointAddress      = USB_DIR_OUT | 0x02,
 258                .bmAttributes          = USB_ENDPOINT_XFER_BULK,
 259                .wMaxPacketSize        = 0x40,
 260            }
 261        }
 262    }
 263};
 264
 265static const USBDescDevice desc_device_net = {
 266    .bcdUSB                        = 0x0200,
 267    .bDeviceClass                  = USB_CLASS_COMM,
 268    .bMaxPacketSize0               = 0x40,
 269    .bNumConfigurations            = 2,
 270    .confs = (USBDescConfig[]) {
 271        {
 272            .bNumInterfaces        = 2,
 273            .bConfigurationValue   = DEV_RNDIS_CONFIG_VALUE,
 274            .iConfiguration        = STRING_RNDIS,
 275            .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_SELFPOWER,
 276            .bMaxPower             = 0x32,
 277            .nif = ARRAY_SIZE(desc_iface_rndis),
 278            .ifs = desc_iface_rndis,
 279        },{
 280            .bNumInterfaces        = 2,
 281            .bConfigurationValue   = DEV_CONFIG_VALUE,
 282            .iConfiguration        = STRING_CDC,
 283            .bmAttributes          = USB_CFG_ATT_ONE | USB_CFG_ATT_SELFPOWER,
 284            .bMaxPower             = 0x32,
 285            .nif = ARRAY_SIZE(desc_iface_cdc),
 286            .ifs = desc_iface_cdc,
 287        }
 288    },
 289};
 290
 291static const USBDesc desc_net = {
 292    .id = {
 293        .idVendor          = RNDIS_VENDOR_NUM,
 294        .idProduct         = RNDIS_PRODUCT_NUM,
 295        .bcdDevice         = 0,
 296        .iManufacturer     = STRING_MANUFACTURER,
 297        .iProduct          = STRING_PRODUCT,
 298        .iSerialNumber     = STRING_SERIALNUMBER,
 299    },
 300    .full = &desc_device_net,
 301    .str  = usb_net_stringtable,
 302};
 303
 304/*
 305 * RNDIS Definitions - in theory not specific to USB.
 306 */
 307#define RNDIS_MAXIMUM_FRAME_SIZE        1518
 308#define RNDIS_MAX_TOTAL_SIZE            1558
 309
 310/* Remote NDIS Versions */
 311#define RNDIS_MAJOR_VERSION             1
 312#define RNDIS_MINOR_VERSION             0
 313
 314/* Status Values */
 315#define RNDIS_STATUS_SUCCESS            0x00000000U /* Success */
 316#define RNDIS_STATUS_FAILURE            0xc0000001U /* Unspecified error */
 317#define RNDIS_STATUS_INVALID_DATA       0xc0010015U /* Invalid data */
 318#define RNDIS_STATUS_NOT_SUPPORTED      0xc00000bbU /* Unsupported request */
 319#define RNDIS_STATUS_MEDIA_CONNECT      0x4001000bU /* Device connected */
 320#define RNDIS_STATUS_MEDIA_DISCONNECT   0x4001000cU /* Device disconnected */
 321
 322/* Message Set for Connectionless (802.3) Devices */
 323enum {
 324    RNDIS_PACKET_MSG            = 1,
 325    RNDIS_INITIALIZE_MSG        = 2,    /* Initialize device */
 326    RNDIS_HALT_MSG              = 3,
 327    RNDIS_QUERY_MSG             = 4,
 328    RNDIS_SET_MSG               = 5,
 329    RNDIS_RESET_MSG             = 6,
 330    RNDIS_INDICATE_STATUS_MSG   = 7,
 331    RNDIS_KEEPALIVE_MSG         = 8,
 332};
 333
 334/* Message completion */
 335enum {
 336    RNDIS_INITIALIZE_CMPLT      = 0x80000002U,
 337    RNDIS_QUERY_CMPLT           = 0x80000004U,
 338    RNDIS_SET_CMPLT             = 0x80000005U,
 339    RNDIS_RESET_CMPLT           = 0x80000006U,
 340    RNDIS_KEEPALIVE_CMPLT       = 0x80000008U,
 341};
 342
 343/* Device Flags */
 344enum {
 345    RNDIS_DF_CONNECTIONLESS     = 1,
 346    RNDIS_DF_CONNECTIONORIENTED = 2,
 347};
 348
 349#define RNDIS_MEDIUM_802_3              0x00000000U
 350
 351/* from drivers/net/sk98lin/h/skgepnmi.h */
 352#define OID_PNP_CAPABILITIES            0xfd010100
 353#define OID_PNP_SET_POWER               0xfd010101
 354#define OID_PNP_QUERY_POWER             0xfd010102
 355#define OID_PNP_ADD_WAKE_UP_PATTERN     0xfd010103
 356#define OID_PNP_REMOVE_WAKE_UP_PATTERN  0xfd010104
 357#define OID_PNP_ENABLE_WAKE_UP          0xfd010106
 358
 359typedef uint32_t le32;
 360
 361typedef struct rndis_init_msg_type {
 362    le32 MessageType;
 363    le32 MessageLength;
 364    le32 RequestID;
 365    le32 MajorVersion;
 366    le32 MinorVersion;
 367    le32 MaxTransferSize;
 368} rndis_init_msg_type;
 369
 370typedef struct rndis_init_cmplt_type {
 371    le32 MessageType;
 372    le32 MessageLength;
 373    le32 RequestID;
 374    le32 Status;
 375    le32 MajorVersion;
 376    le32 MinorVersion;
 377    le32 DeviceFlags;
 378    le32 Medium;
 379    le32 MaxPacketsPerTransfer;
 380    le32 MaxTransferSize;
 381    le32 PacketAlignmentFactor;
 382    le32 AFListOffset;
 383    le32 AFListSize;
 384} rndis_init_cmplt_type;
 385
 386typedef struct rndis_halt_msg_type {
 387    le32 MessageType;
 388    le32 MessageLength;
 389    le32 RequestID;
 390} rndis_halt_msg_type;
 391
 392typedef struct rndis_query_msg_type {
 393    le32 MessageType;
 394    le32 MessageLength;
 395    le32 RequestID;
 396    le32 OID;
 397    le32 InformationBufferLength;
 398    le32 InformationBufferOffset;
 399    le32 DeviceVcHandle;
 400} rndis_query_msg_type;
 401
 402typedef struct rndis_query_cmplt_type {
 403    le32 MessageType;
 404    le32 MessageLength;
 405    le32 RequestID;
 406    le32 Status;
 407    le32 InformationBufferLength;
 408    le32 InformationBufferOffset;
 409} rndis_query_cmplt_type;
 410
 411typedef struct rndis_set_msg_type {
 412    le32 MessageType;
 413    le32 MessageLength;
 414    le32 RequestID;
 415    le32 OID;
 416    le32 InformationBufferLength;
 417    le32 InformationBufferOffset;
 418    le32 DeviceVcHandle;
 419} rndis_set_msg_type;
 420
 421typedef struct rndis_set_cmplt_type {
 422    le32 MessageType;
 423    le32 MessageLength;
 424    le32 RequestID;
 425    le32 Status;
 426} rndis_set_cmplt_type;
 427
 428typedef struct rndis_reset_msg_type {
 429    le32 MessageType;
 430    le32 MessageLength;
 431    le32 Reserved;
 432} rndis_reset_msg_type;
 433
 434typedef struct rndis_reset_cmplt_type {
 435    le32 MessageType;
 436    le32 MessageLength;
 437    le32 Status;
 438    le32 AddressingReset;
 439} rndis_reset_cmplt_type;
 440
 441typedef struct rndis_indicate_status_msg_type {
 442    le32 MessageType;
 443    le32 MessageLength;
 444    le32 Status;
 445    le32 StatusBufferLength;
 446    le32 StatusBufferOffset;
 447} rndis_indicate_status_msg_type;
 448
 449typedef struct rndis_keepalive_msg_type {
 450    le32 MessageType;
 451    le32 MessageLength;
 452    le32 RequestID;
 453} rndis_keepalive_msg_type;
 454
 455typedef struct rndis_keepalive_cmplt_type {
 456    le32 MessageType;
 457    le32 MessageLength;
 458    le32 RequestID;
 459    le32 Status;
 460} rndis_keepalive_cmplt_type;
 461
 462struct rndis_packet_msg_type {
 463    le32 MessageType;
 464    le32 MessageLength;
 465    le32 DataOffset;
 466    le32 DataLength;
 467    le32 OOBDataOffset;
 468    le32 OOBDataLength;
 469    le32 NumOOBDataElements;
 470    le32 PerPacketInfoOffset;
 471    le32 PerPacketInfoLength;
 472    le32 VcHandle;
 473    le32 Reserved;
 474};
 475
 476struct rndis_config_parameter {
 477    le32 ParameterNameOffset;
 478    le32 ParameterNameLength;
 479    le32 ParameterType;
 480    le32 ParameterValueOffset;
 481    le32 ParameterValueLength;
 482};
 483
 484/* implementation specific */
 485enum rndis_state
 486{
 487    RNDIS_UNINITIALIZED,
 488    RNDIS_INITIALIZED,
 489    RNDIS_DATA_INITIALIZED,
 490};
 491
 492/* from ndis.h */
 493enum ndis_oid {
 494    /* Required Object IDs (OIDs) */
 495    OID_GEN_SUPPORTED_LIST              = 0x00010101,
 496    OID_GEN_HARDWARE_STATUS             = 0x00010102,
 497    OID_GEN_MEDIA_SUPPORTED             = 0x00010103,
 498    OID_GEN_MEDIA_IN_USE                = 0x00010104,
 499    OID_GEN_MAXIMUM_LOOKAHEAD           = 0x00010105,
 500    OID_GEN_MAXIMUM_FRAME_SIZE          = 0x00010106,
 501    OID_GEN_LINK_SPEED                  = 0x00010107,
 502    OID_GEN_TRANSMIT_BUFFER_SPACE       = 0x00010108,
 503    OID_GEN_RECEIVE_BUFFER_SPACE        = 0x00010109,
 504    OID_GEN_TRANSMIT_BLOCK_SIZE         = 0x0001010a,
 505    OID_GEN_RECEIVE_BLOCK_SIZE          = 0x0001010b,
 506    OID_GEN_VENDOR_ID                   = 0x0001010c,
 507    OID_GEN_VENDOR_DESCRIPTION          = 0x0001010d,
 508    OID_GEN_CURRENT_PACKET_FILTER       = 0x0001010e,
 509    OID_GEN_CURRENT_LOOKAHEAD           = 0x0001010f,
 510    OID_GEN_DRIVER_VERSION              = 0x00010110,
 511    OID_GEN_MAXIMUM_TOTAL_SIZE          = 0x00010111,
 512    OID_GEN_PROTOCOL_OPTIONS            = 0x00010112,
 513    OID_GEN_MAC_OPTIONS                 = 0x00010113,
 514    OID_GEN_MEDIA_CONNECT_STATUS        = 0x00010114,
 515    OID_GEN_MAXIMUM_SEND_PACKETS        = 0x00010115,
 516    OID_GEN_VENDOR_DRIVER_VERSION       = 0x00010116,
 517    OID_GEN_SUPPORTED_GUIDS             = 0x00010117,
 518    OID_GEN_NETWORK_LAYER_ADDRESSES     = 0x00010118,
 519    OID_GEN_TRANSPORT_HEADER_OFFSET     = 0x00010119,
 520    OID_GEN_MACHINE_NAME                = 0x0001021a,
 521    OID_GEN_RNDIS_CONFIG_PARAMETER      = 0x0001021b,
 522    OID_GEN_VLAN_ID                     = 0x0001021c,
 523
 524    /* Optional OIDs */
 525    OID_GEN_MEDIA_CAPABILITIES          = 0x00010201,
 526    OID_GEN_PHYSICAL_MEDIUM             = 0x00010202,
 527
 528    /* Required statistics OIDs */
 529    OID_GEN_XMIT_OK                     = 0x00020101,
 530    OID_GEN_RCV_OK                      = 0x00020102,
 531    OID_GEN_XMIT_ERROR                  = 0x00020103,
 532    OID_GEN_RCV_ERROR                   = 0x00020104,
 533    OID_GEN_RCV_NO_BUFFER               = 0x00020105,
 534
 535    /* Optional statistics OIDs */
 536    OID_GEN_DIRECTED_BYTES_XMIT         = 0x00020201,
 537    OID_GEN_DIRECTED_FRAMES_XMIT        = 0x00020202,
 538    OID_GEN_MULTICAST_BYTES_XMIT        = 0x00020203,
 539    OID_GEN_MULTICAST_FRAMES_XMIT       = 0x00020204,
 540    OID_GEN_BROADCAST_BYTES_XMIT        = 0x00020205,
 541    OID_GEN_BROADCAST_FRAMES_XMIT       = 0x00020206,
 542    OID_GEN_DIRECTED_BYTES_RCV          = 0x00020207,
 543    OID_GEN_DIRECTED_FRAMES_RCV         = 0x00020208,
 544    OID_GEN_MULTICAST_BYTES_RCV         = 0x00020209,
 545    OID_GEN_MULTICAST_FRAMES_RCV        = 0x0002020a,
 546    OID_GEN_BROADCAST_BYTES_RCV         = 0x0002020b,
 547    OID_GEN_BROADCAST_FRAMES_RCV        = 0x0002020c,
 548    OID_GEN_RCV_CRC_ERROR               = 0x0002020d,
 549    OID_GEN_TRANSMIT_QUEUE_LENGTH       = 0x0002020e,
 550    OID_GEN_GET_TIME_CAPS               = 0x0002020f,
 551    OID_GEN_GET_NETCARD_TIME            = 0x00020210,
 552    OID_GEN_NETCARD_LOAD                = 0x00020211,
 553    OID_GEN_DEVICE_PROFILE              = 0x00020212,
 554    OID_GEN_INIT_TIME_MS                = 0x00020213,
 555    OID_GEN_RESET_COUNTS                = 0x00020214,
 556    OID_GEN_MEDIA_SENSE_COUNTS          = 0x00020215,
 557    OID_GEN_FRIENDLY_NAME               = 0x00020216,
 558    OID_GEN_MINIPORT_INFO               = 0x00020217,
 559    OID_GEN_RESET_VERIFY_PARAMETERS     = 0x00020218,
 560
 561    /* IEEE 802.3 (Ethernet) OIDs */
 562    OID_802_3_PERMANENT_ADDRESS         = 0x01010101,
 563    OID_802_3_CURRENT_ADDRESS           = 0x01010102,
 564    OID_802_3_MULTICAST_LIST            = 0x01010103,
 565    OID_802_3_MAXIMUM_LIST_SIZE         = 0x01010104,
 566    OID_802_3_MAC_OPTIONS               = 0x01010105,
 567    OID_802_3_RCV_ERROR_ALIGNMENT       = 0x01020101,
 568    OID_802_3_XMIT_ONE_COLLISION        = 0x01020102,
 569    OID_802_3_XMIT_MORE_COLLISIONS      = 0x01020103,
 570    OID_802_3_XMIT_DEFERRED             = 0x01020201,
 571    OID_802_3_XMIT_MAX_COLLISIONS       = 0x01020202,
 572    OID_802_3_RCV_OVERRUN               = 0x01020203,
 573    OID_802_3_XMIT_UNDERRUN             = 0x01020204,
 574    OID_802_3_XMIT_HEARTBEAT_FAILURE    = 0x01020205,
 575    OID_802_3_XMIT_TIMES_CRS_LOST       = 0x01020206,
 576    OID_802_3_XMIT_LATE_COLLISIONS      = 0x01020207,
 577};
 578
 579static const uint32_t oid_supported_list[] =
 580{
 581    /* the general stuff */
 582    OID_GEN_SUPPORTED_LIST,
 583    OID_GEN_HARDWARE_STATUS,
 584    OID_GEN_MEDIA_SUPPORTED,
 585    OID_GEN_MEDIA_IN_USE,
 586    OID_GEN_MAXIMUM_FRAME_SIZE,
 587    OID_GEN_LINK_SPEED,
 588    OID_GEN_TRANSMIT_BLOCK_SIZE,
 589    OID_GEN_RECEIVE_BLOCK_SIZE,
 590    OID_GEN_VENDOR_ID,
 591    OID_GEN_VENDOR_DESCRIPTION,
 592    OID_GEN_VENDOR_DRIVER_VERSION,
 593    OID_GEN_CURRENT_PACKET_FILTER,
 594    OID_GEN_MAXIMUM_TOTAL_SIZE,
 595    OID_GEN_MEDIA_CONNECT_STATUS,
 596    OID_GEN_PHYSICAL_MEDIUM,
 597
 598    /* the statistical stuff */
 599    OID_GEN_XMIT_OK,
 600    OID_GEN_RCV_OK,
 601    OID_GEN_XMIT_ERROR,
 602    OID_GEN_RCV_ERROR,
 603    OID_GEN_RCV_NO_BUFFER,
 604
 605    /* IEEE 802.3 */
 606    /* the general stuff */
 607    OID_802_3_PERMANENT_ADDRESS,
 608    OID_802_3_CURRENT_ADDRESS,
 609    OID_802_3_MULTICAST_LIST,
 610    OID_802_3_MAC_OPTIONS,
 611    OID_802_3_MAXIMUM_LIST_SIZE,
 612
 613    /* the statistical stuff */
 614    OID_802_3_RCV_ERROR_ALIGNMENT,
 615    OID_802_3_XMIT_ONE_COLLISION,
 616    OID_802_3_XMIT_MORE_COLLISIONS,
 617};
 618
 619#define NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA     (1 << 0)
 620#define NDIS_MAC_OPTION_RECEIVE_SERIALIZED      (1 << 1)
 621#define NDIS_MAC_OPTION_TRANSFERS_NOT_PEND      (1 << 2)
 622#define NDIS_MAC_OPTION_NO_LOOPBACK             (1 << 3)
 623#define NDIS_MAC_OPTION_FULL_DUPLEX             (1 << 4)
 624#define NDIS_MAC_OPTION_EOTX_INDICATION         (1 << 5)
 625#define NDIS_MAC_OPTION_8021P_PRIORITY          (1 << 6)
 626
 627struct rndis_response {
 628    QTAILQ_ENTRY(rndis_response) entries;
 629    uint32_t length;
 630    uint8_t buf[];
 631};
 632
 633struct USBNetState {
 634    USBDevice dev;
 635
 636    enum rndis_state rndis_state;
 637    uint32_t medium;
 638    uint32_t speed;
 639    uint32_t media_state;
 640    uint16_t filter;
 641    uint32_t vendorid;
 642
 643    unsigned int out_ptr;
 644    uint8_t out_buf[2048];
 645
 646    unsigned int in_ptr, in_len;
 647    uint8_t in_buf[2048];
 648
 649    USBEndpoint *intr;
 650
 651    char usbstring_mac[13];
 652    NICState *nic;
 653    NICConf conf;
 654    QTAILQ_HEAD(, rndis_response) rndis_resp;
 655};
 656
 657#define TYPE_USB_NET "usb-net"
 658OBJECT_DECLARE_SIMPLE_TYPE(USBNetState, USB_NET)
 659
 660static int is_rndis(USBNetState *s)
 661{
 662    return s->dev.config ?
 663            s->dev.config->bConfigurationValue == DEV_RNDIS_CONFIG_VALUE : 0;
 664}
 665
 666static int ndis_query(USBNetState *s, uint32_t oid,
 667                      uint8_t *inbuf, unsigned int inlen, uint8_t *outbuf,
 668                      size_t outlen)
 669{
 670    unsigned int i;
 671
 672    switch (oid) {
 673    /* general oids (table 4-1) */
 674    /* mandatory */
 675    case OID_GEN_SUPPORTED_LIST:
 676        for (i = 0; i < ARRAY_SIZE(oid_supported_list); i++) {
 677            stl_le_p(outbuf + (i * sizeof(le32)), oid_supported_list[i]);
 678        }
 679        return sizeof(oid_supported_list);
 680
 681    /* mandatory */
 682    case OID_GEN_HARDWARE_STATUS:
 683        stl_le_p(outbuf, 0);
 684        return sizeof(le32);
 685
 686    /* mandatory */
 687    case OID_GEN_MEDIA_SUPPORTED:
 688        stl_le_p(outbuf, s->medium);
 689        return sizeof(le32);
 690
 691    /* mandatory */
 692    case OID_GEN_MEDIA_IN_USE:
 693        stl_le_p(outbuf, s->medium);
 694        return sizeof(le32);
 695
 696    /* mandatory */
 697    case OID_GEN_MAXIMUM_FRAME_SIZE:
 698        stl_le_p(outbuf, ETH_FRAME_LEN);
 699        return sizeof(le32);
 700
 701    /* mandatory */
 702    case OID_GEN_LINK_SPEED:
 703        stl_le_p(outbuf, s->speed);
 704        return sizeof(le32);
 705
 706    /* mandatory */
 707    case OID_GEN_TRANSMIT_BLOCK_SIZE:
 708        stl_le_p(outbuf, ETH_FRAME_LEN);
 709        return sizeof(le32);
 710
 711    /* mandatory */
 712    case OID_GEN_RECEIVE_BLOCK_SIZE:
 713        stl_le_p(outbuf, ETH_FRAME_LEN);
 714        return sizeof(le32);
 715
 716    /* mandatory */
 717    case OID_GEN_VENDOR_ID:
 718        stl_le_p(outbuf, s->vendorid);
 719        return sizeof(le32);
 720
 721    /* mandatory */
 722    case OID_GEN_VENDOR_DESCRIPTION:
 723        pstrcpy((char *)outbuf, outlen, "QEMU USB RNDIS Net");
 724        return strlen((char *)outbuf) + 1;
 725
 726    case OID_GEN_VENDOR_DRIVER_VERSION:
 727        stl_le_p(outbuf, 1);
 728        return sizeof(le32);
 729
 730    /* mandatory */
 731    case OID_GEN_CURRENT_PACKET_FILTER:
 732        stl_le_p(outbuf, s->filter);
 733        return sizeof(le32);
 734
 735    /* mandatory */
 736    case OID_GEN_MAXIMUM_TOTAL_SIZE:
 737        stl_le_p(outbuf, RNDIS_MAX_TOTAL_SIZE);
 738        return sizeof(le32);
 739
 740    /* mandatory */
 741    case OID_GEN_MEDIA_CONNECT_STATUS:
 742        stl_le_p(outbuf, s->media_state);
 743        return sizeof(le32);
 744
 745    case OID_GEN_PHYSICAL_MEDIUM:
 746        stl_le_p(outbuf, 0);
 747        return sizeof(le32);
 748
 749    case OID_GEN_MAC_OPTIONS:
 750        stl_le_p(outbuf, NDIS_MAC_OPTION_RECEIVE_SERIALIZED |
 751                 NDIS_MAC_OPTION_FULL_DUPLEX);
 752        return sizeof(le32);
 753
 754    /* statistics OIDs (table 4-2) */
 755    /* mandatory */
 756    case OID_GEN_XMIT_OK:
 757        stl_le_p(outbuf, 0);
 758        return sizeof(le32);
 759
 760    /* mandatory */
 761    case OID_GEN_RCV_OK:
 762        stl_le_p(outbuf, 0);
 763        return sizeof(le32);
 764
 765    /* mandatory */
 766    case OID_GEN_XMIT_ERROR:
 767        stl_le_p(outbuf, 0);
 768        return sizeof(le32);
 769
 770    /* mandatory */
 771    case OID_GEN_RCV_ERROR:
 772        stl_le_p(outbuf, 0);
 773        return sizeof(le32);
 774
 775    /* mandatory */
 776    case OID_GEN_RCV_NO_BUFFER:
 777        stl_le_p(outbuf, 0);
 778        return sizeof(le32);
 779
 780    /* ieee802.3 OIDs (table 4-3) */
 781    /* mandatory */
 782    case OID_802_3_PERMANENT_ADDRESS:
 783        memcpy(outbuf, s->conf.macaddr.a, 6);
 784        return 6;
 785
 786    /* mandatory */
 787    case OID_802_3_CURRENT_ADDRESS:
 788        memcpy(outbuf, s->conf.macaddr.a, 6);
 789        return 6;
 790
 791    /* mandatory */
 792    case OID_802_3_MULTICAST_LIST:
 793        stl_le_p(outbuf, 0xe0000000);
 794        return sizeof(le32);
 795
 796    /* mandatory */
 797    case OID_802_3_MAXIMUM_LIST_SIZE:
 798        stl_le_p(outbuf, 1);
 799        return sizeof(le32);
 800
 801    case OID_802_3_MAC_OPTIONS:
 802        return 0;
 803
 804    /* ieee802.3 statistics OIDs (table 4-4) */
 805    /* mandatory */
 806    case OID_802_3_RCV_ERROR_ALIGNMENT:
 807        stl_le_p(outbuf, 0);
 808        return sizeof(le32);
 809
 810    /* mandatory */
 811    case OID_802_3_XMIT_ONE_COLLISION:
 812        stl_le_p(outbuf, 0);
 813        return sizeof(le32);
 814
 815    /* mandatory */
 816    case OID_802_3_XMIT_MORE_COLLISIONS:
 817        stl_le_p(outbuf, 0);
 818        return sizeof(le32);
 819
 820    default:
 821        fprintf(stderr, "usbnet: unknown OID 0x%08x\n", oid);
 822        return 0;
 823    }
 824    return -1;
 825}
 826
 827static int ndis_set(USBNetState *s, uint32_t oid,
 828                uint8_t *inbuf, unsigned int inlen)
 829{
 830    switch (oid) {
 831    case OID_GEN_CURRENT_PACKET_FILTER:
 832        s->filter = ldl_le_p(inbuf);
 833        if (s->filter) {
 834            s->rndis_state = RNDIS_DATA_INITIALIZED;
 835        } else {
 836            s->rndis_state = RNDIS_INITIALIZED;
 837        }
 838        return 0;
 839
 840    case OID_802_3_MULTICAST_LIST:
 841        return 0;
 842    }
 843    return -1;
 844}
 845
 846static int rndis_get_response(USBNetState *s, uint8_t *buf)
 847{
 848    int ret = 0;
 849    struct rndis_response *r = s->rndis_resp.tqh_first;
 850
 851    if (!r)
 852        return ret;
 853
 854    QTAILQ_REMOVE(&s->rndis_resp, r, entries);
 855    ret = r->length;
 856    memcpy(buf, r->buf, r->length);
 857    g_free(r);
 858
 859    return ret;
 860}
 861
 862static void *rndis_queue_response(USBNetState *s, unsigned int length)
 863{
 864    struct rndis_response *r =
 865            g_malloc0(sizeof(struct rndis_response) + length);
 866
 867    if (QTAILQ_EMPTY(&s->rndis_resp)) {
 868        usb_wakeup(s->intr, 0);
 869    }
 870
 871    QTAILQ_INSERT_TAIL(&s->rndis_resp, r, entries);
 872    r->length = length;
 873
 874    return &r->buf[0];
 875}
 876
 877static void rndis_clear_responsequeue(USBNetState *s)
 878{
 879    struct rndis_response *r;
 880
 881    while ((r = s->rndis_resp.tqh_first)) {
 882        QTAILQ_REMOVE(&s->rndis_resp, r, entries);
 883        g_free(r);
 884    }
 885}
 886
 887static int rndis_init_response(USBNetState *s, rndis_init_msg_type *buf)
 888{
 889    rndis_init_cmplt_type *resp =
 890            rndis_queue_response(s, sizeof(rndis_init_cmplt_type));
 891
 892    if (!resp)
 893        return USB_RET_STALL;
 894
 895    resp->MessageType = cpu_to_le32(RNDIS_INITIALIZE_CMPLT);
 896    resp->MessageLength = cpu_to_le32(sizeof(rndis_init_cmplt_type));
 897    resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
 898    resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
 899    resp->MajorVersion = cpu_to_le32(RNDIS_MAJOR_VERSION);
 900    resp->MinorVersion = cpu_to_le32(RNDIS_MINOR_VERSION);
 901    resp->DeviceFlags = cpu_to_le32(RNDIS_DF_CONNECTIONLESS);
 902    resp->Medium = cpu_to_le32(RNDIS_MEDIUM_802_3);
 903    resp->MaxPacketsPerTransfer = cpu_to_le32(1);
 904    resp->MaxTransferSize = cpu_to_le32(ETH_FRAME_LEN +
 905                    sizeof(struct rndis_packet_msg_type) + 22);
 906    resp->PacketAlignmentFactor = cpu_to_le32(0);
 907    resp->AFListOffset = cpu_to_le32(0);
 908    resp->AFListSize = cpu_to_le32(0);
 909    return 0;
 910}
 911
 912static int rndis_query_response(USBNetState *s,
 913                rndis_query_msg_type *buf, unsigned int length)
 914{
 915    rndis_query_cmplt_type *resp;
 916    /* oid_supported_list is the largest data reply */
 917    uint8_t infobuf[sizeof(oid_supported_list)];
 918    uint32_t bufoffs, buflen;
 919    int infobuflen;
 920    unsigned int resplen;
 921
 922    bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
 923    buflen = le32_to_cpu(buf->InformationBufferLength);
 924    if (buflen > length || bufoffs >= length || bufoffs + buflen > length) {
 925        return USB_RET_STALL;
 926    }
 927
 928    infobuflen = ndis_query(s, le32_to_cpu(buf->OID),
 929                            bufoffs + (uint8_t *) buf, buflen, infobuf,
 930                            sizeof(infobuf));
 931    resplen = sizeof(rndis_query_cmplt_type) +
 932            ((infobuflen < 0) ? 0 : infobuflen);
 933    resp = rndis_queue_response(s, resplen);
 934    if (!resp)
 935        return USB_RET_STALL;
 936
 937    resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT);
 938    resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
 939    resp->MessageLength = cpu_to_le32(resplen);
 940
 941    if (infobuflen < 0) {
 942        /* OID not supported */
 943        resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
 944        resp->InformationBufferLength = cpu_to_le32(0);
 945        resp->InformationBufferOffset = cpu_to_le32(0);
 946        return 0;
 947    }
 948
 949    resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
 950    resp->InformationBufferOffset =
 951            cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0);
 952    resp->InformationBufferLength = cpu_to_le32(infobuflen);
 953    memcpy(resp + 1, infobuf, infobuflen);
 954
 955    return 0;
 956}
 957
 958static int rndis_set_response(USBNetState *s,
 959                rndis_set_msg_type *buf, unsigned int length)
 960{
 961    rndis_set_cmplt_type *resp =
 962            rndis_queue_response(s, sizeof(rndis_set_cmplt_type));
 963    uint32_t bufoffs, buflen;
 964    int ret;
 965
 966    if (!resp)
 967        return USB_RET_STALL;
 968
 969    bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
 970    buflen = le32_to_cpu(buf->InformationBufferLength);
 971    if (buflen > length || bufoffs >= length || bufoffs + buflen > length) {
 972        return USB_RET_STALL;
 973    }
 974
 975    ret = ndis_set(s, le32_to_cpu(buf->OID),
 976                    bufoffs + (uint8_t *) buf, buflen);
 977    resp->MessageType = cpu_to_le32(RNDIS_SET_CMPLT);
 978    resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
 979    resp->MessageLength = cpu_to_le32(sizeof(rndis_set_cmplt_type));
 980    if (ret < 0) {
 981        /* OID not supported */
 982        resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
 983        return 0;
 984    }
 985    resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
 986
 987    return 0;
 988}
 989
 990static int rndis_reset_response(USBNetState *s, rndis_reset_msg_type *buf)
 991{
 992    rndis_reset_cmplt_type *resp =
 993            rndis_queue_response(s, sizeof(rndis_reset_cmplt_type));
 994
 995    if (!resp)
 996        return USB_RET_STALL;
 997
 998    resp->MessageType = cpu_to_le32(RNDIS_RESET_CMPLT);
 999    resp->MessageLength = cpu_to_le32(sizeof(rndis_reset_cmplt_type));
1000    resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
1001    resp->AddressingReset = cpu_to_le32(1); /* reset information */
1002
1003    return 0;
1004}
1005
1006static int rndis_keepalive_response(USBNetState *s,
1007                rndis_keepalive_msg_type *buf)
1008{
1009    rndis_keepalive_cmplt_type *resp =
1010            rndis_queue_response(s, sizeof(rndis_keepalive_cmplt_type));
1011
1012    if (!resp)
1013        return USB_RET_STALL;
1014
1015    resp->MessageType = cpu_to_le32(RNDIS_KEEPALIVE_CMPLT);
1016    resp->MessageLength = cpu_to_le32(sizeof(rndis_keepalive_cmplt_type));
1017    resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
1018    resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
1019
1020    return 0;
1021}
1022
1023/* Prepare to receive the next packet */
1024static void usb_net_reset_in_buf(USBNetState *s)
1025{
1026    s->in_ptr = s->in_len = 0;
1027    qemu_flush_queued_packets(qemu_get_queue(s->nic));
1028}
1029
1030static int rndis_parse(USBNetState *s, uint8_t *data, int length)
1031{
1032    uint32_t msg_type = ldl_le_p(data);
1033
1034    switch (msg_type) {
1035    case RNDIS_INITIALIZE_MSG:
1036        s->rndis_state = RNDIS_INITIALIZED;
1037        return rndis_init_response(s, (rndis_init_msg_type *) data);
1038
1039    case RNDIS_HALT_MSG:
1040        s->rndis_state = RNDIS_UNINITIALIZED;
1041        return 0;
1042
1043    case RNDIS_QUERY_MSG:
1044        return rndis_query_response(s, (rndis_query_msg_type *) data, length);
1045
1046    case RNDIS_SET_MSG:
1047        return rndis_set_response(s, (rndis_set_msg_type *) data, length);
1048
1049    case RNDIS_RESET_MSG:
1050        rndis_clear_responsequeue(s);
1051        s->out_ptr = 0;
1052        usb_net_reset_in_buf(s);
1053        return rndis_reset_response(s, (rndis_reset_msg_type *) data);
1054
1055    case RNDIS_KEEPALIVE_MSG:
1056        /* For USB: host does this every 5 seconds */
1057        return rndis_keepalive_response(s, (rndis_keepalive_msg_type *) data);
1058    }
1059
1060    return USB_RET_STALL;
1061}
1062
1063static void usb_net_handle_reset(USBDevice *dev)
1064{
1065}
1066
1067static void usb_net_handle_control(USBDevice *dev, USBPacket *p,
1068               int request, int value, int index, int length, uint8_t *data)
1069{
1070    USBNetState *s = (USBNetState *) dev;
1071    int ret;
1072
1073    ret = usb_desc_handle_control(dev, p, request, value, index, length, data);
1074    if (ret >= 0) {
1075        return;
1076    }
1077
1078    switch(request) {
1079    case ClassInterfaceOutRequest | USB_CDC_SEND_ENCAPSULATED_COMMAND:
1080        if (!is_rndis(s) || value || index != 0) {
1081            goto fail;
1082        }
1083#ifdef TRAFFIC_DEBUG
1084        {
1085            unsigned int i;
1086            fprintf(stderr, "SEND_ENCAPSULATED_COMMAND:");
1087            for (i = 0; i < length; i++) {
1088                if (!(i & 15))
1089                    fprintf(stderr, "\n%04x:", i);
1090                fprintf(stderr, " %02x", data[i]);
1091            }
1092            fprintf(stderr, "\n\n");
1093        }
1094#endif
1095        ret = rndis_parse(s, data, length);
1096        if (ret < 0) {
1097            p->status = ret;
1098        }
1099        break;
1100
1101    case ClassInterfaceRequest | USB_CDC_GET_ENCAPSULATED_RESPONSE:
1102        if (!is_rndis(s) || value || index != 0) {
1103            goto fail;
1104        }
1105        p->actual_length = rndis_get_response(s, data);
1106        if (p->actual_length == 0) {
1107            data[0] = 0;
1108            p->actual_length = 1;
1109        }
1110#ifdef TRAFFIC_DEBUG
1111        {
1112            unsigned int i;
1113            fprintf(stderr, "GET_ENCAPSULATED_RESPONSE:");
1114            for (i = 0; i < p->actual_length; i++) {
1115                if (!(i & 15))
1116                    fprintf(stderr, "\n%04x:", i);
1117                fprintf(stderr, " %02x", data[i]);
1118            }
1119            fprintf(stderr, "\n\n");
1120        }
1121#endif
1122        break;
1123
1124    default:
1125    fail:
1126        fprintf(stderr, "usbnet: failed control transaction: "
1127                        "request 0x%x value 0x%x index 0x%x length 0x%x\n",
1128                        request, value, index, length);
1129        p->status = USB_RET_STALL;
1130        break;
1131    }
1132}
1133
1134static void usb_net_handle_statusin(USBNetState *s, USBPacket *p)
1135{
1136    le32 buf[2];
1137
1138    if (p->iov.size < 8) {
1139        p->status = USB_RET_STALL;
1140        return;
1141    }
1142
1143    buf[0] = cpu_to_le32(1);
1144    buf[1] = cpu_to_le32(0);
1145    usb_packet_copy(p, buf, 8);
1146    if (!s->rndis_resp.tqh_first) {
1147        p->status = USB_RET_NAK;
1148    }
1149
1150#ifdef TRAFFIC_DEBUG
1151    fprintf(stderr, "usbnet: interrupt poll len %zu return %d",
1152            p->iov.size, p->status);
1153    iov_hexdump(p->iov.iov, p->iov.niov, stderr, "usbnet", p->status);
1154#endif
1155}
1156
1157static void usb_net_handle_datain(USBNetState *s, USBPacket *p)
1158{
1159    int len;
1160
1161    if (s->in_ptr > s->in_len) {
1162        usb_net_reset_in_buf(s);
1163        p->status = USB_RET_NAK;
1164        return;
1165    }
1166    if (!s->in_len) {
1167        p->status = USB_RET_NAK;
1168        return;
1169    }
1170    len = s->in_len - s->in_ptr;
1171    if (len > p->iov.size) {
1172        len = p->iov.size;
1173    }
1174    usb_packet_copy(p, &s->in_buf[s->in_ptr], len);
1175    s->in_ptr += len;
1176    if (s->in_ptr >= s->in_len &&
1177                    (is_rndis(s) || (s->in_len & (64 - 1)) || !len)) {
1178        /* no short packet necessary */
1179        usb_net_reset_in_buf(s);
1180    }
1181
1182#ifdef TRAFFIC_DEBUG
1183    fprintf(stderr, "usbnet: data in len %zu return %d", p->iov.size, len);
1184    iov_hexdump(p->iov.iov, p->iov.niov, stderr, "usbnet", len);
1185#endif
1186}
1187
1188static void usb_net_handle_dataout(USBNetState *s, USBPacket *p)
1189{
1190    int sz = sizeof(s->out_buf) - s->out_ptr;
1191    struct rndis_packet_msg_type *msg =
1192            (struct rndis_packet_msg_type *) s->out_buf;
1193    uint32_t len;
1194
1195#ifdef TRAFFIC_DEBUG
1196    fprintf(stderr, "usbnet: data out len %zu\n", p->iov.size);
1197    iov_hexdump(p->iov.iov, p->iov.niov, stderr, "usbnet", p->iov.size);
1198#endif
1199
1200    if (sz > p->iov.size) {
1201        sz = p->iov.size;
1202    }
1203    usb_packet_copy(p, &s->out_buf[s->out_ptr], sz);
1204    s->out_ptr += sz;
1205
1206    if (!is_rndis(s)) {
1207        if (p->iov.size < 64) {
1208            qemu_send_packet(qemu_get_queue(s->nic), s->out_buf, s->out_ptr);
1209            s->out_ptr = 0;
1210        }
1211        return;
1212    }
1213    len = le32_to_cpu(msg->MessageLength);
1214    if (s->out_ptr < 8 || s->out_ptr < len) {
1215        return;
1216    }
1217    if (le32_to_cpu(msg->MessageType) == RNDIS_PACKET_MSG) {
1218        uint32_t offs = 8 + le32_to_cpu(msg->DataOffset);
1219        uint32_t size = le32_to_cpu(msg->DataLength);
1220        if (offs < len && size < len && offs + size <= len) {
1221            qemu_send_packet(qemu_get_queue(s->nic), s->out_buf + offs, size);
1222        }
1223    }
1224    s->out_ptr -= len;
1225    memmove(s->out_buf, &s->out_buf[len], s->out_ptr);
1226}
1227
1228static void usb_net_handle_data(USBDevice *dev, USBPacket *p)
1229{
1230    USBNetState *s = (USBNetState *) dev;
1231
1232    switch(p->pid) {
1233    case USB_TOKEN_IN:
1234        switch (p->ep->nr) {
1235        case 1:
1236            usb_net_handle_statusin(s, p);
1237            break;
1238
1239        case 2:
1240            usb_net_handle_datain(s, p);
1241            break;
1242
1243        default:
1244            goto fail;
1245        }
1246        break;
1247
1248    case USB_TOKEN_OUT:
1249        switch (p->ep->nr) {
1250        case 2:
1251            usb_net_handle_dataout(s, p);
1252            break;
1253
1254        default:
1255            goto fail;
1256        }
1257        break;
1258
1259    default:
1260    fail:
1261        p->status = USB_RET_STALL;
1262        break;
1263    }
1264
1265    if (p->status == USB_RET_STALL) {
1266        fprintf(stderr, "usbnet: failed data transaction: "
1267                        "pid 0x%x ep 0x%x len 0x%zx\n",
1268                        p->pid, p->ep->nr, p->iov.size);
1269    }
1270}
1271
1272static ssize_t usbnet_receive(NetClientState *nc, const uint8_t *buf, size_t size)
1273{
1274    USBNetState *s = qemu_get_nic_opaque(nc);
1275    uint8_t *in_buf = s->in_buf;
1276    size_t total_size = size;
1277
1278    if (!s->dev.config) {
1279        return -1;
1280    }
1281
1282    if (is_rndis(s)) {
1283        if (s->rndis_state != RNDIS_DATA_INITIALIZED) {
1284            return -1;
1285        }
1286        total_size += sizeof(struct rndis_packet_msg_type);
1287    }
1288    if (total_size > sizeof(s->in_buf)) {
1289        return -1;
1290    }
1291
1292    /* Only accept packet if input buffer is empty */
1293    if (s->in_len > 0) {
1294        return 0;
1295    }
1296
1297    if (is_rndis(s)) {
1298        struct rndis_packet_msg_type *msg;
1299
1300        msg = (struct rndis_packet_msg_type *)in_buf;
1301        memset(msg, 0, sizeof(struct rndis_packet_msg_type));
1302        msg->MessageType = cpu_to_le32(RNDIS_PACKET_MSG);
1303        msg->MessageLength = cpu_to_le32(size + sizeof(*msg));
1304        msg->DataOffset = cpu_to_le32(sizeof(*msg) - 8);
1305        msg->DataLength = cpu_to_le32(size);
1306        /* msg->OOBDataOffset;
1307         * msg->OOBDataLength;
1308         * msg->NumOOBDataElements;
1309         * msg->PerPacketInfoOffset;
1310         * msg->PerPacketInfoLength;
1311         * msg->VcHandle;
1312         * msg->Reserved;
1313         */
1314        in_buf += sizeof(*msg);
1315    }
1316
1317    memcpy(in_buf, buf, size);
1318    s->in_len = total_size;
1319    s->in_ptr = 0;
1320    return size;
1321}
1322
1323static void usbnet_cleanup(NetClientState *nc)
1324{
1325    USBNetState *s = qemu_get_nic_opaque(nc);
1326
1327    s->nic = NULL;
1328}
1329
1330static void usb_net_unrealize(USBDevice *dev)
1331{
1332    USBNetState *s = (USBNetState *) dev;
1333
1334    /* TODO: remove the nd_table[] entry */
1335    rndis_clear_responsequeue(s);
1336    qemu_del_nic(s->nic);
1337}
1338
1339static NetClientInfo net_usbnet_info = {
1340    .type = NET_CLIENT_DRIVER_NIC,
1341    .size = sizeof(NICState),
1342    .receive = usbnet_receive,
1343    .cleanup = usbnet_cleanup,
1344};
1345
1346static void usb_net_realize(USBDevice *dev, Error **errp)
1347{
1348    USBNetState *s = USB_NET(dev);
1349
1350    usb_desc_create_serial(dev);
1351    usb_desc_init(dev);
1352
1353    s->rndis_state = RNDIS_UNINITIALIZED;
1354    QTAILQ_INIT(&s->rndis_resp);
1355
1356    s->medium = 0;      /* NDIS_MEDIUM_802_3 */
1357    s->speed = 1000000; /* 100MBps, in 100Bps units */
1358    s->media_state = 0; /* NDIS_MEDIA_STATE_CONNECTED */;
1359    s->filter = 0;
1360    s->vendorid = 0x1234;
1361    s->intr = usb_ep_get(dev, USB_TOKEN_IN, 1);
1362
1363    qemu_macaddr_default_if_unset(&s->conf.macaddr);
1364    s->nic = qemu_new_nic(&net_usbnet_info, &s->conf,
1365                          object_get_typename(OBJECT(s)), s->dev.qdev.id, s);
1366    qemu_format_nic_info_str(qemu_get_queue(s->nic), s->conf.macaddr.a);
1367    snprintf(s->usbstring_mac, sizeof(s->usbstring_mac),
1368             "%02x%02x%02x%02x%02x%02x",
1369             0x40,
1370             s->conf.macaddr.a[1],
1371             s->conf.macaddr.a[2],
1372             s->conf.macaddr.a[3],
1373             s->conf.macaddr.a[4],
1374             s->conf.macaddr.a[5]);
1375    usb_desc_set_string(dev, STRING_ETHADDR, s->usbstring_mac);
1376}
1377
1378static void usb_net_instance_init(Object *obj)
1379{
1380    USBDevice *dev = USB_DEVICE(obj);
1381    USBNetState *s = USB_NET(dev);
1382
1383    device_add_bootindex_property(obj, &s->conf.bootindex,
1384                                  "bootindex", "/ethernet-phy@0",
1385                                  &dev->qdev);
1386}
1387
1388static const VMStateDescription vmstate_usb_net = {
1389    .name = "usb-net",
1390    .unmigratable = 1,
1391};
1392
1393static Property net_properties[] = {
1394    DEFINE_NIC_PROPERTIES(USBNetState, conf),
1395    DEFINE_PROP_END_OF_LIST(),
1396};
1397
1398static void usb_net_class_initfn(ObjectClass *klass, void *data)
1399{
1400    DeviceClass *dc = DEVICE_CLASS(klass);
1401    USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
1402
1403    uc->realize        = usb_net_realize;
1404    uc->product_desc   = "QEMU USB Network Interface";
1405    uc->usb_desc       = &desc_net;
1406    uc->handle_reset   = usb_net_handle_reset;
1407    uc->handle_control = usb_net_handle_control;
1408    uc->handle_data    = usb_net_handle_data;
1409    uc->unrealize      = usb_net_unrealize;
1410    set_bit(DEVICE_CATEGORY_NETWORK, dc->categories);
1411    dc->fw_name = "network";
1412    dc->vmsd = &vmstate_usb_net;
1413    device_class_set_props(dc, net_properties);
1414}
1415
1416static const TypeInfo net_info = {
1417    .name          = TYPE_USB_NET,
1418    .parent        = TYPE_USB_DEVICE,
1419    .instance_size = sizeof(USBNetState),
1420    .class_init    = usb_net_class_initfn,
1421    .instance_init = usb_net_instance_init,
1422};
1423
1424static void usb_net_register_types(void)
1425{
1426    type_register_static(&net_info);
1427}
1428
1429type_init(usb_net_register_types)
1430