summaryrefslogtreecommitdiffstats
path: root/src/VBox/HostDrivers/VBoxUSB/win/lib/VBoxUsbLib-win.cpp
blob: 817b26ed10e9d61f6ffd182aee05f74555bfc26e (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
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
/* $Id: VBoxUsbLib-win.cpp $ */
/** @file
 * VBox USB ring-3 Driver Interface library, Windows.
 */

/*
 * Copyright (C) 2011-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
 * in the VirtualBox distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 *
 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#define LOG_GROUP LOG_GROUP_DRV_USBPROXY
#include <iprt/win/windows.h>

#include <VBox/sup.h>
#include <VBox/types.h>
#include <VBox/err.h>
#include <VBox/param.h>
#include <iprt/path.h>
#include <iprt/assert.h>
#include <iprt/alloc.h>
#include <iprt/string.h>
#include <iprt/thread.h>
#include <iprt/utf16.h>
#include <VBox/log.h>
#include <VBox/usblib.h>
#include <VBox/usblib-win.h>
#include <VBox/usb.h>
#include <VBox/VBoxDrvCfg-win.h>
#pragma warning (disable:4200) /* shuts up the empty array member warnings */
#include <iprt/win/setupapi.h>
#include <usbdi.h>
#include <hidsdi.h>
#include <Dbt.h>

/* Defined in Windows 8 DDK (through usbdi.h) but we use Windows 7 DDK to build. */
#define UsbSuperSpeed   3

#ifdef VBOX_WITH_NEW_USB_ENUM
# include <cfgmgr32.h>
#endif


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
typedef struct _USB_INTERFACE_DESCRIPTOR2
{
    UCHAR  bLength;
    UCHAR  bDescriptorType;
    UCHAR  bInterfaceNumber;
    UCHAR  bAlternateSetting;
    UCHAR  bNumEndpoints;
    UCHAR  bInterfaceClass;
    UCHAR  bInterfaceSubClass;
    UCHAR  bInterfaceProtocol;
    UCHAR  iInterface;
    USHORT wNumClasses;
} USB_INTERFACE_DESCRIPTOR2, *PUSB_INTERFACE_DESCRIPTOR2;

typedef struct VBOXUSBGLOBALSTATE
{
    HANDLE hMonitor;
    HANDLE hNotifyEvent;
    HANDLE hInterruptEvent;
    HANDLE hThread;
    HWND   hWnd;
    HANDLE hTimerQueue;
    HANDLE hTimer;
} VBOXUSBGLOBALSTATE, *PVBOXUSBGLOBALSTATE;

typedef struct VBOXUSB_STRING_DR_ENTRY
{
    struct VBOXUSB_STRING_DR_ENTRY *pNext;
    UCHAR iDr;
    USHORT idLang;
    USB_STRING_DESCRIPTOR StrDr;
} VBOXUSB_STRING_DR_ENTRY, *PVBOXUSB_STRING_DR_ENTRY;

/**
 * This represents VBoxUsb device instance
 */
typedef struct VBOXUSB_DEV
{
    struct VBOXUSB_DEV *pNext;
    char                szName[512];
    char                szDriverRegName[512];
} VBOXUSB_DEV, *PVBOXUSB_DEV;


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
static VBOXUSBGLOBALSTATE g_VBoxUsbGlobal;


static void usbLibVuFreeDevices(PVBOXUSB_DEV pDevInfos)
{
    while (pDevInfos)
    {
        PVBOXUSB_DEV pNext = pDevInfos->pNext;
        RTMemFree(pDevInfos);
        pDevInfos = pNext;
    }
}

/* Check that a proxied device responds the way we expect it to. */
static int usbLibVuDeviceValidate(PVBOXUSB_DEV pVuDev)
{
    HANDLE  hOut = INVALID_HANDLE_VALUE;
    DWORD   dwErr;

    hOut = CreateFile(pVuDev->szName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL,
                      OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM, NULL);

    if (hOut == INVALID_HANDLE_VALUE)
    {
        dwErr = GetLastError();
        AssertFailed();
        LogRelFunc(("Failed to open `%s' (dwErr=%u)!\n", pVuDev->szName, dwErr));
        return VERR_GENERAL_FAILURE;
    }

    USBSUP_VERSION version = {0};
    DWORD cbReturned = 0;
    int rc = VERR_VERSION_MISMATCH;

    do
    {
        if (!DeviceIoControl(hOut, SUPUSB_IOCTL_GET_VERSION, NULL, 0,&version, sizeof(version),  &cbReturned, NULL))
        {
            dwErr = GetLastError();
            AssertFailed();
            LogRelFunc(("SUPUSB_IOCTL_GET_VERSION failed on `%s' (dwErr=%u)!\n", pVuDev->szName, dwErr));
            break;
        }

        if (   version.u32Major != USBDRV_MAJOR_VERSION
#if USBDRV_MINOR_VERSION != 0
            || version.u32Minor <  USBDRV_MINOR_VERSION
#endif
           )
        {
            AssertFailed();
            LogRelFunc(("Invalid version %d:%d (%s) vs %d:%d (library)!\n", version.u32Major, version.u32Minor, pVuDev->szName, USBDRV_MAJOR_VERSION, USBDRV_MINOR_VERSION));
            break;
        }

        if (!DeviceIoControl(hOut, SUPUSB_IOCTL_IS_OPERATIONAL, NULL, 0, NULL, NULL, &cbReturned, NULL))
        {
            dwErr = GetLastError();
            AssertFailed();
            LogRelFunc(("SUPUSB_IOCTL_IS_OPERATIONAL failed on `%s' (dwErr=%u)!\n", pVuDev->szName, dwErr));
            break;
        }

        rc = VINF_SUCCESS;
    } while (0);

    CloseHandle(hOut);
    return rc;
}

#ifndef VBOX_WITH_NEW_USB_ENUM
static int usbLibVuDevicePopulate(PVBOXUSB_DEV pVuDev, HDEVINFO hDevInfo, PSP_DEVICE_INTERFACE_DATA pIfData)
{
    DWORD cbIfDetailData;
    int rc = VINF_SUCCESS;

    SetupDiGetDeviceInterfaceDetail(hDevInfo, pIfData,
                NULL, /* OUT PSP_DEVICE_INTERFACE_DETAIL_DATA DeviceInterfaceDetailData */
                0, /* IN DWORD DeviceInterfaceDetailDataSize */
                &cbIfDetailData,
                NULL
                );
    Assert(GetLastError() == ERROR_INSUFFICIENT_BUFFER);

    PSP_DEVICE_INTERFACE_DETAIL_DATA pIfDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)RTMemAllocZ(cbIfDetailData);
    if (!pIfDetailData)
    {
        AssertMsgFailed(("RTMemAllocZ failed\n"));
        return VERR_OUT_OF_RESOURCES;
    }

    DWORD cbDbgRequired;
    SP_DEVINFO_DATA DevInfoData;
    DevInfoData.cbSize = sizeof (DevInfoData);
    /* the cbSize should contain the sizeof a fixed-size part according to the docs */
    pIfDetailData->cbSize = sizeof (*pIfDetailData);
    do
    {
        if (!SetupDiGetDeviceInterfaceDetail(hDevInfo, pIfData,
                                pIfDetailData,
                                cbIfDetailData,
                                &cbDbgRequired,
                                &DevInfoData))
        {
            DWORD dwErr = GetLastError(); NOREF(dwErr);
            AssertMsgFailed(("SetupDiGetDeviceInterfaceDetail, cbRequired (%d), was (%d), dwErr (%d)\n", cbDbgRequired, cbIfDetailData, dwErr));
            rc = VERR_GENERAL_FAILURE;
            break;
        }

        strncpy(pVuDev->szName, pIfDetailData->DevicePath, sizeof (pVuDev->szName));

        if (!SetupDiGetDeviceRegistryPropertyA(hDevInfo, &DevInfoData, SPDRP_DRIVER,
            NULL, /* OUT PDWORD PropertyRegDataType */
            (PBYTE)pVuDev->szDriverRegName,
            sizeof (pVuDev->szDriverRegName),
            &cbDbgRequired))
        {
            DWORD dwErr = GetLastError(); NOREF(dwErr);
            AssertMsgFailed(("SetupDiGetDeviceRegistryPropertyA, cbRequired (%d), was (%d), dwErr (%d)\n", cbDbgRequired, sizeof (pVuDev->szDriverRegName), dwErr));
            rc = VERR_GENERAL_FAILURE;
            break;
        }

        rc = usbLibVuDeviceValidate(pVuDev);
        LogRelFunc(("Found VBoxUSB on `%s' (rc=%d)\n", pVuDev->szName, rc));
        AssertRC(rc);
    } while (0);

    RTMemFree(pIfDetailData);
    return rc;
}

static int usbLibVuGetDevices(PVBOXUSB_DEV *ppVuDevs, uint32_t *pcVuDevs)
{
    *ppVuDevs = NULL;
    *pcVuDevs = 0;

    HDEVINFO hDevInfo =  SetupDiGetClassDevs(&GUID_CLASS_VBOXUSB,
            NULL, /* IN PCTSTR Enumerator */
            NULL, /* IN HWND hwndParent */
            (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE) /* IN DWORD Flags */
            );
    if (hDevInfo == INVALID_HANDLE_VALUE)
    {
        DWORD dwErr = GetLastError(); NOREF(dwErr);
        AssertMsgFailed(("SetupDiGetClassDevs, dwErr (%u)\n", dwErr));
        return VERR_GENERAL_FAILURE;
    }

    for (int i = 0; ; ++i)
    {
        SP_DEVICE_INTERFACE_DATA IfData;
        IfData.cbSize = sizeof (IfData);
        if (!SetupDiEnumDeviceInterfaces(hDevInfo,
                            NULL, /* IN PSP_DEVINFO_DATA DeviceInfoData */
                            &GUID_CLASS_VBOXUSB, /* IN LPGUID InterfaceClassGuid */
                            i,
                            &IfData))
        {
            DWORD dwErr = GetLastError();
            if (dwErr == ERROR_NO_MORE_ITEMS)
                break;

            AssertMsgFailed(("SetupDiEnumDeviceInterfaces, dwErr (%u), resuming\n", dwErr));
            continue;
        }

        /* we've now got the IfData */
        PVBOXUSB_DEV pVuDev = (PVBOXUSB_DEV)RTMemAllocZ(sizeof (*pVuDev));
        if (!pVuDev)
        {
            AssertMsgFailed(("RTMemAllocZ failed, resuming\n"));
            continue;
        }

        int rc = usbLibVuDevicePopulate(pVuDev, hDevInfo, &IfData);
        if (!RT_SUCCESS(rc))
        {
            AssertMsgFailed(("usbLibVuDevicePopulate failed, rc (%d), resuming\n", rc));
            continue;
        }

        pVuDev->pNext = *ppVuDevs;
        *ppVuDevs = pVuDev;
        ++*pcVuDevs;
    }

    SetupDiDestroyDeviceInfoList(hDevInfo);

    return VINF_SUCCESS;
}

static int usbLibDevPopulate(PUSBDEVICE pDev, PUSB_NODE_CONNECTION_INFORMATION_EX pConInfo, ULONG iPort, LPCSTR lpszDrvKeyName, LPCSTR lpszHubName, PVBOXUSB_STRING_DR_ENTRY pDrList)
{
    pDev->bcdUSB = pConInfo->DeviceDescriptor.bcdUSB;
    pDev->bDeviceClass = pConInfo->DeviceDescriptor.bDeviceClass;
    pDev->bDeviceSubClass = pConInfo->DeviceDescriptor.bDeviceSubClass;
    pDev->bDeviceProtocol = pConInfo->DeviceDescriptor.bDeviceProtocol;
    pDev->idVendor = pConInfo->DeviceDescriptor.idVendor;
    pDev->idProduct = pConInfo->DeviceDescriptor.idProduct;
    pDev->bcdDevice = pConInfo->DeviceDescriptor.bcdDevice;
    pDev->bBus = 0; /** @todo figure out bBus on windows... */
    pDev->bPort = iPort;
    /** @todo check which devices are used for primary input (keyboard & mouse) */
    if (!lpszDrvKeyName || *lpszDrvKeyName == 0)
        pDev->enmState = USBDEVICESTATE_UNUSED;
    else
        pDev->enmState = USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;

    /* Determine the speed the device is operating at. */
    switch (pConInfo->Speed)
    {
        case UsbLowSpeed:   pDev->enmSpeed = USBDEVICESPEED_LOW;    break;
        case UsbFullSpeed:  pDev->enmSpeed = USBDEVICESPEED_FULL;   break;
        case UsbHighSpeed:  pDev->enmSpeed = USBDEVICESPEED_HIGH;   break;
        default:    /* If we don't know, most likely it's something new. */
        case UsbSuperSpeed: pDev->enmSpeed = USBDEVICESPEED_SUPER;  break;
    }
    /* Unfortunately USB_NODE_CONNECTION_INFORMATION_EX will not report UsbSuperSpeed, and
     * it's not even defined in the Win7 DDK we use. So we go by the USB version, and
     * luckily we know that USB3 must mean SuperSpeed. The USB3 spec guarantees this (9.6.1).
     */
    if (pDev->bcdUSB >= 0x0300)
        pDev->enmSpeed = USBDEVICESPEED_SUPER;

    int rc = RTStrAPrintf((char **)&pDev->pszAddress, "%s", lpszDrvKeyName);
    if (rc < 0)
        return VERR_NO_MEMORY;
    pDev->pszBackend = RTStrDup("host");
    if (!pDev->pszBackend)
    {
        RTStrFree((char *)pDev->pszAddress);
        return VERR_NO_STR_MEMORY;
    }
    pDev->pszHubName = RTStrDup(lpszHubName);
    pDev->bNumConfigurations = 0;
    pDev->u64SerialHash = 0;

    for (; pDrList; pDrList = pDrList->pNext)
    {
        char **ppszString = NULL;
        if (   pConInfo->DeviceDescriptor.iManufacturer
            && pDrList->iDr == pConInfo->DeviceDescriptor.iManufacturer)
            ppszString = (char **)&pDev->pszManufacturer;
        else if (   pConInfo->DeviceDescriptor.iProduct
                 && pDrList->iDr == pConInfo->DeviceDescriptor.iProduct)
            ppszString = (char **)&pDev->pszProduct;
        else if (   pConInfo->DeviceDescriptor.iSerialNumber
                 && pDrList->iDr == pConInfo->DeviceDescriptor.iSerialNumber)
            ppszString = (char **)&pDev->pszSerialNumber;
        if (ppszString)
        {
            rc = RTUtf16ToUtf8((PCRTUTF16)pDrList->StrDr.bString, ppszString);
            if (RT_SUCCESS(rc))
            {
                Assert(*ppszString);
                USBLibPurgeEncoding(*ppszString);

                if (pDrList->iDr == pConInfo->DeviceDescriptor.iSerialNumber)
                    pDev->u64SerialHash = USBLibHashSerial(*ppszString);
            }
            else
            {
                AssertMsgFailed(("RTUtf16ToUtf8 failed, rc (%d), resuming\n", rc));
                *ppszString = NULL;
            }
        }
    }

    return VINF_SUCCESS;
}
#else

static PSP_DEVICE_INTERFACE_DETAIL_DATA usbLibGetDevDetail(HDEVINFO InfoSet, PSP_DEVICE_INTERFACE_DATA InterfaceData, PSP_DEVINFO_DATA DevInfoData);
static void *usbLibGetRegistryProperty(HDEVINFO InfoSet, const PSP_DEVINFO_DATA DevData, DWORD Property);

/* Populate the data for a single proxied USB device. */
static int usbLibVUsbDevicePopulate(PVBOXUSB_DEV pVuDev, HDEVINFO InfoSet, PSP_DEVICE_INTERFACE_DATA InterfaceData)
{
    PSP_DEVICE_INTERFACE_DETAIL_DATA    DetailData = NULL;
    SP_DEVINFO_DATA                     DeviceData;
    LPCSTR                              Location;
    int                                 rc = VINF_SUCCESS;

    memset(&DeviceData, 0, sizeof(DeviceData));
    DeviceData.cbSize = sizeof(DeviceData);
    /* The interface detail includes the device path. */
    DetailData = usbLibGetDevDetail(InfoSet, InterfaceData, &DeviceData);
    if (DetailData)
    {
        strncpy(pVuDev->szName, DetailData->DevicePath, sizeof(pVuDev->szName));

        /* The location is used as a unique identifier for cross-referencing the two lists. */
        Location = (LPCSTR)usbLibGetRegistryProperty(InfoSet, &DeviceData, SPDRP_DRIVER);
        if (Location)
        {
            strncpy(pVuDev->szDriverRegName, Location, sizeof(pVuDev->szDriverRegName));
            rc = usbLibVuDeviceValidate(pVuDev);
            LogRelFunc(("Found VBoxUSB on `%s' (rc=%d)\n", pVuDev->szName, rc));
            AssertRC(rc);

            RTMemFree((void *)Location);
        }
        else
        {
            /* Errors will be logged by usbLibGetRegistryProperty(). */
            rc = VERR_GENERAL_FAILURE;
        }

        RTMemFree(DetailData);
    }
    else
    {
        /* Errors will be logged by usbLibGetDevDetail(). */
        rc = VERR_GENERAL_FAILURE;
    }


    return rc;
}

/* Enumerate proxied USB devices (with VBoxUSB.sys loaded). */
static int usbLibEnumVUsbDevices(PVBOXUSB_DEV *ppVuDevs, uint32_t *pcVuDevs)
{
    SP_DEVICE_INTERFACE_DATA    InterfaceData;
    HDEVINFO                    InfoSet;
    DWORD                       DeviceIndex;
    DWORD                       dwErr;

    *ppVuDevs = NULL;
    *pcVuDevs = 0;

    /* Enumerate all present devices which support the GUID_CLASS_VBOXUSB interface. */
    InfoSet = SetupDiGetClassDevs(&GUID_CLASS_VBOXUSB, NULL, NULL,
                                  (DIGCF_PRESENT | DIGCF_DEVICEINTERFACE));
    if (InfoSet == INVALID_HANDLE_VALUE)
    {
        DWORD dwErr = GetLastError();
        LogRelFunc(("SetupDiGetClassDevs for GUID_CLASS_VBOXUSB failed (dwErr=%u)\n", dwErr));
        AssertFailed();
        return VERR_GENERAL_FAILURE;
    }

    memset(&InterfaceData, 0, sizeof(InterfaceData));
    InterfaceData.cbSize = sizeof(InterfaceData);
    DeviceIndex = 0;

    /* Loop over the enumerated list. */
    while (SetupDiEnumDeviceInterfaces(InfoSet, NULL, &GUID_CLASS_VBOXUSB, DeviceIndex, &InterfaceData))
    {
        /* we've now got the IfData */
        PVBOXUSB_DEV pVuDev = (PVBOXUSB_DEV)RTMemAllocZ(sizeof (*pVuDev));
        if (!pVuDev)
        {
            AssertFailed();
            LogRelFunc(("RTMemAllocZ failed\n"));
            break;
        }

        int rc = usbLibVUsbDevicePopulate(pVuDev, InfoSet, &InterfaceData);
        if (RT_SUCCESS(rc))
        {
            pVuDev->pNext = *ppVuDevs;
            *ppVuDevs = pVuDev;
            ++*pcVuDevs;
        }
        else    /* Skip this device but continue enumerating. */
            AssertMsgFailed(("usbLibVuDevicePopulate failed, rc=%d\n", rc));

        memset(&InterfaceData, 0, sizeof(InterfaceData));
        InterfaceData.cbSize = sizeof(InterfaceData);
        ++DeviceIndex;
    }

    /* Paranoia. */
    dwErr = GetLastError();
    if (dwErr != ERROR_NO_MORE_ITEMS)
    {
        LogRelFunc(("SetupDiEnumDeviceInterfaces failed (dwErr=%u)\n", dwErr));
        AssertFailed();
    }

    SetupDiDestroyDeviceInfoList(InfoSet);

    return VINF_SUCCESS;
}

static uint16_t usbLibParseHexNumU16(LPCSTR *ppStr)
{
    const char  *pStr = *ppStr;
    char        c;
    uint16_t    num = 0;
    unsigned    u;

    for (int i = 0; i < 4; ++i)
    {
        if (!*pStr)     /* Just in case the string is too short. */
            break;

        c = *pStr;
        u = c >= 'A' ? c - 'A' + 10 : c - '0';  /* Hex digit to number. */
        num |= u << (12 - 4 * i);
        pStr++;
    }
    *ppStr = pStr;

    return num;
}

static int usbLibDevPopulate(PUSBDEVICE pDev, PUSB_NODE_CONNECTION_INFORMATION_EX pConInfo, ULONG iPort, LPCSTR lpszLocation, LPCSTR lpszDrvKeyName, LPCSTR lpszHubName, PVBOXUSB_STRING_DR_ENTRY pDrList)
{
    pDev->bcdUSB = pConInfo->DeviceDescriptor.bcdUSB;
    pDev->bDeviceClass = pConInfo->DeviceDescriptor.bDeviceClass;
    pDev->bDeviceSubClass = pConInfo->DeviceDescriptor.bDeviceSubClass;
    pDev->bDeviceProtocol = pConInfo->DeviceDescriptor.bDeviceProtocol;
    pDev->idVendor = pConInfo->DeviceDescriptor.idVendor;
    pDev->idProduct = pConInfo->DeviceDescriptor.idProduct;
    pDev->bcdDevice = pConInfo->DeviceDescriptor.bcdDevice;
    pDev->bBus = 0; /* The hub numbering is not very useful on Windows. Skip it. */
    pDev->bPort = iPort;

    /* The port path/location uniquely identifies the port. */
    pDev->pszPortPath = RTStrDup(lpszLocation);
    if (!pDev->pszPortPath)
        return VERR_NO_STR_MEMORY;

    /* If there is no DriverKey, the device is unused because there's no driver. */
    if (!lpszDrvKeyName || *lpszDrvKeyName == 0)
        pDev->enmState = USBDEVICESTATE_UNUSED;
    else
        pDev->enmState = USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;

    /* Determine the speed the device is operating at. */
    switch (pConInfo->Speed)
    {
        case UsbLowSpeed:   pDev->enmSpeed = USBDEVICESPEED_LOW;    break;
        case UsbFullSpeed:  pDev->enmSpeed = USBDEVICESPEED_FULL;   break;
        case UsbHighSpeed:  pDev->enmSpeed = USBDEVICESPEED_HIGH;   break;
        default:    /* If we don't know, most likely it's something new. */
        case UsbSuperSpeed: pDev->enmSpeed = USBDEVICESPEED_SUPER;  break;
    }
    /* Unfortunately USB_NODE_CONNECTION_INFORMATION_EX will not report UsbSuperSpeed, and
     * it's not even defined in the Win7 DDK we use. So we go by the USB version, and
     * luckily we know that USB3 must mean SuperSpeed. The USB3 spec guarantees this (9.6.1).
     */
    if (pDev->bcdUSB >= 0x0300)
        pDev->enmSpeed = USBDEVICESPEED_SUPER;

    /* If there's no DriverKey, jam in an empty string to avoid NULL pointers. */
    if (!lpszDrvKeyName)
        pDev->pszAddress = RTStrDup("");
    else
        pDev->pszAddress = RTStrDup(lpszDrvKeyName);

    pDev->pszBackend = RTStrDup("host");
    if (!pDev->pszBackend)
    {
        RTStrFree((char *)pDev->pszAddress);
        return VERR_NO_STR_MEMORY;
    }
    pDev->pszHubName = RTStrDup(lpszHubName);
    pDev->bNumConfigurations = 0;
    pDev->u64SerialHash = 0;

    for (; pDrList; pDrList = pDrList->pNext)
    {
        char **ppszString = NULL;
        if (   pConInfo->DeviceDescriptor.iManufacturer
            && pDrList->iDr == pConInfo->DeviceDescriptor.iManufacturer)
            ppszString = (char **)&pDev->pszManufacturer;
        else if (   pConInfo->DeviceDescriptor.iProduct
                 && pDrList->iDr == pConInfo->DeviceDescriptor.iProduct)
            ppszString = (char **)&pDev->pszProduct;
        else if (   pConInfo->DeviceDescriptor.iSerialNumber
                 && pDrList->iDr == pConInfo->DeviceDescriptor.iSerialNumber)
            ppszString = (char **)&pDev->pszSerialNumber;
        if (ppszString)
        {
            int rc = RTUtf16ToUtf8((PCRTUTF16)pDrList->StrDr.bString, ppszString);
            if (RT_SUCCESS(rc))
            {
                Assert(*ppszString);
                USBLibPurgeEncoding(*ppszString);

                if (pDrList->iDr == pConInfo->DeviceDescriptor.iSerialNumber)
                    pDev->u64SerialHash = USBLibHashSerial(*ppszString);
            }
            else
            {
                AssertMsgFailed(("RTUtf16ToUtf8 failed, rc (%d), resuming\n", rc));
                *ppszString = NULL;
            }
        }
    }

    return VINF_SUCCESS;
}
#endif

static void usbLibDevStrFree(LPSTR lpszName)
{
    RTStrFree(lpszName);
}

#ifndef VBOX_WITH_NEW_USB_ENUM
static int usbLibDevStrDriverKeyGet(HANDLE hHub, ULONG iPort, LPSTR* plpszName)
{
    USB_NODE_CONNECTION_DRIVERKEY_NAME Name;
    DWORD cbReturned = 0;
    Name.ConnectionIndex = iPort;
    *plpszName = NULL;
    if (!DeviceIoControl(hHub, IOCTL_USB_GET_NODE_CONNECTION_DRIVERKEY_NAME, &Name, sizeof (Name), &Name, sizeof (Name), &cbReturned, NULL))
    {
#ifdef VBOX_WITH_ANNOYING_USB_ASSERTIONS
        AssertMsgFailed(("DeviceIoControl 1 fail dwErr (%u)\n", GetLastError()));
#endif
        return VERR_GENERAL_FAILURE;
    }

    if (Name.ActualLength < sizeof (Name))
    {
        AssertFailed();
        return VERR_OUT_OF_RESOURCES;
    }

    PUSB_NODE_CONNECTION_DRIVERKEY_NAME pName = (PUSB_NODE_CONNECTION_DRIVERKEY_NAME)RTMemAllocZ(Name.ActualLength);
    if (!pName)
    {
        AssertFailed();
        return VERR_OUT_OF_RESOURCES;
    }

    int rc = VINF_SUCCESS;
    pName->ConnectionIndex = iPort;
    if (DeviceIoControl(hHub, IOCTL_USB_GET_NODE_CONNECTION_DRIVERKEY_NAME, pName, Name.ActualLength, pName, Name.ActualLength, &cbReturned, NULL))
    {
        rc = RTUtf16ToUtf8Ex((PCRTUTF16)pName->DriverKeyName, pName->ActualLength / sizeof (WCHAR), plpszName, 0, NULL);
        AssertRC(rc);
        if (RT_SUCCESS(rc))
            rc = VINF_SUCCESS;
    }
    else
    {
        DWORD dwErr = GetLastError(); NOREF(dwErr);
        AssertMsgFailed(("DeviceIoControl 2 fail dwErr (%u)\n", dwErr));
        rc = VERR_GENERAL_FAILURE;
    }
    RTMemFree(pName);
    return rc;
}
#endif

static int usbLibDevStrHubNameGet(HANDLE hHub, ULONG iPort, LPSTR* plpszName)
{
    USB_NODE_CONNECTION_NAME Name;
    DWORD cbReturned = 0;
    Name.ConnectionIndex = iPort;
    *plpszName = NULL;
    if (!DeviceIoControl(hHub, IOCTL_USB_GET_NODE_CONNECTION_NAME, &Name, sizeof (Name), &Name, sizeof (Name), &cbReturned, NULL))
    {
        AssertFailed();
        return VERR_GENERAL_FAILURE;
    }

    if (Name.ActualLength < sizeof (Name))
    {
        AssertFailed();
        return VERR_OUT_OF_RESOURCES;
    }

    PUSB_NODE_CONNECTION_NAME pName = (PUSB_NODE_CONNECTION_NAME)RTMemAllocZ(Name.ActualLength);
    if (!pName)
    {
        AssertFailed();
        return VERR_OUT_OF_RESOURCES;
    }

    int rc = VINF_SUCCESS;
    pName->ConnectionIndex = iPort;
    if (DeviceIoControl(hHub, IOCTL_USB_GET_NODE_CONNECTION_NAME, pName, Name.ActualLength, pName, Name.ActualLength, &cbReturned, NULL))
    {
        rc = RTUtf16ToUtf8Ex((PCRTUTF16)pName->NodeName, pName->ActualLength / sizeof (WCHAR), plpszName, 0, NULL);
        AssertRC(rc);
        if (RT_SUCCESS(rc))
            rc = VINF_SUCCESS;
    }
    else
    {
        AssertFailed();
        rc = VERR_GENERAL_FAILURE;
    }
    RTMemFree(pName);
    return rc;
}

static int usbLibDevStrRootHubNameGet(HANDLE hCtl, LPSTR* plpszName)
{
    USB_ROOT_HUB_NAME HubName;
    DWORD cbReturned = 0;
    *plpszName = NULL;
    if (!DeviceIoControl(hCtl, IOCTL_USB_GET_ROOT_HUB_NAME, NULL, 0, &HubName, sizeof (HubName), &cbReturned, NULL))
    {
        return VERR_GENERAL_FAILURE;
    }
    PUSB_ROOT_HUB_NAME pHubName = (PUSB_ROOT_HUB_NAME)RTMemAllocZ(HubName.ActualLength);
    if (!pHubName)
        return VERR_OUT_OF_RESOURCES;

    int rc = VINF_SUCCESS;
    if (DeviceIoControl(hCtl, IOCTL_USB_GET_ROOT_HUB_NAME, NULL, 0, pHubName, HubName.ActualLength, &cbReturned, NULL))
    {
        rc = RTUtf16ToUtf8Ex((PCRTUTF16)pHubName->RootHubName, pHubName->ActualLength / sizeof (WCHAR), plpszName, 0, NULL);
        AssertRC(rc);
        if (RT_SUCCESS(rc))
            rc = VINF_SUCCESS;
    }
    else
    {
        rc = VERR_GENERAL_FAILURE;
    }
    RTMemFree(pHubName);
    return rc;
}

static int usbLibDevCfgDrGet(HANDLE hHub, LPCSTR lpcszHubName, ULONG iPort, ULONG iDr, PUSB_CONFIGURATION_DESCRIPTOR *ppDr)
{
    *ppDr = NULL;

    char Buf[sizeof (USB_DESCRIPTOR_REQUEST) + sizeof (USB_CONFIGURATION_DESCRIPTOR)];
    memset(&Buf, 0, sizeof (Buf));

    PUSB_DESCRIPTOR_REQUEST pCfgDrRq = (PUSB_DESCRIPTOR_REQUEST)Buf;
    PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = (PUSB_CONFIGURATION_DESCRIPTOR)(Buf + sizeof (*pCfgDrRq));

    pCfgDrRq->ConnectionIndex = iPort;
    pCfgDrRq->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | iDr;
    pCfgDrRq->SetupPacket.wLength = (USHORT)(sizeof (USB_CONFIGURATION_DESCRIPTOR));
    DWORD cbReturned = 0;
    if (!DeviceIoControl(hHub, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, pCfgDrRq, sizeof (Buf),
                                pCfgDrRq, sizeof (Buf),
                                &cbReturned, NULL))
    {
        DWORD dwErr = GetLastError();
        LogRelFunc(("IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION #1 failed (dwErr=%u) on hub %s port %d\n", dwErr, lpcszHubName, iPort));
#ifdef VBOX_WITH_ANNOYING_USB_ASSERTIONS
        AssertFailed();
#endif
        return VERR_GENERAL_FAILURE;
    }

    if (sizeof (Buf) != cbReturned)
    {
        AssertFailed();
        return VERR_GENERAL_FAILURE;
    }

    if (pCfgDr->wTotalLength < sizeof (USB_CONFIGURATION_DESCRIPTOR))
    {
        AssertFailed();
        return VERR_GENERAL_FAILURE;
    }

    DWORD cbRq = sizeof (USB_DESCRIPTOR_REQUEST) + pCfgDr->wTotalLength;
    PUSB_DESCRIPTOR_REQUEST pRq = (PUSB_DESCRIPTOR_REQUEST)RTMemAllocZ(cbRq);
    Assert(pRq);
    if (!pRq)
        return VERR_OUT_OF_RESOURCES;

    int rc = VERR_GENERAL_FAILURE;
    do
    {
        PUSB_CONFIGURATION_DESCRIPTOR pDr = (PUSB_CONFIGURATION_DESCRIPTOR)(pRq + 1);
        pRq->ConnectionIndex = iPort;
        pRq->SetupPacket.wValue = (USB_CONFIGURATION_DESCRIPTOR_TYPE << 8) | iDr;
        pRq->SetupPacket.wLength = (USHORT)(cbRq - sizeof (USB_DESCRIPTOR_REQUEST));
        if (!DeviceIoControl(hHub, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, pRq, cbRq,
                                    pRq, cbRq,
                                    &cbReturned, NULL))
        {
            DWORD dwErr = GetLastError();
            LogRelFunc(("IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION #2 failed (dwErr=%u) on hub %s port %d\n", dwErr, lpcszHubName, iPort));
#ifdef VBOX_WITH_ANNOYING_USB_ASSERTIONS
            AssertFailed();
#endif
            break;
        }

        if (cbRq != cbReturned)
        {
            AssertFailed();
            break;
        }

        if (pDr->wTotalLength != cbRq - sizeof (USB_DESCRIPTOR_REQUEST))
        {
            AssertFailed();
            break;
        }

        *ppDr = pDr;
        return VINF_SUCCESS;
    } while (0);

    RTMemFree(pRq);
    return rc;
}

static void usbLibDevCfgDrFree(PUSB_CONFIGURATION_DESCRIPTOR pDr)
{
    Assert(pDr);
    PUSB_DESCRIPTOR_REQUEST pRq = ((PUSB_DESCRIPTOR_REQUEST)pDr)-1;
    RTMemFree(pRq);
}

static int usbLibDevStrDrEntryGet(HANDLE hHub, LPCSTR lpcszHubName, ULONG iPort, ULONG iDr, USHORT idLang, PVBOXUSB_STRING_DR_ENTRY *ppList)
{
    char szBuf[sizeof (USB_DESCRIPTOR_REQUEST) + MAXIMUM_USB_STRING_LENGTH];
    RT_ZERO(szBuf);

    PUSB_DESCRIPTOR_REQUEST pRq = (PUSB_DESCRIPTOR_REQUEST)szBuf;
    PUSB_STRING_DESCRIPTOR pDr = (PUSB_STRING_DESCRIPTOR)(szBuf + sizeof (*pRq));
    RT_BZERO(pDr, sizeof(USB_STRING_DESCRIPTOR));

    pRq->ConnectionIndex = iPort;
    pRq->SetupPacket.wValue = (USB_STRING_DESCRIPTOR_TYPE << 8) | iDr;
    pRq->SetupPacket.wIndex = idLang;
    pRq->SetupPacket.wLength = sizeof (szBuf) - sizeof (*pRq);

    DWORD cbReturned = 0;
    if (!DeviceIoControl(hHub, IOCTL_USB_GET_DESCRIPTOR_FROM_NODE_CONNECTION, pRq, sizeof (szBuf),
                         pRq, sizeof(szBuf),
                         &cbReturned, NULL))
    {
        DWORD dwErr = GetLastError();
        LogRel(("Getting USB descriptor (id %u) failed (dwErr=%u) on hub %s port %d\n", iDr, dwErr, lpcszHubName, iPort));
        return RTErrConvertFromWin32(dwErr);
    }

    /* Wrong descriptor type at the requested port index? Bail out. */
    if (pDr->bDescriptorType != USB_STRING_DESCRIPTOR_TYPE)
        return VERR_NOT_FOUND;

    /* Some more sanity checks. */
    if (   (cbReturned < sizeof (*pDr) + 2)
        || (!!(pDr->bLength % 2))
        || (pDr->bLength != cbReturned - sizeof(*pRq)))
    {
        AssertMsgFailed(("Sanity check failed for string descriptor: cbReturned=%RI32, cbDevReq=%zu, type=%RU8, len=%RU8, port=%RU32, index=%RU32, lang=%RU32\n",
                         cbReturned, sizeof(*pRq), pDr->bDescriptorType, pDr->bLength, iPort, iDr, idLang));
        return VERR_INVALID_PARAMETER;
    }

    PVBOXUSB_STRING_DR_ENTRY pEntry =
        (PVBOXUSB_STRING_DR_ENTRY)RTMemAllocZ(sizeof(VBOXUSB_STRING_DR_ENTRY) + pDr->bLength + 2);
    AssertPtr(pEntry);
    if (!pEntry)
        return VERR_NO_MEMORY;

    pEntry->pNext = *ppList;
    pEntry->iDr = iDr;
    pEntry->idLang = idLang;
    memcpy(&pEntry->StrDr, pDr, pDr->bLength);

    *ppList = pEntry;

    return VINF_SUCCESS;
}

static void usbLibDevStrDrEntryFree(PVBOXUSB_STRING_DR_ENTRY pDr)
{
    RTMemFree(pDr);
}

static void usbLibDevStrDrEntryFreeList(PVBOXUSB_STRING_DR_ENTRY pDr)
{
    while (pDr)
    {
        PVBOXUSB_STRING_DR_ENTRY pNext = pDr->pNext;
        usbLibDevStrDrEntryFree(pDr);
        pDr = pNext;
    }
}

static int usbLibDevStrDrEntryGetForLangs(HANDLE hHub, LPCSTR lpcszHubName, ULONG iPort, ULONG iDr, ULONG cIdLang, const USHORT *pIdLang, PVBOXUSB_STRING_DR_ENTRY *ppList)
{
    for (ULONG i = 0; i < cIdLang; ++i)
    {
        usbLibDevStrDrEntryGet(hHub, lpcszHubName, iPort, iDr, pIdLang[i], ppList);
    }
    return VINF_SUCCESS;
}

static int usbLibDevStrDrEntryGetAll(HANDLE hHub, LPCSTR lpcszHubName, ULONG iPort, PUSB_DEVICE_DESCRIPTOR pDevDr, PUSB_CONFIGURATION_DESCRIPTOR pCfgDr, PVBOXUSB_STRING_DR_ENTRY *ppList)
{
    /* Read string descriptor zero to determine what languages are available. */
    int rc = usbLibDevStrDrEntryGet(hHub, lpcszHubName, iPort, 0, 0, ppList);
    if (RT_FAILURE(rc))
        return rc;

    PUSB_STRING_DESCRIPTOR pLangStrDr = &(*ppList)->StrDr;
    USHORT *pIdLang = pLangStrDr->bString;
    ULONG cIdLang = (pLangStrDr->bLength - RT_OFFSETOF(USB_STRING_DESCRIPTOR, bString)) / sizeof (*pIdLang);

    if (pDevDr->iManufacturer)
    {
        rc = usbLibDevStrDrEntryGetForLangs(hHub, lpcszHubName, iPort, pDevDr->iManufacturer, cIdLang, pIdLang, ppList);
        AssertRC(rc);
    }

    if (pDevDr->iProduct)
    {
        rc = usbLibDevStrDrEntryGetForLangs(hHub, lpcszHubName, iPort, pDevDr->iProduct, cIdLang, pIdLang, ppList);
        AssertRC(rc);
    }

    if (pDevDr->iSerialNumber)
    {
        rc = usbLibDevStrDrEntryGetForLangs(hHub, lpcszHubName, iPort, pDevDr->iSerialNumber, cIdLang, pIdLang, ppList);
        AssertRC(rc);
    }

    PUCHAR pCur = (PUCHAR)pCfgDr;
    PUCHAR pEnd = pCur + pCfgDr->wTotalLength;
    while (pCur + sizeof (USB_COMMON_DESCRIPTOR) <= pEnd)
    {
        PUSB_COMMON_DESCRIPTOR pCmnDr = (PUSB_COMMON_DESCRIPTOR)pCur;
        if (pCur + pCmnDr->bLength > pEnd)
        {
            AssertFailed();
            break;
        }

        /* This is invalid but was seen with a TerraTec Aureon 7.1 USB sound card. */
        if (!pCmnDr->bLength)
            break;

        switch (pCmnDr->bDescriptorType)
        {
            case USB_CONFIGURATION_DESCRIPTOR_TYPE:
            {
                if (pCmnDr->bLength != sizeof (USB_CONFIGURATION_DESCRIPTOR))
                {
                    AssertFailed();
                    break;
                }
                PUSB_CONFIGURATION_DESCRIPTOR pCurCfgDr = (PUSB_CONFIGURATION_DESCRIPTOR)pCmnDr;
                if (!pCurCfgDr->iConfiguration)
                    break;
                rc = usbLibDevStrDrEntryGetForLangs(hHub, lpcszHubName, iPort, pCurCfgDr->iConfiguration, cIdLang, pIdLang, ppList);
                AssertRC(rc);
                break;
            }
            case USB_INTERFACE_DESCRIPTOR_TYPE:
            {
                if (pCmnDr->bLength != sizeof (USB_INTERFACE_DESCRIPTOR) && pCmnDr->bLength != sizeof (USB_INTERFACE_DESCRIPTOR2))
                {
                    AssertFailed();
                    break;
                }
                PUSB_INTERFACE_DESCRIPTOR pCurIfDr = (PUSB_INTERFACE_DESCRIPTOR)pCmnDr;
                if (!pCurIfDr->iInterface)
                    break;
                rc = usbLibDevStrDrEntryGetForLangs(hHub, lpcszHubName, iPort, pCurIfDr->iInterface, cIdLang, pIdLang, ppList);
                AssertRC(rc);
                break;
            }
            default:
                break;
        }

        pCur = pCur + pCmnDr->bLength;
    }

    return VINF_SUCCESS;
}

#ifndef VBOX_WITH_NEW_USB_ENUM
static int usbLibDevGetHubDevices(LPCSTR lpszName, PUSBDEVICE *ppDevs, uint32_t *pcDevs);

static int usbLibDevGetHubPortDevices(HANDLE hHub, LPCSTR lpcszHubName, ULONG iPort, PUSBDEVICE *ppDevs, uint32_t *pcDevs)
{
    int rc = VINF_SUCCESS;
    char Buf[sizeof (USB_NODE_CONNECTION_INFORMATION_EX) + (sizeof (USB_PIPE_INFO) * 20)];
    PUSB_NODE_CONNECTION_INFORMATION_EX pConInfo = (PUSB_NODE_CONNECTION_INFORMATION_EX)Buf;
    //PUSB_PIPE_INFO paPipeInfo = (PUSB_PIPE_INFO)(Buf + sizeof (PUSB_NODE_CONNECTION_INFORMATION_EX));
    DWORD cbReturned = 0;
    memset(&Buf, 0, sizeof (Buf));
    pConInfo->ConnectionIndex = iPort;
    if (!DeviceIoControl(hHub, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX,
                                  pConInfo, sizeof (Buf),
                                  pConInfo, sizeof (Buf),
                                  &cbReturned, NULL))
    {
        DWORD dwErr = GetLastError(); NOREF(dwErr);
        LogRel(("Getting USB connection information failed (dwErr=%u) on hub %s\n", dwErr, lpcszHubName));
        AssertMsg(dwErr == ERROR_DEVICE_NOT_CONNECTED, (__FUNCTION__": DeviceIoControl failed (dwErr=%u)\n", dwErr));
        return VERR_GENERAL_FAILURE;
    }

    if (pConInfo->ConnectionStatus != DeviceConnected)
    {
        /* just ignore & return success */
        return VWRN_INVALID_HANDLE;
    }

    if (pConInfo->DeviceIsHub)
    {
        LPSTR lpszChildHubName = NULL;
        rc = usbLibDevStrHubNameGet(hHub, iPort, &lpszChildHubName);
        AssertRC(rc);
        if (RT_SUCCESS(rc))
        {
            rc = usbLibDevGetHubDevices(lpszChildHubName, ppDevs, pcDevs);
            usbLibDevStrFree(lpszChildHubName);
            AssertRC(rc);
            return rc;
        }
        /* ignore this err */
        return VINF_SUCCESS;
    }

    bool fFreeNameBuf = true;
    char nameEmptyBuf = '\0';
    LPSTR lpszName = NULL;
    rc = usbLibDevStrDriverKeyGet(hHub, iPort, &lpszName);
    Assert(!!lpszName == !!RT_SUCCESS(rc));
    if (!lpszName)
    {
        LogRelFunc(("No DriverKey on hub %s port %d\n", lpcszHubName, iPort));
        lpszName = &nameEmptyBuf;
        fFreeNameBuf = false;
    }

    PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = NULL;
    PVBOXUSB_STRING_DR_ENTRY pList = NULL;
    rc = usbLibDevCfgDrGet(hHub, lpcszHubName, iPort, 0, &pCfgDr);
    if (pCfgDr)
    {
        rc = usbLibDevStrDrEntryGetAll(hHub, lpcszHubName, iPort, &pConInfo->DeviceDescriptor, pCfgDr, &pList);
#ifdef VBOX_WITH_ANNOYING_USB_ASSERTIONS
        AssertRC(rc); // this can fail if device suspended
#endif
    }

    PUSBDEVICE pDev = (PUSBDEVICE)RTMemAllocZ(sizeof (*pDev));
    if (RT_LIKELY(pDev))
    {
        rc = usbLibDevPopulate(pDev, pConInfo, iPort, lpszName, lpcszHubName, pList);
        if (RT_SUCCESS(rc))
        {
            pDev->pNext = *ppDevs;
            *ppDevs = pDev;
            ++*pcDevs;
        }
        else
            RTMemFree(pDev);
    }
    else
        rc = VERR_NO_MEMORY;

    if (pCfgDr)
        usbLibDevCfgDrFree(pCfgDr);
    if (fFreeNameBuf)
    {
        Assert(lpszName);
        usbLibDevStrFree(lpszName);
    }
    if (pList)
        usbLibDevStrDrEntryFreeList(pList);

    return rc;
}

static int usbLibDevGetHubDevices(LPCSTR lpszName, PUSBDEVICE *ppDevs, uint32_t *pcDevs)
{
    LPSTR lpszDevName = (LPSTR)RTMemAllocZ(strlen(lpszName) + sizeof("\\\\.\\"));
    HANDLE hDev = INVALID_HANDLE_VALUE;
    Assert(lpszDevName);
    if (!lpszDevName)
    {
        AssertFailed();
        return VERR_OUT_OF_RESOURCES;
    }

    int rc = VINF_SUCCESS;
    strcpy(lpszDevName, "\\\\.\\");
    strcpy(lpszDevName + sizeof("\\\\.\\") - sizeof (lpszDevName[0]), lpszName);
    do
    {
        DWORD cbReturned = 0;
        hDev = CreateFile(lpszDevName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
        if (hDev == INVALID_HANDLE_VALUE)
        {
            AssertFailed();
            break;
        }

        USB_NODE_INFORMATION NodeInfo;
        memset(&NodeInfo, 0, sizeof (NodeInfo));
        if (!DeviceIoControl(hDev, IOCTL_USB_GET_NODE_INFORMATION,
                            &NodeInfo, sizeof (NodeInfo),
                            &NodeInfo, sizeof (NodeInfo),
                            &cbReturned, NULL))
        {
            LogRel(("Getting USB node information failed (dwErr=%u) on hub %s\n", GetLastError(), lpszName));
            AssertFailed();
            break;
        }

        for (ULONG i = 1; i <= NodeInfo.u.HubInformation.HubDescriptor.bNumberOfPorts; ++i)
        {
            /* Just skip devices for which we failed to create the device structure. */
            usbLibDevGetHubPortDevices(hDev, lpszName, i, ppDevs, pcDevs);
        }
    } while (0);

    if (hDev != INVALID_HANDLE_VALUE)
        CloseHandle(hDev);

    RTMemFree(lpszDevName);

    return rc;
}
#endif

#ifdef VBOX_WITH_NEW_USB_ENUM

/* Get a registry property for a device given its HDEVINFO + SP_DEVINFO_DATA. */
static void *usbLibGetRegistryProperty(HDEVINFO InfoSet, const PSP_DEVINFO_DATA DevData, DWORD Property)
{
    BOOL    rc;
    DWORD   dwReqLen;
    void    *PropertyData;

    /* How large a buffer do we need? */
    rc = SetupDiGetDeviceRegistryProperty(InfoSet, DevData, Property,
                                          NULL, NULL, 0, &dwReqLen);
    if (!rc && (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
    {
        LogRelFunc(("Failed to query buffer size, error %ld\n", GetLastError()));
        return NULL;
    }

    PropertyData = RTMemAlloc(dwReqLen);
    if (!PropertyData)
        return NULL;

    /* Get the actual property data. */
    rc = SetupDiGetDeviceRegistryProperty(InfoSet, DevData, Property,
                                          NULL, (PBYTE)PropertyData, dwReqLen, &dwReqLen);
    if (!rc)
    {
        LogRelFunc(("Failed to get property data, error %ld\n", GetLastError()));
        RTMemFree(PropertyData);
        return NULL;
    }
    return PropertyData;
}

/* Given a HDEVINFO and SP_DEVICE_INTERFACE_DATA, get the interface detail data and optionally device info data. */
static PSP_DEVICE_INTERFACE_DETAIL_DATA usbLibGetDevDetail(HDEVINFO InfoSet, PSP_DEVICE_INTERFACE_DATA InterfaceData, PSP_DEVINFO_DATA DevInfoData)
{
    BOOL                                rc;
    DWORD                               dwReqLen;
    PSP_DEVICE_INTERFACE_DETAIL_DATA    DetailData;

    rc = SetupDiGetDeviceInterfaceDetail(InfoSet, InterfaceData, NULL, 0, &dwReqLen, DevInfoData);
    if (!rc && (GetLastError() != ERROR_INSUFFICIENT_BUFFER))
    {
        LogRelFunc(("Failed to get interface detail size, error %ld\n", GetLastError()));
        return NULL;
    }

    DetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)RTMemAlloc(dwReqLen);
    if (!DetailData)
        return NULL;

    memset(DetailData, 0, dwReqLen);
    DetailData->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

    rc = SetupDiGetDeviceInterfaceDetail(InfoSet, InterfaceData, DetailData, dwReqLen, &dwReqLen, DevInfoData);
    if (!rc)
    {
        LogRelFunc(("Failed to get interface detail, error %ld\n", GetLastError()));
        RTMemFree(DetailData);
    }

    return DetailData;
}

/* Given a hub's PnP device instance, find its device path (file name). */
static LPCSTR usbLibGetHubPathFromInstanceID(LPCSTR InstanceID)
{
    HDEVINFO                            InfoSet;
    SP_DEVICE_INTERFACE_DATA            InterfaceData;
    PSP_DEVICE_INTERFACE_DETAIL_DATA    DetailData;
    BOOL                                rc;
    LPSTR                               DevicePath = NULL;

    /* Enumerate the DevInst's USB hub interface. */
    InfoSet = SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_HUB, InstanceID, NULL,
                                  DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
    if (InfoSet == INVALID_HANDLE_VALUE)
    {
        LogRelFunc(("Failed to get interface for InstID %se, error %ld\n", InstanceID, GetLastError()));
        return NULL;
    }

    memset(&InterfaceData, 0, sizeof(InterfaceData));
    InterfaceData.cbSize = sizeof(InterfaceData);
    rc = SetupDiEnumDeviceInterfaces(InfoSet, 0, &GUID_DEVINTERFACE_USB_HUB, 0, &InterfaceData);
    if (!rc)
    {
        DWORD   dwErr = GetLastError();

        /* The parent device might not be a hub; that is valid, ignore such errors. */
        if (dwErr != ERROR_NO_MORE_ITEMS)
            LogRelFunc(("Failed to get interface data for InstID %s, error %ld\n", InstanceID, dwErr));
        SetupDiDestroyDeviceInfoList(InfoSet);
        return NULL;
    }

    DetailData = usbLibGetDevDetail(InfoSet, &InterfaceData, NULL);
    if (!DetailData)
    {
        SetupDiDestroyDeviceInfoList(InfoSet);
        return NULL;
    }

    /* Copy the device path out of the interface detail. */
    DevicePath = RTStrDup(DetailData->DevicePath);
    RTMemFree(DetailData);
    SetupDiDestroyDeviceInfoList(InfoSet);

    return DevicePath;
}


/* Use the Configuration Manager (CM) to get a devices's parent given its DEVINST and
 * turn it into a PnP device instance ID string.
 */
static LPCSTR usbLibGetParentInstanceID(DEVINST DevInst)
{
    LPSTR       InstanceID;
    DEVINST     ParentInst;
    ULONG       ulReqChars;
    ULONG       ulReqBytes;
    CONFIGRET   cr;

    /* First get the parent DEVINST. */
    cr = CM_Get_Parent(&ParentInst, DevInst, 0);
    if (cr != CR_SUCCESS)
    {
        LogRelFunc(("Failed to get parent instance, error %ld\n", GetLastError()));
        return NULL;
    }

    /* Then convert it to the instance ID string. */
    cr = CM_Get_Device_ID_Size(&ulReqChars, ParentInst, 0);
    if (cr != CR_SUCCESS)
    {
        LogRelFunc(("Failed to get device ID size (DevInst=%X), error %ld\n", DevInst, GetLastError()));
        return NULL;
    }

    /* CM_Get_Device_ID_Size gives us the size in characters without terminating null. */
    ulReqBytes = (ulReqChars + 1) * sizeof(char);
    InstanceID = (LPSTR)RTMemAlloc(ulReqBytes);
    if (!InstanceID)
        return NULL;

    cr = CM_Get_Device_ID(ParentInst, InstanceID, ulReqBytes, 0);
    if (cr != CR_SUCCESS)
    {
        LogRelFunc(("Failed to get device ID (DevInst=%X), error %ld\n", DevInst, GetLastError()));
        RTMemFree(InstanceID);
        return NULL;
    }

    return InstanceID;
}

/* Process a single USB device that's being enumerated and grab its hub-specific data. */
static int usbLibDevGetDevice(LPCSTR lpcszHubFile, ULONG iPort, LPCSTR lpcszLocation, LPCSTR lpcszDriverKey, PUSBDEVICE *ppDevs, uint32_t *pcDevs)
{
    HANDLE                                  HubDevice;
    BYTE                                    abConBuf[sizeof(USB_NODE_CONNECTION_INFORMATION_EX)];
    PUSB_NODE_CONNECTION_INFORMATION_EX     pConInfo = PUSB_NODE_CONNECTION_INFORMATION_EX(abConBuf);
    int                                     rc = VINF_SUCCESS;
    DWORD                                   cbReturned = 0;

    /* Validate inputs. */
    if ((iPort < 1) || (iPort > 255))
    {
        LogRelFunc(("Port index out of range (%u)\n", iPort));
        return VERR_INVALID_PARAMETER;
    }
    if (!lpcszHubFile)
    {
        LogRelFunc(("Hub path is NULL!\n"));
        return VERR_INVALID_PARAMETER;
    }
    if (!lpcszLocation)
    {
        LogRelFunc(("Location NULL!\n"));
        return VERR_INVALID_PARAMETER;
    }

    /* Try opening the hub file so we can send IOCTLs to it. */
    HubDevice = CreateFile(lpcszHubFile, GENERIC_WRITE, FILE_SHARE_WRITE,
                           NULL, OPEN_EXISTING, 0, NULL);
    if (HubDevice == INVALID_HANDLE_VALUE)
    {
        LogRelFunc(("Failed to open hub `%s' (dwErr=%u)\n", lpcszHubFile, GetLastError()));
        return VERR_FILE_NOT_FOUND;
    }

    /* The shenanigans with abConBuf are due to USB_NODE_CONNECTION_INFORMATION_EX
     * containing a zero-sized array, triggering compiler warnings.
     */
    memset(pConInfo, 0, sizeof(abConBuf));
    pConInfo->ConnectionIndex = iPort;

    /* We expect that IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX is always available
     * on any supported Windows version and hardware.
     * NB: IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX_V2 is Win8 and later only.
     */
    if (!DeviceIoControl(HubDevice, IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX,
                         pConInfo, sizeof(abConBuf), pConInfo, sizeof(abConBuf),
                         &cbReturned, NULL))
    {
        DWORD dwErr = GetLastError(); NOREF(dwErr);
        LogRel(("IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX failed (dwErr=%u) on hub %s, port %d\n", dwErr, lpcszHubFile, iPort));
        AssertMsg(dwErr == ERROR_DEVICE_NOT_CONNECTED, (__FUNCTION__": DeviceIoControl failed dwErr (%u)\n", dwErr));
        CloseHandle(HubDevice);
        return VERR_GENERAL_FAILURE;
    }

    if (pConInfo->ConnectionStatus != DeviceConnected)
    {
        /* Ignore this, can't do anything with it. */
        LogFunc(("Device is not connected, skipping.\n"));
        CloseHandle(HubDevice);
        return VINF_SUCCESS;
    }

    if (pConInfo->DeviceIsHub)
    {
        /* We're ignoring hubs, just skip this. */
        LogFunc(("Device is a hub, skipping.\n"));
        CloseHandle(HubDevice);
        return VINF_SUCCESS;
    }

    PUSB_CONFIGURATION_DESCRIPTOR pCfgDr = NULL;
    PVBOXUSB_STRING_DR_ENTRY pList = NULL;
    rc = usbLibDevCfgDrGet(HubDevice, lpcszHubFile, iPort, 0, &pCfgDr);
    if (pCfgDr)
    {
        rc = usbLibDevStrDrEntryGetAll(HubDevice, lpcszHubFile, iPort, &pConInfo->DeviceDescriptor, pCfgDr, &pList);
#ifdef VBOX_WITH_ANNOYING_USB_ASSERTIONS
        AssertRC(rc); // this can fail if device suspended
#endif
    }

    /* At this point we're done with the hub device. */
    CloseHandle(HubDevice);

    PUSBDEVICE pDev = (PUSBDEVICE)RTMemAllocZ(sizeof (*pDev));
    if (RT_LIKELY(pDev))
    {
        rc = usbLibDevPopulate(pDev, pConInfo, iPort, lpcszLocation, lpcszDriverKey, lpcszHubFile, pList);
        if (RT_SUCCESS(rc))
        {
            pDev->pNext = *ppDevs;
            *ppDevs = pDev;
            ++*pcDevs;
        }
        else
            RTMemFree(pDev);
    }
    else
        rc = VERR_NO_MEMORY;

    if (pCfgDr)
        usbLibDevCfgDrFree(pCfgDr);
    if (pList)
        usbLibDevStrDrEntryFreeList(pList);

    return rc;
}


/*
 * Enumerate the USB devices in the host system. Since we do not care about the hierarchical
 * structure of root hubs, other hubs, and devices, we just ask the USB PnP enumerator to
 * give us all it has. This includes hubs (though not root hubs), as well as multiple child
 * interfaces of multi-interface USB devices, which we filter out. It also includes USB
 * devices with no driver, which is notably something we cannot get by enumerating via
 * GUID_DEVINTERFACE_USB_DEVICE.
 *
 * This approach also saves us some trouble relative to enumerating devices via hub IOCTLs and
 * then hunting through the PnP manager to find them. Instead, we look up the device's parent
 * which (for devices we're interested in) is always a hub, and that allows us to obtain
 * USB-specific data (descriptors, speeds, etc.) when combined with the devices PnP "address"
 * (USB port on parent hub).
 *
 * NB: Every USB device known to the Windows PnP Manager will have a device instance ID. Typically
 * it also has a DriverKey but only if it has a driver installed. Hence we ignore the DriverKey, at
 * least prior to capturing (once VBoxUSB.sys is installed, a DriverKey must by definition be
 * present). Also note that the device instance ID changes for captured devices since we change
 * their USB VID/PID, though it is unique at any given point.
 *
 * The location information should be a reliable way of identifying a device and does not change
 * with driver installs, capturing, etc. USB device location information is only available on
 * Windows Vista and later; earlier Windows version had no reliable way of cross-referencing the
 * USB IOCTL and PnP Manager data.
 */
static int usbLibEnumDevices(PUSBDEVICE *ppDevs, uint32_t *pcDevs)
{
    HDEVINFO            InfoSet;
    DWORD               DeviceIndex;
    LPDWORD             Address;
    SP_DEVINFO_DATA     DeviceData;
    LPCSTR              ParentInstID;
    LPCSTR              HubPath = NULL;
    LPCSTR              Location;
    LPCSTR              DriverKey;

    /* Ask the USB PnP enumerator for all it has. */
    InfoSet = SetupDiGetClassDevs(NULL, "USB", NULL, DIGCF_ALLCLASSES | DIGCF_PRESENT);

    memset(&DeviceData, 0, sizeof(DeviceData));
    DeviceData.cbSize = sizeof(DeviceData);
    DeviceIndex = 0;

    /* Enumerate everything in the info set. */
    while (SetupDiEnumDeviceInfo(InfoSet, DeviceIndex, &DeviceData))
    {
        /* Use the CM API to get the parent instance ID. */
        ParentInstID = usbLibGetParentInstanceID(DeviceData.DevInst);

        /* Now figure out the hub's file path fron the instance ID, if there is one. */
        if (ParentInstID)
            HubPath = usbLibGetHubPathFromInstanceID(ParentInstID);

        /* If there's no hub interface on the parent, then this might be a child
         * device of a multi-interface device. Either way, we're not interested.
         */
        if (HubPath)
        {
            /* The location information uniquely identifies the USB device, (hub/port). */
            Location = (LPCSTR)usbLibGetRegistryProperty(InfoSet, &DeviceData, SPDRP_LOCATION_PATHS);

            /* The software key aka DriverKey. This will be NULL for devices with no driver
             * and allows us to distinguish between 'busy' (driver installed) and 'available'
             * (no driver) devices.
             */
            DriverKey = (LPCSTR)usbLibGetRegistryProperty(InfoSet, &DeviceData, SPDRP_DRIVER);

            /* The device's PnP Manager "address" is the port number on the parent hub. */
            Address = (LPDWORD)usbLibGetRegistryProperty(InfoSet, &DeviceData, SPDRP_ADDRESS);
            if (Address && Location)    /* NB: DriverKey may be NULL! */
            {
                usbLibDevGetDevice(HubPath, *Address, Location, DriverKey, ppDevs, pcDevs);
            }
            RTMemFree((void *)HubPath);

            if (Location)
                RTMemFree((void *)Location);
            if (DriverKey)
                RTMemFree((void *)DriverKey);
            if (Address)
                RTMemFree((void *)Address);
        }

        /* Clean up after this device. */
        if (ParentInstID)
            RTMemFree((void *)ParentInstID);

        ++DeviceIndex;
        memset(&DeviceData, 0, sizeof(DeviceData));
        DeviceData.cbSize = sizeof(DeviceData);
    }

    if (InfoSet)
        SetupDiDestroyDeviceInfoList(InfoSet);

    return VINF_SUCCESS;
}

#else
static int usbLibDevGetDevices(PUSBDEVICE *ppDevs, uint32_t *pcDevs)
{
    char CtlName[16];
    int rc = VINF_SUCCESS;

    for (int i = 0; i < 10; ++i)
    {
        RTStrPrintf(CtlName, sizeof(CtlName), "\\\\.\\HCD%d", i);
        HANDLE hCtl = CreateFile(CtlName, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
        if (hCtl != INVALID_HANDLE_VALUE)
        {
            char* lpszName;
            rc = usbLibDevStrRootHubNameGet(hCtl, &lpszName);
            AssertRC(rc);
            if (RT_SUCCESS(rc))
            {
                rc = usbLibDevGetHubDevices(lpszName, ppDevs, pcDevs);
                AssertRC(rc);
                usbLibDevStrFree(lpszName);
            }
            CloseHandle(hCtl);
            if (RT_FAILURE(rc))
                break;
        }
    }
    return VINF_SUCCESS;
}
#endif

static int usbLibMonDevicesCmp(PUSBDEVICE pDev, PVBOXUSB_DEV pDevInfo)
{
    int iDiff;
    iDiff = strcmp(pDev->pszAddress, pDevInfo->szDriverRegName);
    return iDiff;
}

static int usbLibMonDevicesUpdate(PVBOXUSBGLOBALSTATE pGlobal, PUSBDEVICE pDevs, PVBOXUSB_DEV pDevInfos)
{

    PUSBDEVICE pDevsHead = pDevs;
    for (; pDevInfos; pDevInfos = pDevInfos->pNext)
    {
        for (pDevs = pDevsHead; pDevs; pDevs = pDevs->pNext)
        {
            if (usbLibMonDevicesCmp(pDevs, pDevInfos))
                continue;

            if (!pDevInfos->szDriverRegName[0])
            {
                AssertFailed();
                break;
            }

            USBSUP_GETDEV Dev = {0};
            HANDLE hDev = CreateFile(pDevInfos->szName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL,
                                                          OPEN_EXISTING,  FILE_ATTRIBUTE_SYSTEM, NULL);
            if (hDev == INVALID_HANDLE_VALUE)
            {
                AssertFailed();
                break;
            }

            DWORD cbReturned = 0;
            if (!DeviceIoControl(hDev, SUPUSB_IOCTL_GET_DEVICE, &Dev, sizeof (Dev), &Dev, sizeof (Dev), &cbReturned, NULL))
            {
                DWORD dwErr = GetLastError();
#ifdef VBOX_WITH_ANNOYING_USB_ASSERTIONS
                /* ERROR_DEVICE_NOT_CONNECTED -> device was removed just now */
                AsserFailed();
#endif
                LogRelFunc(("SUPUSB_IOCTL_GET_DEVICE failed on '%s' (dwErr=%u)!\n", pDevInfos->szName, dwErr));
                CloseHandle(hDev);
                break;
            }

            /* we must not close the handle until we request for the device state from the monitor to ensure
             * the device handle returned by the device driver does not disappear */
            Assert(Dev.hDevice);
            USBSUP_GETDEV_MON MonInfo;
            HVBOXUSBDEVUSR hDevice = Dev.hDevice;
            if (!DeviceIoControl(pGlobal->hMonitor, SUPUSBFLT_IOCTL_GET_DEVICE, &hDevice, sizeof (hDevice), &MonInfo, sizeof (MonInfo), &cbReturned, NULL))
            {
                DWORD dwErr = GetLastError();
                /* ERROR_DEVICE_NOT_CONNECTED -> device was removed just now */
                AssertFailed();
                LogRelFunc(("SUPUSBFLT_IOCTL_GET_DEVICE failed for '%s' (hDevice=%p, dwErr=%u)!\n", pDevInfos->szName, hDevice, dwErr));
                CloseHandle(hDev);
                break;
            }

            CloseHandle(hDev);

            /* success!! update device info */
            /* ensure the state returned is valid */
            Assert(    MonInfo.enmState == USBDEVICESTATE_USED_BY_HOST
                    || MonInfo.enmState == USBDEVICESTATE_USED_BY_HOST_CAPTURABLE
                    || MonInfo.enmState == USBDEVICESTATE_UNUSED
                    || MonInfo.enmState == USBDEVICESTATE_HELD_BY_PROXY
                    || MonInfo.enmState == USBDEVICESTATE_USED_BY_GUEST);
            pDevs->enmState = MonInfo.enmState;

            if (pDevs->enmState != USBDEVICESTATE_USED_BY_HOST)
            {
                /* only set the interface name if device can be grabbed */
                RTStrFree(pDevs->pszAltAddress);
                pDevs->pszAltAddress = (char*)pDevs->pszAddress;
                pDevs->pszAddress = RTStrDup(pDevInfos->szName);
            }
#ifdef VBOX_WITH_ANNOYING_USB_ASSERTIONS
            else
            {
                /* dbg breakpoint */
                AssertFailed();
            }
#endif

            /* we've found the device, break in any way */
            break;
        }
    }

    return VINF_SUCCESS;
}

static int usbLibGetDevices(PVBOXUSBGLOBALSTATE pGlobal, PUSBDEVICE *ppDevs, uint32_t *pcDevs)
{
    *ppDevs = NULL;
    *pcDevs = 0;

    LogRelFunc(("Starting USB device enumeration\n"));
#ifdef VBOX_WITH_NEW_USB_ENUM
    int rc = usbLibEnumDevices(ppDevs, pcDevs);
#else
    int rc = usbLibDevGetDevices(ppDevs, pcDevs);
#endif
    AssertRC(rc);
    if (RT_SUCCESS(rc))
    {
        PVBOXUSB_DEV pDevInfos = NULL;
        uint32_t cDevInfos = 0;
#ifdef VBOX_WITH_NEW_USB_ENUM
        rc = usbLibEnumVUsbDevices(&pDevInfos, &cDevInfos);
#else
        rc = usbLibVuGetDevices(&pDevInfos, &cDevInfos);
#endif
        AssertRC(rc);
        if (RT_SUCCESS(rc))
        {
            rc = usbLibMonDevicesUpdate(pGlobal, *ppDevs, pDevInfos);
            AssertRC(rc);
            usbLibVuFreeDevices(pDevInfos);
        }

        LogRelFunc(("Found %u USB devices, %u captured\n", *pcDevs, cDevInfos));
        return VINF_SUCCESS;
    }
    return rc;
}

AssertCompile(INFINITE == RT_INDEFINITE_WAIT);
static int usbLibStateWaitChange(PVBOXUSBGLOBALSTATE pGlobal, RTMSINTERVAL cMillies)
{
    HANDLE ahEvents[] = {pGlobal->hNotifyEvent, pGlobal->hInterruptEvent};
    DWORD dwResult = WaitForMultipleObjects(RT_ELEMENTS(ahEvents), ahEvents,
                        FALSE, /* BOOL bWaitAll */
                        cMillies);

    switch (dwResult)
    {
        case WAIT_OBJECT_0:
            return VINF_SUCCESS;
        case WAIT_OBJECT_0 + 1:
            return VERR_INTERRUPTED;
        case WAIT_TIMEOUT:
            return VERR_TIMEOUT;
        default:
        {
            DWORD dwErr = GetLastError(); NOREF(dwErr);
            AssertMsgFailed(("WaitForMultipleObjects failed, dwErr (%u)\n", dwErr));
            return VERR_GENERAL_FAILURE;
        }
    }
}

AssertCompile(RT_INDEFINITE_WAIT == INFINITE);
AssertCompile(sizeof (RTMSINTERVAL) == sizeof (DWORD));
USBLIB_DECL(int) USBLibWaitChange(RTMSINTERVAL msWaitTimeout)
{
    return usbLibStateWaitChange(&g_VBoxUsbGlobal, msWaitTimeout);
}

static int usbLibInterruptWaitChange(PVBOXUSBGLOBALSTATE pGlobal)
{
    BOOL fRc = SetEvent(pGlobal->hInterruptEvent);
    if (!fRc)
    {
        DWORD dwErr = GetLastError(); NOREF(dwErr);
        AssertMsgFailed(("SetEvent failed, dwErr (%u)\n", dwErr));
        return VERR_GENERAL_FAILURE;
    }
    return VINF_SUCCESS;
}

USBLIB_DECL(int) USBLibInterruptWaitChange(void)
{
    return usbLibInterruptWaitChange(&g_VBoxUsbGlobal);
}

/*
USBLIB_DECL(bool) USBLibHasPendingDeviceChanges(void)
{
    int rc = USBLibWaitChange(0);
    return rc == VINF_SUCCESS;
}
*/

USBLIB_DECL(int) USBLibGetDevices(PUSBDEVICE *ppDevices, uint32_t *pcbNumDevices)
{
    Assert(g_VBoxUsbGlobal.hMonitor != INVALID_HANDLE_VALUE);
    return usbLibGetDevices(&g_VBoxUsbGlobal, ppDevices, pcbNumDevices);
}

USBLIB_DECL(void *) USBLibAddFilter(PCUSBFILTER pFilter)
{
    USBSUP_FLTADDOUT FltAddRc;
    DWORD cbReturned = 0;

    if (g_VBoxUsbGlobal.hMonitor == INVALID_HANDLE_VALUE)
    {
#ifdef VBOX_WITH_ANNOYING_USB_ASSERTIONS
        AssertFailed();
#endif
        return NULL;
    }

    Log(("usblibInsertFilter: Manufacturer=%s Product=%s Serial=%s\n",
         USBFilterGetString(pFilter, USBFILTERIDX_MANUFACTURER_STR)  ? USBFilterGetString(pFilter, USBFILTERIDX_MANUFACTURER_STR)  : "<null>",
         USBFilterGetString(pFilter, USBFILTERIDX_PRODUCT_STR)       ? USBFilterGetString(pFilter, USBFILTERIDX_PRODUCT_STR)       : "<null>",
         USBFilterGetString(pFilter, USBFILTERIDX_SERIAL_NUMBER_STR) ? USBFilterGetString(pFilter, USBFILTERIDX_SERIAL_NUMBER_STR) : "<null>"));

    if (!DeviceIoControl(g_VBoxUsbGlobal.hMonitor, SUPUSBFLT_IOCTL_ADD_FILTER,
                (LPVOID)pFilter, sizeof(*pFilter),
                &FltAddRc, sizeof(FltAddRc),
                &cbReturned, NULL))
    {
        DWORD dwErr = GetLastError();
        AssertFailed();
        LogRelFunc(("SUPUSBFLT_IOCTL_ADD_FILTER failed (dwErr=%u)!\n", dwErr));
        return NULL;
    }

    if (RT_FAILURE(FltAddRc.rc))
    {
        AssertFailed();
        LogRelFunc(("Adding a USB filter failed with rc=%d!\n", FltAddRc.rc));
        return NULL;
    }

    LogRel(("Added USB filter (ID=%u, type=%d) for device %04X:%04X rev %04X, c/s/p %02X/%02X/%02X, Manufacturer=`%s' Product=`%s' Serial=`%s'\n", FltAddRc.uId, USBFilterGetFilterType(pFilter),
            USBFilterGetNum(pFilter, USBFILTERIDX_VENDOR_ID), USBFilterGetNum(pFilter, USBFILTERIDX_PRODUCT_ID), USBFilterGetNum(pFilter, USBFILTERIDX_DEVICE_REV),
            USBFilterGetNum(pFilter, USBFILTERIDX_DEVICE_CLASS), USBFilterGetNum(pFilter, USBFILTERIDX_DEVICE_SUB_CLASS), USBFilterGetNum(pFilter, USBFILTERIDX_DEVICE_PROTOCOL),
            USBFilterGetString(pFilter, USBFILTERIDX_MANUFACTURER_STR)  ? USBFilterGetString(pFilter, USBFILTERIDX_MANUFACTURER_STR)  : "<null>",
            USBFilterGetString(pFilter, USBFILTERIDX_PRODUCT_STR)       ? USBFilterGetString(pFilter, USBFILTERIDX_PRODUCT_STR)       : "<null>",
         USBFilterGetString(pFilter, USBFILTERIDX_SERIAL_NUMBER_STR) ? USBFilterGetString(pFilter, USBFILTERIDX_SERIAL_NUMBER_STR) : "<null>"));

    return (void *)FltAddRc.uId;
}


USBLIB_DECL(void) USBLibRemoveFilter(void *pvId)
{
    uintptr_t uId;
    DWORD cbReturned = 0;

    if (g_VBoxUsbGlobal.hMonitor == INVALID_HANDLE_VALUE)
    {
#ifdef VBOX_WITH_ANNOYING_USB_ASSERTIONS
        AssertFailed();
#endif
        return;
    }

    Log(("usblibRemoveFilter %p\n", pvId));

    uId = (uintptr_t)pvId;
    if (!DeviceIoControl(g_VBoxUsbGlobal.hMonitor, SUPUSBFLT_IOCTL_REMOVE_FILTER, &uId, sizeof(uId),  NULL, 0,&cbReturned, NULL))
    {
        DWORD dwErr = GetLastError();
        AssertFailed();
        LogRelFunc(("SUPUSBFLT_IOCTL_REMOVE_FILTER failed (dwErr=%u)!\n", dwErr));
    }
    else
        LogRel(("Removed USB filter ID=%u\n", uId));
}

USBLIB_DECL(int) USBLibRunFilters(void)
{
    DWORD cbReturned = 0;

    Assert(g_VBoxUsbGlobal.hMonitor != INVALID_HANDLE_VALUE);

    if (!DeviceIoControl(g_VBoxUsbGlobal.hMonitor, SUPUSBFLT_IOCTL_RUN_FILTERS,
                NULL, 0,
                NULL, 0,
                &cbReturned, NULL))
    {
        DWORD dwErr = GetLastError();
        AssertFailed();
        LogRelFunc(("SUPUSBFLT_IOCTL_RUN_FILTERS failed (dwErr=%u)!\n", dwErr));
        return RTErrConvertFromWin32(dwErr);
    }

    return VINF_SUCCESS;
}


static VOID CALLBACK usbLibTimerCallback(__in PVOID lpParameter, __in BOOLEAN TimerOrWaitFired) RT_NOTHROW_DEF
{
    RT_NOREF2(lpParameter, TimerOrWaitFired);
    SetEvent(g_VBoxUsbGlobal.hNotifyEvent);
}

static void usbLibOnDeviceChange(void)
{
    /* we're getting series of events like that especially on device re-attach
     * (i.e. first for device detach and then for device attach)
     * unfortunately the event does not tell us what actually happened.
     * To avoid extra notifications, we delay the SetEvent via a timer
     * and update the timer if additional notification comes before the timer fires
     * */
    if (g_VBoxUsbGlobal.hTimer)
    {
        if (!DeleteTimerQueueTimer(g_VBoxUsbGlobal.hTimerQueue, g_VBoxUsbGlobal.hTimer, NULL))
        {
            DWORD dwErr = GetLastError(); NOREF(dwErr);
            AssertMsg(dwErr == ERROR_IO_PENDING, ("DeleteTimerQueueTimer failed, dwErr (%u)\n", dwErr));
        }
    }

    if (!CreateTimerQueueTimer(&g_VBoxUsbGlobal.hTimer, g_VBoxUsbGlobal.hTimerQueue,
                               usbLibTimerCallback,
                               NULL,
                               500, /* ms*/
                               0,
                               WT_EXECUTEONLYONCE))
    {
        DWORD dwErr = GetLastError(); NOREF(dwErr);
        AssertMsgFailed(("CreateTimerQueueTimer failed, dwErr (%u)\n", dwErr));

        /* call it directly */
        usbLibTimerCallback(NULL, FALSE);
    }
}

static LRESULT CALLBACK usbLibWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
        case WM_DEVICECHANGE:
            if (wParam == DBT_DEVNODES_CHANGED)
            {
                /* we notify change any device arivals/removals on the system
                 * and let the client decide whether the usb change actually happened
                 * so far this is more clean than reporting events from the Monitor
                 * because monitor sees only PDO arrivals/removals,
                 * and by the time PDO is created, device can not
                 * be yet started and fully functional,
                 * so usblib won't be able to pick it up
                 * */

                usbLibOnDeviceChange();
            }
            break;
         case WM_DESTROY:
            {
                PostQuitMessage(0);
                return 0;
            }
    }
    return DefWindowProc (hwnd, uMsg, wParam, lParam);
}

/** @todo r=bird: Use an IPRT thread!! */
static DWORD WINAPI usbLibMsgThreadProc(__in LPVOID lpParameter) RT_NOTHROW_DEF
{
    static LPCSTR   s_szVBoxUsbWndClassName = "VBoxUsbLibClass";
    const HINSTANCE hInstance               = (HINSTANCE)GetModuleHandle(NULL);
    RT_NOREF1(lpParameter);

    Assert(g_VBoxUsbGlobal.hWnd == NULL);
    g_VBoxUsbGlobal.hWnd = NULL;

    /*
     * Register the Window Class and create the hidden window.
     */
    WNDCLASS wc;
    wc.style         = 0;
    wc.lpfnWndProc   = usbLibWndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = sizeof(void *);
    wc.hInstance     = hInstance;
    wc.hIcon         = NULL;
    wc.hCursor       = NULL;
    wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
    wc.lpszMenuName  = NULL;
    wc.lpszClassName = s_szVBoxUsbWndClassName;
    ATOM atomWindowClass = RegisterClass(&wc);
    if (atomWindowClass != 0)
        g_VBoxUsbGlobal.hWnd = CreateWindowEx(WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
                                              s_szVBoxUsbWndClassName, s_szVBoxUsbWndClassName,
                                              WS_POPUPWINDOW,
                                              -200, -200, 100, 100, NULL, NULL, hInstance, NULL);
    else
        AssertMsgFailed(("RegisterClass failed, last error %u\n", GetLastError()));

    /*
     * Signal the creator thread.
     */
    ASMCompilerBarrier();
    SetEvent(g_VBoxUsbGlobal.hNotifyEvent);

    if (g_VBoxUsbGlobal.hWnd)
    {
        /* Make sure it's really hidden. */
        SetWindowPos(g_VBoxUsbGlobal.hWnd, HWND_TOPMOST, -200, -200, 0, 0,
                     SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);

        /*
         * The message pump.
         */
        MSG msg;
        BOOL fRet;
        while ((fRet = GetMessage(&msg, NULL, 0, 0)) > 0)
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        Assert(fRet >= 0);
    }

    if (atomWindowClass != NULL)
        UnregisterClass(s_szVBoxUsbWndClassName, hInstance);

    return 0;
}


/**
 * Initialize the USB library
 *
 * @returns VBox status code.
 */
USBLIB_DECL(int) USBLibInit(void)
{
    int rc = VERR_GENERAL_FAILURE;

    Log(("usbproxy: usbLibInit\n"));

    RT_ZERO(g_VBoxUsbGlobal);
    g_VBoxUsbGlobal.hMonitor = INVALID_HANDLE_VALUE;

    /*
     * Create the notification and interrupt event before opening the device.
     */
    g_VBoxUsbGlobal.hNotifyEvent = CreateEvent(NULL,  /* LPSECURITY_ATTRIBUTES lpEventAttributes */
                                               FALSE, /* BOOL bManualReset */
                                               FALSE, /* set to false since it will be initially used for notification thread startup sync */
                                               NULL   /* LPCTSTR lpName */);
    if (g_VBoxUsbGlobal.hNotifyEvent)
    {
        g_VBoxUsbGlobal.hInterruptEvent = CreateEvent(NULL,  /* LPSECURITY_ATTRIBUTES lpEventAttributes */
                                                      FALSE, /* BOOL bManualReset */
                                                      FALSE, /* BOOL bInitialState */
                                                      NULL   /* LPCTSTR lpName */);
        if (g_VBoxUsbGlobal.hInterruptEvent)
        {
            /*
             * Open the USB monitor device, starting if needed.
             */
            g_VBoxUsbGlobal.hMonitor = CreateFile(USBMON_DEVICE_NAME,
                                                  GENERIC_READ | GENERIC_WRITE,
                                                  FILE_SHARE_READ | FILE_SHARE_WRITE,
                                                  NULL,
                                                  OPEN_EXISTING,
                                                  FILE_ATTRIBUTE_SYSTEM,
                                                  NULL);

            if (g_VBoxUsbGlobal.hMonitor == INVALID_HANDLE_VALUE)
            {
                HRESULT hr = VBoxDrvCfgSvcStart(USBMON_SERVICE_NAME_W);
                if (hr == S_OK)
                {
                    g_VBoxUsbGlobal.hMonitor = CreateFile(USBMON_DEVICE_NAME,
                                                          GENERIC_READ | GENERIC_WRITE,
                                                          FILE_SHARE_READ | FILE_SHARE_WRITE,
                                                          NULL,
                                                          OPEN_EXISTING,
                                                          FILE_ATTRIBUTE_SYSTEM,
                                                          NULL);
                    if (g_VBoxUsbGlobal.hMonitor == INVALID_HANDLE_VALUE)
                    {
                        DWORD dwErr = GetLastError();
                        LogRelFunc(("CreateFile failed (dwErr=%u) for `%s'\n", dwErr, USBMON_DEVICE_NAME));
                        rc = VERR_FILE_NOT_FOUND;
                    }
                }
            }

            if (g_VBoxUsbGlobal.hMonitor != INVALID_HANDLE_VALUE)
            {
                /*
                 * Check the USB monitor version.
                 *
                 * Drivers are backwards compatible within the same major
                 * number.  We consider the minor version number this library
                 * is compiled with to be the minimum required by the driver.
                 * This is by reasoning that the library uses the full feature
                 * set of the driver it's written for.
                 */
                USBSUP_VERSION  Version = {0};
                DWORD           cbReturned = 0;
                if (DeviceIoControl(g_VBoxUsbGlobal.hMonitor, SUPUSBFLT_IOCTL_GET_VERSION,
                                    NULL, 0,
                                    &Version, sizeof (Version),
                                    &cbReturned, NULL))
                {
                    if (   Version.u32Major == USBMON_MAJOR_VERSION
#if USBMON_MINOR_VERSION != 0
                        && Version.u32Minor >= USBMON_MINOR_VERSION
#endif
                        )
                    {
                        /*
                         * We can not use USB Mon for reliable device add/remove tracking
                         * since once USB Mon is notified about PDO creation and/or IRP_MN_START_DEVICE,
                         * the function device driver may still do some initialization, which might result in
                         * notifying too early.
                         * Instead we use WM_DEVICECHANGE + DBT_DEVNODES_CHANGED to make Windows notify us about
                         * device arivals/removals.
                         * Since WM_DEVICECHANGE is a window message, create a dedicated thread to be used for WndProc and stuff.
                         * The thread would create a window, track windows messages and call usbLibOnDeviceChange on WM_DEVICECHANGE arrival.
                         * See comments in usbLibOnDeviceChange function for detail about using the timer queue.
                         */
                        g_VBoxUsbGlobal.hTimerQueue = CreateTimerQueue();
                        if (g_VBoxUsbGlobal.hTimerQueue)
                        {
/** @todo r=bird: Which lunatic used CreateThread here?!?
 *  Only the CRT uses CreateThread. */
                            g_VBoxUsbGlobal.hThread = CreateThread(
                              NULL, /*__in_opt   LPSECURITY_ATTRIBUTES lpThreadAttributes, */
                              0, /*__in       SIZE_T dwStackSize, */
                              usbLibMsgThreadProc, /*__in       LPTHREAD_START_ROUTINE lpStartAddress,*/
                              NULL, /*__in_opt   LPVOID lpParameter,*/
                              0, /*__in       DWORD dwCreationFlags,*/
                              NULL /*__out_opt  LPDWORD lpThreadId*/
                            );
                            if (g_VBoxUsbGlobal.hThread)
                            {
                                DWORD dwResult = WaitForSingleObject(g_VBoxUsbGlobal.hNotifyEvent, INFINITE);
                                Assert(dwResult == WAIT_OBJECT_0);
                                if (g_VBoxUsbGlobal.hWnd)
                                {
                                    /*
                                     * We're DONE!
                                     *
                                     * Just ensure that the event is set so the
                                     * first "wait change" request is processed.
                                     */
                                    SetEvent(g_VBoxUsbGlobal.hNotifyEvent);
                                    return VINF_SUCCESS;
                                }

                                dwResult = WaitForSingleObject(g_VBoxUsbGlobal.hThread, INFINITE);
                                Assert(dwResult == WAIT_OBJECT_0);
                                BOOL fRc = CloseHandle(g_VBoxUsbGlobal.hThread); NOREF(fRc);
                                DWORD dwErr = GetLastError(); NOREF(dwErr);
                                AssertMsg(fRc, ("CloseHandle for hThread failed (dwErr=%u)\n", dwErr));
                                g_VBoxUsbGlobal.hThread = INVALID_HANDLE_VALUE;
                            }
                            else
                            {
                                DWORD dwErr = GetLastError(); NOREF(dwErr);
                                AssertMsgFailed(("CreateThread failed, (dwErr=%u)\n", dwErr));
                                rc = VERR_GENERAL_FAILURE;
                            }

                            DeleteTimerQueueEx(g_VBoxUsbGlobal.hTimerQueue, INVALID_HANDLE_VALUE /* see term */);
                            g_VBoxUsbGlobal.hTimerQueue = NULL;
                        }
                        else
                        {
                            DWORD dwErr = GetLastError(); NOREF(dwErr);
                            AssertMsgFailed(("CreateTimerQueue failed (dwErr=%u)\n", dwErr));
                        }
                    }
                    else
                    {
                        LogRelFunc(("USB Monitor driver version mismatch! driver=%u.%u library=%u.%u\n",
                                Version.u32Major, Version.u32Minor, USBMON_MAJOR_VERSION, USBMON_MINOR_VERSION));
#ifdef VBOX_WITH_ANNOYING_USB_ASSERTIONS
                        AssertFailed();
#endif
                        rc = VERR_VERSION_MISMATCH;
                    }
                }
                else
                {
                    DWORD dwErr = GetLastError(); NOREF(dwErr);
                    LogRelFunc(("SUPUSBFLT_IOCTL_GET_VERSION failed (dwErr=%u)\n", dwErr));
                    AssertFailed();
                    rc = VERR_VERSION_MISMATCH;
                }

                CloseHandle(g_VBoxUsbGlobal.hMonitor);
                g_VBoxUsbGlobal.hMonitor = INVALID_HANDLE_VALUE;
            }
            else
            {
                LogRelFunc(("USB Service not found\n"));
#ifdef VBOX_WITH_ANNOYING_USB_ASSERTIONS
                AssertFailed();
#endif
                rc = VERR_FILE_NOT_FOUND;
            }

            CloseHandle(g_VBoxUsbGlobal.hInterruptEvent);
            g_VBoxUsbGlobal.hInterruptEvent = NULL;
        }
        else
        {
            AssertMsgFailed(("CreateEvent for InterruptEvent failed (dwErr=%u)\n", GetLastError()));
            rc = VERR_GENERAL_FAILURE;
        }

        CloseHandle(g_VBoxUsbGlobal.hNotifyEvent);
        g_VBoxUsbGlobal.hNotifyEvent = NULL;
    }
    else
    {
        AssertMsgFailed(("CreateEvent for NotifyEvent failed (dwErr=%u)\n", GetLastError()));
        rc = VERR_GENERAL_FAILURE;
    }

    /* since main calls us even if USBLibInit fails,
     * we use hMonitor == INVALID_HANDLE_VALUE as a marker to indicate whether the lib is inited */

    Assert(RT_FAILURE(rc));
    return rc;
}


/**
 * Terminate the USB library
 *
 * @returns VBox status code.
 */
USBLIB_DECL(int) USBLibTerm(void)
{
    if (g_VBoxUsbGlobal.hMonitor == INVALID_HANDLE_VALUE)
    {
        Assert(g_VBoxUsbGlobal.hInterruptEvent == NULL);
        Assert(g_VBoxUsbGlobal.hNotifyEvent == NULL);
        return VINF_SUCCESS;
    }

    BOOL fRc;
    fRc = PostMessage(g_VBoxUsbGlobal.hWnd, WM_CLOSE, 0, 0);
    AssertMsg(fRc, ("PostMessage for hWnd failed (dwErr=%u)\n", GetLastError()));

    if (g_VBoxUsbGlobal.hThread != NULL)
    {
        DWORD dwResult = WaitForSingleObject(g_VBoxUsbGlobal.hThread, INFINITE);
        Assert(dwResult == WAIT_OBJECT_0); NOREF(dwResult);
        fRc = CloseHandle(g_VBoxUsbGlobal.hThread);
        AssertMsg(fRc, ("CloseHandle for hThread failed (dwErr=%u)\n", GetLastError()));
    }

    if (g_VBoxUsbGlobal.hTimer)
    {
        fRc = DeleteTimerQueueTimer(g_VBoxUsbGlobal.hTimerQueue, g_VBoxUsbGlobal.hTimer,
                                    INVALID_HANDLE_VALUE); /* <-- to block until the timer is completed */
        AssertMsg(fRc, ("DeleteTimerQueueTimer failed (dwErr=%u)\n", GetLastError()));
    }

    if (g_VBoxUsbGlobal.hTimerQueue)
    {
        fRc = DeleteTimerQueueEx(g_VBoxUsbGlobal.hTimerQueue,
                                 INVALID_HANDLE_VALUE); /* <-- to block until all timers are completed */
        AssertMsg(fRc, ("DeleteTimerQueueEx failed (dwErr=%u)\n", GetLastError()));
    }

    fRc = CloseHandle(g_VBoxUsbGlobal.hMonitor);
    AssertMsg(fRc, ("CloseHandle for hMonitor failed (dwErr=%u)\n", GetLastError()));
    g_VBoxUsbGlobal.hMonitor = INVALID_HANDLE_VALUE;

    fRc = CloseHandle(g_VBoxUsbGlobal.hInterruptEvent);
    AssertMsg(fRc, ("CloseHandle for hInterruptEvent failed (dwErr=%u)\n", GetLastError()));
    g_VBoxUsbGlobal.hInterruptEvent = NULL;

    fRc = CloseHandle(g_VBoxUsbGlobal.hNotifyEvent);
    AssertMsg(fRc, ("CloseHandle for hNotifyEvent failed (dwErr=%u)\n", GetLastError()));
    g_VBoxUsbGlobal.hNotifyEvent = NULL;

    return VINF_SUCCESS;
}