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