summaryrefslogtreecommitdiff
path: root/src/VBox/HostDrivers/VBoxUSB/win/mon/VBoxUsbMon.cpp
blob: 909e98b22727c3eadf8cd2bf1ecac04d7cb9be48 (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
/* $Id$ */
/** @file
 * VBox USB Monitor
 */

/*
 * Copyright (C) 2011-2016 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE 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.
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#include "VBoxUsbMon.h"
#include "../cmn/VBoxUsbIdc.h"
#include <vbox/err.h>
#include <VBox/usblib.h>
#include <excpt.h>
#include <stdio.h>


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
/*
 * Note: Must match the VID & PID in the USB driver .inf file!!
 */
/*
  BusQueryDeviceID USB\Vid_80EE&Pid_CAFE
  BusQueryInstanceID 2
  BusQueryHardwareIDs USB\Vid_80EE&Pid_CAFE&Rev_0100
  BusQueryHardwareIDs USB\Vid_80EE&Pid_CAFE
  BusQueryCompatibleIDs USB\Class_ff&SubClass_00&Prot_00
  BusQueryCompatibleIDs USB\Class_ff&SubClass_00
  BusQueryCompatibleIDs USB\Class_ff
*/

#define szBusQueryDeviceId       L"USB\\Vid_80EE&Pid_CAFE"
#define szBusQueryHardwareIDs    L"USB\\Vid_80EE&Pid_CAFE&Rev_0100\0USB\\Vid_80EE&Pid_CAFE\0\0"
#define szBusQueryCompatibleIDs  L"USB\\Class_ff&SubClass_00&Prot_00\0USB\\Class_ff&SubClass_00\0USB\\Class_ff\0\0"

#define szDeviceTextDescription          L"VirtualBox USB"


#define VBOXUSBMON_MEMTAG 'MUBV'


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
typedef struct VBOXUSBMONINS
{
    void * pvDummy;
} VBOXUSBMONINS, *PVBOXUSBMONINS;

typedef struct VBOXUSBMONCTX
{
    VBOXUSBFLTCTX FltCtx;
} VBOXUSBMONCTX, *PVBOXUSBMONCTX;

typedef struct VBOXUSBHUB_PNPHOOK
{
    VBOXUSBHOOK_ENTRY Hook;
    bool fUninitFailed;
} VBOXUSBHUB_PNPHOOK, *PVBOXUSBHUB_PNPHOOK;

typedef struct VBOXUSBHUB_PNPHOOK_COMPLETION
{
    VBOXUSBHOOK_REQUEST Rq;
} VBOXUSBHUB_PNPHOOK_COMPLETION, *PVBOXUSBHUB_PNPHOOK_COMPLETION;

/*
 * Comment out VBOX_USB3PORT definition to disable hooking to multiple drivers (#6509)
 */
#define VBOX_USB3PORT

#ifdef VBOX_USB3PORT
#define VBOXUSBMON_MAXDRIVERS 5
typedef struct VBOXUSB_PNPDRIVER
{
    PDRIVER_OBJECT     DriverObject;
    VBOXUSBHUB_PNPHOOK UsbHubPnPHook;
    PDRIVER_DISPATCH   pfnHookStub;
} VBOXUSB_PNPDRIVER, *PVBOXUSB_PNPDRIVER;
#endif /* !VBOX_USB3PORT */

typedef struct VBOXUSBMONGLOBALS
{
    PDEVICE_OBJECT pDevObj;
#ifdef VBOX_USB3PORT
    VBOXUSB_PNPDRIVER pDrivers[VBOXUSBMON_MAXDRIVERS];
#else /* !VBOX_USB3PORT */
    VBOXUSBHUB_PNPHOOK UsbHubPnPHook;
#endif /* !VBOX_USB3PORT */
    KEVENT OpenSynchEvent;
    IO_REMOVE_LOCK RmLock;
    uint32_t cOpens;
    volatile LONG ulPreventUnloadOn;
    PFILE_OBJECT pPreventUnloadFileObj;
} VBOXUSBMONGLOBALS, *PVBOXUSBMONGLOBALS;


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
static VBOXUSBMONGLOBALS g_VBoxUsbMonGlobals;



PVOID VBoxUsbMonMemAlloc(SIZE_T cbBytes)
{
    PVOID pvMem = ExAllocatePoolWithTag(NonPagedPool, cbBytes, VBOXUSBMON_MEMTAG);
    Assert(pvMem);
    return pvMem;
}

PVOID VBoxUsbMonMemAllocZ(SIZE_T cbBytes)
{
    PVOID pvMem = VBoxUsbMonMemAlloc(cbBytes);
    if (pvMem)
    {
        RtlZeroMemory(pvMem, cbBytes);
    }
    return pvMem;
}

VOID VBoxUsbMonMemFree(PVOID pvMem)
{
    ExFreePoolWithTag(pvMem, VBOXUSBMON_MEMTAG);
}

#define VBOXUSBDBG_STRCASE(_t) \
        case _t: return #_t
#define VBOXUSBDBG_STRCASE_UNKNOWN(_v) \
        default: LOG((__FUNCTION__": Unknown Value (0n%d), (0x%x)", _v, _v)); return "Unknown"

static const char* vboxUsbDbgStrPnPMn(UCHAR uMn)
{
    switch (uMn)
    {
        VBOXUSBDBG_STRCASE(IRP_MN_START_DEVICE);
        VBOXUSBDBG_STRCASE(IRP_MN_QUERY_REMOVE_DEVICE);
        VBOXUSBDBG_STRCASE(IRP_MN_REMOVE_DEVICE);
        VBOXUSBDBG_STRCASE(IRP_MN_CANCEL_REMOVE_DEVICE);
        VBOXUSBDBG_STRCASE(IRP_MN_STOP_DEVICE);
        VBOXUSBDBG_STRCASE(IRP_MN_QUERY_STOP_DEVICE);
        VBOXUSBDBG_STRCASE(IRP_MN_CANCEL_STOP_DEVICE);
        VBOXUSBDBG_STRCASE(IRP_MN_QUERY_DEVICE_RELATIONS);
        VBOXUSBDBG_STRCASE(IRP_MN_QUERY_INTERFACE);
        VBOXUSBDBG_STRCASE(IRP_MN_QUERY_CAPABILITIES);
        VBOXUSBDBG_STRCASE(IRP_MN_QUERY_RESOURCES);
        VBOXUSBDBG_STRCASE(IRP_MN_QUERY_RESOURCE_REQUIREMENTS);
        VBOXUSBDBG_STRCASE(IRP_MN_QUERY_DEVICE_TEXT);
        VBOXUSBDBG_STRCASE(IRP_MN_FILTER_RESOURCE_REQUIREMENTS);
        VBOXUSBDBG_STRCASE(IRP_MN_READ_CONFIG);
        VBOXUSBDBG_STRCASE(IRP_MN_WRITE_CONFIG);
        VBOXUSBDBG_STRCASE(IRP_MN_EJECT);
        VBOXUSBDBG_STRCASE(IRP_MN_SET_LOCK);
        VBOXUSBDBG_STRCASE(IRP_MN_QUERY_ID);
        VBOXUSBDBG_STRCASE(IRP_MN_QUERY_PNP_DEVICE_STATE);
        VBOXUSBDBG_STRCASE(IRP_MN_QUERY_BUS_INFORMATION);
        VBOXUSBDBG_STRCASE(IRP_MN_DEVICE_USAGE_NOTIFICATION);
        VBOXUSBDBG_STRCASE(IRP_MN_SURPRISE_REMOVAL);
        VBOXUSBDBG_STRCASE_UNKNOWN(uMn);
    }
}

void vboxUsbDbgPrintUnicodeString(PUNICODE_STRING pUnicodeString)
{
    RT_NOREF1(pUnicodeString);
    Log(("%.*ls", pUnicodeString->Length / 2, pUnicodeString->Buffer));
}

/**
 * Send IRP_MN_QUERY_DEVICE_RELATIONS
 *
 * @returns NT Status
 * @param   pDevObj         USB device pointer
 * @param   pFileObj        Valid file object pointer
 * @param   pDevRelations   Pointer to DEVICE_RELATIONS pointer (out)
 */
NTSTATUS VBoxUsbMonQueryBusRelations(PDEVICE_OBJECT pDevObj, PFILE_OBJECT pFileObj, PDEVICE_RELATIONS *pDevRelations)
{
    IO_STATUS_BLOCK IoStatus;
    KEVENT Event;
    NTSTATUS Status;
    PIRP pIrp;
    PIO_STACK_LOCATION pSl;

    KeInitializeEvent(&Event, NotificationEvent, FALSE);

    Assert(pDevRelations);
    *pDevRelations = NULL;

    pIrp = IoBuildSynchronousFsdRequest(IRP_MJ_PNP, pDevObj, NULL, 0, NULL, &Event, &IoStatus);
    if (!pIrp)
    {
        WARN(("IoBuildDeviceIoControlRequest failed!!"));
        return STATUS_INSUFFICIENT_RESOURCES;
    }
    pIrp->IoStatus.Status = STATUS_NOT_SUPPORTED;

    pSl = IoGetNextIrpStackLocation(pIrp);
    pSl->MajorFunction = IRP_MJ_PNP;
    pSl->MinorFunction = IRP_MN_QUERY_DEVICE_RELATIONS;
    pSl->Parameters.QueryDeviceRelations.Type = BusRelations;
    pSl->FileObject = pFileObj;

    Status = IoCallDriver(pDevObj, pIrp);
    if (Status == STATUS_PENDING)
    {
        LOG(("IoCallDriver returned STATUS_PENDING!!"));
        KeWaitForSingleObject(&Event, Executive, KernelMode, FALSE, NULL);
        Status = IoStatus.Status;
    }

    if (Status == STATUS_SUCCESS)
    {
        PDEVICE_RELATIONS pRel = (PDEVICE_RELATIONS)IoStatus.Information;
        LOG(("pRel = %p", pRel));
        if (VALID_PTR(pRel))
        {
            *pDevRelations = pRel;
        }
        else
        {
            WARN(("Invalid pointer %p", pRel));
        }
    }
    else
    {
        WARN(("IRP_MN_QUERY_DEVICE_RELATIONS failed Status(0x%x)", Status));
    }

    LOG(("IoCallDriver returned %x", Status));
    return Status;
}

RT_C_DECLS_BEGIN
/* these two come from IFS Kit, which is not included in 2K DDK we use,
 * although they are documented and exported in ntoskrnl,
 * and both should be present for >= XP according to MSDN */
NTKERNELAPI
NTSTATUS
ObQueryNameString(
    __in PVOID Object,
    __out_bcount_opt(Length) POBJECT_NAME_INFORMATION ObjectNameInfo,
    __in ULONG Length,
    __out PULONG ReturnLength
    );

NTKERNELAPI
PDEVICE_OBJECT
IoGetLowerDeviceObject(
    __in  PDEVICE_OBJECT  DeviceObject
    );

RT_C_DECLS_END

typedef DECLCALLBACK(VOID) FNVBOXUSBDEVNAMEMATCHER(PDEVICE_OBJECT pDo, PUNICODE_STRING pName, PVOID pvMatcher);
typedef FNVBOXUSBDEVNAMEMATCHER *PFNVBOXUSBDEVNAMEMATCHER;

static NTSTATUS vboxUsbObjCheckName(PDEVICE_OBJECT pDo, PFNVBOXUSBDEVNAMEMATCHER pfnMatcher, PVOID pvMatcher)
{
    union
    {
        OBJECT_NAME_INFORMATION Info;
        char buf[1024];
    } buf;
    ULONG cbLength = 0;

    POBJECT_NAME_INFORMATION pInfo = &buf.Info;
    NTSTATUS Status = ObQueryNameString(pDo, &buf.Info, sizeof (buf), &cbLength);
    if (!NT_SUCCESS(Status))
    {
        if (STATUS_INFO_LENGTH_MISMATCH != Status)
        {
            WARN(("ObQueryNameString failed 0x%x", Status));
            return Status;
        }

        LOG(("ObQueryNameString returned STATUS_INFO_LENGTH_MISMATCH, required size %d", cbLength));

        pInfo = (POBJECT_NAME_INFORMATION)VBoxUsbMonMemAlloc(cbLength);
        if (!pInfo)
        {
            WARN(("VBoxUsbMonMemAlloc failed"));
            return STATUS_NO_MEMORY;
        }
        Status = ObQueryNameString(pDo, pInfo, cbLength, &cbLength);
        if (!NT_SUCCESS(Status))
        {
            WARN(("ObQueryNameString second try failed 0x%x", Status));
            VBoxUsbMonMemFree(pInfo);
            return Status;
        }
    }

    /* we've got the name! */
    LOG(("got the name:"));
    LOG_USTR(&pInfo->Name);
    pfnMatcher(pDo, &pInfo->Name, pvMatcher);

    if (&buf.Info != pInfo)
    {
        LOG(("freeing allocated pInfo(0x%p)", pInfo));
        VBoxUsbMonMemFree(pInfo);
    }
    else
    {
        LOG(("no freeing info needed"));
    }

    return STATUS_SUCCESS;
}


typedef DECLCALLBACK(BOOLEAN) FNVBOXUSBDEVSTACKWALKER(PDEVICE_OBJECT pTopDo, PDEVICE_OBJECT pCurDo, PVOID pvContext);
typedef FNVBOXUSBDEVSTACKWALKER *PFNVBOXUSBDEVSTACKWALKER;

VOID vboxUsbObjDevStackWalk(PDEVICE_OBJECT pDo, PFNVBOXUSBDEVSTACKWALKER pfnWalker, PVOID pvWalker)
{
    LOG(("==>tree walk for Do 0x%p", pDo));
    PDEVICE_OBJECT pCurDo = pDo;
    ObReferenceObject(pCurDo); /* <- to make sure the dereferencing logic below works correctly */
    do
    {
        LOG(("==Do 0x%p", pCurDo));
#ifdef VBOX_USB_WITH_VERBOSE_LOGGING
        {
            union
            {
                OBJECT_NAME_INFORMATION Info;
                char buf[1024];
            } buf;
            ULONG cbLength = 0;

            NTSTATUS tmpStatus = ObQueryNameString(pCurDo, &buf.Info, sizeof (buf), &cbLength);
            if (NT_SUCCESS(tmpStatus))
            {
                LOG(("  Obj name:"));
                LOG_USTR(&buf.Info.Name);
            }
            else
            {
                if (STATUS_INFO_LENGTH_MISMATCH != tmpStatus)
                {
                    WARN(("ObQueryNameString failed 0x%x", tmpStatus));
                }
                else
                {
                    WARN(("ObQueryNameString STATUS_INFO_LENGTH_MISMATCH, required %d", cbLength));
                }
            }

            if (pCurDo->DriverObject
                && pCurDo->DriverObject->DriverName.Buffer
                && pCurDo->DriverObject->DriverName.Length)
            {
                LOG(("  Drv Obj(0x%p), name:", pCurDo->DriverObject));
                LOG_USTR(&pCurDo->DriverObject->DriverName);
            }
            else
            {
                LOG(("  No Drv Name, Drv Obj(0x%p)", pCurDo->DriverObject));
                if (pCurDo->DriverObject)
                {
                    LOG(("  driver name is zero, Length(%d), Buffer(0x%p)",
                                pCurDo->DriverObject->DriverName.Length, pCurDo->DriverObject->DriverName.Buffer));
                }
                else
                {
                    LOG(("  driver object is NULL"));
                }
            }
        }
#endif
        if (!pfnWalker(pDo, pCurDo, pvWalker))
        {
            LOG(("the walker said to stop"));
            ObDereferenceObject(pCurDo);
            break;
        }

        PDEVICE_OBJECT pLowerDo = IoGetLowerDeviceObject(pCurDo);
        ObDereferenceObject(pCurDo);
        if (!pLowerDo)
        {
            LOG(("IoGetLowerDeviceObject returnned NULL, stop"));
            break;
        }
        pCurDo = pLowerDo;
    } while (1);

    LOG(("<==tree walk"));
}

static DECLCALLBACK(BOOLEAN) vboxUsbObjNamePrefixMatch(PUNICODE_STRING pName, PUNICODE_STRING pNamePrefix, BOOLEAN fCaseInSensitive)
{
    LOG(("Matching prefix:"));
    LOG_USTR(pNamePrefix);
    if (pNamePrefix->Length > pName->Length)
    {
        LOG(("Pregix Length(%d) > Name Length(%d)", pNamePrefix->Length, pName->Length));
        return FALSE;
    }

    LOG(("Pregix Length(%d) <= Name Length(%d)", pNamePrefix->Length, pName->Length));

    UNICODE_STRING NamePrefix = *pName;
    NamePrefix.Length = pNamePrefix->Length;
    LONG rc = RtlCompareUnicodeString(&NamePrefix, pNamePrefix, fCaseInSensitive);

    if (!rc)
    {
        LOG(("prefix MATCHED!"));
        return TRUE;
    }

    LOG(("prefix NOT matched!"));
    return FALSE;
}

typedef struct VBOXUSBOBJNAMEPREFIXMATCHER
{
    PUNICODE_STRING pNamePrefix;
    BOOLEAN fMatched;
} VBOXUSBOBJNAMEPREFIXMATCHER, *PVBOXUSBOBJNAMEPREFIXMATCHER;

static DECLCALLBACK(VOID) vboxUsbObjDevNamePrefixMatcher(PDEVICE_OBJECT pDo, PUNICODE_STRING pName, PVOID pvMatcher)
{
    RT_NOREF1(pDo);
    PVBOXUSBOBJNAMEPREFIXMATCHER pData = (PVBOXUSBOBJNAMEPREFIXMATCHER)pvMatcher;
    PUNICODE_STRING pNamePrefix = pData->pNamePrefix;
    ASSERT_WARN(!pData->fMatched, ("match flag already set!"));
    pData->fMatched = vboxUsbObjNamePrefixMatch(pName, pNamePrefix, TRUE /* fCaseInSensitive */);
    LOG(("match result (%d)", (int)pData->fMatched));
}

typedef struct VBOXUSBOBJDRVOBJSEARCHER
{
    PDEVICE_OBJECT pDevObj;
    PUNICODE_STRING pDrvName;
    PUNICODE_STRING pPdoNamePrefix;
    ULONG fFlags;
} VBOXUSBOBJDRVOBJSEARCHER, *PVBOXUSBOBJDRVOBJSEARCHER;

static DECLCALLBACK(BOOLEAN) vboxUsbObjDevObjSearcherWalker(PDEVICE_OBJECT pTopDo, PDEVICE_OBJECT pCurDo, PVOID pvContext)
{
    RT_NOREF1(pTopDo);
    PVBOXUSBOBJDRVOBJSEARCHER pData = (PVBOXUSBOBJDRVOBJSEARCHER)pvContext;
    ASSERT_WARN(!pData->pDevObj, ("non-null dev object (0x%p) on enter", pData->pDevObj));
    pData->pDevObj = NULL;
    if (pCurDo->DriverObject
        && pCurDo->DriverObject->DriverName.Buffer
        && pCurDo->DriverObject->DriverName.Length
        && !RtlCompareUnicodeString(pData->pDrvName, &pCurDo->DriverObject->DriverName, TRUE /* case insensitive */))
    {
        LOG(("MATCHED driver:"));
        LOG_USTR(&pCurDo->DriverObject->DriverName);
        if ((pData->fFlags & VBOXUSBMONHUBWALK_F_ALL) != VBOXUSBMONHUBWALK_F_ALL)
        {
            VBOXUSBOBJNAMEPREFIXMATCHER Data = {0};
            Data.pNamePrefix = pData->pPdoNamePrefix;
            NTSTATUS Status = vboxUsbObjCheckName(pCurDo, vboxUsbObjDevNamePrefixMatcher, &Data);
            if (!NT_SUCCESS(Status))
            {
                WARN(("vboxUsbObjCheckName failed Status (0x%x)", Status));
                return TRUE;
            }


            LOG(("prefix match result (%d)", Data.fMatched));
            if ((pData->fFlags & VBOXUSBMONHUBWALK_F_FDO) == VBOXUSBMONHUBWALK_F_FDO)
            {
                LOG(("VBOXUSBMONHUBWALK_F_FDO"));
                if (Data.fMatched)
                {
                    LOG(("this is a PDO object, skip it and stop search"));
                    /* stop search as we will not find FDO here */
                    return FALSE;
                }

                LOG(("this is a FDO object, MATCHED!!"));
            }
            else if ((pData->fFlags & VBOXUSBMONHUBWALK_F_PDO) == VBOXUSBMONHUBWALK_F_PDO)
            {
                LOG(("VBOXUSBMONHUBWALK_F_PDO"));
                if (!Data.fMatched)
                {
                    LOG(("this is a FDO object, skip it and continue search"));
                    /* continue seach since since this could be a nested hub that would have a usbhub-originated PDO */
                    return TRUE;
                }

                LOG(("this is a PDO object, MATCHED!!"));
            }

        }
        else
        {
            LOG(("VBOXUSBMONHUBWALK_F_ALL"));
            LOG(("either PDO or FDO, MATCHED!!"));
        }

        /* ensure the dev object is not destroyed */
        ObReferenceObject(pCurDo);
        pData->pDevObj = pCurDo;
        /* we are done */
        return FALSE;
    }
    else
    {
        LOG(("driver object (0x%p) no match", pCurDo->DriverObject));
        if (pCurDo->DriverObject)
        {
            if (   pCurDo->DriverObject->DriverName.Buffer
                && pCurDo->DriverObject->DriverName.Length)
            {
                LOG(("driver name not match, was:"));
                LOG_USTR(&pCurDo->DriverObject->DriverName);
                LOG(("but expected:"));
                LOG_USTR(pData->pDrvName);
            }
            else
            {
                LOG(("driver name is zero, Length(%d), Buffer(0x%p)",
                        pCurDo->DriverObject->DriverName.Length, pCurDo->DriverObject->DriverName.Buffer));
            }
        }
        else
        {
            LOG(("driver object is NULL"));
        }
    }
    return TRUE;
}

VOID vboxUsbMonHubDevWalk(PFNVBOXUSBMONDEVWALKER pfnWalker, PVOID pvWalker, ULONG fFlags)
{
    NTSTATUS Status = STATUS_UNSUCCESSFUL;
#ifndef VBOX_USB3PORT
    UNICODE_STRING szStandardHubName;
    PDRIVER_OBJECT pDrvObj = NULL;
    szStandardHubName.Length = 0;
    szStandardHubName.MaximumLength = 0;
    szStandardHubName.Buffer = 0;
    RtlInitUnicodeString(&szStandardHubName, L"\\Driver\\usbhub");
    UNICODE_STRING szStandardHubPdoNamePrefix;
    szStandardHubPdoNamePrefix.Length = 0;
    szStandardHubPdoNamePrefix.MaximumLength = 0;
    szStandardHubPdoNamePrefix.Buffer = 0;
    RtlInitUnicodeString(&szStandardHubPdoNamePrefix, L"\\Device\\USBPDO-");

    for (int i = 0; i < 16; i++)
    {
        WCHAR           szwHubName[32] = {0};
        char            szHubName[32] = {0};
        ANSI_STRING     AnsiName;
        UNICODE_STRING  UnicodeName;
        PDEVICE_OBJECT  pHubDevObj;
        PFILE_OBJECT    pHubFileObj;

        sprintf(szHubName, "\\Device\\USBPDO-%d", i);

        RtlInitAnsiString(&AnsiName, szHubName);

        UnicodeName.Length = 0;
        UnicodeName.MaximumLength = sizeof (szwHubName);
        UnicodeName.Buffer = szwHubName;

        RtlInitAnsiString(&AnsiName, szHubName);
        Status = RtlAnsiStringToUnicodeString(&UnicodeName, &AnsiName, FALSE);
        if (Status == STATUS_SUCCESS)
        {
            Status = IoGetDeviceObjectPointer(&UnicodeName, FILE_READ_DATA, &pHubFileObj, &pHubDevObj);
            if (Status == STATUS_SUCCESS)
            {
                LOG(("IoGetDeviceObjectPointer for \\Device\\USBPDO-%d returned %p %p", i, pHubDevObj, pHubFileObj));

                VBOXUSBOBJDRVOBJSEARCHER Data = {0};
                Data.pDrvName = &szStandardHubName;
                Data.pPdoNamePrefix = &szStandardHubPdoNamePrefix;
                Data.fFlags = fFlags;

                vboxUsbObjDevStackWalk(pHubDevObj, vboxUsbObjDevObjSearcherWalker, &Data);
                if (Data.pDevObj)
                {
                    LOG(("found hub dev obj (0x%p)", Data.pDevObj));
                    if (!pfnWalker(pHubFileObj, pHubDevObj, Data.pDevObj, pvWalker))
                    {
                        LOG(("the walker said to stop"));
                        ObDereferenceObject(Data.pDevObj);
                        ObDereferenceObject(pHubFileObj);
                        break;
                    }

                    LOG(("going forward.."));
                    ObDereferenceObject(Data.pDevObj);
                }
                else
                {
                    LOG(("no hub driver obj found"));
                    ASSERT_WARN(!Data.pDevObj, ("non-null dev obj poiter returned (0x%p)", Data.pDevObj));
                }

                /* this will dereference both file and dev obj */
                ObDereferenceObject(pHubFileObj);
            }
            else
            {
                LOG(("IoGetDeviceObjectPointer returned Status (0x%x) for (\\Device\\USBPDO-%d)", Status, i));
            }
        }
        else
        {
            WARN(("RtlAnsiStringToUnicodeString failed, Status (0x%x) for Ansu name (\\Device\\USBPDO-%d)", Status, i));
        }
    }
#else /* VBOX_USB3PORT */
    RT_NOREF1(fFlags);
    PWSTR szwHubList;
    Status = IoGetDeviceInterfaces(&GUID_DEVINTERFACE_USB_HUB, NULL, 0, &szwHubList);
    if (Status != STATUS_SUCCESS)
    {
        LOG(("IoGetDeviceInterfaces failed with %d\n", Status));
        return;
    }
    if (szwHubList)
    {
        UNICODE_STRING  UnicodeName;
        PDEVICE_OBJECT  pHubDevObj;
        PFILE_OBJECT    pHubFileObj;
        PWSTR           szwHubName = szwHubList;
        while (*szwHubName != UNICODE_NULL)
        {
            RtlInitUnicodeString(&UnicodeName, szwHubName);
            Status = IoGetDeviceObjectPointer(&UnicodeName, FILE_READ_DATA, &pHubFileObj, &pHubDevObj);
            if (Status == STATUS_SUCCESS)
            {
                /* We could not log hub name here.
                 * It is the paged memory and we cannot use it in logger cause it increases the IRQL
                 */
                LOG(("IoGetDeviceObjectPointer returned %p %p", pHubDevObj, pHubFileObj));
                if (!pfnWalker(pHubFileObj, pHubDevObj, pHubDevObj, pvWalker))
                {
                    LOG(("the walker said to stop"));
                    ObDereferenceObject(pHubFileObj);
                    break;
                }

                LOG(("going forward.."));
                ObDereferenceObject(pHubFileObj);
            }
            szwHubName += wcslen(szwHubName) + 1;
        }
        ExFreePool(szwHubList);
    }
#endif /* VBOX_USB3PORT */
}

typedef struct VBOXUSBMONFINDHUBWALKER
{
    PDRIVER_OBJECT pDrvObj;
} VBOXUSBMONFINDHUBWALKER, *PVBOXUSBMONFINDHUBWALKER;

static DECLCALLBACK(BOOLEAN) vboxUsbMonFindHubDrvObjWalker(PFILE_OBJECT pFile, PDEVICE_OBJECT pTopDo, PDEVICE_OBJECT pHubDo, PVOID pvContext)
{
    RT_NOREF2(pFile, pTopDo);
    PVBOXUSBMONFINDHUBWALKER pData = (PVBOXUSBMONFINDHUBWALKER)pvContext;
    PDRIVER_OBJECT pDrvObj = pHubDo->DriverObject;

    ASSERT_WARN(!pData->pDrvObj, ("pDrvObj expected null on enter, but was(0x%p)", pData->pDrvObj));
    if (pDrvObj)
    {
        LOG(("found driver object 0x%p", pDrvObj));
        ObReferenceObject(pDrvObj);
        pData->pDrvObj = pDrvObj;
        return FALSE;
    }

    WARN(("null pDrvObj!"));
    return TRUE;
}

static PDRIVER_OBJECT vboxUsbMonHookFindHubDrvObj()
{
    UNICODE_STRING szStandardHubName;
    szStandardHubName.Length = 0;
    szStandardHubName.MaximumLength = 0;
    szStandardHubName.Buffer = 0;
    RtlInitUnicodeString(&szStandardHubName, L"\\Driver\\usbhub");

    LOG(("Search USB hub"));
    VBOXUSBMONFINDHUBWALKER Data = {0};
    vboxUsbMonHubDevWalk(vboxUsbMonFindHubDrvObjWalker, &Data, VBOXUSBMONHUBWALK_F_ALL);
    if (Data.pDrvObj)
        LOG(("returning driver object 0x%p", Data.pDrvObj));
    else
        WARN(("no hub driver object found!"));
    return Data.pDrvObj;
}

/* NOTE: the stack location data is not the "actual" IRP stack location,
 * but a copy being preserved on the IRP way down.
 * See the note in VBoxUsbPnPCompletion for detail */
static NTSTATUS vboxUsbMonHandlePnPIoctl(PDEVICE_OBJECT pDevObj, PIO_STACK_LOCATION pSl, PIO_STATUS_BLOCK pIoStatus)
{
    LOG(("IRQL = %d", KeGetCurrentIrql()));
    switch(pSl->MinorFunction)
    {
        case IRP_MN_QUERY_DEVICE_TEXT:
        {
            LOG(("IRP_MN_QUERY_DEVICE_TEXT: pIoStatus->Status = %x", pIoStatus->Status));
            if (pIoStatus->Status == STATUS_SUCCESS)
            {
                WCHAR *pId = (WCHAR *)pIoStatus->Information;
                if (VALID_PTR(pId))
                {
                    KIRQL Iqrl = KeGetCurrentIrql();
                    /* IRQL should be always passive here */
                    ASSERT_WARN(Iqrl == PASSIVE_LEVEL, ("irql is not PASSIVE"));
                    switch(pSl->Parameters.QueryDeviceText.DeviceTextType)
                    {
                        case DeviceTextLocationInformation:
                            LOG(("DeviceTextLocationInformation"));
                            LOG_STRW(pId);
                            break;

                        case DeviceTextDescription:
                            LOG(("DeviceTextDescription"));
                            LOG_STRW(pId);
                            if (VBoxUsbFltPdoIsFiltered(pDevObj))
                            {
                                LOG(("PDO (0x%p) is filtered", pDevObj));
                                WCHAR *pId = (WCHAR *)ExAllocatePool(PagedPool, sizeof(szDeviceTextDescription));
                                if (!pId)
                                {
                                    AssertFailed();
                                    break;
                                }
                                memcpy(pId, szDeviceTextDescription, sizeof(szDeviceTextDescription));
                                LOG(("NEW szDeviceTextDescription"));
                                LOG_STRW(pId);
                                ExFreePool((PVOID)pIoStatus->Information);
                                pIoStatus->Information = (ULONG_PTR)pId;
                            }
                            else
                            {
                                LOG(("PDO (0x%p) is NOT filtered", pDevObj));
                            }
                            break;
                        default:
                            LOG(("DeviceText %d", pSl->Parameters.QueryDeviceText.DeviceTextType));
                            break;
                    }
                }
                else
                    LOG(("Invalid pointer %p", pId));
            }
            break;
        }

        case IRP_MN_QUERY_ID:
        {
            LOG(("IRP_MN_QUERY_ID: Irp->pIoStatus->Status = %x", pIoStatus->Status));
            if (pIoStatus->Status == STATUS_SUCCESS &&  pDevObj)
            {
                WCHAR *pId = (WCHAR *)pIoStatus->Information;
#ifdef VBOX_USB_WITH_VERBOSE_LOGGING
                WCHAR *pTmp;
#endif
                if (VALID_PTR(pId))
                {
                    KIRQL Iqrl = KeGetCurrentIrql();
                    /* IRQL should be always passive here */
                    ASSERT_WARN(Iqrl == PASSIVE_LEVEL, ("irql is not PASSIVE"));

                    switch (pSl->Parameters.QueryId.IdType)
                    {
                        case BusQueryInstanceID:
                            LOG(("BusQueryInstanceID"));
                            LOG_STRW(pId);
                            break;

                        case BusQueryDeviceID:
                        {
                            LOG(("BusQueryDeviceID"));
                            pId = (WCHAR *)ExAllocatePool(PagedPool, sizeof(szBusQueryDeviceId));
                            if (!pId)
                            {
                                WARN(("ExAllocatePool failed"));
                                break;
                            }

                            BOOLEAN bFiltered = FALSE;
                            NTSTATUS Status = VBoxUsbFltPdoAdd(pDevObj, &bFiltered);
                            if (Status != STATUS_SUCCESS || !bFiltered)
                            {
                                if (Status == STATUS_SUCCESS)
                                {
                                    LOG(("PDO (0x%p) is NOT filtered", pDevObj));
                                }
                                else
                                {
                                    WARN(("VBoxUsbFltPdoAdd for PDO (0x%p) failed Status 0x%x", pDevObj, Status));
                                }
                                ExFreePool(pId);
                                break;
                            }

                            LOG(("PDO (0x%p) is filtered", pDevObj));
                            ExFreePool((PVOID)pIoStatus->Information);
                            memcpy(pId, szBusQueryDeviceId, sizeof(szBusQueryDeviceId));
                            pIoStatus->Information = (ULONG_PTR)pId;
                            break;
                        }
                    case BusQueryHardwareIDs:
                    {
                        LOG(("BusQueryHardwareIDs"));
#ifdef VBOX_USB_WITH_VERBOSE_LOGGING
                        while (*pId) //MULTI_SZ
                        {
                            LOG_STRW(pId);
                            while (*pId) pId++;
                            pId++;
                        }
#endif
                        pId = (WCHAR *)ExAllocatePool(PagedPool, sizeof(szBusQueryHardwareIDs));
                        if (!pId)
                        {
                            WARN(("ExAllocatePool failed"));
                            break;
                        }

                        BOOLEAN bFiltered = FALSE;
                        NTSTATUS Status = VBoxUsbFltPdoAdd(pDevObj, &bFiltered);
                        if (Status != STATUS_SUCCESS || !bFiltered)
                        {
                            if (Status == STATUS_SUCCESS)
                            {
                                LOG(("PDO (0x%p) is NOT filtered", pDevObj));
                            }
                            else
                            {
                                WARN(("VBoxUsbFltPdoAdd for PDO (0x%p) failed Status 0x%x", pDevObj, Status));
                            }
                            ExFreePool(pId);
                            break;
                        }

                        LOG(("PDO (0x%p) is filtered", pDevObj));

                        memcpy(pId, szBusQueryHardwareIDs, sizeof(szBusQueryHardwareIDs));
#ifdef VBOX_USB_WITH_VERBOSE_LOGGING
                        LOG(("NEW BusQueryHardwareIDs"));
                        pTmp = pId;
                        while (*pTmp) //MULTI_SZ
                        {

                            LOG_STRW(pTmp);
                            while (*pTmp) pTmp++;
                            pTmp++;
                        }
#endif
                        ExFreePool((PVOID)pIoStatus->Information);
                        pIoStatus->Information = (ULONG_PTR)pId;
                        break;
                    }
                    case BusQueryCompatibleIDs:
                        LOG(("BusQueryCompatibleIDs"));
#ifdef VBOX_USB_WITH_VERBOSE_LOGGING
                        while (*pId) //MULTI_SZ
                        {
                            LOG_STRW(pId);
                            while (*pId) pId++;
                            pId++;
                        }
#endif
                        if (VBoxUsbFltPdoIsFiltered(pDevObj))
                        {
                            LOG(("PDO (0x%p) is filtered", pDevObj));
                            pId = (WCHAR *)ExAllocatePool(PagedPool, sizeof(szBusQueryCompatibleIDs));
                            if (!pId)
                            {
                                WARN(("ExAllocatePool failed"));
                                break;
                            }
                            memcpy(pId, szBusQueryCompatibleIDs, sizeof(szBusQueryCompatibleIDs));
#ifdef VBOX_USB_WITH_VERBOSE_LOGGING
                            LOG(("NEW BusQueryCompatibleIDs"));
                            pTmp = pId;
                            while (*pTmp) //MULTI_SZ
                            {
                                LOG_STRW(pTmp);
                                while (*pTmp) pTmp++;
                                pTmp++;
                            }
#endif
                            ExFreePool((PVOID)pIoStatus->Information);
                            pIoStatus->Information = (ULONG_PTR)pId;
                        }
                        else
                        {
                            LOG(("PDO (0x%p) is NOT filtered", pDevObj));
                        }
                        break;

                        default:
                            /** @todo r=bird: handle BusQueryContainerID and whatever else we might see  */
                            break;
                    }
                }
                else
                {
                    LOG(("Invalid pointer %p", pId));
                }
            }
            break;
        }

#ifdef VBOX_USB_WITH_VERBOSE_LOGGING
        case IRP_MN_QUERY_DEVICE_RELATIONS:
        {
            switch(pSl->Parameters.QueryDeviceRelations.Type)
            {
                case BusRelations:
                    LOG(("BusRelations"));

                    if (pIoStatus->Status == STATUS_SUCCESS)
                    {
                        PDEVICE_RELATIONS pRel = (PDEVICE_RELATIONS)pIoStatus->Information;
                        LOG(("pRel = %p", pRel));
                        if (VALID_PTR(pRel))
                        {
                            for (unsigned i=0;i<pRel->Count;i++)
                            {
                                if (VBoxUsbFltPdoIsFiltered(pDevObj))
                                    LOG(("New PDO %p", pRel->Objects[i]));
                            }
                        }
                        else
                            LOG(("Invalid pointer %p", pRel));
                    }
                    break;
                case TargetDeviceRelation:
                    LOG(("TargetDeviceRelation"));
                    break;
                case RemovalRelations:
                    LOG(("RemovalRelations"));
                    break;
                case EjectionRelations:
                    LOG(("EjectionRelations"));
                    break;
                default:
                    LOG(("QueryDeviceRelations.Type=%d", pSl->Parameters.QueryDeviceRelations.Type));
            }
            break;
        }

        case IRP_MN_QUERY_CAPABILITIES:
        {
            LOG(("IRP_MN_QUERY_CAPABILITIES: pIoStatus->Status = %x", pIoStatus->Status));
            if (pIoStatus->Status == STATUS_SUCCESS)
            {
                PDEVICE_CAPABILITIES pCaps = pSl->Parameters.DeviceCapabilities.Capabilities;
                if (VALID_PTR(pCaps))
                {
                    LOG(("Caps.SilentInstall  = %d", pCaps->SilentInstall));
                    LOG(("Caps.UniqueID       = %d", pCaps->UniqueID ));
                    LOG(("Caps.Address        = %d", pCaps->Address ));
                    LOG(("Caps.UINumber       = %d", pCaps->UINumber ));
                }
                else
                    LOG(("Invalid pointer %p", pCaps));
            }
            break;
        }

        default:
            break;
#endif
    } /*switch */

    LOG(("Done returns %x (IRQL = %d)", pIoStatus->Status, KeGetCurrentIrql()));
    return pIoStatus->Status;
}

NTSTATUS _stdcall VBoxUsbPnPCompletion(DEVICE_OBJECT *pDevObj, IRP *pIrp, void *pvContext)
{
    LOG(("Completion PDO(0x%p), IRP(0x%p), Status(0x%x)", pDevObj, pIrp, pIrp->IoStatus.Status));
    ASSERT_WARN(pvContext, ("zero context"));

    PVBOXUSBHOOK_REQUEST pRequest = (PVBOXUSBHOOK_REQUEST)pvContext;
    /* NOTE: despite a regular IRP processing the stack location in our completion
     * differs from those of the PnP hook since the hook is invoked in the "context" of the calle,
     * while the completion is in the "coller" context in terms of IRP,
     * so the completion stack location is one level "up" here.
     *
     * Moreover we CAN NOT access irp stack location in the completion because we might not have one at all
     * in case the hooked driver is at the top of the irp call stack
     *
     * This is why we use the stack location we saved on IRP way down.
     * */
    PIO_STACK_LOCATION pSl = &pRequest->OldLocation;
    ASSERT_WARN(pIrp == pRequest->pIrp, ("completed IRP(0x%x) not match request IRP(0x%x)", pIrp, pRequest->pIrp));
    /* NOTE: we can not rely on pDevObj passed in IoCompletion since it may be zero
     * in case IRP was created with extra stack locations and the caller did not initialize
     * the IO_STACK_LOCATION::DeviceObject */
    DEVICE_OBJECT *pRealDevObj = pRequest->pDevObj;
//    Assert(!pDevObj || pDevObj == pRealDevObj);
//    Assert(pSl->DeviceObject == pDevObj);

    switch(pSl->MinorFunction)
    {
        case IRP_MN_QUERY_DEVICE_TEXT:
        case IRP_MN_QUERY_ID:
#ifdef VBOX_USB_WITH_VERBOSE_LOGGING
        case IRP_MN_QUERY_DEVICE_RELATIONS:
        case IRP_MN_QUERY_CAPABILITIES:
#endif
            if (NT_SUCCESS(pIrp->IoStatus.Status))
            {
                vboxUsbMonHandlePnPIoctl(pRealDevObj, pSl, &pIrp->IoStatus);
            }
            else
            {
                ASSERT_WARN(pIrp->IoStatus.Status == STATUS_NOT_SUPPORTED, ("Irp failed with status(0x%x)", pIrp->IoStatus.Status));
            }
            break;

        case IRP_MN_SURPRISE_REMOVAL:
        case IRP_MN_REMOVE_DEVICE:
            if (NT_SUCCESS(pIrp->IoStatus.Status))
            {
                VBoxUsbFltPdoRemove(pRealDevObj);
            }
            else
            {
                AssertFailed();
            }
            break;

        /* These two IRPs are received when the PnP subsystem has determined the id of the newly arrived device */
        /* IRP_MN_START_DEVICE only arrives if it's a USB device of a known class or with a present host driver */
        case IRP_MN_QUERY_RESOURCE_REQUIREMENTS:
        case IRP_MN_QUERY_RESOURCES:
            if (NT_SUCCESS(pIrp->IoStatus.Status) || pIrp->IoStatus.Status == STATUS_NOT_SUPPORTED)
            {
                VBoxUsbFltPdoAddCompleted(pRealDevObj);
            }
            else
            {
                AssertFailed();
            }
            break;

        default:
            break;
    }

    LOG(("<==PnP: Mn(%s), PDO(0x%p), IRP(0x%p), Status(0x%x), Sl PDO(0x%p), Compl PDO(0x%p)",
                            vboxUsbDbgStrPnPMn(pSl->MinorFunction),
                            pRealDevObj, pIrp, pIrp->IoStatus.Status,
                            pSl->DeviceObject, pDevObj));
#ifdef DEBUG_misha
    NTSTATUS tmpStatus = pIrp->IoStatus.Status;
#endif
#ifdef VBOX_USB3PORT
    PVBOXUSBHOOK_ENTRY pHook = pRequest->pHook;
#else /* !VBOX_USB3PORT */
    PVBOXUSBHOOK_ENTRY pHook = &g_VBoxUsbMonGlobals.UsbHubPnPHook.Hook;
#endif /* !VBOX_USB3PORT */
    NTSTATUS Status = VBoxUsbHookRequestComplete(pHook, pDevObj, pIrp, pRequest);
    VBoxUsbMonMemFree(pRequest);
#ifdef DEBUG_misha
    if (Status != STATUS_MORE_PROCESSING_REQUIRED)
    {
        Assert(pIrp->IoStatus.Status == tmpStatus);
    }
#endif
    VBoxUsbHookRelease(pHook);
    return Status;
}

/**
 * Device PnP hook
 *
 * @param   pDevObj     Device object.
 * @param   pIrp         Request packet.
 */
#ifdef VBOX_USB3PORT
static NTSTATUS vboxUsbMonPnPHook(IN PVBOXUSBHOOK_ENTRY pHook, IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp)
#else /* !VBOX_USB3PORT */
NTSTATUS _stdcall VBoxUsbMonPnPHook(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp)
#endif /* !VBOX_USB3PORT */
{
#ifndef VBOX_USB3PORT
    PVBOXUSBHOOK_ENTRY pHook = &g_VBoxUsbMonGlobals.UsbHubPnPHook.Hook;
#endif /* !VBOX_USB3PORT */
    LOG(("==>PnP: Mn(%s), PDO(0x%p), IRP(0x%p), Status(0x%x)", vboxUsbDbgStrPnPMn(IoGetCurrentIrpStackLocation(pIrp)->MinorFunction), pDevObj, pIrp, pIrp->IoStatus.Status));

    if (!VBoxUsbHookRetain(pHook))
    {
        WARN(("VBoxUsbHookRetain failed"));
        return VBoxUsbHookRequestPassDownHookSkip(pHook, pDevObj, pIrp);
    }

    PVBOXUSBHUB_PNPHOOK_COMPLETION pCompletion = (PVBOXUSBHUB_PNPHOOK_COMPLETION)VBoxUsbMonMemAlloc(sizeof (*pCompletion));
    if (!pCompletion)
    {
        WARN(("VBoxUsbMonMemAlloc failed"));
        VBoxUsbHookRelease(pHook);
        pIrp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
        pIrp->IoStatus.Information = 0;
        IoCompleteRequest(pIrp, IO_NO_INCREMENT);
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    NTSTATUS Status = VBoxUsbHookRequestPassDownHookCompletion(pHook, pDevObj, pIrp, VBoxUsbPnPCompletion, &pCompletion->Rq);
#ifdef VBOX_USB_WITH_VERBOSE_LOGGING
    if (Status != STATUS_PENDING)
    {
        LOG(("Request completed, Status(0x%x)", Status));
        VBoxUsbHookVerifyCompletion(pHook, &pCompletion->Rq, pIrp);
    }
    else
    {
        LOG(("Request pending"));
    }
#endif
    return Status;
}

#ifdef VBOX_USB3PORT
/**
 * Device PnP hook stubs.
 *
 * @param   pDevObj     Device object.
 * @param   pIrp         Request packet.
 */
#define VBOX_PNPHOOKSTUB(n) NTSTATUS _stdcall VBoxUsbMonPnPHook##n(IN PDEVICE_OBJECT pDevObj, IN PIRP pIrp) \
{ \
    return vboxUsbMonPnPHook(&g_VBoxUsbMonGlobals.pDrivers[n].UsbHubPnPHook.Hook, pDevObj, pIrp); \
}

#define VBOX_PNPHOOKSTUB_INIT(n) g_VBoxUsbMonGlobals.pDrivers[n].pfnHookStub = VBoxUsbMonPnPHook##n

VBOX_PNPHOOKSTUB(0)
VBOX_PNPHOOKSTUB(1)
VBOX_PNPHOOKSTUB(2)
VBOX_PNPHOOKSTUB(3)
VBOX_PNPHOOKSTUB(4)
AssertCompile(VBOXUSBMON_MAXDRIVERS == 5);

typedef struct VBOXUSBMONHOOKDRIVERWALKER
{
    PDRIVER_OBJECT pDrvObj;
} VBOXUSBMONHOOKDRIVERWALKER, *PVBOXUSBMONHOOKDRIVERWALKER;

/**
 * Logs an error to the system event log.
 *
 * @param   ErrCode        Error to report to event log.
 * @param   ReturnedStatus Error that was reported by the driver to the caller.
 * @param   uErrId         Unique error id representing the location in the driver.
 * @param   cbDumpData     Number of bytes at pDumpData.
 * @param   pDumpData      Pointer to data that will be added to the message (see 'details' tab).
 */
static void vboxUsbMonLogError(NTSTATUS ErrCode, NTSTATUS ReturnedStatus, ULONG uErrId, USHORT cbDumpData, PVOID pDumpData)
{
    PIO_ERROR_LOG_PACKET pErrEntry;


    /* Truncate dumps that do not fit into IO_ERROR_LOG_PACKET. */
    if (FIELD_OFFSET(IO_ERROR_LOG_PACKET, DumpData) + cbDumpData > ERROR_LOG_MAXIMUM_SIZE)
        cbDumpData = ERROR_LOG_MAXIMUM_SIZE - FIELD_OFFSET(IO_ERROR_LOG_PACKET, DumpData);

    pErrEntry = (PIO_ERROR_LOG_PACKET)IoAllocateErrorLogEntry(g_VBoxUsbMonGlobals.pDevObj,
                                                              FIELD_OFFSET(IO_ERROR_LOG_PACKET, DumpData) + cbDumpData);
    if (pErrEntry)
    {
        uint8_t *pDump = (uint8_t *)pErrEntry->DumpData;
        if (cbDumpData)
            memcpy(pDump, pDumpData, cbDumpData);
        pErrEntry->MajorFunctionCode = 0;
        pErrEntry->RetryCount = 0;
        pErrEntry->DumpDataSize = cbDumpData;
        pErrEntry->NumberOfStrings = 0;
        pErrEntry->StringOffset = 0;
        pErrEntry->ErrorCode = ErrCode;
        pErrEntry->UniqueErrorValue = uErrId;
        pErrEntry->FinalStatus = ReturnedStatus;
        pErrEntry->IoControlCode = 0;
        IoWriteErrorLogEntry(pErrEntry);
    }
    else
    {
        LOG(("Failed to allocate error log entry (cb=%d)\n", FIELD_OFFSET(IO_ERROR_LOG_PACKET, DumpData) + cbDumpData));
    }
}

static DECLCALLBACK(BOOLEAN) vboxUsbMonHookDrvObjWalker(PFILE_OBJECT pFile, PDEVICE_OBJECT pTopDo, PDEVICE_OBJECT pHubDo, PVOID pvContext)
{
    RT_NOREF3(pFile, pTopDo, pvContext);
    PDRIVER_OBJECT pDrvObj = pHubDo->DriverObject;

    /* First we try to figure out if we are already hooked to this driver. */
    for (int i = 0; i < VBOXUSBMON_MAXDRIVERS; i++)
        if (pDrvObj == g_VBoxUsbMonGlobals.pDrivers[i].DriverObject)
        {
            LOG(("Found %p at pDrivers[%d]\n", pDrvObj, i));
            /* We've already hooked to this one -- nothing to do. */
            return TRUE;
        }
    /* We are not hooked yet, find an empty slot. */
    for (int i = 0; i < VBOXUSBMON_MAXDRIVERS; i++)
    {
        if (!g_VBoxUsbMonGlobals.pDrivers[i].DriverObject)
        {
            /* Found an emtpy slot, use it. */
            g_VBoxUsbMonGlobals.pDrivers[i].DriverObject = pDrvObj;
            ObReferenceObject(pDrvObj);
            LOG(("pDrivers[%d] = %p, installing the hook...\n", i, pDrvObj));
            VBoxUsbHookInit(&g_VBoxUsbMonGlobals.pDrivers[i].UsbHubPnPHook.Hook,
                            pDrvObj,
                            IRP_MJ_PNP,
                            g_VBoxUsbMonGlobals.pDrivers[i].pfnHookStub);
            VBoxUsbHookInstall(&g_VBoxUsbMonGlobals.pDrivers[i].UsbHubPnPHook.Hook);
            return TRUE; /* Must continue to find all drivers. */
        }
        if (pDrvObj == g_VBoxUsbMonGlobals.pDrivers[i].DriverObject)
        {
            LOG(("Found %p at pDrivers[%d]\n", pDrvObj, i));
            /* We've already hooked to this one -- nothing to do. */
            return TRUE;
        }
    }
    /* No empty slots! No reason to continue. */
    LOG(("No empty slots!\n"));
    ANSI_STRING ansiDrvName;
    NTSTATUS Status = RtlUnicodeStringToAnsiString(&ansiDrvName, &pDrvObj->DriverName, true);
    if (Status != STATUS_SUCCESS)
    {
        ansiDrvName.Length = 0;
        LOG(("RtlUnicodeStringToAnsiString failed with 0x%x", Status));
    }
    vboxUsbMonLogError(IO_ERR_INSUFFICIENT_RESOURCES, STATUS_SUCCESS, 1, ansiDrvName.Length, ansiDrvName.Buffer);
    if (Status == STATUS_SUCCESS)
        RtlFreeAnsiString(&ansiDrvName);
    return FALSE;
}

/**
 * Finds all USB drivers in the system and installs hooks if haven't done already.
 */
static NTSTATUS vboxUsbMonInstallAllHooks()
{
    vboxUsbMonHubDevWalk(vboxUsbMonHookDrvObjWalker, NULL, VBOXUSBMONHUBWALK_F_ALL);
    return STATUS_SUCCESS;
}
#endif /* VBOX_USB3PORT */

static NTSTATUS vboxUsbMonHookCheckInit()
{
    static bool fIsHookInited = false;
    if (fIsHookInited)
    {
        LOG(("hook inited already, success"));
        return STATUS_SUCCESS;
    }
#ifdef VBOX_USB3PORT
    return vboxUsbMonInstallAllHooks();
#else /* !VBOX_USB3PORT */
    PDRIVER_OBJECT pDrvObj = vboxUsbMonHookFindHubDrvObj();
    if (pDrvObj)
    {
        VBoxUsbHookInit(&g_VBoxUsbMonGlobals.UsbHubPnPHook.Hook, pDrvObj, IRP_MJ_PNP, VBoxUsbMonPnPHook);
        fIsHookInited = true;
        LOG(("SUCCESS"));
        return STATUS_SUCCESS;
    }
    WARN(("hub drv obj not found, fail"));
    return STATUS_UNSUCCESSFUL;
#endif /* !VBOX_USB3PORT */
}

static NTSTATUS vboxUsbMonHookInstall()
{
#ifdef VBOX_USB3PORT
    /* Nothing to do here as we have already installed all hooks in vboxUsbMonHookCheckInit(). */
    return STATUS_SUCCESS;
#else /* !VBOX_USB3PORT */
#ifdef VBOXUSBMON_DBG_NO_PNPHOOK
    return STATUS_SUCCESS;
#else
    if (g_VBoxUsbMonGlobals.UsbHubPnPHook.fUninitFailed)
    {
        WARN(("trying to hook usbhub pnp after the unhook failed, do nothing & pretend success"));
        return STATUS_SUCCESS;
    }
    return VBoxUsbHookInstall(&g_VBoxUsbMonGlobals.UsbHubPnPHook.Hook);
#endif
#endif /* !VBOX_USB3PORT */
}

static NTSTATUS vboxUsbMonHookUninstall()
{
#ifdef VBOXUSBMON_DBG_NO_PNPHOOK
    return STATUS_SUCCESS;
#else
#ifdef VBOX_USB3PORT
    NTSTATUS Status = STATUS_SUCCESS;
    for (int i = 0; i < VBOXUSBMON_MAXDRIVERS; i++)
    {
        if (g_VBoxUsbMonGlobals.pDrivers[i].DriverObject)
        {
            Assert(g_VBoxUsbMonGlobals.pDrivers[i].DriverObject == g_VBoxUsbMonGlobals.pDrivers[i].UsbHubPnPHook.Hook.pDrvObj);
            LOG(("Unhooking from %p...\n", g_VBoxUsbMonGlobals.pDrivers[i].DriverObject));
            Status = VBoxUsbHookUninstall(&g_VBoxUsbMonGlobals.pDrivers[i].UsbHubPnPHook.Hook);
            if (!NT_SUCCESS(Status))
            {
                /*
                 * We failed to uninstall the hook, so we keep the reference to the driver
                 * in order to prevent another driver re-using this slot because we are
                 * going to mark this hook as fUninitFailed.
                 */
                //AssertMsgFailed(("usbhub pnp unhook failed, setting the fUninitFailed flag, the current value of fUninitFailed (%d)", g_VBoxUsbMonGlobals.UsbHubPnPHook.fUninitFailed));
                LOG(("usbhub pnp unhook failed, setting the fUninitFailed flag, the current value of fUninitFailed (%d)", g_VBoxUsbMonGlobals.pDrivers[i].UsbHubPnPHook.fUninitFailed));
                g_VBoxUsbMonGlobals.pDrivers[i].UsbHubPnPHook.fUninitFailed = true;
            }
            else
            {
                /* The hook was removed successfully, now we can forget about this driver. */
                ObDereferenceObject(g_VBoxUsbMonGlobals.pDrivers[i].DriverObject);
                g_VBoxUsbMonGlobals.pDrivers[i].DriverObject = NULL;
            }
        }
    }
#else /* !VBOX_USB3PORT */
    NTSTATUS Status = VBoxUsbHookUninstall(&g_VBoxUsbMonGlobals.UsbHubPnPHook.Hook);
    if (!NT_SUCCESS(Status))
    {
        AssertMsgFailed(("usbhub pnp unhook failed, setting the fUninitFailed flag, the current value of fUninitFailed (%d)", g_VBoxUsbMonGlobals.UsbHubPnPHook.fUninitFailed));
        g_VBoxUsbMonGlobals.UsbHubPnPHook.fUninitFailed = true;
    }
#endif /* !VBOX_USB3PORT */
    return Status;
#endif
}


static NTSTATUS vboxUsbMonCheckTermStuff()
{
    NTSTATUS Status = KeWaitForSingleObject(&g_VBoxUsbMonGlobals.OpenSynchEvent,
            Executive, KernelMode,
            FALSE, /* BOOLEAN Alertable */
            NULL /* IN PLARGE_INTEGER Timeout */
            );
    AssertRelease(Status == STATUS_SUCCESS);

    do
    {
        if (--g_VBoxUsbMonGlobals.cOpens)
            break;

        Status = vboxUsbMonHookUninstall();

        NTSTATUS tmpStatus = VBoxUsbFltTerm();
        if (!NT_SUCCESS(tmpStatus))
        {
            /* this means a driver state is screwed up, KeBugCheckEx here ? */
            AssertReleaseFailed();
        }
    } while (0);

    KeSetEvent(&g_VBoxUsbMonGlobals.OpenSynchEvent, 0, FALSE);

    return Status;
}

static NTSTATUS vboxUsbMonCheckInitStuff()
{
    NTSTATUS Status = KeWaitForSingleObject(&g_VBoxUsbMonGlobals.OpenSynchEvent,
            Executive, KernelMode,
            FALSE, /* BOOLEAN Alertable */
            NULL /* IN PLARGE_INTEGER Timeout */
        );
    if (Status == STATUS_SUCCESS)
    {
        do
        {
            if (g_VBoxUsbMonGlobals.cOpens++)
            {
                LOG(("opens: %d, success", g_VBoxUsbMonGlobals.cOpens));
                break;
            }

            Status = VBoxUsbFltInit();
            if (NT_SUCCESS(Status))
            {
                Status = vboxUsbMonHookCheckInit();
                if (NT_SUCCESS(Status))
                {
                    Status = vboxUsbMonHookInstall();
                    if (NT_SUCCESS(Status))
                    {
                        Status = STATUS_SUCCESS;
                        LOG(("succeded!!"));
                        break;
                    }
                    else
                    {
                        WARN(("vboxUsbMonHookInstall failed, Status (0x%x)", Status));
                    }
                }
                else
                {
                    WARN(("vboxUsbMonHookCheckInit failed, Status (0x%x)", Status));
                }
                VBoxUsbFltTerm();
            }
            else
            {
                WARN(("VBoxUsbFltInit failed, Status (0x%x)", Status));
            }

            --g_VBoxUsbMonGlobals.cOpens;
            Assert(!g_VBoxUsbMonGlobals.cOpens);
        } while (0);

        KeSetEvent(&g_VBoxUsbMonGlobals.OpenSynchEvent, 0, FALSE);
    }
    else
    {
        WARN(("KeWaitForSingleObject failed, Status (0x%x)", Status));
    }
    return Status;
}

static NTSTATUS vboxUsbMonContextCreate(PVBOXUSBMONCTX *ppCtx)
{
    NTSTATUS Status;
    *ppCtx = NULL;
    PVBOXUSBMONCTX pFileCtx = (PVBOXUSBMONCTX)VBoxUsbMonMemAllocZ(sizeof (*pFileCtx));
    if (pFileCtx)
    {
        Status = vboxUsbMonCheckInitStuff();
        if (Status == STATUS_SUCCESS)
        {
            Status = VBoxUsbFltCreate(&pFileCtx->FltCtx);
            if (Status == STATUS_SUCCESS)
            {
                *ppCtx = pFileCtx;
                LOG(("succeeded!!"));
                return STATUS_SUCCESS;
            }
            else
            {
                WARN(("VBoxUsbFltCreate failed"));
            }
            vboxUsbMonCheckTermStuff();
        }
        else
        {
            WARN(("vboxUsbMonCheckInitStuff failed"));
        }
        VBoxUsbMonMemFree(pFileCtx);
    }
    else
    {
        WARN(("VBoxUsbMonMemAllocZ failed"));
        Status = STATUS_NO_MEMORY;
    }

    return Status;
}

static NTSTATUS vboxUsbMonContextClose(PVBOXUSBMONCTX pCtx)
{
    NTSTATUS Status = VBoxUsbFltClose(&pCtx->FltCtx);
    if (Status == STATUS_SUCCESS)
    {
        Status = vboxUsbMonCheckTermStuff();
        Assert(Status == STATUS_SUCCESS);
        /* ignore the failure */
        VBoxUsbMonMemFree(pCtx);
    }

    return Status;
}

static NTSTATUS _stdcall VBoxUsbMonClose(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
    PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
    PFILE_OBJECT pFileObj = pStack->FileObject;
    Assert(pFileObj->FsContext);
    PVBOXUSBMONCTX pCtx = (PVBOXUSBMONCTX)pFileObj->FsContext;

    LOG(("VBoxUsbMonClose"));

    NTSTATUS Status = vboxUsbMonContextClose(pCtx);
    if (Status != STATUS_SUCCESS)
    {
        WARN(("vboxUsbMonContextClose failed, Status (0x%x), prefent unload", Status));
        if (!InterlockedExchange(&g_VBoxUsbMonGlobals.ulPreventUnloadOn, 1))
        {
            LOGREL(("ulPreventUnloadOn not set, preventing unload"));
            UNICODE_STRING UniName;
            PDEVICE_OBJECT pTmpDevObj;
            RtlInitUnicodeString(&UniName, USBMON_DEVICE_NAME_NT);
            NTSTATUS tmpStatus = IoGetDeviceObjectPointer(&UniName, FILE_ALL_ACCESS, &g_VBoxUsbMonGlobals.pPreventUnloadFileObj, &pTmpDevObj);
            AssertRelease(NT_SUCCESS(tmpStatus));
            AssertRelease(pTmpDevObj == pDevObj);
        }
        else
        {
            WARN(("ulPreventUnloadOn already set"));
        }
        LOG(("success!!"));
        Status = STATUS_SUCCESS;
    }
    pFileObj->FsContext = NULL;
    pIrp->IoStatus.Status = Status;
    pIrp->IoStatus.Information  = 0;
    IoCompleteRequest(pIrp, IO_NO_INCREMENT);
    return Status;
}


static NTSTATUS _stdcall VBoxUsbMonCreate(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
    RT_NOREF1(pDevObj);
    PIO_STACK_LOCATION pStack = IoGetCurrentIrpStackLocation(pIrp);
    PFILE_OBJECT pFileObj = pStack->FileObject;
    NTSTATUS Status;

    LOG(("VBoxUSBMonCreate"));

    if (pStack->Parameters.Create.Options & FILE_DIRECTORY_FILE)
    {
        WARN(("trying to open as a directory"));
        pIrp->IoStatus.Status = STATUS_NOT_A_DIRECTORY;
        pIrp->IoStatus.Information = 0;
        IoCompleteRequest(pIrp, IO_NO_INCREMENT);
        return STATUS_NOT_A_DIRECTORY;
    }

    pFileObj->FsContext = NULL;
    PVBOXUSBMONCTX pCtx = NULL;
    Status = vboxUsbMonContextCreate(&pCtx);
    if (Status == STATUS_SUCCESS)
    {
        Assert(pCtx);
        pFileObj->FsContext = pCtx;
    }
    else
    {
        WARN(("vboxUsbMonContextCreate failed Status (0x%x)", Status));
    }

    pIrp->IoStatus.Status = Status;
    pIrp->IoStatus.Information  = 0;
    IoCompleteRequest(pIrp, IO_NO_INCREMENT);
    return Status;
}

static int VBoxUsbMonSetNotifyEvent(PVBOXUSBMONCTX pContext, HANDLE hEvent)
{
    int rc = VBoxUsbFltSetNotifyEvent(&pContext->FltCtx, hEvent);
    return rc;
}

static int VBoxUsbMonFltAdd(PVBOXUSBMONCTX pContext, PUSBFILTER pFilter, uintptr_t *pId)
{
#ifdef VBOXUSBMON_DBG_NO_FILTERS
    static uintptr_t idDummy = 1;
    *pId = idDummy;
    ++idDummy;
    return VINF_SUCCESS;
#else
    int rc = VBoxUsbFltAdd(&pContext->FltCtx, pFilter, pId);
    return rc;
#endif
}

static int VBoxUsbMonFltRemove(PVBOXUSBMONCTX pContext, uintptr_t uId)
{
#ifdef VBOXUSBMON_DBG_NO_FILTERS
    return VINF_SUCCESS;
#else
    int rc = VBoxUsbFltRemove(&pContext->FltCtx, uId);
    return rc;
#endif
}

static NTSTATUS VBoxUsbMonRunFilters(PVBOXUSBMONCTX pContext)
{
    NTSTATUS Status = VBoxUsbFltFilterCheck(&pContext->FltCtx);
    return Status;
}

static NTSTATUS VBoxUsbMonGetDevice(PVBOXUSBMONCTX pContext, HVBOXUSBDEVUSR hDevice, PUSBSUP_GETDEV_MON pInfo)
{
    NTSTATUS Status = VBoxUsbFltGetDevice(&pContext->FltCtx, hDevice, pInfo);
    return Status;
}

static NTSTATUS vboxUsbMonIoctlDispatch(PVBOXUSBMONCTX pContext, ULONG Ctl, PVOID pvBuffer, ULONG cbInBuffer,
                                        ULONG cbOutBuffer, ULONG_PTR *pInfo)
{
    NTSTATUS Status = STATUS_SUCCESS;
    ULONG_PTR Info = 0;
    switch (Ctl)
    {
        case SUPUSBFLT_IOCTL_GET_VERSION:
        {
            PUSBSUP_VERSION pOut = (PUSBSUP_VERSION)pvBuffer;

            LOG(("SUPUSBFLT_IOCTL_GET_VERSION"));
            if (!pvBuffer || cbOutBuffer != sizeof(*pOut) || cbInBuffer != 0)
            {
                WARN(("SUPUSBFLT_IOCTL_GET_VERSION: Invalid input/output sizes. cbIn=%d expected %d. cbOut=%d expected %d.",
                        cbInBuffer, 0, cbOutBuffer, sizeof (*pOut)));
                Status = STATUS_INVALID_PARAMETER;
                break;
            }
            pOut->u32Major = USBMON_MAJOR_VERSION;
            pOut->u32Minor = USBMON_MINOR_VERSION;
            Info = sizeof (*pOut);
            ASSERT_WARN(Status == STATUS_SUCCESS, ("unexpected status, 0x%x", Status));
            break;
        }

        case SUPUSBFLT_IOCTL_ADD_FILTER:
        {
            PUSBFILTER pFilter = (PUSBFILTER)pvBuffer;
            PUSBSUP_FLTADDOUT pOut = (PUSBSUP_FLTADDOUT)pvBuffer;
            uintptr_t uId = 0;
            int rc;
            if (RT_UNLIKELY(!pvBuffer || cbInBuffer != sizeof (*pFilter) || cbOutBuffer != sizeof (*pOut)))
            {
                WARN(("SUPUSBFLT_IOCTL_ADD_FILTER: Invalid input/output sizes. cbIn=%d expected %d. cbOut=%d expected %d.",
                        cbInBuffer, sizeof (*pFilter), cbOutBuffer, sizeof (*pOut)));
                Status = STATUS_INVALID_PARAMETER;
                break;
            }

            rc = VBoxUsbMonFltAdd(pContext, pFilter, &uId);
            pOut->rc  = rc;
            pOut->uId = uId;
            Info = sizeof (*pOut);
            ASSERT_WARN(Status == STATUS_SUCCESS, ("unexpected status, 0x%x", Status));
            break;
        }

        case SUPUSBFLT_IOCTL_REMOVE_FILTER:
        {
            uintptr_t *pIn = (uintptr_t *)pvBuffer;
            int *pRc = (int *)pvBuffer;

            if (!pvBuffer || cbInBuffer != sizeof (*pIn) || (cbOutBuffer && cbOutBuffer != sizeof (*pRc)))
            {
                WARN(("SUPUSBFLT_IOCTL_REMOVE_FILTER: Invalid input/output sizes. cbIn=%d expected %d. cbOut=%d expected %d.",
                        cbInBuffer, sizeof (*pIn), cbOutBuffer, 0));
                Status = STATUS_INVALID_PARAMETER;
                break;
            }
            LOG(("SUPUSBFLT_IOCTL_REMOVE_FILTER %x", *pIn));
            int rc = VBoxUsbMonFltRemove(pContext, *pIn);
            if (cbOutBuffer)
            {
                /* we've validated that already */
                Assert(cbOutBuffer == (ULONG)*pRc);
                *pRc = rc;
                Info = sizeof (*pRc);
            }
            ASSERT_WARN(Status == STATUS_SUCCESS, ("unexpected status, 0x%x", Status));
            break;
        }

        case SUPUSBFLT_IOCTL_RUN_FILTERS:
        {
            if (pvBuffer || cbInBuffer || cbOutBuffer)
            {
                WARN(("SUPUSBFLT_IOCTL_RUN_FILTERS: Invalid input/output sizes. cbIn=%d expected %d. cbOut=%d expected %d.",
                        cbInBuffer, 0, cbOutBuffer, 0));
                Status = STATUS_INVALID_PARAMETER;
                break;
            }
            LOG(("SUPUSBFLT_IOCTL_RUN_FILTERS "));
            Status = VBoxUsbMonRunFilters(pContext);
            ASSERT_WARN(Status != STATUS_PENDING, ("status pending!"));
            break;
        }

        case SUPUSBFLT_IOCTL_GET_DEVICE:
        {
            HVBOXUSBDEVUSR hDevice = *((HVBOXUSBDEVUSR*)pvBuffer);
            PUSBSUP_GETDEV_MON pOut = (PUSBSUP_GETDEV_MON)pvBuffer;
            if (!pvBuffer || cbInBuffer != sizeof (hDevice) || cbOutBuffer < sizeof (*pOut))
            {
                WARN(("SUPUSBFLT_IOCTL_GET_DEVICE: Invalid input/output sizes. cbIn=%d expected %d. cbOut=%d expected >= %d.",
                        cbInBuffer, sizeof (hDevice), cbOutBuffer, sizeof (*pOut)));
                Status = STATUS_INVALID_PARAMETER;
                break;
            }

            Status = VBoxUsbMonGetDevice(pContext, hDevice, pOut);

            if (NT_SUCCESS(Status))
            {
                Info = sizeof (*pOut);
            }
            else
            {
                WARN(("VBoxUsbMonGetDevice fail 0x%x", Status));
            }
            break;
        }

        case SUPUSBFLT_IOCTL_SET_NOTIFY_EVENT:
        {
            PUSBSUP_SET_NOTIFY_EVENT pSne = (PUSBSUP_SET_NOTIFY_EVENT)pvBuffer;
            if (!pvBuffer || cbInBuffer != sizeof (*pSne) || cbOutBuffer != sizeof (*pSne))
            {
                WARN(("SUPUSBFLT_IOCTL_SET_NOTIFY_EVENT: Invalid input/output sizes. cbIn=%d expected %d. cbOut=%d expected %d.",
                        cbInBuffer, sizeof (*pSne), cbOutBuffer, sizeof (*pSne)));
                Status = STATUS_INVALID_PARAMETER;
                break;
            }

            pSne->u.rc = VBoxUsbMonSetNotifyEvent(pContext, pSne->u.hEvent);
            Info = sizeof (*pSne);
            ASSERT_WARN(Status == STATUS_SUCCESS, ("unexpected status, 0x%x", Status));
            break;
        }

        default:
            WARN(("Unknown code 0x%x", Ctl));
            Status = STATUS_INVALID_PARAMETER;
            break;
    }

    ASSERT_WARN(Status != STATUS_PENDING, ("Status pending!"));

    *pInfo = Info;
    return Status;
}

static NTSTATUS _stdcall VBoxUsbMonDeviceControl(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
    ULONG_PTR Info = 0;
    NTSTATUS Status = IoAcquireRemoveLock(&g_VBoxUsbMonGlobals.RmLock, pDevObj);
    if (NT_SUCCESS(Status))
    {
        PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
        PFILE_OBJECT pFileObj = pSl->FileObject;
        Assert(pFileObj);
        Assert(pFileObj->FsContext);
        PVBOXUSBMONCTX pCtx = (PVBOXUSBMONCTX)pFileObj->FsContext;
        Assert(pCtx);
        Status = vboxUsbMonIoctlDispatch(pCtx,
                    pSl->Parameters.DeviceIoControl.IoControlCode,
                    pIrp->AssociatedIrp.SystemBuffer,
                    pSl->Parameters.DeviceIoControl.InputBufferLength,
                    pSl->Parameters.DeviceIoControl.OutputBufferLength,
                    &Info);
        ASSERT_WARN(Status != STATUS_PENDING, ("Status pending"));

        IoReleaseRemoveLock(&g_VBoxUsbMonGlobals.RmLock, pDevObj);
    }
    else
    {
        WARN(("IoAcquireRemoveLock failed Status (0x%x)", Status));
    }

    pIrp->IoStatus.Information = Info;
    pIrp->IoStatus.Status = Status;
    IoCompleteRequest (pIrp, IO_NO_INCREMENT);
    return Status;
}

static NTSTATUS vboxUsbMonInternalIoctlDispatch(ULONG Ctl, PVOID pvBuffer,  ULONG_PTR *pInfo)
{
    NTSTATUS Status = STATUS_SUCCESS;
    *pInfo = 0;
    switch (Ctl)
    {
        case VBOXUSBIDC_INTERNAL_IOCTL_GET_VERSION:
        {
            PVBOXUSBIDC_VERSION pOut = (PVBOXUSBIDC_VERSION)pvBuffer;

            LOG(("VBOXUSBIDC_INTERNAL_IOCTL_GET_VERSION"));
            if (!pvBuffer)
            {
                WARN(("VBOXUSBIDC_INTERNAL_IOCTL_GET_VERSION: Buffer is NULL"));
                Status = STATUS_INVALID_PARAMETER;
                break;
            }
            pOut->u32Major = VBOXUSBIDC_VERSION_MAJOR;
            pOut->u32Minor = VBOXUSBIDC_VERSION_MINOR;
            ASSERT_WARN(Status == STATUS_SUCCESS, ("unexpected status, 0x%x", Status));
            break;
        }

        case VBOXUSBIDC_INTERNAL_IOCTL_PROXY_STARTUP:
        {
            PVBOXUSBIDC_PROXY_STARTUP pOut = (PVBOXUSBIDC_PROXY_STARTUP)pvBuffer;

            LOG(("VBOXUSBIDC_INTERNAL_IOCTL_PROXY_STARTUP"));
            if (!pvBuffer)
            {
                WARN(("VBOXUSBIDC_INTERNAL_IOCTL_PROXY_STARTUP: Buffer is NULL"));
                Status = STATUS_INVALID_PARAMETER;
                break;
            }

            pOut->u.hDev = VBoxUsbFltProxyStarted(pOut->u.pPDO);
            ASSERT_WARN(pOut->u.hDev, ("zero hDev"));
            ASSERT_WARN(Status == STATUS_SUCCESS, ("unexpected status, 0x%x", Status));
            break;
        }

        case VBOXUSBIDC_INTERNAL_IOCTL_PROXY_TEARDOWN:
        {
            PVBOXUSBIDC_PROXY_TEARDOWN pOut = (PVBOXUSBIDC_PROXY_TEARDOWN)pvBuffer;

            LOG(("VBOXUSBIDC_INTERNAL_IOCTL_PROXY_TEARDOWN"));
            if (!pvBuffer)
            {
                WARN(("VBOXUSBIDC_INTERNAL_IOCTL_PROXY_TEARDOWN: Buffer is NULL"));
                Status = STATUS_INVALID_PARAMETER;
                break;
            }

            ASSERT_WARN(pOut->hDev, ("zero hDev"));
            VBoxUsbFltProxyStopped(pOut->hDev);
            ASSERT_WARN(Status == STATUS_SUCCESS, ("unexpected status, 0x%x", Status));
            break;
        }

        default:
        {
            WARN(("Unknown code 0x%x", Ctl));
            Status = STATUS_INVALID_PARAMETER;
            break;
        }
    }

    return Status;
}

static NTSTATUS _stdcall VBoxUsbMonInternalDeviceControl(PDEVICE_OBJECT pDevObj, PIRP pIrp)
{
    ULONG_PTR Info = 0;
    NTSTATUS Status = IoAcquireRemoveLock(&g_VBoxUsbMonGlobals.RmLock, pDevObj);
    if (NT_SUCCESS(Status))
    {
        PIO_STACK_LOCATION pSl = IoGetCurrentIrpStackLocation(pIrp);
        Status = vboxUsbMonInternalIoctlDispatch(pSl->Parameters.DeviceIoControl.IoControlCode,
                        pSl->Parameters.Others.Argument1,
                        &Info);
        Assert(Status != STATUS_PENDING);

        IoReleaseRemoveLock(&g_VBoxUsbMonGlobals.RmLock, pDevObj);
    }

    pIrp->IoStatus.Information = Info;
    pIrp->IoStatus.Status = Status;
    IoCompleteRequest (pIrp, IO_NO_INCREMENT);
    return Status;
}

/**
 * Unload the driver.
 *
 * @param   pDrvObj     Driver object.
 */
static void _stdcall VBoxUsbMonUnload(PDRIVER_OBJECT pDrvObj)
{
    RT_NOREF1(pDrvObj);
    LOG(("VBoxUSBMonUnload pDrvObj (0x%p)", pDrvObj));

    IoReleaseRemoveLockAndWait(&g_VBoxUsbMonGlobals.RmLock, &g_VBoxUsbMonGlobals);

    Assert(!g_VBoxUsbMonGlobals.cOpens);

    UNICODE_STRING DosName;
    RtlInitUnicodeString(&DosName, USBMON_DEVICE_NAME_DOS);
    IoDeleteSymbolicLink(&DosName);

    IoDeleteDevice(g_VBoxUsbMonGlobals.pDevObj);

    /* cleanup the logger */
    PRTLOGGER pLogger = RTLogRelSetDefaultInstance(NULL);
    if (pLogger)
        RTLogDestroy(pLogger);
    pLogger = RTLogSetDefaultInstance(NULL);
    if (pLogger)
        RTLogDestroy(pLogger);
}

RT_C_DECLS_BEGIN
NTSTATUS _stdcall DriverEntry(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath);
RT_C_DECLS_END

/**
 * Driver entry point.
 *
 * @returns appropriate status code.
 * @param   pDrvObj     Pointer to driver object.
 * @param   pRegPath    Registry base path.
 */
NTSTATUS _stdcall DriverEntry(PDRIVER_OBJECT pDrvObj, PUNICODE_STRING pRegPath)
{
    RT_NOREF1(pRegPath);
#ifdef VBOX_USB_WITH_VERBOSE_LOGGING
    RTLogGroupSettings(0, "+default.e.l.f.l2.l3");
    RTLogDestinations(0, "debugger");
#endif

    LOGREL(("Built %s %s", __DATE__, __TIME__));

    memset (&g_VBoxUsbMonGlobals, 0, sizeof (g_VBoxUsbMonGlobals));
#ifdef VBOX_USB3PORT
    VBOX_PNPHOOKSTUB_INIT(0);
    VBOX_PNPHOOKSTUB_INIT(1);
    VBOX_PNPHOOKSTUB_INIT(2);
    VBOX_PNPHOOKSTUB_INIT(3);
    VBOX_PNPHOOKSTUB_INIT(4);
    AssertCompile(VBOXUSBMON_MAXDRIVERS == 5);
#endif /* VBOX_USB3PORT */
    KeInitializeEvent(&g_VBoxUsbMonGlobals.OpenSynchEvent, SynchronizationEvent, TRUE /* signaled */);
    IoInitializeRemoveLock(&g_VBoxUsbMonGlobals.RmLock, VBOXUSBMON_MEMTAG, 1, 100);
    UNICODE_STRING DevName;
    PDEVICE_OBJECT pDevObj;
    /* create the device */
    RtlInitUnicodeString(&DevName, USBMON_DEVICE_NAME_NT);
    NTSTATUS Status = IoAcquireRemoveLock(&g_VBoxUsbMonGlobals.RmLock, &g_VBoxUsbMonGlobals);
    if (NT_SUCCESS(Status))
    {
        Status = IoCreateDevice(pDrvObj, sizeof (VBOXUSBMONINS), &DevName, FILE_DEVICE_UNKNOWN, 0, FALSE, &pDevObj);
        if (NT_SUCCESS(Status))
        {
            UNICODE_STRING DosName;
            RtlInitUnicodeString(&DosName, USBMON_DEVICE_NAME_DOS);
            Status = IoCreateSymbolicLink(&DosName, &DevName);
            if (NT_SUCCESS(Status))
            {
                PVBOXUSBMONINS pDevExt = (PVBOXUSBMONINS)pDevObj->DeviceExtension;
                memset(pDevExt, 0, sizeof(*pDevExt));

                pDrvObj->DriverUnload = VBoxUsbMonUnload;
                pDrvObj->MajorFunction[IRP_MJ_CREATE] = VBoxUsbMonCreate;
                pDrvObj->MajorFunction[IRP_MJ_CLOSE] = VBoxUsbMonClose;
                pDrvObj->MajorFunction[IRP_MJ_DEVICE_CONTROL] = VBoxUsbMonDeviceControl;
                pDrvObj->MajorFunction[IRP_MJ_INTERNAL_DEVICE_CONTROL] = VBoxUsbMonInternalDeviceControl;

                g_VBoxUsbMonGlobals.pDevObj = pDevObj;
                LOG(("VBoxUSBMon::DriverEntry returning STATUS_SUCCESS"));
                return STATUS_SUCCESS;
            }
            IoDeleteDevice(pDevObj);
        }
        IoReleaseRemoveLockAndWait(&g_VBoxUsbMonGlobals.RmLock, &g_VBoxUsbMonGlobals);
    }

    return Status;
}