1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
/*--

Copyright (C) Microsoft Corporation, 1999 - 1999

Module Name:

    ioctl.c

Abstract:

    The CDROM class driver tranlates IRPs to SRBs with embedded CDBs
    and sends them to its devices through the port driver.

Environment:

    kernel mode only

Notes:

    SCSI Tape, CDRom and Disk class drivers share common routines
    that can be found in the CLASS directory (..\ntos\dd\class).

Revision History:

--*/

#include "cdrom.h"

#if DBG
    PUCHAR READ_DVD_STRUCTURE_FORMAT_STRINGS[DvdMaxDescriptor+1] = {
        "Physical",
        "Copyright",
        "DiskKey",
        "BCA",
        "Manufacturer",
        "Unknown"
    };
#endif // DBG

#define DEFAULT_CDROM_SECTORS_PER_TRACK 32
#define DEFAULT_TRACKS_PER_CYLINDER     64

NTSTATUS
NTAPI
CdRomDeviceControlDispatch(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp
    )
/*++

Routine Description:

    This is the NT device control handler for CDROMs.

Arguments:

    DeviceObject - for this CDROM

    Irp - IO Request packet

Return Value:

    NTSTATUS

--*/
{
    PFUNCTIONAL_DEVICE_EXTENSION  fdoExtension = DeviceObject->DeviceExtension;
    PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;

    PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
    PIO_STACK_LOCATION nextStack;
    PCDROM_DATA        cdData = (PCDROM_DATA)(commonExtension->DriverData);

    //BOOLEAN            use6Byte = TEST_FLAG(cdData->XAFlags, XA_USE_6_BYTE);
    SCSI_REQUEST_BLOCK srb;
    PCDB cdb = (PCDB)srb.Cdb;
    //PVOID outputBuffer;
    //ULONG bytesTransferred = 0;
    NTSTATUS status;
    //NTSTATUS status2;
    KIRQL    irql;

    ULONG ioctlCode;
    ULONG baseCode;
    ULONG functionCode;

RetryControl:

    //
    // Zero the SRB on stack.
    //

    RtlZeroMemory(&srb, sizeof(SCSI_REQUEST_BLOCK));

    Irp->IoStatus.Information = 0;

    //
    // if this is a class driver ioctl then we need to change the base code
    // to IOCTL_CDROM_BASE so that the switch statement can handle it.
    //
    // WARNING - currently the scsi class ioctl function codes are between
    // 0x200 & 0x300.  this routine depends on that fact
    //

    ioctlCode = irpStack->Parameters.DeviceIoControl.IoControlCode;
    baseCode = ioctlCode >> 16;
    functionCode = (ioctlCode & (~0xffffc003)) >> 2;

    TraceLog((CdromDebugTrace,
                "CdRomDeviceControl: Ioctl Code = %lx, Base Code = %lx,"
                " Function Code = %lx\n",
                ioctlCode,
                baseCode,
                functionCode
              ));

    if((functionCode >= 0x200) && (functionCode <= 0x300)) {

        ioctlCode = (ioctlCode & 0x0000ffff) | CTL_CODE(IOCTL_CDROM_BASE, 0, 0, 0);

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Class Code - new ioctl code is %lx\n",
                    ioctlCode));

        irpStack->Parameters.DeviceIoControl.IoControlCode = ioctlCode;

    }

    switch (ioctlCode) {

    case IOCTL_STORAGE_GET_MEDIA_TYPES_EX: {

        PGET_MEDIA_TYPES  mediaTypes = Irp->AssociatedIrp.SystemBuffer;
        PDEVICE_MEDIA_INFO mediaInfo = &mediaTypes->MediaInfo[0];
        ULONG sizeNeeded;

        sizeNeeded = sizeof(GET_MEDIA_TYPES);
        
        //
        // IsMmc is static...
        //

        if (cdData->Mmc.IsMmc) {
            sizeNeeded += sizeof(DEVICE_MEDIA_INFO) * 1; // return two media types
        }

        //
        // Ensure that buffer is large enough.
        //

        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            sizeNeeded) {

            //
            // Buffer too small.
            //

            Irp->IoStatus.Information = sizeNeeded;
            status = STATUS_BUFFER_TOO_SMALL;
            break;
        }
        
        RtlZeroMemory(Irp->AssociatedIrp.SystemBuffer, sizeNeeded);

        //
        // ISSUE-2000/5/11-henrygab - need to update GET_MEDIA_TYPES_EX
        //

        mediaTypes->DeviceType = CdRomGetDeviceType(DeviceObject);

        mediaTypes->MediaInfoCount = 1;
        mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaType = CD_ROM;
        mediaInfo->DeviceSpecific.RemovableDiskInfo.NumberMediaSides = 1;
        mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaCharacteristics = MEDIA_READ_ONLY;
        mediaInfo->DeviceSpecific.RemovableDiskInfo.Cylinders.QuadPart = fdoExtension->DiskGeometry.Cylinders.QuadPart;
        mediaInfo->DeviceSpecific.RemovableDiskInfo.TracksPerCylinder = fdoExtension->DiskGeometry.TracksPerCylinder;
        mediaInfo->DeviceSpecific.RemovableDiskInfo.SectorsPerTrack = fdoExtension->DiskGeometry.SectorsPerTrack;
        mediaInfo->DeviceSpecific.RemovableDiskInfo.BytesPerSector = fdoExtension->DiskGeometry.BytesPerSector;

        if (cdData->Mmc.IsMmc) {
            
            //
            // also report a removable disk
            //
            mediaTypes->MediaInfoCount += 1;
            
            mediaInfo++;
            mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaType = RemovableMedia;
            mediaInfo->DeviceSpecific.RemovableDiskInfo.NumberMediaSides = 1;
            mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaCharacteristics = MEDIA_READ_WRITE;
            mediaInfo->DeviceSpecific.RemovableDiskInfo.Cylinders.QuadPart = fdoExtension->DiskGeometry.Cylinders.QuadPart;
            mediaInfo->DeviceSpecific.RemovableDiskInfo.TracksPerCylinder = fdoExtension->DiskGeometry.TracksPerCylinder;
            mediaInfo->DeviceSpecific.RemovableDiskInfo.SectorsPerTrack = fdoExtension->DiskGeometry.SectorsPerTrack;
            mediaInfo->DeviceSpecific.RemovableDiskInfo.BytesPerSector = fdoExtension->DiskGeometry.BytesPerSector;
            mediaInfo--;
        
        }

        //
        // Status will either be success, if media is present, or no media.
        // It would be optimal to base from density code and medium type, but not all devices
        // have values for these fields.
        //

        //
        // Send a TUR to determine if media is present.
        //

        srb.CdbLength = 6;
        cdb = (PCDB)srb.Cdb;
        cdb->CDB6GENERIC.OperationCode = SCSIOP_TEST_UNIT_READY;

        //
        // Set timeout value.
        //

        srb.TimeOutValue = fdoExtension->TimeOutValue;

        status = ClassSendSrbSynchronous(DeviceObject,
                                         &srb,
                                         NULL,
                                         0,
                                         FALSE);


        TraceLog((CdromDebugWarning,
                   "CdRomDeviceControl: GET_MEDIA_TYPES status of TUR - %lx\n",
                   status));

        if (NT_SUCCESS(status)) {

            //
            // set the disk's media as current if we can write to it.
            //

            if (cdData->Mmc.IsMmc && cdData->Mmc.WriteAllowed) {

                mediaInfo++;
                SET_FLAG(mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaCharacteristics,
                         MEDIA_CURRENTLY_MOUNTED);
                mediaInfo--;


            } else {

                SET_FLAG(mediaInfo->DeviceSpecific.RemovableDiskInfo.MediaCharacteristics,
                         MEDIA_CURRENTLY_MOUNTED);

            }

        }

        Irp->IoStatus.Information = sizeNeeded;
        status = STATUS_SUCCESS;
        break;
    }


    case IOCTL_CDROM_RAW_READ: {

        LARGE_INTEGER  startingOffset;
        ULONGLONG      transferBytes;
        ULONGLONG      endOffset;
        ULONGLONG      mdlBytes;
        //ULONG          startingSector;
        PRAW_READ_INFO rawReadInfo = (PRAW_READ_INFO)irpStack->Parameters.DeviceIoControl.Type3InputBuffer;

        //
        // Ensure that XA reads are supported.
        //

        if (TEST_FLAG(cdData->XAFlags, XA_NOT_SUPPORTED)) {
            TraceLog((CdromDebugWarning,
                        "CdRomDeviceControl: XA Reads not supported. Flags (%x)\n",
                        cdData->XAFlags));
            status = STATUS_INVALID_DEVICE_REQUEST;
            break;
        }

        //
        // Check that ending sector is on disc and buffers are there and of
        // correct size.
        //

        if (rawReadInfo == NULL) {
            
            //
            // Called from user space. Save the userbuffer in the 
            // Type3InputBuffer so we can reduce the number of code paths.
            //

            irpStack->Parameters.DeviceIoControl.Type3InputBuffer =
                Irp->AssociatedIrp.SystemBuffer;

            //
            // Called from user space.  Validate the buffers.
            //

            rawReadInfo = (PRAW_READ_INFO)irpStack->Parameters.DeviceIoControl.Type3InputBuffer;

            if (rawReadInfo == NULL) {

                TraceLog((CdromDebugWarning,
                            "CdRomDeviceControl: Invalid I/O parameters for "
                            "XA Read (No extent info\n"));
                status = STATUS_INVALID_PARAMETER;
                break;

            }

            if (irpStack->Parameters.DeviceIoControl.InputBufferLength !=
                sizeof(RAW_READ_INFO)) {

                TraceLog((CdromDebugWarning,
                            "CdRomDeviceControl: Invalid I/O parameters for "
                            "XA Read (Invalid info buffer\n"));
                status = STATUS_INVALID_PARAMETER;
                break;

            }
        }

        //
        // if they don't request any data, just fail the request
        //

        if (rawReadInfo->SectorCount == 0) {

            status = STATUS_INVALID_PARAMETER;
            break;

        }

        startingOffset.QuadPart = rawReadInfo->DiskOffset.QuadPart;
        /* startingSector = (ULONG)(rawReadInfo->DiskOffset.QuadPart >>
                                 fdoExtension->SectorShift); */
        transferBytes = (ULONGLONG)rawReadInfo->SectorCount * RAW_SECTOR_SIZE;
        
        endOffset = (ULONGLONG)rawReadInfo->SectorCount * COOKED_SECTOR_SIZE;
        endOffset += startingOffset.QuadPart;

        //
        // check for overflows....
        //
        
        if (transferBytes < (ULONGLONG)(rawReadInfo->SectorCount)) {
            TraceLog((CdromDebugWarning,
                        "CdRomDeviceControl: Invalid I/O parameters for XA "
                        "Read (TransferBytes Overflow)\n"));
            status = STATUS_INVALID_PARAMETER;
            break;
        }
        if (endOffset < (ULONGLONG)startingOffset.QuadPart) {
            TraceLog((CdromDebugWarning,
                        "CdRomDeviceControl: Invalid I/O parameters for XA "
                        "Read (EndingOffset Overflow)\n"));
            status = STATUS_INVALID_PARAMETER;
            break;
        }
        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            transferBytes) {
            TraceLog((CdromDebugWarning,
                        "CdRomDeviceControl: Invalid I/O parameters for XA "
                        "Read (Bad buffer size)\n"));
            status = STATUS_INVALID_PARAMETER;
            break;
        }
        if (endOffset > (ULONGLONG)commonExtension->PartitionLength.QuadPart) {
            TraceLog((CdromDebugWarning,
                        "CdRomDeviceControl: Invalid I/O parameters for XA "
                        "Read (Request Out of Bounds)\n"));
            status = STATUS_INVALID_PARAMETER;
            break;
        }

        //
        // cannot validate the MdlAddress, since it is not included in any
        // other location per the DDK and file system calls.
        //

        //
        // validate the mdl describes at least the number of bytes
        // requested from us.
        //

        mdlBytes = (ULONGLONG)MmGetMdlByteCount(Irp->MdlAddress);
        if (mdlBytes < transferBytes) {
            TraceLog((CdromDebugWarning,
                        "CdRomDeviceControl: Invalid MDL %s, Irp %p\n",
                        "size (5)", Irp));
            status = STATUS_INVALID_PARAMETER;
            break;
        }

        //
        // HACKHACK - REF #0001
        // The retry count will be in this irp's IRP_MN function,
        // as the new irp was freed, and we therefore cannot use
        // this irp's next stack location for this function.
        // This may be a good location to store this info for
        // when we remove RAW_READ (mode switching), as we will
        // no longer have the nextIrpStackLocation to play with
        // when that occurs
        //
        // once XA_READ is removed, then this hack can also be
        // removed.
        //
        irpStack->MinorFunction = MAXIMUM_RETRIES; // HACKHACK - REF #0001

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_DISK_GET_DRIVE_GEOMETRY_EX:
    case IOCTL_CDROM_GET_DRIVE_GEOMETRY_EX: {
        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Get drive geometryEx\n"));
        if ( irpStack->Parameters.DeviceIoControl.OutputBufferLength <
             FIELD_OFFSET(DISK_GEOMETRY_EX, Data)) {
            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = FIELD_OFFSET(DISK_GEOMETRY_EX, Data);
            break;
        }
        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);
        return STATUS_PENDING;
    }

    case IOCTL_DISK_GET_DRIVE_GEOMETRY:
    case IOCTL_CDROM_GET_DRIVE_GEOMETRY: {

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Get drive geometry\n"));

        if ( irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            sizeof( DISK_GEOMETRY ) ) {

            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = sizeof(DISK_GEOMETRY);
            break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_CDROM_READ_TOC_EX: {

        PCDROM_READ_TOC_EX inputBuffer;
        
        if (CdRomIsPlayActive(DeviceObject)) {
            status = STATUS_DEVICE_BUSY;
            break;
        }

        if (irpStack->Parameters.DeviceIoControl.InputBufferLength <
            sizeof(CDROM_READ_TOC_EX)) {
            status = STATUS_INFO_LENGTH_MISMATCH;
            break;
        }

        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            MINIMUM_CDROM_READ_TOC_EX_SIZE) {
            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = MINIMUM_CDROM_READ_TOC_EX_SIZE;
            break;
        }

        if (irpStack->Parameters.Read.Length > ((USHORT)-1)) {
            status = STATUS_INVALID_PARAMETER;
            break;
        }

        inputBuffer = Irp->AssociatedIrp.SystemBuffer;

        if ((inputBuffer->Reserved1 != 0) ||
            (inputBuffer->Reserved2 != 0) ||
            (inputBuffer->Reserved3 != 0)) {
            status = STATUS_INVALID_PARAMETER;
            break;
        }

        //
        // NOTE: when adding new formats, ensure that first two bytes
        //       specify the amount of additional data available.
        //

        if ((inputBuffer->Format == CDROM_READ_TOC_EX_FORMAT_TOC     ) ||
            (inputBuffer->Format == CDROM_READ_TOC_EX_FORMAT_FULL_TOC) ||
            (inputBuffer->Format == CDROM_READ_TOC_EX_FORMAT_CDTEXT  )) {
            
            // SessionTrack field is used

        } else
        if ((inputBuffer->Format == CDROM_READ_TOC_EX_FORMAT_SESSION) ||
            (inputBuffer->Format == CDROM_READ_TOC_EX_FORMAT_PMA)     ||
            (inputBuffer->Format == CDROM_READ_TOC_EX_FORMAT_ATIP)) {
            
            // SessionTrack field is reserved
            
            if (inputBuffer->SessionTrack != 0) {
                status = STATUS_INVALID_PARAMETER;
                break;
            }
            
        } else {
            status = STATUS_INVALID_PARAMETER;
            break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);
        return STATUS_PENDING;
    }

    case IOCTL_CDROM_GET_LAST_SESSION: {

        //
        // If the cd is playing music then reject this request.
        //

        if (CdRomIsPlayActive(DeviceObject)) {
            status = STATUS_DEVICE_BUSY;
            break;
        }

        //
        // Make sure the caller is requesting enough data to make this worth
        // our while.
        //

        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            sizeof(CDROM_TOC_SESSION_DATA)) {

            //
            // they didn't request the entire TOC -- use _EX version
            // for partial transfers and such.
            //

            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = sizeof(CDROM_TOC_SESSION_DATA);
            break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_CDROM_READ_TOC:  {

        //
        // If the cd is playing music then reject this request.
        //

        if (CdRomIsPlayActive(DeviceObject)) {
            status = STATUS_DEVICE_BUSY;
            break;
        }

        //
        // Make sure the caller is requesting enough data to make this worth
        // our while.
        //

        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            sizeof(CDROM_TOC)) {

            //
            // they didn't request the entire TOC -- use _EX version
            // for partial transfers and such.
            //

            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = sizeof(CDROM_TOC);
            break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_CDROM_PLAY_AUDIO_MSF: {

        //
        // Play Audio MSF
        //

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Play audio MSF\n"));

        if (irpStack->Parameters.DeviceIoControl.InputBufferLength <
            sizeof(CDROM_PLAY_AUDIO_MSF)) {

            //
            // Indicate unsuccessful status.
            //

            status = STATUS_INFO_LENGTH_MISMATCH;
            break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_CDROM_SEEK_AUDIO_MSF: {


        //
        // Seek Audio MSF
        //

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Seek audio MSF\n"));

        if (irpStack->Parameters.DeviceIoControl.InputBufferLength <
            sizeof(CDROM_SEEK_AUDIO_MSF)) {

            //
            // Indicate unsuccessful status.
            //

            status = STATUS_INFO_LENGTH_MISMATCH;
            break;
        }
        
        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);
        return STATUS_PENDING;

    }

    case IOCTL_CDROM_PAUSE_AUDIO: {

        //
        // Pause audio
        //

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Pause audio\n"));

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;

        break;
    }

    case IOCTL_CDROM_RESUME_AUDIO: {

        //
        // Resume audio
        //

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Resume audio\n"));

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_CDROM_READ_Q_CHANNEL: {

        PCDROM_SUB_Q_DATA_FORMAT inputBuffer =
                         Irp->AssociatedIrp.SystemBuffer;

        if(irpStack->Parameters.DeviceIoControl.InputBufferLength <
            sizeof(CDROM_SUB_Q_DATA_FORMAT)) {

            status = STATUS_INFO_LENGTH_MISMATCH;
            break;
        }

        //
        // check for all valid types of request
        //

        if (inputBuffer->Format != IOCTL_CDROM_CURRENT_POSITION &&
            inputBuffer->Format != IOCTL_CDROM_MEDIA_CATALOG &&
            inputBuffer->Format != IOCTL_CDROM_TRACK_ISRC ) {
            status = STATUS_INVALID_PARAMETER;
            Irp->IoStatus.Information = 0;
            break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_CDROM_GET_CONTROL: {

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Get audio control\n"));

        //
        // Verify user buffer is large enough for the data.
        //

        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            sizeof(CDROM_AUDIO_CONTROL)) {

            //
            // Indicate unsuccessful status and no data transferred.
            //

            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = sizeof(CDROM_AUDIO_CONTROL);
            break;

        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_CDROM_GET_VOLUME: {

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Get volume control\n"));

        //
        // Verify user buffer is large enough for data.
        //

        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            sizeof(VOLUME_CONTROL)) {

            //
            // Indicate unsuccessful status and no data transferred.
            //

            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = sizeof(VOLUME_CONTROL);
            break;

        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_CDROM_SET_VOLUME: {

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Set volume control\n"));

        if (irpStack->Parameters.DeviceIoControl.InputBufferLength <
            sizeof(VOLUME_CONTROL)) {

            //
            // Indicate unsuccessful status.
            //

            status = STATUS_INFO_LENGTH_MISMATCH;
            break;

        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_CDROM_STOP_AUDIO: {

        //
        // Stop play.
        //

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Stop audio\n"));

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_STORAGE_CHECK_VERIFY:
    case IOCTL_DISK_CHECK_VERIFY:
    case IOCTL_CDROM_CHECK_VERIFY: {

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: [%p] Check Verify\n", Irp));

        if((irpStack->Parameters.DeviceIoControl.OutputBufferLength) &&
           (irpStack->Parameters.DeviceIoControl.OutputBufferLength < sizeof(ULONG))) {

           TraceLog((CdromDebugWarning,
                       "CdRomDeviceControl: Check Verify: media count "
                       "buffer too small\n"));

           status = STATUS_BUFFER_TOO_SMALL;
           Irp->IoStatus.Information = sizeof(ULONG);
           break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_DVD_READ_STRUCTURE: {

        TraceLog((CdromDebugTrace,
                    "DvdDeviceControl: [%p] IOCTL_DVD_READ_STRUCTURE\n", Irp));

        if (cdData->DvdRpc0Device && cdData->DvdRpc0LicenseFailure) {
            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: License Failure\n"));
            status = STATUS_COPY_PROTECTION_FAILURE;
            break;
        }

        if (cdData->DvdRpc0Device && cdData->Rpc0RetryRegistryCallback) {
            //
            // if currently in-progress, this will just return.
            // prevents looping by doing that interlockedExchange()
            //
            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: PickRegion() from "
                        "READ_STRUCTURE\n"));
            CdRomPickDvdRegion(DeviceObject);
        }


        if(irpStack->Parameters.DeviceIoControl.InputBufferLength <
           sizeof(DVD_READ_STRUCTURE)) {

            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl - READ_STRUCTURE: input buffer "
                        "length too small (was %d should be %d)\n",
                        irpStack->Parameters.DeviceIoControl.InputBufferLength,
                        sizeof(DVD_READ_STRUCTURE)));
            status = STATUS_INVALID_PARAMETER;
            break;
        }

        if(irpStack->Parameters.DeviceIoControl.OutputBufferLength <
           sizeof(READ_DVD_STRUCTURES_HEADER)) {

            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl - READ_STRUCTURE: output buffer "
                        "cannot hold header information\n"));
            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = sizeof(READ_DVD_STRUCTURES_HEADER);            
            break;
        }

        if(irpStack->Parameters.DeviceIoControl.OutputBufferLength >
           MAXUSHORT) {

            //
            // key length must fit in two bytes
            //
            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl - READ_STRUCTURE: output buffer "
                        "too large\n"));
            status = STATUS_INVALID_PARAMETER;
            break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_DVD_START_SESSION: {

        TraceLog((CdromDebugTrace,
                    "DvdDeviceControl: [%p] IOCTL_DVD_START_SESSION\n", Irp));

        if (cdData->DvdRpc0Device && cdData->DvdRpc0LicenseFailure) {
            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: License Failure\n"));
            status = STATUS_COPY_PROTECTION_FAILURE;
            break;
        }

        if(irpStack->Parameters.DeviceIoControl.OutputBufferLength <
           sizeof(DVD_SESSION_ID)) {

            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: DVD_START_SESSION - output "
                        "buffer too small\n"));
            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = sizeof(DVD_SESSION_ID);
            break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_DVD_SEND_KEY:
    case IOCTL_DVD_SEND_KEY2: {

        PDVD_COPY_PROTECT_KEY key = Irp->AssociatedIrp.SystemBuffer;
        //ULONG keyLength;

        TraceLog((CdromDebugTrace,
                    "DvdDeviceControl: [%p] IOCTL_DVD_SEND_KEY\n", Irp));

        if (cdData->DvdRpc0Device && cdData->DvdRpc0LicenseFailure) {
            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: License Failure\n"));
            status = STATUS_COPY_PROTECTION_FAILURE;
            break;
        }

        if((irpStack->Parameters.DeviceIoControl.InputBufferLength <
            sizeof(DVD_COPY_PROTECT_KEY)) ||
           (irpStack->Parameters.DeviceIoControl.InputBufferLength !=
            key->KeyLength)) {

            //
            // Key is too small to have a header or the key length doesn't
            // match the input buffer length.  Key must be invalid
            //

            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: [%p] IOCTL_DVD_SEND_KEY - "
                        "key is too small or does not match KeyLength\n",
                        Irp));
            status = STATUS_INVALID_PARAMETER;
            break;
        }

        //
        // allow only certain key type (non-destructive) to go through
        // IOCTL_DVD_SEND_KEY (which only requires READ access to the device
        //
        if (ioctlCode == IOCTL_DVD_SEND_KEY) {

            if ((key->KeyType != DvdChallengeKey) &&
                (key->KeyType != DvdBusKey2) &&
                (key->KeyType != DvdInvalidateAGID)) {

                status = STATUS_INVALID_PARAMETER;
                break;
            }
        }

        if (cdData->DvdRpc0Device) {

            if (key->KeyType == DvdSetRpcKey) {

                PDVD_SET_RPC_KEY rpcKey = (PDVD_SET_RPC_KEY) key->KeyData;

                if (irpStack->Parameters.DeviceIoControl.InputBufferLength <
                    DVD_SET_RPC_KEY_LENGTH) {

                    status = STATUS_INVALID_PARAMETER;
                    break;
                }

                //
                // we have a request to set region code
                // on a RPC0 device which doesn't support
                // region coding.
                //
                // we have to fake it.
                //

                KeWaitForMutexObject(
                    &cdData->Rpc0RegionMutex,
                    UserRequest,
                    KernelMode,
                    FALSE,
                    NULL
                    );

                if (cdData->DvdRpc0Device && cdData->Rpc0RetryRegistryCallback) {
                    //
                    // if currently in-progress, this will just return.
                    // prevents looping by doing that interlockedExchange()
                    //
                    TraceLog((CdromDebugWarning,
                                "DvdDeviceControl: PickRegion() from "
                                "SEND_KEY\n"));
                    CdRomPickDvdRegion(DeviceObject);
                }

                if (cdData->Rpc0SystemRegion == rpcKey->PreferredDriveRegionCode) {

                    //
                    // nothing to change
                    //
                    TraceLog((CdromDebugWarning,
                                "DvdDeviceControl (%p) => not changing "
                                "regions -- requesting current region\n",
                                DeviceObject));
                    status = STATUS_SUCCESS;

                } else if (cdData->Rpc0SystemRegionResetCount == 0) {

                    //
                    // not allowed to change it again
                    //

                    TraceLog((CdromDebugWarning,
                                "DvdDeviceControl (%p) => no more region "
                                "changes are allowed for this device\n",
                                DeviceObject));
                    status = STATUS_CSS_RESETS_EXHAUSTED;

                } else {

                    //ULONG i;
                    UCHAR mask;
                    ULONG bufferLen;
                    PDVD_READ_STRUCTURE dvdReadStructure;
                    PDVD_COPYRIGHT_DESCRIPTOR dvdCopyRight;
                    IO_STATUS_BLOCK ioStatus;
                    UCHAR mediaRegionData;

                    mask = ~rpcKey->PreferredDriveRegionCode;

                    if (CountOfSetBitsUChar(mask) != 1) {

                        status = STATUS_INVALID_DEVICE_REQUEST;
                        break;
                    }

                    //
                    // this test will always be TRUE except during initial
                    // automatic selection of the first region.
                    //

                    if (cdData->Rpc0SystemRegion != 0xff) {

                        //
                        // make sure we have a media in the drive with the same
                        // region code if the drive is already has a region set
                        //

                        TraceLog((CdromDebugTrace,
                                    "DvdDeviceControl (%p) => Checking "
                                    "media region\n",
                                    DeviceObject));

                        bufferLen = max(sizeof(DVD_DESCRIPTOR_HEADER) +
                                            sizeof(DVD_COPYRIGHT_DESCRIPTOR),
                                        sizeof(DVD_READ_STRUCTURE)
                                        );

                        dvdReadStructure = (PDVD_READ_STRUCTURE)
                            ExAllocatePoolWithTag(PagedPool,
                                                  bufferLen,
                                                  DVD_TAG_RPC2_CHECK);

                        if (dvdReadStructure == NULL) {
                            status = STATUS_INSUFFICIENT_RESOURCES;
                            KeReleaseMutex(&cdData->Rpc0RegionMutex,FALSE);
                            break;
                        }

                        dvdCopyRight = (PDVD_COPYRIGHT_DESCRIPTOR)
                            ((PDVD_DESCRIPTOR_HEADER) dvdReadStructure)->Data;

                        //
                        // check to see if we have a DVD device
                        //

                        RtlZeroMemory (dvdReadStructure, bufferLen);
                        dvdReadStructure->Format = DvdCopyrightDescriptor;

                        //
                        // Build a request for READ_KEY
                        //
                        ClassSendDeviceIoControlSynchronous(
                            IOCTL_DVD_READ_STRUCTURE,
                            DeviceObject,
                            dvdReadStructure,
                            sizeof(DVD_READ_STRUCTURE),
                            sizeof(DVD_DESCRIPTOR_HEADER) +
                                sizeof(DVD_COPYRIGHT_DESCRIPTOR),
                            FALSE,
                            &ioStatus);

                        //
                        // this is just to prevent bugs from creeping in
                        // if status is not set later in development
                        //

                        status = ioStatus.Status;

                        //
                        // handle errors
                        //

                        if (!NT_SUCCESS(status)) {
                            KeReleaseMutex(&cdData->Rpc0RegionMutex,FALSE);
                            ExFreePool(dvdReadStructure);
                            status = STATUS_INVALID_DEVICE_REQUEST;
                            break;
                        }

                        //
                        // save the mediaRegionData before freeing the
                        // allocated memory
                        //

                        mediaRegionData =
                            dvdCopyRight->RegionManagementInformation;
                        ExFreePool(dvdReadStructure);

                        TraceLog((CdromDebugWarning,
                                    "DvdDeviceControl (%p) => new mask is %x"
                                    " MediaRegionData is %x\n", DeviceObject,
                                    rpcKey->PreferredDriveRegionCode,
                                    mediaRegionData));

                        //
                        // the media region must match the requested region
                        // for RPC0 drives for initial region selection
                        //

                        if (((UCHAR)~(mediaRegionData | rpcKey->PreferredDriveRegionCode)) == 0) {
                            KeReleaseMutex(&cdData->Rpc0RegionMutex,FALSE);
                            status = STATUS_CSS_REGION_MISMATCH;
                            break;
                        }

                    }

                    //
                    // now try to set the region
                    //

                    TraceLog((CdromDebugTrace,
                                "DvdDeviceControl (%p) => Soft-Setting "
                                "region of RPC1 device to %x\n",
                                DeviceObject,
                                rpcKey->PreferredDriveRegionCode
                                ));

                    status = CdRomSetRpc0Settings(DeviceObject,
                                                  rpcKey->PreferredDriveRegionCode);

                    if (!NT_SUCCESS(status)) {
                        TraceLog((CdromDebugWarning,
                                    "DvdDeviceControl (%p) => Could not "
                                    "set region code (%x)\n",
                                    DeviceObject, status
                                    ));
                    } else {

                        TraceLog((CdromDebugTrace,
                                    "DvdDeviceControl (%p) => New region set "
                                    " for RPC1 drive\n", DeviceObject));

                        //
                        // if it worked, our extension is already updated.
                        // release the mutex
                        //

                        DebugPrint ((4, "DvdDeviceControl (%p) => DVD current "
                                     "region bitmap  0x%x\n", DeviceObject,
                                     cdData->Rpc0SystemRegion));
                        DebugPrint ((4, "DvdDeviceControl (%p) => DVD region "
                                     " reset Count     0x%x\n", DeviceObject,
                                     cdData->Rpc0SystemRegionResetCount));
                    }

                }

                KeReleaseMutex(&cdData->Rpc0RegionMutex,FALSE);
                break;
            } // end of key->KeyType == DvdSetRpcKey
        } // end of Rpc0Device hacks

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);
        return STATUS_PENDING;
    }

    case IOCTL_DVD_READ_KEY: {

        PDVD_COPY_PROTECT_KEY keyParameters = Irp->AssociatedIrp.SystemBuffer;
        ULONG keyLength;

        TraceLog((CdromDebugTrace,
                    "DvdDeviceControl: [%p] IOCTL_DVD_READ_KEY\n", Irp));

        if (cdData->DvdRpc0Device && cdData->DvdRpc0LicenseFailure) {
            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: License Failure\n"));
            status = STATUS_COPY_PROTECTION_FAILURE;
            break;
        }

        if (cdData->DvdRpc0Device && cdData->Rpc0RetryRegistryCallback) {
            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: PickRegion() from READ_KEY\n"));
            CdRomPickDvdRegion(DeviceObject);
        }


        if(irpStack->Parameters.DeviceIoControl.InputBufferLength <
            sizeof(DVD_COPY_PROTECT_KEY)) {

            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: EstablishDriveKey - challenge "
                        "key buffer too small\n"));

            status = STATUS_INVALID_PARAMETER;
            break;

        }


        switch(keyParameters->KeyType) {

            case DvdChallengeKey:
                keyLength = DVD_CHALLENGE_KEY_LENGTH;
                break;

            case DvdBusKey1:
            case DvdBusKey2:

                keyLength = DVD_BUS_KEY_LENGTH;
                break;

            case DvdTitleKey:
                keyLength = DVD_TITLE_KEY_LENGTH;
                break;

            case DvdAsf:
                keyLength = DVD_ASF_LENGTH;
                break;

            case DvdDiskKey:
                keyLength = DVD_DISK_KEY_LENGTH;
                break;

            case DvdGetRpcKey:
                keyLength = DVD_RPC_KEY_LENGTH;
                break;

            default:
                keyLength = sizeof(DVD_COPY_PROTECT_KEY);
                break;
        }

        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            keyLength) {

            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: EstablishDriveKey - output "
                        "buffer too small\n"));
            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = keyLength;
            break;
        }

        if (keyParameters->KeyType == DvdGetRpcKey) {

            CdRomPickDvdRegion(DeviceObject);
        }

        if ((keyParameters->KeyType == DvdGetRpcKey) &&
            (cdData->DvdRpc0Device)) {

            PDVD_RPC_KEY rpcKey;
            rpcKey = (PDVD_RPC_KEY)keyParameters->KeyData;
            RtlZeroMemory (rpcKey, sizeof (*rpcKey));

            KeWaitForMutexObject(
                &cdData->Rpc0RegionMutex,
                UserRequest,
                KernelMode,
                FALSE,
                NULL
                );

            //
            // make up the data
            //
            rpcKey->UserResetsAvailable = cdData->Rpc0SystemRegionResetCount;
            rpcKey->ManufacturerResetsAvailable = 0;
            if (cdData->Rpc0SystemRegion == 0xff) {
                rpcKey->TypeCode = 0;
            } else {
                rpcKey->TypeCode = 1;
            }
            rpcKey->RegionMask = (UCHAR) cdData->Rpc0SystemRegion;
            rpcKey->RpcScheme = 1;

            KeReleaseMutex(
                &cdData->Rpc0RegionMutex,
                FALSE
                );

            Irp->IoStatus.Information = DVD_RPC_KEY_LENGTH;
            status = STATUS_SUCCESS;
            break;

        } else if (keyParameters->KeyType == DvdDiskKey) {

            PDVD_COPY_PROTECT_KEY keyHeader;
            PDVD_READ_STRUCTURE readStructureRequest;

            //
            // Special case - build a request to get the dvd structure
            // so we can get the disk key.
            //

            //
            // save the key header so we can restore the interesting
            // parts later
            //

            keyHeader = ExAllocatePoolWithTag(NonPagedPool,
                                              sizeof(DVD_COPY_PROTECT_KEY),
                                              DVD_TAG_READ_KEY);

            if(keyHeader == NULL) {

                //
                // Can't save the context so return an error
                //

                TraceLog((CdromDebugWarning,
                            "DvdDeviceControl - READ_KEY: unable to "
                            "allocate context\n"));
                status = STATUS_INSUFFICIENT_RESOURCES;
                break;
            }

            RtlCopyMemory(keyHeader,
                          Irp->AssociatedIrp.SystemBuffer,
                          sizeof(DVD_COPY_PROTECT_KEY));

            IoCopyCurrentIrpStackLocationToNext(Irp);

            nextStack = IoGetNextIrpStackLocation(Irp);

            nextStack->Parameters.DeviceIoControl.IoControlCode =
                IOCTL_DVD_READ_STRUCTURE;

            readStructureRequest = Irp->AssociatedIrp.SystemBuffer;
            readStructureRequest->Format = DvdDiskKeyDescriptor;
            readStructureRequest->BlockByteOffset.QuadPart = 0;
            readStructureRequest->LayerNumber = 0;
            readStructureRequest->SessionId = keyHeader->SessionId;

            nextStack->Parameters.DeviceIoControl.InputBufferLength =
                sizeof(DVD_READ_STRUCTURE);

            nextStack->Parameters.DeviceIoControl.OutputBufferLength =
                sizeof(READ_DVD_STRUCTURES_HEADER) + sizeof(DVD_DISK_KEY_DESCRIPTOR);

            IoSetCompletionRoutine(Irp,
                                   CdRomDvdReadDiskKeyCompletion,
                                   (PVOID) keyHeader,
                                   TRUE,
                                   TRUE,
                                   TRUE);

            {
                UCHAR uniqueAddress;
                ClassAcquireRemoveLock(DeviceObject, (PIRP)&uniqueAddress);
                ClassReleaseRemoveLock(DeviceObject, Irp);

                IoMarkIrpPending(Irp);
                IoCallDriver(commonExtension->DeviceObject, Irp);
                status = STATUS_PENDING;

                ClassReleaseRemoveLock(DeviceObject, (PIRP)&uniqueAddress);
            }

            return STATUS_PENDING;

        } else {

            IoMarkIrpPending(Irp);
            IoStartPacket(DeviceObject, Irp, NULL, NULL);

        }
        return STATUS_PENDING;
    }

    case IOCTL_DVD_END_SESSION: {

        PDVD_SESSION_ID sessionId = Irp->AssociatedIrp.SystemBuffer;

        TraceLog((CdromDebugTrace,
                    "DvdDeviceControl: [%p] END_SESSION\n", Irp));

        if (cdData->DvdRpc0Device && cdData->DvdRpc0LicenseFailure) {
            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: License Failure\n"));
            status = STATUS_COPY_PROTECTION_FAILURE;
            break;
        }

        if(irpStack->Parameters.DeviceIoControl.InputBufferLength <
            sizeof(DVD_SESSION_ID)) {

            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: EndSession - input buffer too "
                        "small\n"));
            status = STATUS_INVALID_PARAMETER;
            break;
        }

        IoMarkIrpPending(Irp);

        if(*sessionId == DVD_END_ALL_SESSIONS) {

            status = CdRomDvdEndAllSessionsCompletion(DeviceObject, Irp, NULL);

            if(status == STATUS_SUCCESS) {

                //
                // Just complete the request - it was never issued to the
                // lower device
                //

                break;

            } else {

                return STATUS_PENDING;

            }
        }

        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_DVD_GET_REGION: {

        PDVD_COPY_PROTECT_KEY copyProtectKey;
        ULONG keyLength;
        IO_STATUS_BLOCK ioStatus;
        PDVD_DESCRIPTOR_HEADER dvdHeader;
        PDVD_COPYRIGHT_DESCRIPTOR copyRightDescriptor;
        PDVD_REGION dvdRegion;
        PDVD_READ_STRUCTURE readStructure;
        PDVD_RPC_KEY rpcKey;

        TraceLog((CdromDebugTrace,
                    "DvdDeviceControl: [%p] IOCTL_DVD_GET_REGION\n", Irp));

        if (cdData->DvdRpc0Device && cdData->DvdRpc0LicenseFailure) {
            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: License Failure\n"));
            status = STATUS_COPY_PROTECTION_FAILURE;
            break;
        }

        if(irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            sizeof(DVD_REGION)) {

            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: output buffer DVD_REGION too small\n"));
            status = STATUS_INVALID_PARAMETER;
            break;
        }

        //
        // figure out how much data buffer we need
        //

        keyLength = max(sizeof(DVD_DESCRIPTOR_HEADER) +
                            sizeof(DVD_COPYRIGHT_DESCRIPTOR),
                        sizeof(DVD_READ_STRUCTURE)
                        );
        keyLength = max(keyLength,
                        DVD_RPC_KEY_LENGTH
                        );

        //
        // round the size to nearest ULONGLONG -- why?
        //

        keyLength += sizeof(ULONGLONG) - (keyLength & (sizeof(ULONGLONG) - 1));

        readStructure = ExAllocatePoolWithTag(NonPagedPool,
                                              keyLength,
                                              DVD_TAG_READ_KEY);
        if (readStructure == NULL) {
            status = STATUS_INSUFFICIENT_RESOURCES;
            break;
        }

        RtlZeroMemory (readStructure, keyLength);
        readStructure->Format = DvdCopyrightDescriptor;

        //
        // Build a request for READ_STRUCTURE
        //

        ClassSendDeviceIoControlSynchronous(
            IOCTL_DVD_READ_STRUCTURE,
            DeviceObject,
            readStructure,
            keyLength,
            sizeof(DVD_DESCRIPTOR_HEADER) +
                sizeof(DVD_COPYRIGHT_DESCRIPTOR),
            FALSE,
            &ioStatus);

        status = ioStatus.Status;

        if (!NT_SUCCESS(status)) {
            TraceLog((CdromDebugWarning,
                        "CdRomDvdGetRegion => read structure failed %x\n",
                        status));
            ExFreePool(readStructure);
            break;
        }

        //
        // we got the copyright descriptor, so now get the region if possible
        //

        dvdHeader = (PDVD_DESCRIPTOR_HEADER) readStructure;
        copyRightDescriptor = (PDVD_COPYRIGHT_DESCRIPTOR) dvdHeader->Data;

        //
        // the original irp's systembuffer has a copy of the info that
        // should be passed down in the request
        //

        dvdRegion = Irp->AssociatedIrp.SystemBuffer;

        dvdRegion->CopySystem = copyRightDescriptor->CopyrightProtectionType;
        dvdRegion->RegionData = copyRightDescriptor->RegionManagementInformation;

        //
        // now reuse the buffer to request the copy protection info
        //

        copyProtectKey = (PDVD_COPY_PROTECT_KEY) readStructure;
        RtlZeroMemory (copyProtectKey, DVD_RPC_KEY_LENGTH);
        copyProtectKey->KeyLength = DVD_RPC_KEY_LENGTH;
        copyProtectKey->KeyType = DvdGetRpcKey;

        //
        // send a request for READ_KEY
        //

        ClassSendDeviceIoControlSynchronous(
            IOCTL_DVD_READ_KEY,
            DeviceObject,
            copyProtectKey,
            DVD_RPC_KEY_LENGTH,
            DVD_RPC_KEY_LENGTH,
            FALSE,
            &ioStatus);
        status = ioStatus.Status;

        if (!NT_SUCCESS(status)) {
            TraceLog((CdromDebugWarning,
                        "CdRomDvdGetRegion => read key failed %x\n",
                        status));
            ExFreePool(readStructure);
            break;
        }

        //
        // the request succeeded.  if a supported scheme is returned,
        // then return the information to the caller
        //

        rpcKey = (PDVD_RPC_KEY) copyProtectKey->KeyData;

        if (rpcKey->RpcScheme == 1) {

            if (rpcKey->TypeCode) {

                dvdRegion->SystemRegion = ~rpcKey->RegionMask;
                dvdRegion->ResetCount = rpcKey->UserResetsAvailable;

            } else {

                //
                // the drive has not been set for any region
                //

                dvdRegion->SystemRegion = 0;
                dvdRegion->ResetCount = rpcKey->UserResetsAvailable;
            }
            Irp->IoStatus.Information = sizeof(DVD_REGION);

        } else {

            TraceLog((CdromDebugWarning,
                        "CdRomDvdGetRegion => rpcKey->RpcScheme != 1\n"));
            status = STATUS_INVALID_DEVICE_REQUEST;
        }

        ExFreePool(readStructure);
        break;
    }


    case IOCTL_STORAGE_SET_READ_AHEAD: {

        if(irpStack->Parameters.DeviceIoControl.InputBufferLength <
           sizeof(STORAGE_SET_READ_AHEAD)) {

            TraceLog((CdromDebugWarning,
                        "DvdDeviceControl: SetReadAhead buffer too small\n"));
            status = STATUS_INVALID_PARAMETER;
            break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;
    }

    case IOCTL_DISK_IS_WRITABLE: {

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);

        return STATUS_PENDING;

    }

    case IOCTL_DISK_GET_DRIVE_LAYOUT: {

        ULONG size;

        //
        // we always fake zero or one partitions, and one partition
        // structure is included in DRIVE_LAYOUT_INFORMATION
        //
        
        size = FIELD_OFFSET(DRIVE_LAYOUT_INFORMATION, PartitionEntry[1]);


        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Get drive layout\n"));
        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength < size) {            
            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = size;
            break;
        }
        
        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);
        return STATUS_PENDING;


    }
    case IOCTL_DISK_GET_DRIVE_LAYOUT_EX: {
        
        ULONG size;

        //
        // we always fake zero or one partitions, and one partition
        // structure is included in DRIVE_LAYOUT_INFORMATION_EX
        //

        size = FIELD_OFFSET(DRIVE_LAYOUT_INFORMATION_EX, PartitionEntry[1]);

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControl: Get drive layout ex\n"));
        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength < size) {            
            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = size;
            break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);
        return STATUS_PENDING;    
    
    }

    
    case IOCTL_DISK_GET_PARTITION_INFO: {

        //
        // Check that the buffer is large enough.
        //

        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            sizeof(PARTITION_INFORMATION)) {

            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = sizeof(PARTITION_INFORMATION);
            break;
        }
        
        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);
        return STATUS_PENDING;
    
    }
    case IOCTL_DISK_GET_PARTITION_INFO_EX: {

        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            sizeof(PARTITION_INFORMATION_EX)) {

            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = sizeof(PARTITION_INFORMATION_EX);
            break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);
        return STATUS_PENDING;
    }

    case IOCTL_DISK_VERIFY: {

        TraceLog((CdromDebugTrace,
                    "IOCTL_DISK_VERIFY to device %p through irp %p\n",
                    DeviceObject, Irp));

        //
        // Validate buffer length.
        //

        if (irpStack->Parameters.DeviceIoControl.InputBufferLength <
            sizeof(VERIFY_INFORMATION)) {

            status = STATUS_INFO_LENGTH_MISMATCH;
            break;
        }
        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);
        return STATUS_PENDING;
    }

    case IOCTL_DISK_GET_LENGTH_INFO: {
        
        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            sizeof(GET_LENGTH_INFORMATION)) {
            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = sizeof(GET_LENGTH_INFORMATION);
            break;
        }
        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);
        return STATUS_PENDING;
    }

    case IOCTL_CDROM_GET_CONFIGURATION: {

        PGET_CONFIGURATION_IOCTL_INPUT inputBuffer;

        TraceLog((CdromDebugTrace,
                    "IOCTL_CDROM_GET_CONFIGURATION to via irp %p\n", Irp));

        //
        // Validate buffer length.
        //

        if (irpStack->Parameters.DeviceIoControl.InputBufferLength !=
            sizeof(GET_CONFIGURATION_IOCTL_INPUT)) {
            status = STATUS_INFO_LENGTH_MISMATCH;
            break;
        }
        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength <
            sizeof(GET_CONFIGURATION_HEADER)) {
            status = STATUS_BUFFER_TOO_SMALL;
            Irp->IoStatus.Information = sizeof(GET_CONFIGURATION_HEADER);
            break;
        }
        if (irpStack->Parameters.DeviceIoControl.OutputBufferLength > 0xffff) {
            // output buffer is too large
            status = STATUS_INVALID_BUFFER_SIZE;
            break;
        }

        //
        // also verify the arguments are reasonable.
        //

        inputBuffer = Irp->AssociatedIrp.SystemBuffer;
        if (inputBuffer->Feature > 0xffff) {
            status = STATUS_INVALID_PARAMETER;
            break;
        }
        if ((inputBuffer->RequestType != SCSI_GET_CONFIGURATION_REQUEST_TYPE_ONE) &&
            (inputBuffer->RequestType != SCSI_GET_CONFIGURATION_REQUEST_TYPE_CURRENT) &&
            (inputBuffer->RequestType != SCSI_GET_CONFIGURATION_REQUEST_TYPE_ALL)) {
            status = STATUS_INVALID_PARAMETER;
            break;
        }
        if (inputBuffer->Reserved[0] || inputBuffer->Reserved[1]) {
            status = STATUS_INVALID_PARAMETER;
            break;
        }

        IoMarkIrpPending(Irp);
        IoStartPacket(DeviceObject, Irp, NULL, NULL);
        return STATUS_PENDING;

    }

    default: {

        BOOLEAN synchronize = (KeGetCurrentIrql() == PASSIVE_LEVEL);
        PKEVENT deviceControlEvent;

        //
        // If the ioctl has come in at passive level then we will synchronize
        // with our start-io routine when sending the ioctl.  If the ioctl
        // has come in at a higher interrupt level and it was not handled
        // above then it's unlikely to be a request for the class DLL - however
        // we'll still use it's common code to forward the request through.
        //

        if (synchronize) {

            deviceControlEvent = ExAllocatePoolWithTag(NonPagedPool,
                                                       sizeof(KEVENT),
                                                       CDROM_TAG_DC_EVENT);

            if (deviceControlEvent == NULL) {

                //
                // must complete this irp unsuccessful here
                //
                status = STATUS_INSUFFICIENT_RESOURCES;
                break;

            } else {

                //PIO_STACK_LOCATION currentStack;

                KeInitializeEvent(deviceControlEvent, NotificationEvent, FALSE);

                //currentStack = IoGetCurrentIrpStackLocation(Irp);
                nextStack = IoGetNextIrpStackLocation(Irp);

                //
                // Copy the stack down a notch
                //

                IoCopyCurrentIrpStackLocationToNext(Irp);

                IoSetCompletionRoutine(
                    Irp,
                    CdRomClassIoctlCompletion,
                    deviceControlEvent,
                    TRUE,
                    TRUE,
                    TRUE
                    );

                IoSetNextIrpStackLocation(Irp);

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

                //
                // Override volume verifies on this stack location so that we
                // will be forced through the synchronization.  Once this
                // location goes away we get the old value back
                //

                SET_FLAG(nextStack->Flags, SL_OVERRIDE_VERIFY_VOLUME);

                IoStartPacket(DeviceObject, Irp, NULL, NULL);

                //
                // Wait for CdRomClassIoctlCompletion to set the event. This
                // ensures serialization remains intact for these unhandled device
                // controls.
                //

                KeWaitForSingleObject(
                    deviceControlEvent,
                    Executive,
                    KernelMode,
                    FALSE,
                    NULL);

                ExFreePool(deviceControlEvent);

                TraceLog((CdromDebugTrace,
                            "CdRomDeviceControl: irp %p synchronized\n", Irp));

                status = Irp->IoStatus.Status;
            }

        } else {
            status = STATUS_SUCCESS;
        }

        //
        // If an error occured then propagate that back up - we are no longer
        // guaranteed synchronization and the upper layers will have to
        // retry.
        //
        // If no error occured, call down to the class driver directly
        // then start up the next request.
        //

        if (NT_SUCCESS(status)) {

            UCHAR uniqueAddress;

            //
            // The class device control routine will release the remove
            // lock for this Irp.  We need to make sure we have one
            // available so that it's safe to call IoStartNextPacket
            //

            if(synchronize) {

                ClassAcquireRemoveLock(DeviceObject, (PIRP)&uniqueAddress);

            }

            status = ClassDeviceControl(DeviceObject, Irp);

            if(synchronize) {
                KeRaiseIrql(DISPATCH_LEVEL, &irql);
                IoStartNextPacket(DeviceObject, FALSE);
                KeLowerIrql(irql);
                ClassReleaseRemoveLock(DeviceObject, (PIRP)&uniqueAddress);
            }
            return status;

        }

        //
        // an error occurred (either STATUS_INSUFFICIENT_RESOURCES from
        // attempting to synchronize or  StartIo() error'd this one
        // out), so we need to finish the irp, which is
        // done at the end of this routine.
        //
        break;

    } // end default case

    } // end switch()

    if (status == STATUS_VERIFY_REQUIRED) {

        //
        // If the status is verified required and this request
        // should bypass verify required then retry the request.
        //

        if (irpStack->Flags & SL_OVERRIDE_VERIFY_VOLUME) {

            status = STATUS_IO_DEVICE_ERROR;
            goto RetryControl;

        }
    }

    if (IoIsErrorUserInduced(status)) {

        if (Irp->Tail.Overlay.Thread) {
            IoSetHardErrorOrVerifyDevice(Irp, DeviceObject);
        }

    }

    //
    // Update IRP with completion status.
    //

    Irp->IoStatus.Status = status;

    //
    // Complete the request.
    //

    ClassReleaseRemoveLock(DeviceObject, Irp);
    ClassCompleteRequest(DeviceObject, Irp, IO_DISK_INCREMENT);
    TraceLog((CdromDebugTrace,
                "CdRomDeviceControl: Status is %lx\n", status));
    return status;

} // end CdRomDeviceControl()

NTSTATUS
NTAPI
CdRomClassIoctlCompletion(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )
/*++

Routine Description:

    This routine signals the event used by CdRomDeviceControl to synchronize
    class driver (and lower level driver) ioctls with cdrom's startio routine.
    The irp completion is short-circuited so that CdRomDeviceControlDispatch
    can reissue it once it wakes up.

Arguments:

    DeviceObject - the device object
    Irp - the request we are synchronizing
    Context - a PKEVENT that we need to signal

Return Value:

    NTSTATUS

--*/
{
    PKEVENT syncEvent = (PKEVENT) Context;

    TraceLog((CdromDebugTrace,
                "CdRomClassIoctlCompletion: setting event for irp %p\n", Irp));

    //
    // We released the lock when we completed this request.  Reacquire it.
    //

    ClassAcquireRemoveLock(DeviceObject, Irp);

    KeSetEvent(syncEvent, IO_DISK_INCREMENT, FALSE);

    return STATUS_MORE_PROCESSING_REQUIRED;
}

NTSTATUS
NTAPI
CdRomDeviceControlCompletion(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )
{
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;
    PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;

    PCDROM_DATA         cdData = (PCDROM_DATA)(commonExtension->DriverData);
    BOOLEAN             use6Byte = TEST_FLAG(cdData->XAFlags, XA_USE_6_BYTE);

    PIO_STACK_LOCATION  irpStack        = IoGetCurrentIrpStackLocation(Irp);
    PIO_STACK_LOCATION  realIrpStack;
    PIO_STACK_LOCATION  realIrpNextStack;

    PSCSI_REQUEST_BLOCK srb     = Context;

    PIRP                realIrp = NULL;

    NTSTATUS            status;
    BOOLEAN             retry;
    ULONG retryCount;

    //
    // Extract the 'real' irp from the irpstack.
    //

    realIrp = (PIRP) irpStack->Parameters.Others.Argument2;
    realIrpStack = IoGetCurrentIrpStackLocation(realIrp);
    realIrpNextStack = IoGetNextIrpStackLocation(realIrp);

    //
    // check that we've really got the correct irp
    //

    ASSERT(realIrpNextStack->Parameters.Others.Argument3 == Irp);

    //
    // Check SRB status for success of completing request.
    //

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

        ULONG retryInterval;

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControlCompletion: Irp %p, Srb %p Real Irp %p Status %lx\n",
                    Irp,
                    srb,
                    realIrp,
                    srb->SrbStatus));

        //
        // Release the queue if it is frozen.
        //

        if (srb->SrbStatus & SRB_STATUS_QUEUE_FROZEN) {
            TraceLog((CdromDebugTrace,
                        "CdRomDeviceControlCompletion: Releasing Queue\n"));
            ClassReleaseQueue(DeviceObject);
        }


        retry = ClassInterpretSenseInfo(DeviceObject,
                                        srb,
                                        irpStack->MajorFunction,
                                        irpStack->Parameters.DeviceIoControl.IoControlCode,
                                        MAXIMUM_RETRIES - ((ULONG)(ULONG_PTR)realIrpNextStack->Parameters.Others.Argument1),
                                        &status,
                                        &retryInterval);

        TraceLog((CdromDebugTrace,
                    "CdRomDeviceControlCompletion: IRP will %sbe retried\n",
                    (retry ? "" : "not ")));

        //
        // Some of the Device Controls need special cases on non-Success status's.
        //

        if (realIrpStack->MajorFunction == IRP_MJ_DEVICE_CONTROL) {
            if ((realIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_CDROM_GET_LAST_SESSION) ||
                (realIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_CDROM_READ_TOC)         ||
                (realIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_CDROM_READ_TOC_EX)      ||
                (realIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_CDROM_GET_CONTROL)      ||
                (realIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_CDROM_GET_VOLUME)) {

                if (status == STATUS_DATA_OVERRUN) {
                    status = STATUS_SUCCESS;
                    retry = FALSE;
                }
            }

            if (realIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_CDROM_READ_Q_CHANNEL) {
                PLAY_ACTIVE(fdoExtension) = FALSE;
            }
        }

        //
        // If the status is verified required and the this request
        // should bypass verify required then retry the request.
        //

        if (realIrpStack->Flags & SL_OVERRIDE_VERIFY_VOLUME &&
            status == STATUS_VERIFY_REQUIRED) {

            // note: status gets overwritten here
            status = STATUS_IO_DEVICE_ERROR;
            retry = TRUE;

            if (((realIrpStack->MajorFunction == IRP_MJ_DEVICE_CONTROL) ||
                 (realIrpStack->MajorFunction == IRP_MJ_INTERNAL_DEVICE_CONTROL)
                ) &&
                ((realIrpStack->Parameters.DeviceIoControl.IoControlCode ==
                  IOCTL_CDROM_CHECK_VERIFY) ||
                 (realIrpStack->Parameters.DeviceIoControl.IoControlCode ==
                  IOCTL_STORAGE_CHECK_VERIFY) ||
                 (realIrpStack->Parameters.DeviceIoControl.IoControlCode ==
                  IOCTL_STORAGE_CHECK_VERIFY2) ||
                 (realIrpStack->Parameters.DeviceIoControl.IoControlCode ==
                  IOCTL_DISK_CHECK_VERIFY)
                )
               ) {

                //
                // Update the geometry information, as the media could have
                // changed. The completion routine for this will complete
                // the real irp and start the next packet.
                //

                if (srb) {
                    if (srb->SenseInfoBuffer) {
                        ExFreePool(srb->SenseInfoBuffer);
                    }
                    if (srb->DataBuffer) {
                        ExFreePool(srb->DataBuffer);
                    }
                    ExFreePool(srb);
                    srb = NULL;
                }

                if (Irp->MdlAddress) {
                    IoFreeMdl(Irp->MdlAddress);
                    Irp->MdlAddress = NULL;
                }

                IoFreeIrp(Irp);
                Irp = NULL;

                status = CdRomUpdateCapacity(fdoExtension, realIrp, NULL);
                TraceLog((CdromDebugTrace,
                            "CdRomDeviceControlCompletion: [%p] "
                            "CdRomUpdateCapacity completed with status %lx\n",
                            realIrp, status));
                
                //
                // needed to update the capacity.
                // the irp's already handed off to CdRomUpdateCapacity().
                // we've already free'd the current irp.
                // nothing left to do in this code path.
                //
                
                return STATUS_MORE_PROCESSING_REQUIRED;

            } // end of ioctls to update capacity

        }

        //
        // get current retry count
        //
        retryCount = PtrToUlong(realIrpNextStack->Parameters.Others.Argument1);

        if (retry && retryCount) {

            //
            // update retry count
            //
            realIrpNextStack->Parameters.Others.Argument1 = UlongToPtr(retryCount-1);

            if (((ULONG)(ULONG_PTR)realIrpNextStack->Parameters.Others.Argument1)) {

                //
                // Retry request.
                //

                TraceLog((CdromDebugWarning,
                            "Retry request %p - Calling StartIo\n", Irp));


                ExFreePool(srb->SenseInfoBuffer);
                if (srb->DataBuffer) {
                    ExFreePool(srb->DataBuffer);
                }
                ExFreePool(srb);
                if (Irp->MdlAddress) {
                    IoFreeMdl(Irp->MdlAddress);
                }

                realIrpNextStack->Parameters.Others.Argument3 = (PVOID)-1;
                IoFreeIrp(Irp);

                CdRomRetryRequest(fdoExtension, realIrp, retryInterval, FALSE);
                return STATUS_MORE_PROCESSING_REQUIRED;
            }

            //
            // Exhausted retries. Fall through and complete the request with
            // the appropriate status.
            //

        }
    } else {

        //
        // Set status for successful request.
        //

        status = STATUS_SUCCESS;

    }


    if (NT_SUCCESS(status)) {
        
        //BOOLEAN b = FALSE;


        switch (realIrpStack->Parameters.DeviceIoControl.IoControlCode) {

        case IOCTL_CDROM_GET_CONFIGURATION: {
            RtlMoveMemory(realIrp->AssociatedIrp.SystemBuffer,
                          srb->DataBuffer,
                          srb->DataTransferLength);
            realIrp->IoStatus.Information = srb->DataTransferLength;
            break;
        }

        case IOCTL_DISK_GET_LENGTH_INFO: {
            
            PGET_LENGTH_INFORMATION lengthInfo;
            
            CdRomInterpretReadCapacity(DeviceObject,
                                       (PREAD_CAPACITY_DATA)srb->DataBuffer);

            lengthInfo = (PGET_LENGTH_INFORMATION)realIrp->AssociatedIrp.SystemBuffer;
            lengthInfo->Length = commonExtension->PartitionLength;
            realIrp->IoStatus.Information = sizeof(GET_LENGTH_INFORMATION);
            status = STATUS_SUCCESS;
            break;
        }

        case IOCTL_DISK_GET_DRIVE_GEOMETRY_EX:
        case IOCTL_CDROM_GET_DRIVE_GEOMETRY_EX: {
            
            PDISK_GEOMETRY_EX geometryEx;
            
            CdRomInterpretReadCapacity(DeviceObject,
                                       (PREAD_CAPACITY_DATA)srb->DataBuffer);

            geometryEx = (PDISK_GEOMETRY_EX)(realIrp->AssociatedIrp.SystemBuffer);
            geometryEx->DiskSize = commonExtension->PartitionLength;
            geometryEx->Geometry = fdoExtension->DiskGeometry;
            realIrp->IoStatus.Information =
                FIELD_OFFSET(DISK_GEOMETRY_EX, Data);
            break;
        }

        case IOCTL_DISK_GET_DRIVE_GEOMETRY:
        case IOCTL_CDROM_GET_DRIVE_GEOMETRY: {

            PDISK_GEOMETRY geometry;
            
            CdRomInterpretReadCapacity(DeviceObject,
                                       (PREAD_CAPACITY_DATA)srb->DataBuffer);

            geometry = (PDISK_GEOMETRY)(realIrp->AssociatedIrp.SystemBuffer);
            *geometry = fdoExtension->DiskGeometry;
            realIrp->IoStatus.Information = sizeof(DISK_GEOMETRY);
            break;
        }

        case IOCTL_DISK_VERIFY: {
            //
            // nothing to do but return the status...
            //
            break;
        }

        case IOCTL_DISK_CHECK_VERIFY:
        case IOCTL_STORAGE_CHECK_VERIFY:
        case IOCTL_CDROM_CHECK_VERIFY: {

            if((realIrpStack->Parameters.DeviceIoControl.IoControlCode == IOCTL_CDROM_CHECK_VERIFY) &&
               (realIrpStack->Parameters.DeviceIoControl.OutputBufferLength)) {

                *((PULONG)realIrp->AssociatedIrp.SystemBuffer) =
                    commonExtension->PartitionZeroExtension->MediaChangeCount;

                realIrp->IoStatus.Information = sizeof(ULONG);
            } else {
                realIrp->IoStatus.Information = 0;
            }

            TraceLog((CdromDebugTrace,
                        "CdRomDeviceControlCompletion: [%p] completing "
                        "CHECK_VERIFY buddy irp %p\n", realIrp, Irp));
            break;
        }

        case IOCTL_CDROM_READ_TOC_EX: {

            if (srb->DataTransferLength < MINIMUM_CDROM_READ_TOC_EX_SIZE) {
                status = STATUS_INVALID_DEVICE_REQUEST;
                break;
            }

            //
            // Copy the returned info into the user buffer.
            //

            RtlMoveMemory(realIrp->AssociatedIrp.SystemBuffer,
                          srb->DataBuffer,
                          srb->DataTransferLength);

            //
            // update information field.
            //

            realIrp->IoStatus.Information = srb->DataTransferLength;
            break;
        }


        case IOCTL_CDROM_GET_LAST_SESSION:
        case IOCTL_CDROM_READ_TOC: {

            //
            // Copy the returned info into the user buffer.
            //

            RtlMoveMemory(realIrp->AssociatedIrp.SystemBuffer,
                          srb->DataBuffer,
                          srb->DataTransferLength);

            //
            // update information field.
            //

            realIrp->IoStatus.Information = srb->DataTransferLength;
            break;
        }

        case IOCTL_DVD_READ_STRUCTURE: {

            DVD_STRUCTURE_FORMAT format = ((PDVD_READ_STRUCTURE) realIrp->AssociatedIrp.SystemBuffer)->Format;

            PDVD_DESCRIPTOR_HEADER header = realIrp->AssociatedIrp.SystemBuffer;

            //FOUR_BYTE fourByte;
            //PTWO_BYTE twoByte;
            //UCHAR tmp;

            TraceLog((CdromDebugTrace,
                        "DvdDeviceControlCompletion - IOCTL_DVD_READ_STRUCTURE: completing irp %p (buddy %p)\n",
                        Irp,
                        realIrp));

            TraceLog((CdromDebugTrace,
                        "DvdDCCompletion - READ_STRUCTURE: descriptor format of %d\n", format));

            RtlMoveMemory(header,
                          srb->DataBuffer,
                          srb->DataTransferLength);

            //
            // Cook the data.  There are a number of fields that really
            // should be byte-swapped for the caller.
            //

            TraceLog((CdromDebugInfo,
                      "DvdDCCompletion - READ_STRUCTURE:\n"
                      "\tHeader at %p\n"
                      "\tDvdDCCompletion - READ_STRUCTURE: data at %p\n"
                      "\tDataBuffer was at %p\n"
                      "\tDataTransferLength was %lx\n",
                      header,
                      header->Data,
                      srb->DataBuffer,
                      srb->DataTransferLength));

            //
            // First the fields in the header
            //

            TraceLog((CdromDebugInfo, "READ_STRUCTURE: header->Length %lx -> ",
                           header->Length));
            REVERSE_SHORT(&header->Length);
            TraceLog((CdromDebugInfo, "%lx\n", header->Length));

            //
            // Now the fields in the descriptor
            //

            if(format == DvdPhysicalDescriptor) {

                PDVD_LAYER_DESCRIPTOR layer = (PDVD_LAYER_DESCRIPTOR) &(header->Data[0]);

                TraceLog((CdromDebugInfo, "READ_STRUCTURE: StartingDataSector %lx -> ",
                               layer->StartingDataSector));
                REVERSE_LONG(&(layer->StartingDataSector));
                TraceLog((CdromDebugInfo, "%lx\n", layer->StartingDataSector));

                TraceLog((CdromDebugInfo, "READ_STRUCTURE: EndDataSector %lx -> ",
                               layer->EndDataSector));
                REVERSE_LONG(&(layer->EndDataSector));
                TraceLog((CdromDebugInfo, "%lx\n", layer->EndDataSector));

                TraceLog((CdromDebugInfo, "READ_STRUCTURE: EndLayerZeroSector %lx -> ",
                               layer->EndLayerZeroSector));
                REVERSE_LONG(&(layer->EndLayerZeroSector));
                TraceLog((CdromDebugInfo, "%lx\n", layer->EndLayerZeroSector));
            }

            TraceLog((CdromDebugTrace, "Status is %lx\n", Irp->IoStatus.Status));
            TraceLog((CdromDebugTrace, "DvdDeviceControlCompletion - "
                        "IOCTL_DVD_READ_STRUCTURE: data transfer length of %d\n",
                        srb->DataTransferLength));

            realIrp->IoStatus.Information = srb->DataTransferLength;
            break;
        }

        case IOCTL_DVD_READ_KEY: {

            PDVD_COPY_PROTECT_KEY copyProtectKey = realIrp->AssociatedIrp.SystemBuffer;

            PCDVD_KEY_HEADER keyHeader = srb->DataBuffer;
            ULONG dataLength;

            ULONG transferLength =
                srb->DataTransferLength -
                FIELD_OFFSET(CDVD_KEY_HEADER, Data);

            //
            // Adjust the data length to ignore the two reserved bytes in the
            // header.
            //

            dataLength = (keyHeader->DataLength[0] << 8) +
                         keyHeader->DataLength[1];
            dataLength -= 2;

            //
            // take the minimum of the transferred length and the
            // length as specified in the header.
            //

            if(dataLength < transferLength) {
                transferLength = dataLength;
            }

            TraceLog((CdromDebugTrace,
                        "DvdDeviceControlCompletion: [%p] - READ_KEY with "
                        "transfer length of (%d or %d) bytes\n",
                        Irp,
                        dataLength,
                        srb->DataTransferLength - 2));

            //
            // Copy the key data into the return buffer
            //
            if(copyProtectKey->KeyType == DvdTitleKey) {

                RtlMoveMemory(copyProtectKey->KeyData,
                              keyHeader->Data + 1,
                              transferLength - 1);
                copyProtectKey->KeyData[transferLength - 1] = 0;

                //
                // If this is a title key then we need to copy the CGMS flags
                // as well.
                //
                copyProtectKey->KeyFlags = *(keyHeader->Data);

            } else {

                RtlMoveMemory(copyProtectKey->KeyData,
                              keyHeader->Data,
                              transferLength);
            }

            copyProtectKey->KeyLength = sizeof(DVD_COPY_PROTECT_KEY);
            copyProtectKey->KeyLength += transferLength;

            realIrp->IoStatus.Information = copyProtectKey->KeyLength;
            break;
        }

        case IOCTL_DVD_START_SESSION: {

            PDVD_SESSION_ID sessionId = realIrp->AssociatedIrp.SystemBuffer;

            PCDVD_KEY_HEADER keyHeader = srb->DataBuffer;
            PCDVD_REPORT_AGID_DATA keyData = (PCDVD_REPORT_AGID_DATA) keyHeader->Data;

            *sessionId = keyData->AGID;

            realIrp->IoStatus.Information = sizeof(DVD_SESSION_ID);

            break;
        }

        case IOCTL_DVD_END_SESSION:
        case IOCTL_DVD_SEND_KEY:
        case IOCTL_DVD_SEND_KEY2:

            //
            // nothing to return
            //
            realIrp->IoStatus.Information = 0;
            break;

        case IOCTL_CDROM_PLAY_AUDIO_MSF:

            PLAY_ACTIVE(fdoExtension) = TRUE;

            break;

        case IOCTL_CDROM_READ_Q_CHANNEL: {

            PSUB_Q_CHANNEL_DATA userChannelData = realIrp->AssociatedIrp.SystemBuffer;
            PCDROM_SUB_Q_DATA_FORMAT inputBuffer = realIrp->AssociatedIrp.SystemBuffer;
            PSUB_Q_CHANNEL_DATA subQPtr = srb->DataBuffer;

#if DBG
            switch( inputBuffer->Format ) {

            case IOCTL_CDROM_CURRENT_POSITION:
                TraceLog((CdromDebugTrace,"CdRomDeviceControlCompletion: Audio Status is %u\n", subQPtr->CurrentPosition.Header.AudioStatus ));
                TraceLog((CdromDebugTrace,"CdRomDeviceControlCompletion: ADR = 0x%x\n", subQPtr->CurrentPosition.ADR ));
                TraceLog((CdromDebugTrace,"CdRomDeviceControlCompletion: Control = 0x%x\n", subQPtr->CurrentPosition.Control ));
                TraceLog((CdromDebugTrace,"CdRomDeviceControlCompletion: Track = %u\n", subQPtr->CurrentPosition.TrackNumber ));
                TraceLog((CdromDebugTrace,"CdRomDeviceControlCompletion: Index = %u\n", subQPtr->CurrentPosition.IndexNumber ));
                TraceLog((CdromDebugTrace,"CdRomDeviceControlCompletion: Absolute Address = %x\n", *((PULONG)subQPtr->CurrentPosition.AbsoluteAddress) ));
                TraceLog((CdromDebugTrace,"CdRomDeviceControlCompletion: Relative Address = %x\n", *((PULONG)subQPtr->CurrentPosition.TrackRelativeAddress) ));
                break;

            case IOCTL_CDROM_MEDIA_CATALOG:
                TraceLog((CdromDebugTrace,"CdRomDeviceControlCompletion: Audio Status is %u\n", subQPtr->MediaCatalog.Header.AudioStatus ));
                TraceLog((CdromDebugTrace,"CdRomDeviceControlCompletion: Mcval is %u\n", subQPtr->MediaCatalog.Mcval ));
                break;

            case IOCTL_CDROM_TRACK_ISRC:
                TraceLog((CdromDebugTrace,"CdRomDeviceControlCompletion: Audio Status is %u\n", subQPtr->TrackIsrc.Header.AudioStatus ));
                TraceLog((CdromDebugTrace,"CdRomDeviceControlCompletion: Tcval is %u\n", subQPtr->TrackIsrc.Tcval ));
                break;

            }
#endif

            //
            // Update the play active status.
            //

            if (subQPtr->CurrentPosition.Header.AudioStatus == AUDIO_STATUS_IN_PROGRESS) {

                PLAY_ACTIVE(fdoExtension) = TRUE;

            } else {

                PLAY_ACTIVE(fdoExtension) = FALSE;

            }

            //
            // Check if output buffer is large enough to contain
            // the data.
            //

            if (realIrpStack->Parameters.DeviceIoControl.OutputBufferLength <
                srb->DataTransferLength) {

                srb->DataTransferLength =
                    realIrpStack->Parameters.DeviceIoControl.OutputBufferLength;
            }

            //
            // Copy our buffer into users.
            //

            RtlMoveMemory(userChannelData,
                          subQPtr,
                          srb->DataTransferLength);

            realIrp->IoStatus.Information = srb->DataTransferLength;
            break;
        }

        case IOCTL_CDROM_PAUSE_AUDIO:

            PLAY_ACTIVE(fdoExtension) = FALSE;
            realIrp->IoStatus.Information = 0;
            break;

        case IOCTL_CDROM_RESUME_AUDIO:

            realIrp->IoStatus.Information = 0;
            break;

        case IOCTL_CDROM_SEEK_AUDIO_MSF:

            realIrp->IoStatus.Information = 0;
            break;

        case IOCTL_CDROM_STOP_AUDIO:

            PLAY_ACTIVE(fdoExtension) = FALSE;
            realIrp->IoStatus.Information = 0;
            break;

        case IOCTL_CDROM_GET_CONTROL: {

            PCDROM_AUDIO_CONTROL audioControl = srb->DataBuffer;
            PAUDIO_OUTPUT        audioOutput;
            ULONG                bytesTransferred;

            audioOutput = ClassFindModePage((PCHAR)audioControl,
                                            srb->DataTransferLength,
                                            CDROM_AUDIO_CONTROL_PAGE,
                                            use6Byte);
            //
            // Verify the page is as big as expected.
            //

            bytesTransferred = (ULONG)((PCHAR) audioOutput - (PCHAR) audioControl) +
                               sizeof(AUDIO_OUTPUT);

            if (audioOutput != NULL &&
                srb->DataTransferLength >= bytesTransferred) {

                audioControl->LbaFormat = audioOutput->LbaFormat;

                audioControl->LogicalBlocksPerSecond =
                    (audioOutput->LogicalBlocksPerSecond[0] << (UCHAR)8) |
                    audioOutput->LogicalBlocksPerSecond[1];

                realIrp->IoStatus.Information = sizeof(CDROM_AUDIO_CONTROL);

            } else {
                realIrp->IoStatus.Information = 0;
                status = STATUS_INVALID_DEVICE_REQUEST;
            }
            break;
        }

        case IOCTL_CDROM_GET_VOLUME: {

            PAUDIO_OUTPUT audioOutput;
            PVOLUME_CONTROL volumeControl = srb->DataBuffer;
            ULONG i;
            ULONG bytesTransferred;

            audioOutput = ClassFindModePage((PCHAR)volumeControl,
                                                 srb->DataTransferLength,
                                                 CDROM_AUDIO_CONTROL_PAGE,
                                                 use6Byte);

            //
            // Verify the page is as big as expected.
            //

            bytesTransferred = (ULONG)((PCHAR) audioOutput - (PCHAR) volumeControl) +
                               sizeof(AUDIO_OUTPUT);

            if (audioOutput != NULL &&
                srb->DataTransferLength >= bytesTransferred) {

                for (i=0; i<4; i++) {
                    volumeControl->PortVolume[i] =
                        audioOutput->PortOutput[i].Volume;
                }

                //
                // Set bytes transferred in IRP.
                //

                realIrp->IoStatus.Information = sizeof(VOLUME_CONTROL);

            } else {
                realIrp->IoStatus.Information = 0;
                status = STATUS_INVALID_DEVICE_REQUEST;
            }

            break;
        }

        case IOCTL_CDROM_SET_VOLUME:

            realIrp->IoStatus.Information = 0;
            break;

        default:

            ASSERT(FALSE);
            realIrp->IoStatus.Information = 0;
            status = STATUS_INVALID_DEVICE_REQUEST;

        } // end switch()
    }

    //
    // Deallocate srb and sense buffer.
    //

    if (srb) {
        if (srb->DataBuffer) {
            ExFreePool(srb->DataBuffer);
        }
        if (srb->SenseInfoBuffer) {
            ExFreePool(srb->SenseInfoBuffer);
        }
        ExFreePool(srb);
    }

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

    if (Irp->MdlAddress) {
        IoFreeMdl(Irp->MdlAddress);
    }

    IoFreeIrp(Irp);

    //
    // Set status in completing IRP.
    //

    realIrp->IoStatus.Status = status;

    //
    // Set the hard error if necessary.
    //

    if (!NT_SUCCESS(status) && IoIsErrorUserInduced(status)) {

        //
        // Store DeviceObject for filesystem, and clear
        // in IoStatus.Information field.
        //

        TraceLog((CdromDebugWarning,
                    "CdRomDeviceCompletion - Setting Hard Error on realIrp %p\n",
                    realIrp));
        if (realIrp->Tail.Overlay.Thread) {
            IoSetHardErrorOrVerifyDevice(realIrp, DeviceObject);
        }

        realIrp->IoStatus.Information = 0;
    }
    
    //
    // note: must complete the realIrp, as the completed irp (above)
    //       was self-allocated.
    //

    CdRomCompleteIrpAndStartNextPacketSafely(DeviceObject, realIrp);
    return STATUS_MORE_PROCESSING_REQUIRED;
}

NTSTATUS
NTAPI
CdRomSetVolumeIntermediateCompletion(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )
{
    PFUNCTIONAL_DEVICE_EXTENSION deviceExtension = DeviceObject->DeviceExtension;
    PCOMMON_DEVICE_EXTENSION commonExtension = DeviceObject->DeviceExtension;

    PIO_STACK_LOCATION  irpStack = IoGetCurrentIrpStackLocation(Irp);
    PCDROM_DATA         cdData = (PCDROM_DATA)(commonExtension->DriverData);
    BOOLEAN             use6Byte = TEST_FLAG(cdData->XAFlags, XA_USE_6_BYTE);
    PIO_STACK_LOCATION  realIrpStack;
    PIO_STACK_LOCATION  realIrpNextStack;
    PSCSI_REQUEST_BLOCK srb     = Context;
    PIRP                realIrp = NULL;
    NTSTATUS            status;
    BOOLEAN             retry;
    ULONG retryCount;

    //
    // Extract the 'real' irp from the irpstack.
    //

    realIrp = (PIRP) irpStack->Parameters.Others.Argument2;
    realIrpStack = IoGetCurrentIrpStackLocation(realIrp);
    realIrpNextStack = IoGetNextIrpStackLocation(realIrp);

    //
    // Check SRB status for success of completing request.
    //

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

        ULONG retryInterval;

        TraceLog((CdromDebugTrace,
                    "CdRomSetVolumeIntermediateCompletion: Irp %p, Srb %p, Real Irp %p\n",
                    Irp,
                    srb,
                    realIrp));

        //
        // Release the queue if it is frozen.
        //

        if (srb->SrbStatus & SRB_STATUS_QUEUE_FROZEN) {
            ClassReleaseQueue(DeviceObject);
        }


        retry = ClassInterpretSenseInfo(DeviceObject,
                                            srb,
                                            irpStack->MajorFunction,
                                            irpStack->Parameters.DeviceIoControl.IoControlCode,
                                            MAXIMUM_RETRIES - ((ULONG)(ULONG_PTR)realIrpNextStack->Parameters.Others.Argument1),
                                            &status,
                                            &retryInterval);

        if (status == STATUS_DATA_OVERRUN) {
            status = STATUS_SUCCESS;
            retry = FALSE;
        }

        //
        // If the status is verified required and the this request
        // should bypass verify required then retry the request.
        //

        if (realIrpStack->Flags & SL_OVERRIDE_VERIFY_VOLUME &&
            status == STATUS_VERIFY_REQUIRED) {

            status = STATUS_IO_DEVICE_ERROR;
            retry = TRUE;
        }

        //
        // get current retry count
        //
        retryCount = PtrToUlong(realIrpNextStack->Parameters.Others.Argument1);

        if (retry && retryCount) {

            //
            // update retry count
            //
            realIrpNextStack->Parameters.Others.Argument1 = UlongToPtr(retryCount-1);


            if (((ULONG)(ULONG_PTR)realIrpNextStack->Parameters.Others.Argument1)) {

                //
                // Retry request.
                //

                TraceLog((CdromDebugWarning,
                            "Retry request %p - Calling StartIo\n", Irp));


                ExFreePool(srb->SenseInfoBuffer);
                ExFreePool(srb->DataBuffer);
                ExFreePool(srb);
                if (Irp->MdlAddress) {
                    IoFreeMdl(Irp->MdlAddress);
                }

                IoFreeIrp(Irp);

                CdRomRetryRequest(deviceExtension,
                                  realIrp,
                                  retryInterval,
                                  FALSE);

                return STATUS_MORE_PROCESSING_REQUIRED;

            }

            //
            // Exhausted retries. Fall through and complete the request with the appropriate status.
            //

        }
    } else {

        //
        // Set status for successful request.
        //

        status = STATUS_SUCCESS;
    
    }

    if (NT_SUCCESS(status)) {

        PAUDIO_OUTPUT   audioInput = NULL;
        PAUDIO_OUTPUT   audioOutput;
        PVOLUME_CONTROL volumeControl = realIrp->AssociatedIrp.SystemBuffer;
        ULONG           i,bytesTransferred,headerLength;
        PVOID           dataBuffer;
        PCDB            cdb;

        audioInput = ClassFindModePage((PCHAR)srb->DataBuffer,
                                             srb->DataTransferLength,
                                             CDROM_AUDIO_CONTROL_PAGE,
                                             use6Byte);

        //
        // Check to make sure the mode sense data is valid before we go on
        //

        if(audioInput == NULL) {

            TraceLog((CdromDebugWarning,
                        "Mode Sense Page %d not found\n",
                        CDROM_AUDIO_CONTROL_PAGE));

            realIrp->IoStatus.Information = 0;
            realIrp->IoStatus.Status = STATUS_INVALID_DEVICE_REQUEST;
            goto SafeExit;
        }

        if (use6Byte) {
            headerLength = sizeof(MODE_PARAMETER_HEADER);
        } else {
            headerLength = sizeof(MODE_PARAMETER_HEADER10);
        }

        bytesTransferred = sizeof(AUDIO_OUTPUT) + headerLength;

        //
        // Allocate a new buffer for the mode select.
        //

        dataBuffer = ExAllocatePoolWithTag(NonPagedPoolCacheAligned,
                                    bytesTransferred,
                                    CDROM_TAG_VOLUME_INT);

        if (!dataBuffer) {
            realIrp->IoStatus.Information = 0;
            realIrp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
            goto SafeExit;
        }

        RtlZeroMemory(dataBuffer, bytesTransferred);

        //
        // Rebuild the data buffer to include the user requested values.
        //

        audioOutput = (PAUDIO_OUTPUT) ((PCHAR) dataBuffer + headerLength);

        for (i=0; i<4; i++) {
            audioOutput->PortOutput[i].Volume =
                volumeControl->PortVolume[i];
            audioOutput->PortOutput[i].ChannelSelection =
                audioInput->PortOutput[i].ChannelSelection;
        }

        audioOutput->CodePage = CDROM_AUDIO_CONTROL_PAGE;
        audioOutput->ParameterLength = sizeof(AUDIO_OUTPUT) - 2;
        audioOutput->Immediate = MODE_SELECT_IMMEDIATE;

        //
        // Free the old data buffer, mdl.
        //

        IoFreeMdl(Irp->MdlAddress);
        Irp->MdlAddress = NULL;
        ExFreePool(srb->DataBuffer);

        //
        // set the data buffer to new allocation, so it can be
        // freed in the exit path
        //
        
        srb->DataBuffer = dataBuffer;

        //
        // rebuild the srb.
        //

        cdb = (PCDB)srb->Cdb;
        RtlZeroMemory(cdb, CDB12GENERIC_LENGTH);

        srb->SrbStatus = srb->ScsiStatus = 0;
        srb->SrbFlags = deviceExtension->SrbFlags;
        SET_FLAG(srb->SrbFlags, SRB_FLAGS_DISABLE_SYNCH_TRANSFER);
        SET_FLAG(srb->SrbFlags, SRB_FLAGS_DATA_OUT);
        srb->DataTransferLength = bytesTransferred;

        if (use6Byte) {

            cdb->MODE_SELECT.OperationCode = SCSIOP_MODE_SELECT;
            cdb->MODE_SELECT.ParameterListLength = (UCHAR) bytesTransferred;
            cdb->MODE_SELECT.PFBit = 1;
            srb->CdbLength = 6;
        } else {

            cdb->MODE_SELECT10.OperationCode = SCSIOP_MODE_SELECT10;
            cdb->MODE_SELECT10.ParameterListLength[0] = (UCHAR) (bytesTransferred >> 8);
            cdb->MODE_SELECT10.ParameterListLength[1] = (UCHAR) (bytesTransferred & 0xFF);
            cdb->MODE_SELECT10.PFBit = 1;
            srb->CdbLength = 10;
        }

        //
        // Prepare the MDL
        //

        Irp->MdlAddress = IoAllocateMdl(dataBuffer,
                                        bytesTransferred,
                                        FALSE,
                                        FALSE,
                                        (PIRP) NULL);

        if (!Irp->MdlAddress) {
            realIrp->IoStatus.Information = 0;
            realIrp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;
            goto SafeExit;
        }

        MmBuildMdlForNonPagedPool(Irp->MdlAddress);

        irpStack = IoGetNextIrpStackLocation(Irp);
        irpStack->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL;
        irpStack->Parameters.DeviceIoControl.IoControlCode = IOCTL_SCSI_EXECUTE_IN;
        irpStack->Parameters.Scsi.Srb = srb;

        //
        // reset the irp completion.
        //

        IoSetCompletionRoutine(Irp,
                               CdRomDeviceControlCompletion,
                               srb,
                               TRUE,
                               TRUE,
                               TRUE);
        //
        // Call the port driver.
        //

        IoCallDriver(commonExtension->LowerDeviceObject, Irp);

        return STATUS_MORE_PROCESSING_REQUIRED;
    }

SafeExit:

    //
    // Deallocate srb and sense buffer.
    //

    if (srb) {
        if (srb->DataBuffer) {
            ExFreePool(srb->DataBuffer);
        }
        if (srb->SenseInfoBuffer) {
            ExFreePool(srb->SenseInfoBuffer);
        }
        ExFreePool(srb);
    }

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

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

    if (Irp->MdlAddress) {
        IoFreeMdl(Irp->MdlAddress);
    }

    IoFreeIrp(Irp);

    //
    // Set status in completing IRP.
    //

    realIrp->IoStatus.Status = status;

    //
    // Set the hard error if necessary.
    //

    if (!NT_SUCCESS(status) && IoIsErrorUserInduced(status)) {

        //
        // Store DeviceObject for filesystem, and clear
        // in IoStatus.Information field.
        //

        if (realIrp->Tail.Overlay.Thread) {
            IoSetHardErrorOrVerifyDevice(realIrp, DeviceObject);
        }
        realIrp->IoStatus.Information = 0;
    }

    CdRomCompleteIrpAndStartNextPacketSafely(DeviceObject, realIrp);
    return STATUS_MORE_PROCESSING_REQUIRED;
}

NTSTATUS
NTAPI
CdRomDvdEndAllSessionsCompletion(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )

/*++

Routine Description:

    This routine will setup the next stack location to issue an end session
    to the device.  It will increment the session id in the system buffer
    and issue an END_SESSION for that AGID if the AGID is valid.

    When the new AGID is > 3 this routine will complete the request.

Arguments:

    DeviceObject - the device object for this drive

    Irp - the request

    Context - done

Return Value:

    STATUS_MORE_PROCESSING_REQUIRED if there is another AGID to clear
    status otherwise.

--*/

{
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = DeviceObject->DeviceExtension;

    //PIO_STACK_LOCATION nextIrpStack = IoGetNextIrpStackLocation(Irp);

    PDVD_SESSION_ID sessionId = Irp->AssociatedIrp.SystemBuffer;

    //NTSTATUS status;

    if(++(*sessionId) > MAX_COPY_PROTECT_AGID) {

        //
        // We're done here - just return success and let the io system
        // continue to complete it.
        //

        return STATUS_SUCCESS;

    }

    IoCopyCurrentIrpStackLocationToNext(Irp);

    IoSetCompletionRoutine(Irp,
                           CdRomDvdEndAllSessionsCompletion,
                           NULL,
                           TRUE,
                           FALSE,
                           FALSE);

    IoMarkIrpPending(Irp);

    IoCallDriver(fdoExtension->CommonExtension.DeviceObject, Irp);

    //
    // At this point we have to assume the irp may have already been
    // completed.  Ignore the returned status and return.
    //

    return STATUS_MORE_PROCESSING_REQUIRED;
}

NTSTATUS
NTAPI
CdRomDvdReadDiskKeyCompletion(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )

/*++

Routine Description:

    This routine handles the completion of a request to obtain the disk
    key from the dvd media.  It will transform the raw 2K of key data into
    a DVD_COPY_PROTECT_KEY structure and copy back the saved key parameters
    from the context pointer before returning.

Arguments:

    DeviceObject -

    Irp -

    Context - a DVD_COPY_PROTECT_KEY pointer which contains the key
              parameters handed down by the caller.

Return Value:

    STATUS_SUCCESS;

--*/

{
    PDVD_COPY_PROTECT_KEY savedKey = Context;

    PREAD_DVD_STRUCTURES_HEADER rawKey = Irp->AssociatedIrp.SystemBuffer;
    PDVD_COPY_PROTECT_KEY outputKey = Irp->AssociatedIrp.SystemBuffer;

    if (NT_SUCCESS(Irp->IoStatus.Status)) {

        //
        // Shift the data down to its new position.
        //

        RtlMoveMemory(outputKey->KeyData,
                      rawKey->Data,
                      sizeof(DVD_DISK_KEY_DESCRIPTOR));

        RtlCopyMemory(outputKey,
                      savedKey,
                      sizeof(DVD_COPY_PROTECT_KEY));

        outputKey->KeyLength = DVD_DISK_KEY_LENGTH;

        Irp->IoStatus.Information = DVD_DISK_KEY_LENGTH;

    } else {

        TraceLog((CdromDebugWarning,
                    "DiskKey Failed with status %x, %p (%x) bytes\n",
                    Irp->IoStatus.Status,
                    (PVOID)Irp->IoStatus.Information,
                    ((rawKey->Length[0] << 16) | rawKey->Length[1])
                    ));

    }

    //
    // release the context block
    //

    ExFreePool(Context);

    return STATUS_SUCCESS;
}

NTSTATUS
NTAPI
CdRomXACompletion(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )

/*++

Routine Description:

    This routine executes when the port driver has completed a request.
    It looks at the SRB status in the completing SRB and if not success
    it checks for valid request sense buffer information. If valid, the
    info is used to update status with more precise message of type of
    error. This routine deallocates the SRB.

Arguments:

    DeviceObject - Supplies the device object which represents the logical
        unit.

    Irp - Supplies the Irp which has completed.

    Context - Supplies a pointer to the SRB.

Return Value:

    NT status

--*/

{
    PIO_STACK_LOCATION irpStack = IoGetCurrentIrpStackLocation(Irp);
    PSCSI_REQUEST_BLOCK srb = Context;
    PFUNCTIONAL_DEVICE_EXTENSION deviceExtension = DeviceObject->DeviceExtension;
    NTSTATUS status;
    BOOLEAN retry;

    //
    // Check SRB status for success of completing request.
    //

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

        ULONG retryInterval;

        TraceLog((CdromDebugTrace, "CdromXAComplete: IRP %p  SRB %p  Status %x\n",
                    Irp, srb, srb->SrbStatus));

        //
        // Release the queue if it is frozen.
        //

        if (srb->SrbStatus & SRB_STATUS_QUEUE_FROZEN) {
            ClassReleaseQueue(DeviceObject);
        }

        retry = ClassInterpretSenseInfo(
            DeviceObject,
            srb,
            irpStack->MajorFunction,
            irpStack->MajorFunction == IRP_MJ_DEVICE_CONTROL ? irpStack->Parameters.DeviceIoControl.IoControlCode : 0,
            MAXIMUM_RETRIES - irpStack->MinorFunction, // HACKHACK - REF #0001
            &status,
            &retryInterval);

        //
        // If the status is verified required and the this request
        // should bypass verify required then retry the request.
        //

        if (irpStack->Flags & SL_OVERRIDE_VERIFY_VOLUME &&
            status == STATUS_VERIFY_REQUIRED) {

            status = STATUS_IO_DEVICE_ERROR;
            retry = TRUE;
        }

        if (retry) {

            if (irpStack->MinorFunction != 0) { // HACKHACK - REF #0001

                irpStack->MinorFunction--;      // HACKHACK - REF #0001

                //
                // Retry request.
                //

                TraceLog((CdromDebugWarning,
                            "CdRomXACompletion: Retry request %p (%x) - "
                            "Calling StartIo\n", Irp, irpStack->MinorFunction));


                ExFreePool(srb->SenseInfoBuffer);
                ExFreePool(srb);

                //
                // Call StartIo directly since IoStartNextPacket hasn't been called,
                // the serialisation is still intact.
                //

                CdRomRetryRequest(deviceExtension,
                                  Irp,
                                  retryInterval,
                                  FALSE);

                return STATUS_MORE_PROCESSING_REQUIRED;

            }

            //
            // Exhausted retries, fall through and complete the request
            // with the appropriate status
            //

            TraceLog((CdromDebugWarning,
                        "CdRomXACompletion: Retries exhausted for irp %p\n",
                        Irp));

        }

    } else {

        //
        // Set status for successful request.
        //

        status = STATUS_SUCCESS;

    } // end if (SRB_STATUS(srb->SrbStatus) ...

    //
    // Return SRB to nonpaged pool.
    //

    ExFreePool(srb->SenseInfoBuffer);
    ExFreePool(srb);

    //
    // Set status in completing IRP.
    //

    Irp->IoStatus.Status = status;    

    //
    // Set the hard error if necessary.
    //

    if (!NT_SUCCESS(status) &&
        IoIsErrorUserInduced(status) &&
        Irp->Tail.Overlay.Thread != NULL ) {

        //
        // Store DeviceObject for filesystem, and clear
        // in IoStatus.Information field.
        //

        IoSetHardErrorOrVerifyDevice(Irp, DeviceObject);
        Irp->IoStatus.Information = 0;
    }

    //
    // If pending has be returned for this irp then mark the current stack as
    // pending.
    //

    if (Irp->PendingReturned) {
      IoMarkIrpPending(Irp);
    }
    
    {
        KIRQL oldIrql = KeRaiseIrqlToDpcLevel();
        IoStartNextPacket(DeviceObject, FALSE);
        KeLowerIrql(oldIrql);
    }
    ClassReleaseRemoveLock(DeviceObject, Irp);
    
    return status;
}

VOID
NTAPI
CdRomDeviceControlDvdReadStructure(
    IN PDEVICE_OBJECT Fdo,
    IN PIRP OriginalIrp,
    IN PIRP NewIrp,
    IN PSCSI_REQUEST_BLOCK Srb
    )
{
    PIO_STACK_LOCATION currentIrpStack = IoGetCurrentIrpStackLocation(OriginalIrp);
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
    PCDB cdb = (PCDB)Srb->Cdb;
    PVOID dataBuffer;

    PDVD_READ_STRUCTURE request;
    USHORT dataLength;
    ULONG blockNumber;
    PFOUR_BYTE fourByte;

    dataLength =
        (USHORT)currentIrpStack->Parameters.DeviceIoControl.OutputBufferLength;

    request = OriginalIrp->AssociatedIrp.SystemBuffer;
    blockNumber =
        (ULONG)(request->BlockByteOffset.QuadPart >> fdoExtension->SectorShift);
    fourByte = (PFOUR_BYTE) &blockNumber;

    Srb->CdbLength = 12;
    Srb->TimeOutValue = fdoExtension->TimeOutValue;
    Srb->SrbFlags = fdoExtension->SrbFlags;
    SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DATA_IN);

    cdb->READ_DVD_STRUCTURE.OperationCode = SCSIOP_READ_DVD_STRUCTURE;
    cdb->READ_DVD_STRUCTURE.RMDBlockNumber[0] = fourByte->Byte3;
    cdb->READ_DVD_STRUCTURE.RMDBlockNumber[1] = fourByte->Byte2;
    cdb->READ_DVD_STRUCTURE.RMDBlockNumber[2] = fourByte->Byte1;
    cdb->READ_DVD_STRUCTURE.RMDBlockNumber[3] = fourByte->Byte0;
    cdb->READ_DVD_STRUCTURE.LayerNumber   = request->LayerNumber;
    cdb->READ_DVD_STRUCTURE.Format        = (UCHAR)request->Format;

#if DBG
    {
        if ((UCHAR)request->Format > DvdMaxDescriptor) {
            TraceLog((CdromDebugWarning,
                        "READ_DVD_STRUCTURE format %x = %s (%x bytes)\n",
                        (UCHAR)request->Format,
                        READ_DVD_STRUCTURE_FORMAT_STRINGS[DvdMaxDescriptor],
                        dataLength
                        ));
        } else {
            TraceLog((CdromDebugWarning,
                        "READ_DVD_STRUCTURE format %x = %s (%x bytes)\n",
                        (UCHAR)request->Format,
                        READ_DVD_STRUCTURE_FORMAT_STRINGS[(UCHAR)request->Format],
                        dataLength
                        ));
        }
    }
#endif // DBG

    if (request->Format == DvdDiskKeyDescriptor) {

        cdb->READ_DVD_STRUCTURE.AGID = (UCHAR) request->SessionId;

    }

    cdb->READ_DVD_STRUCTURE.AllocationLength[0] = (UCHAR)(dataLength >> 8);
    cdb->READ_DVD_STRUCTURE.AllocationLength[1] = (UCHAR)(dataLength & 0xff);
    Srb->DataTransferLength = dataLength;



    dataBuffer = ExAllocatePoolWithTag(NonPagedPoolCacheAligned,
                                       dataLength,
                                       DVD_TAG_READ_STRUCTURE);

    if (!dataBuffer) {
        ExFreePool(Srb->SenseInfoBuffer);
        ExFreePool(Srb);
        IoFreeIrp(NewIrp);
        OriginalIrp->IoStatus.Information = 0;
        OriginalIrp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;

        BAIL_OUT(OriginalIrp);
        CdRomCompleteIrpAndStartNextPacketSafely(Fdo, OriginalIrp);
        return;
    }
    RtlZeroMemory(dataBuffer, dataLength);

    NewIrp->MdlAddress = IoAllocateMdl(dataBuffer,
                                       currentIrpStack->Parameters.Read.Length,
                                       FALSE,
                                       FALSE,
                                       (PIRP) NULL);

    if (NewIrp->MdlAddress == NULL) {
        ExFreePool(dataBuffer);
        ExFreePool(Srb->SenseInfoBuffer);
        ExFreePool(Srb);
        IoFreeIrp(NewIrp);
        OriginalIrp->IoStatus.Information = 0;
        OriginalIrp->IoStatus.Status = STATUS_INSUFFICIENT_RESOURCES;

        BAIL_OUT(OriginalIrp);
        CdRomCompleteIrpAndStartNextPacketSafely(Fdo, OriginalIrp);
        return;
    }

    //
    // Prepare the MDL
    //

    MmBuildMdlForNonPagedPool(NewIrp->MdlAddress);

    Srb->DataBuffer = dataBuffer;

    IoCallDriver(fdoExtension->CommonExtension.LowerDeviceObject, NewIrp);

    return;
}

VOID
NTAPI
CdRomDeviceControlDvdEndSession(
    IN PDEVICE_OBJECT Fdo,
    IN PIRP OriginalIrp,
    IN PIRP NewIrp,
    IN PSCSI_REQUEST_BLOCK Srb
    )
{
    //PIO_STACK_LOCATION currentIrpStack = IoGetCurrentIrpStackLocation(OriginalIrp);
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
    PCDB cdb = (PCDB)Srb->Cdb;

    PDVD_SESSION_ID sessionId = OriginalIrp->AssociatedIrp.SystemBuffer;

    Srb->CdbLength = 12;
    Srb->TimeOutValue = fdoExtension->TimeOutValue;
    Srb->SrbFlags = fdoExtension->SrbFlags;
    SET_FLAG(Srb->SrbFlags, SRB_FLAGS_NO_DATA_TRANSFER);

    cdb->SEND_KEY.OperationCode = SCSIOP_SEND_KEY;
    cdb->SEND_KEY.AGID = (UCHAR) (*sessionId);
    cdb->SEND_KEY.KeyFormat = DVD_INVALIDATE_AGID;

    IoCallDriver(fdoExtension->CommonExtension.LowerDeviceObject, NewIrp);
    return;

}

VOID
NTAPI
CdRomDeviceControlDvdStartSessionReadKey(
    IN PDEVICE_OBJECT Fdo,
    IN PIRP OriginalIrp,
    IN PIRP NewIrp,
    IN PSCSI_REQUEST_BLOCK Srb
    )
{
    PIO_STACK_LOCATION currentIrpStack = IoGetCurrentIrpStackLocation(OriginalIrp);
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
    PCDB cdb = (PCDB)Srb->Cdb;
    NTSTATUS status;

    PDVD_COPY_PROTECT_KEY keyParameters;
    PCDVD_KEY_HEADER keyBuffer = NULL;

    ULONG keyLength;

    ULONG allocationLength;
    PFOUR_BYTE fourByte;

    //
    // Both of these use REPORT_KEY commands.
    // Determine the size of the input buffer
    //

    if(currentIrpStack->Parameters.DeviceIoControl.IoControlCode ==
       IOCTL_DVD_READ_KEY) {

        keyParameters = OriginalIrp->AssociatedIrp.SystemBuffer;

        keyLength = sizeof(CDVD_KEY_HEADER) +
                    (currentIrpStack->Parameters.DeviceIoControl.OutputBufferLength -
                     sizeof(DVD_COPY_PROTECT_KEY));
    } else {

        keyParameters = NULL;
        keyLength = sizeof(CDVD_KEY_HEADER) +
                    sizeof(CDVD_REPORT_AGID_DATA);
    }

    TRY {

        keyBuffer = ExAllocatePoolWithTag(NonPagedPoolCacheAligned,
                                          keyLength,
                                          DVD_TAG_READ_KEY);

        if(keyBuffer == NULL) {

            TraceLog((CdromDebugWarning,
                        "IOCTL_DVD_READ_KEY - couldn't allocate "
                        "%d byte buffer for key\n",
                        keyLength));
            status = STATUS_INSUFFICIENT_RESOURCES;<--- status is assigned
            LEAVE;
        }


        NewIrp->MdlAddress = IoAllocateMdl(keyBuffer,
                                           keyLength,
                                           FALSE,
                                           FALSE,
                                           (PIRP) NULL);

        if(NewIrp->MdlAddress == NULL) {

            TraceLog((CdromDebugWarning,
                        "IOCTL_DVD_READ_KEY - couldn't create mdl\n"));
            status = STATUS_INSUFFICIENT_RESOURCES;<--- status is assigned
            LEAVE;
        }

        MmBuildMdlForNonPagedPool(NewIrp->MdlAddress);

        Srb->DataBuffer = keyBuffer;
        Srb->CdbLength = 12;

        cdb->REPORT_KEY.OperationCode = SCSIOP_REPORT_KEY;

        allocationLength = keyLength;
        fourByte = (PFOUR_BYTE) &allocationLength;
        cdb->REPORT_KEY.AllocationLength[0] = fourByte->Byte1;
        cdb->REPORT_KEY.AllocationLength[1] = fourByte->Byte0;

        Srb->DataTransferLength = keyLength;

        //
        // set the specific parameters....
        //

        if(currentIrpStack->Parameters.DeviceIoControl.IoControlCode ==
           IOCTL_DVD_READ_KEY) {

            if(keyParameters->KeyType == DvdTitleKey) {

                ULONG logicalBlockAddress;

                logicalBlockAddress = (ULONG)
                    (keyParameters->Parameters.TitleOffset.QuadPart >>
                     fdoExtension->SectorShift);

                fourByte = (PFOUR_BYTE) &(logicalBlockAddress);

                cdb->REPORT_KEY.LogicalBlockAddress[0] = fourByte->Byte3;
                cdb->REPORT_KEY.LogicalBlockAddress[1] = fourByte->Byte2;
                cdb->REPORT_KEY.LogicalBlockAddress[2] = fourByte->Byte1;
                cdb->REPORT_KEY.LogicalBlockAddress[3] = fourByte->Byte0;
            }

            cdb->REPORT_KEY.KeyFormat = (UCHAR)keyParameters->KeyType;
            cdb->REPORT_KEY.AGID = (UCHAR) keyParameters->SessionId;
            TraceLog((CdromDebugWarning,
                        "CdRomDvdReadKey => sending irp %p for irp %p (%s)\n",
                        NewIrp, OriginalIrp, "READ_KEY"));

        } else {

            cdb->REPORT_KEY.KeyFormat = DVD_REPORT_AGID;
            cdb->REPORT_KEY.AGID = 0;
            TraceLog((CdromDebugWarning,
                        "CdRomDvdReadKey => sending irp %p for irp %p (%s)\n",
                        NewIrp, OriginalIrp, "START_SESSION"));
        }

        Srb->TimeOutValue = fdoExtension->TimeOutValue;
        Srb->SrbFlags = fdoExtension->SrbFlags;
        SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DATA_IN);

        IoCallDriver(fdoExtension->CommonExtension.LowerDeviceObject, NewIrp);

        status = STATUS_SUCCESS;<--- status is overwritten<--- status is overwritten

    } FINALLY {

        if (!NT_SUCCESS(status)) {

            //
            // An error occured during setup - free resources and
            // complete this request.
            //
            if (NewIrp->MdlAddress != NULL) {
                IoFreeMdl(NewIrp->MdlAddress);
            }

            if (keyBuffer != NULL) {
                ExFreePool(keyBuffer);
            }
            ExFreePool(Srb->SenseInfoBuffer);
            ExFreePool(Srb);
            IoFreeIrp(NewIrp);

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

            BAIL_OUT(OriginalIrp);
            CdRomCompleteIrpAndStartNextPacketSafely(Fdo, OriginalIrp);

        } // end !NT_SUCCESS
    }
    return;
}

VOID
NTAPI
CdRomDeviceControlDvdSendKey(
    IN PDEVICE_OBJECT Fdo,
    IN PIRP OriginalIrp,
    IN PIRP NewIrp,
    IN PSCSI_REQUEST_BLOCK Srb
    )
{
    //PIO_STACK_LOCATION currentIrpStack = IoGetCurrentIrpStackLocation(OriginalIrp);
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
    PCDB cdb = (PCDB)Srb->Cdb;

    PDVD_COPY_PROTECT_KEY key;
    PCDVD_KEY_HEADER keyBuffer = NULL;

    NTSTATUS status;
    ULONG keyLength;
    PFOUR_BYTE fourByte;

    key = OriginalIrp->AssociatedIrp.SystemBuffer;
    keyLength = (key->KeyLength - sizeof(DVD_COPY_PROTECT_KEY)) +
                sizeof(CDVD_KEY_HEADER);

    TRY {

        keyBuffer = ExAllocatePoolWithTag(NonPagedPoolCacheAligned,
                                          keyLength,
                                          DVD_TAG_SEND_KEY);

        if(keyBuffer == NULL) {

            TraceLog((CdromDebugWarning,
                        "IOCTL_DVD_SEND_KEY - couldn't allocate "
                        "%d byte buffer for key\n",
                        keyLength));
            status = STATUS_INSUFFICIENT_RESOURCES;<--- status is assigned
            LEAVE;
        }

        RtlZeroMemory(keyBuffer, keyLength);

        //
        // keylength is decremented here by two because the
        // datalength does not include the header, which is two
        // bytes.  keylength is immediately incremented later
        // by the same amount.
        //

        keyLength -= 2;
        fourByte = (PFOUR_BYTE) &keyLength;
        keyBuffer->DataLength[0] = fourByte->Byte1;
        keyBuffer->DataLength[1] = fourByte->Byte0;
        keyLength += 2;

        //
        // copy the user's buffer to our own allocated buffer
        //

        RtlMoveMemory(keyBuffer->Data,
                      key->KeyData,
                      key->KeyLength - sizeof(DVD_COPY_PROTECT_KEY));


        NewIrp->MdlAddress = IoAllocateMdl(keyBuffer,
                                           keyLength,
                                           FALSE,
                                           FALSE,
                                           (PIRP) NULL);

        if(NewIrp->MdlAddress == NULL) {
            TraceLog((CdromDebugWarning,
                        "IOCTL_DVD_SEND_KEY - couldn't create mdl\n"));
            status = STATUS_INSUFFICIENT_RESOURCES;<--- status is assigned
            LEAVE;
        }


        MmBuildMdlForNonPagedPool(NewIrp->MdlAddress);

        Srb->CdbLength = 12;
        Srb->DataBuffer = keyBuffer;
        Srb->DataTransferLength = keyLength;

        Srb->TimeOutValue = fdoExtension->TimeOutValue;
        Srb->SrbFlags = fdoExtension->SrbFlags;
        SET_FLAG(Srb->SrbFlags, SRB_FLAGS_DATA_OUT);

        cdb->REPORT_KEY.OperationCode = SCSIOP_SEND_KEY;

        fourByte = (PFOUR_BYTE) &keyLength;

        cdb->SEND_KEY.ParameterListLength[0] = fourByte->Byte1;
        cdb->SEND_KEY.ParameterListLength[1] = fourByte->Byte0;
        cdb->SEND_KEY.KeyFormat = (UCHAR)key->KeyType;
        cdb->SEND_KEY.AGID = (UCHAR) key->SessionId;

        if (key->KeyType == DvdSetRpcKey) {
            TraceLog((CdromDebugWarning,
                        "IOCTL_DVD_SEND_KEY - Setting RPC2 drive region\n"));
        } else {
            TraceLog((CdromDebugWarning,
                        "IOCTL_DVD_SEND_KEY - key type %x\n", key->KeyType));
        }

        IoCallDriver(fdoExtension->CommonExtension.LowerDeviceObject, NewIrp);

        status = STATUS_SUCCESS;<--- status is overwritten<--- status is overwritten

    } FINALLY {

        if (!NT_SUCCESS(status)) {

            //
            // An error occured during setup - free resources and
            // complete this request.
            //

            if (NewIrp->MdlAddress != NULL) {
                IoFreeMdl(NewIrp->MdlAddress);
            }

            if (keyBuffer != NULL) {
                ExFreePool(keyBuffer);
            }

            ExFreePool(Srb->SenseInfoBuffer);
            ExFreePool(Srb);
            IoFreeIrp(NewIrp);

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

            BAIL_OUT(OriginalIrp);
            CdRomCompleteIrpAndStartNextPacketSafely(Fdo, OriginalIrp);

        }
    }

    return;
}

VOID
NTAPI
CdRomInterpretReadCapacity(
    IN PDEVICE_OBJECT Fdo,
    IN PREAD_CAPACITY_DATA ReadCapacityBuffer
    )
{
    PFUNCTIONAL_DEVICE_EXTENSION fdoExtension = Fdo->DeviceExtension;
    PCOMMON_DEVICE_EXTENSION commonExtension = Fdo->DeviceExtension;
    ULONG               lastSector;
    ULONG               bps;
    ULONG               lastBit;
    ULONG               tmp;

    ASSERT(ReadCapacityBuffer);
    ASSERT(commonExtension->IsFdo);
    
    TraceLog((CdromDebugError,
                "CdRomInterpretReadCapacity: Entering\n"));

    //
    // Swizzle bytes from Read Capacity and translate into
    // the necessary geometry information in the device extension.
    //

    tmp = ReadCapacityBuffer->BytesPerBlock;
    ((PFOUR_BYTE)&bps)->Byte0 = ((PFOUR_BYTE)&tmp)->Byte3;<--- Uninitialized variable: bps
    ((PFOUR_BYTE)&bps)->Byte1 = ((PFOUR_BYTE)&tmp)->Byte2;
    ((PFOUR_BYTE)&bps)->Byte2 = ((PFOUR_BYTE)&tmp)->Byte1;
    ((PFOUR_BYTE)&bps)->Byte3 = ((PFOUR_BYTE)&tmp)->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) {
        bps = 2048;
    } else {
        lastBit = (ULONG) -1;
        while (bps) {
            lastBit++;
            bps = bps >> 1;
        }
        bps = 1 << lastBit;
    }

    fdoExtension->DiskGeometry.BytesPerSector = bps;

    TraceLog((CdromDebugTrace, "CdRomInterpretReadCapacity: Calculated bps %#x\n",
                fdoExtension->DiskGeometry.BytesPerSector));

    //
    // Copy last sector in reverse byte order.
    //

    tmp = ReadCapacityBuffer->LogicalBlockAddress;
    ((PFOUR_BYTE)&lastSector)->Byte0 = ((PFOUR_BYTE)&tmp)->Byte3;<--- Uninitialized variable: lastSector
    ((PFOUR_BYTE)&lastSector)->Byte1 = ((PFOUR_BYTE)&tmp)->Byte2;
    ((PFOUR_BYTE)&lastSector)->Byte2 = ((PFOUR_BYTE)&tmp)->Byte1;
    ((PFOUR_BYTE)&lastSector)->Byte3 = ((PFOUR_BYTE)&tmp)->Byte0;

    //
    // Calculate sector to byte shift.
    //

    WHICH_BIT(bps, fdoExtension->SectorShift);

    TraceLog((CdromDebugTrace,"CdRomInterpretReadCapacity: Sector size is %d\n",
        fdoExtension->DiskGeometry.BytesPerSector));

    TraceLog((CdromDebugTrace,"CdRomInterpretReadCapacity: Number of Sectors is %d\n",
        lastSector + 1));

    //
    // Calculate media capacity in bytes.
    //

    commonExtension->PartitionLength.QuadPart = (LONGLONG)(lastSector + 1);

    //
    // we've defaulted to 32/64 forever.  don't want to change this now...
    //

    fdoExtension->DiskGeometry.TracksPerCylinder = 0x40;
    fdoExtension->DiskGeometry.SectorsPerTrack = 0x20;

    //
    // Calculate number of cylinders.
    //

    fdoExtension->DiskGeometry.Cylinders.QuadPart = (LONGLONG)((lastSector + 1) / (32 * 64));

    commonExtension->PartitionLength.QuadPart =
        (commonExtension->PartitionLength.QuadPart << fdoExtension->SectorShift);


    ASSERT(TEST_FLAG(Fdo->Characteristics, FILE_REMOVABLE_MEDIA));
    
    //
    // This device supports removable media.
    //

    fdoExtension->DiskGeometry.MediaType = RemovableMedia;

    return;
}