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