aboutsummaryrefslogtreecommitdiff
path: root/hw/usb-net.c
blob: c49fd62a41b89d9561960db107af501d3b6d2b6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
/*
 * QEMU USB Net devices
 *
 * Copyright (c) 2006 Thomas Sailer
 * Copyright (c) 2008 Andrzej Zaborowski
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "qemu-common.h"
#include "usb.h"
#include "net.h"
#include "sys-queue.h"

/*#define TRAFFIC_DEBUG*/
/* Thanks to NetChip Technologies for donating this product ID.
 * It's for devices with only CDC Ethernet configurations.
 */
#define CDC_VENDOR_NUM          0x0525  /* NetChip */
#define CDC_PRODUCT_NUM         0xa4a1  /* Linux-USB Ethernet Gadget */
/* For hardware that can talk RNDIS and either of the above protocols,
 * use this ID ... the windows INF files will know it.
 */
#define RNDIS_VENDOR_NUM        0x0525  /* NetChip */
#define RNDIS_PRODUCT_NUM       0xa4a2  /* Ethernet/RNDIS Gadget */

enum usbstring_idx {
    STRING_MANUFACTURER		= 1,
    STRING_PRODUCT,
    STRING_ETHADDR,
    STRING_DATA,
    STRING_CONTROL,
    STRING_RNDIS_CONTROL,
    STRING_CDC,
    STRING_SUBSET,
    STRING_RNDIS,
    STRING_SERIALNUMBER,
};

#define DEV_CONFIG_VALUE		1	/* CDC or a subset */
#define DEV_RNDIS_CONFIG_VALUE		2	/* RNDIS; optional */

#define USB_CDC_SUBCLASS_ACM		0x02
#define USB_CDC_SUBCLASS_ETHERNET	0x06

#define USB_CDC_PROTO_NONE		0
#define USB_CDC_ACM_PROTO_VENDOR	0xff

#define USB_CDC_HEADER_TYPE		0x00	/* header_desc */
#define USB_CDC_CALL_MANAGEMENT_TYPE	0x01	/* call_mgmt_descriptor */
#define USB_CDC_ACM_TYPE		0x02	/* acm_descriptor */
#define USB_CDC_UNION_TYPE		0x06	/* union_desc */
#define USB_CDC_ETHERNET_TYPE		0x0f	/* ether_desc */

#define USB_DT_CS_INTERFACE		0x24
#define USB_DT_CS_ENDPOINT		0x25

#define ClassInterfaceRequest		\
    ((USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)
#define ClassInterfaceOutRequest	\
    ((USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE) << 8)

#define USB_CDC_SEND_ENCAPSULATED_COMMAND	0x00
#define USB_CDC_GET_ENCAPSULATED_RESPONSE	0x01
#define USB_CDC_REQ_SET_LINE_CODING		0x20
#define USB_CDC_REQ_GET_LINE_CODING		0x21
#define USB_CDC_REQ_SET_CONTROL_LINE_STATE	0x22
#define USB_CDC_REQ_SEND_BREAK			0x23
#define USB_CDC_SET_ETHERNET_MULTICAST_FILTERS	0x40
#define USB_CDC_SET_ETHERNET_PM_PATTERN_FILTER	0x41
#define USB_CDC_GET_ETHERNET_PM_PATTERN_FILTER	0x42
#define USB_CDC_SET_ETHERNET_PACKET_FILTER	0x43
#define USB_CDC_GET_ETHERNET_STATISTIC		0x44

#define LOG2_STATUS_INTERVAL_MSEC	5    /* 1 << 5 == 32 msec */
#define STATUS_BYTECOUNT		16   /* 8 byte header + data */

#define ETH_FRAME_LEN			1514 /* Max. octets in frame sans FCS */

/*
 * mostly the same descriptor as the linux gadget rndis driver
 */
static const uint8_t qemu_net_dev_descriptor[] = {
    0x12,			/*  u8 bLength; */
    USB_DT_DEVICE,		/*  u8 bDescriptorType; Device */
    0x00, 0x02,			/*  u16 bcdUSB; v2.0 */
    USB_CLASS_COMM,		/*  u8  bDeviceClass; */
    0x00,			/*  u8  bDeviceSubClass; */
    0x00,			/*  u8  bDeviceProtocol; [ low/full only ] */
    0x40,			/*  u8  bMaxPacketSize0 */
    RNDIS_VENDOR_NUM & 0xff, RNDIS_VENDOR_NUM >> 8,	/*  u16 idVendor; */
    RNDIS_PRODUCT_NUM & 0xff, RNDIS_PRODUCT_NUM >> 8,	/*  u16 idProduct; */
    0x00, 0x00,			/*  u16 bcdDevice */
    STRING_MANUFACTURER,	/*  u8  iManufacturer; */
    STRING_PRODUCT,		/*  u8  iProduct; */
    STRING_SERIALNUMBER,	/*  u8  iSerialNumber; */
    0x02,			/*  u8  bNumConfigurations; */
};

static const uint8_t qemu_net_rndis_config_descriptor[] = {
    /* Configuration Descriptor */
    0x09,			/*  u8  bLength */
    USB_DT_CONFIG,		/*  u8  bDescriptorType */
    0x43, 0x00,			/*  le16 wTotalLength */
    0x02,			/*  u8  bNumInterfaces */
    DEV_RNDIS_CONFIG_VALUE,	/*  u8  bConfigurationValue */
    STRING_RNDIS,		/*  u8  iConfiguration */
    0xc0,			/*  u8  bmAttributes */
    0x32,			/*  u8  bMaxPower */
    /* RNDIS Control Interface */
    0x09,			/*  u8  bLength */
    USB_DT_INTERFACE,		/*  u8  bDescriptorType */
    0x00,			/*  u8  bInterfaceNumber */
    0x00,			/*  u8  bAlternateSetting */
    0x01,			/*  u8  bNumEndpoints */
    USB_CLASS_COMM,		/*  u8  bInterfaceClass */
    USB_CDC_SUBCLASS_ACM,	/*  u8  bInterfaceSubClass */
    USB_CDC_ACM_PROTO_VENDOR,	/*  u8  bInterfaceProtocol */
    STRING_RNDIS_CONTROL,	/*  u8  iInterface */
    /* Header Descriptor */
    0x05,			/*  u8    bLength */
    USB_DT_CS_INTERFACE,	/*  u8    bDescriptorType */
    USB_CDC_HEADER_TYPE,	/*  u8    bDescriptorSubType */
    0x10, 0x01,			/*  le16  bcdCDC */
    /* Call Management Descriptor */
    0x05,			/*  u8    bLength */
    USB_DT_CS_INTERFACE,	/*  u8    bDescriptorType */
    USB_CDC_CALL_MANAGEMENT_TYPE,	/*  u8    bDescriptorSubType */
    0x00,			/*  u8    bmCapabilities */
    0x01,			/*  u8    bDataInterface */
    /* ACM Descriptor */
    0x04,			/*  u8    bLength */
    USB_DT_CS_INTERFACE,	/*  u8    bDescriptorType */
    USB_CDC_ACM_TYPE,		/*  u8    bDescriptorSubType */
    0x00,			/*  u8    bmCapabilities */
    /* Union Descriptor */
    0x05,			/*  u8    bLength */
    USB_DT_CS_INTERFACE,	/*  u8    bDescriptorType */
    USB_CDC_UNION_TYPE,		/*  u8    bDescriptorSubType */
    0x00,			/*  u8    bMasterInterface0 */
    0x01,			/*  u8    bSlaveInterface0 */
    /* Status Descriptor */
    0x07,			/*  u8  bLength */
    USB_DT_ENDPOINT,		/*  u8  bDescriptorType */
    USB_DIR_IN | 1,		/*  u8  bEndpointAddress */
    USB_ENDPOINT_XFER_INT,	/*  u8  bmAttributes */
    STATUS_BYTECOUNT & 0xff, STATUS_BYTECOUNT >> 8, /*  le16 wMaxPacketSize */
    1 << LOG2_STATUS_INTERVAL_MSEC,	/*  u8  bInterval */
    /* RNDIS Data Interface */
    0x09,			/*  u8  bLength */
    USB_DT_INTERFACE,		/*  u8  bDescriptorType */
    0x01,			/*  u8  bInterfaceNumber */
    0x00,			/*  u8  bAlternateSetting */
    0x02,			/*  u8  bNumEndpoints */
    USB_CLASS_CDC_DATA,		/*  u8  bInterfaceClass */
    0x00,			/*  u8  bInterfaceSubClass */
    0x00,			/*  u8  bInterfaceProtocol */
    STRING_DATA,		/*  u8  iInterface */
    /* Source Endpoint */
    0x07,			/*  u8  bLength */
    USB_DT_ENDPOINT,		/*  u8  bDescriptorType */
    USB_DIR_IN | 2,		/*  u8  bEndpointAddress */
    USB_ENDPOINT_XFER_BULK,	/*  u8  bmAttributes */
    0x40, 0x00,			/*  le16 wMaxPacketSize */
    0x00,			/*  u8  bInterval */
    /* Sink Endpoint */
    0x07,			/*  u8  bLength */
    USB_DT_ENDPOINT,		/*  u8  bDescriptorType */
    USB_DIR_OUT | 2,		/*  u8  bEndpointAddress */
    USB_ENDPOINT_XFER_BULK,	/*  u8  bmAttributes */
    0x40, 0x00,			/*  le16 wMaxPacketSize */
    0x00			/*  u8  bInterval */
};

static const uint8_t qemu_net_cdc_config_descriptor[] = {
    /* Configuration Descriptor */
    0x09,			/*  u8  bLength */
    USB_DT_CONFIG,		/*  u8  bDescriptorType */
    0x50, 0x00,			/*  le16 wTotalLength */
    0x02,			/*  u8  bNumInterfaces */
    DEV_CONFIG_VALUE,		/*  u8  bConfigurationValue */
    STRING_CDC,			/*  u8  iConfiguration */
    0xc0,			/*  u8  bmAttributes */
    0x32,			/*  u8  bMaxPower */
    /* CDC Control Interface */
    0x09,			/*  u8  bLength */
    USB_DT_INTERFACE,		/*  u8  bDescriptorType */
    0x00,			/*  u8  bInterfaceNumber */
    0x00,			/*  u8  bAlternateSetting */
    0x01,			/*  u8  bNumEndpoints */
    USB_CLASS_COMM,		/*  u8  bInterfaceClass */
    USB_CDC_SUBCLASS_ETHERNET,	/*  u8  bInterfaceSubClass */
    USB_CDC_PROTO_NONE,		/*  u8  bInterfaceProtocol */
    STRING_CONTROL,		/*  u8  iInterface */
    /* Header Descriptor */
    0x05,			/*  u8    bLength */
    USB_DT_CS_INTERFACE,	/*  u8    bDescriptorType */
    USB_CDC_HEADER_TYPE,	/*  u8    bDescriptorSubType */
    0x10, 0x01,			/*  le16  bcdCDC */
    /* Union Descriptor */
    0x05,			/*  u8    bLength */
    USB_DT_CS_INTERFACE,	/*  u8    bDescriptorType */
    USB_CDC_UNION_TYPE,		/*  u8    bDescriptorSubType */
    0x00,			/*  u8    bMasterInterface0 */
    0x01,			/*  u8    bSlaveInterface0 */
    /* Ethernet Descriptor */
    0x0d,			/*  u8    bLength */
    USB_DT_CS_INTERFACE,	/*  u8    bDescriptorType */
    USB_CDC_ETHERNET_TYPE,	/*  u8    bDescriptorSubType */
    STRING_ETHADDR,		/*  u8    iMACAddress */
    0x00, 0x00, 0x00, 0x00,	/*  le32  bmEthernetStatistics */
    ETH_FRAME_LEN & 0xff, ETH_FRAME_LEN >> 8,	/*  le16  wMaxSegmentSize */
    0x00, 0x00,			/*  le16  wNumberMCFilters */
    0x00,			/*  u8    bNumberPowerFilters */
    /* Status Descriptor */
    0x07,			/*  u8  bLength */
    USB_DT_ENDPOINT,		/*  u8  bDescriptorType */
    USB_DIR_IN | 1,		/*  u8  bEndpointAddress */
    USB_ENDPOINT_XFER_INT,	/*  u8  bmAttributes */
    STATUS_BYTECOUNT & 0xff, STATUS_BYTECOUNT >> 8, /*  le16 wMaxPacketSize */
    1 << LOG2_STATUS_INTERVAL_MSEC,	/*  u8  bInterval */
    /* CDC Data (nop) Interface */
    0x09,			/*  u8  bLength */
    USB_DT_INTERFACE,		/*  u8  bDescriptorType */
    0x01,			/*  u8  bInterfaceNumber */
    0x00,			/*  u8  bAlternateSetting */
    0x00,			/*  u8  bNumEndpoints */
    USB_CLASS_CDC_DATA,		/*  u8  bInterfaceClass */
    0x00,			/*  u8  bInterfaceSubClass */
    0x00,			/*  u8  bInterfaceProtocol */
    0x00,			/*  u8  iInterface */
    /* CDC Data Interface */
    0x09,			/*  u8  bLength */
    USB_DT_INTERFACE,		/*  u8  bDescriptorType */
    0x01,			/*  u8  bInterfaceNumber */
    0x01,			/*  u8  bAlternateSetting */
    0x02,			/*  u8  bNumEndpoints */
    USB_CLASS_CDC_DATA,		/*  u8  bInterfaceClass */
    0x00,			/*  u8  bInterfaceSubClass */
    0x00,			/*  u8  bInterfaceProtocol */
    STRING_DATA,		/*  u8  iInterface */
    /* Source Endpoint */
    0x07,			/*  u8  bLength */
    USB_DT_ENDPOINT,		/*  u8  bDescriptorType */
    USB_DIR_IN | 2,		/*  u8  bEndpointAddress */
    USB_ENDPOINT_XFER_BULK,	/*  u8  bmAttributes */
    0x40, 0x00,			/*  le16 wMaxPacketSize */
    0x00,			/*  u8  bInterval */
    /* Sink Endpoint */
    0x07,			/*  u8  bLength */
    USB_DT_ENDPOINT,		/*  u8  bDescriptorType */
    USB_DIR_OUT | 2,		/*  u8  bEndpointAddress */
    USB_ENDPOINT_XFER_BULK,	/*  u8  bmAttributes */
    0x40, 0x00,			/*  le16 wMaxPacketSize */
    0x00			/*  u8  bInterval */
};

/*
 * RNDIS Definitions - in theory not specific to USB.
 */
#define RNDIS_MAXIMUM_FRAME_SIZE	1518
#define RNDIS_MAX_TOTAL_SIZE		1558

/* Remote NDIS Versions */
#define RNDIS_MAJOR_VERSION		1
#define RNDIS_MINOR_VERSION		0

/* Status Values */
#define RNDIS_STATUS_SUCCESS		0x00000000U /* Success */
#define RNDIS_STATUS_FAILURE		0xc0000001U /* Unspecified error */
#define RNDIS_STATUS_INVALID_DATA	0xc0010015U /* Invalid data */
#define RNDIS_STATUS_NOT_SUPPORTED	0xc00000bbU /* Unsupported request */
#define RNDIS_STATUS_MEDIA_CONNECT	0x4001000bU /* Device connected */
#define RNDIS_STATUS_MEDIA_DISCONNECT	0x4001000cU /* Device disconnected */

/* Message Set for Connectionless (802.3) Devices */
enum {
    RNDIS_PACKET_MSG		= 1,
    RNDIS_INITIALIZE_MSG	= 2,	/* Initialize device */
    RNDIS_HALT_MSG		= 3,
    RNDIS_QUERY_MSG		= 4,
    RNDIS_SET_MSG		= 5,
    RNDIS_RESET_MSG		= 6,
    RNDIS_INDICATE_STATUS_MSG	= 7,
    RNDIS_KEEPALIVE_MSG		= 8,
};

/* Message completion */
enum {
    RNDIS_INITIALIZE_CMPLT	= 0x80000002U,
    RNDIS_QUERY_CMPLT		= 0x80000004U,
    RNDIS_SET_CMPLT		= 0x80000005U,
    RNDIS_RESET_CMPLT		= 0x80000006U,
    RNDIS_KEEPALIVE_CMPLT	= 0x80000008U,
};

/* Device Flags */
enum {
    RNDIS_DF_CONNECTIONLESS	= 1,
    RNDIS_DF_CONNECTIONORIENTED	= 2,
};

#define RNDIS_MEDIUM_802_3		0x00000000U

/* from drivers/net/sk98lin/h/skgepnmi.h */
#define OID_PNP_CAPABILITIES		0xfd010100
#define OID_PNP_SET_POWER		0xfd010101
#define OID_PNP_QUERY_POWER		0xfd010102
#define OID_PNP_ADD_WAKE_UP_PATTERN	0xfd010103
#define OID_PNP_REMOVE_WAKE_UP_PATTERN	0xfd010104
#define OID_PNP_ENABLE_WAKE_UP		0xfd010106

typedef uint32_t le32;

typedef struct rndis_init_msg_type {
    le32 MessageType;
    le32 MessageLength;
    le32 RequestID;
    le32 MajorVersion;
    le32 MinorVersion;
    le32 MaxTransferSize;
} rndis_init_msg_type;

typedef struct rndis_init_cmplt_type {
    le32 MessageType;
    le32 MessageLength;
    le32 RequestID;
    le32 Status;
    le32 MajorVersion;
    le32 MinorVersion;
    le32 DeviceFlags;
    le32 Medium;
    le32 MaxPacketsPerTransfer;
    le32 MaxTransferSize;
    le32 PacketAlignmentFactor;
    le32 AFListOffset;
    le32 AFListSize;
} rndis_init_cmplt_type;

typedef struct rndis_halt_msg_type {
    le32 MessageType;
    le32 MessageLength;
    le32 RequestID;
} rndis_halt_msg_type;

typedef struct rndis_query_msg_type {
    le32 MessageType;
    le32 MessageLength;
    le32 RequestID;
    le32 OID;
    le32 InformationBufferLength;
    le32 InformationBufferOffset;
    le32 DeviceVcHandle;
} rndis_query_msg_type;

typedef struct rndis_query_cmplt_type {
    le32 MessageType;
    le32 MessageLength;
    le32 RequestID;
    le32 Status;
    le32 InformationBufferLength;
    le32 InformationBufferOffset;
} rndis_query_cmplt_type;

typedef struct rndis_set_msg_type {
    le32 MessageType;
    le32 MessageLength;
    le32 RequestID;
    le32 OID;
    le32 InformationBufferLength;
    le32 InformationBufferOffset;
    le32 DeviceVcHandle;
} rndis_set_msg_type;

typedef struct rndis_set_cmplt_type {
    le32 MessageType;
    le32 MessageLength;
    le32 RequestID;
    le32 Status;
} rndis_set_cmplt_type;

typedef struct rndis_reset_msg_type {
    le32 MessageType;
    le32 MessageLength;
    le32 Reserved;
} rndis_reset_msg_type;

typedef struct rndis_reset_cmplt_type {
    le32 MessageType;
    le32 MessageLength;
    le32 Status;
    le32 AddressingReset;
} rndis_reset_cmplt_type;

typedef struct rndis_indicate_status_msg_type {
    le32 MessageType;
    le32 MessageLength;
    le32 Status;
    le32 StatusBufferLength;
    le32 StatusBufferOffset;
} rndis_indicate_status_msg_type;

typedef struct rndis_keepalive_msg_type {
    le32 MessageType;
    le32 MessageLength;
    le32 RequestID;
} rndis_keepalive_msg_type;

typedef struct rndis_keepalive_cmplt_type {
    le32 MessageType;
    le32 MessageLength;
    le32 RequestID;
    le32 Status;
} rndis_keepalive_cmplt_type;

struct rndis_packet_msg_type {
    le32 MessageType;
    le32 MessageLength;
    le32 DataOffset;
    le32 DataLength;
    le32 OOBDataOffset;
    le32 OOBDataLength;
    le32 NumOOBDataElements;
    le32 PerPacketInfoOffset;
    le32 PerPacketInfoLength;
    le32 VcHandle;
    le32 Reserved;
};

struct rndis_config_parameter {
    le32 ParameterNameOffset;
    le32 ParameterNameLength;
    le32 ParameterType;
    le32 ParameterValueOffset;
    le32 ParameterValueLength;
};

/* implementation specific */
enum rndis_state
{
    RNDIS_UNINITIALIZED,
    RNDIS_INITIALIZED,
    RNDIS_DATA_INITIALIZED,
};

/* from ndis.h */
enum ndis_oid {
    /* Required Object IDs (OIDs) */
    OID_GEN_SUPPORTED_LIST		= 0x00010101,
    OID_GEN_HARDWARE_STATUS		= 0x00010102,
    OID_GEN_MEDIA_SUPPORTED		= 0x00010103,
    OID_GEN_MEDIA_IN_USE		= 0x00010104,
    OID_GEN_MAXIMUM_LOOKAHEAD		= 0x00010105,
    OID_GEN_MAXIMUM_FRAME_SIZE		= 0x00010106,
    OID_GEN_LINK_SPEED			= 0x00010107,
    OID_GEN_TRANSMIT_BUFFER_SPACE	= 0x00010108,
    OID_GEN_RECEIVE_BUFFER_SPACE	= 0x00010109,
    OID_GEN_TRANSMIT_BLOCK_SIZE		= 0x0001010a,
    OID_GEN_RECEIVE_BLOCK_SIZE		= 0x0001010b,
    OID_GEN_VENDOR_ID			= 0x0001010c,
    OID_GEN_VENDOR_DESCRIPTION		= 0x0001010d,
    OID_GEN_CURRENT_PACKET_FILTER	= 0x0001010e,
    OID_GEN_CURRENT_LOOKAHEAD		= 0x0001010f,
    OID_GEN_DRIVER_VERSION		= 0x00010110,
    OID_GEN_MAXIMUM_TOTAL_SIZE		= 0x00010111,
    OID_GEN_PROTOCOL_OPTIONS		= 0x00010112,
    OID_GEN_MAC_OPTIONS			= 0x00010113,
    OID_GEN_MEDIA_CONNECT_STATUS	= 0x00010114,
    OID_GEN_MAXIMUM_SEND_PACKETS	= 0x00010115,
    OID_GEN_VENDOR_DRIVER_VERSION	= 0x00010116,
    OID_GEN_SUPPORTED_GUIDS		= 0x00010117,
    OID_GEN_NETWORK_LAYER_ADDRESSES	= 0x00010118,
    OID_GEN_TRANSPORT_HEADER_OFFSET	= 0x00010119,
    OID_GEN_MACHINE_NAME		= 0x0001021a,
    OID_GEN_RNDIS_CONFIG_PARAMETER	= 0x0001021b,
    OID_GEN_VLAN_ID			= 0x0001021c,

    /* Optional OIDs */
    OID_GEN_MEDIA_CAPABILITIES		= 0x00010201,
    OID_GEN_PHYSICAL_MEDIUM		= 0x00010202,

    /* Required statistics OIDs */
    OID_GEN_XMIT_OK			= 0x00020101,
    OID_GEN_RCV_OK			= 0x00020102,
    OID_GEN_XMIT_ERROR			= 0x00020103,
    OID_GEN_RCV_ERROR			= 0x00020104,
    OID_GEN_RCV_NO_BUFFER		= 0x00020105,

    /* Optional statistics OIDs */
    OID_GEN_DIRECTED_BYTES_XMIT		= 0x00020201,
    OID_GEN_DIRECTED_FRAMES_XMIT	= 0x00020202,
    OID_GEN_MULTICAST_BYTES_XMIT	= 0x00020203,
    OID_GEN_MULTICAST_FRAMES_XMIT	= 0x00020204,
    OID_GEN_BROADCAST_BYTES_XMIT	= 0x00020205,
    OID_GEN_BROADCAST_FRAMES_XMIT	= 0x00020206,
    OID_GEN_DIRECTED_BYTES_RCV		= 0x00020207,
    OID_GEN_DIRECTED_FRAMES_RCV		= 0x00020208,
    OID_GEN_MULTICAST_BYTES_RCV		= 0x00020209,
    OID_GEN_MULTICAST_FRAMES_RCV	= 0x0002020a,
    OID_GEN_BROADCAST_BYTES_RCV		= 0x0002020b,
    OID_GEN_BROADCAST_FRAMES_RCV	= 0x0002020c,
    OID_GEN_RCV_CRC_ERROR		= 0x0002020d,
    OID_GEN_TRANSMIT_QUEUE_LENGTH	= 0x0002020e,
    OID_GEN_GET_TIME_CAPS		= 0x0002020f,
    OID_GEN_GET_NETCARD_TIME		= 0x00020210,
    OID_GEN_NETCARD_LOAD		= 0x00020211,
    OID_GEN_DEVICE_PROFILE		= 0x00020212,
    OID_GEN_INIT_TIME_MS		= 0x00020213,
    OID_GEN_RESET_COUNTS		= 0x00020214,
    OID_GEN_MEDIA_SENSE_COUNTS		= 0x00020215,
    OID_GEN_FRIENDLY_NAME		= 0x00020216,
    OID_GEN_MINIPORT_INFO		= 0x00020217,
    OID_GEN_RESET_VERIFY_PARAMETERS	= 0x00020218,

    /* IEEE 802.3 (Ethernet) OIDs */
    OID_802_3_PERMANENT_ADDRESS		= 0x01010101,
    OID_802_3_CURRENT_ADDRESS		= 0x01010102,
    OID_802_3_MULTICAST_LIST		= 0x01010103,
    OID_802_3_MAXIMUM_LIST_SIZE		= 0x01010104,
    OID_802_3_MAC_OPTIONS		= 0x01010105,
    OID_802_3_RCV_ERROR_ALIGNMENT	= 0x01020101,
    OID_802_3_XMIT_ONE_COLLISION	= 0x01020102,
    OID_802_3_XMIT_MORE_COLLISIONS	= 0x01020103,
    OID_802_3_XMIT_DEFERRED		= 0x01020201,
    OID_802_3_XMIT_MAX_COLLISIONS	= 0x01020202,
    OID_802_3_RCV_OVERRUN		= 0x01020203,
    OID_802_3_XMIT_UNDERRUN		= 0x01020204,
    OID_802_3_XMIT_HEARTBEAT_FAILURE	= 0x01020205,
    OID_802_3_XMIT_TIMES_CRS_LOST	= 0x01020206,
    OID_802_3_XMIT_LATE_COLLISIONS	= 0x01020207,
};

static const uint32_t oid_supported_list[] =
{
    /* the general stuff */
    OID_GEN_SUPPORTED_LIST,
    OID_GEN_HARDWARE_STATUS,
    OID_GEN_MEDIA_SUPPORTED,
    OID_GEN_MEDIA_IN_USE,
    OID_GEN_MAXIMUM_FRAME_SIZE,
    OID_GEN_LINK_SPEED,
    OID_GEN_TRANSMIT_BLOCK_SIZE,
    OID_GEN_RECEIVE_BLOCK_SIZE,
    OID_GEN_VENDOR_ID,
    OID_GEN_VENDOR_DESCRIPTION,
    OID_GEN_VENDOR_DRIVER_VERSION,
    OID_GEN_CURRENT_PACKET_FILTER,
    OID_GEN_MAXIMUM_TOTAL_SIZE,
    OID_GEN_MEDIA_CONNECT_STATUS,
    OID_GEN_PHYSICAL_MEDIUM,

    /* the statistical stuff */
    OID_GEN_XMIT_OK,
    OID_GEN_RCV_OK,
    OID_GEN_XMIT_ERROR,
    OID_GEN_RCV_ERROR,
    OID_GEN_RCV_NO_BUFFER,

    /* IEEE 802.3 */
    /* the general stuff */
    OID_802_3_PERMANENT_ADDRESS,
    OID_802_3_CURRENT_ADDRESS,
    OID_802_3_MULTICAST_LIST,
    OID_802_3_MAC_OPTIONS,
    OID_802_3_MAXIMUM_LIST_SIZE,

    /* the statistical stuff */
    OID_802_3_RCV_ERROR_ALIGNMENT,
    OID_802_3_XMIT_ONE_COLLISION,
    OID_802_3_XMIT_MORE_COLLISIONS,
};

#define NDIS_MAC_OPTION_COPY_LOOKAHEAD_DATA	(1 << 0)
#define NDIS_MAC_OPTION_RECEIVE_SERIALIZED	(1 << 1)
#define NDIS_MAC_OPTION_TRANSFERS_NOT_PEND	(1 << 2)
#define NDIS_MAC_OPTION_NO_LOOPBACK		(1 << 3)
#define NDIS_MAC_OPTION_FULL_DUPLEX		(1 << 4)
#define NDIS_MAC_OPTION_EOTX_INDICATION		(1 << 5)
#define NDIS_MAC_OPTION_8021P_PRIORITY		(1 << 6)

struct rndis_response {
    TAILQ_ENTRY(rndis_response) entries;
    uint32_t length;
    uint8_t buf[0];
};

typedef struct USBNetState {
    USBDevice dev;

    unsigned int rndis;
    enum rndis_state rndis_state;
    uint32_t medium;
    uint32_t speed;
    uint32_t media_state;
    uint16_t filter;
    uint32_t vendorid;
    uint8_t mac[6];

    unsigned int out_ptr;
    uint8_t out_buf[2048];

    USBPacket *inpkt;
    unsigned int in_ptr, in_len;
    uint8_t in_buf[2048];

    char usbstring_mac[13];
    VLANClientState *vc;
    TAILQ_HEAD(rndis_resp_head, rndis_response) rndis_resp;
} USBNetState;

static int ndis_query(USBNetState *s, uint32_t oid,
                      uint8_t *inbuf, unsigned int inlen, uint8_t *outbuf,
                      size_t outlen)
{
    unsigned int i;

    switch (oid) {
    /* general oids (table 4-1) */
    /* mandatory */
    case OID_GEN_SUPPORTED_LIST:
        for (i = 0; i < ARRAY_SIZE(oid_supported_list); i++)
            ((le32 *) outbuf)[i] = cpu_to_le32(oid_supported_list[i]);
        return sizeof(oid_supported_list);

    /* mandatory */
    case OID_GEN_HARDWARE_STATUS:
        *((le32 *) outbuf) = cpu_to_le32(0);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_MEDIA_SUPPORTED:
        *((le32 *) outbuf) = cpu_to_le32(s->medium);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_MEDIA_IN_USE:
        *((le32 *) outbuf) = cpu_to_le32(s->medium);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_MAXIMUM_FRAME_SIZE:
        *((le32 *) outbuf) = cpu_to_le32(ETH_FRAME_LEN);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_LINK_SPEED:
        *((le32 *) outbuf) = cpu_to_le32(s->speed);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_TRANSMIT_BLOCK_SIZE:
        *((le32 *) outbuf) = cpu_to_le32(ETH_FRAME_LEN);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_RECEIVE_BLOCK_SIZE:
        *((le32 *) outbuf) = cpu_to_le32(ETH_FRAME_LEN);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_VENDOR_ID:
        *((le32 *) outbuf) = cpu_to_le32(s->vendorid);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_VENDOR_DESCRIPTION:
        pstrcpy((char *)outbuf, outlen, "QEMU USB RNDIS Net");
        return strlen((char *)outbuf) + 1;

    case OID_GEN_VENDOR_DRIVER_VERSION:
        *((le32 *) outbuf) = cpu_to_le32(1);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_CURRENT_PACKET_FILTER:
        *((le32 *) outbuf) = cpu_to_le32(s->filter);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_MAXIMUM_TOTAL_SIZE:
        *((le32 *) outbuf) = cpu_to_le32(RNDIS_MAX_TOTAL_SIZE);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_MEDIA_CONNECT_STATUS:
        *((le32 *) outbuf) = cpu_to_le32(s->media_state);
        return sizeof(le32);

    case OID_GEN_PHYSICAL_MEDIUM:
        *((le32 *) outbuf) = cpu_to_le32(0);
        return sizeof(le32);

    case OID_GEN_MAC_OPTIONS:
        *((le32 *) outbuf) = cpu_to_le32(
                        NDIS_MAC_OPTION_RECEIVE_SERIALIZED |
                        NDIS_MAC_OPTION_FULL_DUPLEX);
        return sizeof(le32);

    /* statistics OIDs (table 4-2) */
    /* mandatory */
    case OID_GEN_XMIT_OK:
        *((le32 *) outbuf) = cpu_to_le32(0);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_RCV_OK:
        *((le32 *) outbuf) = cpu_to_le32(0);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_XMIT_ERROR:
        *((le32 *) outbuf) = cpu_to_le32(0);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_RCV_ERROR:
        *((le32 *) outbuf) = cpu_to_le32(0);
        return sizeof(le32);

    /* mandatory */
    case OID_GEN_RCV_NO_BUFFER:
        *((le32 *) outbuf) = cpu_to_le32(0);
        return sizeof(le32);

    /* ieee802.3 OIDs (table 4-3) */
    /* mandatory */
    case OID_802_3_PERMANENT_ADDRESS:
        memcpy(outbuf, s->mac, 6);
        return 6;

    /* mandatory */
    case OID_802_3_CURRENT_ADDRESS:
        memcpy(outbuf, s->mac, 6);
        return 6;

    /* mandatory */
    case OID_802_3_MULTICAST_LIST:
        *((le32 *) outbuf) = cpu_to_le32(0xe0000000);
        return sizeof(le32);

    /* mandatory */
    case OID_802_3_MAXIMUM_LIST_SIZE:
        *((le32 *) outbuf) = cpu_to_le32(1);
        return sizeof(le32);

    case OID_802_3_MAC_OPTIONS:
        return 0;

    /* ieee802.3 statistics OIDs (table 4-4) */
    /* mandatory */
    case OID_802_3_RCV_ERROR_ALIGNMENT:
        *((le32 *) outbuf) = cpu_to_le32(0);
        return sizeof(le32);

    /* mandatory */
    case OID_802_3_XMIT_ONE_COLLISION:
        *((le32 *) outbuf) = cpu_to_le32(0);
        return sizeof(le32);

    /* mandatory */
    case OID_802_3_XMIT_MORE_COLLISIONS:
        *((le32 *) outbuf) = cpu_to_le32(0);
        return sizeof(le32);

    default:
        fprintf(stderr, "usbnet: unknown OID 0x%08x\n", oid);
        return 0;
    }
    return -1;
}

static int ndis_set(USBNetState *s, uint32_t oid,
                uint8_t *inbuf, unsigned int inlen)
{
    switch (oid) {
    case OID_GEN_CURRENT_PACKET_FILTER:
        s->filter = le32_to_cpup((le32 *) inbuf);
        if (s->filter) {
            s->rndis_state = RNDIS_DATA_INITIALIZED;
        } else {
            s->rndis_state = RNDIS_INITIALIZED;
        }
        return 0;

    case OID_802_3_MULTICAST_LIST:
        return 0;
    }
    return -1;
}

static int rndis_get_response(USBNetState *s, uint8_t *buf)
{
    int ret = 0;
    struct rndis_response *r = s->rndis_resp.tqh_first;

    if (!r)
        return ret;

    TAILQ_REMOVE(&s->rndis_resp, r, entries);
    ret = r->length;
    memcpy(buf, r->buf, r->length);
    qemu_free(r);

    return ret;
}

static void *rndis_queue_response(USBNetState *s, unsigned int length)
{
    struct rndis_response *r =
            qemu_mallocz(sizeof(struct rndis_response) + length);

    TAILQ_INSERT_TAIL(&s->rndis_resp, r, entries);
    r->length = length;

    return &r->buf[0];
}

static void rndis_clear_responsequeue(USBNetState *s)
{
    struct rndis_response *r;

    while ((r = s->rndis_resp.tqh_first)) {
        TAILQ_REMOVE(&s->rndis_resp, r, entries);
        qemu_free(r);
    }
}

static int rndis_init_response(USBNetState *s, rndis_init_msg_type *buf)
{
    rndis_init_cmplt_type *resp =
            rndis_queue_response(s, sizeof(rndis_init_cmplt_type));

    if (!resp)
        return USB_RET_STALL;

    resp->MessageType = cpu_to_le32(RNDIS_INITIALIZE_CMPLT);
    resp->MessageLength = cpu_to_le32(sizeof(rndis_init_cmplt_type));
    resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
    resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
    resp->MajorVersion = cpu_to_le32(RNDIS_MAJOR_VERSION);
    resp->MinorVersion = cpu_to_le32(RNDIS_MINOR_VERSION);
    resp->DeviceFlags = cpu_to_le32(RNDIS_DF_CONNECTIONLESS);
    resp->Medium = cpu_to_le32(RNDIS_MEDIUM_802_3);
    resp->MaxPacketsPerTransfer = cpu_to_le32(1);
    resp->MaxTransferSize = cpu_to_le32(ETH_FRAME_LEN +
                    sizeof(struct rndis_packet_msg_type) + 22);
    resp->PacketAlignmentFactor = cpu_to_le32(0);
    resp->AFListOffset = cpu_to_le32(0);
    resp->AFListSize = cpu_to_le32(0);
    return 0;
}

static int rndis_query_response(USBNetState *s,
                rndis_query_msg_type *buf, unsigned int length)
{
    rndis_query_cmplt_type *resp;
    /* oid_supported_list is the largest data reply */
    uint8_t infobuf[sizeof(oid_supported_list)];
    uint32_t bufoffs, buflen;
    int infobuflen;
    unsigned int resplen;

    bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
    buflen = le32_to_cpu(buf->InformationBufferLength);
    if (bufoffs + buflen > length)
        return USB_RET_STALL;

    infobuflen = ndis_query(s, le32_to_cpu(buf->OID),
                            bufoffs + (uint8_t *) buf, buflen, infobuf,
                            sizeof(infobuf));
    resplen = sizeof(rndis_query_cmplt_type) +
            ((infobuflen < 0) ? 0 : infobuflen);
    resp = rndis_queue_response(s, resplen);
    if (!resp)
        return USB_RET_STALL;

    resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT);
    resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
    resp->MessageLength = cpu_to_le32(resplen);

    if (infobuflen < 0) {
        /* OID not supported */
        resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
        resp->InformationBufferLength = cpu_to_le32(0);
        resp->InformationBufferOffset = cpu_to_le32(0);
        return 0;
    }

    resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
    resp->InformationBufferOffset =
            cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0);
    resp->InformationBufferLength = cpu_to_le32(infobuflen);
    memcpy(resp + 1, infobuf, infobuflen);

    return 0;
}

static int rndis_set_response(USBNetState *s,
                rndis_set_msg_type *buf, unsigned int length)
{
    rndis_set_cmplt_type *resp =
            rndis_queue_response(s, sizeof(rndis_set_cmplt_type));
    uint32_t bufoffs, buflen;
    int ret;

    if (!resp)
        return USB_RET_STALL;

    bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;
    buflen = le32_to_cpu(buf->InformationBufferLength);
    if (bufoffs + buflen > length)
        return USB_RET_STALL;

    ret = ndis_set(s, le32_to_cpu(buf->OID),
                    bufoffs + (uint8_t *) buf, buflen);
    resp->MessageType = cpu_to_le32(RNDIS_SET_CMPLT);
    resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
    resp->MessageLength = cpu_to_le32(sizeof(rndis_set_cmplt_type));
    if (ret < 0) {
        /* OID not supported */
        resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);
        return 0;
    }
    resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);

    return 0;
}

static int rndis_reset_response(USBNetState *s, rndis_reset_msg_type *buf)
{
    rndis_reset_cmplt_type *resp =
            rndis_queue_response(s, sizeof(rndis_reset_cmplt_type));

    if (!resp)
        return USB_RET_STALL;

    resp->MessageType = cpu_to_le32(RNDIS_RESET_CMPLT);
    resp->MessageLength = cpu_to_le32(sizeof(rndis_reset_cmplt_type));
    resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);
    resp->AddressingReset = cpu_to_le32(1); /* reset information */

    return 0;
}

static int rndis_keepalive_response(USBNetState *s,
                rndis_keepalive_msg_type *buf)
{
    rndis_keepalive_cmplt_type *resp =
            rndis_queue_response(s, sizeof(rndis_keepalive_cmplt_type));

    if (!resp)
        return USB_RET_STALL;

    resp->MessageType = cpu_to_le32(RNDIS_KEEPALIVE_CMPLT);
    resp->MessageLength = cpu_to_le32(sizeof(rndis_keepalive_cmplt_type));
    resp->RequestID = buf->RequestID; /* Still LE in msg buffer */
    resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);

    return 0;
}

static int rndis_parse(USBNetState *s, uint8_t *data, int length)
{
    uint32_t msg_type, msg_length;
    le32 *tmp = (le32 *) data;

    msg_type = le32_to_cpup(tmp++);
    msg_length = le32_to_cpup(tmp++);

    switch (msg_type) {
    case RNDIS_INITIALIZE_MSG:
        s->rndis_state = RNDIS_INITIALIZED;
        return rndis_init_response(s, (rndis_init_msg_type *) data);

    case RNDIS_HALT_MSG:
        s->rndis_state = RNDIS_UNINITIALIZED;
        return 0;

    case RNDIS_QUERY_MSG:
        return rndis_query_response(s, (rndis_query_msg_type *) data, length);

    case RNDIS_SET_MSG:
        return rndis_set_response(s, (rndis_set_msg_type *) data, length);

    case RNDIS_RESET_MSG:
        rndis_clear_responsequeue(s);
        s->out_ptr = s->in_ptr = s->in_len = 0;
        return rndis_reset_response(s, (rndis_reset_msg_type *) data);

    case RNDIS_KEEPALIVE_MSG:
        /* For USB: host does this every 5 seconds */
        return rndis_keepalive_response(s, (rndis_keepalive_msg_type *) data);
    }

    return USB_RET_STALL;
}

static void usb_net_handle_reset(USBDevice *dev)
{
}

static const char * const usb_net_stringtable[] = {
    [STRING_MANUFACTURER]	= "QEMU",
    [STRING_PRODUCT]		= "RNDIS/QEMU USB Network Device",
    [STRING_ETHADDR]		= "400102030405",
    [STRING_DATA]		= "QEMU USB Net Data Interface",
    [STRING_CONTROL]		= "QEMU USB Net Control Interface",
    [STRING_RNDIS_CONTROL]	= "QEMU USB Net RNDIS Control Interface",
    [STRING_CDC]		= "QEMU USB Net CDC",
    [STRING_SUBSET]		= "QEMU USB Net Subset",
    [STRING_RNDIS]		= "QEMU USB Net RNDIS",
    [STRING_SERIALNUMBER]	= "1",
};

static int usb_net_handle_control(USBDevice *dev, int request, int value,
                int index, int length, uint8_t *data)
{
    USBNetState *s = (USBNetState *) dev;
    int ret = 0;

    switch(request) {
    case DeviceRequest | USB_REQ_GET_STATUS:
        data[0] = (1 << USB_DEVICE_SELF_POWERED) |
                (dev->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP);
        data[1] = 0x00;
        ret = 2;
        break;

    case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:
        if (value == USB_DEVICE_REMOTE_WAKEUP) {
            dev->remote_wakeup = 0;
        } else {
            goto fail;
        }
        ret = 0;
        break;

    case DeviceOutRequest | USB_REQ_SET_FEATURE:
        if (value == USB_DEVICE_REMOTE_WAKEUP) {
            dev->remote_wakeup = 1;
        } else {
            goto fail;
        }
        ret = 0;
        break;

    case DeviceOutRequest | USB_REQ_SET_ADDRESS:
        dev->addr = value;
        ret = 0;
        break;

    case ClassInterfaceOutRequest | USB_CDC_SEND_ENCAPSULATED_COMMAND:
        if (!s->rndis || value || index != 0)
            goto fail;
#ifdef TRAFFIC_DEBUG
        {
            unsigned int i;
            fprintf(stderr, "SEND_ENCAPSULATED_COMMAND:");
            for (i = 0; i < length; i++) {
                if (!(i & 15))
                    fprintf(stderr, "\n%04x:", i);
                fprintf(stderr, " %02x", data[i]);
            }
            fprintf(stderr, "\n\n");
        }
#endif
        ret = rndis_parse(s, data, length);
        break;

    case ClassInterfaceRequest | USB_CDC_GET_ENCAPSULATED_RESPONSE:
        if (!s->rndis || value || index != 0)
            goto fail;
        ret = rndis_get_response(s, data);
        if (!ret) {
            data[0] = 0;
            ret = 1;
        }
#ifdef TRAFFIC_DEBUG
        {
            unsigned int i;
            fprintf(stderr, "GET_ENCAPSULATED_RESPONSE:");
            for (i = 0; i < ret; i++) {
                if (!(i & 15))
                    fprintf(stderr, "\n%04x:", i);
                fprintf(stderr, " %02x", data[i]);
            }
            fprintf(stderr, "\n\n");
        }
#endif
        break;

    case DeviceRequest | USB_REQ_GET_DESCRIPTOR:
        switch(value >> 8) {
        case USB_DT_DEVICE:
            ret = sizeof(qemu_net_dev_descriptor);
            memcpy(data, qemu_net_dev_descriptor, ret);
            break;

        case USB_DT_CONFIG:
            switch (value & 0xff) {
            case 0:
                ret = sizeof(qemu_net_rndis_config_descriptor);
                memcpy(data, qemu_net_rndis_config_descriptor, ret);
                break;

            case 1:
                ret = sizeof(qemu_net_cdc_config_descriptor);
                memcpy(data, qemu_net_cdc_config_descriptor, ret);
                break;

            default:
                goto fail;
            }

            data[2] = ret & 0xff;
            data[3] = ret >> 8;
            break;

        case USB_DT_STRING:
            switch (value & 0xff) {
            case 0:
                /* language ids */
                data[0] = 4;
                data[1] = 3;
                data[2] = 0x09;
                data[3] = 0x04;
                ret = 4;
                break;

            case STRING_ETHADDR:
                ret = set_usb_string(data, s->usbstring_mac);
                break;

            default:
                if (usb_net_stringtable[value & 0xff]) {
                    ret = set_usb_string(data,
                                    usb_net_stringtable[value & 0xff]);
                    break;
                }

                goto fail;
            }
            break;

        default:
            goto fail;
        }
        break;

    case DeviceRequest | USB_REQ_GET_CONFIGURATION:
        data[0] = s->rndis ? DEV_RNDIS_CONFIG_VALUE : DEV_CONFIG_VALUE;
        ret = 1;
        break;

    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:
        switch (value & 0xff) {
        case DEV_CONFIG_VALUE:
            s->rndis = 0;
            break;

        case DEV_RNDIS_CONFIG_VALUE:
            s->rndis = 1;
            break;

        default:
            goto fail;
        }
        ret = 0;
        break;

    case DeviceRequest | USB_REQ_GET_INTERFACE:
    case InterfaceRequest | USB_REQ_GET_INTERFACE:
        data[0] = 0;
        ret = 1;
        break;

    case DeviceOutRequest | USB_REQ_SET_INTERFACE:
    case InterfaceOutRequest | USB_REQ_SET_INTERFACE:
        ret = 0;
        break;

    default:
    fail:
        fprintf(stderr, "usbnet: failed control transaction: "
                        "request 0x%x value 0x%x index 0x%x length 0x%x\n",
                        request, value, index, length);
        ret = USB_RET_STALL;
        break;
    }
    return ret;
}

static int usb_net_handle_statusin(USBNetState *s, USBPacket *p)
{
    int ret = 8;

    if (p->len < 8)
        return USB_RET_STALL;

    ((le32 *) p->data)[0] = cpu_to_le32(1);
    ((le32 *) p->data)[1] = cpu_to_le32(0);
    if (!s->rndis_resp.tqh_first)
        ret = USB_RET_NAK;

#ifdef TRAFFIC_DEBUG
    fprintf(stderr, "usbnet: interrupt poll len %u return %d", p->len, ret);
    {
        int i;
        fprintf(stderr, ":");
        for (i = 0; i < ret; i++) {
            if (!(i & 15))
                fprintf(stderr, "\n%04x:", i);
            fprintf(stderr, " %02x", p->data[i]);
        }
        fprintf(stderr, "\n\n");
    }
#endif

    return ret;
}

static int usb_net_handle_datain(USBNetState *s, USBPacket *p)
{
    int ret = USB_RET_NAK;

    if (s->in_ptr > s->in_len) {
        s->in_ptr = s->in_len = 0;
        ret = USB_RET_NAK;
        return ret;
    }
    if (!s->in_len) {
        ret = USB_RET_NAK;
        return ret;
    }
    ret = s->in_len - s->in_ptr;
    if (ret > p->len)
        ret = p->len;
    memcpy(p->data, &s->in_buf[s->in_ptr], ret);
    s->in_ptr += ret;
    if (s->in_ptr >= s->in_len &&
                    (s->rndis || (s->in_len & (64 - 1)) || !ret)) {
        /* no short packet necessary */
        s->in_ptr = s->in_len = 0;
    }

#ifdef TRAFFIC_DEBUG
    fprintf(stderr, "usbnet: data in len %u return %d", p->len, ret);
    {
        int i;
        fprintf(stderr, ":");
        for (i = 0; i < ret; i++) {
            if (!(i & 15))
                fprintf(stderr, "\n%04x:", i);
            fprintf(stderr, " %02x", p->data[i]);
        }
        fprintf(stderr, "\n\n");
    }
#endif

    return ret;
}

static int usb_net_handle_dataout(USBNetState *s, USBPacket *p)
{
    int ret = p->len;
    int sz = sizeof(s->out_buf) - s->out_ptr;
    struct rndis_packet_msg_type *msg =
            (struct rndis_packet_msg_type *) s->out_buf;
    uint32_t len;

#ifdef TRAFFIC_DEBUG
    fprintf(stderr, "usbnet: data out len %u\n", p->len);
    {
        int i;
        fprintf(stderr, ":");
        for (i = 0; i < p->len; i++) {
            if (!(i & 15))
                fprintf(stderr, "\n%04x:", i);
            fprintf(stderr, " %02x", p->data[i]);
        }
        fprintf(stderr, "\n\n");
    }
#endif

    if (sz > ret)
        sz = ret;
    memcpy(&s->out_buf[s->out_ptr], p->data, sz);
    s->out_ptr += sz;

    if (!s->rndis) {
        if (ret < 64) {
            qemu_send_packet(s->vc, s->out_buf, s->out_ptr);
            s->out_ptr = 0;
        }
        return ret;
    }
    len = le32_to_cpu(msg->MessageLength);
    if (s->out_ptr < 8 || s->out_ptr < len)
        return ret;
    if (le32_to_cpu(msg->MessageType) == RNDIS_PACKET_MSG) {
        uint32_t offs = 8 + le32_to_cpu(msg->DataOffset);
        uint32_t size = le32_to_cpu(msg->DataLength);
        if (offs + size <= len)
            qemu_send_packet(s->vc, s->out_buf + offs, size);
    }
    s->out_ptr -= len;
    memmove(s->out_buf, &s->out_buf[len], s->out_ptr);

    return ret;
}

static int usb_net_handle_data(USBDevice *dev, USBPacket *p)
{
    USBNetState *s = (USBNetState *) dev;
    int ret = 0;

    switch(p->pid) {
    case USB_TOKEN_IN:
        switch (p->devep) {
        case 1:
            ret = usb_net_handle_statusin(s, p);
            break;

        case 2:
            ret = usb_net_handle_datain(s, p);
            break;

        default:
            goto fail;
        }
        break;

    case USB_TOKEN_OUT:
        switch (p->devep) {
        case 2:
            ret = usb_net_handle_dataout(s, p);
            break;

        default:
            goto fail;
        }
        break;

    default:
    fail:
        ret = USB_RET_STALL;
        break;
    }
    if (ret == USB_RET_STALL)
        fprintf(stderr, "usbnet: failed data transaction: "
                        "pid 0x%x ep 0x%x len 0x%x\n",
                        p->pid, p->devep, p->len);
    return ret;
}

static void usbnet_receive(void *opaque, const uint8_t *buf, int size)
{
    USBNetState *s = opaque;
    struct rndis_packet_msg_type *msg;

    if (s->rndis) {
        msg = (struct rndis_packet_msg_type *) s->in_buf;
        if (!s->rndis_state == RNDIS_DATA_INITIALIZED)
            return;
        if (size + sizeof(struct rndis_packet_msg_type) > sizeof(s->in_buf))
            return;

        memset(msg, 0, sizeof(struct rndis_packet_msg_type));
        msg->MessageType = cpu_to_le32(RNDIS_PACKET_MSG);
        msg->MessageLength = cpu_to_le32(size + sizeof(struct rndis_packet_msg_type));
        msg->DataOffset = cpu_to_le32(sizeof(struct rndis_packet_msg_type) - 8);
        msg->DataLength = cpu_to_le32(size);
        /* msg->OOBDataOffset;
         * msg->OOBDataLength;
         * msg->NumOOBDataElements;
         * msg->PerPacketInfoOffset;
         * msg->PerPacketInfoLength;
         * msg->VcHandle;
         * msg->Reserved;
         */
        memcpy(msg + 1, buf, size);
        s->in_len = size + sizeof(struct rndis_packet_msg_type);
    } else {
        if (size > sizeof(s->in_buf))
            return;
        memcpy(s->in_buf, buf, size);
        s->in_len = size;
    }
    s->in_ptr = 0;
}

static int usbnet_can_receive(void *opaque)
{
    USBNetState *s = opaque;

    if (s->rndis && !s->rndis_state == RNDIS_DATA_INITIALIZED)
        return 1;

    return !s->in_len;
}

static void usb_net_handle_destroy(USBDevice *dev)
{
    USBNetState *s = (USBNetState *) dev;

    /* TODO: remove the nd_table[] entry */
    qemu_del_vlan_client(s->vc);
    rndis_clear_responsequeue(s);
    qemu_free(s);
}

USBDevice *usb_net_init(NICInfo *nd)
{
    USBNetState *s;

    s = qemu_mallocz(sizeof(USBNetState));
    if (!s)
        return NULL;
    s->dev.speed = USB_SPEED_FULL;
    s->dev.handle_packet = usb_generic_handle_packet;

    s->dev.handle_reset = usb_net_handle_reset;
    s->dev.handle_control = usb_net_handle_control;
    s->dev.handle_data = usb_net_handle_data;
    s->dev.handle_destroy = usb_net_handle_destroy;

    s->rndis = 1;
    s->rndis_state = RNDIS_UNINITIALIZED;
    s->medium = 0;	/* NDIS_MEDIUM_802_3 */
    s->speed = 1000000; /* 100MBps, in 100Bps units */
    s->media_state = 0;	/* NDIS_MEDIA_STATE_CONNECTED */;
    s->filter = 0;
    s->vendorid = 0x1234;

    memcpy(s->mac, nd->macaddr, 6);
    TAILQ_INIT(&s->rndis_resp);

    pstrcpy(s->dev.devname, sizeof(s->dev.devname),
                    "QEMU USB Network Interface");
    s->vc = qemu_new_vlan_client(nd->vlan, nd->model, nd->name,
                    usbnet_receive, usbnet_can_receive, s);

    qemu_format_nic_info_str(s->vc, s->mac);

    snprintf(s->usbstring_mac, sizeof(s->usbstring_mac),
                    "%02x%02x%02x%02x%02x%02x",
                    0x40, s->mac[1], s->mac[2],
                    s->mac[3], s->mac[4], s->mac[5]);
    fprintf(stderr, "usbnet: initialized mac %02x:%02x:%02x:%02x:%02x:%02x\n",
                    s->mac[0], s->mac[1], s->mac[2],
                    s->mac[3], s->mac[4], s->mac[5]);

    return (USBDevice *) s;
}