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