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
// Copyright (c) 2004, Antony C. Roberts

// Use of this file is subject to the terms
// described in the LICENSE.TXT file that
// accompanies this file.
//
// Your use of this file indicates your
// acceptance of the terms described in
// LICENSE.TXT.
//
// http://www.freebt.net

#include "stdio.h"
#include "fbtusb.h"
#include "fbtpnp.h"
#include "fbtpwr.h"
#include "fbtdev.h"
#include "fbtrwr.h"
#include "fbtwmi.h"

#include "fbtusr.h"

// Handle PNP events
NTSTATUS NTAPI FreeBT_DispatchPnP(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
    PIO_STACK_LOCATION irpStack;
    PDEVICE_EXTENSION  deviceExtension;
    //KEVENT             startDeviceEvent;
    NTSTATUS           ntStatus;

    irpStack = IoGetCurrentIrpStackLocation(Irp);
    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;

    // since the device is removed, fail the Irp.
    if (Removed == deviceExtension->DeviceState)
    {
        ntStatus = STATUS_DELETE_PENDING;
        Irp->IoStatus.Status = ntStatus;
        Irp->IoStatus.Information = 0;
        IoCompleteRequest(Irp, IO_NO_INCREMENT);
        return ntStatus;

    }

    FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_DispatchPnP::"));
    FreeBT_IoIncrement(deviceExtension);
    if (irpStack->MinorFunction == IRP_MN_START_DEVICE)
    {
        ASSERT(deviceExtension->IdleReqPend == 0);

    }

    else
    {
        if (deviceExtension->SSEnable)
        {
            CancelSelectSuspend(deviceExtension);

        }

    }

    FreeBT_DbgPrint(3, ("FBTUSB: ///////////////////////////////////////////\n"));
    FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_DispatchPnP::"));
    FreeBT_DbgPrint(2, (PnPMinorFunctionString(irpStack->MinorFunction)));
    switch (irpStack->MinorFunction)
    {
    case IRP_MN_START_DEVICE:
        ntStatus = HandleStartDevice(DeviceObject, Irp);
        break;

    case IRP_MN_QUERY_STOP_DEVICE:
        // if we cannot stop the device, we fail the query stop irp
        ntStatus = CanStopDevice(DeviceObject, Irp);
        if(NT_SUCCESS(ntStatus))
        {
            ntStatus = HandleQueryStopDevice(DeviceObject, Irp);
            return ntStatus;

        }

        break;

    case IRP_MN_CANCEL_STOP_DEVICE:
        ntStatus = HandleCancelStopDevice(DeviceObject, Irp);
        break;

    case IRP_MN_STOP_DEVICE:
        ntStatus = HandleStopDevice(DeviceObject, Irp);
        FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_DispatchPnP::IRP_MN_STOP_DEVICE::"));
        FreeBT_IoDecrement(deviceExtension);

        return ntStatus;

    case IRP_MN_QUERY_REMOVE_DEVICE:
        // if we cannot remove the device, we fail the query remove irp
        ntStatus = HandleQueryRemoveDevice(DeviceObject, Irp);

        return ntStatus;

    case IRP_MN_CANCEL_REMOVE_DEVICE:
        ntStatus = HandleCancelRemoveDevice(DeviceObject, Irp);
        break;

    case IRP_MN_SURPRISE_REMOVAL:
        ntStatus = HandleSurpriseRemoval(DeviceObject, Irp);
        FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_DispatchPnP::IRP_MN_SURPRISE_REMOVAL::"));
        FreeBT_IoDecrement(deviceExtension);
        return ntStatus;

    case IRP_MN_REMOVE_DEVICE:
        ntStatus = HandleRemoveDevice(DeviceObject, Irp);
        return ntStatus;

    case IRP_MN_QUERY_CAPABILITIES:
        ntStatus = HandleQueryCapabilities(DeviceObject, Irp);
        break;

    default:
        IoSkipCurrentIrpStackLocation(Irp);

        ntStatus = IoCallDriver(deviceExtension->TopOfStackDeviceObject, Irp);

        FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_DispatchPnP::default::"));
        FreeBT_IoDecrement(deviceExtension);

        return ntStatus;

    }

    Irp->IoStatus.Status = ntStatus;
    Irp->IoStatus.Information = 0;
    IoCompleteRequest(Irp, IO_NO_INCREMENT);

    FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_DispatchPnP::"));
    FreeBT_IoDecrement(deviceExtension);

    return ntStatus;

}

NTSTATUS NTAPI HandleStartDevice(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
    KIRQL             oldIrql;
    KEVENT            startDeviceEvent;
    NTSTATUS          ntStatus;
    PDEVICE_EXTENSION deviceExtension;
    LARGE_INTEGER     dueTime;

    FreeBT_DbgPrint(3, ("FBTUSB: HandleStartDevice: Entered\n"));

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;
    deviceExtension->UsbConfigurationDescriptor = NULL;
    deviceExtension->UsbInterface = NULL;
    deviceExtension->PipeContext = NULL;

    // We cannot touch the device (send it any non pnp irps) until a
    // start device has been passed down to the lower drivers.
    // first pass the Irp down
    KeInitializeEvent(&startDeviceEvent, NotificationEvent, FALSE);
    IoCopyCurrentIrpStackLocationToNext(Irp);
    IoSetCompletionRoutine(Irp,
                           (PIO_COMPLETION_ROUTINE)IrpCompletionRoutine,
                           (PVOID)&startDeviceEvent,
                           TRUE,
                           TRUE,
                           TRUE);

    ntStatus = IoCallDriver(deviceExtension->TopOfStackDeviceObject, Irp);
    if (ntStatus == STATUS_PENDING)
    {
        KeWaitForSingleObject(&startDeviceEvent, Executive, KernelMode, FALSE, NULL);
        ntStatus = Irp->IoStatus.Status;

    }

    if (!NT_SUCCESS(ntStatus))
    {
        FreeBT_DbgPrint(1, ("FBTUSB: HandleStartDevice: Lower drivers failed this Irp (0x%08x)\n", ntStatus));
        return ntStatus;

    }

    // Read the device descriptor, configuration descriptor
    // and select the interface descriptors
    ntStatus = ReadandSelectDescriptors(DeviceObject);
    if (!NT_SUCCESS(ntStatus))
    {
        FreeBT_DbgPrint(1, ("FBTUSB: HandleStartDevice: ReadandSelectDescriptors failed (0x%08x)\n", ntStatus));
        return ntStatus;

    }

    // enable the symbolic links for system components to open
    // handles to the device
    ntStatus = IoSetDeviceInterfaceState(&deviceExtension->InterfaceName, TRUE);
    if (!NT_SUCCESS(ntStatus))
    {
        FreeBT_DbgPrint(1, ("FBTUSB: HandleStartDevice: IoSetDeviceInterfaceState failed (0x%08x)\n", ntStatus));
        return ntStatus;

    }

    KeAcquireSpinLock(&deviceExtension->DevStateLock, &oldIrql);

    SET_NEW_PNP_STATE(deviceExtension, Working);
    deviceExtension->QueueState = AllowRequests;

    KeReleaseSpinLock(&deviceExtension->DevStateLock, oldIrql);

    deviceExtension->FlagWWOutstanding = 0;
    deviceExtension->FlagWWCancel = 0;
    deviceExtension->WaitWakeIrp = NULL;

    if (deviceExtension->WaitWakeEnable)
    {
        IssueWaitWake(deviceExtension);

    }

    ProcessQueuedRequests(deviceExtension);
    if (WinXpOrBetter == deviceExtension->WdmVersion)
    {
        deviceExtension->SSEnable = deviceExtension->SSRegistryEnable;

        // set timer.for selective suspend requests
        if (deviceExtension->SSEnable)
        {
            dueTime.QuadPart = -10000 * IDLE_INTERVAL;               // 5000 ms
            KeSetTimerEx(&deviceExtension->Timer, dueTime, IDLE_INTERVAL, &deviceExtension->DeferredProcCall);
            deviceExtension->FreeIdleIrpCount = 0;

        }

    }

    FreeBT_DbgPrint(3, ("FBTUSB: HandleStartDevice: Leaving\n"));

    return ntStatus;

}


NTSTATUS NTAPI ReadandSelectDescriptors(IN PDEVICE_OBJECT DeviceObject)
{
    PURB                   urb;
    ULONG                  siz;
    NTSTATUS               ntStatus;
    PUSB_DEVICE_DESCRIPTOR deviceDescriptor;

    urb = NULL;
    deviceDescriptor = NULL;

    // 1. Read the device descriptor
    urb = (PURB) ExAllocatePool(NonPagedPool, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST));
    if(urb)
    {
        siz = sizeof(USB_DEVICE_DESCRIPTOR);
        deviceDescriptor = (PUSB_DEVICE_DESCRIPTOR) ExAllocatePool(NonPagedPool, siz);
        if (deviceDescriptor)
        {
            UsbBuildGetDescriptorRequest(
                    urb,
                    (USHORT) sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST),
                    USB_DEVICE_DESCRIPTOR_TYPE,
                    0,
                    0,
                    deviceDescriptor,
                    NULL,
                    siz,
                    NULL);

            ntStatus = CallUSBD(DeviceObject, urb);
            if (NT_SUCCESS(ntStatus))
            {
                ASSERT(deviceDescriptor->bNumConfigurations);
                ntStatus = ConfigureDevice(DeviceObject);

            }

            ExFreePool(urb);
            ExFreePool(deviceDescriptor);

        }

        else
        {
            FreeBT_DbgPrint(1, ("FBTUSB: ReadandSelectDescriptors: Failed to allocate memory for deviceDescriptor"));
            ExFreePool(urb);
            ntStatus = STATUS_INSUFFICIENT_RESOURCES;

        }

    }

    else
    {
        FreeBT_DbgPrint(1, ("FBTUSB: ReadandSelectDescriptors: Failed to allocate memory for urb"));
        ntStatus = STATUS_INSUFFICIENT_RESOURCES;

    }


    return ntStatus;

}

NTSTATUS NTAPI ConfigureDevice(IN PDEVICE_OBJECT DeviceObject)
{
    PURB                          urb;
    ULONG                         siz;
    NTSTATUS                      ntStatus;
    PDEVICE_EXTENSION             deviceExtension;
    PUSB_CONFIGURATION_DESCRIPTOR configurationDescriptor;

    urb = NULL;
    configurationDescriptor = NULL;
    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;

    // Read the first configuration descriptor
    // This requires two steps:
    // 1. Read the fixed sized configuration desciptor (CD)
    // 2. Read the CD with all embedded interface and endpoint descriptors
    urb = (PURB) ExAllocatePool(NonPagedPool, sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST));
    if (urb)
    {
        siz = sizeof(USB_CONFIGURATION_DESCRIPTOR);
        configurationDescriptor = (PUSB_CONFIGURATION_DESCRIPTOR) ExAllocatePool(NonPagedPool, siz);

        if(configurationDescriptor)
        {
            UsbBuildGetDescriptorRequest(
                    urb,
                    (USHORT) sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST),
                    USB_CONFIGURATION_DESCRIPTOR_TYPE,
                    0,
                    0,
                    configurationDescriptor,
                    NULL,
                    sizeof(USB_CONFIGURATION_DESCRIPTOR),
                    NULL);

            ntStatus = CallUSBD(DeviceObject, urb);
            if(!NT_SUCCESS(ntStatus))
            {
                FreeBT_DbgPrint(1, ("FBTUSB: ConfigureDevice: UsbBuildGetDescriptorRequest failed\n"));
                goto ConfigureDevice_Exit;

            }

        }

        else
        {
            FreeBT_DbgPrint(1, ("FBTUSB: ConfigureDevice: Failed to allocate mem for config Descriptor\n"));
            ntStatus = STATUS_INSUFFICIENT_RESOURCES;
            goto ConfigureDevice_Exit;

        }

        siz = configurationDescriptor->wTotalLength;
        ExFreePool(configurationDescriptor);

        configurationDescriptor = (PUSB_CONFIGURATION_DESCRIPTOR) ExAllocatePool(NonPagedPool, siz);
        if (configurationDescriptor)
        {
            UsbBuildGetDescriptorRequest(
                    urb,
                    (USHORT)sizeof(struct _URB_CONTROL_DESCRIPTOR_REQUEST),
                    USB_CONFIGURATION_DESCRIPTOR_TYPE,
                    0,
                    0,
                    configurationDescriptor,
                    NULL,
                    siz,
                    NULL);

            ntStatus = CallUSBD(DeviceObject, urb);
            if (!NT_SUCCESS(ntStatus))
            {
                FreeBT_DbgPrint(1,("FBTUSB: ConfigureDevice: Failed to read configuration descriptor"));
                goto ConfigureDevice_Exit;

            }

        }

        else
        {
            FreeBT_DbgPrint(1, ("FBTUSB: ConfigureDevice: Failed to alloc mem for config Descriptor\n"));
            ntStatus = STATUS_INSUFFICIENT_RESOURCES;
            goto ConfigureDevice_Exit;

        }

    }

    else
    {
        FreeBT_DbgPrint(1, ("FBTUSB: ConfigureDevice: Failed to allocate memory for urb\n"));
        ntStatus = STATUS_INSUFFICIENT_RESOURCES;
        goto ConfigureDevice_Exit;

    }

    if (configurationDescriptor)
    {
        // save a copy of configurationDescriptor in deviceExtension
        // remember to free it later.
        deviceExtension->UsbConfigurationDescriptor = configurationDescriptor;

        if (configurationDescriptor->bmAttributes & REMOTE_WAKEUP_MASK)
        {
            // this configuration supports remote wakeup
            deviceExtension->WaitWakeEnable = 1;

        }

        else
        {
            deviceExtension->WaitWakeEnable = 0;

        }

        ntStatus = SelectInterfaces(DeviceObject, configurationDescriptor);

    }

    else
    {
        deviceExtension->UsbConfigurationDescriptor = NULL;

    }

ConfigureDevice_Exit:
    if (urb)
    {
        ExFreePool(urb);

    }

    return ntStatus;

}

NTSTATUS NTAPI SelectInterfaces(IN PDEVICE_OBJECT DeviceObject, IN PUSB_CONFIGURATION_DESCRIPTOR ConfigurationDescriptor)
{
    LONG                        numberOfInterfaces, interfaceNumber, interfaceindex;
    ULONG                       i;
    PURB                        urb;
    //PUCHAR                      pInf;
    NTSTATUS                    ntStatus;
    PDEVICE_EXTENSION           deviceExtension;
    PUSB_INTERFACE_DESCRIPTOR   interfaceDescriptor;
    PUSBD_INTERFACE_LIST_ENTRY  interfaceList,
                                tmp;
    PUSBD_INTERFACE_INFORMATION Interface;

    urb = NULL;
    Interface = NULL;
    interfaceDescriptor = NULL;
    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;
    numberOfInterfaces = ConfigurationDescriptor->bNumInterfaces;
    interfaceindex = interfaceNumber = 0;

    // Parse the configuration descriptor for the interface;
    tmp = interfaceList = (PUSBD_INTERFACE_LIST_ENTRY)
        ExAllocatePool(NonPagedPool, sizeof(USBD_INTERFACE_LIST_ENTRY) * (numberOfInterfaces + 1));

    if (!tmp)
    {

        FreeBT_DbgPrint(1, ("FBTUSB: SelectInterfaces: Failed to allocate mem for interfaceList\n"));
        return STATUS_INSUFFICIENT_RESOURCES;

    }


    FreeBT_DbgPrint(3, ("FBTUSB: -------------\n"));
    FreeBT_DbgPrint(3, ("FBTUSB: Number of interfaces %d\n", numberOfInterfaces));

    while (interfaceNumber < numberOfInterfaces)
    {
        interfaceDescriptor = USBD_ParseConfigurationDescriptorEx(
                                            ConfigurationDescriptor,
                                            ConfigurationDescriptor,
                                            interfaceindex,
                                            0, -1, -1, -1);

        if (interfaceDescriptor)
        {
            interfaceList->InterfaceDescriptor = interfaceDescriptor;
            interfaceList->Interface = NULL;
            interfaceList++;
            interfaceNumber++;

        }

        interfaceindex++;

    }

    interfaceList->InterfaceDescriptor = NULL;
    interfaceList->Interface = NULL;
    urb = USBD_CreateConfigurationRequestEx(ConfigurationDescriptor, tmp);

    if (urb)
    {
        Interface = &urb->UrbSelectConfiguration.Interface;
        for (i=0; i<Interface->NumberOfPipes; i++)
        {
            // perform pipe initialization here
            // set the transfer size and any pipe flags we use
            // USBD sets the rest of the Interface struct members
            Interface->Pipes[i].MaximumTransferSize = USBD_DEFAULT_MAXIMUM_TRANSFER_SIZE;

        }

        ntStatus = CallUSBD(DeviceObject, urb);
        if (NT_SUCCESS(ntStatus))
        {
            // save a copy of interface information in the device extension.
            deviceExtension->UsbInterface = (PUSBD_INTERFACE_INFORMATION) ExAllocatePool(NonPagedPool, Interface->Length);
            if (deviceExtension->UsbInterface)
            {
                RtlCopyMemory(deviceExtension->UsbInterface, Interface, Interface->Length);

            }

            else
            {
                ntStatus = STATUS_INSUFFICIENT_RESOURCES;
                FreeBT_DbgPrint(1, ("FBTUSB: SelectInterfaces: Memory alloc for UsbInterface failed\n"));

            }

            // Dump the interface to the debugger
            Interface = &urb->UrbSelectConfiguration.Interface;

            FreeBT_DbgPrint(3, ("FBTUSB: ---------\n"));
            FreeBT_DbgPrint(3, ("FBTUSB: NumberOfPipes 0x%x\n", Interface->NumberOfPipes));
            FreeBT_DbgPrint(3, ("FBTUSB: Length 0x%x\n", Interface->Length));
            FreeBT_DbgPrint(3, ("FBTUSB: Alt Setting 0x%x\n", Interface->AlternateSetting));
            FreeBT_DbgPrint(3, ("FBTUSB: Interface Number 0x%x\n", Interface->InterfaceNumber));
            FreeBT_DbgPrint(3, ("FBTUSB: Class, subclass, protocol 0x%x 0x%x 0x%x\n",
                                 Interface->Class,
                                 Interface->SubClass,
                                 Interface->Protocol));

            if (Interface->Class==FREEBT_USB_STDCLASS && Interface->SubClass==FREEBT_USB_STDSUBCLASS &&
                Interface->Protocol==FREEBT_USB_STDPROTOCOL)
            {
                FreeBT_DbgPrint(3, ("FBTUSB: This is a standard USB Bluetooth device\n"));

            }

            else
            {
                FreeBT_DbgPrint(3, ("FBTUSB: WARNING: This device does not report itself as a standard USB Bluetooth device\n"));

            }

            // Initialize the PipeContext
            // Dump the pipe info
            deviceExtension->PipeContext = (PFREEBT_PIPE_CONTEXT) ExAllocatePool(
                                                NonPagedPool,
                                                Interface->NumberOfPipes *
                                                sizeof(FREEBT_PIPE_CONTEXT));

            if (!deviceExtension->PipeContext)
            {
                ntStatus = STATUS_INSUFFICIENT_RESOURCES;
                FreeBT_DbgPrint(1, ("FBTUSB: Memory alloc for UsbInterface failed\n"));

            }

            else
            {
                FreeBT_DbgPrint(3, ("FBTUSB: SelectInterfaces: Allocated PipeContext %p\n", deviceExtension->PipeContext));
                for (i=0; i<Interface->NumberOfPipes; i++)
                {
                    deviceExtension->PipeContext[i].PipeOpen = FALSE;

                    FreeBT_DbgPrint(3, ("FBTUSB: ---------\n"));
                    FreeBT_DbgPrint(3, ("FBTUSB: PipeType 0x%x\n", Interface->Pipes[i].PipeType));
                    FreeBT_DbgPrint(3, ("FBTUSB: EndpointAddress 0x%x\n", Interface->Pipes[i].EndpointAddress));
                    FreeBT_DbgPrint(3, ("FBTUSB: MaxPacketSize 0x%x\n", Interface->Pipes[i].MaximumPacketSize));
                    FreeBT_DbgPrint(3, ("FBTUSB: Interval 0x%x\n", Interface->Pipes[i].Interval));
                    FreeBT_DbgPrint(3, ("FBTUSB: Handle 0x%x\n", Interface->Pipes[i].PipeHandle));
                    FreeBT_DbgPrint(3, ("FBTUSB: MaximumTransferSize 0x%x\n", Interface->Pipes[i].MaximumTransferSize));

                    // Log the pipes
                    // Note the HCI Command endpoint won't appear here, because the Default Control Pipe
                    // is used for this. The Default Control Pipe is always present at EndPointAddress 0x0
                    switch (Interface->Pipes[i].EndpointAddress)
                    {
                        case FREEBT_STDENDPOINT_HCIEVENT:
                            deviceExtension->PipeContext[i].PipeType=HciEventPipe;
                            deviceExtension->EventPipe=Interface->Pipes[i];
                            FreeBT_DbgPrint(3, ("FBTUSB: HCI Event Endpoint\n"));
                            break;

                        case FREEBT_STDENDPOINT_ACLIN:
                            deviceExtension->PipeContext[i].PipeType=AclDataIn;
                            deviceExtension->DataInPipe=Interface->Pipes[i];
                            FreeBT_DbgPrint(3, ("FBTUSB: ACL Data In Endpoint\n"));
                            break;

                        case FREEBT_STDENDPOINT_ACLOUT:
                            deviceExtension->PipeContext[i].PipeType=AclDataOut;
                            deviceExtension->DataOutPipe=Interface->Pipes[i];
                            FreeBT_DbgPrint(3, ("FBTUSB: ACL Data Out Endpoint\n"));
                            break;

                        case FREEBT_STDENDPOINT_AUDIOIN:
                            deviceExtension->PipeContext[i].PipeType=SCODataIn;
                            deviceExtension->AudioInPipe=Interface->Pipes[i];
                            FreeBT_DbgPrint(3, ("FBTUSB: ACL Data Out Endpoint\n"));
                            break;

                        case FREEBT_STDENDPOINT_AUDIOOUT:
                            deviceExtension->PipeContext[i].PipeType=SCODataOut;
                            deviceExtension->AudioOutPipe=Interface->Pipes[i];
                            FreeBT_DbgPrint(3, ("FBTUSB: ACL Data Out Endpoint\n"));
                            break;

                    }

                }

            }

            FreeBT_DbgPrint(3, ("FBTUSB: ---------\n"));

        }

        else
        {
            FreeBT_DbgPrint(1, ("FBTUSB: SelectInterfaces: Failed to select an interface\n"));

        }

    }

    else
    {
        FreeBT_DbgPrint(1, ("FBTUSB: SelectInterfaces: USBD_CreateConfigurationRequestEx failed\n"));
        ntStatus = STATUS_INSUFFICIENT_RESOURCES;

    }

    if (tmp)
    {
        ExFreePool(tmp);

    }

    if (urb)
    {
        ExFreePool(urb);

    }

    return ntStatus;
}


NTSTATUS NTAPI DeconfigureDevice(IN PDEVICE_OBJECT DeviceObject)
{
    PURB     urb;
    ULONG    siz;
    NTSTATUS ntStatus;

    siz = sizeof(struct _URB_SELECT_CONFIGURATION);
    urb = (PURB) ExAllocatePool(NonPagedPool, siz);
    if (urb)
    {
        UsbBuildSelectConfigurationRequest(urb, (USHORT)siz, NULL);
        ntStatus = CallUSBD(DeviceObject, urb);
        if(!NT_SUCCESS(ntStatus))
        {
            FreeBT_DbgPrint(3, ("FBTUSB: DeconfigureDevice: Failed to deconfigure device\n"));

        }

        ExFreePool(urb);

    }

    else
    {
        FreeBT_DbgPrint(1, ("FBTUSB: DeconfigureDevice: Failed to allocate urb\n"));
        ntStatus = STATUS_INSUFFICIENT_RESOURCES;

    }

    return ntStatus;

}

NTSTATUS NTAPI CallUSBD(IN PDEVICE_OBJECT DeviceObject, IN PURB Urb)
{
    PIRP               irp;
    KEVENT             event;
    NTSTATUS           ntStatus;
    IO_STATUS_BLOCK    ioStatus;
    PIO_STACK_LOCATION nextStack;
    PDEVICE_EXTENSION  deviceExtension;

    irp = NULL;
    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;

    KeInitializeEvent(&event, NotificationEvent, FALSE);
    irp = IoBuildDeviceIoControlRequest(IOCTL_INTERNAL_USB_SUBMIT_URB,
                                        deviceExtension->TopOfStackDeviceObject,
                                        NULL,
                                        0,
                                        NULL,
                                        0,
                                        TRUE,
                                        &event,
                                        &ioStatus);

    if (!irp)
    {
        FreeBT_DbgPrint(1, ("FBTUSB: CallUSBD: IoBuildDeviceIoControlRequest failed\n"));
        return STATUS_INSUFFICIENT_RESOURCES;

    }

    nextStack = IoGetNextIrpStackLocation(irp);
    ASSERT(nextStack != NULL);
    nextStack->Parameters.Others.Argument1 = Urb;

    FreeBT_DbgPrint(3, ("FBTUSB: CallUSBD::"));
    FreeBT_IoIncrement(deviceExtension);

    ntStatus = IoCallDriver(deviceExtension->TopOfStackDeviceObject, irp);
    if (ntStatus == STATUS_PENDING)
    {
        KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
        ntStatus = ioStatus.Status;

    }

    FreeBT_DbgPrint(3, ("FBTUSB: CallUSBD::"));
    FreeBT_IoDecrement(deviceExtension);
    return ntStatus;

}

NTSTATUS NTAPI HandleQueryStopDevice(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
    KIRQL             oldIrql;
    NTSTATUS          ntStatus;
    PDEVICE_EXTENSION deviceExtension;

    FreeBT_DbgPrint(3, ("FBTUSB: HandleQueryStopDevice: Entered\n"));

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;

    // If we can stop the device, we need to set the QueueState to
    // HoldRequests so further requests will be queued.
    KeAcquireSpinLock(&deviceExtension->DevStateLock, &oldIrql);

    SET_NEW_PNP_STATE(deviceExtension, PendingStop);
    deviceExtension->QueueState = HoldRequests;

    KeReleaseSpinLock(&deviceExtension->DevStateLock, oldIrql);

    // wait for the existing ones to be finished.
    // first, decrement this operation
    FreeBT_DbgPrint(3, ("FBTUSB: HandleQueryStopDevice::"));
    FreeBT_IoDecrement(deviceExtension);

    KeWaitForSingleObject(&deviceExtension->StopEvent, Executive, KernelMode, FALSE, NULL);

    Irp->IoStatus.Status = STATUS_SUCCESS;
    Irp->IoStatus.Information = 0;

    IoSkipCurrentIrpStackLocation(Irp);

    ntStatus = IoCallDriver(deviceExtension->TopOfStackDeviceObject, Irp);

    FreeBT_DbgPrint(3, ("FBTUSB: HandleQueryStopDevice: Leaving\n"));

    return ntStatus;

}

NTSTATUS NTAPI HandleCancelStopDevice(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
    KIRQL             oldIrql;
    KEVENT            event;
    NTSTATUS          ntStatus;
    PDEVICE_EXTENSION deviceExtension;

    FreeBT_DbgPrint(3, ("FBTUSB: HandleCancelStopDevice: Entered\n"));

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;

    // Send this IRP down and wait for it to come back.
    // Set the QueueState flag to AllowRequests,
    // and process all the previously queued up IRPs.

    // First check to see whether you have received cancel-stop
    // without first receiving a query-stop. This could happen if someone
    // above us fails a query-stop and passes down the subsequent
    // cancel-stop.
    if(PendingStop == deviceExtension->DeviceState)
    {
        KeInitializeEvent(&event, NotificationEvent, FALSE);

        IoCopyCurrentIrpStackLocationToNext(Irp);
        IoSetCompletionRoutine(Irp,
                               (PIO_COMPLETION_ROUTINE)IrpCompletionRoutine,
                               (PVOID)&event,
                               TRUE,
                               TRUE,
                               TRUE);

        ntStatus = IoCallDriver(deviceExtension->TopOfStackDeviceObject, Irp);
        if(ntStatus == STATUS_PENDING)
        {
            KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
            ntStatus = Irp->IoStatus.Status;

        }

        if(NT_SUCCESS(ntStatus))
        {
            KeAcquireSpinLock(&deviceExtension->DevStateLock, &oldIrql);

            RESTORE_PREVIOUS_PNP_STATE(deviceExtension);
            deviceExtension->QueueState = AllowRequests;
            ASSERT(deviceExtension->DeviceState == Working);

            KeReleaseSpinLock(&deviceExtension->DevStateLock, oldIrql);

            ProcessQueuedRequests(deviceExtension);

        }

    }

    else
    {
        // spurious Irp
        ntStatus = STATUS_SUCCESS;

    }

    FreeBT_DbgPrint(3, ("FBTUSB: HandleCancelStopDevice: Leaving\n"));

    return ntStatus;

}

NTSTATUS NTAPI HandleStopDevice(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
    KIRQL             oldIrql;
    NTSTATUS          ntStatus;
    PDEVICE_EXTENSION deviceExtension;

    FreeBT_DbgPrint(3, ("FBTUSB: HandleStopDevice: Entered\n"));

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;
    if(WinXpOrBetter == deviceExtension->WdmVersion)
    {
        if(deviceExtension->SSEnable)
        {
            // Cancel the timer so that the DPCs are no longer fired.
            // Thus, we are making judicious usage of our resources.
            // we do not need DPCs because the device is stopping.
            // The timers are re-initialized while handling the start
            // device irp.
            KeCancelTimer(&deviceExtension->Timer);

            // after the device is stopped, it can be surprise removed.
            // we set this to 0, so that we do not attempt to cancel
            // the timer while handling surprise remove or remove irps.
            // when we get the start device request, this flag will be
            // reinitialized.
            deviceExtension->SSEnable = 0;

            // make sure that if a DPC was fired before we called cancel timer,
            // then the DPC and work-time have run to their completion
            KeWaitForSingleObject(&deviceExtension->NoDpcWorkItemPendingEvent, Executive, KernelMode, FALSE, NULL);

            // make sure that the selective suspend request has been completed.
            KeWaitForSingleObject(&deviceExtension->NoIdleReqPendEvent, Executive, KernelMode, FALSE, NULL);

        }

    }

    // after the stop Irp is sent to the lower driver object,
    // the driver must not send any more Irps down that touch
    // the device until another Start has occurred.
    if (deviceExtension->WaitWakeEnable)
    {
        CancelWaitWake(deviceExtension);

    }

    KeAcquireSpinLock(&deviceExtension->DevStateLock, &oldIrql);

    SET_NEW_PNP_STATE(deviceExtension, Stopped);

    KeReleaseSpinLock(&deviceExtension->DevStateLock, oldIrql);

    // This is the right place to actually give up all the resources used
    // This might include calls to IoDisconnectInterrupt, MmUnmapIoSpace,
    // etc.
    ReleaseMemory(DeviceObject);

    ntStatus = DeconfigureDevice(DeviceObject);

    Irp->IoStatus.Status = ntStatus;
    Irp->IoStatus.Information = 0;

    IoSkipCurrentIrpStackLocation(Irp);
    ntStatus = IoCallDriver(deviceExtension->TopOfStackDeviceObject, Irp);

    FreeBT_DbgPrint(3, ("FBTUSB: HandleStopDevice: Leaving\n"));

    return ntStatus;

}

NTSTATUS NTAPI HandleQueryRemoveDevice(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
    KIRQL             oldIrql;
    NTSTATUS          ntStatus;
    PDEVICE_EXTENSION deviceExtension;

    FreeBT_DbgPrint(3, ("FBTUSB: HandleQueryRemoveDevice: Entered\n"));

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;

    // If we can allow removal of the device, we should set the QueueState
    // to HoldRequests so further requests will be queued. This is required
    // so that we can process queued up requests in cancel-remove just in
    // case somebody else in the stack fails the query-remove.
    ntStatus = CanRemoveDevice(DeviceObject, Irp);<--- ntStatus is assigned

    KeAcquireSpinLock(&deviceExtension->DevStateLock, &oldIrql);

    deviceExtension->QueueState = HoldRequests;
    SET_NEW_PNP_STATE(deviceExtension, PendingRemove);

    KeReleaseSpinLock(&deviceExtension->DevStateLock, oldIrql);

    FreeBT_DbgPrint(3, ("FBTUSB: HandleQueryRemoveDevice::"));
    FreeBT_IoDecrement(deviceExtension);

    // Wait for all the requests to be completed
    KeWaitForSingleObject(&deviceExtension->StopEvent, Executive, KernelMode, FALSE, NULL);

    Irp->IoStatus.Status = STATUS_SUCCESS;
    Irp->IoStatus.Information = 0;

    IoSkipCurrentIrpStackLocation(Irp);
    ntStatus = IoCallDriver(deviceExtension->TopOfStackDeviceObject, Irp);<--- ntStatus is overwritten

    FreeBT_DbgPrint(3, ("FBTUSB: HandleQueryRemoveDevice: Leaving\n"));

    return ntStatus;

}

NTSTATUS NTAPI HandleCancelRemoveDevice(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
    KIRQL             oldIrql;
    KEVENT            event;
    NTSTATUS          ntStatus;
    PDEVICE_EXTENSION deviceExtension;

    FreeBT_DbgPrint(3, ("FBTUSB: HandleCancelRemoveDevice: Entered\n"));

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;

    // We need to reset the QueueState flag to ProcessRequest,
    // since the device resume its normal activities.

    // First check to see whether you have received cancel-remove
    // without first receiving a query-remove. This could happen if
    // someone above us fails a query-remove and passes down the
    // subsequent cancel-remove.
    if(PendingRemove == deviceExtension->DeviceState)
    {

        KeInitializeEvent(&event, NotificationEvent, FALSE);

        IoCopyCurrentIrpStackLocationToNext(Irp);
        IoSetCompletionRoutine(Irp,
                               (PIO_COMPLETION_ROUTINE)IrpCompletionRoutine,
                               (PVOID)&event,
                               TRUE,
                               TRUE,
                               TRUE);

        ntStatus = IoCallDriver(deviceExtension->TopOfStackDeviceObject, Irp);
        if(ntStatus == STATUS_PENDING)
        {
            KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
            ntStatus = Irp->IoStatus.Status;

        }

        if (NT_SUCCESS(ntStatus))
        {
            KeAcquireSpinLock(&deviceExtension->DevStateLock, &oldIrql);

            deviceExtension->QueueState = AllowRequests;
            RESTORE_PREVIOUS_PNP_STATE(deviceExtension);

            KeReleaseSpinLock(&deviceExtension->DevStateLock, oldIrql);

            // process the queued requests that arrive between
            // QUERY_REMOVE and CANCEL_REMOVE
            ProcessQueuedRequests(deviceExtension);

        }

    }

    else
    {
        // spurious cancel-remove
        ntStatus = STATUS_SUCCESS;

    }

    FreeBT_DbgPrint(3, ("FBTUSB: HandleCancelRemoveDevice: Leaving\n"));

    return ntStatus;

}

NTSTATUS NTAPI HandleSurpriseRemoval(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
    KIRQL             oldIrql;
    NTSTATUS          ntStatus;
    PDEVICE_EXTENSION deviceExtension;

    FreeBT_DbgPrint(3, ("FBTUSB: HandleSurpriseRemoval: Entered\n"));

    // initialize variables
    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;

    // 1. fail pending requests
    // 2. return device and memory resources
    // 3. disable interfaces
    if(deviceExtension->WaitWakeEnable)
    {
        CancelWaitWake(deviceExtension);

    }


    if (WinXpOrBetter == deviceExtension->WdmVersion)
    {
        if (deviceExtension->SSEnable)
        {
            // Cancel the timer so that the DPCs are no longer fired.
            // we do not need DPCs because the device has been surprise
            // removed
            KeCancelTimer(&deviceExtension->Timer);

            deviceExtension->SSEnable = 0;

            // make sure that if a DPC was fired before we called cancel timer,
            // then the DPC and work-time have run to their completion
            KeWaitForSingleObject(&deviceExtension->NoDpcWorkItemPendingEvent, Executive, KernelMode, FALSE, NULL);

            // make sure that the selective suspend request has been completed.
            KeWaitForSingleObject(&deviceExtension->NoIdleReqPendEvent, Executive, KernelMode, FALSE, NULL);

        }

    }

    KeAcquireSpinLock(&deviceExtension->DevStateLock, &oldIrql);
    deviceExtension->QueueState = FailRequests;
    SET_NEW_PNP_STATE(deviceExtension, SurpriseRemoved);
    KeReleaseSpinLock(&deviceExtension->DevStateLock, oldIrql);

    ProcessQueuedRequests(deviceExtension);

    ntStatus = IoSetDeviceInterfaceState(&deviceExtension->InterfaceName, FALSE);
    if(!NT_SUCCESS(ntStatus))
    {
        FreeBT_DbgPrint(1, ("FBTUSB: HandleSurpriseRemoval: IoSetDeviceInterfaceState::disable:failed\n"));

    }

    FreeBT_AbortPipes(DeviceObject);

    Irp->IoStatus.Status = STATUS_SUCCESS;
    Irp->IoStatus.Information = 0;

    IoSkipCurrentIrpStackLocation(Irp);
    ntStatus = IoCallDriver(deviceExtension->TopOfStackDeviceObject, Irp);

    FreeBT_DbgPrint(3, ("FBTUSB: HandleSurpriseRemoval: Leaving\n"));

    return ntStatus;

}

NTSTATUS NTAPI HandleRemoveDevice(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
    KIRQL             oldIrql;
    //KEVENT            event;
    ULONG             requestCount;
    NTSTATUS          ntStatus;
    PDEVICE_EXTENSION deviceExtension;

    FreeBT_DbgPrint(3, ("FBTUSB: HandleRemoveDevice: Entered\n"));

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;

    // The Plug & Play system has dictated the removal of this device.  We
    // have no choice but to detach and delete the device object.
    // (If we wanted to express an interest in preventing this removal,
    // we should have failed the query remove IRP).
    if(SurpriseRemoved != deviceExtension->DeviceState)
    {

        // we are here after QUERY_REMOVE
        KeAcquireSpinLock(&deviceExtension->DevStateLock, &oldIrql);
        deviceExtension->QueueState = FailRequests;
        KeReleaseSpinLock(&deviceExtension->DevStateLock, oldIrql);

        if(deviceExtension->WaitWakeEnable)
        {
            CancelWaitWake(deviceExtension);

        }

        if(WinXpOrBetter == deviceExtension->WdmVersion)
        {
            if (deviceExtension->SSEnable)
            {
                // Cancel the timer so that the DPCs are no longer fired.
                // we do not need DPCs because the device has been removed
                KeCancelTimer(&deviceExtension->Timer);

                deviceExtension->SSEnable = 0;

                // make sure that if a DPC was fired before we called cancel timer,
                // then the DPC and work-time have run to their completion
                KeWaitForSingleObject(&deviceExtension->NoDpcWorkItemPendingEvent, Executive, KernelMode, FALSE, NULL);

                // make sure that the selective suspend request has been completed.
                KeWaitForSingleObject(&deviceExtension->NoIdleReqPendEvent, Executive, KernelMode, FALSE, NULL);

            }

        }

        ProcessQueuedRequests(deviceExtension);

        ntStatus = IoSetDeviceInterfaceState(&deviceExtension->InterfaceName, FALSE);
        if(!NT_SUCCESS(ntStatus))
        {
            FreeBT_DbgPrint(1, ("FBTUSB: HandleRemoveDevice: IoSetDeviceInterfaceState::disable:failed\n"));

        }

        FreeBT_AbortPipes(DeviceObject);

    }

    KeAcquireSpinLock(&deviceExtension->DevStateLock, &oldIrql);
    SET_NEW_PNP_STATE(deviceExtension, Removed);
    KeReleaseSpinLock(&deviceExtension->DevStateLock, oldIrql);
#ifdef ENABLE_WMI
    FreeBT_WmiDeRegistration(deviceExtension);
#endif

    // Need 2 decrements
    FreeBT_DbgPrint(3, ("FBTUSB: HandleRemoveDevice::"));
    requestCount = FreeBT_IoDecrement(deviceExtension);

    ASSERT(requestCount > 0);

    FreeBT_DbgPrint(3, ("FBTUSB: HandleRemoveDevice::"));
    requestCount = FreeBT_IoDecrement(deviceExtension);

    KeWaitForSingleObject(&deviceExtension->RemoveEvent,
                          Executive,
                          KernelMode,
                          FALSE,
                          NULL);

    ReleaseMemory(DeviceObject);

    // We need to send the remove down the stack before we detach,
    // but we don't need to wait for the completion of this operation
    // (and to register a completion routine).
    Irp->IoStatus.Status = STATUS_SUCCESS;
    Irp->IoStatus.Information = 0;

    IoSkipCurrentIrpStackLocation(Irp);
    ntStatus = IoCallDriver(deviceExtension->TopOfStackDeviceObject, Irp);

    IoDetachDevice(deviceExtension->TopOfStackDeviceObject);
    IoDeleteDevice(DeviceObject);

    FreeBT_DbgPrint(3, ("FBTUSB: HandleRemoveDevice: Leaving\n"));

    return ntStatus;

}

NTSTATUS NTAPI HandleQueryCapabilities(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
    ULONG                i;
    KEVENT               event;
    NTSTATUS             ntStatus;
    PDEVICE_EXTENSION    deviceExtension;
    PDEVICE_CAPABILITIES pdc;
    PIO_STACK_LOCATION   irpStack;

    FreeBT_DbgPrint(3, ("FBTUSB: HandleQueryCapabilities: Entered\n"));

    irpStack = IoGetCurrentIrpStackLocation(Irp);
    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;
    pdc = irpStack->Parameters.DeviceCapabilities.Capabilities;

    if(pdc->Version < 1 || pdc->Size < sizeof(DEVICE_CAPABILITIES))
    {

        FreeBT_DbgPrint(1, ("FBTUSB: HandleQueryCapabilities::request failed\n"));
        ntStatus = STATUS_UNSUCCESSFUL;
        return ntStatus;

    }

    // Add in the SurpriseRemovalOK bit before passing it down.
    pdc->SurpriseRemovalOK = TRUE;
    Irp->IoStatus.Status = STATUS_SUCCESS;

    KeInitializeEvent(&event, NotificationEvent, FALSE);

    IoCopyCurrentIrpStackLocationToNext(Irp);
    IoSetCompletionRoutine(Irp,
                           (PIO_COMPLETION_ROUTINE)IrpCompletionRoutine,
                           (PVOID)&event,
                           TRUE,
                           TRUE,
                           TRUE);
    ntStatus = IoCallDriver(deviceExtension->TopOfStackDeviceObject, Irp);
    if(ntStatus == STATUS_PENDING)
    {
        KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
        ntStatus = Irp->IoStatus.Status;

    }

    // initialize PowerDownLevel to disabled
    deviceExtension->PowerDownLevel = PowerDeviceUnspecified;
    if(NT_SUCCESS(ntStatus))
    {
        deviceExtension->DeviceCapabilities = *pdc;
        for(i = PowerSystemSleeping1; i <= PowerSystemSleeping3; i++)
        {
            if(deviceExtension->DeviceCapabilities.DeviceState[i] < PowerDeviceD3)
            {
                deviceExtension->PowerDownLevel = deviceExtension->DeviceCapabilities.DeviceState[i];

            }

        }

        // since its safe to surprise-remove this device, we shall
        // set the SurpriseRemoveOK flag to supress any dialog to
        // user.
        pdc->SurpriseRemovalOK = 1;

    }

    if(deviceExtension->PowerDownLevel == PowerDeviceUnspecified ||
        deviceExtension->PowerDownLevel <= PowerDeviceD0)
    {
        deviceExtension->PowerDownLevel = PowerDeviceD2;

    }

    FreeBT_DbgPrint(3, ("FBTUSB: HandleQueryCapabilities: Leaving\n"));

    return ntStatus;
}


VOID NTAPI DpcRoutine(IN PKDPC Dpc, IN PVOID DeferredContext, IN PVOID SystemArgument1, IN PVOID SystemArgument2)
/*++

    DPC routine triggered by the timer to check the idle state
    of the device and submit an idle request for the device.

 --*/
{
    NTSTATUS          ntStatus;
    PDEVICE_OBJECT    deviceObject;
    PDEVICE_EXTENSION deviceExtension;
    PIO_WORKITEM      item;

    FreeBT_DbgPrint(3, ("FBTUSB: DpcRoutine: Entered\n"));

    deviceObject = (PDEVICE_OBJECT)DeferredContext;
    deviceExtension = (PDEVICE_EXTENSION)deviceObject->DeviceExtension;

    // Clear this event since a DPC has been fired!
    KeClearEvent(&deviceExtension->NoDpcWorkItemPendingEvent);

    if(CanDeviceSuspend(deviceExtension))
    {
        FreeBT_DbgPrint(3, ("FBTUSB: DpcRoutine: Device is Idle\n"));
        item = IoAllocateWorkItem(deviceObject);

        if (item)
        {
            IoQueueWorkItem(item, IdleRequestWorkerRoutine, DelayedWorkQueue, item);
            ntStatus = STATUS_PENDING;

        }

        else
        {
            FreeBT_DbgPrint(3, ("FBTUSB: DpcRoutine: Cannot alloc memory for work item\n"));
            ntStatus = STATUS_INSUFFICIENT_RESOURCES;
            KeSetEvent(&deviceExtension->NoDpcWorkItemPendingEvent, IO_NO_INCREMENT, FALSE);

        }

    }

    else
    {
        FreeBT_DbgPrint(3, ("FBTUSB: DpcRoutine: Idle event not signaled\n"));
        KeSetEvent(&deviceExtension->NoDpcWorkItemPendingEvent, IO_NO_INCREMENT, FALSE);

    }

    FreeBT_DbgPrint(3, ("FBTUSB: DpcRoutine: Leaving\n"));
}


VOID NTAPI IdleRequestWorkerRoutine(IN PDEVICE_OBJECT DeviceObject, IN PVOID Context)
{
    //PIRP                   irp;
    NTSTATUS               ntStatus;
    PDEVICE_EXTENSION      deviceExtension;
    PIO_WORKITEM           workItem;

    FreeBT_DbgPrint(3, ("FBTUSB: IdleRequestWorkerRoutine: Entered\n"));

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;
    workItem = (PIO_WORKITEM) Context;

    if(CanDeviceSuspend(deviceExtension))
    {
        FreeBT_DbgPrint(3, ("FBTUSB: IdleRequestWorkerRoutine: Device is idle\n"));
        ntStatus = SubmitIdleRequestIrp(deviceExtension);
        if(!NT_SUCCESS(ntStatus))
        {
            FreeBT_DbgPrint(1, ("FBTUSB: IdleRequestWorkerRoutine: SubmitIdleRequestIrp failed\n"));

        }

    }

    else
    {
        FreeBT_DbgPrint(3, ("FBTUSB: IdleRequestWorkerRoutine: Device is not idle\n"));

    }

    IoFreeWorkItem(workItem);

    KeSetEvent(&deviceExtension->NoDpcWorkItemPendingEvent, IO_NO_INCREMENT, FALSE);

    FreeBT_DbgPrint(3, ("FBTUSB: IdleRequestsWorkerRoutine: Leaving\n"));

}


VOID NTAPI ProcessQueuedRequests(IN OUT PDEVICE_EXTENSION DeviceExtension)
/*++

Routine Description:

    Remove and process the entries in the queue. If this routine is called
    when processing IRP_MN_CANCEL_STOP_DEVICE, IRP_MN_CANCEL_REMOVE_DEVICE
    or IRP_MN_START_DEVICE, the requests are passed to the next lower driver.
    If the routine is called when IRP_MN_REMOVE_DEVICE is received, the IRPs
    are complete with STATUS_DELETE_PENDING

Arguments:

    DeviceExtension - pointer to device extension

Return Value:

    None

--*/
{
    KIRQL       oldIrql;
    PIRP        nextIrp,
                cancelledIrp;
    PVOID       cancelRoutine;
    LIST_ENTRY  cancelledIrpList;
    PLIST_ENTRY listEntry;

    FreeBT_DbgPrint(3, ("FBTUSB: ProcessQueuedRequests: Entered\n"));

    cancelRoutine = NULL;
    InitializeListHead(&cancelledIrpList);

    // 1.  dequeue the entries in the queue
    // 2.  reset the cancel routine
    // 3.  process them
    // 3a. if the device is active, send them down
    // 3b. else complete with STATUS_DELETE_PENDING
    while(1)
    {
        KeAcquireSpinLock(&DeviceExtension->QueueLock, &oldIrql);
        if(IsListEmpty(&DeviceExtension->NewRequestsQueue))
        {
            KeReleaseSpinLock(&DeviceExtension->QueueLock, oldIrql);
            break;

        }

        listEntry = RemoveHeadList(&DeviceExtension->NewRequestsQueue);
        nextIrp = CONTAINING_RECORD(listEntry, IRP, Tail.Overlay.ListEntry);

        cancelRoutine = IoSetCancelRoutine(nextIrp, NULL);

        // check if its already cancelled
        if (nextIrp->Cancel)
        {
            if(cancelRoutine)
            {
                // the cancel routine for this IRP hasnt been called yet
                // so queue the IRP in the cancelledIrp list and complete
                // after releasing the lock
                InsertTailList(&cancelledIrpList, listEntry);

            }

            else
            {
                // the cancel routine has run
                // it must be waiting to hold the queue lock
                // so initialize the IRPs listEntry
                InitializeListHead(listEntry);

            }

            KeReleaseSpinLock(&DeviceExtension->QueueLock, oldIrql);

        }

        else
        {
            KeReleaseSpinLock(&DeviceExtension->QueueLock, oldIrql);
            if(FailRequests == DeviceExtension->QueueState)
            {
                nextIrp->IoStatus.Information = 0;
                nextIrp->IoStatus.Status = STATUS_DELETE_PENDING;
                IoCompleteRequest(nextIrp, IO_NO_INCREMENT);

            }

            else
            {
                //PIO_STACK_LOCATION irpStack;

                FreeBT_DbgPrint(3, ("FBTUSB: ProcessQueuedRequests::"));
                FreeBT_IoIncrement(DeviceExtension);

                IoSkipCurrentIrpStackLocation(nextIrp);
                IoCallDriver(DeviceExtension->TopOfStackDeviceObject, nextIrp);

                FreeBT_DbgPrint(3, ("FBTUSB: ProcessQueuedRequests::"));
                FreeBT_IoDecrement(DeviceExtension);

            }

        }

    }

    while(!IsListEmpty(&cancelledIrpList))
    {
        PLIST_ENTRY cancelEntry = RemoveHeadList(&cancelledIrpList);

        cancelledIrp = CONTAINING_RECORD(cancelEntry, IRP, Tail.Overlay.ListEntry);
        cancelledIrp->IoStatus.Status = STATUS_CANCELLED;
        cancelledIrp->IoStatus.Information = 0;

        IoCompleteRequest(cancelledIrp, IO_NO_INCREMENT);

    }

    FreeBT_DbgPrint(3, ("FBTUSB: ProcessQueuedRequests: Leaving\n"));

    return;

}

NTSTATUS NTAPI FreeBT_GetRegistryDword(IN PWCHAR RegPath, IN PWCHAR ValueName, IN OUT PULONG Value)
{
    ULONG                    defaultData;
    WCHAR                    buffer[MAXIMUM_FILENAME_LENGTH];
    NTSTATUS                 ntStatus;
    UNICODE_STRING           regPath;
    RTL_QUERY_REGISTRY_TABLE paramTable[2];

    FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_GetRegistryDword: Entered\n"));

    regPath.Length = 0;
    regPath.MaximumLength = MAXIMUM_FILENAME_LENGTH * sizeof(WCHAR);
    regPath.Buffer = buffer;

    RtlZeroMemory(regPath.Buffer, regPath.MaximumLength);
    RtlMoveMemory(regPath.Buffer, RegPath, wcslen(RegPath) * sizeof(WCHAR));
    RtlZeroMemory(paramTable, sizeof(paramTable));

    paramTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT;
    paramTable[0].Name = ValueName;
    paramTable[0].EntryContext = Value;
    paramTable[0].DefaultType = REG_DWORD;
    paramTable[0].DefaultData = &defaultData;
    paramTable[0].DefaultLength = sizeof(ULONG);

    ntStatus = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE |
                                      RTL_REGISTRY_OPTIONAL,
                                      regPath.Buffer,
                                      paramTable,
                                      NULL,
                                      NULL);

    if (NT_SUCCESS(ntStatus))
    {
        FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_GetRegistryDword: Success, Value = %X\n", *Value));
        return STATUS_SUCCESS;
    }

    else
    {
        FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_GetRegistryDword: Failed\n"));
        *Value = 0;
        return STATUS_UNSUCCESSFUL;

    }
}


NTSTATUS NTAPI FreeBT_DispatchClean(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
    PDEVICE_EXTENSION  deviceExtension;
    KIRQL              oldIrql;
    LIST_ENTRY         cleanupList;
    PLIST_ENTRY        thisEntry,
                       nextEntry,
                       listHead;
    PIRP               pendingIrp;
    PIO_STACK_LOCATION pendingIrpStack,
                       irpStack;
    //NTSTATUS           ntStatus;

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;
    irpStack = IoGetCurrentIrpStackLocation(Irp);
    InitializeListHead(&cleanupList);

    FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_DispatchClean::"));
    FreeBT_IoIncrement(deviceExtension);

    KeAcquireSpinLock(&deviceExtension->QueueLock, &oldIrql);

    listHead = &deviceExtension->NewRequestsQueue;
    for(thisEntry = listHead->Flink, nextEntry = thisEntry->Flink;
       thisEntry != listHead;
       thisEntry = nextEntry, nextEntry = thisEntry->Flink)
    {
        pendingIrp = CONTAINING_RECORD(thisEntry, IRP, Tail.Overlay.ListEntry);
        pendingIrpStack = IoGetCurrentIrpStackLocation(pendingIrp);
        if (irpStack->FileObject == pendingIrpStack->FileObject)
        {
            RemoveEntryList(thisEntry);

            if (NULL == IoSetCancelRoutine(pendingIrp, NULL))
            {
                InitializeListHead(thisEntry);

            }

            else
            {
                InsertTailList(&cleanupList, thisEntry);

            }

        }

    }

    KeReleaseSpinLock(&deviceExtension->QueueLock, oldIrql);

    while(!IsListEmpty(&cleanupList))
    {
        thisEntry = RemoveHeadList(&cleanupList);
        pendingIrp = CONTAINING_RECORD(thisEntry, IRP, Tail.Overlay.ListEntry);

        pendingIrp->IoStatus.Information = 0;
        pendingIrp->IoStatus.Status = STATUS_CANCELLED;
        IoCompleteRequest(pendingIrp, IO_NO_INCREMENT);

    }

    Irp->IoStatus.Information = 0;
    Irp->IoStatus.Status = STATUS_SUCCESS;

    IoCompleteRequest(Irp, IO_NO_INCREMENT);

    FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_DispatchClean::"));
    FreeBT_IoDecrement(deviceExtension);

    return STATUS_SUCCESS;

}


BOOLEAN NTAPI CanDeviceSuspend(IN PDEVICE_EXTENSION DeviceExtension)
{
    FreeBT_DbgPrint(3, ("FBTUSB: CanDeviceSuspend: Entered\n"));

    if ((DeviceExtension->OpenHandleCount == 0) && (DeviceExtension->OutStandingIO == 1))
        return TRUE;

    return FALSE;

}

NTSTATUS NTAPI FreeBT_AbortPipes(IN PDEVICE_OBJECT DeviceObject)
{
    PURB                        urb;
    ULONG                       i;
    NTSTATUS                    ntStatus;
    PDEVICE_EXTENSION           deviceExtension;
    PFREEBT_PIPE_CONTEXT        pipeContext;
    //PUSBD_PIPE_INFORMATION      pipeInformation;
    PUSBD_INTERFACE_INFORMATION interfaceInfo;

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;
    pipeContext = deviceExtension->PipeContext;
    interfaceInfo = deviceExtension->UsbInterface;

    FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_AbortPipes: Entered\n"));

    if(interfaceInfo == NULL || pipeContext == NULL)
        return STATUS_SUCCESS;

    for(i=0; i<interfaceInfo->NumberOfPipes; i++)
    {
        if(pipeContext[i].PipeOpen)
        {
            FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_AbortPipes: Aborting open pipe %d\n", i));

            urb = (PURB) ExAllocatePool(NonPagedPool, sizeof(struct _URB_PIPE_REQUEST));
            if (urb)
            {
                urb->UrbHeader.Length = sizeof(struct _URB_PIPE_REQUEST);
                urb->UrbHeader.Function = URB_FUNCTION_ABORT_PIPE;
                urb->UrbPipeRequest.PipeHandle = interfaceInfo->Pipes[i].PipeHandle;

                ntStatus = CallUSBD(DeviceObject, urb);

                ExFreePool(urb);

            }

            else
            {
                FreeBT_DbgPrint(1, ("FBTUSB: FreeBT_AbortPipes: Failed to alloc memory for urb\n"));
                ntStatus = STATUS_INSUFFICIENT_RESOURCES;
                return ntStatus;

            }

            if(NT_SUCCESS(ntStatus))
                pipeContext[i].PipeOpen = FALSE;


        }

    }

    FreeBT_DbgPrint(3, ("FBTUSB: FreeBT_AbortPipes: Leaving\n"));

    return STATUS_SUCCESS;

}

// Completion routine for PNP IRPs
NTSTATUS NTAPI IrpCompletionRoutine(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp, IN PVOID Context)
{
    PKEVENT event = (PKEVENT) Context;
    KeSetEvent(event, 0, FALSE);

    return STATUS_MORE_PROCESSING_REQUIRED;

}


LONG NTAPI FreeBT_IoIncrement(IN OUT PDEVICE_EXTENSION DeviceExtension)
{
    LONG  result = 0;
    KIRQL oldIrql;

    KeAcquireSpinLock(&DeviceExtension->IOCountLock, &oldIrql);
    result = InterlockedIncrement((PLONG)(&DeviceExtension->OutStandingIO));

    // When OutStandingIO bumps from 1 to 2, clear the StopEvent
    if (result == 2)
        KeClearEvent(&DeviceExtension->StopEvent);

    KeReleaseSpinLock(&DeviceExtension->IOCountLock, oldIrql);

    FreeBT_DbgPrint(3, ("FreeBT_IoIncrement::%d\n", result));

    return result;

}

LONG NTAPI FreeBT_IoDecrement(IN OUT PDEVICE_EXTENSION DeviceExtension)
{
    LONG  result = 0;
    KIRQL oldIrql;

    KeAcquireSpinLock(&DeviceExtension->IOCountLock, &oldIrql);

    result = InterlockedDecrement((PLONG)(&DeviceExtension->OutStandingIO));

    if (result == 1)
        KeSetEvent(&DeviceExtension->StopEvent, IO_NO_INCREMENT, FALSE);

    if(result == 0)
    {
        ASSERT(Removed == DeviceExtension->DeviceState);
        KeSetEvent(&DeviceExtension->RemoveEvent, IO_NO_INCREMENT, FALSE);

    }

    KeReleaseSpinLock(&DeviceExtension->IOCountLock, oldIrql);

    FreeBT_DbgPrint(3, ("FreeBT_IoDecrement::%d\n", result));

    return result;

}

NTSTATUS NTAPI CanStopDevice(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
{
   // For the time being, just allow it to be stopped
   UNREFERENCED_PARAMETER(DeviceObject);
   UNREFERENCED_PARAMETER(Irp);

   return STATUS_SUCCESS;

}

NTSTATUS NTAPI CanRemoveDevice(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)

{
   // For the time being, just allow it to be removed
   UNREFERENCED_PARAMETER(DeviceObject);
   UNREFERENCED_PARAMETER(Irp);

   return STATUS_SUCCESS;

}

NTSTATUS NTAPI ReleaseMemory(IN PDEVICE_OBJECT DeviceObject)
{
    // Disconnect from the interrupt and unmap any I/O ports
    PDEVICE_EXTENSION   deviceExtension;
    UNICODE_STRING      uniDeviceName;
    NTSTATUS            ntStatus;

    deviceExtension = (PDEVICE_EXTENSION) DeviceObject->DeviceExtension;
    if (deviceExtension->UsbConfigurationDescriptor)
    {
        FreeBT_DbgPrint(3, ("FBTUSB: ReleaseMemory: Freeing UsbConfigurationDescriptor\n"));
        ExFreePool(deviceExtension->UsbConfigurationDescriptor);
        deviceExtension->UsbConfigurationDescriptor = NULL;

    }

    if(deviceExtension->UsbInterface)
    {
        FreeBT_DbgPrint(3, ("FBTUSB: ReleaseMemory: Freeing UsbInterface\n"));
        ExFreePool(deviceExtension->UsbInterface);
        deviceExtension->UsbInterface = NULL;

    }

    if(deviceExtension->PipeContext)
    {
        RtlInitUnicodeString(&uniDeviceName, deviceExtension->wszDosDeviceName);
        ntStatus = IoDeleteSymbolicLink(&uniDeviceName);
        if (!NT_SUCCESS(ntStatus))
            FreeBT_DbgPrint(3, ("FBTUSB: Failed to delete symbolic link %ws\n", deviceExtension->wszDosDeviceName));

        FreeBT_DbgPrint(3, ("FBTUSB: ReleaseMemory: Freeing PipeContext %p\n", deviceExtension->PipeContext));
        ExFreePool(deviceExtension->PipeContext);
        deviceExtension->PipeContext = NULL;

    }

    return STATUS_SUCCESS;

}

PCHAR NTAPI PnPMinorFunctionString (UCHAR MinorFunction)
{
    switch (MinorFunction)
    {
        case IRP_MN_START_DEVICE:
            return "IRP_MN_START_DEVICE\n";

        case IRP_MN_QUERY_REMOVE_DEVICE:
            return "IRP_MN_QUERY_REMOVE_DEVICE\n";

        case IRP_MN_REMOVE_DEVICE:
            return "IRP_MN_REMOVE_DEVICE\n";

        case IRP_MN_CANCEL_REMOVE_DEVICE:
            return "IRP_MN_CANCEL_REMOVE_DEVICE\n";

        case IRP_MN_STOP_DEVICE:
            return "IRP_MN_STOP_DEVICE\n";

        case IRP_MN_QUERY_STOP_DEVICE:
            return "IRP_MN_QUERY_STOP_DEVICE\n";

        case IRP_MN_CANCEL_STOP_DEVICE:
            return "IRP_MN_CANCEL_STOP_DEVICE\n";

        case IRP_MN_QUERY_DEVICE_RELATIONS:
            return "IRP_MN_QUERY_DEVICE_RELATIONS\n";

        case IRP_MN_QUERY_INTERFACE:
            return "IRP_MN_QUERY_INTERFACE\n";

        case IRP_MN_QUERY_CAPABILITIES:
            return "IRP_MN_QUERY_CAPABILITIES\n";

        case IRP_MN_QUERY_RESOURCES:
            return "IRP_MN_QUERY_RESOURCES\n";

        case IRP_MN_QUERY_RESOURCE_REQUIREMENTS:
            return "IRP_MN_QUERY_RESOURCE_REQUIREMENTS\n";

        case IRP_MN_QUERY_DEVICE_TEXT:
            return "IRP_MN_QUERY_DEVICE_TEXT\n";

        case IRP_MN_FILTER_RESOURCE_REQUIREMENTS:
            return "IRP_MN_FILTER_RESOURCE_REQUIREMENTS\n";

        case IRP_MN_READ_CONFIG:
            return "IRP_MN_READ_CONFIG\n";

        case IRP_MN_WRITE_CONFIG:
            return "IRP_MN_WRITE_CONFIG\n";

        case IRP_MN_EJECT:
            return "IRP_MN_EJECT\n";

        case IRP_MN_SET_LOCK:
            return "IRP_MN_SET_LOCK\n";

        case IRP_MN_QUERY_ID:
            return "IRP_MN_QUERY_ID\n";

        case IRP_MN_QUERY_PNP_DEVICE_STATE:
            return "IRP_MN_QUERY_PNP_DEVICE_STATE\n";

        case IRP_MN_QUERY_BUS_INFORMATION:
            return "IRP_MN_QUERY_BUS_INFORMATION\n";

        case IRP_MN_DEVICE_USAGE_NOTIFICATION:
            return "IRP_MN_DEVICE_USAGE_NOTIFICATION\n";

        case IRP_MN_SURPRISE_REMOVAL:
            return "IRP_MN_SURPRISE_REMOVAL\n";

        default:
            return "IRP_MN_?????\n";

    }

}