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
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
|
/*++
Copyright (C) Microsoft Corporation, 1991 - 2010
Module Name:
utils.c
Abstract:
SCSI class driver routines
Environment:
kernel mode only
Notes:
Revision History:
--*/
#include "classp.h"
#include "debug.h"
#include <ntiologc.h>
#ifdef DEBUG_USE_WPP
#include "utils.tmh"
#endif
//
// Constant value used in firmware upgrade process.
//
#define FIRMWARE_ACTIVATE_TIMEOUT_VALUE 30
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, ClassGetDeviceParameter)
#pragma alloc_text(PAGE, ClassScanForSpecial)
#pragma alloc_text(PAGE, ClassSetDeviceParameter)
#pragma alloc_text(PAGE, ClasspMyStringMatches)
#pragma alloc_text(PAGE, ClasspDeviceCopyOffloadProperty)
#pragma alloc_text(PAGE, ClasspValidateOffloadSupported)
#pragma alloc_text(PAGE, ClasspValidateOffloadInputParameters)
#endif
// custom string match -- careful!
BOOLEAN ClasspMyStringMatches(_In_opt_z_ PCHAR StringToMatch, _In_z_ PCHAR TargetString)
{
ULONG length; // strlen returns an int, not size_t (!)
PAGED_CODE();
NT_ASSERT(TargetString);
// if no match requested, return TRUE
if (StringToMatch == NULL) {
return TRUE;
}
// cache the string length for efficiency
length = (ULONG)strlen(StringToMatch);
// ZERO-length strings may only match zero-length strings
if (length == 0) {
return (strlen(TargetString) == 0);
}
// strncmp returns zero if the strings match
return (strncmp(StringToMatch, TargetString, length) == 0);
}
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID ClassGetDeviceParameter(
_In_ PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
_In_opt_ PWSTR SubkeyName,
_In_ PWSTR ParameterName,
_Inout_ PULONG ParameterValue // also default value
)
{
NTSTATUS status;
RTL_QUERY_REGISTRY_TABLE queryTable[2] = {0};
HANDLE deviceParameterHandle = NULL;
HANDLE deviceSubkeyHandle = NULL;
ULONG defaultParameterValue;
PAGED_CODE();
//
// open the given parameter
//
status = IoOpenDeviceRegistryKey(FdoExtension->LowerPdo,
PLUGPLAY_REGKEY_DEVICE,
KEY_READ,
&deviceParameterHandle);
if (NT_SUCCESS(status) && (SubkeyName != NULL)) {
UNICODE_STRING subkeyName;
OBJECT_ATTRIBUTES objectAttributes = {0};
RtlInitUnicodeString(&subkeyName, SubkeyName);
InitializeObjectAttributes(&objectAttributes,
&subkeyName,
OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
deviceParameterHandle,
NULL);
status = ZwOpenKey(&deviceSubkeyHandle,
KEY_READ,
&objectAttributes);
if (!NT_SUCCESS(status)) {
ZwClose(deviceParameterHandle);
}
}
if (NT_SUCCESS(status)) {
defaultParameterValue = *ParameterValue;
queryTable->Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_REQUIRED | RTL_QUERY_REGISTRY_TYPECHECK;
queryTable->Name = ParameterName;
queryTable->EntryContext = ParameterValue;
queryTable->DefaultType = (REG_DWORD << RTL_QUERY_REGISTRY_TYPECHECK_SHIFT) | REG_NONE;
queryTable->DefaultData = NULL;
queryTable->DefaultLength = 0;
status = RtlQueryRegistryValues(RTL_REGISTRY_HANDLE,
(PWSTR)(SubkeyName ?
deviceSubkeyHandle :
deviceParameterHandle),
queryTable,
NULL,
NULL);
if (!NT_SUCCESS(status)) {
*ParameterValue = defaultParameterValue; // use default value
}
//
// close what we open
//
if (SubkeyName) {
ZwClose(deviceSubkeyHandle);
}
ZwClose(deviceParameterHandle);
}
if (!NT_SUCCESS(status)) {
//
// Windows 2000 SP3 uses the driver-specific key, so look in there
//
status = IoOpenDeviceRegistryKey(FdoExtension->LowerPdo,
PLUGPLAY_REGKEY_DRIVER,
KEY_READ,
&deviceParameterHandle);
if (NT_SUCCESS(status) && (SubkeyName != NULL)) {
UNICODE_STRING subkeyName;
OBJECT_ATTRIBUTES objectAttributes = {0};
RtlInitUnicodeString(&subkeyName, SubkeyName);
InitializeObjectAttributes(&objectAttributes,
&subkeyName,
OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
deviceParameterHandle,
NULL);
status = ZwOpenKey(&deviceSubkeyHandle, KEY_READ, &objectAttributes);
if (!NT_SUCCESS(status)) {
ZwClose(deviceParameterHandle);
}
}
if (NT_SUCCESS(status)) {
defaultParameterValue = *ParameterValue;
queryTable->Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_REQUIRED | RTL_QUERY_REGISTRY_TYPECHECK;
queryTable->Name = ParameterName;
queryTable->EntryContext = ParameterValue;
queryTable->DefaultType = (REG_DWORD << RTL_QUERY_REGISTRY_TYPECHECK_SHIFT) | REG_NONE;
queryTable->DefaultData = NULL;
queryTable->DefaultLength = 0;
status = RtlQueryRegistryValues(RTL_REGISTRY_HANDLE,
(PWSTR)(SubkeyName ?
deviceSubkeyHandle :
deviceParameterHandle),
queryTable,
NULL,
NULL);
if (NT_SUCCESS(status)) {
//
// Migrate the value over to the device-specific key
//
ClassSetDeviceParameter(FdoExtension, SubkeyName, ParameterName, *ParameterValue);
} else {
//
// Use the default value
//
*ParameterValue = defaultParameterValue;
}
if (SubkeyName) {
ZwClose(deviceSubkeyHandle);
}
ZwClose(deviceParameterHandle);
}
}
return;
} // end ClassGetDeviceParameter()
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS ClassSetDeviceParameter(
_In_ PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
_In_opt_ PWSTR SubkeyName,
_In_ PWSTR ParameterName,
_In_ ULONG ParameterValue)
{
NTSTATUS status;
HANDLE deviceParameterHandle = NULL;
HANDLE deviceSubkeyHandle = NULL;
PAGED_CODE();
//
// open the given parameter
//
status = IoOpenDeviceRegistryKey(FdoExtension->LowerPdo,
PLUGPLAY_REGKEY_DEVICE,
KEY_READ | KEY_WRITE,
&deviceParameterHandle);
if (NT_SUCCESS(status) && (SubkeyName != NULL)) {
UNICODE_STRING subkeyName;
OBJECT_ATTRIBUTES objectAttributes;
RtlInitUnicodeString(&subkeyName, SubkeyName);
InitializeObjectAttributes(&objectAttributes,
&subkeyName,
OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE,
deviceParameterHandle,
NULL);
status = ZwCreateKey(&deviceSubkeyHandle,
KEY_READ | KEY_WRITE,
&objectAttributes,
0, NULL, 0, NULL);
if (!NT_SUCCESS(status)) {
ZwClose(deviceParameterHandle);
}
}
if (NT_SUCCESS(status)) {
status = RtlWriteRegistryValue(
RTL_REGISTRY_HANDLE,
(PWSTR) (SubkeyName ?
deviceSubkeyHandle :
deviceParameterHandle),
ParameterName,
REG_DWORD,
&ParameterValue,
sizeof(ULONG));
//
// close what we open
//
if (SubkeyName) {
ZwClose(deviceSubkeyHandle);
}
ZwClose(deviceParameterHandle);
}
return status;
} // end ClassSetDeviceParameter()
/*
* ClassScanForSpecial
*
* This routine was written to simplify scanning for special
* hardware based upon id strings. it does not check the registry.
*/
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID ClassScanForSpecial(
_In_ PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
_In_ CLASSPNP_SCAN_FOR_SPECIAL_INFO DeviceList[],
_In_ PCLASS_SCAN_FOR_SPECIAL_HANDLER Function)
{
PSTORAGE_DEVICE_DESCRIPTOR deviceDescriptor;
PUCHAR vendorId;
PUCHAR productId;
PUCHAR productRevision;
UCHAR nullString[] = "";
PAGED_CODE();
NT_ASSERT(DeviceList);
NT_ASSERT(Function);
deviceDescriptor = FdoExtension->DeviceDescriptor;
if (DeviceList == NULL) {
return;
}
if (Function == NULL) {
return;
}
//
// SCSI sets offsets to -1, ATAPI sets to 0. check for both.
//
if (deviceDescriptor->VendorIdOffset != 0 &&
deviceDescriptor->VendorIdOffset != -1) {
vendorId = ((PUCHAR)deviceDescriptor);
vendorId += deviceDescriptor->VendorIdOffset;
} else {
vendorId = nullString;
}
if (deviceDescriptor->ProductIdOffset != 0 &&
deviceDescriptor->ProductIdOffset != -1) {
productId = ((PUCHAR)deviceDescriptor);
productId += deviceDescriptor->ProductIdOffset;
} else {
productId = nullString;
}
if (deviceDescriptor->ProductRevisionOffset != 0 &&
deviceDescriptor->ProductRevisionOffset != -1) {
productRevision = ((PUCHAR)deviceDescriptor);
productRevision += deviceDescriptor->ProductRevisionOffset;
} else {
productRevision = nullString;
}
//
// loop while the device list is valid (not null-filled)
//
for (;(DeviceList->VendorId != NULL ||
DeviceList->ProductId != NULL ||
DeviceList->ProductRevision != NULL);DeviceList++) {
if (ClasspMyStringMatches(DeviceList->VendorId, (PCHAR)vendorId) &&
ClasspMyStringMatches(DeviceList->ProductId, (PCHAR)productId) &&
ClasspMyStringMatches(DeviceList->ProductRevision, (PCHAR)productRevision)
) {
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, "ClasspScanForSpecialByInquiry: Found matching "
"controller Ven: %s Prod: %s Rev: %s\n",
(PCSZ)vendorId, (PCSZ)productId, (PCSZ)productRevision));
//
// pass the context to the call back routine and exit
//
(Function)(FdoExtension, DeviceList->Data);
//
// for CHK builds, try to prevent wierd stacks by having a debug
// print here. it's a hack, but i know of no other way to prevent
// the stack from being wrong.
//
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, "ClasspScanForSpecialByInquiry: "
"completed callback\n"));
return;
} // else the strings did not match
} // none of the devices matched.
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_INIT, "ClasspScanForSpecialByInquiry: no match found for %p\n",
FdoExtension->DeviceObject));
return;
} // end ClasspScanForSpecialByInquiry()
//
// In order to provide better performance without the need to reboot,
// we need to implement a self-adjusting method to set and clear the
// srb flags based upon current performance.
//
// whenever there is an error, immediately grab the spin lock. the
// MP perf hit here is acceptable, since we're in an error path. this
// is also neccessary because we are guaranteed to be modifying the
// SRB flags here, setting SuccessfulIO to zero, and incrementing the
// actual error count (which is always done within this spinlock).
//
// whenever there is no error, increment a counter. if there have been
// errors on the device, and we've enabled dynamic perf, *and* we've
// just crossed the perf threshhold, then grab the spin lock and
// double check that the threshhold has, indeed been hit(*). then
// decrement the error count, and if it's dropped sufficiently, undo
// some of the safety changes made in the SRB flags due to the errors.
//
// * this works in all cases. even if lots of ios occur after the
// previous guy went in and cleared the successfulio counter, that
// just means that we've hit the threshhold again, and so it's proper
// to run the inner loop again.
//
VOID
ClasspPerfIncrementErrorCount(
IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
)
{
PCLASS_PRIVATE_FDO_DATA fdoData = FdoExtension->PrivateFdoData;
KIRQL oldIrql;
ULONG errors;
KeAcquireSpinLock(&fdoData->SpinLock, &oldIrql);
fdoData->Perf.SuccessfulIO = 0; // implicit interlock
errors = InterlockedIncrement((volatile LONG *)&FdoExtension->ErrorCount);
if (!fdoData->DisableThrottling) {
if (errors >= CLASS_ERROR_LEVEL_1) {
//
// If the error count has exceeded the error limit, then disable
// any tagged queuing, multiple requests per lu queueing
// and sychronous data transfers.
//
// Clearing the no queue freeze flag prevents the port driver
// from sending multiple requests per logical unit.
//
CLEAR_FLAG(FdoExtension->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE);
CLEAR_FLAG(FdoExtension->SrbFlags, SRB_FLAGS_QUEUE_ACTION_ENABLE);
SET_FLAG(FdoExtension->SrbFlags, SRB_FLAGS_DISABLE_SYNCH_TRANSFER);
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, "ClasspPerfIncrementErrorCount: "
"Too many errors; disabling tagged queuing and "
"synchronous data tranfers.\n"));
}
if (errors >= CLASS_ERROR_LEVEL_2) {
//
// If a second threshold is reached, disable disconnects.
//
SET_FLAG(FdoExtension->SrbFlags, SRB_FLAGS_DISABLE_DISCONNECT);
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, "ClasspPerfIncrementErrorCount: "
"Too many errors; disabling disconnects.\n"));
}
}
KeReleaseSpinLock(&fdoData->SpinLock, oldIrql);
return;
}
VOID
ClasspPerfIncrementSuccessfulIo(
IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
)
{
PCLASS_PRIVATE_FDO_DATA fdoData = FdoExtension->PrivateFdoData;
KIRQL oldIrql;
ULONG errors;
ULONG succeeded = 0;
//
// don't take a hit from the interlocked op unless we're in
// a degraded state and we've got a threshold to hit.
//
if (FdoExtension->ErrorCount == 0) {
return;
}
if (fdoData->Perf.ReEnableThreshhold == 0) {
return;
}
succeeded = InterlockedIncrement((volatile LONG *)&fdoData->Perf.SuccessfulIO);
if (succeeded < fdoData->Perf.ReEnableThreshhold) {
return;
}
//
// if we hit the threshold, grab the spinlock and verify we've
// actually done so. this allows us to ignore the spinlock 99%
// of the time.
//
KeAcquireSpinLock(&fdoData->SpinLock, &oldIrql);
//
// re-read the value, so we don't run this multiple times
// for a single threshhold being hit. this keeps errorcount
// somewhat useful.
//
succeeded = fdoData->Perf.SuccessfulIO;
if ((FdoExtension->ErrorCount != 0) &&
(fdoData->Perf.ReEnableThreshhold <= succeeded)
) {
fdoData->Perf.SuccessfulIO = 0; // implicit interlock
NT_ASSERT(FdoExtension->ErrorCount > 0);
errors = InterlockedDecrement((volatile LONG *)&FdoExtension->ErrorCount);
//
// note: do in reverse order of the sets "just in case"
//
if (errors < CLASS_ERROR_LEVEL_2) {
if (errors == CLASS_ERROR_LEVEL_2 - 1) {
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, "ClasspPerfIncrementSuccessfulIo: "
"Error level 2 no longer required.\n"));
}
if (!TEST_FLAG(fdoData->Perf.OriginalSrbFlags,
SRB_FLAGS_DISABLE_DISCONNECT)) {
CLEAR_FLAG(FdoExtension->SrbFlags,
SRB_FLAGS_DISABLE_DISCONNECT);
}
}
if (errors < CLASS_ERROR_LEVEL_1) {
if (errors == CLASS_ERROR_LEVEL_1 - 1) {
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, "ClasspPerfIncrementSuccessfulIo: "
"Error level 1 no longer required.\n"));
}
if (!TEST_FLAG(fdoData->Perf.OriginalSrbFlags,
SRB_FLAGS_DISABLE_SYNCH_TRANSFER)) {
CLEAR_FLAG(FdoExtension->SrbFlags,
SRB_FLAGS_DISABLE_SYNCH_TRANSFER);
}
if (TEST_FLAG(fdoData->Perf.OriginalSrbFlags,
SRB_FLAGS_QUEUE_ACTION_ENABLE)) {
SET_FLAG(FdoExtension->SrbFlags,
SRB_FLAGS_QUEUE_ACTION_ENABLE);
}
if (TEST_FLAG(fdoData->Perf.OriginalSrbFlags,
SRB_FLAGS_NO_QUEUE_FREEZE)) {
SET_FLAG(FdoExtension->SrbFlags,
SRB_FLAGS_NO_QUEUE_FREEZE);
}
}
} // end of threshhold definitely being hit for first time
KeReleaseSpinLock(&fdoData->SpinLock, oldIrql);
return;
}
PMDL ClasspBuildDeviceMdl(PVOID Buffer, ULONG BufferLen, BOOLEAN WriteToDevice)
{
PMDL mdl;
mdl = IoAllocateMdl(Buffer, BufferLen, FALSE, FALSE, NULL);
if (mdl){
try {
MmProbeAndLockPages(mdl, KernelMode, WriteToDevice ? IoReadAccess : IoWriteAccess);
#pragma warning(suppress: 6320) // We want to handle any exception that MmProbeAndLockPages might throw
} except(EXCEPTION_EXECUTE_HANDLER) {
NTSTATUS status = GetExceptionCode();
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, "ClasspBuildDeviceMdl: MmProbeAndLockPages failed with %xh.", status));
IoFreeMdl(mdl);
mdl = NULL;
}
}
else {
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT, "ClasspBuildDeviceMdl: IoAllocateMdl failed"));
}
return mdl;
}
PMDL BuildDeviceInputMdl(PVOID Buffer, ULONG BufferLen)
{
return ClasspBuildDeviceMdl(Buffer, BufferLen, FALSE);
}
VOID ClasspFreeDeviceMdl(PMDL Mdl)
{
MmUnlockPages(Mdl);
IoFreeMdl(Mdl);
}
VOID FreeDeviceInputMdl(PMDL Mdl)
{
ClasspFreeDeviceMdl(Mdl);
return;
}
#if 0
VOID
ClasspPerfResetCounters(
IN PFUNCTIONAL_DEVICE_EXTENSION FdoExtension
)
{
PCLASS_PRIVATE_FDO_DATA fdoData = FdoExtension->PrivateFdoData;
KIRQL oldIrql;
KeAcquireSpinLock(&fdoData->SpinLock, &oldIrql);
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL, "ClasspPerfResetCounters: "
"Resetting all perf counters.\n"));
fdoData->Perf.SuccessfulIO = 0;
FdoExtension->ErrorCount = 0;
if (!TEST_FLAG(fdoData->Perf.OriginalSrbFlags,
SRB_FLAGS_DISABLE_DISCONNECT)) {
CLEAR_FLAG(FdoExtension->SrbFlags,
SRB_FLAGS_DISABLE_DISCONNECT);
}
if (!TEST_FLAG(fdoData->Perf.OriginalSrbFlags,
SRB_FLAGS_DISABLE_SYNCH_TRANSFER)) {
CLEAR_FLAG(FdoExtension->SrbFlags,
SRB_FLAGS_DISABLE_SYNCH_TRANSFER);
}
if (TEST_FLAG(fdoData->Perf.OriginalSrbFlags,
SRB_FLAGS_QUEUE_ACTION_ENABLE)) {
SET_FLAG(FdoExtension->SrbFlags,
SRB_FLAGS_QUEUE_ACTION_ENABLE);
}
if (TEST_FLAG(fdoData->Perf.OriginalSrbFlags,
SRB_FLAGS_NO_QUEUE_FREEZE)) {
SET_FLAG(FdoExtension->SrbFlags,
SRB_FLAGS_NO_QUEUE_FREEZE);
}
KeReleaseSpinLock(&fdoData->SpinLock, oldIrql);
return;
}
#endif
/*++
ClasspDuidGetDeviceIdProperty
Routine Description:
Add StorageDeviceIdProperty to the device unique ID structure.
Arguments:
DeviceObject - a pointer to the device object
Irp - a pointer to the I/O request packet
Return Value:
Status Code
--*/
NTSTATUS
ClasspDuidGetDeviceIdProperty(
IN PDEVICE_OBJECT DeviceObject,
IN PIRP Irp
)
{
PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
PSTORAGE_DEVICE_ID_DESCRIPTOR deviceIdDescriptor = NULL;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
PSTORAGE_DESCRIPTOR_HEADER descHeader;
PSTORAGE_DEVICE_UNIQUE_IDENTIFIER storageDuid;
PUCHAR dest;
STORAGE_PROPERTY_ID propertyId = StorageDeviceIdProperty;
NTSTATUS status;
ULONG queryLength;
ULONG offset;
//
// Get the VPD page 83h data.
//
status = ClassGetDescriptor(commonExtension->LowerDeviceObject,
&propertyId,
&deviceIdDescriptor);
if (!NT_SUCCESS(status) || !deviceIdDescriptor) {
goto FnExit;
}
queryLength = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
descHeader = Irp->AssociatedIrp.SystemBuffer;
//
// Adjust required size and potential destination location.
//
offset = descHeader->Size;
dest = (PUCHAR)descHeader + offset;
descHeader->Size += deviceIdDescriptor->Size;
if (queryLength < descHeader->Size) {
//
// Output buffer is too small. Return error and make sure
// the caller gets info about required buffer size.
//
Irp->IoStatus.Information = sizeof(STORAGE_DESCRIPTOR_HEADER);
status = STATUS_BUFFER_OVERFLOW;
goto FnExit;
}
storageDuid = Irp->AssociatedIrp.SystemBuffer;
storageDuid->StorageDeviceIdOffset = offset;
RtlCopyMemory(dest,
deviceIdDescriptor,
deviceIdDescriptor->Size);
Irp->IoStatus.Information = storageDuid->Size;
status = STATUS_SUCCESS;
FnExit:
FREE_POOL(deviceIdDescriptor);
return status;
}
/*++
ClasspDuidGetDeviceProperty
Routine Description:
Add StorageDeviceProperty to the device unique ID structure.
Arguments:
DeviceObject - a pointer to the device object
Irp - a pointer to the I/O request packet
Return Value:
Status Code
--*/
NTSTATUS
ClasspDuidGetDeviceProperty(
PDEVICE_OBJECT DeviceObject,
PIRP Irp
)
{
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
PSTORAGE_DEVICE_DESCRIPTOR deviceDescriptor = fdoExtension->DeviceDescriptor;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
PSTORAGE_DESCRIPTOR_HEADER descHeader;
PSTORAGE_DEVICE_UNIQUE_IDENTIFIER storageDuid;
PUCHAR dest;
NTSTATUS status = STATUS_NOT_FOUND;
ULONG queryLength;
ULONG offset;
//
// Use the StorageDeviceProperty already cached in the device extension.
//
if (!deviceDescriptor) {
goto FnExit;
}
queryLength = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
descHeader = Irp->AssociatedIrp.SystemBuffer;
//
// Use this info only if serial number is available.
//
if (deviceDescriptor->SerialNumberOffset == 0) {
goto FnExit;
}
//
// Adjust required size and potential destination location.
//
offset = descHeader->Size;
dest = (PUCHAR)descHeader + offset;
descHeader->Size += deviceDescriptor->Size;
if (queryLength < descHeader->Size) {
//
// Output buffer is too small. Return error and make sure
// the caller get info about required buffer size.
//
Irp->IoStatus.Information = sizeof(STORAGE_DESCRIPTOR_HEADER);
status = STATUS_BUFFER_OVERFLOW;
goto FnExit;
}
storageDuid = Irp->AssociatedIrp.SystemBuffer;
storageDuid->StorageDeviceOffset = offset;
RtlCopyMemory(dest,
deviceDescriptor,
deviceDescriptor->Size);
Irp->IoStatus.Information = storageDuid->Size;
status = STATUS_SUCCESS;
FnExit:
return status;
}
/*++
ClasspDuidGetDriveLayout
Routine Description:
Add drive layout signature to the device unique ID structure.
Layout signature is only added for disk-type devices.
Arguments:
DeviceObject - a pointer to the device object
Irp - a pointer to the I/O request packet
Return Value:
Status Code
--*/
NTSTATUS
ClasspDuidGetDriveLayout(
PDEVICE_OBJECT DeviceObject,
PIRP Irp
)
{
PDRIVE_LAYOUT_INFORMATION_EX layoutEx = NULL;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
PSTORAGE_DESCRIPTOR_HEADER descHeader;
PSTORAGE_DEVICE_UNIQUE_IDENTIFIER storageDuid;
PSTORAGE_DEVICE_LAYOUT_SIGNATURE driveLayoutSignature;
NTSTATUS status = STATUS_NOT_FOUND;
ULONG queryLength;
ULONG offset;
//
// Only process disk-type devices.
//
if (DeviceObject->DeviceType != FILE_DEVICE_DISK) {
goto FnExit;
}
//
// Get current partition table and process only if GPT
// or MBR layout.
//
status = IoReadPartitionTableEx(DeviceObject, &layoutEx);
if (!NT_SUCCESS(status)) {
status = STATUS_NOT_FOUND;
goto FnExit;
}
if (layoutEx->PartitionStyle != PARTITION_STYLE_GPT &&
layoutEx->PartitionStyle != PARTITION_STYLE_MBR) {
status = STATUS_NOT_FOUND;
goto FnExit;
}
queryLength = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
descHeader = Irp->AssociatedIrp.SystemBuffer;
//
// Adjust required size and potential destination location.
//
offset = descHeader->Size;
driveLayoutSignature = (PSTORAGE_DEVICE_LAYOUT_SIGNATURE)((PUCHAR)descHeader + offset);
descHeader->Size += sizeof(STORAGE_DEVICE_LAYOUT_SIGNATURE);
if (queryLength < descHeader->Size) {
//
// Output buffer is too small. Return error and make sure
// the caller get info about required buffer size.
//
Irp->IoStatus.Information = sizeof(STORAGE_DESCRIPTOR_HEADER);
status = STATUS_BUFFER_OVERFLOW;
goto FnExit;
}
storageDuid = Irp->AssociatedIrp.SystemBuffer;
driveLayoutSignature->Size = sizeof(STORAGE_DEVICE_LAYOUT_SIGNATURE);
driveLayoutSignature->Version = DUID_VERSION_1;
if (layoutEx->PartitionStyle == PARTITION_STYLE_MBR) {
driveLayoutSignature->Mbr = TRUE;
RtlCopyMemory(&driveLayoutSignature->DeviceSpecific.MbrSignature,
&layoutEx->Mbr.Signature,
sizeof(layoutEx->Mbr.Signature));
} else {
driveLayoutSignature->Mbr = FALSE;
RtlCopyMemory(&driveLayoutSignature->DeviceSpecific.GptDiskId,
&layoutEx->Gpt.DiskId,
sizeof(layoutEx->Gpt.DiskId));
}
storageDuid->DriveLayoutSignatureOffset = offset;
Irp->IoStatus.Information = storageDuid->Size;
status = STATUS_SUCCESS;
FnExit:
FREE_POOL(layoutEx);
return status;
}
/*++
ClasspDuidQueryProperty
Routine Description:
Handles IOCTL_STORAGE_QUERY_PROPERTY for device unique ID requests
(when PropertyId is StorageDeviceUniqueIdProperty).
Arguments:
DeviceObject - a pointer to the device object
Irp - a pointer to the I/O request packet
Return Value:
Status Code
--*/
NTSTATUS
ClasspDuidQueryProperty(
PDEVICE_OBJECT DeviceObject,
PIRP Irp
)
{
PSTORAGE_PROPERTY_QUERY query = Irp->AssociatedIrp.SystemBuffer;
PSTORAGE_DESCRIPTOR_HEADER descHeader;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
NTSTATUS status;
ULONG outLength = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
BOOLEAN includeOptionalIds;
BOOLEAN overflow = FALSE;
BOOLEAN infoFound = FALSE;
BOOLEAN useStatus = TRUE; // Use the status directly instead of relying on overflow and infoFound flags.
//
// Must run at less then dispatch.
//
if (KeGetCurrentIrql() >= DISPATCH_LEVEL) {
NT_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
status = STATUS_INVALID_LEVEL;
goto FnExit;
}
//
// Check proper query type.
//
if (query->QueryType == PropertyExistsQuery) {
Irp->IoStatus.Information = 0;
status = STATUS_SUCCESS;
goto FnExit;
}
if (query->QueryType != PropertyStandardQuery) {
status = STATUS_NOT_SUPPORTED;
goto FnExit;
}
//
// Check AdditionalParameters validity.
//
if (query->AdditionalParameters[0] == DUID_INCLUDE_SOFTWARE_IDS) {
includeOptionalIds = TRUE;
} else if (query->AdditionalParameters[0] == DUID_HARDWARE_IDS_ONLY) {
includeOptionalIds = FALSE;
} else {
status = STATUS_INVALID_PARAMETER;
goto FnExit;
}
//
// Verify output parameters.
//
if (outLength < sizeof(STORAGE_DESCRIPTOR_HEADER)) {
status = STATUS_INFO_LENGTH_MISMATCH;
goto FnExit;
}
//
// From this point forward the status depends on the overflow
// and infoFound flags.
//
useStatus = FALSE;
descHeader = Irp->AssociatedIrp.SystemBuffer;
RtlZeroMemory(descHeader, outLength);
descHeader->Version = DUID_VERSION_1;
descHeader->Size = sizeof(STORAGE_DEVICE_UNIQUE_IDENTIFIER);
//
// Try to build device unique id from StorageDeviceIdProperty.
//
status = ClasspDuidGetDeviceIdProperty(DeviceObject,
Irp);
if (status == STATUS_BUFFER_OVERFLOW) {
overflow = TRUE;
}
if (NT_SUCCESS(status)) {
infoFound = TRUE;
}
//
// Try to build device unique id from StorageDeviceProperty.
//
status = ClasspDuidGetDeviceProperty(DeviceObject,
Irp);
if (status == STATUS_BUFFER_OVERFLOW) {
overflow = TRUE;
}
if (NT_SUCCESS(status)) {
infoFound = TRUE;
}
//
// The following portion is optional and only included if the
// caller requested software IDs.
//
if (!includeOptionalIds) {
goto FnExit;
}
//
// Try to build device unique id from drive layout signature (disk
// devices only).
//
status = ClasspDuidGetDriveLayout(DeviceObject,
Irp);
if (status == STATUS_BUFFER_OVERFLOW) {
overflow = TRUE;
}
if (NT_SUCCESS(status)) {
infoFound = TRUE;
}
FnExit:
if (!useStatus) {
//
// Return overflow, success, or a generic error.
//
if (overflow) {
//
// If output buffer is STORAGE_DESCRIPTOR_HEADER, then return
// success to the user. Otherwise, send an error so the user
// knows a larger buffer is required.
//
if (outLength == sizeof(STORAGE_DESCRIPTOR_HEADER)) {
status = STATUS_SUCCESS;
Irp->IoStatus.Information = sizeof(STORAGE_DESCRIPTOR_HEADER);
} else {
status = STATUS_BUFFER_OVERFLOW;
}
} else if (infoFound) {
status = STATUS_SUCCESS;
//
// Exercise the compare routine. This should always succeed.
//
NT_ASSERT(DuidExactMatch == CompareStorageDuids(Irp->AssociatedIrp.SystemBuffer,
Irp->AssociatedIrp.SystemBuffer));
} else {
status = STATUS_NOT_FOUND;
}
}
Irp->IoStatus.Status = status;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
return status;
}
/*++////////////////////////////////////////////////////////////////////////////
ClasspWriteCacheProperty()
Routine Description:
This routine reads the caching mode page from the device to
build the Write Cache property page.
Arguments:
DeviceObject - The device object to handle this irp
Irp - The IRP for this request
Srb - SRB allocated by the dispatch routine
Return Value:
--*/
NTSTATUS ClasspWriteCacheProperty(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ PIRP Irp,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
{
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
PSTORAGE_WRITE_CACHE_PROPERTY writeCache;
PSTORAGE_PROPERTY_QUERY query = Irp->AssociatedIrp.SystemBuffer;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
PMODE_PARAMETER_HEADER modeData = NULL;
PMODE_CACHING_PAGE pageData = NULL;
ULONG length, information = 0;
NTSTATUS status;
PCDB cdb;
//
// Must run at less then dispatch.
//
if (KeGetCurrentIrql() >= DISPATCH_LEVEL) {
NT_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
status = STATUS_INVALID_LEVEL;
goto WriteCacheExit;
}
//
// Check proper query type.
//
if (query->QueryType == PropertyExistsQuery) {
status = STATUS_SUCCESS;
goto WriteCacheExit;
}
if (query->QueryType != PropertyStandardQuery) {
status = STATUS_NOT_SUPPORTED;
goto WriteCacheExit;
}
length = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
if (length < sizeof(STORAGE_DESCRIPTOR_HEADER)) {
status = STATUS_INFO_LENGTH_MISMATCH;
goto WriteCacheExit;
}
writeCache = (PSTORAGE_WRITE_CACHE_PROPERTY) Irp->AssociatedIrp.SystemBuffer;
RtlZeroMemory(writeCache, length);
//
// Set version and required size.
//
writeCache->Version = sizeof(STORAGE_WRITE_CACHE_PROPERTY);
writeCache->Size = sizeof(STORAGE_WRITE_CACHE_PROPERTY);
if (length < sizeof(STORAGE_WRITE_CACHE_PROPERTY)) {
information = sizeof(STORAGE_DESCRIPTOR_HEADER);
status = STATUS_SUCCESS;
goto WriteCacheExit;
}
//
// Set known values
//
writeCache->NVCacheEnabled = FALSE;
writeCache->UserDefinedPowerProtection = TEST_FLAG(fdoExtension->DeviceFlags, DEV_POWER_PROTECTED);
//
// Check for flush cache support by sending a sync cache command
// to the device.
//
//
// Set timeout value and mark the request as not being a tagged request.
//
SrbSetTimeOutValue(Srb, fdoExtension->TimeOutValue * 4);
SrbSetRequestTag(Srb, SP_UNTAGGED);
SrbSetRequestAttribute(Srb, SRB_SIMPLE_TAG_REQUEST);
SrbAssignSrbFlags(Srb, fdoExtension->SrbFlags);
SrbSetCdbLength(Srb, 10);
cdb = SrbGetCdb(Srb);
cdb->CDB10.OperationCode = SCSIOP_SYNCHRONIZE_CACHE;
status = ClassSendSrbSynchronous(DeviceObject,
Srb,
NULL,
0,
TRUE);
if (NT_SUCCESS(status)) {
writeCache->FlushCacheSupported = TRUE;
} else {
//
// Device does not support sync cache
//
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "ClasspWriteCacheProperty: Synchronize cache failed with status 0x%X\n", status));
writeCache->FlushCacheSupported = FALSE;
//
// Reset the status if there was any failure
//
status = STATUS_SUCCESS;
}
modeData = ExAllocatePoolZero(NonPagedPoolNxCacheAligned,
MODE_PAGE_DATA_SIZE,
CLASS_TAG_MODE_DATA);
if (modeData == NULL) {
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, "ClasspWriteCacheProperty: Unable to allocate mode data buffer\n"));
status = STATUS_INSUFFICIENT_RESOURCES;
goto WriteCacheExit;
}
length = ClassModeSense(DeviceObject,
(PCHAR) modeData,
MODE_PAGE_DATA_SIZE,
MODE_PAGE_CACHING);
if (length < sizeof(MODE_PARAMETER_HEADER)) {
//
// Retry the request in case of a check condition.
//
length = ClassModeSense(DeviceObject,
(PCHAR) modeData,
MODE_PAGE_DATA_SIZE,
MODE_PAGE_CACHING);
if (length < sizeof(MODE_PARAMETER_HEADER)) {
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, "ClasspWriteCacheProperty: Mode Sense failed\n"));
status = STATUS_IO_DEVICE_ERROR;
goto WriteCacheExit;
}
}
//
// If the length is greater than length indicated by the mode data reset
// the data to the mode data.
//
if (length > (ULONG) (modeData->ModeDataLength + 1)) {
length = modeData->ModeDataLength + 1;
}
//
// Look for caching page in the returned mode page data.
//
pageData = ClassFindModePage((PCHAR) modeData,
length,
MODE_PAGE_CACHING,
TRUE);
//
// Check if valid caching page exists.
//
if (pageData == NULL) {
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "ClasspWriteCacheProperty: Unable to find caching mode page.\n"));
//
// Set write cache value as unknown.
//
writeCache->WriteCacheEnabled = WriteCacheEnableUnknown;
writeCache->WriteCacheType = WriteCacheTypeUnknown;
} else {
writeCache->WriteCacheEnabled = pageData->WriteCacheEnable ?
WriteCacheEnabled : WriteCacheDisabled;
writeCache->WriteCacheType = pageData->WriteCacheEnable ?
WriteCacheTypeWriteBack : WriteCacheTypeUnknown;
}
//
// Check write through support. If the device previously failed a write request
// with FUA bit is set, then CLASS_SPECIAL_FUA_NOT_SUPPORTED will be set,
// which means write through is not support by the device.
//
if ((modeData->DeviceSpecificParameter & MODE_DSP_FUA_SUPPORTED) &&
(!TEST_FLAG(fdoExtension->ScanForSpecialFlags, CLASS_SPECIAL_FUA_NOT_SUPPORTED))) {
writeCache->WriteThroughSupported = WriteThroughSupported;
} else {
writeCache->WriteThroughSupported = WriteThroughNotSupported;
}
//
// Get the changeable caching mode page and check write cache is changeable.
//
RtlZeroMemory(modeData, MODE_PAGE_DATA_SIZE);
length = ClasspModeSense(DeviceObject,
(PCHAR) modeData,
MODE_PAGE_DATA_SIZE,
MODE_PAGE_CACHING,
MODE_SENSE_CHANGEABLE_VALUES);
if (length < sizeof(MODE_PARAMETER_HEADER)) {
//
// Retry the request in case of a check condition.
//
length = ClasspModeSense(DeviceObject,
(PCHAR) modeData,
MODE_PAGE_DATA_SIZE,
MODE_PAGE_CACHING,
MODE_SENSE_CHANGEABLE_VALUES);
if (length < sizeof(MODE_PARAMETER_HEADER)) {
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "ClasspWriteCacheProperty: Mode Sense failed\n"));
//
// If the device fails to return changeable pages, then
// set the write cache changeable value to unknown.
//
writeCache->WriteCacheChangeable = WriteCacheChangeUnknown;
information = sizeof(STORAGE_WRITE_CACHE_PROPERTY);
goto WriteCacheExit;
}
}
//
// If the length is greater than length indicated by the mode data reset
// the data to the mode data.
//
if (length > (ULONG) (modeData->ModeDataLength + 1)) {
length = modeData->ModeDataLength + 1;
}
//
// Look for caching page in the returned mode page data.
//
pageData = ClassFindModePage((PCHAR) modeData,
length,
MODE_PAGE_CACHING,
TRUE);
//
// Check if valid caching page exists.
//
if (pageData == NULL) {
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "ClasspWriteCacheProperty: Unable to find caching mode page.\n"));
//
// Set write cache changeable value to unknown.
//
writeCache->WriteCacheChangeable = WriteCacheChangeUnknown;
} else {
writeCache->WriteCacheChangeable = pageData->WriteCacheEnable ?
WriteCacheChangeable : WriteCacheNotChangeable;
}
information = sizeof(STORAGE_WRITE_CACHE_PROPERTY);
WriteCacheExit:
FREE_POOL(modeData);
//
// Set the size and status in IRP
//
Irp->IoStatus.Information = information;;
Irp->IoStatus.Status = status;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
return status;
}
ULONG
ClasspCalculateLogicalSectorSize (
_In_ PDEVICE_OBJECT Fdo,
_In_ ULONG BytesPerBlockInBigEndian
)
/*++
Convert the big-endian value.
if it's 0, default to the standard 512 bytes.
if it's not a power of 2 value, round down to power of 2.
--*/
{
ULONG logicalSectorSize;
REVERSE_BYTES(&logicalSectorSize, &BytesPerBlockInBigEndian);
if (logicalSectorSize == 0) {
logicalSectorSize = 512;
} else {
//
// Clear all but the highest set bit.
// That will give us a bytesPerSector value that is a power of 2.
//
if (logicalSectorSize & (logicalSectorSize-1)) {
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_INIT, "FDO %ph has non-standard sector size 0x%x.", Fdo, logicalSectorSize));
do {
logicalSectorSize &= logicalSectorSize-1;
}
while (logicalSectorSize & (logicalSectorSize-1));
}
}
return logicalSectorSize;
}
NTSTATUS
InterpretReadCapacity16Data (
_Inout_ PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
_In_ PREAD_CAPACITY16_DATA ReadCapacity16Data
)
{
NTSTATUS status = STATUS_SUCCESS;
USHORT lowestAlignedBlock;
USHORT logicalBlocksPerPhysicalBlock;
PCLASS_READ_CAPACITY16_DATA cachedData = &(FdoExtension->FunctionSupportInfo->ReadCapacity16Data);
// use Logical Sector Size from DiskGeometry to avoid duplicated calculation.
FdoExtension->FunctionSupportInfo->ReadCapacity16Data.BytesPerLogicalSector = ClasspCalculateLogicalSectorSize(FdoExtension->DeviceObject, ReadCapacity16Data->BytesPerBlock);
// FdoExtension->DiskGeometry.BytesPerSector might be 0 for class drivers that don't get READ CAPACITY info yet.
NT_ASSERT( (FdoExtension->DiskGeometry.BytesPerSector == 0) ||
(FdoExtension->DiskGeometry.BytesPerSector == FdoExtension->FunctionSupportInfo->ReadCapacity16Data.BytesPerLogicalSector) );
logicalBlocksPerPhysicalBlock = 1 << ReadCapacity16Data->LogicalPerPhysicalExponent;
lowestAlignedBlock = (ReadCapacity16Data->LowestAlignedBlock_MSB << 8) | ReadCapacity16Data->LowestAlignedBlock_LSB;
if (lowestAlignedBlock > logicalBlocksPerPhysicalBlock) {
// we get garbage data
status = STATUS_UNSUCCESSFUL;
} else {
// value of lowestAlignedBlock (from T10 spec) needs to be converted.
lowestAlignedBlock = (logicalBlocksPerPhysicalBlock - lowestAlignedBlock) % logicalBlocksPerPhysicalBlock;
}
if (NT_SUCCESS(status)) {
// fill output buffer
cachedData->BytesPerPhysicalSector = cachedData->BytesPerLogicalSector * logicalBlocksPerPhysicalBlock;
cachedData->BytesOffsetForSectorAlignment = cachedData->BytesPerLogicalSector * lowestAlignedBlock;
//
// Fill in the Logical Block Provisioning info. Note that we do not
// use these fields; we use the Provisioning Type and LBPRZ fields from
// the Logical Block Provisioning VPD page (0xB2).
//
cachedData->LBProvisioningEnabled = ReadCapacity16Data->LBPME;
cachedData->LBProvisioningReadZeros = ReadCapacity16Data->LBPRZ;
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_INIT,
"InterpretReadCapacity16Data: Device\'s LBP enabled = %d\n",
cachedData->LBProvisioningEnabled));
}
return status;
}
NTSTATUS
ClassReadCapacity16 (
_Inout_ PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
/*
This routine may send down a READ CAPACITY 16 command to retrieve info.
The info will be cached in FdoExtension->LowerLayerSupport->AccessAlignment.
After info retrieving finished, this function sets following field:
FdoExtension->LowerLayerSupport->AccessAlignment.LowerLayerSupported = Supported;
to indicate that info has been cached.
NOTE: some future processes may use this function to send the command anyway, it will be caller's decision
on checking 'AccessAlignment.LowerLayerSupported' in case the cached info is good enough.
*/
{
NTSTATUS status = STATUS_SUCCESS;
PREAD_CAPACITY16_DATA dataBuffer = NULL;
UCHAR bufferLength = sizeof(READ_CAPACITY16_DATA);
ULONG allocationBufferLength = bufferLength; //DMA buffer size for alignment
PCDB cdb;
ULONG dataTransferLength = 0;
//
// If the information retrieval has already been attempted, return the cached status.
//
if (FdoExtension->FunctionSupportInfo->ReadCapacity16Data.CommandStatus != -1) {
// get cached NTSTATUS from previous call.
return FdoExtension->FunctionSupportInfo->ReadCapacity16Data.CommandStatus;
}
if (ClasspIsObsoletePortDriver(FdoExtension)) {
FdoExtension->FunctionSupportInfo->ReadCapacity16Data.CommandStatus = STATUS_NOT_IMPLEMENTED;
return STATUS_NOT_IMPLEMENTED;
}
#if defined(_ARM_) || defined(_ARM64_)
//
// ARM has specific alignment requirements, although this will not have a functional impact on x86 or amd64
// based platforms. We are taking the conservative approach here.
//
allocationBufferLength = ALIGN_UP_BY(allocationBufferLength, KeGetRecommendedSharedDataAlignment());
dataBuffer = (PREAD_CAPACITY16_DATA)
ExAllocatePoolZero(NonPagedPoolNxCacheAligned,
allocationBufferLength,
'4CcS');
#else
dataBuffer = (PREAD_CAPACITY16_DATA)
ExAllocatePoolZero(NonPagedPoolNx,
bufferLength,
'4CcS');
#endif
if (dataBuffer == NULL) {
// return without updating FdoExtension->FunctionSupportInfo->ReadCapacity16Data.CommandStatus
// the field will remain value as "-1", so that the command will be attempted next time this function is called.
return STATUS_INSUFFICIENT_RESOURCES;
}
//
// Initialize the SRB.
//
if (FdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
status = InitializeStorageRequestBlock((PSTORAGE_REQUEST_BLOCK)Srb,
STORAGE_ADDRESS_TYPE_BTL8,
CLASS_SRBEX_SCSI_CDB16_BUFFER_SIZE,
1,
SrbExDataTypeScsiCdb16);
if (NT_SUCCESS(status)) {
((PSTORAGE_REQUEST_BLOCK)Srb)->SrbFunction = SRB_FUNCTION_EXECUTE_SCSI;
} else {
//
// Should not occur.
//
NT_ASSERT(FALSE);
}
} else {
RtlZeroMemory(Srb, sizeof(SCSI_REQUEST_BLOCK));
Srb->Length = sizeof(SCSI_REQUEST_BLOCK);
Srb->Function = SRB_FUNCTION_EXECUTE_SCSI;
}
//prepare the Srb
if (NT_SUCCESS(status))
{
SrbSetTimeOutValue(Srb, FdoExtension->TimeOutValue);
SrbSetRequestTag(Srb, SP_UNTAGGED);
SrbSetRequestAttribute(Srb, SRB_SIMPLE_TAG_REQUEST);
SrbAssignSrbFlags(Srb, FdoExtension->SrbFlags);
SrbSetCdbLength(Srb, 16);
cdb = SrbGetCdb(Srb);
cdb->READ_CAPACITY16.OperationCode = SCSIOP_READ_CAPACITY16;
cdb->READ_CAPACITY16.ServiceAction = SERVICE_ACTION_READ_CAPACITY16;
cdb->READ_CAPACITY16.AllocationLength[3] = bufferLength;
status = ClassSendSrbSynchronous(FdoExtension->DeviceObject,
Srb,
dataBuffer,
allocationBufferLength,
FALSE);
dataTransferLength = SrbGetDataTransferLength(Srb);
}
if (NT_SUCCESS(status) && (dataTransferLength < 16))
{
// the device should return at least 16 bytes of data for this command.
status = STATUS_INFO_LENGTH_MISMATCH;
}
//
// Handle the case where we get back STATUS_DATA_OVERRUN b/c the input
// buffer was larger than necessary.
//
if (status == STATUS_DATA_OVERRUN && dataTransferLength < bufferLength)
{
status = STATUS_SUCCESS;
}
if (NT_SUCCESS(status))
{
// cache data into FdoExtension
status = InterpretReadCapacity16Data(FdoExtension, dataBuffer);
}
// cache the status indicates that this funciton has been called.
FdoExtension->FunctionSupportInfo->ReadCapacity16Data.CommandStatus = status;
ExFreePool(dataBuffer);
return status;
}
NTSTATUS ClasspAccessAlignmentProperty(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ PIRP Irp,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
/*
At first time of receiving the request, this function will forward it to lower stack to determine if it's supportted.
If it's not supported, SCSIOP_READ_CAPACITY16 will be sent down to retrieve the information.
*/
{
NTSTATUS status = STATUS_UNSUCCESSFUL;
PCOMMON_DEVICE_EXTENSION commonExtension = (PCOMMON_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PSTORAGE_PROPERTY_QUERY query = (PSTORAGE_PROPERTY_QUERY)Irp->AssociatedIrp.SystemBuffer;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
ULONG length = 0;
ULONG information = 0;
PSTORAGE_ACCESS_ALIGNMENT_DESCRIPTOR accessAlignment;
//
// check registry setting and fail the IOCTL if it's required.
// this registry setting can be used to work around issues which upper layer doesn't support large physical sector size.
//
if (fdoExtension->FunctionSupportInfo->RegAccessAlignmentQueryNotSupported) {
status = STATUS_NOT_SUPPORTED;
goto Exit;
}
if ( (DeviceObject->DeviceType != FILE_DEVICE_DISK) ||
(TEST_FLAG(DeviceObject->Characteristics, FILE_FLOPPY_DISKETTE)) ||
(fdoExtension->FunctionSupportInfo->LowerLayerSupport.AccessAlignmentProperty == Supported) ) {
// if it's not disk, forward the request to lower layer,
// if the IOCTL is supported by lower stack, forward it down.
IoCopyCurrentIrpStackLocationToNext(Irp);
ClassReleaseRemoveLock(DeviceObject, Irp);
status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
return status;
}
//
// Check proper query type.
//
if (query->QueryType == PropertyExistsQuery) {
status = STATUS_SUCCESS;
goto Exit;
} else if (query->QueryType != PropertyStandardQuery) {
status = STATUS_NOT_SUPPORTED;
goto Exit;
}
//
// Request validation.
// Note that InputBufferLength and IsFdo have been validated before entering this routine.
//
if (KeGetCurrentIrql() >= DISPATCH_LEVEL) {
NT_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
status = STATUS_INVALID_LEVEL;
goto Exit;
}
// do not touch this buffer because it can still be used as input buffer for lower layer in 'SupportUnknown' case.
accessAlignment = (PSTORAGE_ACCESS_ALIGNMENT_DESCRIPTOR)Irp->AssociatedIrp.SystemBuffer;
length = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
if (length < sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR)) {
if (length >= sizeof(STORAGE_DESCRIPTOR_HEADER)) {
information = sizeof(STORAGE_DESCRIPTOR_HEADER);
accessAlignment->Version = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
accessAlignment->Size = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
status = STATUS_SUCCESS;
goto Exit;
}
status = STATUS_BUFFER_TOO_SMALL;
goto Exit;
}
// not support Cache Line,
// 'BytesPerCacheLine' and 'BytesOffsetForCacheAlignment' fields are zero-ed.
//
// note that 'Supported' case has been handled at the beginning of this function.
//
switch (fdoExtension->FunctionSupportInfo->LowerLayerSupport.AccessAlignmentProperty) {
case SupportUnknown: {
// send down request and wait for the request to complete.
status = ClassForwardIrpSynchronous(commonExtension, Irp);
if (ClasspLowerLayerNotSupport(status)) {
// case 1: the request is not supported by lower layer, sends down command
// some port drivers (or filter drivers) return STATUS_INVALID_DEVICE_REQUEST if a request is not supported.
// ClassReadCapacity16() will either return status from cached data or send command to retrieve the information.
if (ClasspIsObsoletePortDriver(fdoExtension) == FALSE) {
status = ClassReadCapacity16(fdoExtension, Srb);
} else {
fdoExtension->FunctionSupportInfo->ReadCapacity16Data.CommandStatus = status;
}
// data is ready in fdoExtension
// set the support status after the SCSI command is executed to avoid racing condition between multiple same type of requests.
fdoExtension->FunctionSupportInfo->LowerLayerSupport.AccessAlignmentProperty = NotSupported;
if (NT_SUCCESS(status)) {
// fill output buffer
RtlZeroMemory(accessAlignment, length);
accessAlignment->Version = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
accessAlignment->Size = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
accessAlignment->BytesPerLogicalSector = fdoExtension->FunctionSupportInfo->ReadCapacity16Data.BytesPerLogicalSector;
accessAlignment->BytesPerPhysicalSector = fdoExtension->FunctionSupportInfo->ReadCapacity16Data.BytesPerPhysicalSector;
accessAlignment->BytesOffsetForSectorAlignment = fdoExtension->FunctionSupportInfo->ReadCapacity16Data.BytesOffsetForSectorAlignment;
// set returned data length
information = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
} else {
information = 0;
}
} else {
// case 2: the request is supported and it completes successfully
// case 3: the request is supported by lower stack but other failure status is returned.
// from now on, the same request will be send down to lower stack directly.
fdoExtension->FunctionSupportInfo->LowerLayerSupport.AccessAlignmentProperty = Supported;
information = (ULONG)Irp->IoStatus.Information;
}
goto Exit;
break;
}
case NotSupported: {
// ClassReadCapacity16() will either return status from cached data or send command to retrieve the information.
status = ClassReadCapacity16(fdoExtension, Srb);
if (NT_SUCCESS(status)) {
RtlZeroMemory(accessAlignment, length);
accessAlignment->Version = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
accessAlignment->Size = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
accessAlignment->BytesPerLogicalSector = fdoExtension->FunctionSupportInfo->ReadCapacity16Data.BytesPerLogicalSector;
accessAlignment->BytesPerPhysicalSector = fdoExtension->FunctionSupportInfo->ReadCapacity16Data.BytesPerPhysicalSector;
accessAlignment->BytesOffsetForSectorAlignment = fdoExtension->FunctionSupportInfo->ReadCapacity16Data.BytesOffsetForSectorAlignment;
information = sizeof(STORAGE_ACCESS_ALIGNMENT_DESCRIPTOR);
} else {
information = 0;
}
goto Exit;
break;
}
case Supported: {
NT_ASSERT(FALSE); // this case is handled at the beginning of the function.
status = STATUS_INTERNAL_ERROR;
break;
}
} // end of switch (fdoExtension->FunctionSupportInfo->LowerLayerSupport.AccessAlignmentProperty)
Exit:
//
// Set the size and status in IRP
//
Irp->IoStatus.Information = information;
Irp->IoStatus.Status = status;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
return status;
}
NTSTATUS
__inline
IncursSeekPenalty (
_In_ USHORT MediumRotationRate,
_In_ PBOOLEAN IncursSeekPenalty
)
{
NTSTATUS status;
if (MediumRotationRate == 0x0001) {
// Non-rotating media (e.g., solid state device)
*IncursSeekPenalty = FALSE;
status = STATUS_SUCCESS;
} else if ( (MediumRotationRate >= 0x401) &&
(MediumRotationRate <= 0xFFFE) ) {
// Nominal media rotation rate in rotations per minute (rpm)
*IncursSeekPenalty = TRUE;
status = STATUS_SUCCESS;
} else {
// Unknown cases:
// 0 - Rate not reported
// 0002h-0400h - Reserved
// FFFFh - Reserved
status = STATUS_UNSUCCESSFUL;
}
return status;
}
NTSTATUS
ClasspDeviceMediaTypeProperty(
_In_ PDEVICE_OBJECT DeviceObject,
_Inout_ PIRP Irp,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
/*++
Routine Description:
This routine returns the medium product type reported by the device for the associated LU.
This function must be called at IRQL < DISPATCH_LEVEL.
Arguments:
DeviceObject - Supplies the device object associated with this request
Irp - The IRP to be processed
Srb - The SRB associated with the request
Return Value:
NTSTATUS code
--*/
{
NTSTATUS status = STATUS_UNSUCCESSFUL;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PSTORAGE_PROPERTY_QUERY query = (PSTORAGE_PROPERTY_QUERY)Irp->AssociatedIrp.SystemBuffer;
PSTORAGE_MEDIUM_PRODUCT_TYPE_DESCRIPTOR pDesc = (PSTORAGE_MEDIUM_PRODUCT_TYPE_DESCRIPTOR)Irp->AssociatedIrp.SystemBuffer;
PIO_STACK_LOCATION irpStack;
ULONG length = 0;
ULONG information = 0;
irpStack = IoGetCurrentIrpStackLocation(Irp);
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspDeviceMediaTypeProperty (%p): Entering function.\n",
DeviceObject));
//
// Check proper query type.
//
if (query->QueryType == PropertyExistsQuery) {
//
// In order to maintain consistency with the how the rest of the properties
// are handled, always return success for PropertyExistsQuery.
//
status = STATUS_SUCCESS;
goto __ClasspDeviceMediaTypeProperty_Exit;
} else if (query->QueryType != PropertyStandardQuery) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceMediaTypeProperty (%p): Unsupported query type %x for media type property.\n",
DeviceObject,
query->QueryType));
status = STATUS_NOT_SUPPORTED;
goto __ClasspDeviceMediaTypeProperty_Exit;
}
//
// Validate the request.
// InputBufferLength and IsFdo have already been validated.
//
if (KeGetCurrentIrql() >= DISPATCH_LEVEL) {
NT_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceMediaTypeProperty (%p): Query property for media type at incorrect IRQL.\n",
DeviceObject));
status = STATUS_INVALID_LEVEL;
goto __ClasspDeviceMediaTypeProperty_Exit;
}
length = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
if (length >= sizeof(STORAGE_DESCRIPTOR_HEADER)) {
information = sizeof(STORAGE_MEDIUM_PRODUCT_TYPE_DESCRIPTOR);
pDesc->Version = sizeof(STORAGE_MEDIUM_PRODUCT_TYPE_DESCRIPTOR);
pDesc->Size = sizeof(STORAGE_MEDIUM_PRODUCT_TYPE_DESCRIPTOR);
} else {
status = STATUS_BUFFER_TOO_SMALL;
goto __ClasspDeviceMediaTypeProperty_Exit;
}
if (length < sizeof(STORAGE_MEDIUM_PRODUCT_TYPE_DESCRIPTOR)) {
status = STATUS_SUCCESS;
goto __ClasspDeviceMediaTypeProperty_Exit;
}
//
// Only query BlockDeviceCharacteristics VPD page if device support has been confirmed.
//
if (fdoExtension->FunctionSupportInfo->ValidInquiryPages.BlockDeviceCharacteristics == TRUE) {
status = ClasspDeviceGetBlockDeviceCharacteristicsVPDPage(fdoExtension, Srb);
} else {
//
// Otherwise device was previously found lacking support for this VPD page. Fail the request.
//
status = STATUS_INVALID_DEVICE_REQUEST;
goto __ClasspDeviceMediaTypeProperty_Exit;
}
if (!NT_SUCCESS(status)) {
status = fdoExtension->FunctionSupportInfo->DeviceCharacteristicsData.CommandStatus;
information = 0;
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceGetBlockDeviceCharacteristicsVPDPage (%p): VPD retrieval fails with %x.\n",
DeviceObject,
status));
goto __ClasspDeviceMediaTypeProperty_Exit;
}
//
// Fill in the output buffer. All data is copied from the FDO extension, cached
// from device response to earlier VPD_BLOCK_DEVICE_CHARACTERISTICS query.
//
pDesc->MediumProductType = fdoExtension->FunctionSupportInfo->DeviceCharacteristicsData.MediumProductType;
status = STATUS_SUCCESS;
__ClasspDeviceMediaTypeProperty_Exit:
//
// Set the size and status in IRP
//
Irp->IoStatus.Information = information;
Irp->IoStatus.Status = status;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspDeviceMediaTypeProperty (%p): Exiting function with status %x.\n",
DeviceObject,
status));
return status;
}
NTSTATUS ClasspDeviceGetBlockDeviceCharacteristicsVPDPage(
_In_ PFUNCTIONAL_DEVICE_EXTENSION fdoExtension,
_In_ PSCSI_REQUEST_BLOCK Srb
)
/*
Routine Description:
This function sends an INQUIRY command request for VPD_BLOCK_DEVICE_CHARACTERISTICS to
the device. Relevant data from the response is cached in the FDO extension.
Arguments:
FdoExtension: The FDO extension of the device to which the INQUIRY command will be sent.
Srb: Allocated by the caller.
SrbSize: The size of the Srb buffer in bytes.
Return Value:
STATUS_INVALID_PARAMETER: May be returned if the LogPage buffer is NULL or
not large enough.
STATUS_SUCCESS: The log page was obtained and placed in the LogPage buffer.
This function may return other NTSTATUS codes from internal function calls.
--*/
{
NTSTATUS status = STATUS_UNSUCCESSFUL;
PCDB cdb;
UCHAR bufferLength = sizeof(VPD_BLOCK_DEVICE_CHARACTERISTICS_PAGE); // data is 64 bytes
ULONG allocationBufferLength = bufferLength;
PVPD_BLOCK_DEVICE_CHARACTERISTICS_PAGE dataBuffer = NULL;
#if defined(_ARM_) || defined(_ARM64_)
//
// ARM has specific alignment requirements, although this will not have a functional impact on x86 or amd64
// based platforms. We are taking the conservative approach here.
//
allocationBufferLength = ALIGN_UP_BY(allocationBufferLength, KeGetRecommendedSharedDataAlignment());
dataBuffer = (PVPD_BLOCK_DEVICE_CHARACTERISTICS_PAGE)
ExAllocatePoolZero(NonPagedPoolNxCacheAligned,
allocationBufferLength,
'5CcS');
#else
dataBuffer = (PVPD_BLOCK_DEVICE_CHARACTERISTICS_PAGE)
ExAllocatePoolZero(NonPagedPoolNx,
bufferLength,
'5CcS');
#endif
if (dataBuffer == NULL) {
status = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
// prepare the Srb
SrbSetTimeOutValue(Srb, fdoExtension->TimeOutValue);
SrbSetRequestTag(Srb, SP_UNTAGGED);
SrbSetRequestAttribute(Srb, SRB_SIMPLE_TAG_REQUEST);
SrbAssignSrbFlags(Srb, fdoExtension->SrbFlags);
SrbSetCdbLength(Srb, 6);
cdb = SrbGetCdb(Srb);
cdb->CDB6INQUIRY3.OperationCode = SCSIOP_INQUIRY;
cdb->CDB6INQUIRY3.EnableVitalProductData = 1; //EVPD bit
cdb->CDB6INQUIRY3.PageCode = VPD_BLOCK_DEVICE_CHARACTERISTICS;
cdb->CDB6INQUIRY3.AllocationLength = bufferLength; //AllocationLength field in CDB6INQUIRY3 is only one byte.
status = ClassSendSrbSynchronous(fdoExtension->CommonExtension.DeviceObject,
Srb,
dataBuffer,
allocationBufferLength,
FALSE);
if (NT_SUCCESS(status)) {
if (SrbGetDataTransferLength(Srb) < 0x8) {
// the device should return at least 8 bytes of data for use.
status = STATUS_UNSUCCESSFUL;
} else if ( (dataBuffer->PageLength != 0x3C) || (dataBuffer->PageCode != VPD_BLOCK_DEVICE_CHARACTERISTICS) ) {
// 'PageLength' shall be 0x3C; and 'PageCode' shall match.
status = STATUS_UNSUCCESSFUL;
} else {
// cache data into fdoExtension
fdoExtension->FunctionSupportInfo->DeviceCharacteristicsData.MediumRotationRate = (dataBuffer->MediumRotationRateMsb << 8) |
dataBuffer->MediumRotationRateLsb;
fdoExtension->FunctionSupportInfo->DeviceCharacteristicsData.MediumProductType = dataBuffer->MediumProductType;
fdoExtension->FunctionSupportInfo->DeviceCharacteristicsData.NominalFormFactor = dataBuffer->NominalFormFactor;
}
} else {
// the command failed, surface up the command error from 'status' variable. Nothing to do here.
}
Exit:
if (dataBuffer != NULL) {
ExFreePool(dataBuffer);
}
return status;
}
NTSTATUS ClasspDeviceSeekPenaltyProperty(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ PIRP Irp,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
/*
At first time of receiving the request, this function will forward it to lower stack to determine if it's supportted.
If it's not supported, INQUIRY (Block Device Characteristics VPD page) will be sent down to retrieve the information.
*/
{
NTSTATUS status = STATUS_UNSUCCESSFUL;
PCOMMON_DEVICE_EXTENSION commonExtension = (PCOMMON_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PSTORAGE_PROPERTY_QUERY query = (PSTORAGE_PROPERTY_QUERY)Irp->AssociatedIrp.SystemBuffer;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
ULONG length = 0;
ULONG information = 0;
BOOLEAN incursSeekPenalty = TRUE;
PDEVICE_SEEK_PENALTY_DESCRIPTOR seekPenalty;
if ( (DeviceObject->DeviceType != FILE_DEVICE_DISK) ||
(TEST_FLAG(DeviceObject->Characteristics, FILE_FLOPPY_DISKETTE)) ||
(fdoExtension->FunctionSupportInfo->LowerLayerSupport.SeekPenaltyProperty == Supported) ) {
// if it's not disk, forward the request to lower layer,
// if the IOCTL is supported by lower stack, forward it down.
IoCopyCurrentIrpStackLocationToNext(Irp);
ClassReleaseRemoveLock(DeviceObject, Irp);
status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
return status;
}
//
// Check proper query type.
//
if (query->QueryType == PropertyExistsQuery) {
status = STATUS_SUCCESS;
goto Exit;
} else if (query->QueryType != PropertyStandardQuery) {
status = STATUS_NOT_SUPPORTED;
goto Exit;
}
//
// Request validation.
// Note that InputBufferLength and IsFdo have been validated beforing entering this routine.
//
if (KeGetCurrentIrql() >= DISPATCH_LEVEL) {
NT_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
status = STATUS_INVALID_LEVEL;
goto Exit;
}
// do not touch this buffer because it can still be used as input buffer for lower layer in 'SupportUnknown' case.
seekPenalty = (PDEVICE_SEEK_PENALTY_DESCRIPTOR)Irp->AssociatedIrp.SystemBuffer;
length = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
if (length < sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR)) {
if (length >= sizeof(STORAGE_DESCRIPTOR_HEADER)) {
information = sizeof(STORAGE_DESCRIPTOR_HEADER);
seekPenalty->Version = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR);
seekPenalty->Size = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR);
status = STATUS_SUCCESS;
goto Exit;
}
status = STATUS_BUFFER_TOO_SMALL;
goto Exit;
}
//
// note that 'Supported' case has been handled at the beginning of this function.
//
switch (fdoExtension->FunctionSupportInfo->LowerLayerSupport.SeekPenaltyProperty) {
case SupportUnknown: {
// send down request and wait for the request to complete.
status = ClassForwardIrpSynchronous(commonExtension, Irp);
if (ClasspLowerLayerNotSupport(status)) {
// case 1: the request is not supported by lower layer, sends down command
// some port drivers (or filter drivers) return STATUS_INVALID_DEVICE_REQUEST if a request is not supported.
// send INQUIRY command if the VPD page is supported.
if (fdoExtension->FunctionSupportInfo->ValidInquiryPages.BlockDeviceCharacteristics == TRUE) {
status = ClasspDeviceGetBlockDeviceCharacteristicsVPDPage(fdoExtension, Srb);
} else {
// the INQUIRY - VPD page command to discover the info is not supported, fail the request.
status = STATUS_INVALID_DEVICE_REQUEST;
}
if (NT_SUCCESS(status)) {
status = IncursSeekPenalty(fdoExtension->FunctionSupportInfo->DeviceCharacteristicsData.MediumRotationRate, &incursSeekPenalty);
}
fdoExtension->FunctionSupportInfo->DeviceCharacteristicsData.CommandStatus = status;
// data is ready in fdoExtension
// set the support status after the SCSI command is executed to avoid racing condition between multiple same type of requests.
fdoExtension->FunctionSupportInfo->LowerLayerSupport.SeekPenaltyProperty = NotSupported;
// fill output buffer
if (NT_SUCCESS(status)) {
RtlZeroMemory(seekPenalty, length);
seekPenalty->Version = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR);
seekPenalty->Size = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR);
seekPenalty->IncursSeekPenalty = incursSeekPenalty;
information = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR);
} else {
information = 0;
}
} else {
// case 2: the request is supported and it completes successfully
// case 3: the request is supported by lower stack but other failure status is returned.
// from now on, the same request will be send down to lower stack directly.
fdoExtension->FunctionSupportInfo->LowerLayerSupport.SeekPenaltyProperty = Supported;
information = (ULONG)Irp->IoStatus.Information;
}
goto Exit;
break;
}
case NotSupported: {
status = fdoExtension->FunctionSupportInfo->DeviceCharacteristicsData.CommandStatus;
if (NT_SUCCESS(status)) {
status = IncursSeekPenalty(fdoExtension->FunctionSupportInfo->DeviceCharacteristicsData.MediumRotationRate, &incursSeekPenalty);
}
if (NT_SUCCESS(status)) {
RtlZeroMemory(seekPenalty, length);
seekPenalty->Version = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR);
seekPenalty->Size = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR);
seekPenalty->IncursSeekPenalty = incursSeekPenalty;
information = sizeof(DEVICE_SEEK_PENALTY_DESCRIPTOR);
} else {
information = 0;
}
goto Exit;
break;
}
case Supported: {
NT_ASSERT(FALSE); // this case is handled at the begining of the function.
break;
}
} // end of switch (fdoExtension->FunctionSupportInfo->LowerLayerSupport.SeekPenaltyProperty)
Exit:
//
// Set the size and status in IRP
//
Irp->IoStatus.Information = information;;
Irp->IoStatus.Status = status;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
return status;
}
NTSTATUS ClasspDeviceGetLBProvisioningVPDPage(
_In_ PDEVICE_OBJECT DeviceObject,
_Inout_opt_ PSCSI_REQUEST_BLOCK Srb
)
{
NTSTATUS status = STATUS_UNSUCCESSFUL;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
USHORT pageLength = 0;
PVOID dataBuffer = NULL;
UCHAR bufferLength = VPD_MAX_BUFFER_SIZE; // use biggest buffer possible
ULONG allocationBufferLength = bufferLength; // Since the CDB size may differ from the actual buffer allocation
PCDB cdb;
ULONG dataTransferLength = 0;
PVPD_LOGICAL_BLOCK_PROVISIONING_PAGE lbProvisioning = NULL;
//
// if the informaiton has been attempted to retrieve, return the cached status.
//
if (fdoExtension->FunctionSupportInfo->LBProvisioningData.CommandStatus != -1) {
// get cached NTSTATUS from previous call.
return fdoExtension->FunctionSupportInfo->LBProvisioningData.CommandStatus;
}
//
// Initialize LBProvisioningData fields to 'unsupported' defaults.
//
fdoExtension->FunctionSupportInfo->LBProvisioningData.ProvisioningType = PROVISIONING_TYPE_UNKNOWN;
fdoExtension->FunctionSupportInfo->LBProvisioningData.LBPRZ = FALSE;
fdoExtension->FunctionSupportInfo->LBProvisioningData.LBPU = FALSE;
fdoExtension->FunctionSupportInfo->LBProvisioningData.ANC_SUP = FALSE;
fdoExtension->FunctionSupportInfo->LBProvisioningData.ThresholdExponent = 0;
//
// Try to get the Thin Provisioning VPD page (0xB2), if it is supported.
//
if (fdoExtension->FunctionSupportInfo->ValidInquiryPages.LBProvisioning == TRUE &&
Srb != NULL)
{
#if defined(_ARM_) || defined(_ARM64_)
//
// ARM has specific alignment requirements, although this will not have a functional impact on x86 or amd64
// based platforms. We are taking the conservative approach here.
//
//
allocationBufferLength = ALIGN_UP_BY(allocationBufferLength, KeGetRecommendedSharedDataAlignment());
dataBuffer = ExAllocatePoolZero(NonPagedPoolNxCacheAligned,
allocationBufferLength,
'0CcS');
#else
dataBuffer = ExAllocatePoolZero(NonPagedPoolNx,
bufferLength,
'0CcS');
#endif
if (dataBuffer == NULL) {
// return without updating FdoExtension->FunctionSupportInfo->LBProvisioningData.CommandStatus
// the field will remain value as "-1", so that the command will be attempted next time this function is called.
status = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
lbProvisioning = (PVPD_LOGICAL_BLOCK_PROVISIONING_PAGE)dataBuffer;
if (fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
status = InitializeStorageRequestBlock((PSTORAGE_REQUEST_BLOCK)Srb,
STORAGE_ADDRESS_TYPE_BTL8,
CLASS_SRBEX_SCSI_CDB16_BUFFER_SIZE,
1,
SrbExDataTypeScsiCdb16);
if (NT_SUCCESS(status)) {
((PSTORAGE_REQUEST_BLOCK)Srb)->SrbFunction = SRB_FUNCTION_EXECUTE_SCSI;
} else {
//
// Should not occur.
//
NT_ASSERT(FALSE);
}
} else {
RtlZeroMemory(Srb, sizeof(SCSI_REQUEST_BLOCK));
Srb->Length = sizeof(SCSI_REQUEST_BLOCK);
Srb->Function = SRB_FUNCTION_EXECUTE_SCSI;
status = STATUS_SUCCESS;
}
if (NT_SUCCESS(status)) {
// prepare the Srb
SrbSetTimeOutValue(Srb, fdoExtension->TimeOutValue);
SrbSetRequestTag(Srb, SP_UNTAGGED);
SrbSetRequestAttribute(Srb, SRB_SIMPLE_TAG_REQUEST);
SrbAssignSrbFlags(Srb, fdoExtension->SrbFlags);
SrbSetCdbLength(Srb, 6);
cdb = SrbGetCdb(Srb);
cdb->CDB6INQUIRY3.OperationCode = SCSIOP_INQUIRY;
cdb->CDB6INQUIRY3.EnableVitalProductData = 1; //EVPD bit
cdb->CDB6INQUIRY3.PageCode = VPD_LOGICAL_BLOCK_PROVISIONING;
cdb->CDB6INQUIRY3.AllocationLength = bufferLength; //AllocationLength field in CDB6INQUIRY3 is only one byte.
status = ClassSendSrbSynchronous(fdoExtension->DeviceObject,
Srb,
dataBuffer,
allocationBufferLength,
FALSE);
dataTransferLength = SrbGetDataTransferLength(Srb);
}
//
// Handle the case where we get back STATUS_DATA_OVERRUN b/c the input
// buffer was larger than necessary.
//
if (status == STATUS_DATA_OVERRUN && dataTransferLength < bufferLength)
{
status = STATUS_SUCCESS;
}
if (NT_SUCCESS(status)) {
REVERSE_BYTES_SHORT(&pageLength, &(lbProvisioning->PageLength));
}
if ( NT_SUCCESS(status) &&
((dataTransferLength < 0x08) ||
(pageLength < (FIELD_OFFSET(VPD_LOGICAL_BLOCK_PROVISIONING_PAGE, Reserved2) - FIELD_OFFSET(VPD_LOGICAL_BLOCK_PROVISIONING_PAGE,ThresholdExponent))) ||
(lbProvisioning->PageCode != VPD_LOGICAL_BLOCK_PROVISIONING)) ) {
// the device should return at least 8 bytes of data for use.
// 'PageCode' shall match and we need all the relevant data after the header.
status = STATUS_INFO_LENGTH_MISMATCH;
}
//
// Fill in the FDO extension with either the data from the VPD page, or
// use defaults if there was an error.
//
if (NT_SUCCESS(status))
{
fdoExtension->FunctionSupportInfo->LBProvisioningData.ProvisioningType = lbProvisioning->ProvisioningType;
fdoExtension->FunctionSupportInfo->LBProvisioningData.LBPRZ = lbProvisioning->LBPRZ;
fdoExtension->FunctionSupportInfo->LBProvisioningData.LBPU = lbProvisioning->LBPU;
fdoExtension->FunctionSupportInfo->LBProvisioningData.ANC_SUP = lbProvisioning->ANC_SUP;
fdoExtension->FunctionSupportInfo->LBProvisioningData.ThresholdExponent = lbProvisioning->ThresholdExponent;
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_PNP,
"ClasspDeviceGetLBProvisioningVPDPage (%p): %s %s (rev %s) reported following parameters: \
\n\t\t\tProvisioningType: %u \
\n\t\t\tLBPRZ: %u \
\n\t\t\tLBPU: %u \
\n\t\t\tANC_SUP: %I64u \
\n\t\t\tThresholdExponent: %u\n",
DeviceObject,
(PCSZ)(((PUCHAR)fdoExtension->DeviceDescriptor) + fdoExtension->DeviceDescriptor->VendorIdOffset),
(PCSZ)(((PUCHAR)fdoExtension->DeviceDescriptor) + fdoExtension->DeviceDescriptor->ProductIdOffset),
(PCSZ)(((PUCHAR)fdoExtension->DeviceDescriptor) + fdoExtension->DeviceDescriptor->ProductRevisionOffset),
lbProvisioning->ProvisioningType,
lbProvisioning->LBPRZ,
lbProvisioning->LBPU,
lbProvisioning->ANC_SUP,
lbProvisioning->ThresholdExponent));
}
} else {
status = STATUS_INVALID_DEVICE_REQUEST;
}
fdoExtension->FunctionSupportInfo->LBProvisioningData.CommandStatus = status;
Exit:
FREE_POOL(dataBuffer);
return status;
}
NTSTATUS ClasspDeviceGetBlockLimitsVPDPage(
_In_ PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
_Inout_bytecount_(SrbSize) PSCSI_REQUEST_BLOCK Srb,
_In_ ULONG SrbSize,
_Out_ PCLASS_VPD_B0_DATA BlockLimitsData
)
{
NTSTATUS status = STATUS_UNSUCCESSFUL;
PVOID dataBuffer = NULL;
UCHAR bufferLength = VPD_MAX_BUFFER_SIZE; // use biggest buffer possible
ULONG allocationBufferLength = bufferLength;
PCDB cdb;
PVPD_BLOCK_LIMITS_PAGE blockLimits = NULL;
ULONG dataTransferLength = 0;
//
// Set default values for UNMAP parameters based upon UNMAP support or lack
// thereof.
//
if (FdoExtension->FunctionSupportInfo->LBProvisioningData.LBPU) {
//
// If UNMAP is supported, we default to the maximum LBA count and
// block descriptor count. We also default the UNMAP granularity to
// a single block and specify no granularity alignment.
//
BlockLimitsData->MaxUnmapLbaCount = (ULONG)-1;
BlockLimitsData->MaxUnmapBlockDescrCount = (ULONG)-1;
BlockLimitsData->OptimalUnmapGranularity = 1;
BlockLimitsData->UnmapGranularityAlignment = 0;
BlockLimitsData->UGAVALID = FALSE;
} else {
BlockLimitsData->MaxUnmapLbaCount = 0;
BlockLimitsData->MaxUnmapBlockDescrCount = 0;
BlockLimitsData->OptimalUnmapGranularity = 0;
BlockLimitsData->UnmapGranularityAlignment = 0;
BlockLimitsData->UGAVALID = FALSE;
}
//
// Try to get the Block Limits VPD page (0xB0), if it is supported.
//
if (FdoExtension->FunctionSupportInfo->ValidInquiryPages.BlockLimits == TRUE)
{
#if defined(_ARM_) || defined(_ARM64_)
//
// ARM has specific alignment requirements, although this will not have a functional impact on x86 or amd64
// based platforms. We are taking the conservative approach here.
//
allocationBufferLength = ALIGN_UP_BY(allocationBufferLength, KeGetRecommendedSharedDataAlignment());
dataBuffer = ExAllocatePoolZero(NonPagedPoolNxCacheAligned,
allocationBufferLength,
'0CcS');
#else
dataBuffer = ExAllocatePoolZero(NonPagedPoolNx,
bufferLength,
'0CcS');
#endif
if (dataBuffer == NULL)
{
// return without updating FdoExtension->FunctionSupportInfo->BlockLimitsData.CommandStatus
// the field will remain value as "-1", so that the command will be attempted next time this function is called.
status = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
blockLimits = (PVPD_BLOCK_LIMITS_PAGE)dataBuffer;
if (FdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
#pragma prefast(suppress:26015, "InitializeStorageRequestBlock ensures buffer access is bounded")
status = InitializeStorageRequestBlock((PSTORAGE_REQUEST_BLOCK)Srb,
STORAGE_ADDRESS_TYPE_BTL8,
SrbSize,
1,
SrbExDataTypeScsiCdb16);
if (NT_SUCCESS(status)) {
((PSTORAGE_REQUEST_BLOCK)Srb)->SrbFunction = SRB_FUNCTION_EXECUTE_SCSI;
} else {
//
// Should not occur.
//
NT_ASSERT(FALSE);
}
} else {
RtlZeroMemory(Srb, sizeof(SCSI_REQUEST_BLOCK));
Srb->Length = sizeof(SCSI_REQUEST_BLOCK);
Srb->Function = SRB_FUNCTION_EXECUTE_SCSI;
status = STATUS_SUCCESS;
}
if (NT_SUCCESS(status)) {
// prepare the Srb
SrbSetTimeOutValue(Srb, FdoExtension->TimeOutValue);
SrbSetRequestTag(Srb, SP_UNTAGGED);
SrbSetRequestAttribute(Srb, SRB_SIMPLE_TAG_REQUEST);
SrbAssignSrbFlags(Srb, FdoExtension->SrbFlags);
SrbSetCdbLength(Srb, 6);
cdb = SrbGetCdb(Srb);
cdb->CDB6INQUIRY3.OperationCode = SCSIOP_INQUIRY;
cdb->CDB6INQUIRY3.EnableVitalProductData = 1; //EVPD bit
cdb->CDB6INQUIRY3.PageCode = VPD_BLOCK_LIMITS;
cdb->CDB6INQUIRY3.AllocationLength = bufferLength; //AllocationLength field in CDB6INQUIRY3 is only one byte.
status = ClassSendSrbSynchronous(FdoExtension->DeviceObject,
Srb,
dataBuffer,
allocationBufferLength,
FALSE);
dataTransferLength = SrbGetDataTransferLength(Srb);
}
//
// Handle the case where we get back STATUS_DATA_OVERRUN b/c the input
// buffer was larger than necessary.
//
if (status == STATUS_DATA_OVERRUN && dataTransferLength < bufferLength)
{
status = STATUS_SUCCESS;
}
if (NT_SUCCESS(status))
{
USHORT pageLength;
REVERSE_BYTES_SHORT(&pageLength, &(blockLimits->PageLength));
//
// Regardless of the device's support for unmap, cache away at least the basic block limits information
//
if (dataTransferLength >= 0x10 && blockLimits->PageCode == VPD_BLOCK_LIMITS) {
// (6:7) OPTIMAL TRANSFER LENGTH GRANULARITY
REVERSE_BYTES_SHORT(&BlockLimitsData->OptimalTransferLengthGranularity, &blockLimits->OptimalTransferLengthGranularity);
// (8:11) MAXIMUM TRANSFER LENGTH
REVERSE_BYTES(&BlockLimitsData->MaximumTransferLength, &blockLimits->MaximumTransferLength);
// (12:15) OPTIMAL TRANSFER LENGTH
REVERSE_BYTES(&BlockLimitsData->OptimalTransferLength, &blockLimits->OptimalTransferLength);
}
if ((dataTransferLength < 0x24) ||
(pageLength < (FIELD_OFFSET(VPD_BLOCK_LIMITS_PAGE,Reserved1) - FIELD_OFFSET(VPD_BLOCK_LIMITS_PAGE,Reserved0))) ||
(blockLimits->PageCode != VPD_BLOCK_LIMITS))
{
// the device should return at least 36 bytes of data for use.
// 'PageCode' shall match and we need all the relevant data after the header.
status = STATUS_INFO_LENGTH_MISMATCH;
}
}
if (NT_SUCCESS(status))
{
// cache data into FdoExtension
// (20:23) MAXIMUM UNMAP LBA COUNT
REVERSE_BYTES(&BlockLimitsData->MaxUnmapLbaCount, &blockLimits->MaximumUnmapLBACount);
// (24:27) MAXIMUM UNMAP BLOCK DESCRIPTOR COUNT
REVERSE_BYTES(&BlockLimitsData->MaxUnmapBlockDescrCount, &blockLimits->MaximumUnmapBlockDescriptorCount);
// (28:31) OPTIMAL UNMAP GRANULARITY
REVERSE_BYTES(&BlockLimitsData->OptimalUnmapGranularity, &blockLimits->OptimalUnmapGranularity);
// (32:35) UNMAP GRANULARITY ALIGNMENT; (32) bit7: UGAVALID
BlockLimitsData->UGAVALID = blockLimits->UGAValid;
if (BlockLimitsData->UGAVALID == TRUE) {
REVERSE_BYTES(&BlockLimitsData->UnmapGranularityAlignment, &blockLimits->UnmapGranularityAlignment);
BlockLimitsData->UnmapGranularityAlignment &= 0x7FFFFFFF; // remove value of UGAVALID bit.
} else {
BlockLimitsData->UnmapGranularityAlignment = 0;
}
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_PNP,
"ClasspDeviceGetBlockLimitsVPDPage (%p): %s %s (rev %s) reported following parameters: \
\n\t\t\tOptimalTransferLengthGranularity: %u \
\n\t\t\tMaximumTransferLength: %u \
\n\t\t\tOptimalTransferLength: %u \
\n\t\t\tMaximumUnmapLBACount: %u \
\n\t\t\tMaximumUnmapBlockDescriptorCount: %u \
\n\t\t\tOptimalUnmapGranularity: %u \
\n\t\t\tUGAValid: %u \
\n\t\t\tUnmapGranularityAlignment: %u\n",
FdoExtension->DeviceObject,
(PCSZ)(((PUCHAR)FdoExtension->DeviceDescriptor) + FdoExtension->DeviceDescriptor->VendorIdOffset),
(PCSZ)(((PUCHAR)FdoExtension->DeviceDescriptor) + FdoExtension->DeviceDescriptor->ProductIdOffset),
(PCSZ)(((PUCHAR)FdoExtension->DeviceDescriptor) + FdoExtension->DeviceDescriptor->ProductRevisionOffset),
BlockLimitsData->OptimalTransferLengthGranularity,
BlockLimitsData->MaximumTransferLength,
BlockLimitsData->OptimalTransferLength,
BlockLimitsData->MaxUnmapLbaCount,
BlockLimitsData->MaxUnmapBlockDescrCount,
BlockLimitsData->OptimalUnmapGranularity,
BlockLimitsData->UGAVALID,
BlockLimitsData->UnmapGranularityAlignment));
}
} else {
status = STATUS_INVALID_DEVICE_REQUEST;
}
BlockLimitsData->CommandStatus = status;
Exit:
FREE_POOL(dataBuffer);
return status;
}
NTSTATUS ClasspDeviceTrimProperty(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ PIRP Irp,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
/*
At first time of receiving the request, this function will forward it to lower stack to determine if it's supportted.
If it's not supported, INQUIRY (Block Limits VPD page) will be sent down to retrieve the information.
*/
{
NTSTATUS status = STATUS_SUCCESS;
PCOMMON_DEVICE_EXTENSION commonExtension = (PCOMMON_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PSTORAGE_PROPERTY_QUERY query = (PSTORAGE_PROPERTY_QUERY)Irp->AssociatedIrp.SystemBuffer;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
ULONG length = 0;
ULONG information = 0;
PDEVICE_TRIM_DESCRIPTOR trimDescr;
UNREFERENCED_PARAMETER(Srb);
if ( (DeviceObject->DeviceType != FILE_DEVICE_DISK) ||
(TEST_FLAG(DeviceObject->Characteristics, FILE_FLOPPY_DISKETTE)) ||
(fdoExtension->FunctionSupportInfo->LowerLayerSupport.TrimProperty == Supported) ) {
// if it's not disk, forward the request to lower layer,
// if the IOCTL is supported by lower stack, forward it down.
IoCopyCurrentIrpStackLocationToNext(Irp);
ClassReleaseRemoveLock(DeviceObject, Irp);
status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
return status;
}
//
// Check proper query type.
//
if (query->QueryType == PropertyExistsQuery) {
status = STATUS_SUCCESS;
goto Exit;
} else if (query->QueryType != PropertyStandardQuery) {
status = STATUS_NOT_SUPPORTED;
goto Exit;
}
//
// Request validation.
// Note that InputBufferLength and IsFdo have been validated beforing entering this routine.
//
if (KeGetCurrentIrql() >= DISPATCH_LEVEL) {
NT_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
status = STATUS_INVALID_LEVEL;
goto Exit;
}
// do not touch this buffer because it can still be used as input buffer for lower layer in 'SupportUnknown' case.
trimDescr = (PDEVICE_TRIM_DESCRIPTOR)Irp->AssociatedIrp.SystemBuffer;
length = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
if (length < sizeof(DEVICE_TRIM_DESCRIPTOR)) {
if (length >= sizeof(STORAGE_DESCRIPTOR_HEADER)) {
information = sizeof(STORAGE_DESCRIPTOR_HEADER);
trimDescr->Version = sizeof(DEVICE_TRIM_DESCRIPTOR);
trimDescr->Size = sizeof(DEVICE_TRIM_DESCRIPTOR);
status = STATUS_SUCCESS;
goto Exit;
}
status = STATUS_BUFFER_TOO_SMALL;
goto Exit;
}
//
// note that 'Supported' case has been handled at the beginning of this function.
//
switch (fdoExtension->FunctionSupportInfo->LowerLayerSupport.TrimProperty) {
case SupportUnknown: {
// send down request and wait for the request to complete.
status = ClassForwardIrpSynchronous(commonExtension, Irp);
if ( (status == STATUS_NOT_SUPPORTED) ||
(status == STATUS_NOT_IMPLEMENTED) ||
(status == STATUS_INVALID_DEVICE_REQUEST) ||
(status == STATUS_INVALID_PARAMETER_1) ) {
// case 1: the request is not supported by lower layer, sends down command
// some port drivers (or filter drivers) return STATUS_INVALID_DEVICE_REQUEST if a request is not supported.
status = fdoExtension->FunctionSupportInfo->LBProvisioningData.CommandStatus;
NT_ASSERT(status != -1);
// data is ready in fdoExtension
// set the support status after the SCSI command is executed to avoid racing condition between multiple same type of requests.
fdoExtension->FunctionSupportInfo->LowerLayerSupport.TrimProperty = NotSupported;
if (NT_SUCCESS(status)) {
// fill output buffer
RtlZeroMemory(trimDescr, length);
trimDescr->Version = sizeof(DEVICE_TRIM_DESCRIPTOR);
trimDescr->Size = sizeof(DEVICE_TRIM_DESCRIPTOR);
trimDescr->TrimEnabled = ClasspSupportsUnmap(fdoExtension->FunctionSupportInfo);
// set returned data length
information = sizeof(DEVICE_TRIM_DESCRIPTOR);
} else {
// there was error retrieving TrimProperty. Surface the error up from 'status' variable.
information = 0;
}
goto Exit;
} else {
// case 2: the request is supported and it completes successfully
// case 3: the request is supported by lower stack but other failure status is returned.
// from now on, the same request will be send down to lower stack directly.
fdoExtension->FunctionSupportInfo->LowerLayerSupport.TrimProperty = Supported;
information = (ULONG)Irp->IoStatus.Information;
goto Exit;
}
break;
}
case NotSupported: {
status = fdoExtension->FunctionSupportInfo->LBProvisioningData.CommandStatus;
NT_ASSERT(status != -1);
if (NT_SUCCESS(status)) {
RtlZeroMemory(trimDescr, length);
trimDescr->Version = sizeof(DEVICE_TRIM_DESCRIPTOR);
trimDescr->Size = sizeof(DEVICE_TRIM_DESCRIPTOR);
trimDescr->TrimEnabled = ClasspSupportsUnmap(fdoExtension->FunctionSupportInfo);
information = sizeof(DEVICE_TRIM_DESCRIPTOR);
} else {
information = 0;
}
goto Exit;
break;
}
case Supported: {
NT_ASSERT(FALSE); // this case is handled at the begining of the function.
break;
}
} // end of switch (fdoExtension->FunctionSupportInfo->LowerLayerSupport.TrimProperty)
Exit:
//
// Set the size and status in IRP
//
Irp->IoStatus.Information = information;
Irp->IoStatus.Status = status;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
return status;
}
NTSTATUS ClasspDeviceLBProvisioningProperty(
_In_ PDEVICE_OBJECT DeviceObject,
_Inout_ PIRP Irp,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
{
NTSTATUS status = STATUS_SUCCESS;
NTSTATUS blockLimitsStatus;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PSTORAGE_PROPERTY_QUERY query = (PSTORAGE_PROPERTY_QUERY)Irp->AssociatedIrp.SystemBuffer;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
ULONG length = 0;
ULONG information = 0;
CLASS_VPD_B0_DATA blockLimitsData;
ULONG generationCount;
PDEVICE_LB_PROVISIONING_DESCRIPTOR lbpDescr;
UNREFERENCED_PARAMETER(Srb);
//
// Check proper query type.
//
if (query->QueryType == PropertyExistsQuery) {
status = STATUS_SUCCESS;
goto Exit;
} else if (query->QueryType != PropertyStandardQuery) {
status = STATUS_NOT_SUPPORTED;
goto Exit;
}
//
// Request validation.
// Note that InputBufferLength and IsFdo have been validated beforing entering this routine.
//
if (KeGetCurrentIrql() >= DISPATCH_LEVEL) {
NT_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
status = STATUS_INVALID_LEVEL;
goto Exit;
}
lbpDescr = (PDEVICE_LB_PROVISIONING_DESCRIPTOR)Irp->AssociatedIrp.SystemBuffer;
length = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
RtlZeroMemory(lbpDescr, length);
if (length < DEVICE_LB_PROVISIONING_DESCRIPTOR_V1_SIZE) {
if (length >= sizeof(STORAGE_DESCRIPTOR_HEADER)) {
information = sizeof(STORAGE_DESCRIPTOR_HEADER);
lbpDescr->Version = sizeof(DEVICE_LB_PROVISIONING_DESCRIPTOR);
lbpDescr->Size = sizeof(DEVICE_LB_PROVISIONING_DESCRIPTOR);
status = STATUS_SUCCESS;
goto Exit;
}
status = STATUS_BUFFER_TOO_SMALL;
goto Exit;
}
//
// Set the structure version/size based upon the size of the given output
// buffer. We may be working with an older component that was built with
// the V1 structure definition.
//
if (length < sizeof(DEVICE_LB_PROVISIONING_DESCRIPTOR)) {
lbpDescr->Version = DEVICE_LB_PROVISIONING_DESCRIPTOR_V1_SIZE;
lbpDescr->Size = DEVICE_LB_PROVISIONING_DESCRIPTOR_V1_SIZE;
information = DEVICE_LB_PROVISIONING_DESCRIPTOR_V1_SIZE;
} else {
lbpDescr->Version = sizeof(DEVICE_LB_PROVISIONING_DESCRIPTOR);
lbpDescr->Size = sizeof(DEVICE_LB_PROVISIONING_DESCRIPTOR);
information = sizeof(DEVICE_LB_PROVISIONING_DESCRIPTOR);
}
//
// Take a snapshot of the block limits data since it can change.
// If we failed to get the block limits data, we'll just set the Optimal
// Unmap Granularity (and alignment) will default to 0. We don't want to
// fail the request outright since there is some non-block limits data that
// we can return.
//
blockLimitsStatus = ClasspBlockLimitsDataSnapshot(fdoExtension,
TRUE,
&blockLimitsData,
&generationCount);
//
// Fill in the output buffer. All data is copied from the FDO extension where we
// cached Logical Block Provisioning info when the device was first initialized.
//
lbpDescr->ThinProvisioningEnabled = ClasspIsThinProvisioned(fdoExtension->FunctionSupportInfo);
//
// Make sure we have a non-zero value for the number of bytes per block.
//
if (fdoExtension->DiskGeometry.BytesPerSector == 0)
{
status = ClassReadDriveCapacity(fdoExtension->DeviceObject);
if(!NT_SUCCESS(status) || fdoExtension->DiskGeometry.BytesPerSector == 0)
{
status = STATUS_INVALID_DEVICE_REQUEST;
information = 0;
goto Exit;
}
}
lbpDescr->ThinProvisioningReadZeros = fdoExtension->FunctionSupportInfo->LBProvisioningData.LBPRZ;
lbpDescr->AnchorSupported = fdoExtension->FunctionSupportInfo->LBProvisioningData.ANC_SUP;
if (NT_SUCCESS(blockLimitsStatus)) {
lbpDescr->UnmapGranularityAlignmentValid = blockLimitsData.UGAVALID;
//
// Granularity and Alignment are given to us in units of blocks,
// but we convert and return them in bytes as it is more convenient
// to the caller.
//
lbpDescr->OptimalUnmapGranularity = (ULONGLONG)blockLimitsData.OptimalUnmapGranularity * fdoExtension->DiskGeometry.BytesPerSector;
lbpDescr->UnmapGranularityAlignment = (ULONGLONG)blockLimitsData.UnmapGranularityAlignment * fdoExtension->DiskGeometry.BytesPerSector;
#if (NTDDI_VERSION >= NTDDI_WINBLUE)
//
// If the output buffer is large enough (i.e. not a V1 structure) copy
// over the max UNMAP LBA count and max UNMAP block descriptor count.
//
if (length >= sizeof(DEVICE_LB_PROVISIONING_DESCRIPTOR)) {
lbpDescr->MaxUnmapLbaCount = blockLimitsData.MaxUnmapLbaCount;
lbpDescr->MaxUnmapBlockDescriptorCount = blockLimitsData.MaxUnmapBlockDescrCount;
}
#endif
}
Exit:
//
// Set the size and status in IRP
//
Irp->IoStatus.Information = information;
Irp->IoStatus.Status = status;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
return status;
}
VOID
ConvertDataSetRangeToUnmapBlockDescr(
_In_ PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
_In_ PUNMAP_BLOCK_DESCRIPTOR BlockDescr,
_Inout_ PULONG CurrentBlockDescrIndex,
_In_ ULONG MaxBlockDescrIndex,
_Inout_ PULONGLONG CurrentLbaCount,
_In_ ULONGLONG MaxLbaCount,
_Inout_ PDEVICE_DATA_SET_RANGE DataSetRange
)
/*++
Routine Description:
Convert DEVICE_DATA_SET_RANGE entry to be UNMAP_BLOCK_DESCRIPTOR entries.
As LengthInBytes field in DEVICE_DATA_SET_RANGE structure is 64 bits (bytes)
and LbaCount field in UNMAP_BLOCK_DESCRIPTOR structure is 32 bits (sectors),
it's possible that one DEVICE_DATA_SET_RANGE entry needs multiple UNMAP_BLOCK_DESCRIPTOR entries.
We must also take the unmap granularity into consideration and split up the
the given ranges so that they are aligned with the specified granularity.
Arguments:
All arguments must be validated by the caller.
FdoExtension - The FDO extension of the device to which the unmap
command that will use the resulting unmap block descriptors will be
sent.
BlockDescr - Pointer to a buffer that will contain the unmap block
descriptors. This buffer should be allocated by the caller and the
caller should also ensure that it is large enough to contain all the
requested descriptors. Its size is implied by MaxBlockDescrIndex.
CurrentBlockDescrIndex - This contains the next block descriptor index to
be processed when this function returns. This function should be called
again with the same parameter to continue processing.
MaxBlockDescrIndex - This is the index of the last unmap block descriptor,
provided so that the function does not go off the end of BlockDescr.
CurrentLbaCount - This contains the number of LBAs left to be processed
when this function returns. This function should be called again with
the same parameter to continue processing.
MaxLbaCount - This is the max number of LBAs that can be sent in a single
unmap command.
DataSetRange - This range will be modified to reflect the un-converted part.
It must be valid (including being granularity-aligned) when it is first
passed to this function.
Return Value:
Count of UNMAP_BLOCK_DESCRIPTOR entries converted.
NOTE: if LengthInBytes does not reach to 0, the conversion for DEVICE_DATA_SET_RANGE entry
is not completed. Further conversion is needed by calling this function again.
--*/
{
ULONGLONG startingSector;
ULONGLONG sectorCount;
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_IOCTL,
"ConvertDataSetRangeToUnmapBlockDescr (%p): Generating UNMAP Block Descriptors from DataSetRange: \
\n\t\tStartingOffset = %I64u bytes \
\n\t\tLength = %I64u bytes\n",
FdoExtension->DeviceObject,
DataSetRange->StartingOffset,
DataSetRange->LengthInBytes));
while ( (DataSetRange->LengthInBytes > 0) &&
(*CurrentBlockDescrIndex < MaxBlockDescrIndex) &&
(*CurrentLbaCount < MaxLbaCount) ) {
//
// Convert the starting offset and length from bytes to blocks.
//
startingSector = (ULONGLONG)(DataSetRange->StartingOffset / FdoExtension->DiskGeometry.BytesPerSector);
sectorCount = (DataSetRange->LengthInBytes / FdoExtension->DiskGeometry.BytesPerSector);
//
// Make sure the sector count isn't more than can be specified with a
// single descriptor.
//
if (sectorCount > MAXULONG) {
sectorCount = MAXULONG;
}
//
// The max LBA count is the max number of LBAs that can be unmapped with
// a single UNMAP command. Make sure we don't exceed this value.
//
if ((*CurrentLbaCount + sectorCount) > MaxLbaCount) {
sectorCount = MaxLbaCount - *CurrentLbaCount;
}
REVERSE_BYTES_QUAD(BlockDescr[*CurrentBlockDescrIndex].StartingLba, &startingSector);
REVERSE_BYTES(BlockDescr[*CurrentBlockDescrIndex].LbaCount, (PULONG)§orCount);
DataSetRange->StartingOffset += sectorCount * FdoExtension->DiskGeometry.BytesPerSector;
DataSetRange->LengthInBytes -= sectorCount * FdoExtension->DiskGeometry.BytesPerSector;
*CurrentBlockDescrIndex += 1;
*CurrentLbaCount += (ULONG)sectorCount;
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_IOCTL,
"ConvertDataSetRangeToUnmapBlockDescr (%p): Generated UNMAP Block Descriptor: \
\n\t\t\tStartingLBA = %I64u \
\n\t\t\tLBACount = %I64u\n",
FdoExtension->DeviceObject,
startingSector,
sectorCount));
}
return;
}
NTSTATUS
DeviceProcessDsmTrimRequest(
_In_ PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
_In_ PDEVICE_DATA_SET_RANGE DataSetRanges,
_In_ ULONG DataSetRangesCount,
_In_ ULONG UnmapGranularity,
_In_ ULONG SrbFlags,
_In_ PIRP Irp,
_In_ PGUID ActivityId,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
/*++
Routine Description:
Process TRIM request that received from upper layer.
Arguments:
FdoExtension
DataSetRanges - this parameter must be already validated in caller.
DataSetRangesCount - this parameter must be already validated in caller.
UnmapGranularity - The unmap granularity in blocks. This is used to split
up the unmap command into chunks that are granularity-aligned.
Srb - The SRB to use for the unmap command. The caller must allocate it,
but this function will take care of initialzing it.
Return Value:
status of the operation
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PUNMAP_LIST_HEADER buffer = NULL;
PUNMAP_BLOCK_DESCRIPTOR blockDescrPointer;
ULONG bufferLength;
ULONG maxBlockDescrCount;
ULONG neededBlockDescrCount;
ULONG i;
BOOLEAN allDataSetRangeFullyConverted;
BOOLEAN needToSendCommand;
BOOLEAN tempDataSetRangeFullyConverted;
ULONG dataSetRangeIndex;
DEVICE_DATA_SET_RANGE tempDataSetRange;
ULONG blockDescrIndex;
ULONGLONG lbaCount;
ULONGLONG maxLbaCount;
ULONGLONG maxParameterListLength;
UNREFERENCED_PARAMETER(UnmapGranularity);
UNREFERENCED_PARAMETER(ActivityId);
UNREFERENCED_PARAMETER(Irp);
//
// The given LBA ranges are in DEVICE_DATA_SET_RANGE format and need to be converted into UNMAP Block Descriptors.
// The UNMAP command is able to carry 0xFFFF bytes (0xFFF8 in reality as there are 8 bytes of header plus n*16 bytes of Block Descriptors) of data.
// The actual size will also be constrained by the Maximum LBA Count and Maximum Transfer Length.
//
//
// 1.1 Calculate how many Block Descriptors are needed to complete this request.
//
neededBlockDescrCount = 0;
for (i = 0; i < DataSetRangesCount; i++) {
lbaCount = DataSetRanges[i].LengthInBytes / FdoExtension->DiskGeometry.BytesPerSector;
//
// 1.1.1 the UNMAP_BLOCK_DESCRIPTOR LbaCount is 32 bits, the max value is 0xFFFFFFFF
//
if (lbaCount > 0) {
neededBlockDescrCount += (ULONG)((lbaCount - 1) / MAXULONG + 1);
}
}
//
// Honor Max Unmap Block Descriptor Count if it has been specified. Otherwise,
// use the maximum value that the Parameter List Length field will allow (0xFFFF).
// If the count is 0xFFFFFFFF, then no maximum is specified.
//
if (FdoExtension->FunctionSupportInfo->BlockLimitsData.MaxUnmapBlockDescrCount != 0 &&
FdoExtension->FunctionSupportInfo->BlockLimitsData.MaxUnmapBlockDescrCount != MAXULONG)
{
maxParameterListLength = (ULONGLONG)(FdoExtension->FunctionSupportInfo->BlockLimitsData.MaxUnmapBlockDescrCount * sizeof(UNMAP_BLOCK_DESCRIPTOR))
+ sizeof(UNMAP_LIST_HEADER);
//
// In the SBC-3, the Max Unmap Block Descriptor Count field in the 0xB0
// page is 4 bytes and the Parameter List Length in the UNMAP command is
// 2 bytes, therefore it is possible that the Max Unmap Block Descriptor
// Count could imply more bytes than can be specified in the Parameter
// List Length field. Adjust for that here.
//
maxParameterListLength = min(maxParameterListLength, MAXUSHORT);
}
else
{
maxParameterListLength = MAXUSHORT;
}
//
// 1.2 Calculate the buffer size needed, capped by the device's limitations.
//
bufferLength = min(FdoExtension->PrivateFdoData->HwMaxXferLen, (ULONG)maxParameterListLength);
bufferLength = min(bufferLength, (neededBlockDescrCount * sizeof(UNMAP_BLOCK_DESCRIPTOR) + sizeof(UNMAP_LIST_HEADER)));
maxBlockDescrCount = (bufferLength - sizeof(UNMAP_LIST_HEADER)) / sizeof(UNMAP_BLOCK_DESCRIPTOR);
if (maxBlockDescrCount == 0) {
//
// This shouldn't happen since we've already done validation.
//
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_IOCTL,
"DeviceProcessDsmTrimRequest (%p): Max Block Descriptor count is Zero\n",
FdoExtension->DeviceObject));
NT_ASSERT(maxBlockDescrCount != 0);
status = STATUS_DATA_ERROR;
goto Exit;
}
//
// The Maximum LBA Count is set during device initialization.
//
maxLbaCount = (ULONGLONG)FdoExtension->FunctionSupportInfo->BlockLimitsData.MaxUnmapLbaCount;
if (maxLbaCount == 0) {
//
// This shouldn't happen since we've already done validation.
//
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_IOCTL,
"DeviceProcessDsmTrimRequest (%p): Max LBA count is Zero\n",
FdoExtension->DeviceObject));
NT_ASSERT(maxLbaCount != 0);
status = STATUS_DATA_ERROR;
goto Exit;
}
//
// Finally, allocate the buffer we'll use to send the UNMAP command.
//
#if defined(_ARM_) || defined(_ARM64_)
//
// ARM has specific alignment requirements, although this will not have a functional impact on x86 or amd64
// based platforms. We are taking the conservative approach here.
//
bufferLength = ALIGN_UP_BY(bufferLength,KeGetRecommendedSharedDataAlignment());
buffer = (PUNMAP_LIST_HEADER)
ExAllocatePoolZero(NonPagedPoolNxCacheAligned,
bufferLength,
CLASS_TAG_LB_PROVISIONING);
#else
buffer = (PUNMAP_LIST_HEADER)
ExAllocatePoolZero(NonPagedPoolNx,
bufferLength,
CLASS_TAG_LB_PROVISIONING);
#endif
if (buffer == NULL) {
status = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
blockDescrPointer = &buffer->Descriptors[0];
allDataSetRangeFullyConverted = FALSE;
needToSendCommand = FALSE;
tempDataSetRangeFullyConverted = TRUE;
dataSetRangeIndex = 0;
RtlZeroMemory(&tempDataSetRange, sizeof(tempDataSetRange));
blockDescrIndex = 0;
lbaCount = 0;
while (!allDataSetRangeFullyConverted) {
//
// If the previous entry conversion completed, go on to the next one;
// otherwise, continue processing the current entry.
//
if (tempDataSetRangeFullyConverted) {
tempDataSetRange.StartingOffset = DataSetRanges[dataSetRangeIndex].StartingOffset;
tempDataSetRange.LengthInBytes = DataSetRanges[dataSetRangeIndex].LengthInBytes;
dataSetRangeIndex++;
}
ConvertDataSetRangeToUnmapBlockDescr(FdoExtension,
blockDescrPointer,
&blockDescrIndex,
maxBlockDescrCount,
&lbaCount,
maxLbaCount,
&tempDataSetRange
);
tempDataSetRangeFullyConverted = (tempDataSetRange.LengthInBytes == 0) ? TRUE : FALSE;
allDataSetRangeFullyConverted = tempDataSetRangeFullyConverted && (dataSetRangeIndex == DataSetRangesCount);
//
// Send the UNMAP command when the buffer is full or when all input entries are converted.
//
if ((blockDescrIndex == maxBlockDescrCount) || // Buffer full or block descriptor count reached
(lbaCount == maxLbaCount) || // Block LBA count reached
allDataSetRangeFullyConverted) { // All DataSetRanges have been converted
USHORT transferSize;
USHORT tempSize;
PCDB cdb;
//
// Get the transfer size, including the header.
//
transferSize = (USHORT)(blockDescrIndex * sizeof(UNMAP_BLOCK_DESCRIPTOR) + sizeof(UNMAP_LIST_HEADER));
if (transferSize > bufferLength)
{
//
// This should never happen.
//
NT_ASSERT(transferSize <= bufferLength);
status = STATUS_BUFFER_TOO_SMALL;
break;
}
tempSize = transferSize - (USHORT)FIELD_OFFSET(UNMAP_LIST_HEADER, BlockDescrDataLength);
REVERSE_BYTES_SHORT(buffer->DataLength, &tempSize);
tempSize = transferSize - (USHORT)FIELD_OFFSET(UNMAP_LIST_HEADER, Descriptors[0]);
REVERSE_BYTES_SHORT(buffer->BlockDescrDataLength, &tempSize);
//
// Initialize the SRB.
//
if (FdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
status = InitializeStorageRequestBlock((PSTORAGE_REQUEST_BLOCK)Srb,
STORAGE_ADDRESS_TYPE_BTL8,
CLASS_SRBEX_SCSI_CDB16_BUFFER_SIZE,
1,
SrbExDataTypeScsiCdb16);
if (NT_SUCCESS(status)) {
((PSTORAGE_REQUEST_BLOCK)Srb)->SrbFunction = SRB_FUNCTION_EXECUTE_SCSI;
} else {
//
// Should not occur.
//
NT_ASSERT(FALSE);
break;
}
} else {
RtlZeroMemory(Srb, sizeof(SCSI_REQUEST_BLOCK));
Srb->Length = sizeof(SCSI_REQUEST_BLOCK);
Srb->Function = SRB_FUNCTION_EXECUTE_SCSI;
}
//
// Prepare the Srb
//
SrbSetTimeOutValue(Srb, FdoExtension->TimeOutValue);
SrbSetRequestTag(Srb, SP_UNTAGGED);
SrbSetRequestAttribute(Srb, SRB_SIMPLE_TAG_REQUEST);
//
// Set the SrbFlags to indicate that it's a data-out operation.
// Also set any passed-in SrbFlags.
//
SrbAssignSrbFlags(Srb, FdoExtension->SrbFlags);
SrbClearSrbFlags(Srb, SRB_FLAGS_DATA_IN);
SrbSetSrbFlags(Srb, SRB_FLAGS_DATA_OUT);
SrbSetSrbFlags(Srb, SrbFlags);
SrbSetCdbLength(Srb, 10);
cdb = SrbGetCdb(Srb);
cdb->UNMAP.OperationCode = SCSIOP_UNMAP;
cdb->UNMAP.Anchor = 0;
cdb->UNMAP.GroupNumber = 0;
cdb->UNMAP.AllocationLength[0] = (UCHAR)(transferSize >> 8);
cdb->UNMAP.AllocationLength[1] = (UCHAR)transferSize;
status = ClassSendSrbSynchronous(FdoExtension->DeviceObject,
Srb,
buffer,
transferSize,
TRUE);
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_IOCTL,
"DeviceProcessDsmTrimRequest (%p): UNMAP command issued. Returned NTSTATUS: %!STATUS!.\n",
FdoExtension->DeviceObject,
status
));
//
// Clear the buffer so we can re-use it.
//
blockDescrIndex = 0;
lbaCount = 0;
RtlZeroMemory(buffer, bufferLength);
}
}
Exit:
FREE_POOL(buffer);
return status;
}
NTSTATUS ClasspDeviceTrimProcess(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ PIRP Irp,
_In_ PGUID ActivityId,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
/*
This function is to process IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES with DeviceDsmAction_Trim.
At first time of receiving the request, this function will forward it to lower stack to determine if it's supportted.
If it's not supported, UNMAP (with anchor attribute set) will be sent down to process the request.
*/
{
NTSTATUS status = STATUS_SUCCESS;
PCOMMON_DEVICE_EXTENSION commonExtension = (PCOMMON_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PDEVICE_MANAGE_DATA_SET_ATTRIBUTES dsmAttributes = Irp->AssociatedIrp.SystemBuffer;
PDEVICE_DATA_SET_RANGE dataSetRanges;
ULONG dataSetRangesCount;
DEVICE_DATA_SET_RANGE entireDataSetRange = {0};
ULONG i;
ULONGLONG granularityAlignmentInBytes;
ULONG granularityInBlocks;
ULONG srbFlags = 0;
CLASS_VPD_B0_DATA blockLimitsData;
ULONG generationCount;
if ( (DeviceObject->DeviceType != FILE_DEVICE_DISK) ||
(TEST_FLAG(DeviceObject->Characteristics, FILE_FLOPPY_DISKETTE)) ||
(fdoExtension->FunctionSupportInfo->LowerLayerSupport.TrimProcess == Supported) ) {
// if it's not disk, forward the request to lower layer,
// if the IOCTL is supported by lower stack, forward it down.
IoCopyCurrentIrpStackLocationToNext(Irp);
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClasspDeviceTrimProcess (%p): Lower layer supports Trim DSM IOCTL, forwarding IOCTL.\n",
DeviceObject));
ClassReleaseRemoveLock(DeviceObject, Irp);
status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
return status;
}
//
// Request validation.
// Note that InputBufferLength and IsFdo have been validated beforing entering this routine.
//
if (KeGetCurrentIrql() >= DISPATCH_LEVEL) {
NT_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
status = STATUS_INVALID_LEVEL;
goto Exit;
}
//
// If the caller has not set the "entire dataset range" flag then at least
// one dataset range should be specified. However, if the caller *has* set
// the flag, then there should not be any dataset ranges specified.
//
if ((!TEST_FLAG(dsmAttributes->Flags, DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE) &&
(dsmAttributes->DataSetRangesOffset == 0 ||
dsmAttributes->DataSetRangesLength == 0)) ||
(TEST_FLAG(dsmAttributes->Flags, DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE) &&
(dsmAttributes->DataSetRangesOffset != 0 ||
dsmAttributes->DataSetRangesLength != 0))) {
status = STATUS_INVALID_PARAMETER;
goto Exit;
}
//
// note that 'Supported' case has been handled at the beginning of this function.
//
switch (fdoExtension->FunctionSupportInfo->LowerLayerSupport.TrimProcess) {
case SupportUnknown: {
// send down request and wait for the request to complete.
status = ClassForwardIrpSynchronous(commonExtension, Irp);
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClasspDeviceTrimProcess (%p): Trim DSM IOCTL support unknown. Forwarded IOCTL and received NTSTATUS %!STATUS!.\n",
DeviceObject,
status));
if (ClasspLowerLayerNotSupport(status)) {
// case 1: the request is not supported by lower layer, sends down command
// some port drivers (or filter drivers) return STATUS_INVALID_DEVICE_REQUEST if a request is not supported.
// In this case we'll just fall through to the NotSupported case so that we can handle it ourselves.
//
// VPD pages 0xB2 and 0xB0 should have been cached in Start Device phase - ClassPnpStartDevice.
// 0xB2 page: fdoExtension->FunctionSupportInfo->LBProvisioningData;
// 0xB0 page: fdoExtension->FunctionSupportInfo->BlockLimitsData
//
if (fdoExtension->FunctionSupportInfo->ValidInquiryPages.LBProvisioning == TRUE) {
NT_ASSERT(fdoExtension->FunctionSupportInfo->LBProvisioningData.CommandStatus != -1);
}
if (fdoExtension->FunctionSupportInfo->ValidInquiryPages.BlockLimits == TRUE) {
NT_ASSERT(fdoExtension->FunctionSupportInfo->BlockLimitsData.CommandStatus != -1);
}
} else {
// case 2: the request is supported and it completes successfully
// case 3: the request is supported by lower stack but other failure status is returned.
// from now on, the same request will be send down to lower stack directly.
fdoExtension->FunctionSupportInfo->LowerLayerSupport.TrimProcess = Supported;
goto Exit;
}
}
case NotSupported: {
// send UNMAP command if it is supported. don't need to check 'status' value.
if (ClasspSupportsUnmap(fdoExtension->FunctionSupportInfo))
{
//
// Make sure that we know the bytes per sector (logical block) as it's
// necessary for calculations involving granularity and alignment.
//
if (fdoExtension->DiskGeometry.BytesPerSector == 0) {
status = ClassReadDriveCapacity(fdoExtension->DeviceObject);
if(!NT_SUCCESS(status) || fdoExtension->DiskGeometry.BytesPerSector == 0) {
status = STATUS_INVALID_DEVICE_REQUEST;
goto Exit;
}
}
//
// Take a snapshot of the block limits data since it can change.
// It's acceptable if the block limits data is outdated since
// there isn't a hard requirement on the unmap granularity.
//
ClasspBlockLimitsDataSnapshot(fdoExtension,
FALSE,
&blockLimitsData,
&generationCount);
//
// Check to see if the Optimal Unmap Granularity and Unmap Granularity
// Alignment have been specified. If not, default the granularity to
// one block and the alignment to zero.
//
if (blockLimitsData.OptimalUnmapGranularity != 0)
{
granularityInBlocks = blockLimitsData.OptimalUnmapGranularity;
}
else
{
granularityInBlocks = 1;
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClasspDeviceTrimProcess (%p): Optimal Unmap Granularity not provided, defaulted to 1.\n",
DeviceObject));
}
if (blockLimitsData.UGAVALID == TRUE)
{
granularityAlignmentInBytes = (ULONGLONG)blockLimitsData.UnmapGranularityAlignment * fdoExtension->DiskGeometry.BytesPerSector;
}
else
{
granularityAlignmentInBytes = 0;
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClasspDeviceTrimProcess (%p): Unmap Granularity Alignment not provided, defaulted to 0.\n",
DeviceObject));
}
if (TEST_FLAG(dsmAttributes->Flags, DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE))
{
//
// The caller wants to UNMAP the entire disk so we need to build a single
// dataset range that represents the entire disk.
//
entireDataSetRange.StartingOffset = granularityAlignmentInBytes;
entireDataSetRange.LengthInBytes = (ULONGLONG)fdoExtension->CommonExtension.PartitionLength.QuadPart - (ULONGLONG)entireDataSetRange.StartingOffset;
dataSetRanges = &entireDataSetRange;
dataSetRangesCount = 1;
}
else
{
dataSetRanges = (PDEVICE_DATA_SET_RANGE)((PUCHAR)dsmAttributes + dsmAttributes->DataSetRangesOffset);
dataSetRangesCount = dsmAttributes->DataSetRangesLength / sizeof(DEVICE_DATA_SET_RANGE);
//
// Validate the data ranges. Make sure the range is block-aligned,
// falls in a valid portion of the disk, and is non-zero.
//
for (i = 0; i < dataSetRangesCount; i++)
{
if ((dataSetRanges[i].StartingOffset % fdoExtension->DiskGeometry.BytesPerSector != 0) ||
(dataSetRanges[i].LengthInBytes % fdoExtension->DiskGeometry.BytesPerSector != 0) ||
(dataSetRanges[i].StartingOffset < (LONGLONG)granularityAlignmentInBytes) ||
(dataSetRanges[i].LengthInBytes == 0) ||
((ULONGLONG)dataSetRanges[i].StartingOffset + dataSetRanges[i].LengthInBytes > (ULONGLONG)fdoExtension->CommonExtension.PartitionLength.QuadPart))
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceTrimProcess (%p): Invalid dataset range. StartingOffset = %I64x, LengthInBytes = %I64x\n",
DeviceObject,
dataSetRanges[i].StartingOffset,
dataSetRanges[i].LengthInBytes));
status = STATUS_INVALID_PARAMETER;
goto Exit;
}
}
}
if (!TEST_FLAG(dsmAttributes->Flags, DEVICE_DSM_FLAG_TRIM_NOT_FS_ALLOCATED))
{
{
//
// For security reasons, file-level TRIM must be forwarded on only
// if reading the unmapped blocks' contents will return back zeros.
// This is because if LBPRZ bit is not set, it indicates that a read
// of unmapped blocks may return "any" data thus potentially leaking
// in data (into the read buffer) from other blocks.
//
if (fdoExtension->FunctionSupportInfo->ValidInquiryPages.LBProvisioning &&
!fdoExtension->FunctionSupportInfo->LBProvisioningData.LBPRZ) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceTrimProcess (%p): Device does not support file level TRIM.\n",
DeviceObject));
status = STATUS_TRIM_READ_ZERO_NOT_SUPPORTED;
goto Exit;
}
}
}
// process DSM IOCTL
status = DeviceProcessDsmTrimRequest(fdoExtension,
dataSetRanges,
dataSetRangesCount,
granularityInBlocks,
srbFlags,
Irp,
ActivityId,
Srb);
} else {
// DSM IOCTL should be completed as not supported
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceTrimProcess (%p): Device does not support UNMAP.\n",
DeviceObject));
status = STATUS_NOT_SUPPORTED;
}
// set the support status after the SCSI command is executed to avoid racing condition between multiple same type of requests.
fdoExtension->FunctionSupportInfo->LowerLayerSupport.TrimProcess = NotSupported;
break;
}
case Supported: {
NT_ASSERT(FALSE); // this case is handled at the begining of the function.
break;
}
} // end of switch (fdoExtension->FunctionSupportInfo->LowerLayerSupport.TrimProcess)
Exit:
//
// Set the size and status in IRP
//
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = status;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
return status;
}
NTSTATUS
GetLBAStatus(
_In_ PFUNCTIONAL_DEVICE_EXTENSION FdoExtension,
_In_ PSCSI_REQUEST_BLOCK Srb,
_In_ ULONGLONG StartingLBA,
_Inout_ PLBA_STATUS_LIST_HEADER LBAStatusHeader,
_In_ ULONG LBAStatusSize,
_In_ BOOLEAN ConsolidateableBlocksOnly
)
/*++
Routine Description:
Send down a Get LBA Status command for the given range.
Arguments:
FdoExtension: The FDO extension of the device to which Get LBA Status will
be sent.
Srb: This should be allocated and initialized before it's passed in. It
will be used for the Get LBA Status command.
StartingLBA: The LBA that is at the beginning of the requested range.
LBAStatusHeader: Caller-allocated output buffer.
LBASTatusSize: Size of the caller-allocated output buffer.
Return Value:
Status of the operation.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PCDB cdb;
if (LBAStatusHeader == NULL || LBAStatusSize == 0)
{
return STATUS_INVALID_PARAMETER;
}
//
// Build and send down the Get LBA Status command.
//
SrbSetTimeOutValue(Srb, FdoExtension->TimeOutValue);
SrbSetRequestTag(Srb, SP_UNTAGGED);
SrbSetRequestAttribute(Srb, SRB_SIMPLE_TAG_REQUEST);
SrbAssignSrbFlags(Srb, FdoExtension->SrbFlags);
SrbSetCdbLength(Srb, sizeof(cdb->GET_LBA_STATUS));
cdb = SrbGetCdb(Srb);
cdb->GET_LBA_STATUS.OperationCode = SCSIOP_GET_LBA_STATUS;
cdb->GET_LBA_STATUS.ServiceAction = SERVICE_ACTION_GET_LBA_STATUS;
REVERSE_BYTES_QUAD(&(cdb->GET_LBA_STATUS.StartingLBA), &StartingLBA);
REVERSE_BYTES(&(cdb->GET_LBA_STATUS.AllocationLength), &LBAStatusSize);
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_IOCTL,
"GetLBAStatus (%p): sending command with StartingLBA = 0x%I64x, AllocationLength = 0x%I64x, ConsolidateableBlocksOnly = %u\n",
FdoExtension->DeviceObject,
StartingLBA,
LBAStatusSize,
ConsolidateableBlocksOnly));
status = ClassSendSrbSynchronous(FdoExtension->DeviceObject,
Srb,
LBAStatusHeader,
LBAStatusSize,
FALSE);
//
// Handle the case where we get back STATUS_DATA_OVERRUN b/c the input
// buffer was larger than necessary.
//
if (status == STATUS_DATA_OVERRUN &&
SrbGetDataTransferLength(Srb) < LBAStatusSize)
{
status = STATUS_SUCCESS;
}
// log command.
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_IOCTL,
"GetLBAStatus (%p): command returned NT Status: %!STATUS!\n",
FdoExtension->DeviceObject,
status
));
return status;
}
NTSTATUS ClasspDeviceGetLBAStatus(
_In_ PDEVICE_OBJECT DeviceObject,
_Inout_ PIRP Irp,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
/*
Routine Description:
This function is to process IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES with DeviceDsmAction_Allocation.
1. This function will only handle the first dataset range.
2. This function will not handle dataset ranges whose LengthInBytes is greater than:
((MAXULONG - sizeof(LBA_STATUS_LIST_HEADER)) / sizeof(LBA_STATUS_DESCRIPTOR)) * BytesPerSlab
The input buffer should consist of a DEVICE_MANAGE_DATA_SET_ATTRIBUTES followed
in memory by a single DEVICE_DATA_SET_RANGE that specifies the requested range
of slabs for which mapping status is desired.
The output buffer will consist of a DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT
followed in memory by a single DEVICE_DATA_SET_LB_PROVISIONING_STATE that
contains a bitmap that represents the mapped status of the slabs in the requested
range. Note that the number of slabs returned may be less than the number
requested.
Thus function will automatically re-align the given range offset if it was
not slab-aligned. The delta between the given range offset and the properly
aligned offset will be given in returned DEVICE_DATA_SET_LB_PROVISIONING_STATE.
Arguments:
DeviceObject: The FDO of the device to which Get LBA Status will be sent.
Irp: The IRP for the request. This function will read the input buffer and
write to the output buffer at the current IRP stack location.
Srb: This should be allocated and initialized before it's passed in. It
will be used for the Get LBA Status command.
Return Value:
STATUS_INVALID_PARAMETER: May be returned under the following conditions:
- If the requested range was too large. The caller should try again with a
smaller range. See above for how to calculate the maximum range.
- If the given starting offset was not within the valid range of the device.
STATUS_NOT_SUPPORTED: The storage did not report some information critical to
the execution of this function (e.g. Optimal Unmap Granularity).
STATUS_BUFFER_TOO_SMALL: The output buffer is not large enough to hold the max
data that could be returned from this function. If the output buffer is
at least the size of a ULONG, we will write the required output buffer size
to the first ULONG bytes of the output buffer.
STATUS_UNSUCCESSFUL: The Get LBA Status command succeeded but did not
return data as expected.
--*/
{
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
PDEVICE_MANAGE_DATA_SET_ATTRIBUTES dsmAttributes = (PDEVICE_MANAGE_DATA_SET_ATTRIBUTES)Irp->AssociatedIrp.SystemBuffer;
PDEVICE_DATA_SET_RANGE dataSetRanges = NULL;
PDEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT dsmOutput = (PDEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT)Irp->AssociatedIrp.SystemBuffer;
ULONG dsmOutputLength;
NTSTATUS finalStatus;
NTSTATUS getLBAWorkerStatus;
ULONG retryCount;
ULONG retryCountMax;
CLASS_VPD_B0_DATA blockLimitsData;
ULONG generationCount1;
ULONG generationCount2;
BOOLEAN blockLimitsDataMayHaveChanged;
ULONG_PTR information = 0;
LONGLONG startingOffset;
ULONGLONG lengthInBytes;
BOOLEAN consolidateableBlocksOnly = FALSE;
ULONG outputVersion;
//
// Basic parameter validation.
// Note that InputBufferLength and IsFdo have been validated beforing entering this routine.
//
if (dsmOutput == NULL ||
dsmAttributes == NULL)
{
finalStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
if (TEST_FLAG(dsmAttributes->Flags, DEVICE_DSM_FLAG_ENTIRE_DATA_SET_RANGE)) {
//
// The caller wants the mapping status of the entire disk.
//
ULONG unmapGranularityAlignment = 0;
if (fdoExtension->FunctionSupportInfo->BlockLimitsData.UGAVALID) {
unmapGranularityAlignment = fdoExtension->FunctionSupportInfo->BlockLimitsData.UnmapGranularityAlignment;
}
startingOffset = unmapGranularityAlignment;
lengthInBytes = (ULONGLONG)fdoExtension->CommonExtension.PartitionLength.QuadPart - (ULONGLONG)startingOffset;
} else {
if (dsmAttributes->DataSetRangesOffset == 0 ||
dsmAttributes->DataSetRangesLength == 0) {
finalStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
//
// We only service the first dataset range specified.
//
dataSetRanges = (PDEVICE_DATA_SET_RANGE)((PUCHAR)dsmAttributes + dsmAttributes->DataSetRangesOffset);
startingOffset = dataSetRanges[0].StartingOffset;
lengthInBytes = dataSetRanges[0].LengthInBytes;
}
//
// See if the sender is requesting a specific version of the output data
// structure. Othwerwise, default to V1.
//
outputVersion = DEVICE_DATA_SET_LB_PROVISIONING_STATE_VERSION_V1;
#if (NTDDI_VERSION >= NTDDI_WINBLUE)
if ((dsmAttributes->ParameterBlockOffset >= sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES)) &&
(dsmAttributes->ParameterBlockLength >= sizeof(DEVICE_DATA_SET_LBP_STATE_PARAMETERS))) {
PDEVICE_DATA_SET_LBP_STATE_PARAMETERS parameters = Add2Ptr(dsmAttributes, dsmAttributes->ParameterBlockOffset);
if ((parameters->Version == DEVICE_DATA_SET_LBP_STATE_PARAMETERS_VERSION_V1) &&
(parameters->Size >= sizeof(DEVICE_DATA_SET_LBP_STATE_PARAMETERS))) {
outputVersion = parameters->OutputVersion;
if ((outputVersion != DEVICE_DATA_SET_LB_PROVISIONING_STATE_VERSION_V1) &&
(outputVersion != DEVICE_DATA_SET_LB_PROVISIONING_STATE_VERSION_V2)) {
finalStatus = STATUS_INVALID_PARAMETER;
goto Exit;
}
}
}
#endif
//
// Take a snapshot of the block limits data for the worker function to use.
// We need to fail the request if we fail to get updated block limits data
// since we need an accurate Optimal Unmap Granularity value to properly
// convert the returned mapping descriptors into a bitmap.
//
finalStatus = ClasspBlockLimitsDataSnapshot(fdoExtension,
TRUE,
&blockLimitsData,
&generationCount1);
if (!NT_SUCCESS(finalStatus)) {
information = 0;
goto Exit;
}
if (dsmAttributes->Flags & DEVICE_DSM_FLAG_ALLOCATION_CONSOLIDATEABLE_ONLY) {
consolidateableBlocksOnly = TRUE;
}
//
// The retry logic is to handle the case when block limits data changes during rare occasions
// (e.g. diff-VHD fork or merge).
//
retryCountMax = GET_LBA_STATUS_RETRY_COUNT_MAX;
for (retryCount = 0; retryCount < retryCountMax; retryCount++) {
dsmOutputLength = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
getLBAWorkerStatus = ClasspDeviceGetLBAStatusWorker(DeviceObject,
&blockLimitsData,
startingOffset,
lengthInBytes,
dsmOutput,
&dsmOutputLength,
Srb,
consolidateableBlocksOnly,
outputVersion,
&blockLimitsDataMayHaveChanged);
if (!NT_SUCCESS(getLBAWorkerStatus) && !blockLimitsDataMayHaveChanged) {
information = 0;
finalStatus = getLBAWorkerStatus;
break;
}
//
// Again, we need to fail the request if we fail to get updated block
// limits data since we need an accurate Optimal Unmap Granularity value.
//
finalStatus = ClasspBlockLimitsDataSnapshot(fdoExtension,
TRUE,
&blockLimitsData,
&generationCount2);
if (!NT_SUCCESS(finalStatus)) {
information = 0;
goto Exit;
}
if (generationCount1 == generationCount2) {
//
// Block limits data stays the same during the call to ClasspDeviceGetLBAStatusWorker()
// The result from ClasspDeviceGetLBAStatusWorker() is valid.
//
finalStatus = getLBAWorkerStatus;
if (NT_SUCCESS(finalStatus)) {
information = dsmOutputLength;
}
break;
}
//
// Try again with the latest block limits data
//
generationCount1 = generationCount2;
information = 0;
finalStatus = STATUS_DEVICE_DATA_ERROR;
}
Exit:
Irp->IoStatus.Information = information;
Irp->IoStatus.Status = finalStatus;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
return finalStatus;
}
NTSTATUS
ClasspDeviceGetLBAStatusWorker(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ PCLASS_VPD_B0_DATA BlockLimitsData,
_In_ ULONGLONG StartingOffset,
_In_ ULONGLONG LengthInBytes,
_Out_ PDEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT DsmOutput,
_Inout_ PULONG DsmOutputLength,
_Inout_ PSCSI_REQUEST_BLOCK Srb,
_In_ BOOLEAN ConsolidateableBlocksOnly,
_In_ ULONG OutputVersion,
_Out_ PBOOLEAN BlockLimitsDataMayHaveChanged
)
/*
Routine Description:
This function is to process IOCTL_STORAGE_MANAGE_DATA_SET_ATTRIBUTES with DeviceDsmAction_Allocation.
1. This function will only handle the first dataset range.
2. This function will not handle dataset ranges whose LengthInBytes is greater than:
((MAXULONG - sizeof(LBA_STATUS_LIST_HEADER)) / sizeof(LBA_STATUS_DESCRIPTOR)) * BytesPerSlab
The input buffer should consist of a DEVICE_MANAGE_DATA_SET_ATTRIBUTES followed
in memory by a single DEVICE_DATA_SET_RANGE that specifies the requested range
of slabs for which mapping status is desired.
The output buffer will consist of a DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT
followed in memory by a single DEVICE_DATA_SET_LB_PROVISIONING_STATE that
contains a bitmap that represents the mapped status of the slabs in the requested
range. Note that the number of slabs returned may be less than the number
requested.
Thus function will automatically re-align the given range offset if it was
not slab-aligned. The delta between the given range offset and the properly
aligned offset will be given in returned DEVICE_DATA_SET_LB_PROVISIONING_STATE.
Arguments:
DeviceObject: The FDO of the device to which Get LBA Status will be sent.
BlockLimitsData: Block limits data of the device
StartingOffset: Starting byte offset of byte range to query LBA status (must be sector aligned)
LengthInBytes: Length of byte range to query LBA status (multiple of sector size)
DsmOutput: Output data buffer
DsmOutputLength: output data buffer size. It will be updated with actual bytes used.
Srb: This should be allocated and initialized before it's passed in. It
will be used for the Get LBA Status command.
ConsolidateableBlocksOnly: Only blocks that are eligible for consolidation
should be returned.
OutputVersion: The version of the DEVICE_DATA_SET_LB_PROVISIONING_STATE
structure to return. This should be one of:
- DEVICE_DATA_SET_LB_PROVISIONING_STATE_VERSION_V1
- DEVICE_DATA_SET_LB_PROVISIONING_STATE_VERSION_V2
BlockLimitsDataMayHaveChanged: if this function fails, this flag indicates
if the failure can be caused by changes in device's block limit data.
Return Value:
STATUS_INVALID_PARAMETER: May be returned under the following conditions:
- If the requested range was too large. The caller should try again with a
smaller range. See above for how to calculate the maximum range.
- If the given starting offset was not within the valid range of the device.
STATUS_NOT_SUPPORTED: The storage did not report some information critical to
the execution of this function (e.g. Optimal Unmap Granularity).
STATUS_BUFFER_TOO_SMALL: The output buffer is not large enough to hold the max
data that could be returned from this function. If the output buffer is
at least the size of a ULONG, we will write the required output buffer size
to the first ULONG bytes of the output buffer.
STATUS_DEVICE_DATA_ERROR: The Get LBA Status command succeeded but did not
return data as expected.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PDEVICE_DATA_SET_LB_PROVISIONING_STATE lbpState;
ULONG bitMapGranularityInBits = FIELD_SIZE(DEVICE_DATA_SET_LB_PROVISIONING_STATE,SlabAllocationBitMap[0]) * 8;
ULONG requiredOutputLength;
ULONG outputLength = *DsmOutputLength;
ULONG blocksPerSlab;
ULONGLONG bytesPerSlab;
ULONGLONG alignmentInBytes = 0;
ULONG alignmentInBlocks = 0;
ULONG maxBufferSize;
ULONG maxSlabs;
ULONGLONG requestedSlabs; // Total number of slabs requested by the caller.
ULONGLONG startingLBA;
ULONGLONG startingOffsetDelta;
ULONG totalProcessedSlabs = 0; // Total number of slabs we processed.
ULONGLONG slabsPerCommand; // Number of slabs we can ask for in one Get LBA Status command.
BOOLEAN doneProcessing = FALSE; // Indicates we should break out of the Get LBA Status loop.
ULONG lbaStatusSize;
PLBA_STATUS_LIST_HEADER lbaStatusListHeader = NULL;
//
// This function can fail if the block limits data on the device changes.
// This flag tells the caller if it should retry with a newer block limits data
//
*BlockLimitsDataMayHaveChanged = FALSE;
//
// Make sure we're running at PASSIVE_LEVEL
//
if (KeGetCurrentIrql() >= DISPATCH_LEVEL)
{
NT_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
status = STATUS_INVALID_LEVEL;
goto Exit;
}
//
// Don't send down a Get LBA Status command if UNMAP isn't supported.
//
if (!fdoExtension->FunctionSupportInfo->LBProvisioningData.LBPU)
{
return STATUS_NOT_SUPPORTED;
goto Exit;
}
//
// Make sure we have a non-zero value for the number of bytes per block.
// Otherwise we will end up dividing by zero later on.
//
if (fdoExtension->DiskGeometry.BytesPerSector == 0)
{
status = ClassReadDriveCapacity(fdoExtension->DeviceObject);
if(!NT_SUCCESS(status) || fdoExtension->DiskGeometry.BytesPerSector == 0)
{
status = STATUS_INVALID_DEVICE_REQUEST;
goto Exit;
}
}
//
// We only service the first dataset range specified.
//
if (BlockLimitsData->UGAVALID == TRUE) {
alignmentInBlocks = BlockLimitsData->UnmapGranularityAlignment;
alignmentInBytes = (ULONGLONG)alignmentInBlocks * (ULONGLONG)fdoExtension->DiskGeometry.BytesPerSector;
}
//
// Make sure the specified range is valid. The Unmap Granularity Alignment
// defines a region at the beginning of the disk that cannot be
// mapped/unmapped so the specified range should not include any part of that
// region.
//
if (LengthInBytes == 0 ||
StartingOffset < alignmentInBytes ||
StartingOffset + LengthInBytes > (ULONGLONG)fdoExtension->CommonExtension.PartitionLength.QuadPart)
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceGetLBAStatusWorker (%p): Invalid range, length is %I64u bytes, starting offset is %I64u bytes, Unmap alignment is %I64u bytes, and disk size is %I64u bytes\n",
DeviceObject,
LengthInBytes,
StartingOffset,
alignmentInBytes,
(ULONGLONG)fdoExtension->CommonExtension.PartitionLength.QuadPart));
status = STATUS_INVALID_PARAMETER;
goto Exit;
}
//
// Calculate the number of bytes per slab so that we can convert (and
// possibly align) the given offset (given in bytes) to slabs.
//
blocksPerSlab = BlockLimitsData->OptimalUnmapGranularity;
bytesPerSlab = (ULONGLONG)blocksPerSlab * (ULONGLONG)fdoExtension->DiskGeometry.BytesPerSector;
//
// If the starting offset is not slab-aligned, we need to adjust it to
// be aligned with the next highest slab. We also need to save the delta
// to return to the user later.
//
if (((StartingOffset - alignmentInBytes) % bytesPerSlab) != 0)
{
startingLBA = (((StartingOffset - alignmentInBytes) / bytesPerSlab) + 1) * (ULONGLONG)blocksPerSlab + alignmentInBlocks;
startingOffsetDelta = (startingLBA * fdoExtension->DiskGeometry.BytesPerSector) - StartingOffset;
}
else
{
startingLBA = ((StartingOffset - alignmentInBytes) / bytesPerSlab) * (ULONGLONG)blocksPerSlab + alignmentInBlocks;
startingOffsetDelta = 0;
}
//
// Caclulate the number of slabs the caller requested.
//
if ((LengthInBytes % bytesPerSlab) == 0) {
requestedSlabs = (LengthInBytes / bytesPerSlab);
} else {
//
// Round up the number of requested slabs if the length indicates a
// partial slab. This should cover the case where the user specifies
// a dataset range for the whole disk, but the size of the disk is not
// a slab-multiple. Rounding up allows us to return the status of the
// partial slab
//
requestedSlabs = (LengthInBytes / bytesPerSlab) + 1;
}
//
// If the caller asked for no slabs then return STATUS_INVALID_PARAMETER.
//
if (requestedSlabs == 0)
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceGetLBAStatusWorker (%p): Invalid number (%I64u) of slabs requested\n",
DeviceObject,
requestedSlabs));
status = STATUS_INVALID_PARAMETER;
goto Exit;
}
//
// Cap requested slabs at MAXULONG since SlabAllocationBitMapBitCount
// is a 4-byte field. We may return less data than requested, but the
// caller can simply re-query for the omitted portion(s).
//
requestedSlabs = min(requestedSlabs, MAXULONG);
//
// Calculate the required size of the output buffer based upon the desired
// version of the output structure.
// In the worst case, Get LBA Status returns a descriptor for each slab
// requested, thus the required output buffer length is equal to:
// 1. The size of DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT; plus
// 2. The size of DEVICE_DATA_SET_LB_PROVISIONING_STATE(_V2); plus
// 3. The size of a ULONG array large enough to hold a bit for each slab requested.
// (The first element is already allocated in DEVICE_DATA_SET_LB_PROVISIONING_STATE(_V2).)
//
#if (NTDDI_VERSION >= NTDDI_WINBLUE)
if (OutputVersion == DEVICE_DATA_SET_LB_PROVISIONING_STATE_VERSION_V2) {
requiredOutputLength = (ULONG)(sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT)
+ sizeof(DEVICE_DATA_SET_LB_PROVISIONING_STATE_V2)
+ (((requestedSlabs - 1) / bitMapGranularityInBits))
* FIELD_SIZE(DEVICE_DATA_SET_LB_PROVISIONING_STATE_V2, SlabAllocationBitMap[0]));
} else
#else
UNREFERENCED_PARAMETER(OutputVersion);
#endif
{
requiredOutputLength = (ULONG)(sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT)
+ sizeof(DEVICE_DATA_SET_LB_PROVISIONING_STATE)
+ (((requestedSlabs - 1) / bitMapGranularityInBits))
* FIELD_SIZE(DEVICE_DATA_SET_LB_PROVISIONING_STATE, SlabAllocationBitMap[0]));
}
//
// The output buffer is not big enough to hold the requested data.
// Inform the caller of the correct buffer size.
//
if (outputLength < requiredOutputLength)
{
status = STATUS_BUFFER_TOO_SMALL;
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceGetLBAStatusWorker (%p): Given output buffer is %u bytes, needs to be %u bytes\n",
DeviceObject,
outputLength,
requiredOutputLength));
//
// If the output buffer is big enough, write the required buffer
// length to the first ULONG bytes of the output buffer.
//
if (outputLength >= sizeof(ULONG))
{
*((PULONG)DsmOutput) = requiredOutputLength;
}
goto Exit;
}
//
// Calculate the maximum number of slabs that could be returned by a single
// Get LBA Status command. The max buffer size could either be capped by
// the Parameter Data Length field or the Max Transfer Length of the
// adapter.
// The number of slabs we actually ask for in a single command is the
// smaller of the number of slabs requested by the user or the max number
// of slabs we can theoretically ask for in a single command.
//
maxBufferSize = MIN(MAXULONG, fdoExtension->PrivateFdoData->HwMaxXferLen);
maxSlabs = (maxBufferSize - sizeof(LBA_STATUS_LIST_HEADER)) / sizeof(LBA_STATUS_DESCRIPTOR);
slabsPerCommand = min(requestedSlabs, maxSlabs);
//
// Allocate the buffer that will contain the returned LBA Status Descriptors.
// Assume that in the worst case every other slab has a different mapping
// status. That means that there may be a descriptor for every slab requested.
//
lbaStatusSize = (ULONG)(sizeof(LBA_STATUS_LIST_HEADER) + (slabsPerCommand * sizeof(LBA_STATUS_DESCRIPTOR)));
#if defined(_ARM_) || defined(_ARM64_)
//
// ARM has specific alignment requirements, although this will not have a functional impact on x86 or amd64
// based platforms. We are taking the conservative approach here.
//
lbaStatusSize = ALIGN_UP_BY(lbaStatusSize,KeGetRecommendedSharedDataAlignment());
lbaStatusListHeader = (PLBA_STATUS_LIST_HEADER)
ExAllocatePoolZero(NonPagedPoolNxCacheAligned,
lbaStatusSize,
CLASS_TAG_LB_PROVISIONING);
#else
lbaStatusListHeader = (PLBA_STATUS_LIST_HEADER)
ExAllocatePoolZero(NonPagedPoolNx,
lbaStatusSize,
CLASS_TAG_LB_PROVISIONING);
#endif
if (lbaStatusListHeader == NULL)
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceGetLBAStatusWorker (%p): Failed to allocate %u bytes for descriptors\n",
DeviceObject,
lbaStatusSize));
NT_ASSERT(lbaStatusListHeader != NULL);
status = STATUS_INSUFFICIENT_RESOURCES;
goto Exit;
}
//
// Set default values for the output buffer.
// If we process at least one slab from the device we will update the
// offset and lengths accordingly.
//
DsmOutput->Action = DeviceDsmAction_Allocation;
DsmOutput->Size = sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT);
DsmOutput->OutputBlockOffset = 0;
DsmOutput->OutputBlockLength = 0;
*DsmOutputLength = DsmOutput->Size;
//
// The returned DEVICE_DATA_SET_LB_PROVISIONING_STATE is at the end of the
// DSM output structure. Zero it out before we start to fill it in.
//
lbpState = Add2Ptr(DsmOutput, sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT));
RtlZeroMemory(lbpState, requiredOutputLength - sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT));
do {
//
// Send down GetLBAStatus for the current range.
//
status = GetLBAStatus(fdoExtension,
Srb,
startingLBA,
lbaStatusListHeader,
lbaStatusSize,
ConsolidateableBlocksOnly);
if (NT_SUCCESS(status))
{
ULONG descrIndex = 0;
ULONG descrSize = 0;
ULONG descrSizeOverhead;
ULONG descrCount = 0;
ULONGLONG expectedStartingLBA;
BOOLEAN processCurrentDescriptor = TRUE;
ULONG commandProcessedSlabs = 0; // Number of slabs processed for this command.
descrSizeOverhead = FIELD_OFFSET(LBA_STATUS_LIST_HEADER, Descriptors[0]) -
RTL_SIZEOF_THROUGH_FIELD(LBA_STATUS_LIST_HEADER, ParameterLength);
REVERSE_BYTES(&descrSize, &(lbaStatusListHeader->ParameterLength));
//
// If the returned Parameter Data Length field describes more
// descriptors than we allocated space for then make sure we don't
// try to process more descriptors than are actually present.
//
if (descrSize > (lbaStatusSize - RTL_SIZEOF_THROUGH_FIELD(LBA_STATUS_LIST_HEADER, ParameterLength))) {
descrSize = (lbaStatusSize - RTL_SIZEOF_THROUGH_FIELD(LBA_STATUS_LIST_HEADER, ParameterLength));
}
if (descrSize >= descrSizeOverhead) {
descrSize -= descrSizeOverhead;
descrCount = descrSize / sizeof(LBA_STATUS_DESCRIPTOR);
//
// Make sure at least one descriptor was returned.
//
if (descrCount > 0) {
//
// We expect the first starting LBA returned by the device to be the
// same starting LBA we specified in the command.
//
expectedStartingLBA = startingLBA;
//
// Translate the returned LBA status descriptors into a bitmap where each bit represents
// a slab. The slab size is represented by the Optimal Unmap Granularity.
// 1 = The slab is mapped.
// 0 = The slab is unmapped (deallocated or anchored).
//
for (descrIndex = 0; descrIndex < descrCount && totalProcessedSlabs < requestedSlabs && !doneProcessing; descrIndex++)
{
PLBA_STATUS_DESCRIPTOR lbaStatusDescr = &(lbaStatusListHeader->Descriptors[descrIndex]);
ULONGLONG returnedStartingLBA;
ULONG mapped = (lbaStatusDescr->ProvisioningStatus != LBA_STATUS_MAPPED) ? 0x0 : 0x1;
ULONG lbaCount = 0;
REVERSE_BYTES_QUAD(&returnedStartingLBA, &(lbaStatusDescr->StartingLBA));
REVERSE_BYTES(&lbaCount, &(lbaStatusDescr->LogicalBlockCount));
if (returnedStartingLBA != expectedStartingLBA)
{
//
// We expect the descriptors will express a contiguous range of LBAs.
// If the starting LBA is not contiguous with the LBA range from the
// previous descriptor then we should not process any more descriptors,
// including the current one.
//
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceGetLBAStatusWorker (%p): Device returned starting LBA = %I64x when %I64x was expected.\n",
DeviceObject,
returnedStartingLBA,
startingLBA));
doneProcessing = TRUE;
processCurrentDescriptor = FALSE;
*BlockLimitsDataMayHaveChanged = TRUE;
}
else if (lbaCount > 0 && lbaCount % blocksPerSlab != 0)
{
//
// If the device returned an LBA count with a partial slab, round
// the LBA count up to the nearest slab and set a flag to stop
// processing further descriptors. This is mainly to handle the
// case where disk size may not be slab-aligned and thus the last
// "slab" is actually a partial slab.
//
TracePrint((TRACE_LEVEL_WARNING,
TRACE_FLAG_IOCTL,
"ClasspDeviceGetLBAStatusWorker (%p): Device returned an LBA count (%u) that is not a multiple of the slab size (%u)\n",
DeviceObject,
lbaCount,
blocksPerSlab));
lbaCount = ((lbaCount / blocksPerSlab) + 1) * blocksPerSlab;
doneProcessing = TRUE;
processCurrentDescriptor = TRUE;
}
else if (lbaCount == 0)
{
//
// If the LBA count is 0, just skip this descriptor.
//
TracePrint((TRACE_LEVEL_WARNING,
TRACE_FLAG_IOCTL,
"ClasspDeviceGetLBAStatusWorker (%p): Device returned a zero LBA count\n",
DeviceObject));
processCurrentDescriptor = FALSE;
}
//
// Generate bits for the slabs described in the current descriptor.
// It's possible the device may have returned more slabs than requested
// so we make sure to stop once we've processed all we need.
//
if (processCurrentDescriptor)
{
ULONG descrSlabs = lbaCount / blocksPerSlab; // Number of slabs in this descriptor.
for(; 0 < descrSlabs && totalProcessedSlabs < requestedSlabs; descrSlabs--, commandProcessedSlabs++, totalProcessedSlabs++)
{
ULONG bitMapIndex = totalProcessedSlabs / bitMapGranularityInBits;
ULONG bitPos = totalProcessedSlabs % bitMapGranularityInBits;
#if (NTDDI_VERSION >= NTDDI_WINBLUE)
if (OutputVersion == DEVICE_DATA_SET_LB_PROVISIONING_STATE_VERSION_V2) {
((PDEVICE_DATA_SET_LB_PROVISIONING_STATE_V2)lbpState)->SlabAllocationBitMap[bitMapIndex] |= (mapped << bitPos);
} else
#endif
{
lbpState->SlabAllocationBitMap[bitMapIndex] |= (mapped << bitPos);
}
}
}
//
// Calculate the next expected starting LBA.
//
expectedStartingLBA = returnedStartingLBA + lbaCount;
}
if (commandProcessedSlabs > 0) {
//
// Calculate the starting LBA we'll use for the next command.
//
startingLBA += ((ULONGLONG)commandProcessedSlabs * (ULONGLONG)blocksPerSlab);
} else {
//
// This should never happen, but we should handle it gracefully anyway.
//
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceGetLBAStatusWorker (%p): The slab allocation bitmap has zero length.\n",
DeviceObject));
NT_ASSERT(commandProcessedSlabs != 0);
doneProcessing = TRUE;
status = STATUS_UNSUCCESSFUL;
}
} else {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceGetLBAStatusWorker (%p): Device returned no LBA Status Descriptors.\n",
DeviceObject));
doneProcessing = TRUE;
status = STATUS_UNSUCCESSFUL;
}
} else {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceGetLBAStatusWorker (%p): not enough bytes returned\n",
DeviceObject));
doneProcessing = TRUE;
status = STATUS_DEVICE_DATA_ERROR;
}
}
//
// Loop until we encounter some error or we've processed all the requested slabs.
//
} while (NT_SUCCESS(status) &&
!doneProcessing &&
(totalProcessedSlabs < requestedSlabs));
//
// At least one slab was returned by the device and processed, which we
// consider success. It's up to the caller to detect truncation.
// Update the output buffer sizes, offsets, etc. accordingly.
//
if (totalProcessedSlabs > 0) {
#if (NTDDI_VERSION >= NTDDI_WINBLUE)
if (OutputVersion == DEVICE_DATA_SET_LB_PROVISIONING_STATE_VERSION_V2) {
PDEVICE_DATA_SET_LB_PROVISIONING_STATE_V2 lbpStateV2 = (PDEVICE_DATA_SET_LB_PROVISIONING_STATE_V2)lbpState;
lbpStateV2->SlabSizeInBytes = bytesPerSlab;
lbpStateV2->SlabOffsetDeltaInBytes = startingOffsetDelta;
lbpStateV2->SlabAllocationBitMapBitCount = totalProcessedSlabs;
lbpStateV2->SlabAllocationBitMapLength = ((totalProcessedSlabs - 1) / (ULONGLONG)bitMapGranularityInBits) + 1;
lbpStateV2->Version = DEVICE_DATA_SET_LB_PROVISIONING_STATE_VERSION_V2;
//
// Note that there is already one element of the bitmap array allocated
// in the DEVICE_DATA_SET_LB_PROVISIONING_STATE_V2 structure itself, which
// is why we subtract 1 from SlabAllocationBitMapLength.
//
lbpStateV2->Size = sizeof(DEVICE_DATA_SET_LB_PROVISIONING_STATE_V2)
+ ((lbpStateV2->SlabAllocationBitMapLength - 1) * sizeof(lbpStateV2->SlabAllocationBitMap[0]));
} else
#endif
{
lbpState->SlabSizeInBytes = bytesPerSlab;
lbpState->SlabOffsetDeltaInBytes = (ULONG)startingOffsetDelta;
lbpState->SlabAllocationBitMapBitCount = totalProcessedSlabs;
lbpState->SlabAllocationBitMapLength = ((totalProcessedSlabs - 1) / bitMapGranularityInBits) + 1;
lbpState->Version = DEVICE_DATA_SET_LB_PROVISIONING_STATE_VERSION_V1;
//
// Note that there is already one element of the bitmap array allocated
// in the DEVICE_DATA_SET_LB_PROVISIONING_STATE structure itself, which
// is why we subtract 1 from SlabAllocationBitMapLength.
//
lbpState->Size = sizeof(DEVICE_DATA_SET_LB_PROVISIONING_STATE)
+ ((lbpState->SlabAllocationBitMapLength - 1) * sizeof(lbpState->SlabAllocationBitMap[0]));
}
DsmOutput->OutputBlockLength = lbpState->Size; // Size is at the same offset in all versions of the structure.
DsmOutput->OutputBlockOffset = sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES_OUTPUT);
*DsmOutputLength = DsmOutput->Size + DsmOutput->OutputBlockLength;
status = STATUS_SUCCESS;
}
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_IOCTL,
"ClasspDeviceGetLBAStatusWorker (%p): Processed a total of %u slabs\n",
DeviceObject,
totalProcessedSlabs));
Exit:
FREE_POOL(lbaStatusListHeader);
return status;
}
NTSTATUS ClassGetLBProvisioningLogPage(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ PSCSI_REQUEST_BLOCK Srb,
_In_ ULONG LogPageSize,
_Inout_ PLOG_PAGE_LOGICAL_BLOCK_PROVISIONING LogPage
)
/*
Routine Description:
This function sends a LOG SENSE command to the given device and returns the
Logical Block Provisioning Log Page, if available.
Arguments:
DeviceObject: The FDO of the device to which the Log Sense command will be sent.
Srb: This should be allocated before it is passed in, but it does not have
to be initialized. This function will initialize it.
LogPageSize: The size of the LogPage buffer in bytes.
LogPage: A pointer to an already allocated output buffer that may contain
the LBP log page when this function returns.
Return Value:
STATUS_INVALID_PARAMETER: May be returned if the LogPage buffer is NULL or
not large enough.
STATUS_SUCCESS: The log page was obtained and placed in the LogPage buffer.
This function may return other NTSTATUS codes from internal function calls.
--*/
{
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
NTSTATUS status = STATUS_SUCCESS;
PCDB cdb = NULL;
//
// Make sure the caller passed in an adequate output buffer. The Allocation
// Length field in the Log Sense command is only 2 bytes so we need to also
// make sure that the given log page size isn't larger than MAXUSHORT.
//
if (LogPage == NULL ||
LogPageSize < sizeof(LOG_PAGE_LOGICAL_BLOCK_PROVISIONING) ||
LogPageSize > MAXUSHORT)
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassGetLBProvisioningLogPage: DO (%p), Invalid parameter, LogPage = %p, LogPageSize = %u.\n",
DeviceObject,
LogPage,
LogPageSize));
return STATUS_INVALID_PARAMETER;
}
//
// Initialize the SRB.
//
if (fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK) {
status = InitializeStorageRequestBlock((PSTORAGE_REQUEST_BLOCK)Srb,
STORAGE_ADDRESS_TYPE_BTL8,
CLASS_SRBEX_SCSI_CDB16_BUFFER_SIZE,
1,
SrbExDataTypeScsiCdb16);
if (NT_SUCCESS(status)) {
((PSTORAGE_REQUEST_BLOCK)Srb)->SrbFunction = SRB_FUNCTION_EXECUTE_SCSI;
} else {
//
// Should not occur.
//
NT_ASSERT(FALSE);
}
} else {
RtlZeroMemory(Srb, sizeof(SCSI_REQUEST_BLOCK));
Srb->Length = sizeof(SCSI_REQUEST_BLOCK);
Srb->Function = SRB_FUNCTION_EXECUTE_SCSI;
}
//
// Build and send down the Log Sense command.
//
SrbSetTimeOutValue(Srb, fdoExtension->TimeOutValue);
SrbSetRequestTag(Srb, SP_UNTAGGED);
SrbSetRequestAttribute(Srb, SRB_SIMPLE_TAG_REQUEST);
SrbAssignSrbFlags(Srb, fdoExtension->SrbFlags);
SrbSetCdbLength(Srb, sizeof(cdb->LOGSENSE));
cdb = SrbGetCdb(Srb);
cdb->LOGSENSE.OperationCode = SCSIOP_LOG_SENSE;
cdb->LOGSENSE.PageCode = LOG_PAGE_CODE_LOGICAL_BLOCK_PROVISIONING;
cdb->LOGSENSE.PCBit = 0;
cdb->LOGSENSE.ParameterPointer[0] = 0;
cdb->LOGSENSE.ParameterPointer[1] = 0;
REVERSE_BYTES_SHORT(&(cdb->LOGSENSE.AllocationLength), &LogPageSize);
status = ClassSendSrbSynchronous(fdoExtension->DeviceObject,
Srb,
LogPage,
LogPageSize,
FALSE);
//
// Handle the case where we get back STATUS_DATA_OVERRUN b/c the input
// buffer was larger than necessary.
//
if (status == STATUS_DATA_OVERRUN &&
SrbGetDataTransferLength(Srb) < LogPageSize)
{
status = STATUS_SUCCESS;
}
//
// Log the command.
//
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_IOCTL,
"ClassGetLBProvisioningLogPage: DO (%p), LogSense command issued for LBP log page. NT Status: %!STATUS!.\n",
DeviceObject,
status
));
return status;
}
NTSTATUS ClassInterpretLBProvisioningLogPage(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ ULONG LogPageSize,
_In_ PLOG_PAGE_LOGICAL_BLOCK_PROVISIONING LogPage,
_In_ ULONG ResourcesSize,
_Out_ PSTORAGE_LB_PROVISIONING_MAP_RESOURCES Resources
)
/*
Routine Description:
This function takes a Logical Block Provisioning log page (returned by
ClassGetLBProvisioningLogPage(), for example), interprets its contents,
and returns the interpreted data in a STORAGE_LB_PROVISIONING_MAP_RESOURCES
structure.
None, some, or all of the data in the output buffer may be valid. The
caller must look at the individual "Valid" fields to see which fields have
valid data.
Arguments:
DeviceObject: The FDO of the device from which the log page was obtained.
LogPageSize: The size of the LogPage buffer in bytes.
LogPage: A pointer to a valid LBP log page structure.
ResourcesSize: The size of the Resources buffer in bytes.
Resources: A pointer to an already allocated output buffer that may contain
the interpreted log page data when this function returns.
Return Value:
STATUS_NOT_SUPPORTED: May be returned if the threshold exponent from the
0xB2 page is invalid.
STATUS_INVALID_PARAMETER: May be returned if either the LogPage or Resources
buffers are NULL or too small.
STATUS_SUCCESS: The log page data was interpreted and the Resources output
buffer has data in it.
This function may return other NTSTATUS codes from internal function calls.
--*/
{
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
USHORT pageLength;
PLOG_PARAMETER_HEADER parameter;
PVOID endOfPage;
USHORT parameterCode;
ULONG resourceCount;
UCHAR thresholdExponent = fdoExtension->FunctionSupportInfo->LBProvisioningData.ThresholdExponent;
ULONGLONG thresholdSetSize;
//
// SBC-3 states that the threshold exponent (from the 0xB2 VPD page), must
// be non-zero and less than or equal to 32.
//
if (thresholdExponent < 0 || thresholdExponent > 32)
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassInterpretLBProvisioningLogPage: DO (%p), Threshold Exponent (%u) is invalid.\n",
DeviceObject,
thresholdExponent));
return STATUS_NOT_SUPPORTED;
}
if (Resources == NULL ||
ResourcesSize < sizeof(STORAGE_LB_PROVISIONING_MAP_RESOURCES) ||
LogPage == NULL ||
LogPageSize < sizeof(LOG_PAGE_LOGICAL_BLOCK_PROVISIONING))
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassInterpretLBProvisioningLogPage: DO (%p), Invalid parameter, Resources = %p, ResourcesSize = %u, LogPage = %p, LogPageSize = %u.\n",
DeviceObject,
Resources,
ResourcesSize,
LogPage,
LogPageSize));
return STATUS_INVALID_PARAMETER;
}
//
// Calculate the threshold set size (in LBAs).
//
thresholdSetSize = 1I64 << thresholdExponent;
REVERSE_BYTES_SHORT(&pageLength, &(LogPage->PageLength));
//
// Initialize the output buffer.
//
RtlZeroMemory(Resources, sizeof(STORAGE_LB_PROVISIONING_MAP_RESOURCES));
Resources->Size = sizeof(STORAGE_LB_PROVISIONING_MAP_RESOURCES);
Resources->Version = sizeof(STORAGE_LB_PROVISIONING_MAP_RESOURCES);
//
// Make sure we don't walk off the end of the log page buffer
// if pageLength is somehow longer than the buffer itself.
//
pageLength = (USHORT)min(pageLength, (LogPageSize - FIELD_OFFSET(LOG_PAGE_LOGICAL_BLOCK_PROVISIONING, Parameters)));
parameter = (PLOG_PARAMETER_HEADER)((PUCHAR)LogPage + FIELD_OFFSET(LOG_PAGE_LOGICAL_BLOCK_PROVISIONING, Parameters));
endOfPage = (PVOID)((PUCHAR)parameter + pageLength);
//
// Walk the parameters.
//
while ((PVOID)parameter < endOfPage)
{
if (parameter->ParameterLength > 0)
{
REVERSE_BYTES_SHORT(¶meterCode, &(parameter->ParameterCode));
switch(parameterCode)
{
case LOG_PAGE_LBP_PARAMETER_CODE_AVAILABLE:
{
REVERSE_BYTES(&resourceCount, &(((PLOG_PARAMETER_THRESHOLD_RESOURCE_COUNT)parameter)->ResourceCount));
Resources->AvailableMappingResources = (ULONGLONG)resourceCount * thresholdSetSize * (ULONGLONG)fdoExtension->DiskGeometry.BytesPerSector;
Resources->AvailableMappingResourcesValid = TRUE;
//
// Devices that implement SBC-3 revisions older than r27 will not specify
// an LBP log page parameter that has fields beyond ResourceCount.
//
if (parameter->ParameterLength > FIELD_OFFSET(LOG_PARAMETER_THRESHOLD_RESOURCE_COUNT, ResourceCount[3])) {
Resources->AvailableMappingResourcesScope = ((PLOG_PARAMETER_THRESHOLD_RESOURCE_COUNT)parameter)->Scope;
}
break;
}
case LOG_PAGE_LBP_PARAMETER_CODE_USED:
{
REVERSE_BYTES(&resourceCount, &(((PLOG_PARAMETER_THRESHOLD_RESOURCE_COUNT)parameter)->ResourceCount));
Resources->UsedMappingResources = (ULONGLONG)resourceCount * thresholdSetSize * (ULONGLONG)fdoExtension->DiskGeometry.BytesPerSector;
Resources->UsedMappingResourcesValid = TRUE;
//
// Devices that implement SBC-3 revisions older than r27 will not specify
// an LBP log page parameter that has fields beyond ResourceCount.
//
if (parameter->ParameterLength > FIELD_OFFSET(LOG_PARAMETER_THRESHOLD_RESOURCE_COUNT, ResourceCount[3])) {
Resources->UsedMappingResourcesScope = ((PLOG_PARAMETER_THRESHOLD_RESOURCE_COUNT)parameter)->Scope;
}
break;
}
}
}
//
// Move to the next parameter.
//
parameter = (PLOG_PARAMETER_HEADER)((PUCHAR)parameter + sizeof(LOG_PARAMETER_HEADER) + parameter->ParameterLength);
}
return STATUS_SUCCESS;
}
NTSTATUS ClassGetLBProvisioningResources(
_In_ PDEVICE_OBJECT DeviceObject,
_Inout_ PSCSI_REQUEST_BLOCK Srb,
_In_ ULONG ResourcesSize,
_Inout_ PSTORAGE_LB_PROVISIONING_MAP_RESOURCES Resources
)
/*
Routine Description:
This function obtains the Logical Block Provisioning log page, interprets
its contents, and returns the interpreted data in a
STORAGE_LB_PROVISIONING_MAP_RESOURCES structure.
None, some, or all of the data in the output buffer may be valid. The
caller must look at the individual "Valid" fields to see which fields have
valid data.
Arguments:
DeviceObject: The target FDO.
Srb: This should be allocated before it is passed in, but it does not have
to be initialized.
ResourcesSize: The size of the Resources buffer in bytes.
Resources: A pointer to an already allocated output buffer that may contain
the interpreted log page data when this function returns.
Return Value:
STATUS_NOT_SUPPORTED: May be returned if the device does not have LBP enabled.
STATUS_INVALID_PARAMETER: May be returned if either the Resources buffer is
NULL or too small.
STATUS_INSUFFICIENT_RESOURCES: May be returned if a log page buffer could not
be allocated.
STATUS_SUCCESS: The log page data was obtained and the Resources output
buffer has data in it.
This function may return other NTSTATUS codes from internal function calls.
--*/
{
NTSTATUS status;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
ULONG logPageSize;
PLOG_PAGE_LOGICAL_BLOCK_PROVISIONING logPage = NULL;
//
// This functionality is only supported for devices that support logical
// block provisioning.
//
if (fdoExtension->FunctionSupportInfo->ValidInquiryPages.LBProvisioning == FALSE)
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassGetLBProvisioningResources: DO (%p), Device does not support logical block provisioning.\n",
DeviceObject));
return STATUS_NOT_SUPPORTED;
}
//
// Validate the output buffer.
//
if (Resources == NULL ||
ResourcesSize < sizeof(STORAGE_LB_PROVISIONING_MAP_RESOURCES))
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassGetLBProvisioningResources: DO (%p), Invalid parameter, Resources = %p, ResourcesSize = %u.\n",
DeviceObject,
Resources,
ResourcesSize));
return STATUS_INVALID_PARAMETER;
}
//
// Allocate a buffer for the log page. Currently the log page contains:
// 1. Log page header
// 2. Log page parameter for used resources
// 3. Log page parameter for available resources
//
logPageSize = sizeof(LOG_PAGE_LOGICAL_BLOCK_PROVISIONING) + (2 * sizeof(LOG_PARAMETER_THRESHOLD_RESOURCE_COUNT));
#if defined(_ARM_) || defined(_ARM64_)
//
// ARM has specific alignment requirements, although this will not have a functional impact on x86 or amd64
// based platforms. We are taking the conservative approach here.
//
logPageSize = ALIGN_UP_BY(logPageSize, KeGetRecommendedSharedDataAlignment());
logPage = (PLOG_PAGE_LOGICAL_BLOCK_PROVISIONING)
ExAllocatePoolZero(NonPagedPoolNxCacheAligned,
logPageSize,
CLASS_TAG_LB_PROVISIONING);
#else
logPage = (PLOG_PAGE_LOGICAL_BLOCK_PROVISIONING)
ExAllocatePoolZero(NonPagedPoolNx,
logPageSize,
CLASS_TAG_LB_PROVISIONING);
#endif
if (logPage != NULL)
{
//
// Get the LBP log page from the device.
//
status = ClassGetLBProvisioningLogPage(DeviceObject,
Srb,
logPageSize,
logPage);
if (NT_SUCCESS(status))
{
//
// Interpret the log page and fill in the output buffer.
//
status = ClassInterpretLBProvisioningLogPage(DeviceObject,
logPageSize,
logPage,
ResourcesSize,
Resources);
}
ExFreePool(logPage);
}
else
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassGetLBProvisioningResources: DO (%p), Failed to allocate memory for LBP log page.\n",
DeviceObject));
status = STATUS_INSUFFICIENT_RESOURCES;
}
return status;
}
NTSTATUS
ClassDeviceGetLBProvisioningResources(
_In_ PDEVICE_OBJECT DeviceObject,
_Inout_ PIRP Irp,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
/*
Routine Description:
This function returns the LBP resource counts in a
STORAGE_LB_PROVISIONING_MAP_RESOURCES structure in the IRP.
None, some, or all of the data in the output buffer may be valid. The
caller must look at the individual "Valid" fields to see which fields have
valid data.
Arguments:
DeviceObject: The target FDO.
Irp: The IRP which will contain the output buffer upon completion.
Srb: This should be allocated before it is passed in, but it does not have
to be initialized.
Return Value:
Some NTSTATUS code.
--*/
{
NTSTATUS status;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
PSTORAGE_LB_PROVISIONING_MAP_RESOURCES mapResources = (PSTORAGE_LB_PROVISIONING_MAP_RESOURCES)Irp->AssociatedIrp.SystemBuffer;
status = ClassGetLBProvisioningResources(DeviceObject,
Srb,
irpStack->Parameters.DeviceIoControl.OutputBufferLength,
mapResources);
if (NT_SUCCESS(status)) {
Irp->IoStatus.Information = mapResources->Size;
} else {
Irp->IoStatus.Information = 0;
}
Irp->IoStatus.Status = status;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
return status;
}
_Function_class_(IO_WORKITEM_ROUTINE)
_IRQL_requires_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
ClassLogThresholdEvent(
_In_ PDEVICE_OBJECT DeviceObject,
_In_opt_ PVOID Context
)
/*
Routine Description:
This function logs a logical block provisioning soft threshold event to the
system event log.
Arguments:
DeviceObject: The FDO that represents the device that reported the soft
threshold.
Context: A pointer to the IO_WORKITEM in which this function is running.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PIO_WORKITEM workItem = (PIO_WORKITEM)Context;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PSCSI_REQUEST_BLOCK srb = NULL;
STORAGE_LB_PROVISIONING_MAP_RESOURCES resources = {0};
ULONG resourcesSize = sizeof(STORAGE_LB_PROVISIONING_MAP_RESOURCES);
PIO_ERROR_LOG_PACKET errorLogEntry = NULL;
ULONG logEntrySize = sizeof(IO_ERROR_LOG_PACKET);
PWCHAR stringIndex = NULL;
LONG stringSize = 0;
ULONG srbSize;
//
// Allocate an SRB for getting the LBP log page.
//
if ((fdoExtension->AdapterDescriptor != NULL) &&
(fdoExtension->AdapterDescriptor->SrbType == SRB_TYPE_STORAGE_REQUEST_BLOCK)) {
srbSize = CLASS_SRBEX_SCSI_CDB16_BUFFER_SIZE;
} else {
srbSize = sizeof(SCSI_REQUEST_BLOCK);
}
srb = ExAllocatePoolZero(NonPagedPoolNx,
srbSize,
'ACcS');
if (srb != NULL) {
//
// Try to get the LBP resources from the device so we can report them in
// the system event log.
//
ClassGetLBProvisioningResources(DeviceObject,
srb,
resourcesSize,
&resources);
//
// We need to allocate enough space for 3 insertion strings:
// The first is a ULONG representing the disk number in decimal, which means
// a max of 10 digits, plus one for the NULL character.
// The second and third are ULONGLONGs representing the used and available
// bytes, which means a max of 20 digits, plus one for the NULL character.
// Make sure we do not exceed the max error log size or the max size of a
// UCHAR since the size gets truncated to a UCHAR when we pass it to
// IoAllocateErrorLogEntry().
//
logEntrySize = sizeof(IO_ERROR_LOG_PACKET) + (11 * sizeof(WCHAR)) + (2 * (21 * sizeof(WCHAR)));
logEntrySize = min(logEntrySize, ERROR_LOG_MAXIMUM_SIZE);
logEntrySize = min(logEntrySize, MAXUCHAR);
errorLogEntry = (PIO_ERROR_LOG_PACKET)IoAllocateErrorLogEntry(DeviceObject, (UCHAR)logEntrySize);
if (errorLogEntry != NULL)
{
//
// There are two event IDs we can use here. Both use the disk number,
// but one reports the available and used bytes while the other does not.
// We fall back on the latter if we failed to obtain the available and
// used byte counts from the LBP log page.
//
// The event insertion strings need to be in this order:
// 1. The disk number. (Both event IDs use this.)
// 2. Bytes used.
// 3. Bytes available.
//
RtlZeroMemory(errorLogEntry, logEntrySize);
errorLogEntry->StringOffset = sizeof(IO_ERROR_LOG_PACKET);
stringIndex = (PWCHAR)((ULONG_PTR)errorLogEntry + sizeof(IO_ERROR_LOG_PACKET));
stringSize = logEntrySize - sizeof(IO_ERROR_LOG_PACKET);
//
// Add the disk number to the insertion strings.
//
status = RtlStringCbPrintfW(stringIndex, stringSize, L"%d", fdoExtension->DeviceNumber);
if (NT_SUCCESS(status) )
{
errorLogEntry->NumberOfStrings++;
if (resources.UsedMappingResourcesValid &&
resources.AvailableMappingResourcesValid)
{
//
// Add the used mapping resources to the insertion strings.
//
stringIndex += (wcslen(stringIndex) + 1);
stringSize -= (LONG)(wcslen(stringIndex) + 1) * sizeof(WCHAR);
status = RtlStringCbPrintfW(stringIndex, stringSize, L"%I64u", resources.UsedMappingResources);
if (NT_SUCCESS(status))
{
errorLogEntry->NumberOfStrings++;
//
// Add the available mapping resources to the insertion strings.
//
stringIndex += (wcslen(stringIndex) + 1);
stringSize -= (LONG)(wcslen(stringIndex) + 1) * sizeof(WCHAR);
status = RtlStringCbPrintfW(stringIndex, stringSize, L"%I64u", resources.AvailableMappingResources);
if (NT_SUCCESS(status))
{
errorLogEntry->NumberOfStrings++;
}
}
}
else
{
TracePrint((TRACE_LEVEL_WARNING,
TRACE_FLAG_GENERAL,
"ClassLogThresholdEvent: DO (%p), Used and available mapping resources were unavailable.\n",
DeviceObject));
}
}
//
// If we were able to successfully assemble all 3 insertion strings,
// then we can use one of the "extended" event IDs. Otherwise, use the basic
// event ID, which only requires the disk number.
//
if (errorLogEntry->NumberOfStrings == 3)
{
if (resources.UsedMappingResourcesScope == LOG_PAGE_LBP_RESOURCE_SCOPE_DEDICATED_TO_LUN &&
resources.AvailableMappingResourcesScope == LOG_PAGE_LBP_RESOURCE_SCOPE_DEDICATED_TO_LUN) {
errorLogEntry->ErrorCode = IO_WARNING_SOFT_THRESHOLD_REACHED_EX_LUN_LUN;
} else if (resources.UsedMappingResourcesScope == LOG_PAGE_LBP_RESOURCE_SCOPE_DEDICATED_TO_LUN &&
resources.AvailableMappingResourcesScope == LOG_PAGE_LBP_RESOURCE_SCOPE_NOT_DEDICATED_TO_LUN) {
errorLogEntry->ErrorCode = IO_WARNING_SOFT_THRESHOLD_REACHED_EX_LUN_POOL;
} else if (resources.UsedMappingResourcesScope == LOG_PAGE_LBP_RESOURCE_SCOPE_NOT_DEDICATED_TO_LUN &&
resources.AvailableMappingResourcesScope == LOG_PAGE_LBP_RESOURCE_SCOPE_DEDICATED_TO_LUN) {
errorLogEntry->ErrorCode = IO_WARNING_SOFT_THRESHOLD_REACHED_EX_POOL_LUN;
} else if (resources.UsedMappingResourcesScope == LOG_PAGE_LBP_RESOURCE_SCOPE_NOT_DEDICATED_TO_LUN &&
resources.AvailableMappingResourcesScope == LOG_PAGE_LBP_RESOURCE_SCOPE_NOT_DEDICATED_TO_LUN) {
errorLogEntry->ErrorCode = IO_WARNING_SOFT_THRESHOLD_REACHED_EX_POOL_POOL;
} else {
errorLogEntry->ErrorCode = IO_WARNING_SOFT_THRESHOLD_REACHED_EX;
}
}
else
{
errorLogEntry->ErrorCode = IO_WARNING_SOFT_THRESHOLD_REACHED;
}
//
// Write the error log packet to the system error logging thread.
// It will be freed automatically.
//
IoWriteErrorLogEntry(errorLogEntry);
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClassLogThresholdEvent: DO (%p), Soft threshold notification logged.\n",
DeviceObject));
}
else
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassLogThresholdEvent: DO (%p), Failed to allocate memory for error log entry.\n",
DeviceObject));
}
} else {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassLogThresholdEvent: DO (%p), Failed to allocate memory for SRB.\n",
DeviceObject));
}
//
// Clear the soft threshold event pending flag so that another can be queued.
//
InterlockedExchange((PLONG)&(fdoExtension->FunctionSupportInfo->LBProvisioningData.SoftThresholdEventPending), 0);
ClassReleaseRemoveLock(DeviceObject, (PIRP)workItem);
FREE_POOL(srb);
if (workItem != NULL) {
IoFreeWorkItem(workItem);
}
}
NTSTATUS
ClasspLogSystemEventWithDeviceNumber(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ NTSTATUS IoErrorCode
)
/*
Routine Description:
This function is a helper routine to log any system events that require
the DeviceNumber (e.g. disk number). It is basically a wrapper for the
IoWriteErrorLogEntry call.
Arguments:
DeviceObject: The FDO that represents the device for which the event needs to be logged.
IoErrorCode: The IO error code for the event.
Return Value:
STATUS_SUCCESS - if the event was logged
STATUS_INSUFFICIENT_RESOURCES - otherwise
--*/
{
NTSTATUS status = STATUS_INSUFFICIENT_RESOURCES;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
PIO_ERROR_LOG_PACKET errorLogEntry = NULL;
ULONG logEntrySize = sizeof(IO_ERROR_LOG_PACKET);
PWCHAR stringIndex = NULL;
LONG stringSize = 0;
//
// We need to allocate enough space for one insertion string: a ULONG
// representing the disk number in decimal, which means a max of 10 digits,
// plus one for the NULL character.
// Make sure we do not exceed the max error log size or the max size of a
// UCHAR since the size gets truncated to a UCHAR when we pass it to
// IoAllocateErrorLogEntry().
//
logEntrySize = sizeof(IO_ERROR_LOG_PACKET) + (11 * sizeof(WCHAR));
logEntrySize = min(logEntrySize, ERROR_LOG_MAXIMUM_SIZE);
logEntrySize = min(logEntrySize, MAXUCHAR);
errorLogEntry = (PIO_ERROR_LOG_PACKET)IoAllocateErrorLogEntry(DeviceObject, (UCHAR)logEntrySize);
if (errorLogEntry) {
RtlZeroMemory(errorLogEntry, logEntrySize);
errorLogEntry->StringOffset = sizeof(IO_ERROR_LOG_PACKET);
errorLogEntry->ErrorCode = IoErrorCode;
stringIndex = (PWCHAR)((ULONG_PTR)errorLogEntry + sizeof(IO_ERROR_LOG_PACKET));
stringSize = logEntrySize - sizeof(IO_ERROR_LOG_PACKET);
//
// Add the disk number to the insertion strings.
//
status = RtlStringCbPrintfW(stringIndex, stringSize, L"%d", fdoExtension->DeviceNumber);
if (NT_SUCCESS(status)) {
errorLogEntry->NumberOfStrings++;
}
//
// Write the error log packet to the system error logging thread.
// It will be freed automatically.
//
IoWriteErrorLogEntry(errorLogEntry);
status = STATUS_SUCCESS;
}
return status;
}
_Function_class_(IO_WORKITEM_ROUTINE)
_IRQL_requires_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
ClassLogResourceExhaustionEvent(
_In_ PDEVICE_OBJECT DeviceObject,
_In_opt_ PVOID Context
)
/*
Routine Description:
This function logs a logical block provisioning permanent resource exhaustion
event to the system event log.
Arguments:
DeviceObject: The FDO that represents the device that reported the permanent
resource exhaustion.
Context: A pointer to the IO_WORKITEM in which this function is running.
--*/
{
PIO_WORKITEM workItem = (PIO_WORKITEM)Context;
if (NT_SUCCESS(ClasspLogSystemEventWithDeviceNumber(DeviceObject, IO_ERROR_DISK_RESOURCES_EXHAUSTED))) {
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClassLogResourceExhaustionEvent: DO (%p), Permanent resource exhaustion logged.\n",
DeviceObject));
} else {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassLogResourceExhaustionEvent: DO (%p), Failed to allocate memory for error log entry.\n",
DeviceObject));
}
ClassReleaseRemoveLock(DeviceObject, (PIRP)workItem);
if (workItem != NULL) {
IoFreeWorkItem(workItem);
}
}
VOID ClassQueueThresholdEventWorker(
_In_ PDEVICE_OBJECT DeviceObject
)
/*
Routine Description:
This function queues a delayed work item that will eventually log a
logical block provisioning soft threshold event to the system event log.
Arguments:
DeviceObject: The FDO that represents the device that reported the soft
threshold.
--*/
{
PCOMMON_DEVICE_EXTENSION commonExtension = (PCOMMON_DEVICE_EXTENSION)(DeviceObject->DeviceExtension);
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)(DeviceObject->DeviceExtension);
PIO_WORKITEM workItem = NULL;
if (commonExtension->IsFdo &&
InterlockedCompareExchange((PLONG)&(fdoExtension->FunctionSupportInfo->LBProvisioningData.SoftThresholdEventPending), 1, 0) == 0)
{
workItem = IoAllocateWorkItem(DeviceObject);
if (workItem)
{
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClassQueueThresholdEventWorker: DO (%p), Queueing soft threshold notification work item.\n",
DeviceObject));
ClassAcquireRemoveLock(DeviceObject, (PIRP)(workItem));
//
// Queue a work item to write the threshold notification to the
// system event log.
//
IoQueueWorkItem(workItem, ClassLogThresholdEvent, DelayedWorkQueue, workItem);
}
else
{
//
// Clear the soft threshold event pending flag since this is normally
// done when the work item completes.
//
InterlockedExchange((PLONG)&(fdoExtension->FunctionSupportInfo->LBProvisioningData.SoftThresholdEventPending), 0);
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassQueueThresholdEventWorker: DO (%p), Failed to allocate memory for the work item.\n",
DeviceObject));
}
}
}
VOID ClassQueueResourceExhaustionEventWorker(
_In_ PDEVICE_OBJECT DeviceObject
)
/*
Routine Description:
This function queues a delayed work item that will eventually log a
logical block provisioning permanent resource exhaustion event to the
system event log.
Arguments:
DeviceObject: The FDO that represents the device that reported the resource
exhaustion.
--*/
{
PCOMMON_DEVICE_EXTENSION commonExtension = (PCOMMON_DEVICE_EXTENSION)(DeviceObject->DeviceExtension);
PIO_WORKITEM workItem = NULL;
if (commonExtension->IsFdo)
{
workItem = IoAllocateWorkItem(DeviceObject);
if (workItem)
{
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClassQueueResourceExhaustionEventWorker: DO (%p), Queueing permanent resource exhaustion event work item.\n",
DeviceObject));
ClassAcquireRemoveLock(DeviceObject, (PIRP)(workItem));
//
// Queue a work item to write the threshold notification to the
// system event log.
//
IoQueueWorkItem(workItem, ClassLogResourceExhaustionEvent, DelayedWorkQueue, workItem);
}
else
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassQueueResourceExhaustionEventWorker: DO (%p), Failed to allocate memory for the work item.\n",
DeviceObject));
}
}
}
_Function_class_(IO_WORKITEM_ROUTINE)
_IRQL_requires_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
ClassLogCapacityChangedProcess(
_In_ PDEVICE_OBJECT DeviceObject,
_In_opt_ PVOID Context
)
/*
Routine Description:
This function logs a capacity changed event to the system event log.
Arguments:
DeviceObject: The FDO that represents the device that reported the capacity change.
Context: A pointer to the IO_WORKITEM in which this function is running.
--*/
{
NTSTATUS status;
PIO_WORKITEM workItem = (PIO_WORKITEM)Context;
status = ClasspLogSystemEventWithDeviceNumber(DeviceObject, IO_WARNING_DISK_CAPACITY_CHANGED);
if (NT_SUCCESS(status)) {
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClassLogCapacityChangedEvent: DO (%p), Capacity changed logged.\n",
DeviceObject));
} else {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassLogCapacityChangedEvent: DO (%p), Failed to allocate memory for error log entry.\n",
DeviceObject));
}
//
// Get disk capacity and notify upper layer if capacity is changed.
//
status = ClassReadDriveCapacity(DeviceObject);
if (!NT_SUCCESS(status)) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassLogCapacityChangedEvent: DO (%p), ClassReadDriveCapacity returned %!STATUS!.\n",
DeviceObject,
status));
}
ClassReleaseRemoveLock(DeviceObject, (PIRP)workItem);
if (workItem != NULL) {
IoFreeWorkItem(workItem);
}
}
VOID
ClassQueueCapacityChangedEventWorker(
_In_ PDEVICE_OBJECT DeviceObject
)
/*
Routine Description:
This function queues a delayed work item that will eventually log a
disk capacity changed event to the system event log.
Arguments:
DeviceObject: The FDO that represents the device that reported the capacity change.
--*/
{
PCOMMON_DEVICE_EXTENSION commonExtension = (PCOMMON_DEVICE_EXTENSION)(DeviceObject->DeviceExtension);
PIO_WORKITEM workItem = NULL;
if (commonExtension->IsFdo)
{
workItem = IoAllocateWorkItem(DeviceObject);
if (workItem)
{
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClassQueueCapacityChangedEventWorker: DO (%p), Queueing capacity changed event work item.\n",
DeviceObject));
ClassAcquireRemoveLock(DeviceObject, (PIRP)(workItem));
//
// Queue a work item to write the threshold notification to the
// system event log.
//
IoQueueWorkItem(workItem, ClassLogCapacityChangedProcess, DelayedWorkQueue, workItem);
}
else
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassQueueCapacityChangedEventWorker: DO (%p), Failed to allocate memory for the work item.\n",
DeviceObject));
}
}
}
_Function_class_(IO_WORKITEM_ROUTINE)
_IRQL_requires_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
ClassLogProvisioningTypeChangedEvent(
PDEVICE_OBJECT DeviceObject,
PVOID Context
)
/*
Routine Description:
This function logs a provisioning type changed event to the system event log.
Arguments:
DeviceObject: The FDO that represents the device that reported the provisioning type change.
Context: A pointer to the IO_WORKITEM in which this function is running.
--*/
{
PIO_WORKITEM workItem = (PIO_WORKITEM)Context;
if (NT_SUCCESS(ClasspLogSystemEventWithDeviceNumber(DeviceObject, IO_WARNING_DISK_PROVISIONING_TYPE_CHANGED))) {
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClassLogProvisioningTypeChangedEvent: DO (%p), LB Provisioning Type changed logged.\n",
DeviceObject));
} else {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassLogProvisioningTypeChangedEvent: DO (%p), Failed to allocate memory for error log entry.\n",
DeviceObject));
}
ClassReleaseRemoveLock(DeviceObject, (PIRP)workItem);
IoFreeWorkItem(workItem);
}
VOID
ClassQueueProvisioningTypeChangedEventWorker(
_In_ PDEVICE_OBJECT DeviceObject
)
/*
Routine Description:
This function queues a delayed work item that will eventually log a
provisioning type changed event to the system event log.
Arguments:
DeviceObject: The FDO that represents the device that reported the provisioning type change.
--*/
{
PCOMMON_DEVICE_EXTENSION commonExtension = (PCOMMON_DEVICE_EXTENSION)(DeviceObject->DeviceExtension);
PIO_WORKITEM workItem = NULL;
if (commonExtension->IsFdo)
{
workItem = IoAllocateWorkItem(DeviceObject);
if (workItem)
{
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClassQueueProvisioningTypeChangedEventWorker: DO (%p), Queueing LB provisioning type changed event work item.\n",
DeviceObject));
ClassAcquireRemoveLock(DeviceObject, (PIRP)(workItem));
//
// Queue a work item to write the threshold notification to the
// system event log.
//
IoQueueWorkItem(workItem, ClassLogProvisioningTypeChangedEvent, DelayedWorkQueue, workItem);
}
else
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClassQueueProvisioningTypeChangedEventWorker: DO (%p), Failed to allocate memory for the work item.\n",
DeviceObject));
}
}
}
_Function_class_(IO_WORKITEM_ROUTINE)
_IRQL_requires_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
ClasspLogIOEventWithContext(
_In_ PDEVICE_OBJECT DeviceObject,
_In_opt_ PVOID Context
)
/*
Routine Description:
This function logs an event to the system event log with dumpdata containing opcode and
sense data.
Arguments:
DeviceObject: The FDO that represents the device that retried the IO.
Context: A pointer to the OPCODE_SENSE_DATA_IO_LOG_MESSAGE_CONTEXT that has data to be logged as part of the message.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
POPCODE_SENSE_DATA_IO_LOG_MESSAGE_CONTEXT_HEADER ioLogMessageContextHeader = (POPCODE_SENSE_DATA_IO_LOG_MESSAGE_CONTEXT_HEADER)Context;
PIO_WORKITEM workItem;
PIO_ERROR_LOG_PACKET errorLogEntry = NULL;
ULONG logEntrySize;
PWCHAR stringIndex = NULL;
LONG stringSize = 0;
ULONG senseBufferSize;
ULONG stringsBufferLength = 0;
ULONG pdoNameLength = 0;
NT_ASSERT(ioLogMessageContextHeader != NULL);
_Analysis_assume_(ioLogMessageContextHeader != NULL);
switch (ioLogMessageContextHeader->ErrorCode) {
case IO_ERROR_IO_HARDWARE_ERROR:
case IO_WARNING_IO_OPERATION_RETRIED: {
//
// We need to allocate enough space for 3 insertion strings:
// 1. A ULONGLONG in Hex representing the LBA which means a max of 16 digits,
// plus two for "0x" plus one for the NULL character.
// 2. A ULONG representing the disk number in decimal, which means
// a max of 10 digits, plus one for the NULL character.
// 3. The PDO name, so that if the disk number is hidden from the
// user for some reason, there is still a way to associate the
// event with the correct device.
//
stringsBufferLength = (19 + 11) * sizeof(WCHAR);
//
// Query for the size of the PDO name.
//
status = IoGetDeviceProperty(fdoExtension->LowerPdo,
DevicePropertyPhysicalDeviceObjectName,
0,
NULL,
&pdoNameLength);
if (status == STATUS_BUFFER_TOO_SMALL && pdoNameLength > 0) {
stringsBufferLength += pdoNameLength;
} else {
pdoNameLength = 0;
}
break;
}
}
workItem = ioLogMessageContextHeader->WorkItem;
//
// DumpData[0] which is of ULONG size and will contain opcode|srbstatus|scsistatus.
// Then we will have sensebuffer, hence
// DumpDataSize = senseBufferSize + sizeof(ULONG)
// and DumpDataSize must be multiple of sizeof(ULONG)
// which means senseBufferSize needs to ULONG aligned
// Please note we will use original buffersize for padding later
//
senseBufferSize = ALIGN_UP_BY(ioLogMessageContextHeader->SenseDataSize, sizeof(ULONG));
logEntrySize = FIELD_OFFSET( IO_ERROR_LOG_PACKET, DumpData ) + sizeof(ULONG) + senseBufferSize;
//
// We need to make sure the string offset is WCHAR-aligned (the insertion strings
// come after the sense buffer in the dump data, if any).
// But we don't need to do anything special for it,
// since FIELD_OFFSET( IO_ERROR_LOG_PACKET, DumpData) is currently ULONG aligned
// and SenseBufferSize is also ULONG aligned. This means buffer that precedes the insertion string is ULONG aligned
// note stringoffset = FIELD_OFFSET( IO_ERROR_LOG_PACKET, DumpData ) + DumpDataSize
// This leads us to fact that stringoffset will always be ULONG aligned and effectively WCHAR aligned
//
//
// We need to allocate enough space for the insertion strings provided in the passed in Context
// as well as the opcode and the sense data, while making sure we cap at max error log size.
// The log packet is followed by the opcode, then the sense data, and then the
// insertion strings.
//
logEntrySize = logEntrySize + stringsBufferLength;
if (logEntrySize > ERROR_LOG_MAXIMUM_SIZE) {
if (senseBufferSize) {
if (logEntrySize - ERROR_LOG_MAXIMUM_SIZE < senseBufferSize) {
//
// In below steps, senseBufferSize will become same or less than as ioLogMessageContextHeader->SenseDataSize
// it can't be more than that.
//
senseBufferSize -= logEntrySize - ERROR_LOG_MAXIMUM_SIZE;
//
// Decrease the sensebuffersize further, if needed, to keep senseBufferSize ULONG aligned
//
senseBufferSize = ALIGN_DOWN_BY(senseBufferSize, sizeof(ULONG));
} else {
senseBufferSize = 0;
}
}
logEntrySize = ERROR_LOG_MAXIMUM_SIZE;
}
errorLogEntry = (PIO_ERROR_LOG_PACKET)IoAllocateErrorLogEntry(DeviceObject, (UCHAR)logEntrySize);
if (errorLogEntry) {
RtlZeroMemory(errorLogEntry, logEntrySize);
errorLogEntry->MajorFunctionCode = IRP_MJ_SCSI;
errorLogEntry->RetryCount = 1;
errorLogEntry->DumpDataSize = (USHORT)(sizeof(ULONG) + senseBufferSize);
errorLogEntry->StringOffset = (USHORT)(FIELD_OFFSET( IO_ERROR_LOG_PACKET, DumpData ) + errorLogEntry->DumpDataSize);
errorLogEntry->ErrorCode = ioLogMessageContextHeader->ErrorCode;
errorLogEntry->DumpData[0] = (((ULONG)(ioLogMessageContextHeader->OpCode)) << 24) |
(((ULONG)(ioLogMessageContextHeader->SrbStatus)) << 16) |
(((ULONG)(ioLogMessageContextHeader->ScsiStatus)) << 8);
//
// Copy sense data and do padding for sense data if needed, with '-'
//
if (senseBufferSize > ioLogMessageContextHeader->SenseDataSize) {
RtlCopyMemory(&errorLogEntry->DumpData[1], ioLogMessageContextHeader->SenseData, ioLogMessageContextHeader->SenseDataSize);
RtlFillMemory( (PCHAR)&errorLogEntry->DumpData[1] + ioLogMessageContextHeader->SenseDataSize , (senseBufferSize - ioLogMessageContextHeader->SenseDataSize) , '-' );
} else {
RtlCopyMemory(&errorLogEntry->DumpData[1], ioLogMessageContextHeader->SenseData, senseBufferSize);
}
stringIndex = (PWCHAR)((PCHAR)errorLogEntry->DumpData + errorLogEntry->DumpDataSize);
stringSize = logEntrySize - errorLogEntry->StringOffset;
//
// Add the strings
//
switch (ioLogMessageContextHeader->ErrorCode) {
case IO_ERROR_IO_HARDWARE_ERROR:
case IO_WARNING_IO_OPERATION_RETRIED: {
PIO_RETRIED_LOG_MESSAGE_CONTEXT ioLogMessageContext = (PIO_RETRIED_LOG_MESSAGE_CONTEXT)Context;
//
// The first is a "0x" plus ULONGLONG in hex representing the LBA plus the NULL character.
// The second is a ULONG representing the disk number plus the NULL character.
//
status = RtlStringCbPrintfW(stringIndex, stringSize, L"0x%I64x", ioLogMessageContext->Lba.QuadPart);
if (NT_SUCCESS(status)) {
errorLogEntry->NumberOfStrings++;
//
// Add the disk number to the insertion strings.
//
stringSize -= (ULONG)(wcslen(stringIndex) + 1) * sizeof(WCHAR);
stringIndex += (wcslen(stringIndex) + 1);
if (stringSize > 0) {
status = RtlStringCbPrintfW(stringIndex, stringSize, L"%d", ioLogMessageContext->DeviceNumber);
if (NT_SUCCESS(status)) {
errorLogEntry->NumberOfStrings++;
stringSize -= (ULONG)(wcslen(stringIndex) + 1) * sizeof(WCHAR);
stringIndex += (wcslen(stringIndex) + 1);
if (stringSize >= (LONG)pdoNameLength && pdoNameLength > 0) {
ULONG resultLength;
//
// Get the PDO name and place it in the insertion string buffer.
//
status = IoGetDeviceProperty(fdoExtension->LowerPdo,
DevicePropertyPhysicalDeviceObjectName,
pdoNameLength,
stringIndex,
&resultLength);
if (NT_SUCCESS(status) && resultLength > 0) {
errorLogEntry->NumberOfStrings++;
}
}
}
}
}
break;
}
}
//
// Write the error log packet to the system error logging thread.
// It will be freed automatically.
//
IoWriteErrorLogEntry(errorLogEntry);
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClasspLogIORetriedEvent: DO (%p), Soft threshold notification logged.\n",
DeviceObject));
}
ClassReleaseRemoveLock(DeviceObject, (PIRP)workItem);
if (ioLogMessageContextHeader->SenseData) {
ExFreePool(ioLogMessageContextHeader->SenseData);
}
if (workItem) {
IoFreeWorkItem(workItem);
}
ExFreePool(ioLogMessageContextHeader);
}
VOID
ClasspQueueLogIOEventWithContextWorker(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ ULONG SenseBufferSize,
_In_ PVOID SenseData,
_In_ UCHAR SrbStatus,
_In_ UCHAR ScsiStatus,
_In_ ULONG ErrorCode,
_In_ ULONG CdbLength,
_In_opt_ PCDB Cdb,
_In_opt_ PTRANSFER_PACKET Pkt
)
/*
Routine Description:
Helper function that queues a delayed work item that will eventually
log an event to the system event log corresponding to passed in ErrorCode.
The dumpdata is fixed to include the opcode and the sense information.
But the number of insertion strings varies based on the passed in ErrorCode.
Arguments:
DeviceObject: The FDO that represents the device that was the target of the IO.
SesneBufferSize: Size of the SenseData buffer.
SenseData: Error information from the target (to be included in the dump data).
SrbStatus: Srb status returned by the miniport.
ScsiStatus: SCSI status associated with the request upon completion from lower layers.
ErrorCode: Numerical value of the error code.
CdbLength: Number of bytes of Cdb.
Cdb: Pointer to the CDB.
Pkt: The tranfer packet representing the IO of interest. This may be NULL.
--*/
{
PCOMMON_DEVICE_EXTENSION commonExtension = (PCOMMON_DEVICE_EXTENSION)(DeviceObject->DeviceExtension);
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
POPCODE_SENSE_DATA_IO_LOG_MESSAGE_CONTEXT_HEADER ioLogMessageContextHeader = NULL;
PVOID senseData = NULL;
PIO_WORKITEM workItem = NULL;
ULONG senseBufferSize = 0;
LARGE_INTEGER lba = {0};
if (!commonExtension->IsFdo) {
return;
}
if (!Cdb) {
return;
}
workItem = IoAllocateWorkItem(DeviceObject);
if (!workItem) {
goto __ClasspQueueLogIOEventWithContextWorker_ExitWithMessage;
}
if (SenseBufferSize) {
senseData = ExAllocatePoolZero(NonPagedPoolNx,
SenseBufferSize,
CLASSPNP_POOL_TAG_LOG_MESSAGE);
if (senseData) {
senseBufferSize = SenseBufferSize;
}
}
if (CdbLength == 16) {
REVERSE_BYTES_QUAD(&lba, Cdb->CDB16.LogicalBlock);
} else {
((PFOUR_BYTE)&lba.LowPart)->Byte3 = Cdb->CDB10.LogicalBlockByte0;
((PFOUR_BYTE)&lba.LowPart)->Byte2 = Cdb->CDB10.LogicalBlockByte1;
((PFOUR_BYTE)&lba.LowPart)->Byte1 = Cdb->CDB10.LogicalBlockByte2;
((PFOUR_BYTE)&lba.LowPart)->Byte0 = Cdb->CDB10.LogicalBlockByte3;
}
//
// Calculate the amount of buffer required for the insertion strings.
//
switch (ErrorCode) {
case IO_ERROR_IO_HARDWARE_ERROR:
case IO_WARNING_IO_OPERATION_RETRIED: {
PIO_RETRIED_LOG_MESSAGE_CONTEXT ioLogMessageContext = NULL;
ioLogMessageContext =
ExAllocatePoolZero(NonPagedPoolNx,
sizeof(IO_RETRIED_LOG_MESSAGE_CONTEXT),
CLASSPNP_POOL_TAG_LOG_MESSAGE);
if (!ioLogMessageContext) {
goto __ClasspQueueLogIOEventWithContextWorker_ExitWithMessage;
}
ioLogMessageContext->Lba.QuadPart = lba.QuadPart;
ioLogMessageContext->DeviceNumber = fdoExtension->DeviceNumber;
ioLogMessageContextHeader = (POPCODE_SENSE_DATA_IO_LOG_MESSAGE_CONTEXT_HEADER)ioLogMessageContext;
break;
}
default: goto __ClasspQueueLogIOEventWithContextWorker_Exit;
}
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_GENERAL,
"ClasspQueueLogIOEventWithContextWorker: DO (%p), Pkt (%p), Queueing IO retried event log message work item.\n",
DeviceObject,
Pkt));
ioLogMessageContextHeader->WorkItem = workItem;
if (senseData) {
RtlCopyMemory(senseData, SenseData, SenseBufferSize);
}
ioLogMessageContextHeader->SenseData = senseData;
ioLogMessageContextHeader->SenseDataSize = senseBufferSize;
ioLogMessageContextHeader->SrbStatus = SrbStatus;
ioLogMessageContextHeader->ScsiStatus = ScsiStatus;
ioLogMessageContextHeader->OpCode = Cdb->CDB6GENERIC.OperationCode;
ioLogMessageContextHeader->Reserved = 0;
ioLogMessageContextHeader->ErrorCode = ErrorCode;
ClassAcquireRemoveLock(DeviceObject, (PIRP)(workItem));
//
// Queue a work item to write the system event log.
//
IoQueueWorkItem(workItem, ClasspLogIOEventWithContext, DelayedWorkQueue, ioLogMessageContextHeader);
return;
__ClasspQueueLogIOEventWithContextWorker_ExitWithMessage:
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_GENERAL,
"ClasspQueueLogIOEventWithContextWorker: DO (%p), Failed to allocate memory for the log message.\n",
DeviceObject));
__ClasspQueueLogIOEventWithContextWorker_Exit:
if (senseData) {
ExFreePool(senseData);
}
if (workItem) {
IoFreeWorkItem(workItem);
}
if (ioLogMessageContextHeader) {
ExFreePool(ioLogMessageContextHeader);
}
}
__inline
BOOLEAN
ValidPersistentReserveScope(
UCHAR Scope)
{
switch (Scope) {
case RESERVATION_SCOPE_LU:
case RESERVATION_SCOPE_ELEMENT:
return TRUE;
default:
break;
}
return FALSE;
}
__inline
ValidPersistentReserveType(
UCHAR Type)
{
switch (Type) {
case RESERVATION_TYPE_WRITE_EXCLUSIVE:
case RESERVATION_TYPE_EXCLUSIVE:
case RESERVATION_TYPE_WRITE_EXCLUSIVE_REGISTRANTS:
case RESERVATION_TYPE_EXCLUSIVE_REGISTRANTS:
return TRUE;
default:
break;
}
return FALSE;
}
/*++
ClasspPersistentReserve
Routine Description:
Handles IOCTL_STORAGE_PERSISTENT_RESERVE_IN and IOCTL_STORAGE_PERSISTENT_RESERVE_OUT.
Arguments:
DeviceObject - a pointer to the device object
Irp - a pointer to the I/O request packet
Srb - pointer to preallocated SCSI_REQUEST_BLOCK.
Return Value:
Status Code
--*/
NTSTATUS
ClasspPersistentReserve(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ PIRP Irp,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
{
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
PCDB cdb = NULL;
PPERSISTENT_RESERVE_COMMAND prCommand = Irp->AssociatedIrp.SystemBuffer;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
NTSTATUS status;
ULONG dataBufLen;
ULONG controlCode = irpStack->Parameters.DeviceIoControl.IoControlCode;
BOOLEAN writeToDevice;
//
// Check common input buffer parameters.
//
if (irpStack->Parameters.DeviceIoControl.InputBufferLength <
sizeof(PERSISTENT_RESERVE_COMMAND) ||
prCommand->Size < sizeof(PERSISTENT_RESERVE_COMMAND)) {
status = STATUS_INFO_LENGTH_MISMATCH;
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = 0;
FREE_POOL(Srb);
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
goto ClasspPersistentReserve_Exit;
}
//
// Check buffer alignment. Only an issue if another kernel mode component
// (not the I/O manager) allocates the buffer.
//
if ((ULONG_PTR)prCommand & fdoExtension->AdapterDescriptor->AlignmentMask) {
status = STATUS_INVALID_USER_BUFFER;
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = 0;
FREE_POOL(Srb);
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
goto ClasspPersistentReserve_Exit;
}
//
// Check additional parameters.
//
status = STATUS_SUCCESS;
SrbSetCdbLength(Srb, 10);
cdb = SrbGetCdb(Srb);
if (controlCode == IOCTL_STORAGE_PERSISTENT_RESERVE_IN) {
//
// Check output buffer for PR In.
//
if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
prCommand->PR_IN.AllocationLength) {
status = STATUS_INVALID_PARAMETER;
}
switch (prCommand->PR_IN.ServiceAction) {
case RESERVATION_ACTION_READ_KEYS:
if (prCommand->PR_IN.AllocationLength < sizeof(PRI_REGISTRATION_LIST)) {
status = STATUS_INVALID_PARAMETER;
}
break;
case RESERVATION_ACTION_READ_RESERVATIONS:
if (prCommand->PR_IN.AllocationLength < sizeof(PRI_RESERVATION_LIST)) {
status = STATUS_INVALID_PARAMETER;
}
break;
default:
status = STATUS_INVALID_PARAMETER;
break;
}
if (!NT_SUCCESS(status)) {
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = 0;
FREE_POOL(Srb);
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
goto ClasspPersistentReserve_Exit;
}
//
// Fill in the CDB.
//
cdb->PERSISTENT_RESERVE_IN.OperationCode = SCSIOP_PERSISTENT_RESERVE_IN;
cdb->PERSISTENT_RESERVE_IN.ServiceAction = prCommand->PR_IN.ServiceAction;
REVERSE_BYTES_SHORT(&(cdb->PERSISTENT_RESERVE_IN.AllocationLength),
&(prCommand->PR_IN.AllocationLength));
dataBufLen = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
writeToDevice = FALSE;
} else {
//
// Verify ServiceAction, Scope, and Type
//
switch (prCommand->PR_OUT.ServiceAction) {
case RESERVATION_ACTION_REGISTER:
case RESERVATION_ACTION_REGISTER_IGNORE_EXISTING:
case RESERVATION_ACTION_CLEAR:
// Scope and type ignored.
break;
case RESERVATION_ACTION_RESERVE:
case RESERVATION_ACTION_RELEASE:
case RESERVATION_ACTION_PREEMPT:
case RESERVATION_ACTION_PREEMPT_ABORT:
if (!ValidPersistentReserveScope(prCommand->PR_OUT.Scope) ||
!ValidPersistentReserveType(prCommand->PR_OUT.Type)) {
status = STATUS_INVALID_PARAMETER;
}
break;
default:
status = STATUS_INVALID_PARAMETER;
break;
}
//
// Check input buffer for PR Out.
// Caller must include the PR parameter list.
//
if (NT_SUCCESS(status)) {
if (irpStack->Parameters.DeviceIoControl.InputBufferLength <
(sizeof(PERSISTENT_RESERVE_COMMAND) +
sizeof(PRO_PARAMETER_LIST)) ||
prCommand->Size <
irpStack->Parameters.DeviceIoControl.InputBufferLength) {
status = STATUS_INVALID_PARAMETER;
}
}
if (!NT_SUCCESS(status)) {
Irp->IoStatus.Status = status;
Irp->IoStatus.Information = 0;
FREE_POOL(Srb);
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
goto ClasspPersistentReserve_Exit;
}
//
// Fill in the CDB.
//
cdb->PERSISTENT_RESERVE_OUT.OperationCode = SCSIOP_PERSISTENT_RESERVE_OUT;
cdb->PERSISTENT_RESERVE_OUT.ServiceAction = prCommand->PR_OUT.ServiceAction;
cdb->PERSISTENT_RESERVE_OUT.Scope = prCommand->PR_OUT.Scope;
cdb->PERSISTENT_RESERVE_OUT.Type = prCommand->PR_OUT.Type;
cdb->PERSISTENT_RESERVE_OUT.ParameterListLength[1] = (UCHAR)sizeof(PRO_PARAMETER_LIST);
//
// Move the parameter list to the beginning of the data buffer (so it is aligned
// correctly and that the MDL describes it correctly).
//
RtlMoveMemory(prCommand,
prCommand->PR_OUT.ParameterList,
sizeof(PRO_PARAMETER_LIST));
dataBufLen = sizeof(PRO_PARAMETER_LIST);
writeToDevice = TRUE;
}
//
// Fill in the SRB
//
//
// Set timeout value.
//
SrbSetTimeOutValue(Srb, fdoExtension->TimeOutValue);
//
// Send as a tagged request.
//
SrbSetRequestAttribute(Srb, SRB_HEAD_OF_QUEUE_TAG_REQUEST);
SrbSetSrbFlags(Srb, SRB_FLAGS_NO_QUEUE_FREEZE | SRB_FLAGS_QUEUE_ACTION_ENABLE);
status = ClassSendSrbAsynchronous(DeviceObject,
Srb,
Irp,
prCommand,
dataBufLen,
writeToDevice);
ClasspPersistentReserve_Exit:
return status;
}
/*++
ClasspPriorityHint
Routine Description:
Handles IOCTL_STORAGE_CHECK_PRIORITY_HINT_SUPPORT.
Arguments:
DeviceObject - a pointer to the device object
Irp - a pointer to the I/O request packet
Return Value:
Status Code
--*/
NTSTATUS
ClasspPriorityHint(
PDEVICE_OBJECT DeviceObject,
PIRP Irp
)
{
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
PCLASS_PRIVATE_FDO_DATA fdoData = fdoExtension->PrivateFdoData;
PSTORAGE_PRIORITY_HINT_SUPPORT priSupport = Irp->AssociatedIrp.SystemBuffer;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
NTSTATUS status = STATUS_SUCCESS;
Irp->IoStatus.Information = 0;
//
// Check whether this device supports idle priority.
//
if (!fdoData->IdlePrioritySupported) {
status = STATUS_NOT_SUPPORTED;
goto PriorityHintExit;
}
if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
sizeof(STORAGE_PRIORITY_HINT_SUPPORT)) {
status = STATUS_BUFFER_TOO_SMALL;
goto PriorityHintExit;
}
RtlZeroMemory(priSupport, sizeof(STORAGE_PRIORITY_HINT_SUPPORT));
status = ClassForwardIrpSynchronous(commonExtension, Irp);
if (!NT_SUCCESS(status)) {
//
// If I/O priority is not supported by lower drivers, just set the
// priorities supported by class driver.
//
TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_IOCTL, "ClasspPriorityHint: I/O priority not supported by port driver.\n"));
priSupport->SupportFlags = 0;
status = STATUS_SUCCESS;
}
TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_IOCTL, "ClasspPriorityHint: I/O priorities supported by port driver: %X\n", priSupport->SupportFlags));
priSupport->SupportFlags |= (1 << IoPriorityVeryLow) |
(1 << IoPriorityLow) |
(1 << IoPriorityNormal) ;
TracePrint((TRACE_LEVEL_FATAL, TRACE_FLAG_IOCTL, "ClasspPriorityHint: I/O priorities supported: %X\n", priSupport->SupportFlags));
Irp->IoStatus.Information = sizeof(STORAGE_PRIORITY_HINT_SUPPORT);
PriorityHintExit:
Irp->IoStatus.Status = status;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
return status;
}
/*++
ClasspConvertToScsiRequestBlock
Routine Description:
Convert an extended SRB to a SCSI_REQUEST_BLOCK. This function handles only
a single SRB and will not converted SRBs that are linked.
Arguments:
Srb - a pointer to a SCSI_REQUEST_BLOCK
SrbEx - a pointer to an extended SRB
Return Value:
None
--*/
VOID
ClasspConvertToScsiRequestBlock(
_Out_ PSCSI_REQUEST_BLOCK Srb,
_In_ PSTORAGE_REQUEST_BLOCK SrbEx
)
{
PSTOR_ADDR_BTL8 storAddrBtl8;
ULONG i;
BOOLEAN foundEntry = FALSE;
PSRBEX_DATA srbExData;
if ((Srb == NULL) || (SrbEx == NULL)) {
return;
}
RtlZeroMemory(Srb, sizeof(SCSI_REQUEST_BLOCK));
Srb->Length = sizeof(SCSI_REQUEST_BLOCK);
Srb->Function = (UCHAR)SrbEx->SrbFunction;
Srb->SrbStatus = SrbEx->SrbStatus;
Srb->QueueTag = (UCHAR)SrbEx->RequestTag;
Srb->QueueAction = (UCHAR)SrbEx->RequestAttribute;
Srb->SrbFlags = SrbEx->SrbFlags;
Srb->DataTransferLength = SrbEx->DataTransferLength;
Srb->TimeOutValue = SrbEx->TimeOutValue;
Srb->DataBuffer = SrbEx->DataBuffer;
Srb->OriginalRequest = SrbEx->OriginalRequest;
Srb->SrbExtension = SrbEx->MiniportContext;
Srb->InternalStatus = SrbEx->SystemStatus;
//
// Handle address fields
//
if (SrbEx->AddressOffset >= sizeof(STORAGE_REQUEST_BLOCK)) {
storAddrBtl8 = (PSTOR_ADDR_BTL8)((PCHAR)SrbEx + SrbEx->AddressOffset);
if (storAddrBtl8->Type == STOR_ADDRESS_TYPE_BTL8) {
Srb->PathId = storAddrBtl8->Path;
Srb->TargetId = storAddrBtl8->Target;
Srb->Lun = storAddrBtl8->Lun;
} else {
// Catch unsupported address types
NT_ASSERT(FALSE);
}
}
//
// Handle SRB function specific fields
//
if (SrbEx->NumSrbExData > 0) {
for (i = 0; i < SrbEx->NumSrbExData; i++) {
if ((SrbEx->SrbExDataOffset[i] == 0) ||
(SrbEx->SrbExDataOffset[i] < sizeof(STORAGE_REQUEST_BLOCK))) {
// Catch invalid offsets
NT_ASSERT(FALSE);
continue;
}
srbExData = (PSRBEX_DATA)((PCHAR)SrbEx + SrbEx->SrbExDataOffset[i]);
switch (SrbEx->SrbFunction) {
case SRB_FUNCTION_EXECUTE_SCSI:
switch (srbExData->Type) {
case SrbExDataTypeScsiCdb16:
Srb->ScsiStatus = ((PSRBEX_DATA_SCSI_CDB16)srbExData)->ScsiStatus;
Srb->CdbLength = ((PSRBEX_DATA_SCSI_CDB16)srbExData)->CdbLength;
Srb->SenseInfoBufferLength = ((PSRBEX_DATA_SCSI_CDB16)srbExData)->SenseInfoBufferLength;
Srb->SenseInfoBuffer = ((PSRBEX_DATA_SCSI_CDB16)srbExData)->SenseInfoBuffer;
RtlCopyMemory(Srb->Cdb, ((PSRBEX_DATA_SCSI_CDB16)srbExData)->Cdb, sizeof(Srb->Cdb));
foundEntry = TRUE;
break;
case SrbExDataTypeScsiCdb32:
Srb->ScsiStatus = ((PSRBEX_DATA_SCSI_CDB32)srbExData)->ScsiStatus;
Srb->CdbLength = ((PSRBEX_DATA_SCSI_CDB32)srbExData)->CdbLength;
Srb->SenseInfoBufferLength = ((PSRBEX_DATA_SCSI_CDB32)srbExData)->SenseInfoBufferLength;
Srb->SenseInfoBuffer = ((PSRBEX_DATA_SCSI_CDB32)srbExData)->SenseInfoBuffer;
// Copy only the first 16 bytes
RtlCopyMemory(Srb->Cdb, ((PSRBEX_DATA_SCSI_CDB32)srbExData)->Cdb, sizeof(Srb->Cdb));
foundEntry = TRUE;
break;
case SrbExDataTypeScsiCdbVar:
Srb->ScsiStatus = ((PSRBEX_DATA_SCSI_CDB_VAR)srbExData)->ScsiStatus;
Srb->CdbLength = (UCHAR)((PSRBEX_DATA_SCSI_CDB_VAR)srbExData)->CdbLength;
Srb->SenseInfoBufferLength = ((PSRBEX_DATA_SCSI_CDB_VAR)srbExData)->SenseInfoBufferLength;
Srb->SenseInfoBuffer = ((PSRBEX_DATA_SCSI_CDB_VAR)srbExData)->SenseInfoBuffer;
// Copy only the first 16 bytes
RtlCopyMemory(Srb->Cdb, ((PSRBEX_DATA_SCSI_CDB_VAR)srbExData)->Cdb, sizeof(Srb->Cdb));
foundEntry = TRUE;
break;
default:
break;
}
break;
case SRB_FUNCTION_WMI:
if (srbExData->Type == SrbExDataTypeWmi) {
((PSCSI_WMI_REQUEST_BLOCK)Srb)->WMISubFunction = ((PSRBEX_DATA_WMI)srbExData)->WMISubFunction;
((PSCSI_WMI_REQUEST_BLOCK)Srb)->WMIFlags = ((PSRBEX_DATA_WMI)srbExData)->WMIFlags;
((PSCSI_WMI_REQUEST_BLOCK)Srb)->DataPath = ((PSRBEX_DATA_WMI)srbExData)->DataPath;
foundEntry = TRUE;
}
break;
case SRB_FUNCTION_PNP:
if (srbExData->Type == SrbExDataTypePnP) {
((PSCSI_PNP_REQUEST_BLOCK)Srb)->PnPAction = ((PSRBEX_DATA_PNP)srbExData)->PnPAction;
((PSCSI_PNP_REQUEST_BLOCK)Srb)->PnPSubFunction = ((PSRBEX_DATA_PNP)srbExData)->PnPSubFunction;
((PSCSI_PNP_REQUEST_BLOCK)Srb)->SrbPnPFlags = ((PSRBEX_DATA_PNP)srbExData)->SrbPnPFlags;
foundEntry = TRUE;
}
break;
case SRB_FUNCTION_POWER:
if (srbExData->Type == SrbExDataTypePower) {
((PSCSI_POWER_REQUEST_BLOCK)Srb)->DevicePowerState = ((PSRBEX_DATA_POWER)srbExData)->DevicePowerState;
((PSCSI_POWER_REQUEST_BLOCK)Srb)->PowerAction = ((PSRBEX_DATA_POWER)srbExData)->PowerAction;
((PSCSI_POWER_REQUEST_BLOCK)Srb)->SrbPowerFlags = ((PSRBEX_DATA_POWER)srbExData)->SrbPowerFlags;
foundEntry = TRUE;
}
break;
default:
break;
}
//
// Quit on first match
//
if (foundEntry) {
break;
}
}
}
return;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
ClasspGetMaximumTokenListIdentifier(
_In_ PDEVICE_OBJECT DeviceObject,
_In_z_ PWSTR RegistryPath,
_Out_ PULONG MaximumListIdentifier
)
/*++
Routine Description:
This routine returns the maximum ListIdentifier (to be used when building TokenOperation
requests) by querying the value MaximumListIdentifier under the key 'RegistryPath'.
Arguments:
DeviceObject - The device handling the request.
RegistryPath - The absolute registry path under which MaximumListIdentifier resides.
MaximumListIdentifier - Returns the value being queried.
Return Value:
STATUS_SUCCESS or appropriate error status returned by Registry API.
--*/
{
RTL_QUERY_REGISTRY_TABLE queryTable[2];
ULONG value = 0;
NTSTATUS status;
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_PNP,
"ClasspGetMaximumTokenListIdentifier (%p): Entering function.\n",
DeviceObject));
//
// Zero the table entries.
//
RtlZeroMemory(queryTable, sizeof(queryTable));
//
// The query table has two entries. One for the MaximumListIdentifier and
// the second which is the 'NULL' terminator.
//
// Indicate that there is NO call-back routine.
//
queryTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_TYPECHECK;
//
// The value to query.
//
queryTable[0].Name = REG_MAX_LIST_IDENTIFIER_VALUE;
//
// Where to put the value, the type of the value, default value and length.
//
queryTable[0].EntryContext = &value;
queryTable[0].DefaultType = (REG_DWORD << RTL_QUERY_REGISTRY_TYPECHECK_SHIFT) | REG_DWORD;
queryTable[0].DefaultData = &value;
queryTable[0].DefaultLength = sizeof(value);
//
// Try to get the maximum listIdentifier.
//
status = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE,
RegistryPath,
queryTable,
NULL,
NULL);
if (NT_SUCCESS(status)) {
*MaximumListIdentifier = value;
} else {
*MaximumListIdentifier = 0;
}
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_PNP,
"ClasspGetMaximumTokenListIdentifier (%p): Exiting function with status %x (maxListId %u).\n",
DeviceObject,
status,
*MaximumListIdentifier));
return status;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
ClasspGetCopyOffloadMaxDuration(
_In_ PDEVICE_OBJECT DeviceObject,
_In_z_ PWSTR RegistryPath,
_Out_ PULONG MaxDuration
)
/*++
Routine Description:
This routine returns the maximum time (in seconds) that a Copy Offload
operation should take to complete by a target.
Arguments:
DeviceObject - The device handling the request.
RegistryPath - The absolute registry path under which MaxDuration resides.
MaxDuration - Returns the value being queried, in seconds.
Return Value:
STATUS_SUCCESS or appropriate error status returned by Registry API.
--*/
{
RTL_QUERY_REGISTRY_TABLE queryTable[2];
ULONG value = 0;
NTSTATUS status;
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_PNP,
"ClasspGetCopyOffloadMaxDuration (%p): Entering function.\n",
DeviceObject));
//
// Zero the table entries.
//
RtlZeroMemory(queryTable, sizeof(queryTable));
//
// The query table has two entries. One for CopyOffloadMaxDuration and
// the second which is the 'NULL' terminator.
//
// Indicate that there is NO call-back routine.
//
queryTable[0].Flags = RTL_QUERY_REGISTRY_DIRECT | RTL_QUERY_REGISTRY_TYPECHECK;
//
// The value to query.
//
queryTable[0].Name = CLASSP_REG_COPY_OFFLOAD_MAX_TARGET_DURATION;
//
// Where to put the value, the type of the value, default value and length.
//
queryTable[0].EntryContext = &value;
queryTable[0].DefaultType = (REG_DWORD << RTL_QUERY_REGISTRY_TYPECHECK_SHIFT) | REG_NONE;
queryTable[0].DefaultData = &value;
queryTable[0].DefaultLength = sizeof(value);
//
// Try to get the max target duration.
//
status = RtlQueryRegistryValues(RTL_REGISTRY_ABSOLUTE,
RegistryPath,
queryTable,
NULL,
NULL);
//
// Don't allow the user to set the value to lower than the default (4s) so
// they don't break ODX functionality if they accidentally set it too low.
//
if (NT_SUCCESS(status) &&
value > DEFAULT_MAX_TARGET_DURATION) {
*MaxDuration = value;
} else {
*MaxDuration = DEFAULT_MAX_TARGET_DURATION;
}
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_PNP,
"ClasspGetCopyOffloadMaxDuration (%p): Exiting function with status %x (Max Duration %u seconds).\n",
DeviceObject,
status,
*MaxDuration));
return status;
}
_IRQL_requires_max_(APC_LEVEL)
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_same_
NTSTATUS
ClasspDeviceCopyOffloadProperty(
_In_ PDEVICE_OBJECT DeviceObject,
_Inout_ PIRP Irp,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
/*++
Routine Description:
This routine returns the copy offload parameters associated with the device.
This function must be called at IRQL < DISPATCH_LEVEL.
Arguments:
DeviceObject - Supplies the device object associated with this request
Irp - The IRP to be processed
Srb - The SRB associated with the request
Return Value:
NTSTATUS code
--*/
{
NTSTATUS status;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
PSTORAGE_PROPERTY_QUERY query;
PIO_STACK_LOCATION irpStack;
ULONG length;
ULONG information;
PDEVICE_COPY_OFFLOAD_DESCRIPTOR copyOffloadDescr = (PDEVICE_COPY_OFFLOAD_DESCRIPTOR)Irp->AssociatedIrp.SystemBuffer;
UNREFERENCED_PARAMETER(Srb);
PAGED_CODE();
fdoExtension = DeviceObject->DeviceExtension;
query = (PSTORAGE_PROPERTY_QUERY)Irp->AssociatedIrp.SystemBuffer;
irpStack = IoGetCurrentIrpStackLocation(Irp);
length = 0;
information = 0;
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspDeviceCopyOffloadProperty (%p): Entering function.\n",
DeviceObject));
//
// Check proper query type.
//
if (query->QueryType == PropertyExistsQuery) {
//
// In order to maintain consistency with the how the rest of the properties
// are handled, we shall always return success for PropertyExistsQuery.
//
status = STATUS_SUCCESS;
goto __ClasspDeviceCopyOffloadProperty_Exit;
} else if (query->QueryType != PropertyStandardQuery) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceCopyOffloadProperty (%p): Unsupported query type %x for Copy Offload property.\n",
DeviceObject,
query->QueryType));
status = STATUS_NOT_SUPPORTED;
goto __ClasspDeviceCopyOffloadProperty_Exit;
}
//
// Request validation.
// Note that InputBufferLength and IsFdo have been validated beforing entering this routine.
//
if (KeGetCurrentIrql() >= DISPATCH_LEVEL) {
NT_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceCopyOffloadProperty (%p): Query property for Copy Offload called at incorrect IRQL.\n",
DeviceObject));
status = STATUS_INVALID_LEVEL;
goto __ClasspDeviceCopyOffloadProperty_Exit;
}
length = irpStack->Parameters.DeviceIoControl.OutputBufferLength;
if (length < sizeof(DEVICE_COPY_OFFLOAD_DESCRIPTOR)) {
if (length >= sizeof(STORAGE_DESCRIPTOR_HEADER)) {
TracePrint((TRACE_LEVEL_WARNING,
TRACE_FLAG_IOCTL,
"ClasspDeviceCopyOffloadProperty (%p): Length %u specified for Copy Offload property enough only for header.\n",
DeviceObject,
length));
information = sizeof(STORAGE_DESCRIPTOR_HEADER);
copyOffloadDescr->Version = sizeof(DEVICE_COPY_OFFLOAD_DESCRIPTOR);
copyOffloadDescr->Size = sizeof(DEVICE_COPY_OFFLOAD_DESCRIPTOR);
status = STATUS_SUCCESS;
goto __ClasspDeviceCopyOffloadProperty_Exit;
}
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceCopyOffloadProperty (%p): Incorrect length %u specified for Copy Offload property.\n",
DeviceObject,
length));
status = STATUS_BUFFER_TOO_SMALL;
goto __ClasspDeviceCopyOffloadProperty_Exit;
}
if (!fdoExtension->FunctionSupportInfo->ValidInquiryPages.BlockDeviceRODLimits) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceCopyOffloadProperty (%p): Command not supported on this device.\n",
DeviceObject));
status = STATUS_DEVICE_FEATURE_NOT_SUPPORTED;
goto __ClasspDeviceCopyOffloadProperty_Exit;
}
if (!NT_SUCCESS(fdoExtension->FunctionSupportInfo->BlockDeviceRODLimitsData.CommandStatus)) {
status = fdoExtension->FunctionSupportInfo->BlockDeviceRODLimitsData.CommandStatus;
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspDeviceCopyOffloadProperty (%p): VPD retrieval had failed with %x.\n",
DeviceObject,
status));
goto __ClasspDeviceCopyOffloadProperty_Exit;
}
//
// Fill in the output buffer. All data is copied from the FDO extension where we
// cached Block Limits and Block Device Token Limits info when the device was first initialized.
//
RtlZeroMemory(copyOffloadDescr, length);
copyOffloadDescr->Version = 1;
copyOffloadDescr->Size = sizeof(DEVICE_COPY_OFFLOAD_DESCRIPTOR);
copyOffloadDescr->MaximumTokenLifetime = fdoExtension->FunctionSupportInfo->BlockDeviceRODLimitsData.MaximumInactivityTimer;
copyOffloadDescr->DefaultTokenLifetime = fdoExtension->FunctionSupportInfo->BlockDeviceRODLimitsData.DefaultInactivityTimer;
copyOffloadDescr->MaximumTransferSize = fdoExtension->FunctionSupportInfo->BlockDeviceRODLimitsData.MaximumTokenTransferSize;
copyOffloadDescr->OptimalTransferCount = fdoExtension->FunctionSupportInfo->BlockDeviceRODLimitsData.OptimalTransferCount;
copyOffloadDescr->MaximumDataDescriptors = fdoExtension->FunctionSupportInfo->BlockDeviceRODLimitsData.MaximumRangeDescriptors;
if (NT_SUCCESS(fdoExtension->FunctionSupportInfo->BlockLimitsData.CommandStatus)) {
copyOffloadDescr->MaximumTransferLengthPerDescriptor = fdoExtension->FunctionSupportInfo->BlockLimitsData.MaximumTransferLength;
copyOffloadDescr->OptimalTransferLengthPerDescriptor = fdoExtension->FunctionSupportInfo->BlockLimitsData.OptimalTransferLength;
copyOffloadDescr->OptimalTransferLengthGranularity = fdoExtension->FunctionSupportInfo->BlockLimitsData.OptimalTransferLengthGranularity;
}
information = sizeof(DEVICE_COPY_OFFLOAD_DESCRIPTOR);
status = STATUS_SUCCESS;
__ClasspDeviceCopyOffloadProperty_Exit:
//
// Set the size and status in IRP
//
Irp->IoStatus.Information = information;
Irp->IoStatus.Status = status;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspDeviceCopyOffloadProperty (%p): Exiting function with status %x.\n",
DeviceObject,
status));
return status;
}
_IRQL_requires_max_(APC_LEVEL)
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_same_
NTSTATUS
ClasspValidateOffloadSupported(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ PIRP Irp
)
/*++
Routine Description:
This routine validates if this device supports offload requests.
This function must be called at IRQL < DISPATCH_LEVEL.
Arguments:
DeviceObject - Supplies the device object associated with this request
Irp - The IRP to be processed
Return Value:
NTSTATUS code
--*/
{
PFUNCTIONAL_DEVICE_EXTENSION fdoExt;
NTSTATUS status;
PAGED_CODE();
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadSupported (%p): Entering function. Irp %p\n",
DeviceObject,
Irp));
fdoExt = DeviceObject->DeviceExtension;
status = STATUS_SUCCESS;
//
// For now this command is only supported by disk devices
//
if ((DeviceObject->DeviceType == FILE_DEVICE_DISK) &&
(!TEST_FLAG(DeviceObject->Characteristics, FILE_FLOPPY_DISKETTE))) {
if (!fdoExt->FunctionSupportInfo->ValidInquiryPages.BlockDeviceRODLimits) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadSupported (%p): Command not supported on this disk device.\n",
DeviceObject));
status = STATUS_DEVICE_FEATURE_NOT_SUPPORTED;
goto __ClasspValidateOffloadSupported_Exit;
}
if (!NT_SUCCESS(fdoExt->FunctionSupportInfo->BlockDeviceRODLimitsData.CommandStatus)) {
status = fdoExt->FunctionSupportInfo->BlockDeviceRODLimitsData.CommandStatus;
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadSupported (%p): VPD retrieval failed with %x.\n",
DeviceObject,
status));
goto __ClasspValidateOffloadSupported_Exit;
}
} else {
TracePrint((TRACE_LEVEL_WARNING,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadSupported (%p): Suported only on Disk devices.\n",
DeviceObject));
status = STATUS_DEVICE_FEATURE_NOT_SUPPORTED;
goto __ClasspValidateOffloadSupported_Exit;
}
__ClasspValidateOffloadSupported_Exit:
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadSupported (%p): Exiting function Irp %p with status %x.\n",
DeviceObject,
Irp,
status));
return status;
}
_IRQL_requires_max_(APC_LEVEL)
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_same_
NTSTATUS
ClasspValidateOffloadInputParameters(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ PIRP Irp
)
/*++
Routine Description:
This routine does some basic validation of the input parameters of the offload request.
This function must be called at IRQL < DISPATCH_LEVEL.
Arguments:
DeviceObject - Supplies the device object associated with this request
Irp - The IRP to be processed
Return Value:
NTSTATUS code
--*/
{
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
PIO_STACK_LOCATION irpStack;
PDEVICE_MANAGE_DATA_SET_ATTRIBUTES dsmAttributes;
PDEVICE_DATA_SET_RANGE dataSetRanges;
ULONG dataSetRangesCount;
ULONG i;
NTSTATUS status;
PAGED_CODE();
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadInputParameters (%p): Entering function Irp %p.\n",
DeviceObject,
Irp));
fdoExtension = DeviceObject->DeviceExtension;
irpStack = IoGetCurrentIrpStackLocation (Irp);
dsmAttributes = Irp->AssociatedIrp.SystemBuffer;
status = STATUS_SUCCESS;
if (!dsmAttributes) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadInputParameters (%p): NULL DsmAttributes passed in.\n",
DeviceObject));
status = STATUS_INVALID_PARAMETER;
goto __ClasspValidateOffloadInputParameters_Exit;
}
if ((irpStack->Parameters.DeviceIoControl.InputBufferLength < sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES)) ||
(irpStack->Parameters.DeviceIoControl.InputBufferLength <
(sizeof(DEVICE_MANAGE_DATA_SET_ATTRIBUTES) + dsmAttributes->ParameterBlockLength + dsmAttributes->DataSetRangesLength))) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadInputParameters (%p): Input buffer size (%u) too small.\n",
DeviceObject,
irpStack->Parameters.DeviceIoControl.InputBufferLength));
status = STATUS_INVALID_PARAMETER;
goto __ClasspValidateOffloadInputParameters_Exit;
}
if ((dsmAttributes->DataSetRangesOffset == 0) ||
(dsmAttributes->DataSetRangesLength == 0)) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadInputParameters (%p): Incorrect DataSetRanges [offset %u, length %u].\n",
DeviceObject,
dsmAttributes->DataSetRangesOffset,
dsmAttributes->DataSetRangesLength));
status = STATUS_INVALID_PARAMETER;
goto __ClasspValidateOffloadInputParameters_Exit;
}
dataSetRanges = Add2Ptr(dsmAttributes, dsmAttributes->DataSetRangesOffset);
dataSetRangesCount = dsmAttributes->DataSetRangesLength / sizeof(DEVICE_DATA_SET_RANGE);
if (dataSetRangesCount == 0) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadInputParameters (%p): DataSetRanges specifies no extents.\n",
DeviceObject));
status = STATUS_INVALID_PARAMETER;
goto __ClasspValidateOffloadInputParameters_Exit;
}
//
// Some third party disk class drivers do not query the geometry at initialization time,
// so this information may not be available at this time. If that is the case, we'll
// first query that information before proceeding with the rest of our validations.
//
if (fdoExtension->DiskGeometry.BytesPerSector == 0) {
status = ClassReadDriveCapacity(fdoExtension->DeviceObject);
if ((!NT_SUCCESS(status)) || (fdoExtension->DiskGeometry.BytesPerSector == 0)) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadInputParameters (%p): Couldn't retrieve disk geometry, status: %x, bytes/sector: %u.\n",
DeviceObject,
status,
fdoExtension->DiskGeometry.BytesPerSector));
status = STATUS_INVALID_PARAMETER;
goto __ClasspValidateOffloadInputParameters_Exit;
}
}
//
// Data must be aligned to sector boundary and
// LengthInBytes must be > 0 for it to be a valid LBA entry
//
for (i = 0; i < dataSetRangesCount; i++) {
if ((dataSetRanges[i].StartingOffset % fdoExtension->DiskGeometry.BytesPerSector != 0) ||
(dataSetRanges[i].LengthInBytes % fdoExtension->DiskGeometry.BytesPerSector != 0) ||
(dataSetRanges[i].LengthInBytes == 0) ) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadInputParameters (%p): Incorrect DataSetRanges entry %u [offset %I64x, length %I64x].\n",
DeviceObject,
i,
dataSetRanges[i].StartingOffset,
dataSetRanges[i].LengthInBytes));
status = STATUS_INVALID_PARAMETER;
goto __ClasspValidateOffloadInputParameters_Exit;
}
if ((ULONGLONG)dataSetRanges[i].StartingOffset + dataSetRanges[i].LengthInBytes > (ULONGLONG)fdoExtension->CommonExtension.PartitionLength.QuadPart) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadInputParameters (%p): Error! DataSetRange %u (starting LBA %I64x) specified length %I64x exceeds the medium's capacity (%I64x).\n",
DeviceObject,
i,
dataSetRanges[i].StartingOffset,
dataSetRanges[i].LengthInBytes,
fdoExtension->CommonExtension.PartitionLength.QuadPart));
status = STATUS_NONEXISTENT_SECTOR;
goto __ClasspValidateOffloadInputParameters_Exit;
}
}
__ClasspValidateOffloadInputParameters_Exit:
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspValidateOffloadInputParameters (%p): Exiting function Irp %p with status %x.\n",
DeviceObject,
Irp,
status));
return status;
}
_IRQL_requires_same_
NTSTATUS
ClasspGetTokenOperationCommandBufferLength(
_In_ PDEVICE_OBJECT Fdo,
_In_ ULONG ServiceAction,
_Inout_ PULONG CommandBufferLength,
_Out_opt_ PULONG TokenOperationBufferLength,
_Out_opt_ PULONG ReceiveTokenInformationBufferLength
)
/*++
Routine description:
This routine calculates the buffer length required to service a TokenOperation and its
corresponding ReceiveTokenInformation command.
Arguments:
Fdo - The functional device object processing the PopulateToken/WriteUsingToken request
ServiceAction - Used to distinguish between a PopulateToken and a WriteUsingToken operation
CommandBufferLength - Returns the length of the buffer needed to service the token request (i.e. TokenOperation and its corresponding ReceiveTokenInformation command)
TokenOperationBufferLength - Optional parameter, which returns the length of the buffer needed to service just the TokenOperation command.
ReceiveTokenInformationBufferLength - Optional parameter, which returns the length of the buffer needed to service just the ReceiveTokenInformation command.
Return Value:
STATUS_SUCCESS
--*/
{
PFUNCTIONAL_DEVICE_EXTENSION fdoExt = Fdo->DeviceExtension;
PCLASS_PRIVATE_FDO_DATA fdoData = fdoExt->PrivateFdoData;
ULONG tokenOperationBufferLength;
ULONG receiveTokenInformationBufferLength;
PCOMMON_DEVICE_EXTENSION commonExtension = Fdo->DeviceExtension;
PSTORAGE_ADAPTER_DESCRIPTOR adapterDesc = commonExtension->PartitionZeroExtension->AdapterDescriptor;
ULONG hwMaxXferLen;
ULONG bufferLength = 0;
ULONG tokenOperationHeaderSize;
ULONG responseSize;
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspGetTokenOperationCommandBufferLengths (%p): Entering function.\n",
Fdo));
NT_ASSERT(fdoExt->FunctionSupportInfo->ValidInquiryPages.BlockDeviceRODLimits &&
NT_SUCCESS(fdoExt->FunctionSupportInfo->BlockDeviceRODLimitsData.CommandStatus));
if (ServiceAction == SERVICE_ACTION_POPULATE_TOKEN) {
tokenOperationHeaderSize = FIELD_OFFSET(POPULATE_TOKEN_HEADER, BlockDeviceRangeDescriptor);
responseSize = FIELD_OFFSET(RECEIVE_TOKEN_INFORMATION_RESPONSE_HEADER, TokenDescriptor) + sizeof(BLOCK_DEVICE_TOKEN_DESCRIPTOR);
} else {
tokenOperationHeaderSize = FIELD_OFFSET(WRITE_USING_TOKEN_HEADER, BlockDeviceRangeDescriptor);
responseSize = 0;
}
//
// The TokenOperation command can specify a parameter length of max 2^16.
// If the device has a max limit on the number of range descriptors that can be specified in
// the TokenOperation command, we are limited to the lesser of these two values.
//
if (fdoExt->FunctionSupportInfo->BlockDeviceRODLimitsData.MaximumRangeDescriptors == 0) {
tokenOperationBufferLength = MAX_TOKEN_OPERATION_PARAMETER_DATA_LENGTH;
} else {
tokenOperationBufferLength = MIN(tokenOperationHeaderSize + fdoExt->FunctionSupportInfo->BlockDeviceRODLimitsData.MaximumRangeDescriptors * sizeof(BLOCK_DEVICE_RANGE_DESCRIPTOR),
MAX_TOKEN_OPERATION_PARAMETER_DATA_LENGTH);
}
//
// The ReceiveTokenInformation command can specify a parameter length of max 2 ^ 32
// Also, since the sense data can be of variable size, we'll use MAX_SENSE_BUFFER_SIZE.
//
receiveTokenInformationBufferLength = MIN(FIELD_OFFSET(RECEIVE_TOKEN_INFORMATION_HEADER, SenseData) + MAX_SENSE_BUFFER_SIZE + responseSize,
MAX_RECEIVE_TOKEN_INFORMATION_PARAMETER_DATA_LENGTH);
//
// Since we're going to reuse the buffer for both the TokenOperation and the ReceiveTokenInformation
// commands, the buffer length needs to handle both operations.
//
bufferLength = MAX(tokenOperationBufferLength, receiveTokenInformationBufferLength);
//
// The buffer length needs to be further limited to the adapter's capability though.
//
hwMaxXferLen = MIN(fdoData->HwMaxXferLen, adapterDesc->MaximumTransferLength);
bufferLength = MIN(bufferLength, hwMaxXferLen);
*CommandBufferLength = bufferLength;
if (TokenOperationBufferLength) {
*TokenOperationBufferLength = tokenOperationBufferLength;
}
if (ReceiveTokenInformationBufferLength) {
*ReceiveTokenInformationBufferLength = receiveTokenInformationBufferLength;
}
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspGetTokenOperationCommandBufferLengths (%p): Exiting function with bufferLength %u (tokenOpBufLen %u, recTokenInfoBufLen %u).\n",
Fdo,
bufferLength,
tokenOperationBufferLength,
receiveTokenInformationBufferLength));
return STATUS_SUCCESS;
}
_IRQL_requires_same_
NTSTATUS
ClasspGetTokenOperationDescriptorLimits(
_In_ PDEVICE_OBJECT Fdo,
_In_ ULONG ServiceAction,
_In_ ULONG MaxParameterBufferLength,
_Out_ PULONG MaxBlockDescriptorsCount,
_Out_ PULONGLONG MaxBlockDescriptorsLength
)
/*++
Routine description:
This routine calculates the maximum block descriptors and the maximum token transfer size
that can be accomodated in a single TokenOperation command.
Arguments:
Fdo - The functional device object processing the PopulateToken/WriteUsingToken request
ServiceAction - Used to distinguish between a PopulateToken and a WriteUsingToken operation
MaxParameterBufferLength - The length constraint of the entire buffer for the parameter list based on other limitations (e.g. adapter max transfer length)
MaxBlockDescriptorsCount - Returns the maximum number of the block range descriptors that can be passed in a single TokenOperation command.
MaxBlockDescriptorsLength - Returns the maximum cumulative number of blocks across all the descriptors that must not be exceeded in a single TokenOperation command.
Return Value:
STATUS_SUCCESS
--*/
{
PFUNCTIONAL_DEVICE_EXTENSION fdoExt = Fdo->DeviceExtension;
ULONG tokenOperationHeaderSize = (ServiceAction == SERVICE_ACTION_POPULATE_TOKEN) ?
FIELD_OFFSET(POPULATE_TOKEN_HEADER, BlockDeviceRangeDescriptor) :
FIELD_OFFSET(WRITE_USING_TOKEN_HEADER, BlockDeviceRangeDescriptor);
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspGetTokenOperationDescriptorLimits (%p): Entering function.\n",
Fdo));
NT_ASSERT(fdoExt->FunctionSupportInfo->ValidInquiryPages.BlockDeviceRODLimits &&
NT_SUCCESS(fdoExt->FunctionSupportInfo->BlockDeviceRODLimitsData.CommandStatus));
*MaxBlockDescriptorsCount = (MaxParameterBufferLength - tokenOperationHeaderSize) / sizeof(BLOCK_DEVICE_RANGE_DESCRIPTOR);
*MaxBlockDescriptorsLength = (fdoExt->FunctionSupportInfo->BlockDeviceRODLimitsData.MaximumTokenTransferSize == 0) ?
MAX_TOKEN_TRANSFER_SIZE : fdoExt->FunctionSupportInfo->BlockDeviceRODLimitsData.MaximumTokenTransferSize;
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspGetTokenOperationDescriptorLimits (%p): Exiting function with MaxDescr %u, MaxXferBlocks %I64u.\n",
Fdo,
*MaxBlockDescriptorsCount,
*MaxBlockDescriptorsLength));
return STATUS_SUCCESS;
}
_IRQL_requires_max_(APC_LEVEL)
_IRQL_requires_min_(PASSIVE_LEVEL)
_IRQL_requires_same_
VOID
ClasspConvertDataSetRangeToBlockDescr(
_In_ PDEVICE_OBJECT Fdo,
_In_ PVOID BlockDescr,
_Inout_ PULONG CurrentBlockDescrIndex,
_In_ ULONG MaxBlockDescrCount,
_Inout_ PULONG CurrentLbaCount,
_In_ ULONGLONG MaxLbaCount,
_Inout_ PDEVICE_DATA_SET_RANGE DataSetRange,
_Inout_ PULONGLONG TotalSectorsProcessed
)
/*++
Routine Description:
Convert DEVICE_DATA_SET_RANGE entry to be WINDOWS_BLOCK_DEVICE_RANGE_DESCRIPTOR entries.
As LengthInBytes field in DEVICE_DATA_SET_RANGE structure is 64 bits (bytes)
and LbaCount field in WINDOWS_BLOCK_DEVICE_RANGE_DESCRIPTOR structure is 32 bits (sectors),
it's possible that one DEVICE_DATA_SET_RANGE entry needs multiple
WINDOWS_BLOCK_DEVICE_RANGE_DESCRIPTOR entries. This routine handles the need for that
potential split.
Arguments:
Fdo - The functional device object
BlockDescr - Pointer to the start of the Token Operation command's block descriptor
CurrentBlockDescrIndex - Index into the block descriptor at which to update the DataSetRange info
It also gets updated to return the index to the next empty one.
MaxBlockDescrCount - Maximum number of block descriptors that the device can handle in a single TokenOperation command
CurrentLbaCount - Returns the LBA of the last successfully processed DataSetRange
MaxLbaCount - Maximum transfer size that the device is capable of handling in a single TokenOperation command
DataSetRange - Contains information about one range extent that needs to be converted into a block descriptor
TotalSectorsProcessed - Returns the number of sectors corresponding to the DataSetRange that were succesfully mapped into block descriptors
Return Value:
Nothing.
NOTE: if LengthInBytes does not reach to 0, the conversion for DEVICE_DATA_SET_RANGE entry
is not completed. Further conversion is needed by calling this function again.
--*/
{
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
PBLOCK_DEVICE_RANGE_DESCRIPTOR blockDescr;
ULONGLONG startingSector;
ULONGLONG sectorCount;
ULONGLONG totalSectorCount;
ULONGLONG numberOfOptimalChunks;
USHORT optimalLbaPerDescrGranularity;
ULONG optimalLbaPerDescr;
ULONG maxLbaPerDescr;
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspConvertDataSetRangeToBlockDescr (%p): Entering function. Starting offset %I64x.\n",
Fdo,
DataSetRange->StartingOffset));
fdoExtension = Fdo->DeviceExtension;
blockDescr = (PBLOCK_DEVICE_RANGE_DESCRIPTOR)BlockDescr;
totalSectorCount = 0;
//
// Since the OptimalTransferLength and the MaximumTransferLength are overloaded parameters for
// offloaded data transfers and regular read/write requests, it is not safe to use these values
// as they may report back what is used by regular read/write, which will cause a perf degradation
// in the offloaded case, since we may end up limiting the per block range descriptor length
// specified as opposed to what the target can actually handle in a single request.
// So until the SPC spec introduces these values specific to offloaded data transfers, we shall
// ignore them completely. The expectation we have from the target is as follows:
// 1. If the length specified in any of the block range descriptors is greater than the OTL that
// applies to ODX, the target will internally split into additional descriptors.
// 2. If the above causes it to run out of descriptors, or if the length specified in any of the
// descriptors is greater than the MTL that applies to ODX, the target will operate on as much
// data as possible and truncate the request to that point.
//
optimalLbaPerDescrGranularity = 0;
optimalLbaPerDescr = 0;
maxLbaPerDescr = 0;
if (optimalLbaPerDescr && maxLbaPerDescr) {
NT_ASSERT(optimalLbaPerDescr <= maxLbaPerDescr);
}
while ((DataSetRange->LengthInBytes > 0) &&
(*CurrentBlockDescrIndex < MaxBlockDescrCount) &&
(*CurrentLbaCount < MaxLbaCount)) {
startingSector = (ULONGLONG)(DataSetRange->StartingOffset / fdoExtension->DiskGeometry.BytesPerSector);
//
// Since the block descriptor has only 4 bytes for the number of logical blocks, we are
// constrained by that theoretical maximum.
//
sectorCount = MIN(DataSetRange->LengthInBytes / fdoExtension->DiskGeometry.BytesPerSector,
MAX_NUMBER_BLOCKS_PER_BLOCK_DEVICE_RANGE_DESCRIPTOR);
//
// We are constrained by MaxLbaCount.
//
if (((ULONGLONG)*CurrentLbaCount + sectorCount) >= MaxLbaCount) {
sectorCount = MaxLbaCount - *CurrentLbaCount;
}
//
// For each descriptor, the block count should be lesser than the MaximumTransferSize
//
if (maxLbaPerDescr > 0) {
//
// Each block device range descriptor can specify a max number of LBAs
//
sectorCount = MIN(sectorCount, maxLbaPerDescr);
}
//
// If the number of LBAs specified in the descriptor is greater than the OptimalTransferLength,
// processing of this descriptor by the target may incur a significant delay.
// So in order to allow the target to perform optimally, we'll further limit the number
// of blocks specified in any descriptor to be maximum OptimalTranferLength.
//
if (optimalLbaPerDescr > 0) {
sectorCount = MIN(sectorCount, optimalLbaPerDescr);
}
//
// In addition, it should either be an exact multiple of the OptimalTransferLengthGranularity,
// or be lesser than the OptimalTransferLengthGranularity (taken care of here).
//
if (optimalLbaPerDescrGranularity > 0) {
numberOfOptimalChunks = sectorCount / optimalLbaPerDescrGranularity;
if (numberOfOptimalChunks > 0) {
sectorCount = numberOfOptimalChunks * optimalLbaPerDescrGranularity;
}
}
NT_ASSERT(sectorCount <= MAX_NUMBER_BLOCKS_PER_BLOCK_DEVICE_RANGE_DESCRIPTOR);
REVERSE_BYTES_QUAD(blockDescr[*CurrentBlockDescrIndex].LogicalBlockAddress, &startingSector);
REVERSE_BYTES(blockDescr[*CurrentBlockDescrIndex].TransferLength, §orCount);
totalSectorCount += sectorCount;
DataSetRange->StartingOffset += sectorCount * fdoExtension->DiskGeometry.BytesPerSector;
DataSetRange->LengthInBytes -= sectorCount * fdoExtension->DiskGeometry.BytesPerSector;
*CurrentBlockDescrIndex += 1;
*CurrentLbaCount += (ULONG)sectorCount;
TracePrint((TRACE_LEVEL_INFORMATION,
TRACE_FLAG_IOCTL,
"ClasspConvertDataSetRangeToBlockDescr (%p): Descriptor: %u, starting LBA: %I64x, length: %I64x bytes, media size: %I64x.\n",
Fdo,
*CurrentBlockDescrIndex - 1,
startingSector,
sectorCount * fdoExtension->DiskGeometry.BytesPerSector,
(ULONGLONG)fdoExtension->CommonExtension.PartitionLength.QuadPart));
}
*TotalSectorsProcessed = totalSectorCount;
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspConvertDataSetRangeToBlockDescr (%p): Exiting function (starting offset %I64x). Total sectors processed %I64u.\n",
Fdo,
DataSetRange->StartingOffset,
totalSectorCount));
return;
}
_IRQL_requires_same_
PUCHAR
ClasspBinaryToAscii(
_In_reads_(Length) PUCHAR HexBuffer,
_In_ ULONG Length,
_Inout_ PULONG UpdateLength
)
/*++
Routine Description:
This routine will convert HexBuffer into an ascii NULL-terminated string.
Note: This routine will allocate memory for storing the ascii string. It is
the responsibility of the caller to free this buffer.
Arguments:
HexBuffer - Pointer to the binary data.
Length - Length, in bytes, of HexBuffer.
UpdateLength - Storage to place the actual length of the returned string.
Return Value:
ASCII string equivalent of the hex buffer, or NULL if an error occurred.
--*/
{
static const UCHAR integerTable[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
ULONG i;
ULONG j;
ULONG actualLength;
PUCHAR buffer = NULL;
UCHAR highWord;
UCHAR lowWord;
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspBinaryToAscii (HexBuff %p): Entering function.\n",
HexBuffer));
if (!HexBuffer || Length == 0) {
*UpdateLength = 0;
goto __ClasspBinaryToAscii_Exit;
}
//
// Each byte converts into 2 chars:
// e.g. 0x05 => '0' '5'
// 0x0C => '0' 'C'
// 0x12 => '1' '2'
// And we need a terminating NULL for the string.
//
actualLength = (Length * 2) + 1;
//
// Allocate the buffer.
//
buffer = ExAllocatePoolZero(NonPagedPoolNx,
actualLength,
CLASSPNP_POOL_TAG_TOKEN_OPERATION);
if (!buffer) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspBinaryToAscii (HexBuff %p): Failed to allocate buffer for ASCII equivalent.\n",
HexBuffer));
*UpdateLength = 0;
goto __ClasspBinaryToAscii_Exit;
}
for (i = 0, j = 0; i < Length; i++) {
//
// Split out each nibble from the binary byte.
//
highWord = HexBuffer[i] >> 4;
lowWord = HexBuffer[i] & 0x0F;
//
// Using the lookup table, convert and stuff into
// the ascii buffer.
//
buffer[j++] = integerTable[highWord];
#pragma warning(suppress: 6386) // PREFast bug means it doesn't see that Length < actualLength
buffer[j++] = integerTable[lowWord];
}
//
// Update the caller's length field.
//
*UpdateLength = actualLength;
__ClasspBinaryToAscii_Exit:
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspBinaryToAscii (HexBuff %p): Exiting function with buffer %s.\n",
HexBuffer,
(buffer == NULL) ? "" : (const char*)buffer));
return buffer;
}
_IRQL_requires_same_
NTSTATUS
ClasspStorageEventNotification(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ PIRP Irp
)
/*++
Routine Description:
This routine handles an asynchronous event notification (most likely from
port drivers). Currently, we only care about media status change events.
Arguments:
DeviceObject - Supplies the device object associated with this request
Irp - The IRP to be processed
Return Value:
NTSTATUS code
--*/
{
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension;
PIO_STACK_LOCATION irpStack;
PSTORAGE_EVENT_NOTIFICATION storageEvents;
NTSTATUS status;
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspStorageEventNotification (%p): Entering function Irp %p.\n",
DeviceObject,
Irp));
fdoExtension = DeviceObject->DeviceExtension;
irpStack = IoGetCurrentIrpStackLocation (Irp);
storageEvents = Irp->AssociatedIrp.SystemBuffer;
status = STATUS_SUCCESS;
if (!storageEvents) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspStorageEventNotification (%p): NULL storage events passed in.\n",
DeviceObject));
status = STATUS_INVALID_PARAMETER;
goto __ClasspStorageEventNotification_Exit;
}
if (irpStack->Parameters.DeviceIoControl.InputBufferLength < sizeof(STORAGE_EVENT_NOTIFICATION)) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspStorageEventNotification (%p): Input buffer size (%u) too small.\n",
DeviceObject,
irpStack->Parameters.DeviceIoControl.InputBufferLength));
status = STATUS_INFO_LENGTH_MISMATCH;
goto __ClasspStorageEventNotification_Exit;
}
if ((storageEvents->Version != STORAGE_EVENT_NOTIFICATION_VERSION_V1) ||
(storageEvents->Size != sizeof(STORAGE_EVENT_NOTIFICATION))) {
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_IOCTL,
"ClasspStorageEventNotification (%p): Invalid version/size [version %u, size %u].\n",
DeviceObject,
storageEvents->Version,
storageEvents->Size));
status = STATUS_INVALID_PARAMETER;
goto __ClasspStorageEventNotification_Exit;
}
//
// Handle a media status event.
//
if (storageEvents->Events & STORAGE_EVENT_MEDIA_STATUS) {
//
// Only initiate operation if underlying port driver supports asynchronous notification
// and this is the FDO.
//
if ((fdoExtension->CommonExtension.IsFdo == TRUE) &&
(fdoExtension->FunctionSupportInfo->AsynchronousNotificationSupported)) {
ClassCheckMediaState(fdoExtension);
} else {
status = STATUS_NOT_SUPPORTED;
}
}
__ClasspStorageEventNotification_Exit:
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_IOCTL,
"ClasspStorageEventNotification (%p): Exiting function Irp %p with status %x.\n",
DeviceObject,
Irp,
status));
Irp->IoStatus.Information = 0;
Irp->IoStatus.Status = status;
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
return status;
}
VOID
ClasspZeroQERR(
_In_ PDEVICE_OBJECT DeviceObject
)
/*++
Routine Description:
This routine will attempt to set the QERR bit of the mode Control page to
zero.
Arguments:
DeviceObject - Supplies the device object associated with this request
Return Value:
None
--*/
{
PMODE_PARAMETER_HEADER modeData = NULL;
PMODE_CONTROL_PAGE pageData = NULL;
ULONG size = 0;
modeData = ExAllocatePoolZero(NonPagedPoolNxCacheAligned,
MODE_PAGE_DATA_SIZE,
CLASS_TAG_MODE_DATA);
if (modeData == NULL) {
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_SCSI, "ClasspZeroQERR: Unable to allocate mode data buffer\n"));
goto ClasspZeroQERR_Exit;
}
size = ClassModeSense(DeviceObject,
(PCHAR) modeData,
MODE_PAGE_DATA_SIZE,
MODE_PAGE_CONTROL);
if (size < sizeof(MODE_PARAMETER_HEADER)) {
//
// Retry the request in case of a check condition.
//
size = ClassModeSense(DeviceObject,
(PCHAR) modeData,
MODE_PAGE_DATA_SIZE,
MODE_PAGE_CONTROL);
if (size < sizeof(MODE_PARAMETER_HEADER)) {
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_SCSI, "ClasspZeroQERR: Mode Sense failed\n"));
goto ClasspZeroQERR_Exit;
}
}
//
// If the size is greater than size indicated by the mode data reset
// the data to the mode data.
//
if (size > (ULONG) (modeData->ModeDataLength + 1)) {
size = modeData->ModeDataLength + 1;
}
//
// Look for control page in the returned mode page data.
//
pageData = ClassFindModePage((PCHAR) modeData,
size,
MODE_PAGE_CONTROL,
TRUE);
if (pageData) {
TracePrint((TRACE_LEVEL_VERBOSE,
TRACE_FLAG_SCSI,
"ClasspZeroQERR (%p): Current settings: QERR = %u, TST = %u, TAS = %u.\n",
DeviceObject,
pageData->QERR,
pageData->TST,
pageData->TAS));
if (pageData->QERR != 0) {
NTSTATUS status;
UCHAR pageSavable = 0;
//
// Set QERR to 0 with a Mode Select command. Re-use the modeData
// and pageData structures.
//
pageData->QERR = 0;
//
// We use the original Page Savable (PS) value for the Save Pages
// (SP) bit due to behavior described under the MODE SELECT(6)
// section of SPC-4.
//
pageSavable = pageData->PageSavable;
status = ClasspModeSelect(DeviceObject,
(PCHAR)modeData,
size,
pageSavable);
if (!NT_SUCCESS(status)) {
TracePrint((TRACE_LEVEL_WARNING,
TRACE_FLAG_SCSI,
"ClasspZeroQERR (%p): Failed to set QERR = 0 with status %x\n",
DeviceObject,
status));
}
}
}
ClasspZeroQERR_Exit:
if (modeData != NULL) {
ExFreePool(modeData);
}
}
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
ClasspPowerActivateDevice(
_In_ PDEVICE_OBJECT DeviceObject
)
/*++
Routine Description:
This routine synchronously sends an IOCTL_STORAGE_POWER_ACTIVE to the port
PDO in order to take an active reference on the given device. The device
will remain powered up and active for as long as this active reference is
taken.
The caller should ensure idle power management is enabled for the device
before calling this function.
Call ClasspPowerIdleDevice to release the active reference.
Arguments:
DeviceObject - Supplies the FDO associated with this request.
Return Value:
STATUS_SUCCESS if the active reference was successfully taken.
--*/
{
NTSTATUS status = STATUS_UNSUCCESSFUL;
PIRP irp;
KEVENT event;
IO_STATUS_BLOCK ioStatus;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
NT_ASSERT(fdoExtension->CommonExtension.IsFdo);
NT_ASSERT(fdoExtension->FunctionSupportInfo->IdlePower.IdlePowerEnabled);
KeInitializeEvent(&event, SynchronizationEvent, FALSE);
irp = IoBuildDeviceIoControlRequest(IOCTL_STORAGE_POWER_ACTIVE,
fdoExtension->LowerPdo,
NULL,
0,
NULL,
0,
FALSE,
&event,
&ioStatus);
if (irp != NULL) {
status = IoCallDriver(fdoExtension->LowerPdo, irp);
if (status == STATUS_PENDING) {
(VOID)KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
status = ioStatus.Status;
}
} else {
status = STATUS_INSUFFICIENT_RESOURCES;
}
return status;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
ClasspPowerIdleDevice(
_In_ PDEVICE_OBJECT DeviceObject
)
/*++
Routine Description:
This routine synchronously sends an IOCTL_STORAGE_POWER_IDLE to the port
PDO in order to release an active reference on the given device.
A call to ClasspPowerActivateDevice *must* have preceded a call to this
function.
The caller should ensure idle power management is enabled for the device
before calling this function.
Arguments:
DeviceObject - Supplies the FDO associated with this request.
Return Value:
STATUS_SUCCESS if the active reference was successfully released.
--*/
{
NTSTATUS status = STATUS_UNSUCCESSFUL;
PIRP irp;
KEVENT event;
IO_STATUS_BLOCK ioStatus;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = (PFUNCTIONAL_DEVICE_EXTENSION)DeviceObject->DeviceExtension;
NT_ASSERT(fdoExtension->CommonExtension.IsFdo);
NT_ASSERT(fdoExtension->FunctionSupportInfo->IdlePower.IdlePowerEnabled);
KeInitializeEvent(&event, SynchronizationEvent, FALSE);
irp = IoBuildDeviceIoControlRequest(IOCTL_STORAGE_POWER_IDLE,
fdoExtension->LowerPdo,
NULL,
0,
NULL,
0,
FALSE,
&event,
&ioStatus);
if (irp != NULL) {
status = IoCallDriver(fdoExtension->LowerPdo, irp);
if (status == STATUS_PENDING) {
(VOID)KeWaitForSingleObject(&event, Executive, KernelMode, FALSE, NULL);
status = ioStatus.Status;
}
} else {
status = STATUS_INSUFFICIENT_RESOURCES;
}
return status;
}
#if (NTDDI_VERSION >= NTDDI_WINTHRESHOLD)
NTSTATUS
ClasspGetHwFirmwareInfo(
_In_ PDEVICE_OBJECT DeviceObject
)
{
PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
PSTORAGE_HW_FIRMWARE_INFO firmwareInfo = NULL;
PSTORAGE_HW_FIRMWARE_INFO_QUERY query = NULL;
IO_STATUS_BLOCK ioStatus = {0};
ULONG dataLength = sizeof(STORAGE_HW_FIRMWARE_INFO);
ULONG iteration = 1;
CLASS_FUNCTION_SUPPORT oldState;
KLOCK_QUEUE_HANDLE lockHandle;
//
// Try to get firmware information that contains only one slot.
// We will retry the query if the required buffer size is bigger than that.
//
retry:
firmwareInfo = ExAllocatePoolZero(NonPagedPoolNx,
dataLength,
CLASSPNP_POOL_TAG_FIRMWARE);
if (firmwareInfo == NULL) {
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_INIT, "ClasspGetHwFirmwareInfo: cannot allocate memory to hold data. \n"));
return STATUS_INSUFFICIENT_RESOURCES;
}
//
// Set up query data, making sure the "Flags" field indicating the request is for device itself.
//
query = (PSTORAGE_HW_FIRMWARE_INFO_QUERY)firmwareInfo;
query->Version = sizeof(STORAGE_HW_FIRMWARE_INFO_QUERY);
query->Size = sizeof(STORAGE_HW_FIRMWARE_INFO_QUERY);
query->Flags = 0;
//
// On the first pass we just want to get the first few
// bytes of the descriptor so we can read it's size
//
ClassSendDeviceIoControlSynchronous(IOCTL_STORAGE_FIRMWARE_GET_INFO,
commonExtension->LowerDeviceObject,
query,
sizeof(STORAGE_HW_FIRMWARE_INFO_QUERY),
dataLength,
FALSE,
&ioStatus
);
if (!NT_SUCCESS(ioStatus.Status) &&
(ioStatus.Status != STATUS_BUFFER_OVERFLOW)) {
if (ClasspLowerLayerNotSupport(ioStatus.Status)) {
oldState = InterlockedCompareExchange((PLONG)(&fdoExtension->FunctionSupportInfo->HwFirmwareGetInfoSupport), (LONG)NotSupported, (ULONG)SupportUnknown);
}
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_INIT, "ClasspGetHwFirmwareInfo: error %lx trying to "
"query hardware firmware information #%d \n", ioStatus.Status, iteration));
FREE_POOL(firmwareInfo);
return ioStatus.Status;
}
//
// Catch implementation issues from lower level driver.
//
if ((firmwareInfo->Version < sizeof(STORAGE_HW_FIRMWARE_INFO)) ||
(firmwareInfo->Size < sizeof(STORAGE_HW_FIRMWARE_INFO)) ||
(firmwareInfo->SlotCount == 0) ||
(firmwareInfo->ImagePayloadMaxSize > fdoExtension->AdapterDescriptor->MaximumTransferLength)) {
oldState = InterlockedCompareExchange((PLONG)(&fdoExtension->FunctionSupportInfo->HwFirmwareGetInfoSupport), (LONG)NotSupported, (ULONG)SupportUnknown);
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_INIT, "ClasspGetHwFirmwareInfo: error in returned data! "
"Version: 0x%X, Size: 0x%X, SlotCount: 0x%X, ActiveSlot: 0x%X, PendingActiveSlot: 0x%X, ImagePayloadMaxSize: 0x%X \n",
firmwareInfo->Version,
firmwareInfo->Size,
firmwareInfo->SlotCount,
firmwareInfo->ActiveSlot,
firmwareInfo->PendingActivateSlot,
firmwareInfo->ImagePayloadMaxSize));
FREE_POOL(firmwareInfo);
return STATUS_UNSUCCESSFUL;
}
//
// If the data size is bigger than sizeof(STORAGE_HW_FIRMWARE_INFO), e.g. device has more than one firmware slot,
// allocate a buffer to get all the data.
//
if ((firmwareInfo->Size > sizeof(STORAGE_HW_FIRMWARE_INFO)) &&
(iteration < 2)) {
dataLength = max(firmwareInfo->Size, sizeof(STORAGE_HW_FIRMWARE_INFO) + sizeof(STORAGE_HW_FIRMWARE_SLOT_INFO) * (firmwareInfo->SlotCount - 1));
//
// Retry the query with required buffer length.
//
FREE_POOL(firmwareInfo);
iteration++;
goto retry;
}
//
// Set the support status and use the memory we've allocated as caching buffer.
// In case of a competing thread already set the state, it will assign the caching buffer so release the current allocated one.
//
KeAcquireInStackQueuedSpinLock(&fdoExtension->FunctionSupportInfo->SyncLock, &lockHandle);
oldState = InterlockedCompareExchange((PLONG)(&fdoExtension->FunctionSupportInfo->HwFirmwareGetInfoSupport), (LONG)Supported, (ULONG)SupportUnknown);
if (oldState == SupportUnknown) {
fdoExtension->FunctionSupportInfo->HwFirmwareInfo = firmwareInfo;
} else if (oldState == Supported) {
//
// swap the buffers to keep the latest version.
//
PSTORAGE_HW_FIRMWARE_INFO cachedInfo = fdoExtension->FunctionSupportInfo->HwFirmwareInfo;
fdoExtension->FunctionSupportInfo->HwFirmwareInfo = firmwareInfo;
FREE_POOL(cachedInfo);
} else {
FREE_POOL(firmwareInfo);
}
KeReleaseInStackQueuedSpinLock(&lockHandle);
return ioStatus.Status;
} // end ClasspGetHwFirmwareInfo()
#endif // #if (NTDDI_VERSION >= NTDDI_WINTHRESHOLD)
__inline
BOOLEAN
ClassDeviceHwFirmwareIsPortDriverSupported(
_In_ PDEVICE_OBJECT DeviceObject
)
/*
Routine Description:
This function informs the caller whether the port driver supports hardware firmware requests.
Arguments:
DeviceObject: The target object.
Return Value:
TRUE if the port driver is supported.
--*/
{
//
// If the request is for a FDO, process the request for Storport, SDstor and Spaceport only.
// Don't process it if we don't have a miniport descriptor.
//
PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
BOOLEAN isSupported = FALSE;
if (commonExtension->IsFdo && (fdoExtension->MiniportDescriptor != NULL)) {
isSupported = ((fdoExtension->MiniportDescriptor->Portdriver == StoragePortCodeSetStorport) ||
(fdoExtension->MiniportDescriptor->Portdriver == StoragePortCodeSetSpaceport) ||
(fdoExtension->MiniportDescriptor->Portdriver == StoragePortCodeSetSDport ));
}
return isSupported;
}
NTSTATUS
ClassDeviceHwFirmwareGetInfoProcess(
_In_ PDEVICE_OBJECT DeviceObject,
_Inout_ PIRP Irp
)
/*
Routine Description:
This function processes the Storage Hardware Firmware Get Information request.
If the information is not cached yet, it gets from lower level driver.
Arguments:
DeviceObject: The target FDO.
Irp: The IRP which will contain the output buffer upon completion.
Return Value:
NTSTATUS code.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
#if (NTDDI_VERSION >= NTDDI_WINTHRESHOLD)
PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
PSTORAGE_HW_FIRMWARE_INFO_QUERY query = (PSTORAGE_HW_FIRMWARE_INFO_QUERY)Irp->AssociatedIrp.SystemBuffer;
BOOLEAN passDown = FALSE;
BOOLEAN copyData = FALSE;
//
// Input buffer is not big enough to contain required input information.
//
if (irpStack->Parameters.DeviceIoControl.InputBufferLength < sizeof(STORAGE_HW_FIRMWARE_INFO_QUERY)) {
status = STATUS_INFO_LENGTH_MISMATCH;
goto Exit_Firmware_Get_Info;
}
//
// Output buffer is too small to contain return data.
//
if (irpStack->Parameters.DeviceIoControl.OutputBufferLength < sizeof(STORAGE_HW_FIRMWARE_INFO)) {
status = STATUS_BUFFER_TOO_SMALL;
goto Exit_Firmware_Get_Info;
}
//
// Only process the request for a supported port driver.
//
if (!ClassDeviceHwFirmwareIsPortDriverSupported(DeviceObject)) {
status = STATUS_NOT_IMPLEMENTED;
goto Exit_Firmware_Get_Info;
}
//
// Buffer "FunctionSupportInfo" is allocated during start device process. Following check defends against the situation
// of receiving this IOCTL when the device is created but not started, or device start failed but did not get removed yet.
//
if (commonExtension->IsFdo && (fdoExtension->FunctionSupportInfo == NULL)) {
status = STATUS_UNSUCCESSFUL;
goto Exit_Firmware_Get_Info;
}
//
// Process the situation that request should be forwarded to lower level.
//
if (!commonExtension->IsFdo) {
passDown = TRUE;
}
if ((query->Flags & STORAGE_HW_FIRMWARE_REQUEST_FLAG_CONTROLLER) != 0) {
passDown = TRUE;
}
if (passDown) {
IoCopyCurrentIrpStackLocationToNext(Irp);
ClassReleaseRemoveLock(DeviceObject, Irp);
status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
return status;
}
//
// The request is for a FDO. Process the request.
//
if (fdoExtension->FunctionSupportInfo->HwFirmwareGetInfoSupport == NotSupported) {
status = STATUS_NOT_IMPLEMENTED;
goto Exit_Firmware_Get_Info;
} else {
//
// Retrieve information from lower layer for the request. The cached information is not used
// in case device firmware information changed.
//
status = ClasspGetHwFirmwareInfo(DeviceObject);
copyData = NT_SUCCESS(status);
}
Exit_Firmware_Get_Info:
if (copyData) {
//
// Firmware information is already cached in classpnp. Return a copy.
//
KLOCK_QUEUE_HANDLE lockHandle;
KeAcquireInStackQueuedSpinLock(&fdoExtension->FunctionSupportInfo->SyncLock, &lockHandle);
ULONG dataLength = min(irpStack->Parameters.DeviceIoControl.OutputBufferLength, fdoExtension->FunctionSupportInfo->HwFirmwareInfo->Size);
memcpy(Irp->AssociatedIrp.SystemBuffer, fdoExtension->FunctionSupportInfo->HwFirmwareInfo, dataLength);
KeReleaseInStackQueuedSpinLock(&lockHandle);
Irp->IoStatus.Information = dataLength;
}
Irp->IoStatus.Status = status;
#else
status = STATUS_NOT_IMPLEMENTED;
Irp->IoStatus.Status = status;
#endif // #if (NTDDI_VERSION >= NTDDI_WINTHRESHOLD)
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
return status;
}
#if (NTDDI_VERSION >= NTDDI_WINTHRESHOLD)
_IRQL_requires_same_
_IRQL_requires_max_(DISPATCH_LEVEL)
NTSTATUS
ClassHwFirmwareDownloadComplete (
_In_ PDEVICE_OBJECT Fdo,
_In_ PIRP Irp,
_In_reads_opt_(_Inexpressible_("varies")) PVOID Context
)
{
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
PIRP originalIrp;
//
// Free the allocated buffer for firmware image.
//
if (Context != NULL) {
FREE_POOL(Context);
}
originalIrp = irpStack->Parameters.Others.Argument1;
NT_ASSERT(originalIrp != NULL);
originalIrp->IoStatus.Status = Irp->IoStatus.Status;
originalIrp->IoStatus.Information = Irp->IoStatus.Information;
ClassReleaseRemoveLock(Fdo, originalIrp);
ClassCompleteRequest(Fdo, originalIrp, IO_DISK_INCREMENT);
IoFreeIrp(Irp);
return STATUS_MORE_PROCESSING_REQUIRED;
} // end ClassHwFirmwareDownloadComplete()
#endif // #if (NTDDI_VERSION >= NTDDI_WINTHRESHOLD)
NTSTATUS
ClassDeviceHwFirmwareDownloadProcess(
_In_ PDEVICE_OBJECT DeviceObject,
_Inout_ PIRP Irp,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
{
NTSTATUS status = STATUS_SUCCESS;
#if (NTDDI_VERSION >= NTDDI_WINTHRESHOLD)
PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
PSTORAGE_HW_FIRMWARE_DOWNLOAD firmwareDownload = (PSTORAGE_HW_FIRMWARE_DOWNLOAD)Irp->AssociatedIrp.SystemBuffer;
BOOLEAN passDown = FALSE;
ULONG i;
ULONG bufferSize = 0;
PUCHAR firmwareImageBuffer = NULL;
PIRP irp2 = NULL;
PIO_STACK_LOCATION newStack = NULL;
PCDB cdb = NULL;
BOOLEAN lockHeld = FALSE;
KLOCK_QUEUE_HANDLE lockHandle;
//
// Input buffer is not big enough to contain required input information.
//
if (irpStack->Parameters.DeviceIoControl.InputBufferLength < sizeof(STORAGE_HW_FIRMWARE_DOWNLOAD)) {
status = STATUS_INFO_LENGTH_MISMATCH;
goto Exit_Firmware_Download;
}
//
// Input buffer basic validation.
//
if ((firmwareDownload->Version < sizeof(STORAGE_HW_FIRMWARE_DOWNLOAD)) ||
(firmwareDownload->Size > irpStack->Parameters.DeviceIoControl.InputBufferLength) ||
((firmwareDownload->BufferSize + FIELD_OFFSET(STORAGE_HW_FIRMWARE_DOWNLOAD, ImageBuffer)) > firmwareDownload->Size)) {
status = STATUS_INVALID_PARAMETER;
goto Exit_Firmware_Download;
}
//
// Only process the request for a supported port driver.
//
if (!ClassDeviceHwFirmwareIsPortDriverSupported(DeviceObject)) {
status = STATUS_NOT_IMPLEMENTED;
goto Exit_Firmware_Download;
}
//
// Buffer "FunctionSupportInfo" is allocated during start device process. Following check defends against the situation
// of receiving this IOCTL when the device is created but not started, or device start failed but did not get removed yet.
//
if (commonExtension->IsFdo && (fdoExtension->FunctionSupportInfo == NULL)) {
status = STATUS_UNSUCCESSFUL;
goto Exit_Firmware_Download;
}
//
// Process the situation that request should be forwarded to lower level.
//
if (!commonExtension->IsFdo) {
passDown = TRUE;
}
if ((firmwareDownload->Flags & STORAGE_HW_FIRMWARE_REQUEST_FLAG_CONTROLLER) != 0) {
passDown = TRUE;
}
if (passDown) {
IoCopyCurrentIrpStackLocationToNext(Irp);
ClassReleaseRemoveLock(DeviceObject, Irp);
status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
FREE_POOL(Srb);
return status;
}
//
// If firmware information hasn't been cached in classpnp, retrieve it.
//
if (fdoExtension->FunctionSupportInfo->HwFirmwareInfo == NULL) {
if (fdoExtension->FunctionSupportInfo->HwFirmwareGetInfoSupport == NotSupported) {
status = STATUS_NOT_IMPLEMENTED;
goto Exit_Firmware_Download;
} else {
//
// If this is the first time of retrieving firmware information,
// send request to lower level to get it.
//
status = ClasspGetHwFirmwareInfo(DeviceObject);
if (!NT_SUCCESS(status)) {
goto Exit_Firmware_Download;
}
}
}
//
// Fail the request if the firmware information cannot be retrieved.
//
if (fdoExtension->FunctionSupportInfo->HwFirmwareInfo == NULL) {
if (fdoExtension->FunctionSupportInfo->HwFirmwareGetInfoSupport == NotSupported) {
status = STATUS_NOT_IMPLEMENTED;
} else {
status = STATUS_UNSUCCESSFUL;
}
goto Exit_Firmware_Download;
}
//
// Acquire the SyncLock to ensure the HwFirmwareInfo pointer doesn't change
// while we're dereferencing it.
//
lockHeld = TRUE;
KeAcquireInStackQueuedSpinLock(&fdoExtension->FunctionSupportInfo->SyncLock, &lockHandle);
//
// Validate the device support
//
if ((fdoExtension->FunctionSupportInfo->HwFirmwareInfo->SupportUpgrade == FALSE) ||
(fdoExtension->FunctionSupportInfo->HwFirmwareInfo->ImagePayloadAlignment == 0)) {
status = STATUS_NOT_SUPPORTED;
goto Exit_Firmware_Download;
}
//
// Check if the slot can be used to hold firmware image.
//
for (i = 0; i < fdoExtension->FunctionSupportInfo->HwFirmwareInfo->SlotCount; i++) {
if (fdoExtension->FunctionSupportInfo->HwFirmwareInfo->Slot[i].SlotNumber == firmwareDownload->Slot) {
break;
}
}
if ((i >= fdoExtension->FunctionSupportInfo->HwFirmwareInfo->SlotCount) ||
(fdoExtension->FunctionSupportInfo->HwFirmwareInfo->Slot[i].ReadOnly == TRUE)) {
//
// Either the slot number is out of scope or the slot is read-only.
//
status = STATUS_INVALID_PARAMETER;
goto Exit_Firmware_Download;
}
//
// Buffer size and alignment validation.
// Max Offset and Buffer Size can be represented by SCSI command is max value for 3 bytes.
//
if ((firmwareDownload->BufferSize == 0) ||
((firmwareDownload->BufferSize % fdoExtension->FunctionSupportInfo->HwFirmwareInfo->ImagePayloadAlignment) != 0) ||
(firmwareDownload->BufferSize > fdoExtension->FunctionSupportInfo->HwFirmwareInfo->ImagePayloadMaxSize) ||
(firmwareDownload->BufferSize > fdoExtension->AdapterDescriptor->MaximumTransferLength) ||
((firmwareDownload->Offset % fdoExtension->FunctionSupportInfo->HwFirmwareInfo->ImagePayloadAlignment) != 0) ||
(firmwareDownload->Offset > 0xFFFFFF) ||
(firmwareDownload->BufferSize > 0xFFFFFF)) {
status = STATUS_INVALID_PARAMETER;
goto Exit_Firmware_Download;
}
//
// Process the request by translating it into WRITE BUFFER command.
//
if (((ULONG_PTR)firmwareDownload->ImageBuffer % fdoExtension->FunctionSupportInfo->HwFirmwareInfo->ImagePayloadAlignment) != 0) {
//
// Allocate buffer aligns to ImagePayloadAlignment to accommodate the alignment requirement.
//
bufferSize = ALIGN_UP_BY(firmwareDownload->BufferSize, fdoExtension->FunctionSupportInfo->HwFirmwareInfo->ImagePayloadAlignment);
//
// We're done accessing HwFirmwareInfo at this point so we can release
// the SyncLock.
//
NT_ASSERT(lockHeld);
KeReleaseInStackQueuedSpinLock(&lockHandle);
lockHeld = FALSE;
#pragma prefast(suppress:6014, "The allocated memory that firmwareImageBuffer points to will be freed in ClassHwFirmwareDownloadComplete().")
firmwareImageBuffer = ExAllocatePoolZero(NonPagedPoolNx,
bufferSize,
CLASSPNP_POOL_TAG_FIRMWARE);
if (firmwareImageBuffer == NULL) {
status = STATUS_INSUFFICIENT_RESOURCES;
goto Exit_Firmware_Download;
}
RtlCopyMemory(firmwareImageBuffer, firmwareDownload->ImageBuffer, (ULONG)firmwareDownload->BufferSize);
} else {
NT_ASSERT(lockHeld);
KeReleaseInStackQueuedSpinLock(&lockHandle);
lockHeld = FALSE;
firmwareImageBuffer = firmwareDownload->ImageBuffer;
bufferSize = (ULONG)firmwareDownload->BufferSize;
}
//
// Allocate a new irp to send the WRITE BUFFER command down.
// Similar process as IOCTL_STORAGE_CHECK_VERIFY.
//
irp2 = IoAllocateIrp((CCHAR)(DeviceObject->StackSize + 3), FALSE);
if (irp2 == NULL) {
status = STATUS_INSUFFICIENT_RESOURCES;
if (firmwareImageBuffer != firmwareDownload->ImageBuffer) {
FREE_POOL(firmwareImageBuffer);
}
goto Exit_Firmware_Download;
}
//
// Make sure to acquire the lock for the new irp.
//
ClassAcquireRemoveLock(DeviceObject, irp2);
irp2->Tail.Overlay.Thread = Irp->Tail.Overlay.Thread;
IoSetNextIrpStackLocation(irp2);
//
// Set the top stack location and shove the master Irp into the
// top location
//
newStack = IoGetCurrentIrpStackLocation(irp2);
newStack->Parameters.Others.Argument1 = Irp;
newStack->DeviceObject = DeviceObject;
//
// Stick the firmware download completion routine onto the stack
// and prepare the irp for the port driver
//
IoSetCompletionRoutine(irp2,
ClassHwFirmwareDownloadComplete,
(firmwareImageBuffer != firmwareDownload->ImageBuffer) ? firmwareImageBuffer : NULL,
TRUE,
TRUE,
TRUE);
IoSetNextIrpStackLocation(irp2);
newStack = IoGetCurrentIrpStackLocation(irp2);
newStack->DeviceObject = DeviceObject;
newStack->MajorFunction = irpStack->MajorFunction;
newStack->MinorFunction = irpStack->MinorFunction;
newStack->Flags = irpStack->Flags;
//
// Mark the master irp as pending - whether the lower level
// driver completes it immediately or not this should allow it
// to go all the way back up.
//
IoMarkIrpPending(Irp);
//
// Setup the CDB.
//
SrbSetCdbLength(Srb, CDB10GENERIC_LENGTH);
cdb = SrbGetCdb(Srb);
cdb->WRITE_BUFFER.OperationCode = SCSIOP_WRITE_DATA_BUFF;
cdb->WRITE_BUFFER.Mode = SCSI_WRITE_BUFFER_MODE_DOWNLOAD_MICROCODE_WITH_OFFSETS_SAVE_DEFER_ACTIVATE;
cdb->WRITE_BUFFER.ModeSpecific = 0; //Reserved for Mode 0x0E
cdb->WRITE_BUFFER.BufferID = firmwareDownload->Slot;
cdb->WRITE_BUFFER.BufferOffset[0] = *((PCHAR)&firmwareDownload->Offset + 2);
cdb->WRITE_BUFFER.BufferOffset[1] = *((PCHAR)&firmwareDownload->Offset + 1);
cdb->WRITE_BUFFER.BufferOffset[2] = *((PCHAR)&firmwareDownload->Offset);
cdb->WRITE_BUFFER.ParameterListLength[0] = *((PCHAR)&bufferSize + 2);
cdb->WRITE_BUFFER.ParameterListLength[1] = *((PCHAR)&bufferSize + 1);
cdb->WRITE_BUFFER.ParameterListLength[2] = *((PCHAR)&bufferSize);
//
// Send as a tagged command.
//
SrbSetRequestAttribute(Srb, SRB_HEAD_OF_QUEUE_TAG_REQUEST);
SrbSetSrbFlags(Srb, SRB_FLAGS_NO_QUEUE_FREEZE | SRB_FLAGS_QUEUE_ACTION_ENABLE);
//
// Set timeout value.
//
SrbSetTimeOutValue(Srb, fdoExtension->TimeOutValue);
//
// This routine uses a completion routine so we don't want to release
// the remove lock until then.
//
status = ClassSendSrbAsynchronous(DeviceObject,
Srb,
irp2,
firmwareImageBuffer,
bufferSize,
TRUE);
if (status != STATUS_PENDING) {
//
// If the new irp cannot be sent down, free allocated memory and bail out.
//
if (firmwareImageBuffer != firmwareDownload->ImageBuffer) {
FREE_POOL(firmwareImageBuffer);
}
//
// If the irp cannot be sent down, the Srb has been freed. NULL it to prevent from freeing it again.
//
Srb = NULL;
ClassReleaseRemoveLock(DeviceObject, irp2);
IoFreeIrp(irp2);
goto Exit_Firmware_Download;
}
return status;
Exit_Firmware_Download:
//
// Release the SyncLock if it's still held.
// This should only happen in the failure path.
//
if (lockHeld) {
KeReleaseInStackQueuedSpinLock(&lockHandle);
lockHeld = FALSE;
}
//
// Firmware Download request will be failed.
//
NT_ASSERT(!NT_SUCCESS(status));
Irp->IoStatus.Status = status;
#else
status = STATUS_NOT_IMPLEMENTED;
Irp->IoStatus.Status = status;
#endif // #if (NTDDI_VERSION >= NTDDI_WINTHRESHOLD)
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
FREE_POOL(Srb);
return status;
}
NTSTATUS
ClassDeviceHwFirmwareActivateProcess(
_In_ PDEVICE_OBJECT DeviceObject,
_Inout_ PIRP Irp,
_Inout_ PSCSI_REQUEST_BLOCK Srb
)
{
NTSTATUS status = STATUS_SUCCESS;
#if (NTDDI_VERSION >= NTDDI_WINTHRESHOLD)
PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;
PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
PSTORAGE_HW_FIRMWARE_ACTIVATE firmwareActivate = (PSTORAGE_HW_FIRMWARE_ACTIVATE)Irp->AssociatedIrp.SystemBuffer;
BOOLEAN passDown = FALSE;
PCDB cdb = NULL;
ULONG i;
BOOLEAN lockHeld = FALSE;
KLOCK_QUEUE_HANDLE lockHandle;
//
// Input buffer is not big enough to contain required input information.
//
if (irpStack->Parameters.DeviceIoControl.InputBufferLength < sizeof(STORAGE_HW_FIRMWARE_ACTIVATE)) {
status = STATUS_INFO_LENGTH_MISMATCH;
goto Exit_Firmware_Activate;
}
//
// Input buffer basic validation.
//
if ((firmwareActivate->Version < sizeof(STORAGE_HW_FIRMWARE_ACTIVATE)) ||
(firmwareActivate->Size > irpStack->Parameters.DeviceIoControl.InputBufferLength)) {
status = STATUS_INVALID_PARAMETER;
goto Exit_Firmware_Activate;
}
//
// Only process the request for a supported port driver.
//
if (!ClassDeviceHwFirmwareIsPortDriverSupported(DeviceObject)) {
status = STATUS_NOT_IMPLEMENTED;
goto Exit_Firmware_Activate;
}
//
// Buffer "FunctionSupportInfo" is allocated during start device process. Following check defends against the situation
// of receiving this IOCTL when the device is created but not started, or device start failed but did not get removed yet.
//
if (commonExtension->IsFdo && (fdoExtension->FunctionSupportInfo == NULL)) {
status = STATUS_UNSUCCESSFUL;
goto Exit_Firmware_Activate;
}
//
// Process the situation that request should be forwarded to lower level.
//
if (!commonExtension->IsFdo) {
passDown = TRUE;
}
if ((firmwareActivate->Flags & STORAGE_HW_FIRMWARE_REQUEST_FLAG_CONTROLLER) != 0) {
passDown = TRUE;
}
if (passDown) {
IoCopyCurrentIrpStackLocationToNext(Irp);
ClassReleaseRemoveLock(DeviceObject, Irp);
status = IoCallDriver(commonExtension->LowerDeviceObject, Irp);
FREE_POOL(Srb);
return status;
}
//
// If firmware information hasn't been cached in classpnp, retrieve it.
//
if (fdoExtension->FunctionSupportInfo->HwFirmwareInfo == NULL) {
if (fdoExtension->FunctionSupportInfo->HwFirmwareGetInfoSupport == NotSupported) {
status = STATUS_NOT_IMPLEMENTED;
goto Exit_Firmware_Activate;
} else {
//
// If this is the first time of retrieving firmware information,
// send request to lower level to get it.
//
status = ClasspGetHwFirmwareInfo(DeviceObject);
if (!NT_SUCCESS(status)) {
goto Exit_Firmware_Activate;
}
}
}
//
// Fail the request if the firmware information cannot be retrieved.
//
if (fdoExtension->FunctionSupportInfo->HwFirmwareInfo == NULL) {
if (fdoExtension->FunctionSupportInfo->HwFirmwareGetInfoSupport == NotSupported) {
status = STATUS_NOT_IMPLEMENTED;
} else {
status = STATUS_UNSUCCESSFUL;
}
goto Exit_Firmware_Activate;
}
//
// Acquire the SyncLock to ensure the HwFirmwareInfo pointer doesn't change
// while we're dereferencing it.
//
lockHeld = TRUE;
KeAcquireInStackQueuedSpinLock(&fdoExtension->FunctionSupportInfo->SyncLock, &lockHandle);
//
// Validate the device support
//
if (fdoExtension->FunctionSupportInfo->HwFirmwareInfo->SupportUpgrade == FALSE) {
status = STATUS_NOT_SUPPORTED;
goto Exit_Firmware_Activate;
}
//
// Check if the slot number is valid.
//
for (i = 0; i < fdoExtension->FunctionSupportInfo->HwFirmwareInfo->SlotCount; i++) {
if (fdoExtension->FunctionSupportInfo->HwFirmwareInfo->Slot[i].SlotNumber == firmwareActivate->Slot) {
break;
}
}
if (i >= fdoExtension->FunctionSupportInfo->HwFirmwareInfo->SlotCount) {
//
// Either the slot number is out of scope or the slot is read-only.
//
status = STATUS_INVALID_PARAMETER;
goto Exit_Firmware_Activate;
}
//
// We're done accessing HwFirmwareInfo at this point so we can release
// the SyncLock.
//
NT_ASSERT(lockHeld);
KeReleaseInStackQueuedSpinLock(&lockHandle);
lockHeld = FALSE;
//
// Process the request by translating it into WRITE BUFFER command.
//
//
// Setup the CDB. This should be an untagged request.
//
SrbSetCdbLength(Srb, CDB10GENERIC_LENGTH);
cdb = SrbGetCdb(Srb);
cdb->WRITE_BUFFER.OperationCode = SCSIOP_WRITE_DATA_BUFF;
cdb->WRITE_BUFFER.Mode = SCSI_WRITE_BUFFER_MODE_ACTIVATE_DEFERRED_MICROCODE;
cdb->WRITE_BUFFER.ModeSpecific = 0; //Reserved for Mode 0x0F
cdb->WRITE_BUFFER.BufferID = firmwareActivate->Slot; //NOTE: this field will be ignored by SCSI device.
//
// Set timeout value.
//
SrbSetTimeOutValue(Srb, FIRMWARE_ACTIVATE_TIMEOUT_VALUE);
//
// This routine uses a completion routine - ClassIoComplete() so we don't want to release
// the remove lock until then.
//
status = ClassSendSrbAsynchronous(DeviceObject,
Srb,
Irp,
NULL,
0,
FALSE);
if (status != STATUS_PENDING) {
//
// If the irp cannot be sent down, the Srb has been freed. NULL it to prevent from freeing it again.
//
Srb = NULL;
goto Exit_Firmware_Activate;
}
return status;
Exit_Firmware_Activate:
//
// Release the SyncLock if it's still held.
// This should only happen in the failure path.
//
if (lockHeld) {
KeReleaseInStackQueuedSpinLock(&lockHandle);
lockHeld = FALSE;
}
//
// Firmware Activate request will be failed.
//
NT_ASSERT(!NT_SUCCESS(status));
Irp->IoStatus.Status = status;
#else
status = STATUS_NOT_IMPLEMENTED;
Irp->IoStatus.Status = status;
#endif // #if (NTDDI_VERSION >= NTDDI_WINTHRESHOLD)
ClassReleaseRemoveLock(DeviceObject, Irp);
ClassCompleteRequest(DeviceObject, Irp, IO_NO_INCREMENT);
FREE_POOL(Srb);
return status;
}
BOOLEAN
ClasspIsThinProvisioningError (
_In_ PSCSI_REQUEST_BLOCK Srb
)
/*++
Routine Description:
This routine checks whether the completed SRB Srb was completed with a thin provisioning
soft threshold error.
Arguments:
Srb - the SRB to be checked.
Return Value:
BOOLEAN
--*/
{
if (TEST_FLAG(Srb->SrbStatus, SRB_STATUS_AUTOSENSE_VALID)) {
PVOID senseBuffer = SrbGetSenseInfoBuffer(Srb);
if (senseBuffer) {
UCHAR senseKey = 0;
UCHAR addlSenseCode = 0;
UCHAR addlSenseCodeQual = 0;
BOOLEAN validSense = ScsiGetSenseKeyAndCodes(senseBuffer,
SrbGetSenseInfoBufferLength(Srb),
SCSI_SENSE_OPTIONS_NONE,
&senseKey,
&addlSenseCode,
&addlSenseCodeQual);
return (validSense
&& (senseKey == SCSI_SENSE_UNIT_ATTENTION)
&& (addlSenseCode == SCSI_ADSENSE_LB_PROVISIONING)
&& (addlSenseCodeQual == SCSI_SENSEQ_SOFT_THRESHOLD_REACHED));
}
}
return FALSE;
}
|