summaryrefslogtreecommitdiff
path: root/storage/class/classpnp/src/power.c
blob: 75a6c05db60f76863387fa57c3b0ebcb28abcc24 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
/*++

Copyright (C) Microsoft Corporation, 1991 - 2010

Module Name:

    power.c

Abstract:

    SCSI class driver routines

Environment:

    kernel mode only

Notes:


Revision History:

--*/

#include "stddef.h"
#include "ntddk.h"
#include "scsi.h"
#include "classp.h"

#include <stdarg.h>

#ifdef DEBUG_USE_WPP
#include "power.tmh"
#endif

#define CLASS_TAG_POWER     'WLcS'

// constants for power transition process. (UNIT: seconds)
#define DEFAULT_POWER_IRP_TIMEOUT_VALUE 10*60
#define TIME_LEFT_FOR_LOWER_DRIVERS     30
#define TIME_LEFT_FOR_UPPER_DRIVERS     5
#define DEFAULT_IO_TIMEOUT_VALUE        10
#define MINIMUM_STOP_UNIT_TIMEOUT_VALUE 2

//
// MINIMAL value is one that has some slack and is the value to use
// if there is a shortened POWER IRP timeout value. If time remaining
// is less than MINIMAL, we will use the MINIMUM value. Both values
// are in the same unit as above (seconds).
//
#define MINIMAL_START_UNIT_TIMEOUT_VALUE 60
#define MINIMUM_START_UNIT_TIMEOUT_VALUE 30

// PoQueryWatchdogTime was introduced in Windows 7.
// Returns TRUE if a watchdog-enabled power IRP is found, otherwise FALSE.
#if (NTDDI_VERSION < NTDDI_WIN7)
#define PoQueryWatchdogTime(A, B) FALSE
#endif

IO_COMPLETION_ROUTINE ClasspPowerDownCompletion;

IO_COMPLETION_ROUTINE ClasspPowerUpCompletion;

IO_COMPLETION_ROUTINE ClasspStartNextPowerIrpCompletion;
IO_COMPLETION_ROUTINE ClasspDeviceLockFailurePowerIrpCompletion;

NTSTATUS
ClasspPowerHandler(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN CLASS_POWER_OPTIONS Options
    );

VOID
RetryPowerRequest(
    PDEVICE_OBJECT DeviceObject,
    PIRP Irp,
    PCLASS_POWER_CONTEXT Context
    );

#ifdef ALLOC_PRAGMA
    #pragma alloc_text(PAGE, ClasspPowerSettingCallback)
#endif

/*++////////////////////////////////////////////////////////////////////////////

ClassDispatchPower()

Routine Description:

    This routine acquires the removelock for the irp and then calls the
    appropriate power callback.

Arguments:

    DeviceObject -
    Irp -

Return Value:

--*/
NTSTATUS
ClassDispatchPower(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp
    )
{
    PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
    ULONG isRemoved;

    //
    // NOTE: This code may be called at PASSIVE or DISPATCH, depending
    //       upon the device object it is being called for.
    //       don't do anything that would break under either circumstance.
    //

    //
    // If device is added but not yet started, we need to send the Power
    // request down the stack.  If device is started and then stopped,
    // we have enough state to process the power request.
    //

    if (!commonExtension->IsInitialized) {

        PoStartNextPowerIrp(Irp);
        IoSkipCurrentIrpStackLocation(Irp);
        return PoCallDriver(commonExtension->LowerDeviceObject, Irp);
    }

    isRemoved = ClassAcquireRemoveLock(DeviceObject, Irp);

    if (isRemoved) {
        ClassReleaseRemoveLock(DeviceObject, Irp);
        Irp->IoStatus.Status = STATUS_DEVICE_DOES_NOT_EXIST;
        PoStartNextPowerIrp(Irp);
        ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
        return STATUS_DEVICE_DOES_NOT_EXIST;
    }

    return commonExtension->DevInfo->ClassPowerDevice(DeviceObject, Irp);
} // end ClassDispatchPower()

/*++////////////////////////////////////////////////////////////////////////////

ClasspPowerUpCompletion()

Routine Description:

    This routine is used for intermediate completion of a power up request.
    PowerUp requires four requests to be sent to the lower driver in sequence.

        * The queue is "power locked" to ensure that the class driver power-up
          work can be done before request processing resumes.

        * The power irp is sent down the stack for any filter drivers and the
          port driver to return power and resume command processing for the
          device.  Since the queue is locked, no queued irps will be sent
          immediately.

        * A start unit command is issued to the device with appropriate flags
          to override the "power locked" queue.

        * The queue is "power unlocked" to start processing requests again.

    This routine uses the function in the srb which just completed to determine
    which state it is in.

Arguments:

    DeviceObject - the device object being powered up

    Irp - Context->Irp: original power irp; fdoExtension->PrivateFdoData->PowerProcessIrp: power process irp

    Context - Class power context used to perform port/class operations.

Return Value:

    STATUS_MORE_PROCESSING_REQUIRED or
    STATUS_SUCCESS

--*/
NTSTATUS
ClasspPowerUpCompletion(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )
{
    PCLASS_POWER_CONTEXT PowerContext = (PCLASS_POWER_CONTEXT)Context;
    PCOMMON_DEVICE_EXTENSION commonExtension;
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
    PIRP OriginalIrp;
    PIO_STACK_LOCATION currentStack;
    PIO_STACK_LOCATION nextStack;

    NTSTATUS status = STATUS_MORE_PROCESSING_REQUIRED;
    PSTORAGE_REQUEST_BLOCK_HEADER srbHeader;
    ULONG srbFlags;
    BOOLEAN FailurePredictionEnabled = FALSE;

    UNREFERENCED_PARAMETER(DeviceObject);

    if (PowerContext == NULL) {
        NT_ASSERT(PowerContext != NULL);
        return STATUS_INVALID_PARAMETER;
    }

    commonExtension = PowerContext->DeviceObject->DeviceExtension;
    fdoExtension = PowerContext->DeviceObject->DeviceExtension;
    OriginalIrp = PowerContext->Irp;

    // currentStack - from original power irp
    // nextStack - from power process irp
    currentStack = IoGetCurrentIrpStackLocation(OriginalIrp);
    nextStack = IoGetNextIrpStackLocation(fdoExtension->PrivateFdoData->PowerProcessIrp);

    TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "ClasspPowerUpCompletion: Device Object %p, Irp %p, "
                   "Context %p\n",
                PowerContext->DeviceObject, Irp, Context));

    if (fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
        srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(fdoExtension->PrivateFdoData->PowerSrb.SrbEx);

        //
        // Check if reverted to using legacy SRB.
        //
        if (PowerContext->Srb.Length == sizeof(SCSI_REQUEST_BLOCK)) {
            srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(PowerContext->Srb);
        }
    } else {
        srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(PowerContext->Srb);
    }

    srbFlags = SrbGetSrbFlags(srbHeader);
    NT_ASSERT(!TEST_FLAG(srbFlags, SRB_FLAGS_FREE_SENSE_BUFFER));
    NT_ASSERT(!TEST_FLAG(srbFlags, SRB_FLAGS_PORT_DRIVER_ALLOCSENSE));
    NT_ASSERT(PowerContext->Options.PowerDown == FALSE);
    NT_ASSERT(PowerContext->Options.HandleSpinUp);

    if ((Irp == OriginalIrp) && (Irp->PendingReturned)) {
        // only for original power irp
        IoMarkIrpPending(Irp);
    }

    PowerContext->PowerChangeState.PowerUp++;

    switch (PowerContext->PowerChangeState.PowerUp) {

        case PowerUpDeviceLocked: {

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tPreviously sent power lock\n", Irp));

            //
            // Lock Queue operation has been sent.
            // Now, send the original power irp down to get lower driver and device ready.
            //

            IoCopyCurrentIrpStackLocationToNext(OriginalIrp);

            if ((PowerContext->Options.LockQueue == TRUE) &&
                (!NT_SUCCESS(Irp->IoStatus.Status))) {

                //
                // Lock was not successful:
                // Issue the original power request to the lower driver and next power irp will be started in completion routine.
                //


                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tIrp status was %lx\n",
                            Irp, Irp->IoStatus.Status));
                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tSrb status was %lx\n",
                            Irp, srbHeader->SrbStatus));

                IoSetCompletionRoutine(OriginalIrp,
                                       ClasspDeviceLockFailurePowerIrpCompletion,
                                       PowerContext,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                PoCallDriver(commonExtension->LowerDeviceObject, OriginalIrp);

                return STATUS_MORE_PROCESSING_REQUIRED;

            } else {
                PowerContext->QueueLocked = (UCHAR)PowerContext->Options.LockQueue;
            }

            Irp->IoStatus.Status = STATUS_NOT_SUPPORTED;

            PowerContext->PowerChangeState.PowerUp = PowerUpDeviceLocked;

            IoSetCompletionRoutine(OriginalIrp,
                                   ClasspPowerUpCompletion,
                                   PowerContext,
                                   TRUE,
                                   TRUE,
                                   TRUE);

            status = PoCallDriver(commonExtension->LowerDeviceObject, OriginalIrp);

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tIoCallDriver returned %lx\n", OriginalIrp, status));
            break;
        }

        case PowerUpDeviceOn: {

            //
            // Original power irp has been completed by lower driver.
            //

            if (NT_SUCCESS(Irp->IoStatus.Status)) {
                //
                // If power irp succeeded, START UNIT command will be sent.
                //
                PCDB cdb;
                ULONG secondsRemaining = 0;
                ULONG timeoutValue = 0;
                ULONG startUnitTimeout;

                if (PoQueryWatchdogTime(fdoExtension->LowerPdo, &secondsRemaining)) {

                    // do not exceed DEFAULT_POWER_IRP_TIMEOUT_VALUE.
                    secondsRemaining = min(secondsRemaining, DEFAULT_POWER_IRP_TIMEOUT_VALUE);

                    //
                    // It's possible for POWER IRP timeout value to be smaller than default of
                    // START_UNIT_TIMEOUT. If this is the case, use a smaller timeout value.
                    //
                    if (secondsRemaining >= START_UNIT_TIMEOUT) {
                        startUnitTimeout = START_UNIT_TIMEOUT;
                    } else {
                        startUnitTimeout = MINIMAL_START_UNIT_TIMEOUT_VALUE;
                    }

                    // plan to leave (TIME_LEFT_FOR_UPPER_DRIVERS) seconds to upper level drivers
                    // for processing original power irp.
                    if (secondsRemaining >= (TIME_LEFT_FOR_UPPER_DRIVERS + startUnitTimeout)) {
                        fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount =
                            (secondsRemaining - TIME_LEFT_FOR_UPPER_DRIVERS) / startUnitTimeout;

                        // * No 'short' timeouts
                        //
                        //
                        // timeoutValue = (secondsRemaining - TIME_LEFT_FOR_UPPER_DRIVERS) %
                        //                startUnitTimeout;
                        //

                        if (--fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount)
                        {
                            timeoutValue = startUnitTimeout;
                        } else {
                            timeoutValue = secondsRemaining - TIME_LEFT_FOR_UPPER_DRIVERS;
                        }
                    } else {
                        // issue the command with minimum timeout value and do not retry on it.
                        // case of (secondsRemaining < DEFAULT_IO_TIMEOUT_VALUE) is ignored as it should not happen.
                        NT_ASSERT(secondsRemaining >= DEFAULT_IO_TIMEOUT_VALUE);

                        fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount = 0;
                        timeoutValue = MINIMUM_START_UNIT_TIMEOUT_VALUE; // use the minimum value for this corner case.
                    }

                } else {
                    // don't know how long left, do not exceed DEFAULT_POWER_IRP_TIMEOUT_VALUE.
                    fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount =
                        DEFAULT_POWER_IRP_TIMEOUT_VALUE / START_UNIT_TIMEOUT - 1;
                    timeoutValue = START_UNIT_TIMEOUT;
                }


                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tSending start unit to device\n", Irp));

                //
                // Issue the start unit command to the device.
                //

                PowerContext->RetryCount = fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount;

                if (fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
                    status = InitializeStorageRequestBlock((PSTORAGE_REQUEST_BLOCK)srbHeader,
                                                            STORAGE_ADDRESS_TYPE_BTL8,
                                                            CLASS_SRBEX_SCSI_CDB16_BUFFER_SIZE,
                                                            1,
                                                            SrbExDataTypeScsiCdb16);
                    if (NT_SUCCESS(status)) {
                        ((PSTORAGE_REQUEST_BLOCK)srbHeader)->SrbFunction = SRB_FUNCTION_EXECUTE_SCSI;

                        //
                        // Set length field in Power Context SRB so we know legacy SRB is not being used.
                        //
                        PowerContext->Srb.Length = 0;

                    } else {
                        //
                        // Should not happen. Revert to legacy SRB.
                        //
                        NT_ASSERT(FALSE);
                        srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(PowerContext->Srb);
                        RtlZeroMemory(srbHeader, sizeof(SCSI_REQUEST_BLOCK));
                        srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
                        srbHeader->Function = SRB_FUNCTION_EXECUTE_SCSI;
                    }

                } else {
                    RtlZeroMemory(srbHeader, sizeof(SCSI_REQUEST_BLOCK));
                    srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
                    srbHeader->Function = SRB_FUNCTION_EXECUTE_SCSI;
                }

                SrbSetOriginalRequest(srbHeader, fdoExtension->PrivateFdoData->PowerProcessIrp);
                SrbSetSenseInfoBuffer(srbHeader, commonExtension->PartitionZeroExtension->SenseData);
                SrbSetSenseInfoBufferLength(srbHeader, GET_FDO_EXTENSON_SENSE_DATA_LENGTH(commonExtension->PartitionZeroExtension));

                SrbSetTimeOutValue(srbHeader, timeoutValue);
                SrbAssignSrbFlags(srbHeader,
                                     (SRB_FLAGS_NO_DATA_TRANSFER |
                                      SRB_FLAGS_DISABLE_AUTOSENSE |
                                      SRB_FLAGS_DISABLE_SYNCH_TRANSFER |
                                      SRB_FLAGS_NO_QUEUE_FREEZE));

                if (PowerContext->Options.LockQueue) {
                    SrbSetSrbFlags(srbHeader, SRB_FLAGS_BYPASS_LOCKED_QUEUE);
                }

                SrbSetCdbLength(srbHeader, 6);

                cdb = SrbGetCdb(srbHeader);
                RtlZeroMemory(cdb, sizeof(CDB));

                cdb->START_STOP.OperationCode = SCSIOP_START_STOP_UNIT;
                cdb->START_STOP.Start = 1;

                PowerContext->PowerChangeState.PowerUp = PowerUpDeviceOn;

                IoSetCompletionRoutine(fdoExtension->PrivateFdoData->PowerProcessIrp,
                                       ClasspPowerUpCompletion,
                                       PowerContext,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                nextStack->Parameters.Scsi.Srb = (PSCSI_REQUEST_BLOCK)srbHeader;
                nextStack->MajorFunction = IRP_MJ_SCSI;

                status = IoCallDriver(commonExtension->LowerDeviceObject, fdoExtension->PrivateFdoData->PowerProcessIrp);

                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tIoCallDriver returned %lx\n", fdoExtension->PrivateFdoData->PowerProcessIrp, status));

            } else {

                //
                // power irp is failed by lower driver. we're done.
                //

                PowerContext->FinalStatus = Irp->IoStatus.Status;
                goto ClasspPowerUpCompletionFailure;
            }

            break;
        }

        case PowerUpDeviceStarted: { // 3

            //
            // First deal with an error if one occurred.
            //

            if (SRB_STATUS(srbHeader->SrbStatus) != SRB_STATUS_SUCCESS) {

                BOOLEAN retry;
                LONGLONG delta100nsUnits = 0;
                ULONG secondsRemaining = 0;
                ULONG startUnitTimeout = START_UNIT_TIMEOUT;

                TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_POWER, "%p\tError occured when issuing START_UNIT "
                            "command to device. Srb %p, Status %x\n",
                            Irp,
                            srbHeader,
                            srbHeader->SrbStatus));

                NT_ASSERT(!(TEST_FLAG(srbHeader->SrbStatus, SRB_STATUS_QUEUE_FROZEN)));
                NT_ASSERT((srbHeader->Function == SRB_FUNCTION_EXECUTE_SCSI) ||
                          (((PSTORAGE_REQUEST_BLOCK)srbHeader)->SrbFunction == SRB_FUNCTION_EXECUTE_SCSI));

                PowerContext->RetryInterval = 0;
                retry = InterpretSenseInfoWithoutHistory(
                            fdoExtension->DeviceObject,
                            Irp,
                            (PSCSI_REQUEST_BLOCK)srbHeader,
                            IRP_MJ_SCSI,
                            IRP_MJ_POWER,
                            fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount - PowerContext->RetryCount,
                            &status,
                            &delta100nsUnits);

                // NOTE: Power context is a public structure, and thus cannot be
                //       updated to use 100ns units.  Therefore, must store the
                //       one-second equivalent.  Round up to ensure minimum delay
                //       requirements have been met.
                delta100nsUnits += (10*1000*1000) - 1;
                delta100nsUnits /= (10*1000*1000);
                // guaranteed not to have high bits set per SAL annotations
                PowerContext->RetryInterval = (ULONG)(delta100nsUnits);


                if ((retry == TRUE) && (PowerContext->RetryCount-- != 0)) {

                    TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tRetrying failed request\n", Irp));

                    //
                    // Decrement the state so we come back through here the
                    // next time.
                    //

                    PowerContext->PowerChangeState.PowerUp--;

                    //
                    // Adjust start unit timeout based on remaining time if needed.
                    //
                    if (PoQueryWatchdogTime(fdoExtension->LowerPdo, &secondsRemaining)) {

                        if (secondsRemaining >= TIME_LEFT_FOR_UPPER_DRIVERS) {
                            secondsRemaining -= TIME_LEFT_FOR_UPPER_DRIVERS;
                        }

                        if (secondsRemaining < MINIMAL_START_UNIT_TIMEOUT_VALUE) {
                            startUnitTimeout = MINIMUM_START_UNIT_TIMEOUT_VALUE;
                        } else if (secondsRemaining < START_UNIT_TIMEOUT) {
                            startUnitTimeout = MINIMAL_START_UNIT_TIMEOUT_VALUE;
                        }
                    }

                    SrbSetTimeOutValue(srbHeader, startUnitTimeout);

                    RetryPowerRequest(commonExtension->DeviceObject,
                                      Irp,
                                      PowerContext);

                    break;

                }

                // reset retry count for UNLOCK command.
                fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount = MAXIMUM_RETRIES;
                PowerContext->RetryCount = MAXIMUM_RETRIES;
            }

ClasspPowerUpCompletionFailure:

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tPreviously spun device up\n", Irp));

            if (PowerContext->QueueLocked) {
                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tUnlocking queue\n", Irp));

                if (fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
                    //
                    // Will reuse SRB for a non-SCSI SRB.
                    //
                    status = InitializeStorageRequestBlock((PSTORAGE_REQUEST_BLOCK)srbHeader,
                                                           STORAGE_ADDRESS_TYPE_BTL8,
                                                           CLASS_SRBEX_NO_SRBEX_DATA_BUFFER_SIZE,
                                                           0);
                    if (NT_SUCCESS(status)) {
                        ((PSTORAGE_REQUEST_BLOCK)srbHeader)->SrbFunction = SRB_FUNCTION_UNLOCK_QUEUE;

                        //
                        // Set length field in Power Context SRB so we know legacy SRB is not being used.
                        //
                        PowerContext->Srb.Length = 0;

                    } else {
                        //
                        // Should not occur. Revert to legacy SRB.
                        NT_ASSERT(FALSE);
                        srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(PowerContext->Srb);
                        RtlZeroMemory(srbHeader, sizeof(SCSI_REQUEST_BLOCK));
                        srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
                        srbHeader->Function = SRB_FUNCTION_UNLOCK_QUEUE;
                    }
                } else {
                    RtlZeroMemory(srbHeader, sizeof(SCSI_REQUEST_BLOCK));
                    srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
                    srbHeader->Function = SRB_FUNCTION_UNLOCK_QUEUE;
                }
                SrbAssignSrbFlags(srbHeader, SRB_FLAGS_BYPASS_LOCKED_QUEUE);
                SrbSetOriginalRequest(srbHeader, fdoExtension->PrivateFdoData->PowerProcessIrp);

                nextStack->Parameters.Scsi.Srb = (PSCSI_REQUEST_BLOCK)srbHeader;
                nextStack->MajorFunction = IRP_MJ_SCSI;

                PowerContext->PowerChangeState.PowerUp = PowerUpDeviceStarted;

                IoSetCompletionRoutine(fdoExtension->PrivateFdoData->PowerProcessIrp,
                                       ClasspPowerUpCompletion,
                                       PowerContext,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                status = IoCallDriver(commonExtension->LowerDeviceObject, fdoExtension->PrivateFdoData->PowerProcessIrp);
                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tIoCallDriver returned %lx\n",
                            fdoExtension->PrivateFdoData->PowerProcessIrp, status));
                break;
            }

            // Fall-through to next case...

        }

        case PowerUpDeviceUnlocked: {

            //
            // This is the end of the dance.
            // We're ignoring possible intermediate error conditions ....
            //

            if (PowerContext->QueueLocked) {
                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tPreviously unlocked queue\n", OriginalIrp));

                //
                // If the lower device is being removed, the IRP's status may be STATUS_DELETE_PENDING or 
                // STATUS_DEVICE_DOES_NOT_EXIST. 
                //
                if((NT_SUCCESS(Irp->IoStatus.Status) == FALSE) &&
                   (Irp->IoStatus.Status != STATUS_DELETE_PENDING) &&
                   (Irp->IoStatus.Status != STATUS_DEVICE_DOES_NOT_EXIST)) {


                    NT_ASSERT(FALSE);
                }

            } else {
                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tFall-through (queue not locked)\n", OriginalIrp));
            }

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tFreeing srb and completing\n", OriginalIrp));

            status = PowerContext->FinalStatus;
            OriginalIrp->IoStatus.Status = status;

            //
            // Set the new power state
            //

            if (NT_SUCCESS(status)) {
                fdoExtension->DevicePowerState = currentStack->Parameters.Power.State.DeviceState;
            }

            //
            // Check whether failure detection is enabled
            //

            if ((fdoExtension->FailurePredictionInfo != NULL) &&
                (fdoExtension->FailurePredictionInfo->Method != FailurePredictionNone)) {
                 FailurePredictionEnabled = TRUE;
            }

            //
            // Enable tick timer at end of D0 processing if it was previously enabled.
            //

            if ((commonExtension->DriverExtension->InitData.ClassTick != NULL) ||
                ((fdoExtension->MediaChangeDetectionInfo != NULL) &&
                 (fdoExtension->FunctionSupportInfo != NULL) &&
                 (fdoExtension->FunctionSupportInfo->AsynchronousNotificationSupported == FALSE)) ||
                (FailurePredictionEnabled)) {


                //
                // If failure prediction is turned on and we've been powered
                // off longer than the failure prediction query period then
                // force the query on the next timer tick.
                //

                if ((FailurePredictionEnabled) && (ClasspFailurePredictionPeriodMissed(fdoExtension))) {
                     fdoExtension->FailurePredictionInfo->CountDown = 1;
                }

                //
                // Finally, enable the timer.
                //

                ClasspEnableTimer(fdoExtension);
            }

            //
            // Indicate to Po that we've been successfully powered up so
            // it can do it's notification stuff.
            //

            PoSetPowerState(PowerContext->DeviceObject,
                            currentStack->Parameters.Power.Type,
                            currentStack->Parameters.Power.State);

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tStarting next power irp\n", OriginalIrp));

            ClassReleaseRemoveLock(PowerContext->DeviceObject, OriginalIrp);

            PowerContext->InUse = FALSE;

            PoStartNextPowerIrp(OriginalIrp);

            // prevent from completing the irp allocated by ourselves
            if ((fdoExtension->PrivateFdoData) && (Irp == fdoExtension->PrivateFdoData->PowerProcessIrp)) {
                // complete original irp if we are processing powerprocess irp,
                // otherwise, by returning status other than STATUS_MORE_PROCESSING_REQUIRED, IO manager will complete it.
                ClassCompleteRequest(commonExtension->DeviceObject, OriginalIrp, IO_NO_INCREMENT);
                status = STATUS_MORE_PROCESSING_REQUIRED;
            }

            return status;
        }
    }

    return STATUS_MORE_PROCESSING_REQUIRED;
} // end ClasspPowerUpCompletion()

/*++////////////////////////////////////////////////////////////////////////////

ClasspPowerDownCompletion()

Routine Description:

    This routine is used for intermediate completion of a power down request.
    PowerDown performs the following sequence to power down the device.

        1. The queue(s) in the lower stack is/are "power locked" to ensure new
           requests are held until the power-down process is complete.

        2. A request to the lower layers to wait for all outstanding IO to
           complete ("quiescence") is sent.  This ensures we don't power down
           the device while it's in the middle of handling IO.

        3. A request to flush the device's cache is sent.  The device may lose
           power when we forward the D-IRP so any data in volatile storage must
           be committed to non-volatile storage first.

        4. A "stop unit" request is sent to the device to notify it that it
           is about to be powered down.

        5. The D-IRP is forwarded down the stack.  If D3Cold is supported and
           enabled via ACPI, the ACPI filter driver may power off the device.

        6. Once the D-IRP is completed by the lower stack, we will "power
           unlock" the queue(s).  (It is the lower stack's responsibility to
           continue to queue any IO that requires hardware access until the
           device is powered up again.)

Arguments:

    DeviceObject - the device object being powered down

    Irp - the IO_REQUEST_PACKET containing the power request

    Context - the class power context used to perform port/class operations.

Return Value:

    STATUS_MORE_PROCESSING_REQUIRED or
    STATUS_SUCCESS

--*/
NTSTATUS
ClasspPowerDownCompletion(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )
{
    PCLASS_POWER_CONTEXT PowerContext = (PCLASS_POWER_CONTEXT)Context;
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = PowerContext->DeviceObject->DeviceExtension;
    PCOMMON_DEVICE_EXTENSION commonExtension = PowerContext->DeviceObject->DeviceExtension;
    PIRP OriginalIrp = PowerContext->Irp;

    // currentStack is for original power irp
    // nextStack is for power process irp
    PIO_STACK_LOCATION currentStack = IoGetCurrentIrpStackLocation(OriginalIrp);
    PIO_STACK_LOCATION nextStack = IoGetNextIrpStackLocation(fdoExtension->PrivateFdoData->PowerProcessIrp);

    NTSTATUS status = STATUS_MORE_PROCESSING_REQUIRED;
    PSTORAGE_REQUEST_BLOCK_HEADER srbHeader;
    ULONG srbFlags;

    UNREFERENCED_PARAMETER(DeviceObject);

    TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "ClasspPowerDownCompletion: Device Object %p, "
                   "Irp %p, Context %p\n",
                PowerContext->DeviceObject, Irp, Context));

    if (fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
        srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(fdoExtension->PrivateFdoData->PowerSrb.SrbEx);

        //
        // Check if reverted to using legacy SRB.
        //
        if (PowerContext->Srb.Length == sizeof(SCSI_REQUEST_BLOCK)) {
            srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(PowerContext->Srb);
        }
    } else {
        srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(PowerContext->Srb);
    }

    srbFlags = SrbGetSrbFlags(srbHeader);
    NT_ASSERT(!TEST_FLAG(srbFlags, SRB_FLAGS_FREE_SENSE_BUFFER));
    NT_ASSERT(!TEST_FLAG(srbFlags, SRB_FLAGS_PORT_DRIVER_ALLOCSENSE));
    NT_ASSERT(PowerContext->Options.PowerDown == TRUE);
    NT_ASSERT(PowerContext->Options.HandleSpinDown);

    if ((Irp == OriginalIrp) && (Irp->PendingReturned)) {
        // only for original power irp
        IoMarkIrpPending(Irp);
    }

    PowerContext->PowerChangeState.PowerDown3++;

    switch(PowerContext->PowerChangeState.PowerDown3) {

        case PowerDownDeviceLocked3: {

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tPreviously sent power lock\n", Irp));

            if ((PowerContext->Options.LockQueue == TRUE) &&
                (!NT_SUCCESS(Irp->IoStatus.Status))) {

                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tIrp status was %lx\n",
                            Irp,
                            Irp->IoStatus.Status));
                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tSrb status was %lx\n",
                            Irp,
                            srbHeader->SrbStatus));



                //
                // Lock was not successful - throw down the power IRP
                // by itself and don't try to spin down the drive or unlock
                // the queue.
                //

                //
                // Set the new power state
                //

                fdoExtension->DevicePowerState =
                    currentStack->Parameters.Power.State.DeviceState;

                //
                // Indicate to Po that we've been successfully powered down
                // so it can do it's notification stuff.
                //

                IoCopyCurrentIrpStackLocationToNext(OriginalIrp);
                IoSetCompletionRoutine(OriginalIrp,
                                       ClasspStartNextPowerIrpCompletion,
                                       PowerContext,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                PoSetPowerState(PowerContext->DeviceObject,
                                currentStack->Parameters.Power.Type,
                                currentStack->Parameters.Power.State);

                fdoExtension->PowerDownInProgress = FALSE;

                ClassReleaseRemoveLock(commonExtension->DeviceObject,
                                       OriginalIrp);

                PoCallDriver(commonExtension->LowerDeviceObject, OriginalIrp);

                return STATUS_MORE_PROCESSING_REQUIRED;

            } else {
                //
                // Lock the device queue succeeded. Now wait for all outstanding IO to complete.
                // To do this, Srb with SRB_FUNCTION_QUIESCE_DEVICE will be sent down with default timeout value.
                // We need to tolerant failure of this request, no retry will be made.
                //
                PowerContext->QueueLocked = (UCHAR) PowerContext->Options.LockQueue;

                //
                // No retry on device quiescence reqeust
                //
                fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount = 0;
                PowerContext->RetryCount = 0;

                if (fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
                    srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(fdoExtension->PrivateFdoData->PowerSrb.SrbEx);

                    //
                    // Initialize extended SRB for a SRB_FUNCTION_LOCK_QUEUE
                    //
                    status = InitializeStorageRequestBlock((PSTORAGE_REQUEST_BLOCK)srbHeader,
                                                           STORAGE_ADDRESS_TYPE_BTL8,
                                                           CLASS_SRBEX_NO_SRBEX_DATA_BUFFER_SIZE,
                                                           0);
                    if (NT_SUCCESS(status)) {
                        ((PSTORAGE_REQUEST_BLOCK)srbHeader)->SrbFunction = SRB_FUNCTION_QUIESCE_DEVICE;
                    } else {
                        //
                        // Should not happen. Revert to legacy SRB.
                        //
                        NT_ASSERT(FALSE);
                        srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(PowerContext->Srb);
                        srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
                        srbHeader->Function = SRB_FUNCTION_QUIESCE_DEVICE;
                    }
                } else {
                    srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(PowerContext->Srb);
                    srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
                    srbHeader->Function = SRB_FUNCTION_QUIESCE_DEVICE;
                }

                SrbSetOriginalRequest(srbHeader, fdoExtension->PrivateFdoData->PowerProcessIrp);
                SrbSetTimeOutValue(srbHeader, fdoExtension->TimeOutValue);

                SrbAssignSrbFlags(srbHeader,
                                     (SRB_FLAGS_NO_DATA_TRANSFER |
                                      SRB_FLAGS_DISABLE_AUTOSENSE |
                                      SRB_FLAGS_DISABLE_SYNCH_TRANSFER |
                                      SRB_FLAGS_NO_QUEUE_FREEZE |
                                      SRB_FLAGS_BYPASS_LOCKED_QUEUE |
                                      SRB_FLAGS_D3_PROCESSING));

                IoSetCompletionRoutine(fdoExtension->PrivateFdoData->PowerProcessIrp,
                                       ClasspPowerDownCompletion,
                                       PowerContext,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                nextStack->Parameters.Scsi.Srb = (PSCSI_REQUEST_BLOCK)srbHeader;
                nextStack->MajorFunction = IRP_MJ_SCSI;

                status = IoCallDriver(commonExtension->LowerDeviceObject, fdoExtension->PrivateFdoData->PowerProcessIrp);

                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tIoCallDriver returned %lx\n", fdoExtension->PrivateFdoData->PowerProcessIrp, status));
                break;
            }

        }

        case PowerDownDeviceQuiesced3: {

            PCDB cdb;

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tPreviously sent device quiesce\n", Irp));

            //
            // don't care the result of device quiesce, we've made the effort.
            // continue on sending other SCSI commands anyway.
            //


            if (!TEST_FLAG(fdoExtension->PrivateFdoData->HackFlags,
                           FDO_HACK_NO_SYNC_CACHE)) {

                //
                // send SCSIOP_SYNCHRONIZE_CACHE
                //

                fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount = MAXIMUM_RETRIES;
                PowerContext->RetryCount = MAXIMUM_RETRIES;

                if (fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
                    status = InitializeStorageRequestBlock((PSTORAGE_REQUEST_BLOCK)srbHeader,
                                                            STORAGE_ADDRESS_TYPE_BTL8,
                                                            CLASS_SRBEX_SCSI_CDB16_BUFFER_SIZE,
                                                            1,
                                                            SrbExDataTypeScsiCdb16);
                    if (NT_SUCCESS(status)) {
                        ((PSTORAGE_REQUEST_BLOCK)srbHeader)->SrbFunction = SRB_FUNCTION_EXECUTE_SCSI;

                        //
                        // Set length field in Power Context SRB so we know legacy SRB is not being used.
                        //
                        PowerContext->Srb.Length = 0;

                    } else {
                        //
                        // Should not occur. Revert to legacy SRB.
                        NT_ASSERT(FALSE);
                        srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(PowerContext->Srb);
                        RtlZeroMemory(srbHeader, sizeof(SCSI_REQUEST_BLOCK));
                        srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
                        srbHeader->Function = SRB_FUNCTION_EXECUTE_SCSI;
                    }

                } else {
                    RtlZeroMemory(srbHeader, sizeof(SCSI_REQUEST_BLOCK));
                    srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
                    srbHeader->Function = SRB_FUNCTION_EXECUTE_SCSI;
                }


                SrbSetOriginalRequest(srbHeader, fdoExtension->PrivateFdoData->PowerProcessIrp);
                SrbSetSenseInfoBuffer(srbHeader, commonExtension->PartitionZeroExtension->SenseData);
                SrbSetSenseInfoBufferLength(srbHeader, GET_FDO_EXTENSON_SENSE_DATA_LENGTH(commonExtension->PartitionZeroExtension));
                SrbSetTimeOutValue(srbHeader, fdoExtension->TimeOutValue);

                SrbAssignSrbFlags(srbHeader,
                                     (SRB_FLAGS_NO_DATA_TRANSFER |
                                      SRB_FLAGS_DISABLE_AUTOSENSE |
                                      SRB_FLAGS_DISABLE_SYNCH_TRANSFER |
                                      SRB_FLAGS_NO_QUEUE_FREEZE |
                                      SRB_FLAGS_BYPASS_LOCKED_QUEUE |
                                      SRB_FLAGS_D3_PROCESSING));

                SrbSetCdbLength(srbHeader, 10);

                cdb = SrbGetCdb(srbHeader);

                RtlZeroMemory(cdb, sizeof(CDB));
                cdb->SYNCHRONIZE_CACHE10.OperationCode = SCSIOP_SYNCHRONIZE_CACHE;

                IoSetCompletionRoutine(fdoExtension->PrivateFdoData->PowerProcessIrp,
                                       ClasspPowerDownCompletion,
                                       PowerContext,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                nextStack->Parameters.Scsi.Srb = (PSCSI_REQUEST_BLOCK)srbHeader;
                nextStack->MajorFunction = IRP_MJ_SCSI;

                status = IoCallDriver(commonExtension->LowerDeviceObject, fdoExtension->PrivateFdoData->PowerProcessIrp);

                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tIoCallDriver returned %lx\n", fdoExtension->PrivateFdoData->PowerProcessIrp, status));
                break;

            } else {

                TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_POWER, "(%p)\tPower Down: not sending SYNCH_CACHE\n",
                            PowerContext->DeviceObject));
                PowerContext->PowerChangeState.PowerDown3++;
                srbHeader->SrbStatus = SRB_STATUS_SUCCESS;
                // and fall through....
            }
            // no break in case the device doesn't like synch_cache commands

        }

        case PowerDownDeviceFlushed3: {

            PCDB cdb;

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tPreviously send SCSIOP_SYNCHRONIZE_CACHE\n",
                        Irp));

            //
            // SCSIOP_SYNCHRONIZE_CACHE was sent
            //

            if (SRB_STATUS(srbHeader->SrbStatus) != SRB_STATUS_SUCCESS) {

                BOOLEAN retry;
                LONGLONG delta100nsUnits = 0;

                TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_POWER, "(%p)\tError occured when issuing "
                            "SYNCHRONIZE_CACHE command to device. "
                            "Srb %p, Status %lx\n",
                            Irp,
                            srbHeader,
                            srbHeader->SrbStatus));

                NT_ASSERT(!(TEST_FLAG(srbHeader->SrbStatus, SRB_STATUS_QUEUE_FROZEN)));
                NT_ASSERT((srbHeader->Function == SRB_FUNCTION_EXECUTE_SCSI) ||
                          (((PSTORAGE_REQUEST_BLOCK)srbHeader)->SrbFunction == SRB_FUNCTION_EXECUTE_SCSI));

                PowerContext->RetryInterval = 0;
                retry = InterpretSenseInfoWithoutHistory(
                            fdoExtension->DeviceObject,
                            Irp,
                            (PSCSI_REQUEST_BLOCK)srbHeader,
                            IRP_MJ_SCSI,
                            IRP_MJ_POWER,
                            fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount - PowerContext->RetryCount,
                            &status,
                            &delta100nsUnits);

                // NOTE: Power context is a public structure, and thus cannot be
                //       updated to use 100ns units.  Therefore, must store the
                //       one-second equivalent.  Round up to ensure minimum delay
                //       requirements have been met.
                delta100nsUnits += (10*1000*1000) - 1;
                delta100nsUnits /= (10*1000*1000);
                // guaranteed not to have high bits set per SAL annotations
                PowerContext->RetryInterval = (ULONG)(delta100nsUnits);


                if ((retry == TRUE) && (PowerContext->RetryCount-- != 0)) {

                    TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tRetrying failed request\n", Irp));

                    //
                    // decrement the state so we come back through here
                    // the next time.
                    //

                    PowerContext->PowerChangeState.PowerDown3--;
                    RetryPowerRequest(commonExtension->DeviceObject,
                                      Irp,
                                      PowerContext);
                    break;
                }

                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tSYNCHRONIZE_CACHE not retried\n", Irp));
                fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount = MAXIMUM_RETRIES;
                PowerContext->RetryCount = MAXIMUM_RETRIES;
            } // end !SRB_STATUS_SUCCESS

            //
            // note: we are purposefully ignoring any errors.  if the drive
            //       doesn't support a synch_cache, then we're up a creek
            //       anyways.
            //

            if ((currentStack->Parameters.Power.State.DeviceState == PowerDeviceD3) &&
                (currentStack->Parameters.Power.ShutdownType == PowerActionHibernate) &&
                (commonExtension->HibernationPathCount != 0)) {

                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tPower Down: not sending SPIN DOWN due to hibernation path\n",
                            PowerContext->DeviceObject));

                PowerContext->PowerChangeState.PowerDown3++;
                srbHeader->SrbStatus = SRB_STATUS_SUCCESS;
                status = STATUS_SUCCESS;

                // Fall through to next case...

            } else {
                // Send STOP UNIT command. As "Imme" bit is set to '1', this command should be completed in short time.
                // This command is at low importance, failure of this command has very small impact.

                ULONG secondsRemaining;
                ULONG timeoutValue;

                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tSending stop unit to device\n", Irp));

                if (PoQueryWatchdogTime(fdoExtension->LowerPdo, &secondsRemaining)) {
                    // plan to leave some time (TIME_LEFT_FOR_LOWER_DRIVERS) to lower level drivers
                    // for processing the original power irp.
                    if (secondsRemaining >= (TIME_LEFT_FOR_LOWER_DRIVERS + DEFAULT_IO_TIMEOUT_VALUE)) {
                        fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount =
                            (secondsRemaining - TIME_LEFT_FOR_LOWER_DRIVERS) / DEFAULT_IO_TIMEOUT_VALUE;

                        // * No 'short' timeouts
                        //
                        // timeoutValue = (secondsRemaining - TIME_LEFT_FOR_LOWER_DRIVERS) %
                        //                DEFAULT_IO_TIMEOUT_VALUE;
                        // if (timeoutValue < MINIMUM_STOP_UNIT_TIMEOUT_VALUE)
                        // {
                        if (--fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount)
                        {
                            timeoutValue = DEFAULT_IO_TIMEOUT_VALUE;
                        } else {
                            timeoutValue = secondsRemaining - TIME_LEFT_FOR_LOWER_DRIVERS;
                        }
                        // }

                        // Limit to maximum retry count.
                        if (fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount > MAXIMUM_RETRIES) {
                            fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount = MAXIMUM_RETRIES;
                        }
                    } else {
                        // issue the command with minimum timeout value and do not retry on it.
                        fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount = 0;

                        // minimum as MINIMUM_STOP_UNIT_TIMEOUT_VALUE.
                        if (secondsRemaining > 2 * MINIMUM_STOP_UNIT_TIMEOUT_VALUE) {
                            timeoutValue = secondsRemaining - MINIMUM_STOP_UNIT_TIMEOUT_VALUE;
                        } else {
                            timeoutValue = MINIMUM_STOP_UNIT_TIMEOUT_VALUE;
                        }

                    }

                } else {
                    // do not know how long, use default values.
                    fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount = MAXIMUM_RETRIES;
                    timeoutValue = DEFAULT_IO_TIMEOUT_VALUE;
                }

                //
                // Issue STOP UNIT command to the device.
                //

                PowerContext->RetryCount = fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount;

                if (fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
                    status = InitializeStorageRequestBlock((PSTORAGE_REQUEST_BLOCK)srbHeader,
                                                            STORAGE_ADDRESS_TYPE_BTL8,
                                                            CLASS_SRBEX_SCSI_CDB16_BUFFER_SIZE,
                                                            1,
                                                            SrbExDataTypeScsiCdb16);
                    if (NT_SUCCESS(status)) {
                        ((PSTORAGE_REQUEST_BLOCK)srbHeader)->SrbFunction = SRB_FUNCTION_EXECUTE_SCSI;

                        //
                        // Set length field in Power Context SRB so we know legacy SRB is not being used.
                        //
                        PowerContext->Srb.Length = 0;

                    } else {
                        //
                        // Should not occur. Revert to legacy SRB.
                        //
                        NT_ASSERT(FALSE);
                        srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(PowerContext->Srb);
                        RtlZeroMemory(srbHeader, sizeof(SCSI_REQUEST_BLOCK));
                        srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
                        srbHeader->Function = SRB_FUNCTION_EXECUTE_SCSI;
                    }

                } else {
                    RtlZeroMemory(srbHeader, sizeof(SCSI_REQUEST_BLOCK));
                    srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
                    srbHeader->Function = SRB_FUNCTION_EXECUTE_SCSI;
                }

                SrbSetOriginalRequest(srbHeader, fdoExtension->PrivateFdoData->PowerProcessIrp);
                SrbSetSenseInfoBuffer(srbHeader, commonExtension->PartitionZeroExtension->SenseData);
                SrbSetSenseInfoBufferLength(srbHeader, GET_FDO_EXTENSON_SENSE_DATA_LENGTH(commonExtension->PartitionZeroExtension));
                SrbSetTimeOutValue(srbHeader, timeoutValue);


                SrbAssignSrbFlags(srbHeader,
                                     (SRB_FLAGS_NO_DATA_TRANSFER |
                                      SRB_FLAGS_DISABLE_AUTOSENSE |
                                      SRB_FLAGS_DISABLE_SYNCH_TRANSFER |
                                      SRB_FLAGS_NO_QUEUE_FREEZE |
                                      SRB_FLAGS_BYPASS_LOCKED_QUEUE |
                                      SRB_FLAGS_D3_PROCESSING));

                SrbSetCdbLength(srbHeader, 6);

                cdb = SrbGetCdb(srbHeader);
                RtlZeroMemory(cdb, sizeof(CDB));

                cdb->START_STOP.OperationCode = SCSIOP_START_STOP_UNIT;
                cdb->START_STOP.Start = 0;
                cdb->START_STOP.Immediate = 1;

                IoSetCompletionRoutine(fdoExtension->PrivateFdoData->PowerProcessIrp,
                                       ClasspPowerDownCompletion,
                                       PowerContext,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                nextStack->Parameters.Scsi.Srb = (PSCSI_REQUEST_BLOCK)srbHeader;
                nextStack->MajorFunction = IRP_MJ_SCSI;

                status = IoCallDriver(commonExtension->LowerDeviceObject, fdoExtension->PrivateFdoData->PowerProcessIrp);

                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tIoCallDriver returned %lx\n", fdoExtension->PrivateFdoData->PowerProcessIrp, status));
                break;
            }
        }

        case PowerDownDeviceStopped3: {

            BOOLEAN ignoreError = TRUE;

            //
            // stop was sent
            //

            if (SRB_STATUS(srbHeader->SrbStatus) != SRB_STATUS_SUCCESS) {

                BOOLEAN retry;
                LONGLONG delta100nsUnits = 0;

                TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_POWER, "(%p)\tError occured when issueing STOP_UNIT "
                            "command to device. Srb %p, Status %lx\n",
                            Irp,
                            srbHeader,
                            srbHeader->SrbStatus));

                NT_ASSERT(!(TEST_FLAG(srbHeader->SrbStatus, SRB_STATUS_QUEUE_FROZEN)));
                NT_ASSERT((srbHeader->Function == SRB_FUNCTION_EXECUTE_SCSI) ||
                          (((PSTORAGE_REQUEST_BLOCK)srbHeader)->SrbFunction == SRB_FUNCTION_EXECUTE_SCSI));

                PowerContext->RetryInterval = 0;
                retry = InterpretSenseInfoWithoutHistory(
                            fdoExtension->DeviceObject,
                            Irp,
                            (PSCSI_REQUEST_BLOCK)srbHeader,
                            IRP_MJ_SCSI,
                            IRP_MJ_POWER,
                            fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount - PowerContext->RetryCount,
                            &status,
                            &delta100nsUnits);

                // NOTE: Power context is a public structure, and thus cannot be
                //       updated to use 100ns units.  Therefore, must store the
                //       one-second equivalent.  Round up to ensure minimum delay
                //       requirements have been met.
                delta100nsUnits += (10*1000*1000) - 1;
                delta100nsUnits /= (10*1000*1000);
                // guaranteed not to have high bits set per SAL annotations
                PowerContext->RetryInterval = (ULONG)(delta100nsUnits);


                if ((retry == TRUE) && (PowerContext->RetryCount-- != 0)) {

                    TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tRetrying failed request\n", Irp));

                    //
                    // decrement the state so we come back through here
                    // the next time.
                    //

                    PowerContext->PowerChangeState.PowerDown3--;

                    SrbSetTimeOutValue(srbHeader, DEFAULT_IO_TIMEOUT_VALUE);

                    RetryPowerRequest(commonExtension->DeviceObject,
                                      Irp,
                                      PowerContext);
                    break;
                }

                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tSTOP_UNIT not retried\n", Irp));
                fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount = MAXIMUM_RETRIES;
                PowerContext->RetryCount = MAXIMUM_RETRIES;

            } // end !SRB_STATUS_SUCCESS


            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tPreviously sent stop unit\n", Irp));

            //
            // some operations, such as a physical format in progress,
            // should not be ignored and should fail the power operation.
            //

            if (!NT_SUCCESS(status)) {

                PVOID senseBuffer = SrbGetSenseInfoBuffer(srbHeader);

                if (TEST_FLAG(srbHeader->SrbStatus, SRB_STATUS_AUTOSENSE_VALID) &&
                    (senseBuffer != NULL)) {

                    BOOLEAN validSense = FALSE;
                    UCHAR senseKey = 0;
                    UCHAR additionalSenseCode = 0;
                    UCHAR additionalSenseCodeQualifier = 0;

                    validSense = ScsiGetSenseKeyAndCodes(senseBuffer,
                                                         SrbGetSenseInfoBufferLength(srbHeader),
                                                         SCSI_SENSE_OPTIONS_FIXED_FORMAT_IF_UNKNOWN_FORMAT_INDICATED,
                                                         &senseKey,
                                                         &additionalSenseCode,
                                                         &additionalSenseCodeQualifier);

                    if (validSense) {
                        if ((senseKey == SCSI_SENSE_NOT_READY) &&
                            (additionalSenseCode == SCSI_ADSENSE_LUN_NOT_READY) &&
                            (additionalSenseCodeQualifier == SCSI_SENSEQ_FORMAT_IN_PROGRESS)) {

                            ignoreError = FALSE;
                            PowerContext->FinalStatus = STATUS_DEVICE_BUSY;
                            status = PowerContext->FinalStatus;
                        }
                    }
                }
            }

            if (NT_SUCCESS(status) || ignoreError) {

                //
                // Issue the original power request to the lower driver.
                //

                IoCopyCurrentIrpStackLocationToNext(OriginalIrp);

                IoSetCompletionRoutine(OriginalIrp,
                                       ClasspPowerDownCompletion,
                                       PowerContext,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                status = PoCallDriver(commonExtension->LowerDeviceObject, OriginalIrp);

                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tPoCallDriver returned %lx\n", OriginalIrp, status));
                break;
            }

            // else fall through w/o sending the power irp, since the device
            // is reporting an error that would be "really bad" to power down
            // during.

        }

        case PowerDownDeviceOff3: {

            //
            // SpinDown request completed ... whether it succeeded or not is
            // another matter entirely.
            //

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tPreviously sent power irp\n", OriginalIrp));

            if (PowerContext->QueueLocked) {

                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tUnlocking queue\n", OriginalIrp));

                if (fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
                    //
                    // Will reuse SRB for a non-SCSI SRB.
                    //
                    status = InitializeStorageRequestBlock((PSTORAGE_REQUEST_BLOCK)srbHeader,
                                                           STORAGE_ADDRESS_TYPE_BTL8,
                                                           CLASS_SRBEX_NO_SRBEX_DATA_BUFFER_SIZE,
                                                           0);
                    if (NT_SUCCESS(status)) {
                        ((PSTORAGE_REQUEST_BLOCK)srbHeader)->SrbFunction = SRB_FUNCTION_UNLOCK_QUEUE;

                        //
                        // Set length field in Power Context SRB so we know legacy SRB is not being used.
                        //
                        PowerContext->Srb.Length = 0;

                    } else {
                        //
                        // Should not occur. Revert to legacy SRB.
                        //
                        NT_ASSERT(FALSE);
                        srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(PowerContext->Srb);
                        RtlZeroMemory(srbHeader, sizeof(SCSI_REQUEST_BLOCK));
                        srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
                        srbHeader->Function = SRB_FUNCTION_UNLOCK_QUEUE;
                    }
                } else {
                    RtlZeroMemory(srbHeader, sizeof(SCSI_REQUEST_BLOCK));
                    srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
                    srbHeader->Function = SRB_FUNCTION_UNLOCK_QUEUE;
                }

                SrbSetOriginalRequest(srbHeader, fdoExtension->PrivateFdoData->PowerProcessIrp);
                SrbAssignSrbFlags(srbHeader, (SRB_FLAGS_BYPASS_LOCKED_QUEUE |
                                              SRB_FLAGS_D3_PROCESSING));

                nextStack->Parameters.Scsi.Srb = (PSCSI_REQUEST_BLOCK)srbHeader;
                nextStack->MajorFunction = IRP_MJ_SCSI;

                IoSetCompletionRoutine(fdoExtension->PrivateFdoData->PowerProcessIrp,
                                       ClasspPowerDownCompletion,
                                       PowerContext,
                                       TRUE,
                                       TRUE,
                                       TRUE);

                status = IoCallDriver(commonExtension->LowerDeviceObject, fdoExtension->PrivateFdoData->PowerProcessIrp);
                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tIoCallDriver returned %lx\n",
                            fdoExtension->PrivateFdoData->PowerProcessIrp,
                            status));
                break;
            }

        }

        case PowerDownDeviceUnlocked3: {

            //
            // This is the end of the dance.
            // We're ignoring possible intermediate error conditions ....
            //

            if (PowerContext->QueueLocked == FALSE) {
                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tFall through (queue not locked)\n", OriginalIrp));
            } else {
                TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tPreviously unlocked queue\n", OriginalIrp));
                NT_ASSERT(NT_SUCCESS(Irp->IoStatus.Status));
                NT_ASSERT(srbHeader->SrbStatus == SRB_STATUS_SUCCESS);

                if (NT_SUCCESS(Irp->IoStatus.Status)) {
                    PowerContext->QueueLocked = FALSE;
                }
            }

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tFreeing srb and completing\n", OriginalIrp));
            status = PowerContext->FinalStatus; // allow failure to propogate

            OriginalIrp->IoStatus.Status = status;
            OriginalIrp->IoStatus.Information = 0;

            if (NT_SUCCESS(status)) {

                //
                // Set the new power state
                //

                fdoExtension->DevicePowerState =
                    currentStack->Parameters.Power.State.DeviceState;

            }

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tStarting next power irp\n", OriginalIrp));

            ClassReleaseRemoveLock(PowerContext->DeviceObject, OriginalIrp);

            PowerContext->InUse = FALSE;

            PoStartNextPowerIrp(OriginalIrp);

            fdoExtension->PowerDownInProgress = FALSE;

            // prevent from completing the irp allocated by ourselves
            if (Irp == fdoExtension->PrivateFdoData->PowerProcessIrp) {
                // complete original irp if we are processing powerprocess irp,
                // otherwise, by returning status other than STATUS_MORE_PROCESSING_REQUIRED, IO manager will complete it.
                ClassCompleteRequest(commonExtension->DeviceObject, OriginalIrp, IO_NO_INCREMENT);
                status = STATUS_MORE_PROCESSING_REQUIRED;
            }

            return status;
        }
    }

    return STATUS_MORE_PROCESSING_REQUIRED;
} // end ClasspPowerDownCompletion()

/*++////////////////////////////////////////////////////////////////////////////

ClasspPowerHandler()

Routine Description:

    This routine reduces the number of useless spinups and spindown requests
    sent to a given device by ignoring transitions to power states we are
    currently in.

    ISSUE-2000/02/20-henrygab - by ignoring spin-up requests, we may be
          allowing the drive

Arguments:

    DeviceObject - the device object which is transitioning power states
    Irp - the power irp
    Options - a set of flags indicating what the device handles

Return Value:

--*/
NTSTATUS
ClasspPowerHandler(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN CLASS_POWER_OPTIONS Options  // ISSUE-2000/02/20-henrygab - pass pointer, not whole struct
    )
{
    PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
    PDEVICE_OBJECT lowerDevice = commonExtension->LowerDeviceObject;
    PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
    PIO_STACK_LOCATION nextIrpStack;
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
    PCLASS_POWER_CONTEXT context;
    PSTORAGE_REQUEST_BLOCK_HEADER srbHeader;
    ULONG srbFlags;
    NTSTATUS status;

    _Analysis_assume_(fdoExtension);
    _Analysis_assume_(fdoExtension->PrivateFdoData);

    TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "ClasspPowerHandler: Power irp %p to %s %p\n",
                Irp, (commonExtension->IsFdo ? "fdo" : "pdo"), DeviceObject));

    if (!commonExtension->IsFdo) {

        //
        // certain assumptions are made here,
        // particularly: having the fdoExtension
        //

        TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_POWER, "ClasspPowerHandler: Called for PDO %p???\n",
                    DeviceObject));
        NT_ASSERT(!"PDO using ClasspPowerHandler");

        ClassReleaseRemoveLock(DeviceObject, Irp);
        Irp->IoStatus.Status = STATUS_NOT_SUPPORTED;
        PoStartNextPowerIrp(Irp);
        ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
        return STATUS_NOT_SUPPORTED;
    }

    switch (irpStack->MinorFunction) {

        case IRP_MN_SET_POWER: {
            PCLASS_PRIVATE_FDO_DATA fdoData = fdoExtension->PrivateFdoData;

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tIRP_MN_SET_POWER\n", Irp));

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tSetting %s state to %d\n",
                        Irp,
                        (irpStack->Parameters.Power.Type == SystemPowerState ?
                            "System" : "Device"),
                        irpStack->Parameters.Power.State.SystemState));

            switch (irpStack->Parameters.Power.ShutdownType){

                case PowerActionNone:

                    //
                    // Skip if device doesn't need volume verification during idle power
                    // transitions.
                    //
                    if ((fdoExtension->FunctionSupportInfo) &&
                        (fdoExtension->FunctionSupportInfo->IdlePower.NoVerifyDuringIdlePower)) {
                        break;
                    }

                case PowerActionSleep:
                case PowerActionHibernate:
                    if (fdoData->HotplugInfo.MediaRemovable || fdoData->HotplugInfo.MediaHotplug) {
                        /*
                            *  We are suspending device and this drive is either hot-pluggable
                            *  or contains removeable media.
                            *  Set the media dirty bit, since the media may change while
                            *  we are suspended.
                            */
                        SET_FLAG(DeviceObject->Flags, DO_VERIFY_VOLUME);

                        //
                        // Bumping the media  change count  will force the
                        // file system to verify the volume when we resume
                        //

                        InterlockedIncrement((volatile LONG *)&fdoExtension->MediaChangeCount);
                    }

                    break;
                }

            break;
        }

        default: {

            TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tIrp minor code = %#x\n",
                        Irp, irpStack->MinorFunction));
            break;
        }
    }

    if (irpStack->Parameters.Power.Type != DevicePowerState ||
        irpStack->MinorFunction != IRP_MN_SET_POWER) {

        TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tSending to lower device\n", Irp));

        goto ClasspPowerHandlerCleanup;

    }

    //
    // already in exact same state, don't work to transition to it.
    //

    if (irpStack->Parameters.Power.State.DeviceState ==
        fdoExtension->DevicePowerState) {

        TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tAlready in device state %x\n",
                    Irp, fdoExtension->DevicePowerState));
        goto ClasspPowerHandlerCleanup;

    }

    //
    // or powering down from non-d0 state (device already stopped)
    // NOTE -- we're not sure whether this case can exist or not (the
    // power system may never send this sort of request) but it's trivial
    // to deal with.
    //

    if ((irpStack->Parameters.Power.State.DeviceState != PowerDeviceD0) &&
        (fdoExtension->DevicePowerState != PowerDeviceD0)) {
        TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tAlready powered down to %x???\n",
                    Irp, fdoExtension->DevicePowerState));
        fdoExtension->DevicePowerState =
            irpStack->Parameters.Power.State.DeviceState;
        goto ClasspPowerHandlerCleanup;
    }

    //
    // or when not handling powering up and are powering up
    //

    if ((!Options.HandleSpinUp) &&
        (irpStack->Parameters.Power.State.DeviceState == PowerDeviceD0)) {

        TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tNot handling spinup to state %x\n",
                    Irp, fdoExtension->DevicePowerState));
        fdoExtension->DevicePowerState =
            irpStack->Parameters.Power.State.DeviceState;
        goto ClasspPowerHandlerCleanup;

    }

    //
    // or when not handling powering down and are powering down
    //

    if ((!Options.HandleSpinDown) &&
        (irpStack->Parameters.Power.State.DeviceState != PowerDeviceD0)) {

        TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tNot handling spindown to state %x\n",
                    Irp, fdoExtension->DevicePowerState));
        fdoExtension->DevicePowerState =
            irpStack->Parameters.Power.State.DeviceState;
        goto ClasspPowerHandlerCleanup;

    }

    //
    // validation completed, start the real work.
    //

    IoReuseIrp(fdoExtension->PrivateFdoData->PowerProcessIrp, STATUS_SUCCESS);
    IoSetNextIrpStackLocation(fdoExtension->PrivateFdoData->PowerProcessIrp);
    nextIrpStack = IoGetNextIrpStackLocation(fdoExtension->PrivateFdoData->PowerProcessIrp);

    context = &(fdoExtension->PowerContext);

    NT_ASSERT(context->InUse == FALSE);

    RtlZeroMemory(context, sizeof(CLASS_POWER_CONTEXT));
    context->InUse = TRUE;

    if (fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
        srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(fdoExtension->PrivateFdoData->PowerSrb.SrbEx);

        //
        // Initialize extended SRB for a SRB_FUNCTION_LOCK_QUEUE
        //
        status = InitializeStorageRequestBlock((PSTORAGE_REQUEST_BLOCK)srbHeader,
                                               STORAGE_ADDRESS_TYPE_BTL8,
                                               CLASS_SRBEX_NO_SRBEX_DATA_BUFFER_SIZE,
                                               0);
        if (NT_SUCCESS(status)) {
            ((PSTORAGE_REQUEST_BLOCK)srbHeader)->SrbFunction = SRB_FUNCTION_LOCK_QUEUE;
        } else {
            //
            // Should not happen. Revert to legacy SRB.
            //
            NT_ASSERT(FALSE);
            srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(context->Srb);
            srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
            srbHeader->Function = SRB_FUNCTION_LOCK_QUEUE;
        }
    } else {
        srbHeader = (PSTORAGE_REQUEST_BLOCK_HEADER)&(context->Srb);
        srbHeader->Length = sizeof(SCSI_REQUEST_BLOCK);
        srbHeader->Function = SRB_FUNCTION_LOCK_QUEUE;
    }
    nextIrpStack->Parameters.Scsi.Srb = (PSCSI_REQUEST_BLOCK)srbHeader;
    nextIrpStack->MajorFunction = IRP_MJ_SCSI;

    context->FinalStatus = STATUS_SUCCESS;

    SrbSetOriginalRequest(srbHeader, fdoExtension->PrivateFdoData->PowerProcessIrp);
    SrbSetSrbFlags(srbHeader, (SRB_FLAGS_BYPASS_LOCKED_QUEUE | SRB_FLAGS_NO_QUEUE_FREEZE));

    fdoExtension->PrivateFdoData->MaxPowerOperationRetryCount = MAXIMUM_RETRIES;
    context->RetryCount = MAXIMUM_RETRIES;

    context->Options = Options;
    context->DeviceObject = DeviceObject;
    context->Irp = Irp;

    if (irpStack->Parameters.Power.State.DeviceState == PowerDeviceD0) {

        NT_ASSERT(Options.HandleSpinUp);

        TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tpower up - locking queue\n", Irp));

        //
        // We need to issue a queue lock request so that we
        // can spin the drive back up after the power is restored
        // but before any requests are processed.
        //

        context->Options.PowerDown = FALSE;
        context->PowerChangeState.PowerUp = PowerUpDeviceInitial;
        context->CompletionRoutine = ClasspPowerUpCompletion;

    } else {

        NT_ASSERT(Options.HandleSpinDown);

        fdoExtension->PowerDownInProgress = TRUE;

        TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tPowering down - locking queue\n", Irp));

        //
        // Disable tick timer at beginning of D3 processing if running.
        //
        if ((fdoExtension->PrivateFdoData->TickTimerEnabled)) {
            ClasspDisableTimer(fdoExtension);
        }

        PoSetPowerState(DeviceObject,
                        irpStack->Parameters.Power.Type,
                        irpStack->Parameters.Power.State);

        context->Options.PowerDown = TRUE;
        context->PowerChangeState.PowerDown3 = PowerDownDeviceInitial3;
        context->CompletionRoutine = ClasspPowerDownCompletion;

    }

    //
    // we are not dealing with port-allocated sense in these routines.
    //

    srbFlags = SrbGetSrbFlags(srbHeader);
    NT_ASSERT(!TEST_FLAG(srbFlags, SRB_FLAGS_FREE_SENSE_BUFFER));
    NT_ASSERT(!TEST_FLAG(srbFlags, SRB_FLAGS_PORT_DRIVER_ALLOCSENSE));

    //
    // Mark the original power irp pending.
    //

    IoMarkIrpPending(Irp);

    if (Options.LockQueue) {

        //
        // Send the lock irp down.
        //

        IoSetCompletionRoutine(fdoExtension->PrivateFdoData->PowerProcessIrp,
                               context->CompletionRoutine,
                               context,
                               TRUE,
                               TRUE,
                               TRUE);

        IoCallDriver(lowerDevice, fdoExtension->PrivateFdoData->PowerProcessIrp);

    } else {

        //
        // Call the completion routine directly.  It won't care what the
        // status of the "lock" was - it will just go and do the next
        // step of the operation.
        //

        context->CompletionRoutine(DeviceObject, fdoExtension->PrivateFdoData->PowerProcessIrp, context);
    }

    return STATUS_PENDING;

ClasspPowerHandlerCleanup:

    //
    // Send the original power irp down, we will start the next power irp in completion routine.
    //
    ClassReleaseRemoveLock(DeviceObject, Irp);

    TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tStarting next power irp\n", Irp));
    IoCopyCurrentIrpStackLocationToNext(Irp);
    IoSetCompletionRoutine(Irp,
                           ClasspStartNextPowerIrpCompletion,
                           NULL,
                           TRUE,
                           TRUE,
                           TRUE);
    return PoCallDriver(lowerDevice, Irp);
} // end ClasspPowerHandler()

/*++////////////////////////////////////////////////////////////////////////////

ClassMinimalPowerHandler()

Routine Description:

    This routine is the minimum power handler for a storage driver.  It does
    the least amount of work possible.

--*/
NTSTATUS
ClassMinimalPowerHandler(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp
    )
{
    PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
    PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
    NTSTATUS status;

    ClassReleaseRemoveLock(DeviceObject, Irp);
    PoStartNextPowerIrp(Irp);

    switch (irpStack->MinorFunction)
    {
        case IRP_MN_SET_POWER:
        {
            switch (irpStack->Parameters.Power.ShutdownType)
            {
                case PowerActionNone:
                case PowerActionSleep:
                case PowerActionHibernate:
                {
                    if (TEST_FLAG(DeviceObject->Characteristics, FILE_REMOVABLE_MEDIA))
                    {
                        if ((ClassGetVpb(DeviceObject) != NULL) && (ClassGetVpb(DeviceObject)->Flags & VPB_MOUNTED))
                        {
                            //
                            // This flag will cause the filesystem to verify the
                            // volume when coming out of hibernation or standby or runtime power
                            //
                            SET_FLAG(DeviceObject->Flags, DO_VERIFY_VOLUME);
                        }
                    }
                }
                break;
            }
        }

        //
        // Fall through
        //

        case IRP_MN_QUERY_POWER:
        {
            if (!commonExtension->IsFdo)
            {
                Irp->IoStatus.Status = STATUS_SUCCESS;
                Irp->IoStatus.Information = 0;
            }
        }
        break;
    }

    if (commonExtension->IsFdo)
    {
        IoCopyCurrentIrpStackLocationToNext(Irp);
        status = PoCallDriver(commonExtension->LowerDeviceObject, Irp);
    }
    else
    {
        status = Irp->IoStatus.Status;
        ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
    }

    return status;
} // end ClassMinimalPowerHandler()

/*++////////////////////////////////////////////////////////////////////////////

ClassSpinDownPowerHandler()

Routine Description:

    This routine is a callback for disks and other things which require both
    a start and a stop to be sent to the device.  (actually the starts are
    almost always optional, since most device power themselves on to process
    commands, but i digress).

    Determines proper use of spinup, spindown, and queue locking based upon
    ScanForSpecialFlags in the FdoExtension.  This is the most common power
    handler passed into classpnp.sys

Arguments:

    DeviceObject - Supplies the functional device object

    Irp - Supplies the request to be retried.

Return Value:

    None

--*/
__control_entrypoint(DeviceDriver)
NTSTATUS
ClassSpinDownPowerHandler(
    _In_ PDEVICE_OBJECT DeviceObject,
    _In_ PIRP Irp
    )
{
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
    CLASS_POWER_OPTIONS options = {0};

    fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;

    //
    // check the flags to see what options we need to worry about
    //

    if (!TEST_FLAG(fdoExtension->ScanForSpecialFlags,
                  CLASS_SPECIAL_DISABLE_SPIN_DOWN)) {
        options.HandleSpinDown = TRUE;
    }

    if (!TEST_FLAG(fdoExtension->ScanForSpecialFlags,
                  CLASS_SPECIAL_DISABLE_SPIN_UP)) {
        options.HandleSpinUp = TRUE;
    }

    if (!TEST_FLAG(fdoExtension->ScanForSpecialFlags,
                  CLASS_SPECIAL_NO_QUEUE_LOCK)) {
        options.LockQueue = TRUE;
    }

    TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "ClasspPowerHandler: Devobj %p\n"
                "\t%shandling spin down\n"
                "\t%shandling spin up\n"
                "\t%slocking queue\n",
                DeviceObject,
                (options.HandleSpinDown ? "" : "not "),
                (options.HandleSpinUp   ? "" : "not "),
                (options.LockQueue      ? "" : "not ")
                ));

    //
    // do all the dirty work
    //

    return ClasspPowerHandler(DeviceObject, Irp, options);
} // end ClassSpinDownPowerHandler()

/*++////////////////////////////////////////////////////////////////////////////

ClassStopUnitPowerHandler()

Routine Description:

    This routine is an outdated call.  To achieve equivalent functionality,
    the driver should set the following flags in ScanForSpecialFlags in the
    FdoExtension:

        CLASS_SPECIAL_DISABLE_SPIN_UP
        CLASS_SPECIAL_NO_QUEUE_LOCK

--*/
NTSTATUS
ClassStopUnitPowerHandler(
    _In_ PDEVICE_OBJECT DeviceObject,
    _In_ PIRP Irp
    )
{
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;

    TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_POWER, "ClassStopUnitPowerHandler - Devobj %p using outdated call\n"
                "Drivers should set the following flags in ScanForSpecialFlags "
                " in the FDO extension:\n"
                "\tCLASS_SPECIAL_DISABLE_SPIN_UP\n"
                "\tCLASS_SPECIAL_NO_QUEUE_LOCK\n"
                "This will provide equivalent functionality if the power "
                "routine is then set to ClassSpinDownPowerHandler\n\n",
                DeviceObject));

    fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;

    SET_FLAG(fdoExtension->ScanForSpecialFlags,
             CLASS_SPECIAL_DISABLE_SPIN_UP);
    SET_FLAG(fdoExtension->ScanForSpecialFlags,
             CLASS_SPECIAL_NO_QUEUE_LOCK);

    return ClassSpinDownPowerHandler(DeviceObject, Irp);
} // end ClassStopUnitPowerHandler()

/*++////////////////////////////////////////////////////////////////////////////

RetryPowerRequest()

Routine Description:

    This routine reinitalizes the necessary fields, and sends the request
    to the lower driver.

Arguments:

    DeviceObject - Supplies the device object associated with this request.

    Irp - Supplies the request to be retried.

    Context - Supplies a pointer to the power up context for this request.

Return Value:

    None

--*/
VOID
RetryPowerRequest(
    PDEVICE_OBJECT DeviceObject,
    PIRP Irp,
    PCLASS_POWER_CONTEXT Context
    )
{
    PIO_STACK_LOCATION nextIrpStack = IoGetNextIrpStackLocation(Irp);
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension =
        (PFUNCTIONAL_DEVICE_EXTENSION)Context->DeviceObject->DeviceExtension;
    PSTORAGE_REQUEST_BLOCK_HEADER srb;
    LONGLONG dueTime;
    ULONG srbFlags;
    ULONG srbFunction;

    TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tDelaying retry by queueing DPC\n", Irp));

    //NT_ASSERT(Context->Irp == Irp);
    if (fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
        srb = (PSTORAGE_REQUEST_BLOCK_HEADER)&(fdoExtension->PrivateFdoData->PowerSrb.SrbEx);

        //
        // Check if reverted to using legacy SRB.
        //
        if (Context->Srb.Length == sizeof(SCSI_REQUEST_BLOCK)) {
            srb = (PSTORAGE_REQUEST_BLOCK_HEADER)&(Context->Srb);
            srbFunction = srb->Function;
        } else {
            srbFunction = ((PSTORAGE_REQUEST_BLOCK)srb)->SrbFunction;
        }
    } else {
        srb = (PSTORAGE_REQUEST_BLOCK_HEADER)&(Context->Srb);
        srbFunction = srb->Function;
    }

    NT_ASSERT(Context->DeviceObject == DeviceObject);
    srbFlags = SrbGetSrbFlags(srb);
    NT_ASSERT(!TEST_FLAG(srbFlags, SRB_FLAGS_FREE_SENSE_BUFFER));
    NT_ASSERT(!TEST_FLAG(srbFlags, SRB_FLAGS_PORT_DRIVER_ALLOCSENSE));

    if (Context->RetryInterval == 0) {

        TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tDelaying minimum time (.2 sec)\n", Irp));
        dueTime = (LONGLONG)1000000 * 2;

    } else {

        TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER, "(%p)\tDelaying %x seconds\n",
                    Irp, Context->RetryInterval));
        dueTime = (LONGLONG)1000000 * 10 * Context->RetryInterval;

    }

    //
    // reset the retry interval
    //

    Context->RetryInterval = 0;

    //
    // Reset byte count of transfer in SRB Extension.
    //

    SrbSetDataTransferLength(srb, 0);

    //
    // Zero SRB statuses.
    //

    srb->SrbStatus = 0;
    if (srbFunction == SRB_FUNCTION_EXECUTE_SCSI) {
        SrbSetScsiStatus(srb, 0);
    }

    //
    // Set up major SCSI function.
    //

    nextIrpStack->MajorFunction = IRP_MJ_SCSI;

    //
    // Save SRB address in next stack for port driver.
    //

    nextIrpStack->Parameters.Scsi.Srb = (PSCSI_REQUEST_BLOCK)srb;

    //
    // Set the completion routine up again.
    //

    IoSetCompletionRoutine(Irp, Context->CompletionRoutine, Context,
                           TRUE, TRUE, TRUE);

    ClassRetryRequest(DeviceObject, Irp, dueTime);

    return;

} // end RetryRequest()

/*++////////////////////////////////////////////////////////////////////////////

ClasspStartNextPowerIrpCompletion()

Routine Description:

    This routine guarantees that the next power irp (power up or down) is not
    sent until the previous one has fully completed.

--*/
NTSTATUS
ClasspStartNextPowerIrpCompletion(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )
{
    PCLASS_POWER_CONTEXT PowerContext = (PCLASS_POWER_CONTEXT)Context;

    UNREFERENCED_PARAMETER(DeviceObject);

    if (Irp->PendingReturned) {
        IoMarkIrpPending(Irp);
    }

    if (PowerContext != NULL)
    {
        PowerContext->InUse = FALSE;
    }


    PoStartNextPowerIrp(Irp);
    return STATUS_SUCCESS;
} // end ClasspStartNextPowerIrpCompletion()

NTSTATUS
ClasspDeviceLockFailurePowerIrpCompletion(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )
{
    PCLASS_POWER_CONTEXT PowerContext = (PCLASS_POWER_CONTEXT)Context;
    PCOMMON_DEVICE_EXTENSION commonExtension;
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
    PIO_STACK_LOCATION currentStack;
    BOOLEAN FailurePredictionEnabled = FALSE;

    UNREFERENCED_PARAMETER(DeviceObject);

    commonExtension = PowerContext->DeviceObject->DeviceExtension;
    fdoExtension = PowerContext->DeviceObject->DeviceExtension;

    currentStack = IoGetCurrentIrpStackLocation(Irp);

    //
    // Set the new power state
    //

    fdoExtension->DevicePowerState = currentStack->Parameters.Power.State.DeviceState;

    //
    // We reach here becasue LockQueue operation was not successful.
    // However, media change detection would not happen in case of resume becasue we 
    // had disabled the timer while going into lower power state. 
    // So, if the device goes into D0 then enable the tick timer. 
    //

    if (fdoExtension->DevicePowerState == PowerDeviceD0) {
        //
        // Check whether failure detection is enabled
        //

        if ((fdoExtension->FailurePredictionInfo != NULL) &&
            (fdoExtension->FailurePredictionInfo->Method != FailurePredictionNone)) {
             FailurePredictionEnabled = TRUE;
        }

        //
        // Enable tick timer at end of D0 processing if it was previously enabled.
        //

        if ((commonExtension->DriverExtension->InitData.ClassTick != NULL) ||
            ((fdoExtension->MediaChangeDetectionInfo != NULL) &&
             (fdoExtension->FunctionSupportInfo != NULL) &&
             (fdoExtension->FunctionSupportInfo->AsynchronousNotificationSupported == FALSE)) ||
            (FailurePredictionEnabled)) {

            //
            // If failure prediction is turned on and we've been powered
            // off longer than the failure prediction query period then
            // force the query on the next timer tick.
            //

            if ((FailurePredictionEnabled) && (ClasspFailurePredictionPeriodMissed(fdoExtension))) {
                 fdoExtension->FailurePredictionInfo->CountDown = 1;
            }

            //
            // Finally, enable the timer.
            //

            ClasspEnableTimer(fdoExtension);
        }
    }

    //
    // Indicate to Po that we've been successfully powered up so
    // it can do it's notification stuff.
    //

    PoSetPowerState(PowerContext->DeviceObject,
                    currentStack->Parameters.Power.Type,
                    currentStack->Parameters.Power.State);

    PowerContext->InUse = FALSE;


    ClassReleaseRemoveLock(commonExtension->DeviceObject, Irp);

    //
    // Start the next power IRP
    //

    if (Irp->PendingReturned) {
        IoMarkIrpPending(Irp);
    }

    PoStartNextPowerIrp(Irp);

    return STATUS_SUCCESS;
}


_IRQL_requires_same_
NTSTATUS
ClasspSendEnableIdlePowerIoctl(
    _In_ PDEVICE_OBJECT DeviceObject
    )
/*++
Description:

    This function is used to send IOCTL_STORAGE_ENABLE_IDLE_POWER to the port
    driver.  It pulls the relevant idle power management properties from the
    FDO's device extension.

Arguments:

    DeviceObject - The class FDO.

Return Value:

    The NTSTATUS code returned from the port driver.  STATUS_SUCCESS indicates
    this device is now enabled for idle (runtime) power management.

--*/
{
    NTSTATUS status;
    STORAGE_IDLE_POWER idlePower = {0};
    IO_STATUS_BLOCK ioStatus = {0};
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
    PCOMMON_DEVICE_EXTENSION commonExtension = &(fdoExtension->CommonExtension);

    idlePower.Version = 1;
    idlePower.Size = sizeof(STORAGE_IDLE_POWER);
    idlePower.WakeCapableHint = fdoExtension->FunctionSupportInfo->IdlePower.DeviceWakeable;
    idlePower.D3ColdSupported = fdoExtension->FunctionSupportInfo->IdlePower.D3ColdSupported;
    idlePower.D3IdleTimeout = fdoExtension->FunctionSupportInfo->IdlePower.D3IdleTimeout;

    ClassSendDeviceIoControlSynchronous(
        IOCTL_STORAGE_ENABLE_IDLE_POWER,
        commonExtension->LowerDeviceObject,
        &idlePower,
        sizeof(STORAGE_IDLE_POWER),
        0,
        FALSE,
        &ioStatus
        );

    status = ioStatus.Status;

    TracePrint((TRACE_LEVEL_INFORMATION,
                TRACE_FLAG_POWER,
                "ClasspSendEnableIdlePowerIoctl: Port driver returned status (%x) for FDO (%p)\n"
                "\tWakeCapableHint: %u\n"
                "\tD3ColdSupported: %u\n"
                "\tD3IdleTimeout: %u (ms)",
                status,
                DeviceObject,
                idlePower.WakeCapableHint,
                idlePower.D3ColdSupported,
                idlePower.D3IdleTimeout));

    return status;
}

_Function_class_(POWER_SETTING_CALLBACK)
_IRQL_requires_same_
NTSTATUS
ClasspPowerSettingCallback(
    _In_ LPCGUID SettingGuid,
    _In_reads_bytes_(ValueLength) PVOID Value,
    _In_ ULONG ValueLength,
    _Inout_opt_ PVOID Context
)
/*++
Description:

    This function is the callback for power setting notifications (registered
    when ClasspGetD3IdleTimeout() is called for the first time).

    Currently, this function is used to get the disk idle timeout value from
    the system power settings.

    This function is guaranteed to be called at PASSIVE_LEVEL.

Arguments:

    SettingGuid - The power setting GUID.
    Value - Pointer to the power setting value.
    ValueLength - Size of the Value buffer.
    Context - The FDO's device extension.

Return Value:

    STATUS_SUCCESS

--*/
{    
    PIDLE_POWER_FDO_LIST_ENTRY fdoEntry = NULL;

#pragma warning(suppress:4054) // okay to type cast function pointer to PIRP for this use case
    PIRP removeLockTag = (PIRP)&ClasspPowerSettingCallback;

    UNREFERENCED_PARAMETER(Context);

    PAGED_CODE();

    if (IsEqualGUID(SettingGuid, &GUID_DISK_IDLE_TIMEOUT)) {
        if (ValueLength != sizeof(ULONG) || Value == NULL) {
            return STATUS_INVALID_PARAMETER;
        }

        //
        // The value supplied by this GUID is already in milliseconds.
        //
        DiskIdleTimeoutInMS = *((PULONG)Value);

        //
        // For each FDO on the idle power list, grab the remove lock and send
        // IOCTL_STORAGE_ENABLE_IDLE_POWER to the port driver to update the
        // idle timeout value.
        //
        KeAcquireGuardedMutex(&IdlePowerFDOListMutex);
        fdoEntry = (PIDLE_POWER_FDO_LIST_ENTRY)IdlePowerFDOList.Flink;
        while ((PLIST_ENTRY)fdoEntry != &IdlePowerFDOList) {

            ULONG isRemoved = ClassAcquireRemoveLock(fdoEntry->Fdo, removeLockTag);

            if (!isRemoved) {
                PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)fdoEntry->Fdo->DeviceExtension;

                //
                // Apply the new timeout if the user hasn't overridden it via the registry.
                //
                if (!fdoExtension->FunctionSupportInfo->IdlePower.D3IdleTimeoutOverridden) {
                    fdoExtension->FunctionSupportInfo->IdlePower.D3IdleTimeout = DiskIdleTimeoutInMS;
                    ClasspSendEnableIdlePowerIoctl(fdoEntry->Fdo);
                }
            }

            ClassReleaseRemoveLock(fdoEntry->Fdo, removeLockTag);

            fdoEntry = (PIDLE_POWER_FDO_LIST_ENTRY)fdoEntry->ListEntry.Flink;
        }
        KeReleaseGuardedMutex(&IdlePowerFDOListMutex);

    } else if (IsEqualGUID(SettingGuid, &GUID_CONSOLE_DISPLAY_STATE)) {

        //
        // If monitor is off, change media change requests to not
        // keep device active. This allows removable media devices to
        // go to sleep if there are no other active requests. Otherwise,
        // let media change requests keep the device active.
        //
        if ((ValueLength == sizeof(ULONG)) && (Value != NULL)) {
            if (*((PULONG)Value) == PowerMonitorOff) {
                ClasspScreenOff = TRUE;
            } else {
                ClasspScreenOff = FALSE;
            }
                
            KeAcquireGuardedMutex(&IdlePowerFDOListMutex);
            fdoEntry = (PIDLE_POWER_FDO_LIST_ENTRY)IdlePowerFDOList.Flink;
            while ((PLIST_ENTRY)fdoEntry != &IdlePowerFDOList) {

                ULONG isRemoved = ClassAcquireRemoveLock(fdoEntry->Fdo, removeLockTag);
                if (!isRemoved) {
                    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)fdoEntry->Fdo->DeviceExtension;

                    if (ClasspScreenOff == FALSE) {
                        //
                        // Now that the screen is on, we may need to check for media
                        // for devices that are not in D0 and may have removable media.
                        // This is because the media change polling has been disabled
                        // for devices in D3 and now that the screen is on the user may
                        // have inserted some media that they want to interact with.
                        //
                        if ((fdoExtension->DevicePowerState != PowerDeviceD0) &&
                            (fdoExtension->MediaChangeDetectionInfo != NULL) &&
                            (fdoExtension->FunctionSupportInfo->AsynchronousNotificationSupported == FALSE)) {
                            ClassCheckMediaState(fdoExtension);
                        }

                        //
                        // We disabled failure prediction polling during screen-off
                        // so now check to see if we missed a failure prediction
                        // period and if so, force the IOCTL to be sent now.
                        //
                        if ((fdoExtension->FailurePredictionInfo != NULL) &&
                            (fdoExtension->FailurePredictionInfo->Method != FailurePredictionNone)) {
                            if (ClasspFailurePredictionPeriodMissed(fdoExtension)) {
                                fdoExtension->FailurePredictionInfo->CountDown = 1;
                            }
                        }
                    }
                    
#if (NTDDI_VERSION >= NTDDI_WINBLUE)
                    //
                    // Screen state has changed so attempt to update the tick
                    // timer's no-wake tolerance accordingly.
                    //
                    ClasspUpdateTimerNoWakeTolerance(fdoExtension);
#endif
                }
                ClassReleaseRemoveLock(fdoEntry->Fdo, removeLockTag);

                fdoEntry = (PIDLE_POWER_FDO_LIST_ENTRY)fdoEntry->ListEntry.Flink;
            }
            KeReleaseGuardedMutex(&IdlePowerFDOListMutex);                
        }

    }

    return STATUS_SUCCESS;
}


_IRQL_requires_same_
NTSTATUS
ClasspEnableIdlePower(
    _In_ PDEVICE_OBJECT DeviceObject
    )
/*++
Description:

    This function is used to enable idle (runtime) power management for the
    device.  It will do the work to determine D3Cold support, idle timeout,
    etc. and then notify the port driver that it wants to enable idle power
    management.

    This function may modify some of the idle power fields in the FDO's device
    extension.

Arguments:

    DeviceObject - The class FDO.

Return Value:

    An NTSTATUS code indicating the status of the operation.

--*/
{
    NTSTATUS status = STATUS_SUCCESS;
    ULONG d3ColdDisabledByUser = FALSE;
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
    ULONG idleTimeoutOverrideInSeconds = 0;

    //
    // This function should only be called once.
    //
    NT_ASSERT(fdoExtension->FunctionSupportInfo->IdlePower.IdlePowerEnabled == FALSE);

    ClassGetDeviceParameter(fdoExtension,
                        CLASSP_REG_SUBKEY_NAME,
                        CLASSP_REG_DISABLE_D3COLD,
                        &d3ColdDisabledByUser);

    //
    // If the device is hot-pluggable or the user has explicitly
    // disabled D3Cold, do not enable D3Cold for this device.
    //
    if (d3ColdDisabledByUser || fdoExtension->PrivateFdoData->HotplugInfo.DeviceHotplug) {
        fdoExtension->FunctionSupportInfo->IdlePower.D3ColdSupported = 0;
    }

    ClassGetDeviceParameter(fdoExtension,
                            CLASSP_REG_SUBKEY_NAME,
                            CLASSP_REG_IDLE_TIMEOUT_IN_SECONDS,
                            &idleTimeoutOverrideInSeconds);

    //
    // Set the idle timeout.  If the user has not specified an override value,
    // this will either be a default value or will have been updated by the
    // power setting notification callback.
    //
    if (idleTimeoutOverrideInSeconds != 0) {
        fdoExtension->FunctionSupportInfo->IdlePower.D3IdleTimeout = (idleTimeoutOverrideInSeconds * 1000);
        fdoExtension->FunctionSupportInfo->IdlePower.D3IdleTimeoutOverridden = TRUE;
    } else {
        fdoExtension->FunctionSupportInfo->IdlePower.D3IdleTimeout = DiskIdleTimeoutInMS;
    }

    //
    // We don't allow disks to be wakeable.
    //
    fdoExtension->FunctionSupportInfo->IdlePower.DeviceWakeable = FALSE;

    //
    // Send IOCTL_STORAGE_ENABLE_IDLE_POWER to the port driver to enable idle
    // power management by the port driver.
    //
    status = ClasspSendEnableIdlePowerIoctl(DeviceObject);

    if (NT_SUCCESS(status)) {
        PIDLE_POWER_FDO_LIST_ENTRY fdoEntry = NULL;

        //
        // Put this FDO on the list of devices that are idle power managed.
        //
        fdoEntry = ExAllocatePoolZero(NonPagedPoolNx, 
                                      sizeof(IDLE_POWER_FDO_LIST_ENTRY), 
                                      CLASS_TAG_POWER);
        if (fdoEntry) {

            fdoExtension->FunctionSupportInfo->IdlePower.IdlePowerEnabled = TRUE;

            fdoEntry->Fdo = DeviceObject;

            KeAcquireGuardedMutex(&IdlePowerFDOListMutex);
            InsertHeadList(&IdlePowerFDOList, &(fdoEntry->ListEntry));
            KeReleaseGuardedMutex(&IdlePowerFDOListMutex);

            //
            // If not registered already, register for disk idle timeout power
            // setting notifications.  The power manager will call our power
            // setting callback very soon to set the idle timeout to the actual
            // value.
            //
            if (PowerSettingNotificationHandle == NULL) {
                PoRegisterPowerSettingCallback(DeviceObject,
                                                &GUID_DISK_IDLE_TIMEOUT,
                                                &ClasspPowerSettingCallback,
                                                NULL,
                                                &(PowerSettingNotificationHandle));
            }
        } else {
            fdoExtension->FunctionSupportInfo->IdlePower.IdlePowerEnabled = FALSE;
            status = STATUS_UNSUCCESSFUL;
        }
    }

    return status;
}