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
|
/*++
Copyright (C) Microsoft Corporation. All rights reserved.
Module Name:
common.c
Abstract:
shared private routines for cdrom.sys
Environment:
kernel mode only
Notes:
Revision History:
--*/
#include "ntddk.h"
#include "ntddstor.h"
#include "ntstrsafe.h"
#include "cdrom.h"
#include "scratch.h"
#ifdef DEBUG_USE_WPP
#include "common.tmh"
#endif
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, DeviceGetParameter)
#pragma alloc_text(PAGE, DeviceSetParameter)
#pragma alloc_text(PAGE, DeviceSendSrbSynchronously)
#pragma alloc_text(PAGE, DevicePickDvdRegion)
#pragma alloc_text(PAGE, StringsAreMatched)
#pragma alloc_text(PAGE, PerformEjectionControl)
#pragma alloc_text(PAGE, DeviceFindFeaturePage)
#pragma alloc_text(PAGE, DevicePrintAllFeaturePages)
#pragma alloc_text(PAGE, DeviceRegisterInterface)
#pragma alloc_text(PAGE, DeviceRestoreDefaultSpeed)
#pragma alloc_text(PAGE, DeviceSendRequestSynchronously)
#pragma alloc_text(PAGE, MediaReadCapacity)
#pragma alloc_text(PAGE, MediaReadCapacityDataInterpret)
#pragma alloc_text(PAGE, DeviceRetrieveModeSenseUsingScratch)
#pragma alloc_text(PAGE, ModeSenseFindSpecificPage)
#pragma alloc_text(PAGE, DeviceUnlockExclusive)
#endif
LPCSTR LockTypeStrings[] = {"Simple",
"Secure",
"Internal"
};
VOID
RequestSetReceivedTime(
_In_ WDFREQUEST Request
)
{
PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request);
LARGE_INTEGER temp;
KeQueryTickCount(&temp);
requestContext->TimeReceived = temp;
return;
}
VOID
RequestSetSentTime(
_In_ WDFREQUEST Request
)
{
PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request);
LARGE_INTEGER temp;
KeQueryTickCount(&temp);
if (requestContext->TimeSentDownFirstTime.QuadPart == 0)
{
requestContext->TimeSentDownFirstTime = temp;
}
requestContext->TimeSentDownLasttTime = temp;
if (requestContext->OriginalRequest != NULL)
{
PCDROM_REQUEST_CONTEXT originalRequestContext = RequestGetContext(requestContext->OriginalRequest);
if (originalRequestContext->TimeSentDownFirstTime.QuadPart == 0)
{
originalRequestContext->TimeSentDownFirstTime = temp;
}
originalRequestContext->TimeSentDownLasttTime = temp;
}
return;
}
VOID
RequestClearSendTime(
_In_ WDFREQUEST Request
)
/*
Routine Description:
This function is used to clean SentTime fields in reusable request context.
Arguments:
Request -
Return Value:
N/A
*/
{
PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request);
requestContext->TimeSentDownFirstTime.QuadPart = 0;
requestContext->TimeSentDownLasttTime.QuadPart = 0;
return;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
VOID
DeviceGetParameter(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_opt_ PWSTR SubkeyName,
_In_ PWSTR ParameterName,
_Inout_ PULONG ParameterValue // also default value
)
/*++
Routine Description:
retrieve device parameter from registry.
Arguments:
DeviceExtension - device context.
SubkeyName - name of subkey
ParameterName - the registry parameter to be retrieved
Return Value:
ParameterValue - registry value retrieved
--*/
{
NTSTATUS status;
WDFKEY rootKey = NULL;
WDFKEY subKey = NULL;
UNICODE_STRING registrySubKeyName;
UNICODE_STRING registryValueName;
ULONG defaultParameterValue;
PAGED_CODE();
RtlInitUnicodeString(®istryValueName, ParameterName);
if (SubkeyName != NULL)
{
RtlInitUnicodeString(®istrySubKeyName, SubkeyName);
}
// open the hardware key
status = WdfDeviceOpenRegistryKey(DeviceExtension->Device,
PLUGPLAY_REGKEY_DEVICE,
KEY_READ,
WDF_NO_OBJECT_ATTRIBUTES,
&rootKey);
// open the sub key
if (NT_SUCCESS(status) && (SubkeyName != NULL))
{
status = WdfRegistryOpenKey(rootKey,
®istrySubKeyName,
KEY_READ,
WDF_NO_OBJECT_ATTRIBUTES,
&subKey);
if (!NT_SUCCESS(status))
{
WdfRegistryClose(rootKey);
rootKey = NULL;
}
}
if (NT_SUCCESS(status) && (rootKey != NULL))
{
defaultParameterValue = *ParameterValue;
status = WdfRegistryQueryULong((subKey != NULL) ? subKey : rootKey,
®istryValueName,
ParameterValue);
if (!NT_SUCCESS(status))
{
*ParameterValue = defaultParameterValue; // use default value
}
}
// close what we open
if (subKey != NULL)
{
WdfRegistryClose(subKey);
subKey = NULL;
}
if (rootKey != NULL)
{
WdfRegistryClose(rootKey);
rootKey = NULL;
}
// Windows 2000 SP3 uses the driver-specific key, so look in there
if (!NT_SUCCESS(status))
{
// open the software key
status = WdfDeviceOpenRegistryKey(DeviceExtension->Device,
PLUGPLAY_REGKEY_DRIVER,
KEY_READ,
WDF_NO_OBJECT_ATTRIBUTES,
&rootKey);
// open the sub key
if (NT_SUCCESS(status) && (SubkeyName != NULL))
{
status = WdfRegistryOpenKey(rootKey,
®istrySubKeyName,
KEY_READ,
WDF_NO_OBJECT_ATTRIBUTES,
&subKey);
if (!NT_SUCCESS(status))
{
WdfRegistryClose(rootKey);
rootKey = NULL;
}
}
if (NT_SUCCESS(status) && (rootKey != NULL))
{
defaultParameterValue = *ParameterValue;
status = WdfRegistryQueryULong((subKey != NULL) ? subKey : rootKey,
®istryValueName,
ParameterValue);
if (!NT_SUCCESS(status))
{
*ParameterValue = defaultParameterValue; // use default value
}
else
{
// Migrate the value over to the device-specific key
DeviceSetParameter(DeviceExtension, SubkeyName, ParameterName, *ParameterValue);
}
}
// close what we open
if (subKey != NULL)
{
WdfRegistryClose(subKey);
subKey = NULL;
}
if (rootKey != NULL)
{
WdfRegistryClose(rootKey);
rootKey = NULL;
}
}
return;
} // end DeviceetParameter()
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
DeviceSetParameter(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_opt_z_ PWSTR SubkeyName,
_In_ PWSTR ParameterName,
_In_ ULONG ParameterValue
)
/*++
Routine Description:
set parameter to registry.
Arguments:
DeviceExtension - device context.
SubkeyName - name of subkey
ParameterName - the registry parameter to be retrieved
ParameterValue - registry value to be set
Return Value:
NTSTATUS
--*/
{
NTSTATUS status;
WDFKEY rootKey = NULL;
WDFKEY subKey = NULL;
UNICODE_STRING registrySubKeyName;
UNICODE_STRING registryValueName;
PAGED_CODE();
RtlInitUnicodeString(®istryValueName, ParameterName);
if (SubkeyName != NULL)
{
RtlInitUnicodeString(®istrySubKeyName, SubkeyName);
}
// open the hardware key
status = WdfDeviceOpenRegistryKey(DeviceExtension->Device,
PLUGPLAY_REGKEY_DEVICE,
KEY_READ | KEY_WRITE,
WDF_NO_OBJECT_ATTRIBUTES,
&rootKey);
// open the sub key
if (NT_SUCCESS(status) && (SubkeyName != NULL))
{
status = WdfRegistryOpenKey(rootKey,
®istrySubKeyName,
KEY_READ | KEY_WRITE,
WDF_NO_OBJECT_ATTRIBUTES,
&subKey);
if (!NT_SUCCESS(status))
{
WdfRegistryClose(rootKey);
rootKey = NULL;
}
}
if (NT_SUCCESS(status) && (rootKey != NULL))
{
status = WdfRegistryAssignULong((subKey != NULL) ? subKey : rootKey,
®istryValueName,
ParameterValue);
}
// close what we open
if (subKey != NULL)
{
WdfRegistryClose(subKey);
subKey = NULL;
}
if (rootKey != NULL)
{
WdfRegistryClose(rootKey);
rootKey = NULL;
}
return status;
} // end DeviceSetParameter()
_IRQL_requires_max_(APC_LEVEL)
NTSTATUS
DeviceSendRequestSynchronously(
_In_ WDFDEVICE Device,
_In_ WDFREQUEST Request,
_In_ BOOLEAN RequestFormated
)
/*++
Routine Description:
send a request to lower driver synchronously.
Arguments:
Device - device object.
Request - request object
RequestFormated - if the request is already formatted, will no do it in this function
Return Value:
NTSTATUS
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device);
BOOLEAN requestCancelled = FALSE;
PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request);
PAGED_CODE();
if (!RequestFormated)
{
// set request up for sending down
WdfRequestFormatRequestUsingCurrentType(Request);
}
// get cancellation status for the original request
if (requestContext->OriginalRequest != NULL)
{
requestCancelled = WdfRequestIsCanceled(requestContext->OriginalRequest);
}
if (!requestCancelled)
{
status = RequestSend(deviceExtension,
Request,
deviceExtension->IoTarget,
WDF_REQUEST_SEND_OPTION_SYNCHRONOUS,
NULL);
}
else
{
status = STATUS_CANCELLED;
}
return status;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
DeviceSendSrbSynchronously(
_In_ WDFDEVICE Device,
_In_ PSCSI_REQUEST_BLOCK Srb,
_In_opt_ PVOID BufferAddress,
_In_ ULONG BufferLength,
_In_ BOOLEAN WriteToDevice,
_In_opt_ WDFREQUEST OriginalRequest
)
/*++
Routine Description:
Send a SRB structure to lower driver synchronously.
Process of this function:
1. Allocate SenseBuffer; Create Request; Allocate MDL
2. Do following loop if necessary
2.1 Reuse Request
2.2 Format Srb, Irp
2.3 Send Request
2.4 Error Intepret and retry decision making.
3. Release all allocated resosurces.
Arguments:
Device - device object.
Request - request object
RequestFormated - if the request is already formatted, will no do it in this function
Return Value:
NTSTATUS
NOTE:
The caller needs to setup following fields before calling this routine.
srb.CdbLength
srb.TimeOutValue
cdb
BufferLength and WriteToDevice to control the data direction of the device
BufferLength = 0: No data transfer
BufferLenth != 0 && !WriteToDevice: get data from device
BufferLenth != 0 && WriteToDevice: send data to device
--*/
{
NTSTATUS status;
PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device);
PCDROM_PRIVATE_FDO_DATA fdoData = deviceExtension->PrivateFdoData;
PUCHAR senseInfoBuffer = NULL;
ULONG retryCount = 0;
BOOLEAN retry = FALSE;
ULONG ioctlCode = 0;
WDFREQUEST request = NULL;
PIRP irp = NULL;
PIO_STACK_LOCATION nextStack = NULL;
PMDL mdlAddress = NULL;
BOOLEAN memoryLocked = FALSE;
WDF_OBJECT_ATTRIBUTES attributes;
PZERO_POWER_ODD_INFO zpoddInfo = deviceExtension->ZeroPowerODDInfo;
PAGED_CODE();
// NOTE: This code is only pagable because we are not freezing
// the queue. Allowing the queue to be frozen from a pagable
// routine could leave the queue frozen as we try to page in
// the code to unfreeze the queue. The result would be a nice
// case of deadlock. Therefore, since we are unfreezing the
// queue regardless of the result, just set the NO_FREEZE_QUEUE
// flag in the SRB.
NT_ASSERT(KeGetCurrentIrql() < DISPATCH_LEVEL);
//1. allocate SenseBuffer and initiate Srb common fields
// these fields will not be changed by lower driver.
{
// Write length to SRB.
Srb->Length = sizeof(SCSI_REQUEST_BLOCK);
Srb->Function = SRB_FUNCTION_EXECUTE_SCSI;
Srb->SenseInfoBufferLength = SENSE_BUFFER_SIZE;
// Sense buffer is in aligned nonpaged pool.
senseInfoBuffer = ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_CACHE_ALIGNED,
SENSE_BUFFER_SIZE,
CDROM_TAG_SENSE_INFO);
if (senseInfoBuffer == NULL)
{
status = STATUS_INSUFFICIENT_RESOURCES;
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL,
"DeviceSendSrbSynchronously: Can't allocate MDL\n"));
goto Exit;
}
Srb->SenseInfoBuffer = senseInfoBuffer;
Srb->DataBuffer = BufferAddress;
// set timeout value to default value if it's not specifically set by caller.
if (Srb->TimeOutValue == 0)
{
Srb->TimeOutValue = deviceExtension->TimeOutValue;
}
}
//2. Create Request object
{
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes,
CDROM_REQUEST_CONTEXT);
status = WdfRequestCreate(&attributes,
deviceExtension->IoTarget,
&request);
if (!NT_SUCCESS(status))
{
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL,
"DeviceSendSrbSynchronously: Can't create request: %lx\n",
status));
goto Exit;
}
irp = WdfRequestWdmGetIrp(request);
}
// 3. Build an MDL for the data buffer and stick it into the irp.
if (BufferAddress != NULL)
{
mdlAddress = IoAllocateMdl( BufferAddress,
BufferLength,
FALSE,
FALSE,
irp );
if (mdlAddress == NULL)
{
status = STATUS_INSUFFICIENT_RESOURCES;
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL,
"DeviceSendSrbSynchronously: Can't allocate MDL\n"));
goto Exit;
}
try
{
MmProbeAndLockPages(mdlAddress,
KernelMode,
(WriteToDevice ? IoReadAccess : IoWriteAccess));
}
except(EXCEPTION_EXECUTE_HANDLER)
{
status = GetExceptionCode();
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL,
"DeviceSendSrbSynchronously: Exception %lx locking buffer\n", status));
goto Exit;
}
memoryLocked = TRUE;
}
// 4. Format Srb, Irp; Send request and retry when necessary
do
{
// clear the control variable.
retry = FALSE;
// 4.1 reuse the request object; set originalRequest field.
{
WDF_REQUEST_REUSE_PARAMS params;
PCDROM_REQUEST_CONTEXT requestContext = NULL;
// deassign the MdlAddress, this is the value we assign explicitly.
// doing this can prevent WdfRequestReuse to release the Mdl unexpectly.
if (irp->MdlAddress)
{
irp->MdlAddress = NULL;
}
WDF_REQUEST_REUSE_PARAMS_INIT(¶ms,
WDF_REQUEST_REUSE_NO_FLAGS,
STATUS_SUCCESS);
status = WdfRequestReuse(request, ¶ms);
if (!NT_SUCCESS(status))
{
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL,
"DeviceSendSrbSynchronously: WdfRequestReuse failed, %!STATUS!\n",
status));
// exit the loop.
break;
}
// WDF requests to format the request befor sending it
status = WdfIoTargetFormatRequestForInternalIoctlOthers(deviceExtension->IoTarget,
request,
ioctlCode,
NULL, NULL,
NULL, NULL,
NULL, NULL);
if (!NT_SUCCESS(status))
{
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL,
"DeviceSendSrbSynchronously: WdfIoTargetFormatRequestForInternalIoctlOthers failed, %!STATUS!\n",
status));
// exit the loop.
break;
}
requestContext = RequestGetContext(request);
requestContext->OriginalRequest = OriginalRequest;
}
// 4.2 Format Srb and Irp
{
Srb->OriginalRequest = irp;
Srb->QueueAction = SRB_SIMPLE_TAG_REQUEST;
Srb->DataTransferLength = BufferLength;
Srb->SrbFlags = deviceExtension->SrbFlags;
// Disable synchronous transfer for these requests.
SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DISABLE_SYNCH_TRANSFER);
SET_FLAG(Srb->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE);
if (BufferAddress != NULL)
{
if (WriteToDevice)
{
SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DATA_OUT);
ioctlCode = IOCTL_SCSI_EXECUTE_OUT;
}
else
{
SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DATA_IN);
ioctlCode = IOCTL_SCSI_EXECUTE_IN;
}
}
else
{
ioctlCode = IOCTL_SCSI_EXECUTE_NONE;
}
// Zero out status.
Srb->ScsiStatus = 0;
Srb->SrbStatus = 0;
Srb->NextSrb = NULL;
// irp related fields
irp->MdlAddress = mdlAddress;
nextStack = IoGetNextIrpStackLocation(irp);
nextStack->MajorFunction = IRP_MJ_SCSI;
nextStack->Parameters.DeviceIoControl.IoControlCode = ioctlCode;
nextStack->Parameters.Scsi.Srb = Srb;
}
// 4.3 send Request to lower driver.
status = DeviceSendRequestSynchronously(Device, request, TRUE);
if (status != STATUS_CANCELLED)
{
NT_ASSERT(SRB_STATUS(Srb->SrbStatus) != SRB_STATUS_PENDING);
NT_ASSERT(status != STATUS_PENDING);
NT_ASSERT(!(Srb->SrbStatus & SRB_STATUS_QUEUE_FROZEN));
// 4.4 error process.
if (SRB_STATUS(Srb->SrbStatus) != SRB_STATUS_SUCCESS)
{
LONGLONG retryIntervalIn100ns = 0;
// Update status and determine if request should be retried.
retry = RequestSenseInfoInterpret(deviceExtension,
request,
Srb,
retryCount,
&status,
&retryIntervalIn100ns);
if (retry)
{
LARGE_INTEGER t;
t.QuadPart = -retryIntervalIn100ns;
retryCount++;
KeDelayExecutionThread(KernelMode, FALSE, &t);
}
}
else
{
// Request succeeded.
fdoData->LoggedTURFailureSinceLastIO = FALSE;
status = STATUS_SUCCESS;
retry = FALSE;
}
}
} while(retry);
if ((zpoddInfo != NULL) &&
(zpoddInfo->MonitorStartStopUnit != FALSE) &&
(SRB_STATUS(Srb->SrbStatus) == SRB_STATUS_SUCCESS))
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_POWER,
"DeviceSendSrbSynchronously: soft eject detected, device marked as active\n"));
DeviceMarkActive(deviceExtension, TRUE, FALSE);
}
// 5. Release all allocated resources.
// required even though we allocated our own, since the port driver may
// have allocated one also
if (PORT_ALLOCATED_SENSE(deviceExtension, Srb))
{
FREE_PORT_ALLOCATED_SENSE_BUFFER(deviceExtension, Srb);
}
Exit:
if (senseInfoBuffer != NULL)
{
FREE_POOL(senseInfoBuffer);
}
Srb->SenseInfoBuffer = NULL;
Srb->SenseInfoBufferLength = 0;
if (mdlAddress)
{
if (memoryLocked)
{
MmUnlockPages(mdlAddress);
memoryLocked = FALSE;
}
IoFreeMdl(mdlAddress);
irp->MdlAddress = NULL;
}
if (request)
{
WdfObjectDelete(request);
}
return status;
}
VOID
DeviceSendNotification(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_ const GUID* Guid,
_In_ ULONG ExtraDataSize,
_In_opt_ PVOID ExtraData
)
/*++
Routine Description:
send notification to other components
Arguments:
DeviceExtension - device context.
Guid - GUID for the notification
ExtraDataSize - data size along with notification
ExtraData - data buffer send with notification
Return Value:
None
--*/
{
PTARGET_DEVICE_CUSTOM_NOTIFICATION notification;
ULONG requiredSize;
NTSTATUS status;
status = RtlULongAdd((sizeof(TARGET_DEVICE_CUSTOM_NOTIFICATION) - sizeof(UCHAR)),
ExtraDataSize,
&requiredSize);
if (!(NT_SUCCESS(status)) || (requiredSize > 0x0000ffff))
{
// MAX_USHORT, max total size for these events!
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_MCN,
"Error sending event: size too large! (%x)\n",
requiredSize));
return;
}
notification = ExAllocatePool2(POOL_FLAG_NON_PAGED,
requiredSize,
CDROM_TAG_NOTIFICATION);
// if none allocated, exit
if (notification == NULL)
{
return;
}
// Prepare and send the request!
RtlZeroMemory(notification, requiredSize);
notification->Version = 1;
notification->Size = (USHORT)(requiredSize);
notification->FileObject = NULL;
notification->NameBufferOffset = -1;
notification->Event = *Guid;
if (ExtraData != NULL)
{
RtlCopyMemory(notification->CustomDataBuffer, ExtraData, ExtraDataSize);
}
IoReportTargetDeviceChangeAsynchronous(DeviceExtension->LowerPdo,
notification,
NULL,
NULL);
FREE_POOL(notification);
return;
}
VOID
DeviceSendStartUnit(
_In_ WDFDEVICE Device
)
/*++
Routine Description:
Send command to SCSI unit to start or power up.
Because this command is issued asynchronounsly, that is, without
waiting on it to complete, the IMMEDIATE flag is not set. This
means that the CDB will not return until the drive has powered up.
This should keep subsequent requests from being submitted to the
device before it has completely spun up.
This routine is called from the InterpretSense routine, when a
request sense returns data indicating that a drive must be
powered up.
This routine may also be called from a class driver's error handler,
or anytime a non-critical start device should be sent to the device.
Arguments:
Device - The device object.
Return Value:
None.
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PCDROM_DEVICE_EXTENSION deviceExtension = NULL;
WDF_OBJECT_ATTRIBUTES attributes;
WDFREQUEST startUnitRequest = NULL;
WDFMEMORY inputMemory = NULL;
PCOMPLETION_CONTEXT context = NULL;
PSCSI_REQUEST_BLOCK srb = NULL;
PCDB cdb = NULL;
deviceExtension = DeviceGetExtension(Device);
if (NT_SUCCESS(status))
{
// Allocate Srb from nonpaged pool.
context = ExAllocatePool2(POOL_FLAG_NON_PAGED,
sizeof(COMPLETION_CONTEXT),
CDROM_TAG_COMPLETION_CONTEXT);
if (context == NULL)
{
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL,
"DeviceSendStartUnit: Failed to allocate completion context\n"));
status = STATUS_INTERNAL_ERROR;
}
}
if (NT_SUCCESS(status))
{
// Save the device object in the context for use by the completion
// routine.
context->Device = Device;
srb = &context->Srb;
// Zero out srb.
RtlZeroMemory(srb, sizeof(SCSI_REQUEST_BLOCK));
// setup SRB structure.
srb->Length = sizeof(SCSI_REQUEST_BLOCK);
srb->Function = SRB_FUNCTION_EXECUTE_SCSI;
srb->TimeOutValue = START_UNIT_TIMEOUT;
srb->SrbFlags = SRB_FLAGS_NO_DATA_TRANSFER |
SRB_FLAGS_DISABLE_SYNCH_TRANSFER;
// setup CDB
srb->CdbLength = 6;
cdb = (PCDB)srb->Cdb;
cdb->START_STOP.OperationCode = SCSIOP_START_STOP_UNIT;
cdb->START_STOP.Start = 1;
cdb->START_STOP.Immediate = 0;
cdb->START_STOP.LogicalUnitNumber = srb->Lun;
//Create Request for sending down to port driver
WDF_OBJECT_ATTRIBUTES_INIT_CONTEXT_TYPE(&attributes,
CDROM_REQUEST_CONTEXT);
attributes.ParentObject = deviceExtension->IoTarget;
status = WdfRequestCreate(&attributes,
deviceExtension->IoTarget,
&startUnitRequest);
}
if (NT_SUCCESS(status))
{
srb->OriginalRequest = WdfRequestWdmGetIrp(startUnitRequest);
NT_ASSERT(srb->OriginalRequest != NULL);
//Prepare the request
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ParentObject = startUnitRequest;
status = WdfMemoryCreatePreallocated(&attributes,
(PVOID)srb,
sizeof(SCSI_REQUEST_BLOCK),
&inputMemory);
}
if (NT_SUCCESS(status))
{
status = WdfIoTargetFormatRequestForInternalIoctlOthers(deviceExtension->IoTarget,
startUnitRequest,
IOCTL_SCSI_EXECUTE_NONE,
inputMemory,
NULL,
NULL,
NULL,
NULL,
NULL);
}
if (NT_SUCCESS(status))
{
// Set a CompletionRoutine callback function.
WdfRequestSetCompletionRoutine(startUnitRequest,
DeviceAsynchronousCompletion,
context);
status = RequestSend(deviceExtension,
startUnitRequest,
deviceExtension->IoTarget,
0,
NULL);
}
// release resources when failed.
if (!NT_SUCCESS(status))
{
FREE_POOL(context);
if (startUnitRequest != NULL)
{
WdfObjectDelete(startUnitRequest);
}
}
return;
} // end StartUnit()
VOID
DeviceSendIoctlAsynchronously(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_ ULONG IoControlCode,
_In_ PDEVICE_OBJECT TargetDeviceObject
)
/*++
Routine Description:
Send an IOCTL asynchronously
Arguments:
DeviceExtension - device context.
IoControlCode - IOCTL code.
TargetDeviceObject - target device object.
Return Value:
None.
--*/
{
PIRP irp = NULL;
PIO_STACK_LOCATION nextIrpStack = NULL;
irp = IoAllocateIrp(DeviceExtension->DeviceObject->StackSize, FALSE);
if (irp != NULL)
{
nextIrpStack = IoGetNextIrpStackLocation(irp);
nextIrpStack->MajorFunction = IRP_MJ_DEVICE_CONTROL;
nextIrpStack->Parameters.DeviceIoControl.OutputBufferLength = 0;
nextIrpStack->Parameters.DeviceIoControl.InputBufferLength = 0;
nextIrpStack->Parameters.DeviceIoControl.IoControlCode = IoControlCode;
nextIrpStack->Parameters.DeviceIoControl.Type3InputBuffer = NULL;
IoSetCompletionRoutine(irp,
RequestAsynchronousIrpCompletion,
DeviceExtension,
TRUE,
TRUE,
TRUE);
(VOID) IoCallDriver(TargetDeviceObject, irp);
}
}
NTSTATUS
RequestAsynchronousIrpCompletion(
_In_ PDEVICE_OBJECT DeviceObject,
_In_ PIRP Irp,
_In_reads_opt_(_Inexpressible_("varies")) PVOID Context
)
/*++
Routine Description:
Free the Irp.
Arguments:
DeviceObject - device that the completion routine fires on.
Irp - The irp to be completed.
Context - IRP context
Return Value:
NTSTATUS
--*/
{
UNREFERENCED_PARAMETER(DeviceObject);
UNREFERENCED_PARAMETER(Context);
IoFreeIrp(Irp);
return STATUS_MORE_PROCESSING_REQUIRED;
}
VOID
DeviceAsynchronousCompletion(
_In_ WDFREQUEST Request,
_In_ WDFIOTARGET Target,
_In_ PWDF_REQUEST_COMPLETION_PARAMS Params,
_In_ WDFCONTEXT Context
)
/*++
Routine Description:
This routine is called when an asynchronous I/O request
which was issused by the class driver completes. Examples of such requests
are release queue or START UNIT. This routine releases the queue if
necessary. It then frees the context and the IRP.
Arguments:
DeviceObject - The device object for the logical unit; however since this
is the top stack location the value is NULL.
Irp - Supplies a pointer to the Irp to be processed.
Context - Supplies the context to be used to process this request.
Return Value:
None.
--*/
{
PCOMPLETION_CONTEXT context = (PCOMPLETION_CONTEXT)Context;
PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(context->Device);
UNREFERENCED_PARAMETER(Target);
UNREFERENCED_PARAMETER(Params);
// If this is an execute srb, then check the return status and make sure.
// the queue is not frozen.
if (context->Srb.Function == SRB_FUNCTION_EXECUTE_SCSI)
{
// Check for a frozen queue.
if (context->Srb.SrbStatus & SRB_STATUS_QUEUE_FROZEN)
{
// Unfreeze the queue getting the device object from the context.
DeviceReleaseQueue(context->Device);
}
}
// free port-allocated sense buffer if we can detect
//
if (PORT_ALLOCATED_SENSE(deviceExtension, &context->Srb))
{
FREE_PORT_ALLOCATED_SENSE_BUFFER(deviceExtension, &context->Srb);
}
FREE_POOL(context);
WdfObjectDelete(Request);
} // end DeviceAsynchronousCompletion()
VOID
DeviceReleaseQueue(
_In_ WDFDEVICE Device
)
/*++
Routine Description:
This routine issues an internal device control command
to the port driver to release a frozen queue. The call
is issued asynchronously as DeviceReleaseQueue will be invoked
from the IO completion DPC (and will have no context to
wait for a synchronous call to complete).
This routine must be called with the remove lock held.
Arguments:
Device - The functional device object for the device with the frozen queue.
Return Value:
None.
--*/
{
PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device);
PSCSI_REQUEST_BLOCK srb = NULL;
KIRQL currentIrql;
// we raise irql seperately so we're not swapped out or suspended
// while holding the release queue irp in this routine. this lets
// us release the spin lock before lowering irql.
KeRaiseIrql(DISPATCH_LEVEL, ¤tIrql);
WdfSpinLockAcquire(deviceExtension->ReleaseQueueSpinLock);
if (deviceExtension->ReleaseQueueInProgress)
{
// Someone is already doing this work - just set the flag to indicate that
// we need to release the queue again.
deviceExtension->ReleaseQueueNeeded = TRUE;
WdfSpinLockRelease(deviceExtension->ReleaseQueueSpinLock);
KeLowerIrql(currentIrql);
return;
}
// Mark that there is a release queue in progress and drop the spinlock.
deviceExtension->ReleaseQueueInProgress = TRUE;
WdfSpinLockRelease(deviceExtension->ReleaseQueueSpinLock);
srb = &(deviceExtension->ReleaseQueueSrb);
// Optical media are removable, so we just flush the queue. This will also release it.
srb->Function = SRB_FUNCTION_FLUSH_QUEUE;
srb->OriginalRequest = WdfRequestWdmGetIrp(deviceExtension->ReleaseQueueRequest);
// Set a CompletionRoutine callback function.
WdfRequestSetCompletionRoutine(deviceExtension->ReleaseQueueRequest,
DeviceReleaseQueueCompletion,
Device);
// Send the request. If an error occurs, complete the request.
RequestSend(deviceExtension,
deviceExtension->ReleaseQueueRequest,
deviceExtension->IoTarget,
WDF_REQUEST_SEND_OPTION_IGNORE_TARGET_STATE,
NULL);
KeLowerIrql(currentIrql);
return;
} // end DeviceReleaseQueue()
VOID
DeviceReleaseQueueCompletion(
_In_ WDFREQUEST Request,
_In_ WDFIOTARGET Target,
_In_ PWDF_REQUEST_COMPLETION_PARAMS Params,
_In_ WDFCONTEXT Context
)
/*++
Routine Description:
This routine is called when an asynchronous release queue request which
was issused in DeviceReleaseQueue completes. This routine prepares for
the next release queue request and resends it if necessary.
Arguments:
Request - The completed request.
Target - IoTarget object
Params - Completion parameters
Context - WDFDEVICE object handle.
Return Value:
None.
--*/
{
NTSTATUS status;
WDFDEVICE device = Context;
PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(device);
BOOLEAN releaseQueueNeeded = FALSE;
WDF_REQUEST_REUSE_PARAMS params = {0};
UNREFERENCED_PARAMETER(Target);
UNREFERENCED_PARAMETER(Params);
WDF_REQUEST_REUSE_PARAMS_INIT(¶ms,
WDF_REQUEST_REUSE_NO_FLAGS,
STATUS_SUCCESS);
// Grab the spinlock and clear the release queue in progress flag so others
// can run. Save (and clear) the state of the release queue needed flag
// so that we can issue a new release queue outside the spinlock.
WdfSpinLockAcquire(deviceExtension->ReleaseQueueSpinLock);
releaseQueueNeeded = deviceExtension->ReleaseQueueNeeded;
deviceExtension->ReleaseQueueNeeded = FALSE;
deviceExtension->ReleaseQueueInProgress = FALSE;
// Reuse the ReleaseQueueRequest for the next time.
status = WdfRequestReuse(Request,¶ms);
if (NT_SUCCESS(status))
{
// Preformat the ReleaseQueueRequest for the next time.
// This should always succeed because it was already preformatted once during device initialization
status = WdfIoTargetFormatRequestForInternalIoctlOthers(deviceExtension->IoTarget,
Request,
IOCTL_SCSI_EXECUTE_NONE,
deviceExtension->ReleaseQueueInputMemory,
NULL,
NULL,
NULL,
NULL,
NULL);
}
if (!NT_SUCCESS(status))
{
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL,
"DeviceReleaseQueueCompletion: WdfIoTargetFormatRequestForInternalIoctlOthers failed, %!STATUS!\n",
status));
}
RequestClearSendTime(Request);
WdfSpinLockRelease(deviceExtension->ReleaseQueueSpinLock);
// If we need a release queue then issue one now. Another processor may
// have already started one in which case we'll try to issue this one after
// it is done - but we should never recurse more than one deep.
if (releaseQueueNeeded)
{
DeviceReleaseQueue(device);
}
return;
} // DeviceReleaseQueueCompletion()
//
// 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
DevicePerfIncrementErrorCount(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension
)
{
PCDROM_PRIVATE_FDO_DATA fdoData = DeviceExtension->PrivateFdoData;
KIRQL oldIrql;
ULONG errors;
KeAcquireSpinLock(&fdoData->SpinLock, &oldIrql);
fdoData->Perf.SuccessfulIO = 0; // implicit interlock
errors = InterlockedIncrement((PLONG)&DeviceExtension->ErrorCount);
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(DeviceExtension->SrbFlags, SRB_FLAGS_NO_QUEUE_FREEZE);
CLEAR_FLAG(DeviceExtension->SrbFlags, SRB_FLAGS_QUEUE_ACTION_ENABLE);
SET_FLAG(DeviceExtension->SrbFlags, SRB_FLAGS_DISABLE_SYNCH_TRANSFER);
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL,
"PerfIncrementErrorCount: 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(DeviceExtension->SrbFlags, SRB_FLAGS_DISABLE_DISCONNECT);
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_GENERAL,
"PerfIncrementErrorCount: Too many errors; disabling disconnects.\n"));
}
KeReleaseSpinLock(&fdoData->SpinLock, oldIrql);
return;
}
_IRQL_requires_max_(APC_LEVEL)
PVOID
DeviceFindFeaturePage(
_In_reads_bytes_(Length) PGET_CONFIGURATION_HEADER FeatureBuffer,
_In_ ULONG const Length,
_In_ FEATURE_NUMBER const Feature
)
/*++
Routine Description:
find the specific feature page in the buffer
Arguments:
FeatureBuffer - buffer contains the device feature set.
Length - buffer length
Feature - the feature number looking for.
Return Value:
PVOID - pointer to the starting location of the specific feature in buffer.
--*/
{
PUCHAR buffer;
PUCHAR limit;
ULONG validLength;
PAGED_CODE();
if (Length < sizeof(GET_CONFIGURATION_HEADER) + sizeof(FEATURE_HEADER))
{
return NULL;
}
// Calculate the length of valid data available in the
// capabilities buffer from the DataLength field
REVERSE_BYTES(&validLength, FeatureBuffer->DataLength);
validLength += RTL_SIZEOF_THROUGH_FIELD(GET_CONFIGURATION_HEADER, DataLength);
// set limit to point to first illegal address
limit = (PUCHAR)FeatureBuffer;
limit += min(Length, validLength);
// set buffer to point to first page
buffer = FeatureBuffer->Data;
// loop through each page until we find the requested one, or
// until it's not safe to access the entire feature header
// (if equal, have exactly enough for the feature header)
while (buffer + sizeof(FEATURE_HEADER) <= limit)
{
PFEATURE_HEADER header = (PFEATURE_HEADER)buffer;
FEATURE_NUMBER thisFeature;
thisFeature = (header->FeatureCode[0] << 8) |
(header->FeatureCode[1]);
if (thisFeature == Feature)
{
PUCHAR temp;
// if don't have enough memory to safely access all the feature
// information, return NULL
temp = buffer;
temp += sizeof(FEATURE_HEADER);
temp += header->AdditionalLength;
if (temp > limit)
{
// this means the transfer was cut-off, an insufficiently
// small buffer was given, or other arbitrary error. since
// it's not safe to view the amount of data (even though
// the header is safe) in this feature, pretend it wasn't
// transferred at all...
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL,
"Feature %x exists, but not safe to access all its data. returning NULL\n",
Feature));
return NULL;
}
else
{
return buffer;
}
}
if ((header->AdditionalLength % 4) &&
!(Feature >= 0xff00 && Feature <= 0xffff))
{
return NULL;
}
buffer += sizeof(FEATURE_HEADER);
buffer += header->AdditionalLength;
}
return NULL;
}
_IRQL_requires_max_(APC_LEVEL)
VOID
DevicePrintAllFeaturePages(
_In_reads_bytes_(Usable) PGET_CONFIGURATION_HEADER Buffer,
_In_ ULONG const Usable
)
/*++
Routine Description:
print out all feature pages in the buffer
Arguments:
Buffer - buffer contains the device feature set.
Usable -
Return Value:
none
--*/
{
#if DBG
PFEATURE_HEADER header;
PAGED_CODE();
////////////////////////////////////////////////////////////////////////////////
// items expected to ALWAYS be current if they exist
////////////////////////////////////////////////////////////////////////////////
header = DeviceFindFeaturePage(Buffer, Usable, FeatureProfileList);
if (header != NULL) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: CurrentProfile %x "
"with %x bytes of data at %p\n",
Buffer->CurrentProfile[0] << 8 |
Buffer->CurrentProfile[1],
Usable, Buffer));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureCore);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"CORE Features"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureMorphing);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Morphing"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureRemovableMedium);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Removable Medium"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeaturePowerManagement);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Power Management"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureEmbeddedChanger);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Embedded Changer"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureMicrocodeUpgrade);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Microcode Update"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureTimeout);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Timeouts"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureLogicalUnitSerialNumber);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"LUN Serial Number"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureFirmwareDate);
if (header) {
ULONG featureSize = header->AdditionalLength;
featureSize += RTL_SIZEOF_THROUGH_FIELD(FEATURE_HEADER, AdditionalLength);
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Firmware Date"
));
if (featureSize >= RTL_SIZEOF_THROUGH_FIELD(FEATURE_DATA_FIRMWARE_DATE, Minute))
{
PFEATURE_DATA_FIRMWARE_DATE date = (PFEATURE_DATA_FIRMWARE_DATE)header;
// show date as "YYYY/MM/DD hh:mm", which is 18 chars (17+NULL)
UCHAR dateString[18] = { 0 };
dateString[ 0] = date->Year[0];
dateString[ 1] = date->Year[1];
dateString[ 2] = date->Year[2];
dateString[ 3] = date->Year[3];
dateString[ 4] = '/';
dateString[ 5] = date->Month[0];
dateString[ 6] = date->Month[1];
dateString[ 7] = '/';
dateString[ 8] = date->Day[0];
dateString[ 9] = date->Day[1];
dateString[10] = ' ';
dateString[11] = ' ';
dateString[12] = date->Hour[0];
dateString[13] = date->Hour[1];
dateString[14] = ':';
dateString[15] = date->Minute[0];
dateString[16] = date->Minute[1];
dateString[17] = 0;
// SECONDS IS NOT AVAILABLE ON EARLY IMPLEMENTATIONS -- ignore it
//dateString[17] = ':';
//dateString[18] = date->Seconds[0];
//dateString[19] = date->Seconds[1];
//dateString[20] = 0;
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: Firmware Date/Time %s (UTC)\n",
(PCSTR)dateString
));
}
}
////////////////////////////////////////////////////////////////////////////////
// items expected not to always be current
////////////////////////////////////////////////////////////////////////////////
header = DeviceFindFeaturePage(Buffer, Usable, FeatureWriteProtect);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_GENERAL,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Software Write Protect"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureRandomReadable);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Random Reads"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureMultiRead);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Multi-Read"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureCdRead);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"reading from CD-ROM/R/RW"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureDvdRead);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"DVD Structure Reads"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureRandomWritable);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Random Writes"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureIncrementalStreamingWritable);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Incremental Streaming Writing"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureSectorErasable);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Sector Erasable Media"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureFormattable);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Formatting"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureDefectManagement);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"defect management"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureWriteOnce);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Write Once Media"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureRestrictedOverwrite);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Restricted Overwrites"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureCdrwCAVWrite);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"CD-RW CAV recording"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureMrw);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Mount Rainier media"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureEnhancedDefectReporting);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Enhanced Defect Reporting"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureDvdPlusRW);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"DVD+RW media"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureRigidRestrictedOverwrite);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Rigid Restricted Overwrite"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureCdTrackAtOnce);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"CD Recording (Track At Once)"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureCdMastering);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"CD Recording (Mastering)"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureDvdRecordableWrite);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"DVD Recording (Mastering)"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureDDCDRead);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"DD CD Reading"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureDDCDRWrite);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"DD CD-R Writing"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureDDCDRWWrite);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"DD CD-RW Writing"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureLayerJumpRecording);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Layer Jump Recording"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureHDDVDRead);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"HD-DVD Reading"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureHDDVDWrite);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"HD-DVD Writing"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureSMART);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"S.M.A.R.T."
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureCDAudioAnalogPlay);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Analogue CD Audio Operations"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureDvdCSS);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"DVD CSS"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureRealTimeStreaming);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"Real-time Streaming Reads"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureDiscControlBlocks);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"DVD Disc Control Blocks"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureDvdCPRM);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"DVD CPRM"
));
}
header = DeviceFindFeaturePage(Buffer, Usable, FeatureAACS);
if (header) {
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_INIT,
"CdromGetConfiguration: %s %s\n",
(header->Current ?
"Currently supports" : "Is able to support"),
"AACS"
));
}
#else
PAGED_CODE();
UNREFERENCED_PARAMETER(Usable);
UNREFERENCED_PARAMETER(Buffer);
#endif // DBG
return;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
MediaReadCapacity(
_In_ WDFDEVICE Device
)
/*++
Routine Description:
Get media capacity
Arguments:
Device - the device that owns the media
Return Value:
NTSTATUS
--*/
{
NTSTATUS status;
SCSI_REQUEST_BLOCK srb;
PCDB cdb = NULL;
READ_CAPACITY_DATA capacityData;
PAGED_CODE();
RtlZeroMemory(&srb, sizeof(srb));
RtlZeroMemory(&capacityData, sizeof(capacityData));
cdb = (PCDB)(&srb.Cdb);
//Prepare SCSI command fields
srb.CdbLength = 10;
srb.TimeOutValue = CDROM_READ_CAPACITY_TIMEOUT;
cdb->CDB10.OperationCode = SCSIOP_READ_CAPACITY;
status = DeviceSendSrbSynchronously(Device,
&srb,
&capacityData,
sizeof(READ_CAPACITY_DATA),
FALSE,
NULL);
//Remember the result
if (!NT_SUCCESS(status))
{
//Set the BytesPerBlock to zero, this is for safe as if error happens this field should stay zero (no change).
//it will be treated as error case in MediaReadCapacityDataInterpret()
capacityData.BytesPerBlock = 0;
}
MediaReadCapacityDataInterpret(Device, &capacityData);
return status;
}
_IRQL_requires_max_(APC_LEVEL)
VOID
MediaReadCapacityDataInterpret(
_In_ WDFDEVICE Device,
_In_ PREAD_CAPACITY_DATA ReadCapacityBuffer
)
/*++
Routine Description:
Interpret media capacity and set corresponding fields in device context
Arguments:
Device - the device that owns the media
ReadCapacityBuffer - data buffer of capacity
Return Value:
none
--*/
{
PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device);
ULONG lastSector = 0;
ULONG bps = 0;
ULONG lastBit = 0;
ULONG bytesPerBlock = 0;
BOOLEAN errorHappened = FALSE;
PAGED_CODE();
NT_ASSERT(ReadCapacityBuffer);
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL,
"MediaReadCapacityDataInterpret: Entering\n"));
// Swizzle bytes from Read Capacity and translate into
// the necessary geometry information in the device extension.
bytesPerBlock = ReadCapacityBuffer->BytesPerBlock;
((PFOUR_BYTE)&bps)->Byte0 = ((PFOUR_BYTE)&bytesPerBlock)->Byte3;
((PFOUR_BYTE)&bps)->Byte1 = ((PFOUR_BYTE)&bytesPerBlock)->Byte2;
((PFOUR_BYTE)&bps)->Byte2 = ((PFOUR_BYTE)&bytesPerBlock)->Byte1;
((PFOUR_BYTE)&bps)->Byte3 = ((PFOUR_BYTE)&bytesPerBlock)->Byte0;
// Insure that bps is a power of 2.
// This corrects a problem with the HP 4020i CDR where it
// returns an incorrect number for bytes per sector.
if (!bps)
{
// Set disk geometry to default values (per ISO 9660).
bps = 2048;
errorHappened = TRUE;
}
else
{
lastBit = (ULONG)(-1);
while (bps)
{
lastBit++;
bps = (bps >> 1);
}
bps = (1 << lastBit);
}
deviceExtension->DiskGeometry.BytesPerSector = bps;
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL,
"MediaReadCapacityDataInterpret: Calculated bps %#x\n",
deviceExtension->DiskGeometry.BytesPerSector));
// Copy last sector in reverse byte order.
bytesPerBlock = ReadCapacityBuffer->LogicalBlockAddress;
((PFOUR_BYTE)&lastSector)->Byte0 = ((PFOUR_BYTE)&bytesPerBlock)->Byte3;
((PFOUR_BYTE)&lastSector)->Byte1 = ((PFOUR_BYTE)&bytesPerBlock)->Byte2;
((PFOUR_BYTE)&lastSector)->Byte2 = ((PFOUR_BYTE)&bytesPerBlock)->Byte1;
((PFOUR_BYTE)&lastSector)->Byte3 = ((PFOUR_BYTE)&bytesPerBlock)->Byte0;
// Calculate sector to byte shift.
WHICH_BIT(bps, deviceExtension->SectorShift);
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_GENERAL,
"MediaReadCapacityDataInterpret: Sector size is %d\n",
deviceExtension->DiskGeometry.BytesPerSector));
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL,
"MediaReadCapacityDataInterpret: Number of Sectors is %d\n",
lastSector + 1));
// Calculate media capacity in bytes.
if (errorHappened)
{
// Set disk geometry to default values (per ISO 9660).
deviceExtension->PartitionLength.QuadPart = (LONGLONG)(0x7fffffff);
}
else
{
deviceExtension->PartitionLength.QuadPart = (LONGLONG)(lastSector + 1);
deviceExtension->PartitionLength.QuadPart =
(deviceExtension->PartitionLength.QuadPart << deviceExtension->SectorShift);
}
// we've defaulted to 32/64 forever. don't want to change this now...
deviceExtension->DiskGeometry.TracksPerCylinder = 0x40;
deviceExtension->DiskGeometry.SectorsPerTrack = 0x20;
// Calculate number of cylinders.
deviceExtension->DiskGeometry.Cylinders.QuadPart = (LONGLONG)((lastSector + 1) / (32 * 64));
deviceExtension->DiskGeometry.MediaType = RemovableMedia;
return;
}
_IRQL_requires_max_(APC_LEVEL)
VOID
DevicePickDvdRegion(
_In_ WDFDEVICE Device
)
/*++
Routine Description:
pick a default dvd region
Arguments:
Device - Device Object
Return Value:
none
--*/
{
NTSTATUS status;
PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(Device);
// these five pointers all point to dvdReadStructure or part of
// its data, so don't deallocate them more than once!
PDVD_READ_STRUCTURE dvdReadStructure;
PDVD_COPY_PROTECT_KEY copyProtectKey;
PDVD_COPYRIGHT_DESCRIPTOR dvdCopyRight;
PDVD_RPC_KEY rpcKey;
PDVD_SET_RPC_KEY dvdRpcKey;
size_t bytesReturned = 0;
ULONG bufferLen = 0;
UCHAR mediaRegion = 0;
ULONG pickDvdRegion = 0;
ULONG defaultDvdRegion = 0;
ULONG dvdRegion = 0;
WDFKEY registryKey = NULL;
DECLARE_CONST_UNICODE_STRING(registryValueName, DVD_DEFAULT_REGION);
PAGED_CODE();
if ((pickDvdRegion = InterlockedExchange((PLONG)&deviceExtension->DeviceAdditionalData.PickDvdRegion, 0)) == 0)
{
// it was non-zero, so either another thread will do this, or
// we no longer need to pick a region
return;
}
bufferLen = max(
max(sizeof(DVD_DESCRIPTOR_HEADER) +
sizeof(DVD_COPYRIGHT_DESCRIPTOR),
sizeof(DVD_READ_STRUCTURE)
),
max(DVD_RPC_KEY_LENGTH,
DVD_SET_RPC_KEY_LENGTH
)
);
dvdReadStructure = (PDVD_READ_STRUCTURE)
ExAllocatePool2(POOL_FLAG_PAGED, bufferLen, DVD_TAG_DVD_REGION);
if (dvdReadStructure == NULL)
{
InterlockedExchange((PLONG)&deviceExtension->DeviceAdditionalData.PickDvdRegion, pickDvdRegion);
return;
}
copyProtectKey = (PDVD_COPY_PROTECT_KEY)dvdReadStructure;
dvdCopyRight = (PDVD_COPYRIGHT_DESCRIPTOR)
((PDVD_DESCRIPTOR_HEADER)dvdReadStructure)->Data;
// get the media region
RtlZeroMemory (dvdReadStructure, bufferLen);
dvdReadStructure->Format = DvdCopyrightDescriptor;
// Build and send a request for READ_KEY
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): Getting Copyright Descriptor\n",
Device));
status = ReadDvdStructure(deviceExtension,
NULL,
dvdReadStructure,
sizeof(DVD_READ_STRUCTURE),
dvdReadStructure,
sizeof(DVD_DESCRIPTOR_HEADER) + sizeof(DVD_COPYRIGHT_DESCRIPTOR),
&bytesReturned);
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): Got Copyright Descriptor %x\n",
Device, status));
if ((NT_SUCCESS(status)) &&
(dvdCopyRight->CopyrightProtectionType == 0x01))
{
// keep the media region bitmap around
// a 1 means ok to play
if (dvdCopyRight->RegionManagementInformation == 0xff)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): RegionManagementInformation "
"is set to dis-allow playback for all regions. This is "
"most likely a poorly authored disc. defaulting to all "
"region disc for purpose of choosing initial region\n",
Device));
dvdCopyRight->RegionManagementInformation = 0;
}
mediaRegion = ~dvdCopyRight->RegionManagementInformation;
}
else
{
// can't automatically pick a default region on a drive without media, so just exit
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): failed to auto-choose a region due to status %x getting copyright descriptor\n",
Device, status));
goto getout;
}
// get the device region
RtlZeroMemory (copyProtectKey, bufferLen);
copyProtectKey->KeyLength = DVD_RPC_KEY_LENGTH;
copyProtectKey->KeyType = DvdGetRpcKey;
// Build and send a request for READ_KEY for RPC key
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): Getting RpcKey\n",
Device));
status = DvdStartSessionReadKey(deviceExtension,
IOCTL_DVD_READ_KEY,
NULL,
copyProtectKey,
DVD_RPC_KEY_LENGTH,
copyProtectKey,
DVD_RPC_KEY_LENGTH,
&bytesReturned);
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): Got RpcKey %x\n",
Device, status));
if (!NT_SUCCESS(status))
{
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): failed to get RpcKey from "
"a DVD Device\n", Device));
goto getout;
}
// so we now have what we can get for the media region and the
// drive region. we will not set a region if the drive has one
// set already (mask is not all 1's), nor will we set a region
// if there are no more user resets available.
rpcKey = (PDVD_RPC_KEY)copyProtectKey->KeyData;
if (rpcKey->RegionMask != 0xff)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): not picking a region since "
"it is already chosen\n", Device));
goto getout;
}
if (rpcKey->UserResetsAvailable <= 1)
{
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): not picking a region since "
"only one change remains\n", Device));
goto getout;
}
// OOBE sets this key based upon the system locale
status = WdfDriverOpenParametersRegistryKey(WdfGetDriver(),
KEY_READ,
WDF_NO_OBJECT_ATTRIBUTES,
®istryKey);
if (NT_SUCCESS(status))
{
status = WdfRegistryQueryULong(registryKey,
®istryValueName,
&defaultDvdRegion);
WdfRegistryClose(registryKey);
}
if (!NT_SUCCESS(status))
{
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): failed to read registry value due to status %x\n",
Device, status));
// by default the default Dvd region is 0
defaultDvdRegion = 0;
status = STATUS_SUCCESS;
}
if (defaultDvdRegion > DVD_MAX_REGION)
{
// the registry has a bogus default
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): registry has a bogus default "
"region value of %x\n", Device, defaultDvdRegion));
defaultDvdRegion = 0;
}
// if defaultDvdRegion == 0, it means no default.
// we will select the initial dvd region for the user
if ((defaultDvdRegion != 0) &&
(mediaRegion & (1 << (defaultDvdRegion - 1))))
{
// first choice:
// the media has region that matches
// the default dvd region.
dvdRegion = (1 << (defaultDvdRegion - 1));
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): Choice #1: media matches "
"drive's default, chose region %x\n", Device, dvdRegion));
}
else if (mediaRegion)
{
// second choice:
// pick the lowest region number from the media
UCHAR mask = 1;
dvdRegion = 0;
while (mediaRegion && !dvdRegion)
{
// pick the lowest bit
dvdRegion = mediaRegion & mask;
mask <<= 1;
}
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): Choice #2: choosing lowest "
"media region %x\n", Device, dvdRegion));
}
else if (defaultDvdRegion)
{
// third choice:
// default dvd region from the dvd class installer
dvdRegion = (1 << (defaultDvdRegion - 1));
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): Choice #3: using default "
"region for this install %x\n", Device, dvdRegion));
}
else
{
// unable to pick one for the user -- this should rarely
// happen, since the proppage dvd class installer sets
// the key based upon the system locale
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): Choice #4: failed to choose "
"a media region\n", Device));
goto getout;
}
// now that we've chosen a region, set the region by sending the
// appropriate request to the drive
RtlZeroMemory (copyProtectKey, bufferLen);
copyProtectKey->KeyLength = DVD_SET_RPC_KEY_LENGTH;
copyProtectKey->KeyType = DvdSetRpcKey;
dvdRpcKey = (PDVD_SET_RPC_KEY)copyProtectKey->KeyData;
dvdRpcKey->PreferredDriveRegionCode = (UCHAR)~dvdRegion;
// Build and send request for SEND_KEY
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): Sending new Rpc Key to region %x\n",
Device, dvdRegion));
status = DvdSendKey(deviceExtension,
NULL,
copyProtectKey,
DVD_SET_RPC_KEY_LENGTH,
&bytesReturned);
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL,
"DevicePickDvdRegion (%p): Sent new Rpc Key %x\n",
Device, status));
if (!NT_SUCCESS(status))
{
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_IOCTL, "DevicePickDvdRegion (%p): unable to set dvd initial "
" region code (%x)\n", Device, status));
}
else
{
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_IOCTL, "DevicePickDvdRegion (%p): Successfully set dvd "
"initial region\n", Device));
pickDvdRegion = 0;
}
getout:
if (dvdReadStructure)
{
FREE_POOL(dvdReadStructure);
}
// update the new PickDvdRegion value
InterlockedExchange((PLONG)&deviceExtension->DeviceAdditionalData.PickDvdRegion, pickDvdRegion);
return;
}
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
DeviceRegisterInterface(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_ CDROM_DEVICE_INTERFACES InterfaceType
)
/*++
Routine Description:
used to register device class interface or mount device interface
Arguments:
DeviceExtension - device context
InterfaceType - interface type to be registered.
Return Value:
NTSTATUS
--*/
{
NTSTATUS status;
WDFSTRING string = NULL;
GUID* interfaceGuid = NULL;
PUNICODE_STRING savingString = NULL;
BOOLEAN setRestricted = FALSE;
UNICODE_STRING localString;
PAGED_CODE();
//Get parameters
switch(InterfaceType)
{
case CdRomDeviceInterface:
interfaceGuid = (LPGUID)&GUID_DEVINTERFACE_CDROM;
setRestricted = TRUE;
savingString = &localString;
break;
case MountedDeviceInterface:
interfaceGuid = (LPGUID)&MOUNTDEV_MOUNTED_DEVICE_GUID;
savingString = &(DeviceExtension->MountedDeviceInterfaceName);
break;
default:
return STATUS_INVALID_PARAMETER;
}
status = WdfDeviceCreateDeviceInterface(DeviceExtension->Device,
interfaceGuid,
NULL);
if (!NT_SUCCESS(status))
{
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_INIT,
"DeviceRegisterInterface: Unable to register cdrom "
"DCA for fdo %p type: %s [%lx]\n",
DeviceExtension->Device,
(InterfaceType == CdRomDeviceInterface)? "CdRom Interface" : "Mounted Device Interface",
status));
}
// Retrieve interface string
if (NT_SUCCESS(status))
{
// The string object will be released when its parent object is released.
WDF_OBJECT_ATTRIBUTES attributes;
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
attributes.ParentObject = DeviceExtension->Device;
status = WdfStringCreate(WDF_NO_OBJECT_ATTRIBUTES,
NULL,
&string);
}
if (NT_SUCCESS(status))
{
status = WdfDeviceRetrieveDeviceInterfaceString(DeviceExtension->Device,
interfaceGuid,
NULL,
string);
}
if (NT_SUCCESS(status))
{
WdfStringGetUnicodeString(string, savingString);
if (setRestricted) {
WdfObjectDelete(string);
}
}
return status;
} // end DeviceRegisterInterface()
VOID
DeviceRestoreDefaultSpeed(
_In_ WDFWORKITEM WorkItem
)
/*++
Routine Description:
This workitem is called on a media change when the CDROM device
speed should be restored to the default value.
Arguments:
Fdo - Supplies the device object for the CDROM device.
WorkItem - Supplies the pointer to the workitem.
Return Value:
None
--*/
{
NTSTATUS status;
WDFDEVICE device = WdfWorkItemGetParentObject(WorkItem);
PCDROM_DEVICE_EXTENSION deviceExtension = DeviceGetExtension(device);
PPERFORMANCE_DESCRIPTOR perfDescriptor;
ULONG transferLength = sizeof(PERFORMANCE_DESCRIPTOR);
SCSI_REQUEST_BLOCK srb = {0};
PCDB cdb = (PCDB)srb.Cdb;
PAGED_CODE();
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL, "DeviceRestoreDefaultSpeed: Restore device speed for %p\n", device));
perfDescriptor = ExAllocatePool2(POOL_FLAG_NON_PAGED | POOL_FLAG_CACHE_ALIGNED,
transferLength,
CDROM_TAG_STREAM);
if (perfDescriptor == NULL)
{
return;
}
RtlZeroMemory(perfDescriptor, transferLength);
perfDescriptor->RestoreDefaults = TRUE;
srb.TimeOutValue = deviceExtension->TimeOutValue;
srb.CdbLength = 12;
cdb->SET_STREAMING.OperationCode = SCSIOP_SET_STREAMING;
REVERSE_BYTES_SHORT(&cdb->SET_STREAMING.ParameterListLength, &transferLength);
status = DeviceSendSrbSynchronously(device,
&srb,
perfDescriptor,
transferLength,
TRUE,
NULL);
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL,
"DeviceRestoreDefaultSpeed: Set Streaming command completed with status: 0x%X\n", status));
FREE_POOL(perfDescriptor);
WdfObjectDelete(WorkItem);
return;
}
// custom string match -- careful!
_IRQL_requires_max_(APC_LEVEL)
BOOLEAN
StringsAreMatched(
_In_opt_z_ PCHAR StringToMatch,
_In_z_ PCHAR TargetString
)
/*++
Routine Description:
compares if two strings are identical
Arguments:
StringToMatch - source string.
TargetString - target string.
Return Value:
BOOLEAN - TRUE (identical); FALSE (not match)
--*/
{
size_t length;
PAGED_CODE();
NT_ASSERT(TargetString);
// if no match requested, return TRUE
if (StringToMatch == NULL)
{
return TRUE;
}
// cache the string length for efficiency
length = 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);
}
NTSTATUS
RequestSetContextFields(
_In_ WDFREQUEST Request,
_In_ PSYNC_HANDLER Handler
)
/*++
Routine Description:
set the request object context fields
Arguments:
Request - request object.
Handler - the function that finally handles this request.
Return Value:
NTSTATUS
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PCDROM_REQUEST_CONTEXT requestContext = RequestGetContext(Request);
PKEVENT syncEvent = NULL;
syncEvent = ExAllocatePool2(POOL_FLAG_NON_PAGED,
sizeof(KEVENT),
CDROM_TAG_SYNC_EVENT);
if (syncEvent == NULL)
{
// memory allocation failed.
status = STATUS_INSUFFICIENT_RESOURCES;
}
else
{
// now, put the special synchronization information into the context
requestContext->SyncRequired = TRUE;
requestContext->SyncEvent = syncEvent;
requestContext->SyncCallback = Handler;
status = STATUS_SUCCESS;
}
return status;
}
NTSTATUS
RequestDuidGetDeviceIdProperty(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_ WDFREQUEST Request,
_In_ WDF_REQUEST_PARAMETERS RequestParameters,
_Out_ size_t * DataLength
)
/*++
Routine Description:
Arguments:
DeviceExtension - device context
Request - request object.
RequestParameters - request parameter
DataLength - transferred data length.
Return Value:
NTSTATUS
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PSTORAGE_DEVICE_ID_DESCRIPTOR deviceIdDescriptor = NULL;
PSTORAGE_DESCRIPTOR_HEADER descHeader = NULL;
STORAGE_PROPERTY_ID propertyId = StorageDeviceIdProperty;
*DataLength = 0;
// Get the VPD page 83h data.
status = DeviceRetrieveDescriptor(DeviceExtension->Device,
&propertyId,
(PSTORAGE_DESCRIPTOR_HEADER*)&deviceIdDescriptor);
if (NT_SUCCESS(status) && (deviceIdDescriptor == NULL))
{
status = STATUS_NOT_FOUND;
}
if (NT_SUCCESS(status))
{
status = WdfRequestRetrieveOutputBuffer(Request,
RequestParameters.Parameters.DeviceIoControl.OutputBufferLength,
&descHeader,
NULL);
}
if (NT_SUCCESS(status))
{
PSTORAGE_DEVICE_UNIQUE_IDENTIFIER storageDuid = NULL;
ULONG offset = descHeader->Size;
PUCHAR dest = (PUCHAR)descHeader + offset;
size_t outputBufferSize;
outputBufferSize = RequestParameters.Parameters.DeviceIoControl.OutputBufferLength;
// Adjust required size and potential destination location.
status = RtlULongAdd(descHeader->Size, deviceIdDescriptor->Size, &descHeader->Size);
if (NT_SUCCESS(status) &&
(outputBufferSize < descHeader->Size))
{
// Output buffer is too small. Return error and make sure
// the caller gets info about required buffer size.
*DataLength = descHeader->Size;
status = STATUS_BUFFER_OVERFLOW;
}
if (NT_SUCCESS(status))
{
storageDuid = (PSTORAGE_DEVICE_UNIQUE_IDENTIFIER)descHeader;
storageDuid->StorageDeviceIdOffset = offset;
RtlCopyMemory(dest,
deviceIdDescriptor,
deviceIdDescriptor->Size);
*DataLength = storageDuid->Size;
status = STATUS_SUCCESS;
}
FREE_POOL(deviceIdDescriptor);
}
return status;
}
NTSTATUS
RequestDuidGetDeviceProperty(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_ WDFREQUEST Request,
_In_ WDF_REQUEST_PARAMETERS RequestParameters,
_Out_ size_t * DataLength
)
/*++
Routine Description:
Arguments:
DeviceExtension - device context
Request - request object.
RequestParameters - request parameter
DataLength - transferred data length.
Return Value:
NTSTATUS
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PSTORAGE_DEVICE_DESCRIPTOR deviceDescriptor = DeviceExtension->DeviceDescriptor;
PSTORAGE_DESCRIPTOR_HEADER descHeader = NULL;
PSTORAGE_DEVICE_UNIQUE_IDENTIFIER storageDuid;
PUCHAR dest = NULL;
if (deviceDescriptor == NULL)
{
status = STATUS_NOT_FOUND;
}
if (NT_SUCCESS(status))
{
status = WdfRequestRetrieveOutputBuffer(Request,
RequestParameters.Parameters.DeviceIoControl.OutputBufferLength,
&descHeader,
NULL);
}
if (NT_SUCCESS(status) &&
(deviceDescriptor->SerialNumberOffset == 0))
{
status = STATUS_NOT_FOUND;
}
// Use this info only if serial number is available.
if (NT_SUCCESS(status))
{
ULONG offset = descHeader->Size;
size_t outputBufferSize = RequestParameters.Parameters.DeviceIoControl.OutputBufferLength;
// Adjust required size and potential destination location.
dest = (PUCHAR)descHeader + offset;
status = RtlULongAdd(descHeader->Size, deviceDescriptor->Size, &descHeader->Size);
if (NT_SUCCESS(status) &&
(outputBufferSize < descHeader->Size))
{
// Output buffer is too small. Return error and make sure
// the caller get info about required buffer size.
*DataLength = descHeader->Size;
status = STATUS_BUFFER_OVERFLOW;
}
if (NT_SUCCESS(status))
{
storageDuid = (PSTORAGE_DEVICE_UNIQUE_IDENTIFIER)descHeader;
storageDuid->StorageDeviceOffset = offset;
RtlCopyMemory(dest,
deviceDescriptor,
deviceDescriptor->Size);
*DataLength = storageDuid->Size;
status = STATUS_SUCCESS;
}
}
return status;
}
_IRQL_requires_max_(APC_LEVEL)
ULONG
DeviceRetrieveModeSenseUsingScratch(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_reads_bytes_(Length) PCHAR ModeSenseBuffer,
_In_ ULONG Length,
_In_ UCHAR PageCode,
_In_ UCHAR PageControl
)
/*++
Routine Description:
retrieve mode sense informaiton of the device
Arguments:
DeviceExtension - device context
ModeSenseBuffer - buffer to savee the mode sense info.
Length - buffer length
PageCode - .
PageControl -
Return Value:
ULONG - transferred data length
--*/
{
NTSTATUS status = STATUS_SUCCESS;
ULONG transferSize = min(Length, DeviceExtension->ScratchContext.ScratchBufferSize);
CDB cdb;
PAGED_CODE();
ScratchBuffer_BeginUse(DeviceExtension);
RtlZeroMemory(&cdb, sizeof(CDB));
// Set up the CDB
cdb.MODE_SENSE.OperationCode = SCSIOP_MODE_SENSE;
cdb.MODE_SENSE.PageCode = PageCode;
cdb.MODE_SENSE.Pc = PageControl;
cdb.MODE_SENSE.AllocationLength = (UCHAR)transferSize;
status = ScratchBuffer_ExecuteCdb(DeviceExtension, NULL, transferSize, TRUE, &cdb, 6);
if (NT_SUCCESS(status))
{
transferSize = min(Length, DeviceExtension->ScratchContext.ScratchSrb->DataTransferLength);
RtlCopyMemory(ModeSenseBuffer,
DeviceExtension->ScratchContext.ScratchBuffer,
transferSize);
}
ScratchBuffer_EndUse(DeviceExtension);
return transferSize;
}
_IRQL_requires_max_(APC_LEVEL)
PVOID
ModeSenseFindSpecificPage(
_In_reads_bytes_(Length) PCHAR ModeSenseBuffer,
_In_ size_t Length,
_In_ UCHAR PageMode,
_In_ BOOLEAN Use6BytesCdb
)
/*++
Routine Description:
This routine scans through the mode sense data and finds the requested
mode sense page code.
Arguments:
ModeSenseBuffer - Supplies a pointer to the mode sense data.
Length - Indicates the length of valid data.
PageMode - Supplies the page mode to be searched for.
Use6BytesCdb - Indicates whether 6 or 10 byte mode sense was used.
Return Value:
A pointer to the the requested mode page. If the mode page was not found
then NULL is return.
--*/
{
PCHAR limit;
ULONG parameterHeaderLength;
PVOID result = NULL;
PAGED_CODE();
limit = ModeSenseBuffer + Length;
parameterHeaderLength = (Use6BytesCdb)
? sizeof(MODE_PARAMETER_HEADER)
: sizeof(MODE_PARAMETER_HEADER10);
if (Length >= parameterHeaderLength)
{
PMODE_PARAMETER_HEADER10 modeParam10;
ULONG blockDescriptorLength;
// Skip the mode select header and block descriptors.
if (Use6BytesCdb)
{
blockDescriptorLength = ((PMODE_PARAMETER_HEADER)ModeSenseBuffer)->BlockDescriptorLength;
}
else
{
modeParam10 = (PMODE_PARAMETER_HEADER10) ModeSenseBuffer;
blockDescriptorLength = modeParam10->BlockDescriptorLength[1];
}
ModeSenseBuffer += parameterHeaderLength + blockDescriptorLength;
// ModeSenseBuffer now points at pages. Walk the pages looking for the
// requested page until the limit is reached.
while (ModeSenseBuffer +
RTL_SIZEOF_THROUGH_FIELD(MODE_DISCONNECT_PAGE, PageLength) < limit)
{
if (((PMODE_DISCONNECT_PAGE) ModeSenseBuffer)->PageCode == PageMode)
{
// found the mode page. make sure it's safe to touch it all
// before returning the pointer to caller
if (ModeSenseBuffer + ((PMODE_DISCONNECT_PAGE)ModeSenseBuffer)->PageLength > limit)
{
// Return NULL since the page is not safe to access in full
result = NULL;
}
else
{
result = ModeSenseBuffer;
}
break;
}
// Advance to the next page which is 4-byte-aligned offset after this page.
ModeSenseBuffer += ((PMODE_DISCONNECT_PAGE) ModeSenseBuffer)->PageLength +
RTL_SIZEOF_THROUGH_FIELD(MODE_DISCONNECT_PAGE, PageLength);
}
}
return result;
} // end ModeSenseFindSpecificPage()
_IRQL_requires_max_(PASSIVE_LEVEL)
NTSTATUS
PerformEjectionControl(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_ WDFREQUEST Request,
_In_ MEDIA_LOCK_TYPE LockType,
_In_ BOOLEAN Lock
)
/*++
Routine Description:
ejection control process
Arguments:
DeviceExtension - device extension
Request - WDF request to be used for communication with the device
LockType - the type of lock
Lock - if TRUE, lock the device; if FALSE, unlock it
Return Value:
NTSTATUS
--*/
{
NTSTATUS status;
PFILE_OBJECT_CONTEXT fileObjectContext = NULL;
SCSI_REQUEST_BLOCK srb;
PCDB cdb = NULL;
LONG newLockCount = 0;
LONG newProtectedLockCount = 0;
LONG newInternalLockCount = 0;
LONG newFileLockCount = 0;
BOOLEAN countChanged = FALSE;
BOOLEAN previouslyLocked = FALSE;
BOOLEAN nowLocked = FALSE;
PAGED_CODE();
// Prevent race conditions while working with lock counts
status = WdfWaitLockAcquire(DeviceExtension->EjectSynchronizationLock, NULL);
if (!NT_SUCCESS(status))
{
NT_ASSERT(FALSE);
}
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL,
"PerformEjectionControl: "
"Received request for %s lock type\n",
LockTypeStrings[LockType]
));
// If this is a "secured" request, retrieve the file object context
if (LockType == SecureMediaLock)
{
WDFFILEOBJECT fileObject = NULL;
fileObject = WdfRequestGetFileObject(Request);
if (fileObject == NULL)
{
status = STATUS_INVALID_HANDLE;
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL,
"FileObject does not match to the one in IRP_MJ_CREATE, KMDF returns NULL\n"));
goto Exit;
}
fileObjectContext = FileObjectGetContext(fileObject);
NT_ASSERT(fileObjectContext != NULL);
}
// Lock counts should never fall below 0
NT_ASSERT(DeviceExtension->LockCount >= 0);
NT_ASSERT(DeviceExtension->ProtectedLockCount >= 0);
NT_ASSERT(DeviceExtension->InternalLockCount >= 0);
// Get the current lock counts
newLockCount = DeviceExtension->LockCount;
newProtectedLockCount = DeviceExtension->ProtectedLockCount;
newInternalLockCount = DeviceExtension->InternalLockCount;
if (fileObjectContext)
{
// fileObjectContext->LockCount is ULONG and should always >= 0
newFileLockCount = fileObjectContext->LockCount;
}
// Determine which lock counts need to be changed and how
if (Lock && LockType == SimpleMediaLock)
{
newLockCount++;
countChanged = TRUE;
}
else if (Lock && LockType == SecureMediaLock)
{
newFileLockCount++;
newProtectedLockCount++;
countChanged = TRUE;
}
else if (Lock && LockType == InternalMediaLock)
{
newInternalLockCount++;
countChanged = TRUE;
}
else if (!Lock && LockType == SimpleMediaLock)
{
if (newLockCount != 0)
{
newLockCount--;
countChanged = TRUE;
}
}
else if (!Lock && LockType == SecureMediaLock)
{
if ( (newFileLockCount == 0) || (newProtectedLockCount == 0) )
{
status = STATUS_INVALID_DEVICE_STATE;
goto Exit;
}
newFileLockCount--;
newProtectedLockCount--;
countChanged = TRUE;
}
else if (!Lock && LockType == InternalMediaLock)
{
NT_ASSERT(newInternalLockCount != 0);
newInternalLockCount--;
countChanged = TRUE;
}
if ( (DeviceExtension->LockCount != 0) ||
(DeviceExtension->ProtectedLockCount != 0) ||
(DeviceExtension->InternalLockCount != 0) )
{
previouslyLocked = TRUE;
}
if ( (newLockCount != 0) ||
(newProtectedLockCount != 0) ||
(newInternalLockCount != 0) )
{
nowLocked = TRUE;
}
// Only send command down to device when necessary
if (previouslyLocked != nowLocked)
{
// Compose and send the PREVENT ALLOW MEDIA REMOVAL command.
RtlZeroMemory(&srb, sizeof(SCSI_REQUEST_BLOCK));
srb.CdbLength = 6;
srb.TimeOutValue = DeviceExtension->TimeOutValue;
cdb = (PCDB)&srb.Cdb;
cdb->MEDIA_REMOVAL.OperationCode = SCSIOP_MEDIUM_REMOVAL;
cdb->MEDIA_REMOVAL.Prevent = Lock;
status = DeviceSendSrbSynchronously(DeviceExtension->Device,
&srb,
NULL,
0,
FALSE,
Request);
}
Exit:
// Store the updated lock counts on success
if (countChanged && NT_SUCCESS(status))
{
DeviceExtension->LockCount = newLockCount;
DeviceExtension->ProtectedLockCount = newProtectedLockCount;
DeviceExtension->InternalLockCount = newInternalLockCount;
if (fileObjectContext)
{
fileObjectContext->LockCount = newFileLockCount;
}
}
WdfWaitLockRelease(DeviceExtension->EjectSynchronizationLock);
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL,
"PerformEjectionControl: %!STATUS!, "
"Count Changed: %d, Command Sent: %d, "
"Current Counts: Internal: %x Secure: %x Simple: %x\n",
status,
countChanged,
previouslyLocked != nowLocked,
DeviceExtension->InternalLockCount,
DeviceExtension->ProtectedLockCount,
DeviceExtension->LockCount
));
return status;
}
_IRQL_requires_max_(APC_LEVEL)
NTSTATUS
DeviceUnlockExclusive(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_ WDFFILEOBJECT FileObject,
_In_ BOOLEAN IgnorePreviousMediaChanges
)
/*++
Routine Description:
to unlock the exclusive lock
Arguments:
DeviceExtension - device context
FileObject - file object that currently holds the lock
IgnorePreviousMediaChanges - if TRUE, ignore previously accumulated media changes
Return Value:
NTSTATUS
--*/
{
NTSTATUS status = STATUS_SUCCESS;
PCDROM_DATA cdData = &DeviceExtension->DeviceAdditionalData;
PMEDIA_CHANGE_DETECTION_INFO info = DeviceExtension->MediaChangeDetectionInfo;
BOOLEAN ANPending = 0;
LONG requestInUse = 0;
PAGED_CODE();
if (!EXCLUSIVE_MODE(cdData))
{
// Device is not locked for exclusive access.
// Can not process unlock request.
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL,
"RequestHandleExclusiveAccessUnlockDevice: Device not locked for exclusive access, can't unlock device.\n"));
status = STATUS_INVALID_DEVICE_REQUEST;
}
else if (!EXCLUSIVE_OWNER(cdData, FileObject))
{
// Request not from the exclusive owner, can't unlock the device.
TracePrint((TRACE_LEVEL_ERROR, TRACE_FLAG_IOCTL,
"RequestHandleExclusiveAccessUnlockDevice: Unable to unlock device, invalid file object\n"));
status = STATUS_INVALID_HANDLE;
}
if (NT_SUCCESS(status))
{
// Unless we were explicitly requested not to do so, generate a media removal notification
// followed by a media arrival notification similar to volume lock/unlock file system events.
if (!IgnorePreviousMediaChanges)
{
MEDIA_CHANGE_DETECTION_STATE previousMediaState = MediaUnknown;
// Change the media state to "unavailable", which will cause a removal notification if the media
// was previously present. At the same time, store the previous state in previousMediaState.
DeviceSetMediaChangeStateEx(DeviceExtension, MediaUnavailable, &previousMediaState);
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_IOCTL,
"DeviceUnlockExclusive: Changing the media state to MediaUnavailable\n"));
// Restore the previous media state, which will cause a media arrival notification if the media
// was originally present.
DeviceSetMediaChangeStateEx(DeviceExtension, previousMediaState, NULL);
}
// Set DO_VERIFY_VOLUME so that the file system will remount on it.
if (IsVolumeMounted(DeviceExtension->DeviceObject))
{
SET_FLAG(DeviceExtension->DeviceObject->Flags, DO_VERIFY_VOLUME);
}
// Set MMC state to update required
cdData->Mmc.WriteAllowed = FALSE;
cdData->Mmc.UpdateState = CdromMmcUpdateRequired;
// Send unlock notification
DeviceSendNotification(DeviceExtension,
&GUID_IO_CDROM_EXCLUSIVE_UNLOCK,
0,
NULL);
InterlockedExchangePointer((PVOID)&cdData->ExclusiveOwner, NULL);
if ((info != NULL) && (info->AsynchronousNotificationSupported != FALSE))
{
ANPending = info->ANSignalPendingDueToExclusiveLock;
info->ANSignalPendingDueToExclusiveLock = FALSE;
if ((ANPending != FALSE) && (info->MediaChangeDetectionDisableCount == 0))
{
// if the request is not in use, mark it as such.
requestInUse = InterlockedCompareExchange((PLONG)&info->MediaChangeRequestInUse, 1, 0);
if (requestInUse == 0)
{
// The last MCN finished. ok to issue the new one.
RequestSetupMcnSyncIrp(DeviceExtension);
// The irp will go into KMDF framework and a request will be created there to represent it.
IoCallDriver(DeviceExtension->DeviceObject, info->MediaChangeSyncIrp);
}
}
}
}
return status;
}
VOID
RequestCompletion(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_ WDFREQUEST Request,
_In_ NTSTATUS Status,
_In_ ULONG_PTR Information
)
{
#ifdef DBG
ULONG ioctlCode = 0;
WDF_REQUEST_PARAMETERS requestParameters;
// Get the Request parameters
WDF_REQUEST_PARAMETERS_INIT(&requestParameters);
WdfRequestGetParameters(Request, &requestParameters);
if (requestParameters.Type == WdfRequestTypeDeviceControl)
{
ioctlCode = requestParameters.Parameters.DeviceIoControl.IoControlCode;
if (requestParameters.Parameters.DeviceIoControl.IoControlCode != IOCTL_MCN_SYNC_FAKE_IOCTL)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL,
"Request complete - IOCTL - code: %X; Status: %X; Information: %X\n",
ioctlCode,
Status,
(ULONG)Information));
}
else
{
TracePrint((TRACE_LEVEL_VERBOSE, TRACE_FLAG_GENERAL,
"Request complete - IOCTL - code: %X; Status: %X; Information: %X\n",
ioctlCode,
Status,
(ULONG)Information));
}
}
else if (requestParameters.Type == WdfRequestTypeRead)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL,
"Request complete - READ - Starting Offset: %X; Length: %X; Transferred Length: %X; Status: %X\n",
(ULONG)requestParameters.Parameters.Read.DeviceOffset,
(ULONG)requestParameters.Parameters.Read.Length,
(ULONG)Information,
Status));
}
else if (requestParameters.Type == WdfRequestTypeWrite)
{
TracePrint((TRACE_LEVEL_INFORMATION, TRACE_FLAG_GENERAL,
"Request complete - WRITE - Starting Offset: %X; Length: %X; Transferred Length: %X; Status: %X\n",
(ULONG)requestParameters.Parameters.Write.DeviceOffset,
(ULONG)requestParameters.Parameters.Write.Length,
(ULONG)Information,
Status));
}
#endif
if (IoIsErrorUserInduced(Status))
{
PIRP irp = WdfRequestWdmGetIrp(Request);
if (irp->Tail.Overlay.Thread)
{
IoSetHardErrorOrVerifyDevice(irp, DeviceExtension->DeviceObject);
}
}
if (!NT_SUCCESS(Status) && DeviceExtension->SurpriseRemoved == TRUE)
{
// IMAPI expects ERROR_DEV_NOT_EXISTS if recorder has been surprised removed,
// or it will retry WRITE commands for up to 3 minutes
// CDROM behavior should be consistent for all requests, including SCSI pass-through
Status = STATUS_DEVICE_DOES_NOT_EXIST;
}
WdfRequestCompleteWithInformation(Request, Status, Information);
return;
}
VOID
RequestDummyCompletionRoutine(
_In_ WDFREQUEST Request,
_In_ WDFIOTARGET Target,
_In_ PWDF_REQUEST_COMPLETION_PARAMS Params,
_In_ WDFCONTEXT Context
)
/*++
Routine Description:
This is a dummy competion routine that simply calls WdfRequestComplete. We have to use
this dummy competion routine instead of WDF_REQUEST_SEND_OPTION_SEND_AND_FORGET, because
the latter causes the framework to not check if the I/O target is closed or not.
Arguments:
Request - completed request
Target - the I/O target that completed the request
Params - request parameters
Context - not used
Return Value:
none
--*/
{
UNREFERENCED_PARAMETER(Target);
UNREFERENCED_PARAMETER(Params);
UNREFERENCED_PARAMETER(Context);
WdfRequestCompleteWithInformation(Request,
WdfRequestGetStatus(Request),
WdfRequestGetInformation(Request));
}
_IRQL_requires_max_(DISPATCH_LEVEL)
NTSTATUS
DeviceSendPowerDownProcessRequest(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_opt_ PFN_WDF_REQUEST_COMPLETION_ROUTINE CompletionRoutine,
_In_opt_ PVOID Context
)
/*++
Routine Description:
This function is called during processing power down request.
It is used to send either SYNC CACHE command or STOP UNIT command.
Caller should set proper value in deviceExtension->PowerContext.PowerChangeState.PowerDown
to trigger the correct command be sent.
Arguments:
DeviceExtension -
CompletionRoutine - Completion routine that needs to be set for the request
Context - Completion context associated with the completion routine
Return Value:
NTSTATUS
--*/
{
NTSTATUS status;
BOOLEAN requestSent = FALSE;
BOOLEAN shouldRetry = TRUE;
PCDB cdb = (PCDB)DeviceExtension->PowerContext.Srb.Cdb;
ULONG timeoutValue = DeviceExtension->TimeOutValue;
ULONG retryCount = 1;
// reset some fields.
DeviceExtension->PowerContext.RetryIntervalIn100ns = 0;
status = PowerContextReuseRequest(DeviceExtension);
RequestClearSendTime(DeviceExtension->PowerContext.PowerRequest);
if (!NT_SUCCESS(status))
{
return status;
}
// set proper timeout value and max retry count.
switch(DeviceExtension->PowerContext.PowerChangeState.PowerDown)
{
case PowerDownDeviceInitial:
case PowerDownDeviceQuiesced:
case PowerDownDeviceStopped:
break;
case PowerDownDeviceLocked:
// Case of issuing SYNC CACHE command. Do not use power irp timeout remaining time in this case
// as we want to give best try on SYNC CACHE command.
retryCount = MAXIMUM_RETRIES;
timeoutValue = DeviceExtension->TimeOutValue;
break;
case PowerDownDeviceFlushed:
{
// Case of issuing STOP UNIT command
// As "Imme" bit is set to '1', this command should be completed in short time.
// This command is at low importance, failure of this command has very small impact.
ULONG secondsRemaining = 0;
#if (WINVER >= 0x0601)
// this API is introduced in Windows7
PoQueryWatchdogTime(DeviceExtension->LowerPdo, &secondsRemaining);
#endif
if (secondsRemaining == 0)
{
// not able to retrieve remaining time from PoQueryWatchdogTime API, use default values.
retryCount = MAXIMUM_RETRIES;
timeoutValue = SCSI_CDROM_TIMEOUT;
}
else
{
// plan to leave about 30 seconds to lower level drivers if possible.
if (secondsRemaining >= 32)
{
retryCount = (secondsRemaining - 30)/SCSI_CDROM_TIMEOUT + 1;
timeoutValue = SCSI_CDROM_TIMEOUT;
if (retryCount > MAXIMUM_RETRIES)
{
retryCount = MAXIMUM_RETRIES;
}
if (retryCount == 1)
{
timeoutValue = secondsRemaining - 30;
}
}
else
{
// issue the command with minimal timeout value and do not retry on it.
retryCount = 1;
timeoutValue = 2;
}
}
}
break;
default:
NT_ASSERT( FALSE );
status = STATUS_NOT_IMPLEMENTED;
return status;
}
DeviceExtension->PowerContext.RetryCount = retryCount;
// issue command.
while (shouldRetry)
{
// set SRB fields.
DeviceExtension->PowerContext.Srb.SrbFlags = SRB_FLAGS_NO_DATA_TRANSFER |
SRB_FLAGS_DISABLE_SYNCH_TRANSFER |
SRB_FLAGS_NO_QUEUE_FREEZE |
SRB_FLAGS_BYPASS_LOCKED_QUEUE |
SRB_FLAGS_D3_PROCESSING;
DeviceExtension->PowerContext.Srb.Function = SRB_FUNCTION_EXECUTE_SCSI;
DeviceExtension->PowerContext.Srb.TimeOutValue = timeoutValue;
if (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceInitial)
{
DeviceExtension->PowerContext.Srb.Function = SRB_FUNCTION_LOCK_QUEUE;
}
else if (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceLocked)
{
DeviceExtension->PowerContext.Srb.Function = SRB_FUNCTION_QUIESCE_DEVICE;
}
else if (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceQuiesced)
{
// Case of issuing SYNC CACHE command.
DeviceExtension->PowerContext.Srb.CdbLength = 10;
cdb->SYNCHRONIZE_CACHE10.OperationCode = SCSIOP_SYNCHRONIZE_CACHE;
}
else if (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceFlushed)
{
// Case of issuing STOP UNIT command.
DeviceExtension->PowerContext.Srb.CdbLength = 6;
cdb->START_STOP.OperationCode = SCSIOP_START_STOP_UNIT;
cdb->START_STOP.Start = 0;
cdb->START_STOP.Immediate = 1;
}
else if (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceStopped)
{
DeviceExtension->PowerContext.Srb.Function = SRB_FUNCTION_UNLOCK_QUEUE;
}
// Set up completion routine and context if requested
if (CompletionRoutine)
{
WdfRequestSetCompletionRoutine(DeviceExtension->PowerContext.PowerRequest,
CompletionRoutine,
Context);
}
status = RequestSend(DeviceExtension,
DeviceExtension->PowerContext.PowerRequest,
DeviceExtension->IoTarget,
CompletionRoutine ? 0 : WDF_REQUEST_SEND_OPTION_SYNCHRONOUS,
&requestSent);
if (requestSent)
{
if ((CompletionRoutine == NULL) &&
(SRB_STATUS(DeviceExtension->PowerContext.Srb.SrbStatus) != SRB_STATUS_SUCCESS))
{
TracePrint((TRACE_LEVEL_ERROR,
TRACE_FLAG_POWER,
"%p\tError occured when issuing %s command to device. Srb %p, Status %x\n",
DeviceExtension->PowerContext.PowerRequest,
(DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceQuiesced) ? "SYNC CACHE" : "STOP UNIT",
&DeviceExtension->PowerContext.Srb,
DeviceExtension->PowerContext.Srb.SrbStatus));
NT_ASSERT(!(TEST_FLAG(DeviceExtension->PowerContext.Srb.SrbStatus, SRB_STATUS_QUEUE_FROZEN)));
shouldRetry = RequestSenseInfoInterpret(DeviceExtension,
DeviceExtension->PowerContext.PowerRequest,
&(DeviceExtension->PowerContext.Srb),
retryCount - DeviceExtension->PowerContext.RetryCount,
&status,
&(DeviceExtension->PowerContext.RetryIntervalIn100ns));
if (shouldRetry && (DeviceExtension->PowerContext.RetryCount-- == 0))
{
shouldRetry = FALSE;
}
}
else
{
// succeeded, do not need to retry.
shouldRetry = FALSE;
}
}
else
{
// request failed to be sent
shouldRetry = FALSE;
}
if (shouldRetry)
{
LARGE_INTEGER t;
t.QuadPart = -DeviceExtension->PowerContext.RetryIntervalIn100ns;
KeDelayExecutionThread(KernelMode, FALSE, &t);
status = PowerContextReuseRequest(DeviceExtension);
if (!NT_SUCCESS(status))
{
shouldRetry = FALSE;
}
}
}
if (DeviceExtension->PowerContext.PowerChangeState.PowerDown == PowerDownDeviceQuiesced)
{
// record SYNC CACHE command completion time stamp.
KeQueryTickCount(&DeviceExtension->PowerContext.Step1CompleteTime);
}
return status;
}
NTSTATUS
RequestSend(
_In_ PCDROM_DEVICE_EXTENSION DeviceExtension,
_In_ WDFREQUEST Request,
_In_ WDFIOTARGET IoTarget,
_In_ ULONG Flags,
_Out_opt_ PBOOLEAN RequestSent
)
/*++
Routine Description:
Send the request to the target, wake up the device from Zero Power state if necessary.
Arguments:
DeviceExtension - device extension
Request - the request to be sent
IoTarget - target of the above request
Flags - flags for the operation
RequestSent - optional, if the request was sent
Return Value:
NTSTATUS
--*/
{
NTSTATUS status = STATUS_SUCCESS;
BOOLEAN requestSent = FALSE;
WDF_REQUEST_SEND_OPTIONS options;
UNREFERENCED_PARAMETER(DeviceExtension);
if ((DeviceExtension->ZeroPowerODDInfo != NULL) &&
(DeviceExtension->ZeroPowerODDInfo->InZeroPowerState != FALSE))
{
}
// Now send down the request
if (NT_SUCCESS(status))
{
WDF_REQUEST_SEND_OPTIONS_INIT(&options, Flags);
RequestSetSentTime(Request);
// send request and check status
// Disable SDV warning about infinitely waiting in caller's context:
// 1. Some requests (such as SCSI_PASS_THROUGH, contains buffer from user space) need to be sent down in callers context.
// Consequently, these requests wait in callers context until they are allowed to be sent down.
// 2. Considering the situation that during sleep, a request can be hold by storage port driver. When system resumes, any time out value (if we set using KMDF time out value) might be expires.
// This will cause the waiting request being failed (behavior change). Wed rather not set time out value.
_Analysis_assume_(options.Timeout != 0);
requestSent = WdfRequestSend(Request, IoTarget, &options);
_Analysis_assume_(options.Timeout == 0);
// If WdfRequestSend fails, or if the WDF_REQUEST_SEND_OPTION_SYNCHRONOUS flag is set,
// the driver can call WdfRequestGetStatus immediately after calling WdfRequestSend.
if ((requestSent == FALSE) ||
(Flags & WDF_REQUEST_SEND_OPTION_SYNCHRONOUS))
{
status = WdfRequestGetStatus(Request);
if (requestSent == FALSE)
{
TracePrint((TRACE_LEVEL_WARNING, TRACE_FLAG_GENERAL,
"WdfRequestSend failed: %lx\n",
status
));
}
}
else
{
status = STATUS_SUCCESS;
}
if (RequestSent != NULL)
{
*RequestSent = requestSent;
}
}
return status;
}
|