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