summaryrefslogtreecommitdiff
path: root/serial/serenum/pnp.c
blob: 93004c5cdc9e553ba55393021a98f397aef5f986 (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
/*++
Copyright (c) 1998-2000  Microsoft Corporation

Module Name:

    PNP.C

Abstract:

    This module contains contains the plugplay calls
    PNP / WDM BUS driver.


Environment:

    kernel mode only

Notes:


--*/

#include "pch.h"

#ifdef ALLOC_PRAGMA
#pragma alloc_text (PAGE, Serenum_AddDevice)
#pragma alloc_text (PAGE, Serenum_PnP)
#pragma alloc_text (PAGE, Serenum_FDO_PnP)
#pragma alloc_text (PAGE, Serenum_PDO_PnP)
#pragma alloc_text (PAGE, Serenum_PnPRemove)
#pragma alloc_text (PAGE, SerenumStartDeviceWorker)
//#pragma alloc_text (PAGE, Serenum_Remove)
#endif

// disable warnings

#if _MSC_VER >= 1200
#pragma warning(push)
#endif

#pragma warning(disable:4127) // conditional expression is constant

NTSTATUS
Serenum_AddDevice(IN PDRIVER_OBJECT DriverObject,
                  IN PDEVICE_OBJECT BusPhysicalDeviceObject)
/*++
Routine Description.
    A bus has been found.  Attach our FDO to it.
    Allocate any required resources.  Set things up.  And be prepared for the
    first ``start device.''

Arguments:
    BusPhysicalDeviceObject - Device object representing the bus.  That to which
        we attach a new FDO.

    DriverObject - This very self referenced driver.

--*/
{
   NTSTATUS status;
   PDEVICE_OBJECT deviceObject;
   PFDO_DEVICE_DATA pDeviceData;
   HANDLE keyHandle;
   ULONG actualLength;
   PCOMMON_DEVICE_DATA commonData;

   PAGED_CODE();

   Serenum_KdPrint_Def(SER_DBG_PNP_TRACE, ("Add Device: 0x%p\n",
                                           BusPhysicalDeviceObject));
   //
   // Create our FDO
   //

   status = IoCreateDevice(DriverObject, sizeof(FDO_DEVICE_DATA), NULL,
                           FILE_DEVICE_BUS_EXTENDER, 0, TRUE, &deviceObject);

   if (NT_SUCCESS(status)) {
      pDeviceData = (PFDO_DEVICE_DATA)deviceObject->DeviceExtension;
      RtlFillMemory (pDeviceData, sizeof (FDO_DEVICE_DATA), 0);

      pDeviceData->IsFDO = TRUE;
      pDeviceData->DebugLevel = SER_DEFAULT_DEBUG_OUTPUT_LEVEL;
      pDeviceData->Self = deviceObject;
      pDeviceData->AttachedPDO = NULL;
      pDeviceData->NumPDOs = 0;
      pDeviceData->DeviceState = PowerDeviceD0;
      pDeviceData->SystemState = PowerSystemWorking;
      pDeviceData->PDOForcedRemove = FALSE;

      pDeviceData->SystemWake=PowerSystemUnspecified;
      pDeviceData->DeviceWake=PowerDeviceUnspecified;

      pDeviceData->Removed = FALSE;
      commonData=(PCOMMON_DEVICE_DATA)deviceObject->DeviceExtension;
      IoInitializeRemoveLock(&commonData->RemoveLock, SERENUM_POOL_TAG, 0, 0);
	  

      //
      // Set the PDO for use with PlugPlay functions
      //

      pDeviceData->UnderlyingPDO = BusPhysicalDeviceObject;


      //
      // Attach our filter driver to the device stack.
      // the return value of IoAttachDeviceToDeviceStack is the top of the
      // attachment chain.  This is where all the IRPs should be routed.
      //
      // Our filter will send IRPs to the top of the stack and use the PDO
      // for all PlugPlay functions.
      //

      pDeviceData->TopOfStack
         = IoAttachDeviceToDeviceStack(deviceObject, BusPhysicalDeviceObject);
      
      if (!pDeviceData->TopOfStack) {
         Serenum_KdPrint(pDeviceData, SER_DBG_PNP_ERROR,
                         ("AddDevice: IoAttach failed (%x)", status));
         IoDeleteDevice(deviceObject);
         return STATUS_UNSUCCESSFUL;
      }

      //
      // Set the type of IO we do
      //

      if (pDeviceData->TopOfStack->Flags & DO_BUFFERED_IO) {
         deviceObject->Flags |= DO_BUFFERED_IO;
      } else if (pDeviceData->TopOfStack->Flags & DO_DIRECT_IO) {
         deviceObject->Flags |= DO_DIRECT_IO;
      }

           
      KeInitializeSemaphore(&pDeviceData->CreateSemaphore, 1, 1);
      KeInitializeSpinLock(&pDeviceData->EnumerationLock);



      //
      // Tell the PlugPlay system that this device will need an interface
      // device class shingle.
      //
      // It may be that the driver cannot hang the shingle until it starts
      // the device itself, so that it can query some of its properties.
      // (Aka the shingles guid (or ref string) is based on the properties
      // of the device.)
      //

      status = IoRegisterDeviceInterface(BusPhysicalDeviceObject,
                                         (LPGUID)&GUID_SERENUM_BUS_ENUMERATOR,
                                         NULL,
#pragma warning(suppress: 6014)
                                         &pDeviceData->DevClassAssocName);
      // pDeviceData->DevClassAssocName is freed when processing IRP_MN_REMOVE_DEVICE or in the error code paths of this routine
      if (!NT_SUCCESS(status)) {
         Serenum_KdPrint(pDeviceData, SER_DBG_PNP_ERROR,
                         ("AddDevice: IoRegisterDCA failed (%x)", status));
		 
         IoDetachDevice(pDeviceData->TopOfStack);
         IoDeleteDevice(deviceObject);
         return status;
      }

      //
      // If for any reason you need to save values in a safe location that
      // clients of this DeviceClassAssociate might be interested in reading
      // here is the time to do so, with the function
      // IoOpenDeviceClassRegistryKey
      // the symbolic link name used is was returned in
      // pDeviceData->DevClassAssocName (the same name which is returned by
      // IoGetDeviceClassAssociations and the SetupAPI equivs.
      //

#if DBG
      {
         PWCHAR deviceName = NULL;
         ULONG nameLength = 0;

         status = IoGetDeviceProperty(BusPhysicalDeviceObject,
                                      DevicePropertyPhysicalDeviceObjectName, 0,
                                      NULL, &nameLength);

         if ((nameLength != 0) && (status == STATUS_BUFFER_TOO_SMALL)) {
            deviceName = ExAllocatePoolZero(NonPagedPoolNx, nameLength,SERENUM_POOL_TAG);

            if (NULL == deviceName) {
               goto someDebugStuffExit;
            }

            IoGetDeviceProperty(BusPhysicalDeviceObject,
                                DevicePropertyPhysicalDeviceObjectName,
                                nameLength, deviceName, &nameLength);

            Serenum_KdPrint(pDeviceData, SER_DBG_PNP_TRACE,
                            ("AddDevice: %p to %p->%p (%ws) \n", deviceObject,
                             pDeviceData->TopOfStack, BusPhysicalDeviceObject,
                             deviceName));
         }

         someDebugStuffExit:;
         if (deviceName != NULL) {
            ExFreePoolWithTag(deviceName,SERENUM_POOL_TAG);
         }
      }
#endif // DBG

      //
      // Turn on the shingle and point it to the given device object.
      //
      status = IoSetDeviceInterfaceState(&pDeviceData->DevClassAssocName,
                                         TRUE);
	  
      if (!NT_SUCCESS(status)) {
         Serenum_KdPrint(pDeviceData, SER_DBG_PNP_ERROR,
                         ("AddDevice: IoSetDeviceClass failed (%x)", status));
		 
         RtlFreeUnicodeString(&pDeviceData->DevClassAssocName);
         return status;
      }

      //
      // Open the regW2stry and read in our settings
      //

      status = IoOpenDeviceRegistryKey(pDeviceData->UnderlyingPDO,
                                       PLUGPLAY_REGKEY_DEVICE,
                                       STANDARD_RIGHTS_READ, &keyHandle);

      if (status == STATUS_SUCCESS) {
         status
            = Serenum_GetRegistryKeyValue(keyHandle, L"SkipEnumerations",
                                          sizeof(L"SkipEnumerations"),
                                          &pDeviceData->SkipEnumerations,
                                          sizeof(pDeviceData->SkipEnumerations),
                                          &actualLength);

         if ((status != STATUS_SUCCESS)
             || (actualLength != sizeof(pDeviceData->SkipEnumerations))) {
            pDeviceData->SkipEnumerations = 0;
            status = STATUS_SUCCESS;

         }

         ZwClose(keyHandle);
      }
   }

   if (NT_SUCCESS(status)) {
      deviceObject->Flags |= DO_POWER_PAGABLE;
      deviceObject->Flags &= ~DO_DEVICE_INITIALIZING;

   }
   
   return status;
}


NTSTATUS
Serenum_PnP(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp)
/*++
Routine Description:
    Answer the plethora of Irp Major PnP IRPS.
--*/
{
    PIO_STACK_LOCATION      irpStack;
    NTSTATUS                status;
    PCOMMON_DEVICE_DATA     commonData;

    PAGED_CODE();

    irpStack = IoGetCurrentIrpStackLocation(Irp);

    ASSERT(irpStack->MajorFunction == IRP_MJ_PNP);

    commonData = (PCOMMON_DEVICE_DATA)DeviceObject->DeviceExtension;
    status=IoAcquireRemoveLock(&commonData->RemoveLock,Irp);
    if(!NT_SUCCESS(status)){
        Irp->IoStatus.Information=0;
        Irp->IoStatus.Status=status;
        IoCompleteRequest(Irp,IO_NO_INCREMENT);
        Serenum_KdPrint(commonData, SER_DBG_PNP_TRACE,
                       ("PNP: removed DO: %p got IRP: %p\n", DeviceObject,
                         Irp));
        return status;
    }

    

    //
    // Call either the FDO or PDO Pnp code
    //

    if (commonData->IsFDO) {
        Serenum_KdPrint(commonData, SER_DBG_PNP_TRACE,
                        ("PNP: Functional DO: %p IRP: %p MJ: %X MIN: %X\n",
                         DeviceObject, Irp, irpStack->MajorFunction,
                         irpStack->MinorFunction));

        status = Serenum_FDO_PnP(DeviceObject, Irp, irpStack,
                                 (PFDO_DEVICE_DATA)commonData);
        goto PnPDone;

    }

    //
    // PDO
    //

    Serenum_KdPrint(commonData, SER_DBG_PNP_TRACE,
                    ("PNP: Physical DO: %p IRP: %p MJ: %X MIN: %X\n",
                     DeviceObject, Irp, irpStack->MajorFunction,
                         irpStack->MinorFunction));

    status = Serenum_PDO_PnP(DeviceObject, Irp, irpStack,
                             (PPDO_DEVICE_DATA)commonData);

PnPDone:;
    return status;
}


NTSTATUS
SerenumCheckEnumerations(IN PFDO_DEVICE_DATA PFdoData)
{

   KIRQL oldIrql;
   NTSTATUS status;
   PIRP pIrp;
   BOOLEAN sameDevice = TRUE;

   Serenum_KdPrint(PFdoData, SER_DBG_PNP_TRACE, ("Checking enumerations"));

   //
   // If appropriate, check for new devices or if old devices still there.
   //

   if (PFdoData->SkipEnumerations == 0) {

      KeAcquireSpinLock(&PFdoData->EnumerationLock, &oldIrql);

      if (PFdoData->EnumFlags == SERENUM_ENUMFLAG_CLEAN) {
          Serenum_KdPrint(PFdoData, SER_DBG_PNP_TRACE, ("EnumFlag Clean"));

         //
         // If nothing is going on, kick off an enumeration
         //

         PFdoData->EnumFlags |= SERENUM_ENUMFLAG_PENDING;
         KeReleaseSpinLock(&PFdoData->EnumerationLock, oldIrql);


         status = SerenumStartProtocolThread(PFdoData);
      } else if ((PFdoData->EnumFlags
                  & (SERENUM_ENUMFLAG_REMOVED | SERENUM_ENUMFLAG_PENDING))
                 == SERENUM_ENUMFLAG_REMOVED) {
          Serenum_KdPrint(PFdoData, SER_DBG_PNP_TRACE, ("EnumFlag Removed"));
          //
          // Clear the flag and do it synchronously to make sure we
          // get the exact current state
          //

          PFdoData->EnumFlags &= ~SERENUM_ENUMFLAG_REMOVED;

          KeReleaseSpinLock(&PFdoData->EnumerationLock, oldIrql);

          pIrp = IoAllocateIrp(PFdoData->TopOfStack->StackSize + 1, FALSE);

          if (pIrp == NULL) {
              status = STATUS_INSUFFICIENT_RESOURCES;
              goto SerenumCheckEnumerationsOut;
          }

          IoSetNextIrpStackLocation(pIrp);
          status = Serenum_ReenumerateDevices(pIrp, PFdoData, &sameDevice);

#pragma prefast(suppress:__WARNING_REDUNDANT_POINTER_TEST __WARNING_REDUNDANT_POINTER_TEST_FAR_EVIDENCE, "pIrp cannot be NULL; see IoSetNextIrpStackLocation")
          if (pIrp != NULL) {
              IoFreeIrp(pIrp);
          }

          KeAcquireSpinLock(&PFdoData->EnumerationLock, &oldIrql);

          if (status == STATUS_SUCCESS) {
              PFdoData->AttachedPDO = PFdoData->NewPDO;
              PFdoData->PdoData = PFdoData->NewPdoData;
              PFdoData->NumPDOs = PFdoData->NewNumPDOs;
              PFdoData->PDOForcedRemove = PFdoData->NewPDOForcedRemove;
          }

          KeReleaseSpinLock(&PFdoData->EnumerationLock, oldIrql);

      } else if (PFdoData->EnumFlags & SERENUM_ENUMFLAG_DIRTY) {

          Serenum_KdPrint(PFdoData, SER_DBG_PNP_TRACE, ("EnumFlag Dirty"));

         //
         // If there is a new value, use the new values
         //

         PFdoData->AttachedPDO = PFdoData->NewPDO;
         PFdoData->PdoData = PFdoData->NewPdoData;
         PFdoData->NumPDOs = PFdoData->NewNumPDOs;
         PFdoData->PDOForcedRemove = PFdoData->NewPDOForcedRemove;
         PFdoData->EnumFlags &= ~SERENUM_ENUMFLAG_DIRTY;

         KeReleaseSpinLock(&PFdoData->EnumerationLock, oldIrql);
         status = STATUS_SUCCESS;
      } else {
          Serenum_KdPrint(PFdoData, SER_DBG_PNP_TRACE, ("EnumFlag default"));

         //
         // Use the current values
         //

         KeReleaseSpinLock(&PFdoData->EnumerationLock, oldIrql);
         status = STATUS_SUCCESS;
      }

   } else {
      status = STATUS_SUCCESS;

      if (PFdoData->SkipEnumerations != 0xffffffff) {
         PFdoData->SkipEnumerations--;
      }
   }

SerenumCheckEnumerationsOut:

   return status;
}




NTSTATUS
Serenum_FDO_PnP (
    IN PDEVICE_OBJECT       DeviceObject,
    IN PIRP                 Irp,
    IN PIO_STACK_LOCATION   IrpStack,
    IN PFDO_DEVICE_DATA     DeviceData
    )
/*++
Routine Description:
    Handle requests from the PlugPlay system for the BUS itself

    NB: the various Minor functions of the PlugPlay system will not be
    overlapped and do not have to be reentrant

--*/
{
    NTSTATUS    status;
    KEVENT      event;
    ULONG       length;
    ULONG       i;
    PDEVICE_RELATIONS   relations;

    PCOMMON_DEVICE_DATA commonData=(PCOMMON_DEVICE_DATA)DeviceObject->DeviceExtension;
    PIO_WORKITEM          SerenumStartDeviceWorkItem  = NULL;
	

    PAGED_CODE();

    switch (IrpStack->MinorFunction) {
    case IRP_MN_START_DEVICE:
        //
        // BEFORE you are allowed to ``touch'' the device object to which
        // the FDO is attached (that send an irp from the bus to the Device
        // object to which the bus is attached).   You must first pass down
        // the start IRP.  It might not be powered on, or able to access or
        // something.
        //

        Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE, ("Start Device\n"));

        if (DeviceData->Started){
            Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE,
                ("Device already started\n"));
            status = STATUS_SUCCESS;
            break;
        }

        // if we get here we know the device is stopped
        IoCopyCurrentIrpStackLocationToNext (Irp);
        SerenumStartDeviceWorkItem = IoAllocateWorkItem(DeviceObject);
        if (SerenumStartDeviceWorkItem==NULL){
            status = STATUS_INSUFFICIENT_RESOURCES;
	    break;
        }

        IoMarkIrpPending(Irp);
        IoSetCompletionRoutine (Irp,
                                SerenumStartDeviceCompletion,
                                SerenumStartDeviceWorkItem,
                                TRUE,
                                TRUE,
                                TRUE);

        IoCallDriver (DeviceData->TopOfStack, Irp);
        status = STATUS_PENDING;
        return status;
        break;

    case IRP_MN_QUERY_STOP_DEVICE:
        Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE,
            ("Query Stop Device\n"));

        //
        // Test to see if there are any PDO created as children of this FDO
        // If there are then conclude the device is busy and fail the
        // query stop.
        //
        // CIMEXCIMEX
        // We could do better, by seing if the children PDOs are actually
        // currently open.  If they are not then we could stop, get new
        // resouces, fill in the new resouce values, and then when a new client
        // opens the PDO use the new resources.  But this works for now.
        //

        if (DeviceData->AttachedPDO
            || (DeviceData->EnumFlags & SERENUM_ENUMFLAG_PENDING)) {
            status = STATUS_UNSUCCESSFUL;

        } else {
            status = STATUS_SUCCESS;
        }

        Irp->IoStatus.Status = status;

        if (NT_SUCCESS(status)) {
           IoSkipCurrentIrpStackLocation (Irp);
           status = IoCallDriver (DeviceData->TopOfStack, Irp);
        } else {
          IoCompleteRequest(Irp, IO_NO_INCREMENT);
        }

	      IoReleaseRemoveLock(&commonData->RemoveLock,Irp);
        return status;

    case IRP_MN_CANCEL_STOP_DEVICE:
        //
        // We always succeed a cancel stop
        //

        Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE,
                         ("Cancel Stop Device\n"));

        Irp->IoStatus.Status = STATUS_SUCCESS;
        IoSkipCurrentIrpStackLocation(Irp);
        status = IoCallDriver(DeviceData->TopOfStack, Irp);

        IoReleaseRemoveLock(&commonData->RemoveLock,Irp);
        return status;

    case IRP_MN_STOP_DEVICE:
        Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE, ("Stop Device\n"));

        //
        // Wait for the enum thread to complete if it's running
        //

        SerenumWaitForEnumThreadTerminate(DeviceData);

        //
        // After the start IRP has been sent to the lower driver object, the
        // bus may NOT send any more IRPS down ``touch'' until another START
        // has occured.
        // What ever access is required must be done before the Irp is passed
        // on.
        //
        // Stop device means that the resources given durring Start device
        // are no revoked.  So we need to stop using them
        //

        DeviceData->Started = FALSE;

        //
        // We don't need a completion routine so fire and forget.
        //
        // Set the current stack location to the next stack location and
        // call the next device object.
        //
        Irp->IoStatus.Status = STATUS_SUCCESS;
        IoSkipCurrentIrpStackLocation (Irp);
        status = IoCallDriver (DeviceData->TopOfStack, Irp);

        IoReleaseRemoveLock(&commonData->RemoveLock,Irp);
        return status;

    case IRP_MN_REMOVE_DEVICE:
        Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE, ("Remove Device\n"));

        //
        // The PlugPlay system has detected the removal of this device.  We
        // have no choice but to detach and delete the device object.
        // (If we wanted to express and interest in preventing this removal,
        // we should have filtered the query remove and query stop routines.)
        //
        // Note! we might receive a remove WITHOUT first receiving a stop.
        // ASSERT (!DeviceData->Removed);


        //
        // Synchronize with the enum thread if it is running and wait
        // for it to finish
        //

		
        SerenumWaitForEnumThreadTerminate(DeviceData);

	// block until all outstanding IO has returned
	//
        // Wait for all outstanding requests to complete
        //
        Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE,("Waiting for outstanding requests\n"));
        // We will accept no new requests
        //
        DeviceData->Removed = TRUE; 

        //
        // Complete any outstanding IRPs queued by the driver here.
        //

        //
        // Make the DCA go away.  Some drivers may choose to remove the DCA
        // when they receive a stop or even a query stop.  We just don't care.
        //
        (void)IoSetDeviceInterfaceState (&DeviceData->DevClassAssocName, FALSE);

        //
        // Here if we had any outstanding requests in a personal queue we should
        // complete them all now.
        //
        // Note, the device is guarenteed stopped, so we cannot send it any non-
        // PNP IRPS.
        //

        //
        // Fire and forget
        //
        Irp->IoStatus.Status = STATUS_SUCCESS;
        IoSkipCurrentIrpStackLocation (Irp);
        status = IoCallDriver (DeviceData->TopOfStack, Irp);

        IoReleaseRemoveLockAndWait(&commonData->RemoveLock,Irp);
        //
        // Free the associated resources
        //

        //
        // Detach from the underlying devices.
        //
        Serenum_KdPrint(DeviceData, SER_DBG_PNP_INFO,
                        ("IoDetachDevice: 0x%p\n", DeviceData->TopOfStack));
        IoDetachDevice (DeviceData->TopOfStack);

        //
        // Clean up any resources here
        //

        
        ExFreePoolWithTag (DeviceData->DevClassAssocName.Buffer,SERENUM_POOL_TAG);
        // DeviceData->DevClassAssocName was initialized in AddDevice
#pragma warning(suppress: 6001)
        RtlFreeUnicodeString(&DeviceData->DevClassAssocName);
        Serenum_KdPrint(DeviceData, SER_DBG_PNP_INFO,
                        ("IoDeleteDevice: 0x%p\n", DeviceObject));

        //
        // Remove any PDO's we ejected
        //

        if (DeviceData->AttachedPDO != NULL) {
           ASSERT(DeviceData->NumPDOs == 1);

           Serenum_PnPRemove(DeviceData->AttachedPDO, DeviceData->PdoData);
           DeviceData->PdoData = NULL;
           DeviceData->AttachedPDO = NULL;
           DeviceData->NumPDOs = 0;
        }

        IoDeleteDevice(DeviceObject);

        return status;

    case IRP_MN_QUERY_DEVICE_RELATIONS:
        if (BusRelations != IrpStack->Parameters.QueryDeviceRelations.Type) {
            //
            // We don't support this
            //
            Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE,
                ("Query Device Relations - Non bus\n"));
            goto SER_FDO_PNP_DEFAULT;
        }

        Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE,
            ("Query Bus Relations\n"));

        status = SerenumCheckEnumerations(DeviceData);

	if(!NT_SUCCESS(status))
	{
           Irp->IoStatus.Status = status;
           IoCompleteRequest(Irp, IO_NO_INCREMENT);
           IoReleaseRemoveLock(&commonData->RemoveLock,Irp);
           return status;
	}
        //
        // Tell the plug and play system about all the PDOs.
        //
        // There might also be device relations below and above this FDO,
        // so, be sure to propagate the relations from the upper drivers.
        //
        // No Completion routine is needed so long as the status is preset
        // to success.  (PDOs complete plug and play irps with the current
        // IoStatus.Status and IoStatus.Information as the default.)
        //

        //KeAcquireSpinLock (&DeviceData->Spin, &oldIrq);

        i = (0 == Irp->IoStatus.Information) ? 0 :
            ((PDEVICE_RELATIONS) Irp->IoStatus.Information)->Count;
        // The current number of PDOs in the device relations structure

        length = sizeof(DEVICE_RELATIONS) +
                ((DeviceData->NumPDOs + i) * sizeof (PDEVICE_OBJECT));

        relations = (PDEVICE_RELATIONS) ExAllocatePoolZero(NonPagedPoolNx, length,SERENUM_POOL_TAG);

        if (NULL == relations) {
           Irp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
           IoCompleteRequest(Irp, IO_NO_INCREMENT);
           IoReleaseRemoveLock(&commonData->RemoveLock,Irp);
           return STATUS_INSUFFICIENT_RESOURCES;
        }

        //
        // Copy in the device objects so far
        //
        if (i) {
            RtlCopyMemory (
                  relations->Objects,
                  ((PDEVICE_RELATIONS) Irp->IoStatus.Information)->Objects,
                  i * sizeof (PDEVICE_OBJECT));
        }
        relations->Count = DeviceData->NumPDOs + i;

        //
        // For each PDO on this bus add a pointer to the device relations
        // buffer, being sure to take out a reference to that object.
        // The PlugPlay system will dereference the object when it is done with
        // it and free the device relations buffer.
        //

        if (DeviceData->NumPDOs) {
            relations->Objects[relations->Count-1] = DeviceData->AttachedPDO;
            ObReferenceObject (DeviceData->AttachedPDO);
        }

        //
        // Set up and pass the IRP further down the stack
        //
        Irp->IoStatus.Status = STATUS_SUCCESS;

        if (0 != Irp->IoStatus.Information) {
            ExFreePoolWithTag ((PVOID) Irp->IoStatus.Information,SERENUM_POOL_TAG);
        }
        Irp->IoStatus.Information = (ULONG_PTR)relations;

        IoSkipCurrentIrpStackLocation (Irp);
        status = IoCallDriver (DeviceData->TopOfStack, Irp);

        IoReleaseRemoveLock(&commonData->RemoveLock,Irp);

        return status;

    case IRP_MN_QUERY_REMOVE_DEVICE:
        //
        // If we were to fail this call then we would need to complete the
        // IRP here.  Since we are not, set the status to SUCCESS and
        // call the next driver.
        //

        Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE,
            ("Query Remove Device\n"));

        //
        // Wait for the enum thread to complete if it's running
        //
        SerenumWaitForEnumThreadTerminate(DeviceData);


        Irp->IoStatus.Status = STATUS_SUCCESS;
        IoSkipCurrentIrpStackLocation (Irp);
        status = IoCallDriver (DeviceData->TopOfStack, Irp);
        IoReleaseRemoveLock(&commonData->RemoveLock,Irp);
        return status;


    case IRP_MN_QUERY_CAPABILITIES: {

        PIO_STACK_LOCATION  irpSp;

        //
        // Send this down to the PDO first
        //

        KeInitializeEvent (&event, NotificationEvent, FALSE);
        IoCopyCurrentIrpStackLocationToNext (Irp);

        IoSetCompletionRoutine (Irp,
                                SerenumSyncCompletion,
                                &event,
                                TRUE,
                                TRUE,
                                TRUE);

        status = IoCallDriver (DeviceData->TopOfStack, Irp);

        if (STATUS_PENDING == status) {
            // wait for it...

            status = KeWaitForSingleObject (&event,
                                            Executive,
                                            KernelMode,
                                            FALSE, // Not allertable
                                            NULL); // No timeout structure
#if DBG
            ASSERT (STATUS_SUCCESS == status);
#endif
            if(!NT_SUCCESS(status)){
                Irp->IoStatus.Status=status;
		IoReleaseRemoveLock(&commonData->RemoveLock,Irp);
		IoCompleteRequest (Irp, IO_NO_INCREMENT);
		return status;
            }
            status = Irp->IoStatus.Status;
        }

        if (NT_SUCCESS(status)) {

            irpSp = IoGetCurrentIrpStackLocation(Irp);

            DeviceData->SystemWake
                = irpSp->Parameters.DeviceCapabilities.Capabilities->SystemWake;
            DeviceData->DeviceWake
                = irpSp->Parameters.DeviceCapabilities.Capabilities->DeviceWake;
        }

        break;
    }



SER_FDO_PNP_DEFAULT:
    default:
        //
        // In the default case we merely call the next driver since
        // we don't know what to do.
        //
        Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE, ("Default Case\n"));

        //
        // Fire and Forget
        //
        IoSkipCurrentIrpStackLocation (Irp);

        //
        // Done, do NOT complete the IRP, it will be processed by the lower
        // device object, which will complete the IRP
        //

        status = IoCallDriver (DeviceData->TopOfStack, Irp);
        IoReleaseRemoveLock(&commonData->RemoveLock,Irp);
        return status;
    }

    Irp->IoStatus.Status = status;
    IoCompleteRequest (Irp, IO_NO_INCREMENT);

    IoReleaseRemoveLock(&commonData->RemoveLock,Irp);
    return status;
}

VOID
SerenumMarkPdoRemoved(PFDO_DEVICE_DATA PFdoData)
{
    KIRQL oldIrql;

    KeAcquireSpinLock(&PFdoData->EnumerationLock, &oldIrql);

    PFdoData->EnumFlags |= SERENUM_ENUMFLAG_REMOVED;

    KeReleaseSpinLock(&PFdoData->EnumerationLock, oldIrql);
}


NTSTATUS
Serenum_PDO_PnP (IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp,
                 IN PIO_STACK_LOCATION IrpStack, IN PPDO_DEVICE_DATA DeviceData)
/*++
Routine Description:
    Handle requests from the PlugPlay system for the devices on the BUS

--*/
{
   PDEVICE_CAPABILITIES    deviceCapabilities;
   PWCHAR                  buffer;
   ULONG                   length;
   NTSTATUS                status;
   PWCHAR returnBuffer = NULL;
   PCOMMON_DEVICE_DATA commonData=(PCOMMON_DEVICE_DATA)DeviceObject->DeviceExtension;


   PAGED_CODE();

   status = Irp->IoStatus.Status;

   //
   // NB: since we are a bus enumerator, we have no one to whom we could
   // defer these irps.  Therefore we do not pass them down but merely
   // return them.
   //

   switch (IrpStack->MinorFunction) {
   case IRP_MN_QUERY_CAPABILITIES:

      Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE, ("Query Caps \n"));

      //
      // Get the packet.
      //

      deviceCapabilities=IrpStack->Parameters.DeviceCapabilities.Capabilities;

      //
      // Set the capabilities.
      //

      deviceCapabilities->Version = 1;
      deviceCapabilities->Size = sizeof (DEVICE_CAPABILITIES);

      //
      // We cannot wake the system.
      //

      deviceCapabilities->SystemWake
          = ((PFDO_DEVICE_DATA)DeviceData->ParentFdo->DeviceExtension)
            ->SystemWake;
      deviceCapabilities->DeviceWake
          = ((PFDO_DEVICE_DATA)DeviceData->ParentFdo->DeviceExtension)
            ->DeviceWake;

      //
      // We have no latencies
      //

      deviceCapabilities->D1Latency = 0;
      deviceCapabilities->D2Latency = 0;
      deviceCapabilities->D3Latency = 0;

      deviceCapabilities->UniqueID = FALSE;
      status = STATUS_SUCCESS;
      break;

   case IRP_MN_QUERY_DEVICE_TEXT: {
      if ((IrpStack->Parameters.QueryDeviceText.DeviceTextType
          != DeviceTextDescription) || DeviceData->DevDesc.Buffer == NULL) {
         break;
      }

      returnBuffer = ExAllocatePoolZero(PagedPool, DeviceData->DevDesc.Length,SERENUM_POOL_TAG);

      if (returnBuffer == NULL) {
         status = STATUS_INSUFFICIENT_RESOURCES;
         break;
      }

      status = STATUS_SUCCESS;

      RtlCopyMemory(returnBuffer, DeviceData->DevDesc.Buffer,
                    DeviceData->DevDesc.Length);

      Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE,
                            ("TextID: buf 0x%p\n", returnBuffer));

      Irp->IoStatus.Information = (ULONG_PTR)returnBuffer;
      break;
   }


   case IRP_MN_QUERY_ID:
      //
      // Query the IDs of the device
      //

      Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE,
                      ("QueryID: 0x%x\n", IrpStack->Parameters.QueryId.IdType));

      switch (IrpStack->Parameters.QueryId.IdType) {


      case BusQueryInstanceID:
         //
         // Build an instance ID.  This is what PnP uses to tell if it has
         // seen this thing before or not.  Build it from the first hardware
         // id and the port number.
         //
         // NB since we do not incorperate the port number
         // this method does not produce unique ids;
         //
         // return 0000 for all devices and have the flag set to not unique
         //

         status = STATUS_SUCCESS;

         length = SERENUM_INSTANCE_IDS_LENGTH * sizeof(WCHAR);
         returnBuffer = ExAllocatePoolZero(PagedPool, length,SERENUM_POOL_TAG);

         if (returnBuffer != NULL) {
            RtlCopyMemory(returnBuffer, SERENUM_INSTANCE_IDS, length);
         } else {
            status = STATUS_INSUFFICIENT_RESOURCES;
         }

         Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE,
                      ("InstanceID: buf 0x%p\n", returnBuffer));

         Irp->IoStatus.Information = (ULONG_PTR)returnBuffer;
         break;


      //
      // The other ID's we just copy from the buffers and are done.
      //

      case BusQueryDeviceID:
      case BusQueryHardwareIDs:
      case BusQueryCompatibleIDs:
         {
            PUNICODE_STRING pId = NULL;
            status = STATUS_SUCCESS;

            switch (IrpStack->Parameters.QueryId.IdType) {
            case BusQueryDeviceID:
               pId = &DeviceData->DeviceIDs;
               break;

            case BusQueryHardwareIDs:
               pId = &DeviceData->HardwareIDs;
               break;

            case BusQueryCompatibleIDs:
               pId = &DeviceData->CompIDs;
               break;
            }

            buffer = pId ? pId->Buffer : NULL;

            if (buffer != NULL) {
               length = pId->Length;
               returnBuffer = ExAllocatePoolZero(PagedPool, length + sizeof(WCHAR),SERENUM_POOL_TAG);
               if (returnBuffer != NULL) {
                  RtlZeroMemory(returnBuffer, length + sizeof(WCHAR) );
                  RtlCopyMemory(returnBuffer, buffer, length);

               } else {
                  status = STATUS_INSUFFICIENT_RESOURCES;
               }
            }

            Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE,
                            ("ID: Unicode 0x%p\n", pId));
            Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE,
                            ("ID: buf 0x%p\n", returnBuffer));

            Irp->IoStatus.Information = (ULONG_PTR)returnBuffer;
         }
         break;
      }
      break;

      case IRP_MN_QUERY_BUS_INFORMATION: {
       PPNP_BUS_INFORMATION pBusInfo;

       ASSERTMSG("Serenum appears not to be the sole bus?!?",
                 Irp->IoStatus.Information == (ULONG_PTR)NULL);

       pBusInfo = ExAllocatePoolZero(PagedPool, sizeof(PNP_BUS_INFORMATION),SERENUM_POOL_TAG);

       if (pBusInfo == NULL) {
          status = STATUS_INSUFFICIENT_RESOURCES;
          break;
       }

       pBusInfo->BusTypeGuid = GUID_BUS_TYPE_SERENUM;
       pBusInfo->LegacyBusType = PNPBus;

       //
       // We really can't track our bus number since we can be torn
       // down with our bus
       //

       pBusInfo->BusNumber = 0;

       Irp->IoStatus.Information = (ULONG_PTR)pBusInfo;
       status = STATUS_SUCCESS;
       break;
       }

   case IRP_MN_QUERY_DEVICE_RELATIONS:
      switch (IrpStack->Parameters.QueryDeviceRelations.Type) {
      case TargetDeviceRelation: {
         PDEVICE_RELATIONS pDevRel;

         //
         // No one else should respond to this since we are the PDO
         //

         ASSERT(Irp->IoStatus.Information == 0);

         if (Irp->IoStatus.Information != 0) {
            break;
         }


         pDevRel = ExAllocatePoolZero(PagedPool, sizeof(DEVICE_RELATIONS),SERENUM_POOL_TAG);

         if (pDevRel == NULL) {
            status = STATUS_INSUFFICIENT_RESOURCES;
            break;
         }

         pDevRel->Count = 1;
         pDevRel->Objects[0] = DeviceObject;
         ObReferenceObject(DeviceObject);

         status = STATUS_SUCCESS;
         Irp->IoStatus.Information = (ULONG_PTR)pDevRel;
         break;
      }


      default:
         break;
      }

      break;

   case IRP_MN_START_DEVICE:

      //
      // Save serial number and PnPRev
      //

      if(DeviceData->PnPRev.Length || DeviceData->SerialNo.Length) {
         UNICODE_STRING keyname;
         HANDLE pnpKey;

         status = IoOpenDeviceRegistryKey(DeviceObject, PLUGPLAY_REGKEY_DEVICE,
                                          STANDARD_RIGHTS_WRITE, &pnpKey);
         if (!NT_SUCCESS(status)) {
             Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE,
                             ("DoOpenDeviceRegistryKey failed (%x)\n", status));
             //
             // We failed on opening a handle to registry key. The failure is
             // not so intense that we should fail the IRP_MN_START_DEVICE, 
             // thus we set the status to STATUS_SUCCESS and continue. 
             //
             status = STATUS_SUCCESS;
             break;
         }

         if(DeviceData->PnPRev.Length) {
            RtlInitUnicodeString(&keyname, NULL);
            keyname.MaximumLength = sizeof(L"PnPRev");
            keyname.Buffer = ExAllocatePoolZero(PagedPool, keyname.MaximumLength,SERENUM_POOL_TAG);

            if (keyname.Buffer != NULL) {

               RtlAppendUnicodeToString(&keyname, L"PnPRev");
               status = ZwSetValueKey(pnpKey, &keyname, 0, REG_SZ, DeviceData->PnPRev.Buffer, DeviceData->PnPRev.Length+sizeof(WCHAR));
	       if(NT_SUCCESS(status)){
                   Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE,
                   ("ZwSetValueKey succeeded (%x)\n", status));
               }else{
		   Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE,
                   ("ZwSetValueKey failed (%x)\n", status));
	       }
               ExFreePoolWithTag(keyname.Buffer,SERENUM_POOL_TAG);
            }
         }
         if(DeviceData->SerialNo.Length) {
            RtlInitUnicodeString(&keyname, NULL);
            keyname.MaximumLength = sizeof(L"Serial Number");
            keyname.Buffer = ExAllocatePoolZero(PagedPool, keyname.MaximumLength,SERENUM_POOL_TAG);

            if (keyname.Buffer != NULL) {

               RtlAppendUnicodeToString(&keyname, L"Serial Number");
               status = ZwSetValueKey(pnpKey, &keyname, 0, REG_SZ, DeviceData->SerialNo.Buffer, DeviceData->SerialNo.Length+sizeof(WCHAR));
               if(NT_SUCCESS(status)){
                   Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE,
                   ("ZwSetValueKey succeeded (%x)\n", status));
	       }else{
		   Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE,
                   ("ZwSetValueKey failed (%x)\n", status));
	       }
               ExFreePoolWithTag(keyname.Buffer,SERENUM_POOL_TAG);

            }
         }

         ZwClose(pnpKey);
      }

      DeviceData->Started = TRUE;
      status = STATUS_SUCCESS;
      break;

   case IRP_MN_STOP_DEVICE:
      Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE, ("Stop Device\n"));

      //
      // Here we shut down the device.  The opposite of start.
      //

      DeviceData->Started = FALSE;
      status = STATUS_SUCCESS;
      break;

   case IRP_MN_REMOVE_DEVICE:
      Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE, ("Remove Device\n"));

      //
      // Mark as removed so we enumerate devices correctly -- this will
      // cause the next enumeration request to occur synchronously
      //

      SerenumMarkPdoRemoved((PFDO_DEVICE_DATA)DeviceData->ParentFdo
                            ->DeviceExtension);

      //
      // Attached is only set to FALSE by the enumeration process.
      //

      if (!DeviceData->Attached) {

          status = Serenum_PnPRemove(DeviceObject, DeviceData);
      }
      else {
          //
          // Succeed the remove
          ///
          status = STATUS_SUCCESS;
      }
      break;

   case IRP_MN_QUERY_STOP_DEVICE:
      Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE, ("Query Stop Device\n"));

      //
      // No reason here why we can't stop the device.
      // If there were a reason we should speak now for answering success
      // here may result in a stop device irp.
      //

      status = STATUS_SUCCESS;
      break;

   case IRP_MN_CANCEL_STOP_DEVICE:
      Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE, ("Cancel Stop Device\n"));
      //
      // The stop was canceled.  Whatever state we set, or resources we put
      // on hold in anticipation of the forcoming STOP device IRP should be
      // put back to normal.  Someone, in the long list of concerned parties,
      // has failed the stop device query.
      //

      status = STATUS_SUCCESS;
      break;

   case IRP_MN_QUERY_REMOVE_DEVICE:
      Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE, ("Query Remove Device\n"));
      //
      // Just like Query Stop only now the impending doom is the remove irp
      //
      status = STATUS_SUCCESS;
      break;

   case IRP_MN_CANCEL_REMOVE_DEVICE:
      Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE, ("Cancel Remove Device"
                                                      "\n"));
      //
      // Clean up a remove that did not go through, just like cancel STOP.
      //
      status = STATUS_SUCCESS;
      break;

   case IRP_MN_QUERY_RESOURCE_REQUIREMENTS:
   case IRP_MN_READ_CONFIG:
   case IRP_MN_WRITE_CONFIG: // we have no config space
   case IRP_MN_EJECT:
   case IRP_MN_SET_LOCK:
   case IRP_MN_QUERY_INTERFACE: // We do not have any non IRP based interfaces.
   default:
      Serenum_KdPrint(DeviceData, SER_DBG_PNP_TRACE, ("PNP Not handled 0x%x\n",
                                                      IrpStack->MinorFunction));
      // For PnP requests to the PDO that we do not understand we should
      // return the IRP WITHOUT setting the status or information fields.
      // They may have already been set by a filter (eg acpi).
      break;
   }

   Irp->IoStatus.Status = status;
   IoCompleteRequest (Irp, IO_NO_INCREMENT);
   IoReleaseRemoveLock(&commonData->RemoveLock,Irp);
   return status;
}

NTSTATUS
Serenum_PnPRemove (PDEVICE_OBJECT Device, PPDO_DEVICE_DATA PdoData)
/*++
Routine Description:
    The PlugPlay subsystem has instructed that this PDO should be removed.

    We should therefore
    - Complete any requests queued in the driver
    - If the device is still attached to the system,
      then complete the request and return.
    - Otherwise, cleanup device specific allocations, memory, events...
    - Call IoDeleteDevice
    - Return from the dispatch routine.

    Note that if the device is still connected to the bus (IE in this case
    the control panel has not yet told us that the serial device has
    disappeared) then the PDO must remain around, and must be returned during
    any query Device relaions IRPS.

--*/

{
    PAGED_CODE();
    
   Serenum_KdPrint(PdoData, SER_DBG_PNP_TRACE,
                        ("Serenum_PnPRemove: 0x%p\n", Device));

    //
    // Complete any outstanding requests with STATUS_DELETE_PENDING.
    //
    // Serenum does not queue any irps at this time so we have nothing to do.
    //

    if (PdoData->Attached || PdoData->Removed) {
        return STATUS_SUCCESS;
    }

    PdoData->Removed = TRUE;

    //
    // Free any resources.
    //

    RtlFreeUnicodeString(&PdoData->HardwareIDs);
    RtlFreeUnicodeString(&PdoData->CompIDs);
    RtlFreeUnicodeString(&PdoData->DeviceIDs);

    Serenum_KdPrint(PdoData, SER_DBG_PNP_INFO,
                        ("IoDeleteDevice: 0x%p\n", Device));

    IoDeleteDevice(Device);


    return STATUS_SUCCESS;
}

NTSTATUS
SerenumStartDeviceCompletion(
                PDEVICE_OBJECT  DeviceObject,
                PIRP            Irp,
                PVOID           Context
    )
/*++

Routine Description:

    This routine triggers the event associated with the block semantics of the
    IRP_MN_START_DEVICE
    
Arguments:

    DeviceObject    - Targeted device object
    Irp             - IRP_MN_START_DEVICE irp
    Context         - PIO_WORKITEM workItem

Return Value:

    STATUS_MORE_PROCESSING_REQUIRED
            
--*/
{
    PCOMMON_DEVICE_DATA commonData=(PCOMMON_DEVICE_DATA)DeviceObject->DeviceExtension;
    PIO_WORKITEM workItem = (PIO_WORKITEM)Context;
    NTSTATUS status;

    _Analysis_assume_(workItem != NULL); // Not NULL when passed to IoQueueWorkItem()

    status = Irp->IoStatus.Status;

    if (NT_SUCCESS(status)){
        IoQueueWorkItemEx(workItem,
                          SerenumStartDeviceWorker,
                          DelayedWorkQueue,
                          Irp);
        return STATUS_MORE_PROCESSING_REQUIRED;
    }
    else
    {
        IoFreeWorkItem(workItem);
    }
    IoReleaseRemoveLock( &commonData->RemoveLock,Irp );
    return STATUS_CONTINUE_COMPLETION;
}



VOID SerenumStartDeviceWorker(
    PVOID deviceObject,
    PVOID irp,
    PIO_WORKITEM WorkItem
    )
{
	
    PDEVICE_OBJECT DeviceObject=(PDEVICE_OBJECT)deviceObject;
    PIRP Irp=(PIRP)irp;
    PCOMMON_DEVICE_DATA commonData=(PCOMMON_DEVICE_DATA)DeviceObject->DeviceExtension;
    PFDO_DEVICE_DATA DeviceData=(PFDO_DEVICE_DATA)DeviceObject->DeviceExtension;
    PRTL_QUERY_REGISTRY_TABLE QueryTable = NULL;
    ULONG DebugLevelDefault = SER_DEFAULT_DEBUG_OUTPUT_LEVEL;
    PAGED_CODE();
	
    _Analysis_assume_(Irp != NULL); // Not NULL when passed to IoQueueWorkItem()

    if (NULL == (QueryTable = ExAllocatePoolZero(
                               PagedPool,
                               sizeof(RTL_QUERY_REGISTRY_TABLE)*2,
                               SERENUM_POOL_TAG
                               ))){
        Serenum_KdPrint (DeviceData, SER_DBG_PNP_ERROR,
        ("Failed to allocate memory to query registy\n"));
        DeviceData->DebugLevel = DebugLevelDefault;
        // This Irp is passed as the context parameter 
        // This is the same Irp which is sent by the kernel to the completion routine
	Irp->IoStatus.Status=STATUS_INSUFFICIENT_RESOURCES;
        IoCompleteRequest(Irp, IO_NO_INCREMENT);
        IoFreeWorkItem(WorkItem);
        IoReleaseRemoveLock( &commonData->RemoveLock,Irp);
        return;
    }else{
        RtlZeroMemory(QueryTable,sizeof(RTL_QUERY_REGISTRY_TABLE)*2);
        QueryTable[0].QueryRoutine = NULL;
        QueryTable[0].Flags         = RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_TYPECHECK;;
        QueryTable[0].EntryContext = &commonData->DebugLevel;
        QueryTable[0].Name      = L"DebugLevel";
        QueryTable[0].DefaultType = (REG_DWORD << RTL_QUERY_REGISTRY_TYPECHECK_SHIFT) | REG_DWORD;
        QueryTable[0].DefaultData   = &DebugLevelDefault;
        QueryTable[0].DefaultLength= sizeof(ULONG);

        // CIMEXCIMEX: The rest of the table isn't filled in!

        if (!NT_SUCCESS(RtlQueryRegistryValues(
                    RTL_REGISTRY_SERVICES,
                    L"Serenum",
                    QueryTable,
                    NULL,
                    NULL))){
                    Serenum_KdPrint (DeviceData,SER_DBG_PNP_ERROR,
                        ("Failed to get debug level from registry.  "
                         "Using default\n"));
                    DeviceData->DebugLevel = DebugLevelDefault;
                }
        ExFreePoolWithTag(QueryTable,SERENUM_POOL_TAG);
                
     }

     Serenum_KdPrint (DeviceData, SER_DBG_PNP_TRACE,
                     ("Start Device: Device started successfully\n"));
     DeviceData->Started = TRUE;
    IoCompleteRequest(Irp, IO_NO_INCREMENT);
    IoFreeWorkItem(WorkItem);
    IoReleaseRemoveLock( &commonData->RemoveLock,Irp);
    return;
}



#if _MSC_VER >= 1200
#pragma warning(pop)
#endif

#pragma warning(default:4127) // conditional expression is constant