Training courses

Kernel and Embedded Linux

Bootlin training courses

Embedded Linux, kernel,
Yocto Project, Buildroot, real-time,
graphics, boot time, debugging...

Bootlin logo

Elixir Cross Referencer

   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
/*	$NetBSD: cd.c,v 1.342.4.3 2022/02/01 11:41:29 martin Exp $	*/

/*-
 * Copyright (c) 1998, 2001, 2003, 2004, 2005, 2008 The NetBSD Foundation,
 * Inc.  All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Charles M. Hannum.
 *
 * MMC framework implemented and contributed to the NetBSD Foundation by
 * Reinoud Zandijk.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Originally written by Julian Elischer (julian@tfs.com)
 * for TRW Financial Systems for use under the MACH(2.5) operating system.
 *
 * TRW Financial Systems, in accordance with their agreement with Carnegie
 * Mellon University, makes this software available to CMU to distribute
 * or use in any manner that they see fit as long as this message is kept with
 * the software. For this reason TFS also grants any other persons or
 * organisations permission to use or modify this software.
 *
 * TFS supplies this software to be publicly redistributed
 * on the understanding that TFS is not responsible for the correct
 * functioning of this software in any circumstances.
 *
 * Ported to run under 386BSD by Julian Elischer (julian@tfs.com) Sept 1992
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: cd.c,v 1.342.4.3 2022/02/01 11:41:29 martin Exp $");

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/buf.h>
#include <sys/bufq.h>
#include <sys/uio.h>
#include <sys/malloc.h>
#include <sys/errno.h>
#include <sys/device.h>
#include <sys/disklabel.h>
#include <sys/disk.h>
#include <sys/cdio.h>
#include <sys/dvdio.h>
#include <sys/scsiio.h>
#include <sys/proc.h>
#include <sys/conf.h>
#include <sys/vnode.h>
#include <sys/rndsource.h>

#include <dev/scsipi/scsi_spc.h>
#include <dev/scsipi/scsipi_all.h>
#include <dev/scsipi/scsipi_cd.h>
#include <dev/scsipi/scsipi_disk.h>	/* rw_big and start_stop come */
#include <dev/scsipi/scsi_all.h>
					/* from there */
#include <dev/scsipi/scsi_disk.h>	/* rw comes from there */
#include <dev/scsipi/scsipiconf.h>
#include <dev/scsipi/scsipi_base.h>
#include <dev/scsipi/cdvar.h>

#include <prop/proplib.h>

#define	CDUNIT(z)			DISKUNIT(z)
#define	CDPART(z)			DISKPART(z)
#define	CDMINOR(unit, part)		DISKMINOR(unit, part)
#define	MAKECDDEV(maj, unit, part)	MAKEDISKDEV(maj, unit, part)

#define MAXTRACK	99
#define CD_BLOCK_OFFSET	150
#define CD_FRAMES	75
#define CD_SECS		60

#define CD_TOC_FORM	0	/* formatted TOC, exposed to userland     */
#define CD_TOC_MSINFO	1	/* multi-session info			  */
#define CD_TOC_RAW	2	/* raw TOC as on disc, unprocessed	  */
#define CD_TOC_PMA	3	/* PMA, used as intermediate (rare use)   */
#define CD_TOC_ATIP	4	/* pressed space of recordable		  */
#define CD_TOC_CDTEXT	5	/* special CD-TEXT, rarely used		  */

#define P5LEN	0x32
#define MS5LEN	(P5LEN + 8 + 2)

struct cd_formatted_toc {
	struct ioc_toc_header header;
	struct cd_toc_entry entries[MAXTRACK+1]; /* One extra for the */
						 /* leadout */
};

struct cdbounce {
	struct buf *obp;	/* original buf */
	struct buf *lbp;	/* first buffer */
	struct buf *rbp;	/* second buffer */
	int lerr;		/* error returned for first buffer */
	int rerr;		/* error returned for second buffer */
	int head;		/* bytes skipped at the start */
	int lcount;		/* bytes copied to first buffer */
	int rcount;		/* bytes copied to second buffer */
};

static void	cdstart(struct scsipi_periph *);
static void	cdrestart(void *);
static void	cdminphys(struct buf *);
static void	cddone(struct scsipi_xfer *, int);
static int	cd_interpret_sense(struct scsipi_xfer *);
static int	cd_diskstart(device_t, struct buf *);
static void	cd_iosize(device_t, int *);
static int	cd_lastclose(device_t);
static int      cd_firstopen(device_t, dev_t, int, int);
static void	cd_label(device_t, struct disklabel *);
static u_long	cd_size(struct cd_softc *, int);
static int	cd_play(struct cd_softc *, int, int);
static int	cd_play_tracks(struct cd_softc *, struct cd_formatted_toc *,
		    int, int, int, int);
static int	cd_play_msf(struct cd_softc *, int, int, int, int, int, int);
static int	cd_pause(struct cd_softc *, int);
static int	cd_reset(struct cd_softc *);
static int	cd_read_subchannel(struct cd_softc *, int, int, int,
		    struct cd_sub_channel_info *, int, int);
static int	cd_read_toc(struct cd_softc *, int, int, int,
		    struct cd_formatted_toc *, int, int, int);
static int	cd_get_parms(struct cd_softc *, int);
static int	cd_load_toc(struct cd_softc *, int, struct cd_formatted_toc *, int);
static int	cdreadmsaddr(struct cd_softc *, struct cd_formatted_toc *,int *);
static int	cdcachesync(struct scsipi_periph *periph, int flags);

static int	dvd_auth(struct cd_softc *, dvd_authinfo *);
static int	dvd_read_physical(struct cd_softc *, dvd_struct *);
static int	dvd_read_copyright(struct cd_softc *, dvd_struct *);
static int	dvd_read_disckey(struct cd_softc *, dvd_struct *);
static int	dvd_read_bca(struct cd_softc *, dvd_struct *);
static int	dvd_read_manufact(struct cd_softc *, dvd_struct *);
static int	dvd_read_struct(struct cd_softc *, dvd_struct *);

static int	cd_mode_sense(struct cd_softc *, u_int8_t, void *, size_t, int,
		    int, int *);
static int	cd_mode_select(struct cd_softc *, u_int8_t, void *, size_t,
		    int, int);
static int	cd_setchan(struct cd_softc *, int, int, int, int, int);
static int	cd_getvol(struct cd_softc *, struct ioc_vol *, int);
static int	cd_setvol(struct cd_softc *, const struct ioc_vol *, int);
static int	cd_set_pa_immed(struct cd_softc *, int);
static int	cd_load_unload(struct cd_softc *, struct ioc_load_unload *);
static int	cd_setblksize(struct cd_softc *);

static int	cdmatch(device_t, cfdata_t, void *);
static void	cdattach(device_t, device_t, void *);
static int	cddetach(device_t, int);

static int	mmc_getdiscinfo(struct scsipi_periph *, struct mmc_discinfo *);
static int	mmc_gettrackinfo(struct scsipi_periph *, struct mmc_trackinfo *);
static int	mmc_do_op(struct scsipi_periph *, struct mmc_op *);
static int	mmc_setup_writeparams(struct scsipi_periph *, struct mmc_writeparams *);

static void	cd_set_geometry(struct cd_softc *);

CFATTACH_DECL3_NEW(cd, sizeof(struct cd_softc), cdmatch, cdattach, cddetach,
    NULL, NULL, NULL, DVF_DETACH_SHUTDOWN);

extern struct cfdriver cd_cd;

static const struct scsipi_inquiry_pattern cd_patterns[] = {
	{T_CDROM, T_REMOV,
	 "",         "",                 ""},
	{T_WORM, T_REMOV,
	 "",         "",                 ""},
#if 0
	{T_CDROM, T_REMOV, /* more luns */
	 "PIONEER ", "CD-ROM DRM-600  ", ""},
#endif
	{T_DIRECT, T_REMOV,
	 "NEC                 CD-ROM DRIVE:260", "", ""},
};

static dev_type_open(cdopen);
static dev_type_close(cdclose);
static dev_type_read(cdread);
static dev_type_write(cdwrite);
static dev_type_ioctl(cdioctl);
static dev_type_strategy(cdstrategy);
static dev_type_dump(cddump);
static dev_type_size(cdsize);

const struct bdevsw cd_bdevsw = {
	.d_open = cdopen,
	.d_close = cdclose,
	.d_strategy = cdstrategy,
	.d_ioctl = cdioctl,
	.d_dump = cddump,
	.d_psize = cdsize,
	.d_discard = nodiscard,
	.d_flag = D_DISK | D_MPSAFE
};

const struct cdevsw cd_cdevsw = {
	.d_open = cdopen,
	.d_close = cdclose,
	.d_read = cdread,
	.d_write = cdwrite,
	.d_ioctl = cdioctl,
	.d_stop = nostop,
	.d_tty = notty,
	.d_poll = nopoll,
	.d_mmap = nommap,
	.d_kqfilter = nokqfilter,
	.d_discard = nodiscard,
	.d_flag = D_DISK | D_MPSAFE
};

static struct dkdriver cddkdriver = {
	.d_open = cdopen,
	.d_close = cdclose,
	.d_strategy = cdstrategy,
	.d_minphys = cdminphys,
	.d_diskstart = cd_diskstart,
	.d_firstopen = cd_firstopen,
	.d_lastclose = cd_lastclose,
	.d_label = cd_label,
};

static const struct scsipi_periphsw cd_switch = {
	cd_interpret_sense,	/* use our error handler first */
	cdstart,		/* we have a queue, which is started by this */
	NULL,			/* we do not have an async handler */
	cddone,			/* deal with stats at interrupt time */
};

/*
 * The routine called by the low level scsi routine when it discovers
 * A device suitable for this driver
 */
static int
cdmatch(device_t parent, cfdata_t match, void *aux)
{
	struct scsipibus_attach_args *sa = aux;
	int priority;

	(void)scsipi_inqmatch(&sa->sa_inqbuf,
	    cd_patterns, sizeof(cd_patterns) / sizeof(cd_patterns[0]),
	    sizeof(cd_patterns[0]), &priority);

	return (priority);
}

static void
cdattach(device_t parent, device_t self, void *aux)
{
	struct cd_softc *cd = device_private(self);
	struct dk_softc *dksc = &cd->sc_dksc;
	struct scsipibus_attach_args *sa = aux;
	struct scsipi_periph *periph = sa->sa_periph;
	int dtype;

	SC_DEBUG(periph, SCSIPI_DB2, ("cdattach: "));

	switch (SCSIPI_BUSTYPE_TYPE(scsipi_periph_bustype(sa->sa_periph))) {
	case SCSIPI_BUSTYPE_SCSI:
		dtype = DKTYPE_SCSI;
		if (periph->periph_version == 0)
			cd->flags |= CDF_ANCIENT;
		break; 
	case SCSIPI_BUSTYPE_ATAPI:
		dtype = DKTYPE_ATAPI;
		break;
	default:
		dtype = DKTYPE_UNKNOWN;
		break; 
	}

	/*
	 * Initialize and attach the disk structure.
	 */
	dk_init(dksc, self, dtype);
	disk_init(&dksc->sc_dkdev, dksc->sc_xname, &cddkdriver);

	dk_attach(dksc);
	disk_attach(&dksc->sc_dkdev);

	bufq_alloc(&dksc->sc_bufq, "disksort", BUFQ_SORT_RAWBLOCK);

	callout_init(&cd->sc_callout, 0);

	/*
	 * Store information needed to contact our base driver
	 */
	cd->sc_periph = periph;

	periph->periph_dev = dksc->sc_dev;
	periph->periph_switch = &cd_switch;

	/*
	 * Increase our openings to the maximum-per-periph
	 * supported by the adapter.  This will either be
	 * clamped down or grown by the adapter if necessary.
	 */
	periph->periph_openings =
	    SCSIPI_CHAN_MAX_PERIPH(periph->periph_channel);
	periph->periph_flags |= PERIPH_GROW_OPENINGS;

	aprint_naive("\n");
	aprint_normal("\n");

	if (!pmf_device_register(self, NULL, NULL))
		aprint_error_dev(self, "couldn't establish power handler\n");
}

static int
cddetach(device_t self, int flags)
{
	struct cd_softc *cd = device_private(self);
	struct dk_softc *dksc = &cd->sc_dksc;
	struct scsipi_periph *periph = cd->sc_periph;
	struct scsipi_channel *chan = periph->periph_channel;
	int bmaj, cmaj, i, mn, rc;

	if ((rc = disk_begindetach(&dksc->sc_dkdev, cd_lastclose, self, flags)) != 0)
		return rc;

	/* locate the major number */
	bmaj = bdevsw_lookup_major(&cd_bdevsw);
	cmaj = cdevsw_lookup_major(&cd_cdevsw);

	/* Nuke the vnodes for any open instances */
	for (i = 0; i < MAXPARTITIONS; i++) {
		mn = CDMINOR(device_unit(self), i);
		vdevgone(bmaj, mn, mn, VBLK);
		vdevgone(cmaj, mn, mn, VCHR);
	}

	/* kill any pending restart */
	callout_halt(&cd->sc_callout, NULL);

	dk_drain(dksc);

	/* Kill off any pending commands. */
	mutex_enter(chan_mtx(chan));
	scsipi_kill_pending(cd->sc_periph);
	mutex_exit(chan_mtx(chan));

	bufq_free(dksc->sc_bufq);

	/* Detach from the disk list. */
	disk_detach(&dksc->sc_dkdev);
	disk_destroy(&dksc->sc_dkdev);

	dk_detach(dksc);

	callout_destroy(&cd->sc_callout);

	pmf_device_deregister(self);

	return (0);
}

/*
 * Serialized by caller
 */
static int
cd_firstopen(device_t self, dev_t dev, int flag, int fmt)
{
        struct cd_softc *cd = device_private(self);
        struct scsipi_periph *periph = cd->sc_periph;
        struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
        int error, silent;
        int part;

	part = CDPART(dev);

        error = scsipi_adapter_addref(adapt);
        if (error)
                return error;

        if ((part == RAW_PART && fmt == S_IFCHR) || (flag & FSILENT))
                silent = XS_CTL_SILENT;
        else
                silent = 0;

	/* make cdclose() silent */
	cd->flags |= CDF_EJECTED;

	/* Check that it is still responding and ok. */
	error = scsipi_test_unit_ready(periph,
	    XS_CTL_IGNORE_ILLEGAL_REQUEST | XS_CTL_IGNORE_MEDIA_CHANGE |
	    XS_CTL_SILENT);

	/*
	 * Start the pack spinning if necessary. Always allow the
	 * raw parition to be opened, for raw IOCTLs. Data transfers
	 * will check for SDEV_MEDIA_LOADED.
	 */
	if (error == EIO) {
		error = scsipi_start(periph, SSS_START, silent);
		if (error == EINVAL)
			error = EIO;
	}
	if (error) {
		if (part == RAW_PART)
			goto out;
		goto bad;
	}

	/* Lock the pack in. */
	error = scsipi_prevent(periph, SPAMR_PREVENT_DT,
	    XS_CTL_IGNORE_ILLEGAL_REQUEST |
	    XS_CTL_IGNORE_MEDIA_CHANGE);
	SC_DEBUG(periph, SCSIPI_DB1,
	    ("cdopen: scsipi_prevent, error=%d\n", error));
	if (error) {
		if (part == RAW_PART)
			goto out;
		goto bad;
	}

	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
		int param_error;

		/* Load the physical device parameters. */
		param_error = cd_get_parms(cd, 0);
		if (param_error == CDGP_RESULT_OFFLINE) {
			error = ENXIO;
			goto bad2;
		}
		periph->periph_flags |= PERIPH_MEDIA_LOADED;

		SC_DEBUG(periph, SCSIPI_DB3, ("Params loaded "));

		cd_set_geometry(cd);

		/* make cdclose() loud again */
		cd->flags &= ~CDF_EJECTED;
	}

	periph->periph_flags |= PERIPH_OPEN;

out:
	return 0;

bad2:
	scsipi_prevent(periph, SPAMR_ALLOW,
	    XS_CTL_IGNORE_ILLEGAL_REQUEST |
	    XS_CTL_IGNORE_MEDIA_CHANGE |
	    XS_CTL_SILENT);

bad:
	scsipi_adapter_delref(adapt);
	return error;
}

/*
 * open the device. Make sure the partition info is a up-to-date as can be.
 */
static int
cdopen(dev_t dev, int flag, int fmt, struct lwp *l)
{
	struct cd_softc *cd;
	struct dk_softc *dksc;
	struct scsipi_periph *periph;
	int unit, part;
	int error;

	unit = CDUNIT(dev);
	cd = device_lookup_private(&cd_cd, unit);
	if (cd == NULL)
		return (ENXIO);
	dksc = &cd->sc_dksc;

	periph = cd->sc_periph;
	part = CDPART(dev);

	SC_DEBUG(periph, SCSIPI_DB1,
	    ("cdopen: dev=0x%"PRIu64" (unit %"PRIu32" (of %d), partition %d)\n",
	    dev, unit, cd_cd.cd_ndevs, CDPART(dev)));

	/*
	 * If any partition is open, but the disk has been invalidated,
	 * disallow further opens of non-raw partition
	 */
	if ((periph->periph_flags & (PERIPH_OPEN | PERIPH_MEDIA_LOADED)) ==
	    PERIPH_OPEN) {
		if (part != RAW_PART || fmt != S_IFCHR)
			return EIO;
	}

	error = dk_open(dksc, dev, flag, fmt, l);

	SC_DEBUG(periph, SCSIPI_DB3, ("open complete\n"));

	return error;
}

/*      
 * Serialized by caller
 */     
static int
cd_lastclose(device_t self)
{ 
	struct cd_softc *cd = device_private(self);
	struct scsipi_periph *periph = cd->sc_periph;
	struct scsipi_adapter *adapt = periph->periph_channel->chan_adapter;
	int silent;

	if ((cd->flags & CDF_EJECTED) != 0 ||
	    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)
		silent = XS_CTL_SILENT;
	else
		silent = 0;

	cdcachesync(periph, silent);

	scsipi_wait_drain(periph);  

	scsipi_prevent(periph, SPAMR_ALLOW,
	    XS_CTL_IGNORE_ILLEGAL_REQUEST |
	    XS_CTL_IGNORE_NOT_READY |
	    XS_CTL_SILENT);
	periph->periph_flags &= ~PERIPH_OPEN;

	scsipi_wait_drain(periph);

	scsipi_adapter_delref(adapt); 

	return 0;
}

/*
 * close the device.. only called if we are the LAST
 * occurence of an open device
 */
static int
cdclose(dev_t dev, int flag, int fmt, struct lwp *l)
{
	struct cd_softc *cd;
	struct dk_softc *dksc;
	int unit;

	unit = CDUNIT(dev);
	cd = device_lookup_private(&cd_cd, unit);
	dksc = &cd->sc_dksc;

	return dk_close(dksc, dev, flag, fmt, l);
}

static void
cd_bounce_buffer_done(struct buf *bp)
{
	struct cdbounce *bounce = bp->b_private;
	struct buf *obp = bounce->obp;

	if (bp == bounce->lbp) {
		if ((bounce->lerr = bp->b_error) == 0)
			memcpy(obp->b_data, (char *)bp->b_data + bounce->head, bounce->lcount);
		bounce->lbp = NULL;
	}

	if (bp == bounce->rbp) {
		if ((bounce->rerr = bp->b_error) == 0)
			memcpy((char *)obp->b_data + bounce->lcount, bp->b_data, bounce->rcount);
		bounce->rbp = NULL;
	}

	free(bp->b_data, M_DEVBUF);
	putiobuf(bp);

	if (bounce->lbp != NULL || bounce->rbp != NULL)
		return;

	obp->b_error = bounce->rerr;
	if (bounce->lerr)
		obp->b_error = bounce->lerr;

	obp->b_resid = 0;
	if (obp->b_error)
		obp->b_resid = obp->b_bcount;

	free(bounce, M_DEVBUF);
	biodone(obp);
}

static int
cd_make_bounce_buffer(struct cd_softc *cd, struct buf *bp, daddr_t blkno, int count, struct buf **nbpp, void *priv)
{
	struct buf *nbp;

	/* We don't support bouncing writes */
	if ((bp->b_flags & B_READ) == 0)
		return EACCES; /* XXX */

	nbp = getiobuf(NULL, false);
	if (nbp == NULL)
		return ENOMEM;

	nbp->b_data = malloc(count, M_DEVBUF, M_NOWAIT);
	if (nbp->b_data == NULL) {
		putiobuf(nbp);
		return ENOMEM;
	}

	/* Set up the IOP to the bounce buffer */
	nbp->b_error = 0;
	nbp->b_dev = bp->b_dev;
	nbp->b_proc = bp->b_proc;
	nbp->b_bcount = count;
	nbp->b_bufsize = count;
	nbp->b_blkno = blkno;
	nbp->b_flags = bp->b_flags | B_READ;
	nbp->b_oflags = bp->b_oflags;
	nbp->b_cflags = bp->b_cflags;
	nbp->b_iodone = cd_bounce_buffer_done;
	nbp->b_private = priv;

	BIO_COPYPRIO(nbp, bp);

	*nbpp = nbp;
	return 0;
}

static int
cd_make_bounce(struct cd_softc *cd, struct buf *bp, struct cdbounce **bouncep)
{
	struct dk_softc *dksc = &cd->sc_dksc;
	unsigned secsize = dksc->sc_dkdev.dk_geom.dg_secsize;
	struct cdbounce *bounce;
	int bps, nblks, skip, total, count;
	daddr_t blkno;
	struct buf *lbp, *rbp;
	int error;

	bounce = malloc(sizeof(struct cdbounce), M_DEVBUF, M_NOWAIT|M_ZERO);
	if (bounce == NULL)
		return ENOMEM;

	bps = howmany(secsize, DEV_BSIZE);
	nblks = howmany(bp->b_bcount, DEV_BSIZE);

	skip = bp->b_blkno % bps;

	blkno = bp->b_blkno - skip;
	total = roundup(nblks + skip, bps) * DEV_BSIZE;

	count = total;
	cd_iosize(dksc->sc_dev, &count);

	bounce->head = skip * DEV_BSIZE;
	bounce->lcount = count - bounce->head;
	bounce->rcount = bp->b_bcount - bounce->lcount;

	error = cd_make_bounce_buffer(cd, bp, blkno, count, &lbp, bounce);
	if (error)
		goto bad;

	blkno += howmany(count, DEV_BSIZE);
	count = total - count;

	if (count > 0) {
		bounce->lbp->b_private = bounce;
		error = cd_make_bounce_buffer(cd, bp, blkno, count, &rbp, bounce);
		if (error) {
			putiobuf(bounce->lbp);
			goto bad;
		}
	} else
		rbp = NULL;

	bounce->obp = bp;
	bounce->lbp = lbp;
	bounce->rbp = rbp;

	*bouncep = bounce;

	return 0;

bad:
	free(bounce, M_DEVBUF);
	return error;
}

/*
 * Actually translate the requested transfer into one the physical driver can
 * understand.  The transfer is described by a buf and will include only one
 * physical transfer.
 */
static void
cdstrategy(struct buf *bp)
{
	struct cd_softc *cd = device_lookup_private(&cd_cd,CDUNIT(bp->b_dev));
	struct dk_softc *dksc = &cd->sc_dksc;
	struct scsipi_periph *periph = cd->sc_periph;
	int error;

	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cdstrategy "));
	SC_DEBUG(cd->sc_periph, SCSIPI_DB1,
	    ("%d bytes @ blk %" PRId64 "\n", bp->b_bcount, bp->b_blkno));

	/*
	 * If the device has been made invalid, error out
	 * maybe the media changed
	 */
	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0) {
		if (periph->periph_flags & PERIPH_OPEN)
			error = EIO;
		else
			error = ENODEV;
		goto bad;
	}

	/*
	 * If label and device don't agree in sector size use a bounce buffer
	 */
	if (dksc->sc_dkdev.dk_label->d_secsize != dksc->sc_dkdev.dk_geom.dg_secsize) {
		struct cdbounce *bounce = NULL;

		error = cd_make_bounce(cd, bp, &bounce);
		if (error)
			goto bad;

		dk_strategy(dksc, bounce->lbp);
		if (bounce->rbp != NULL)
			dk_strategy(dksc, bounce->rbp);

		return;
	}
	
	dk_strategy(dksc, bp);
	return;

bad:
	bp->b_error = error;
	bp->b_resid = bp->b_bcount;
	biodone(bp);
}

/*
 * Issue single I/O command
 *
 * Called from dk_start and implicitely from dk_strategy
 */
static int
cd_diskstart(device_t dev, struct buf *bp)
{
	struct cd_softc *cd = device_private(dev);
        struct scsipi_periph *periph = cd->sc_periph;
        struct scsipi_channel *chan = periph->periph_channel;
	struct scsipi_rw_10 cmd_big;
	struct scsi_rw_6 cmd_small;
	struct scsipi_generic *cmdp;
	struct scsipi_xfer *xs;
	int error, flags, nblks, cmdlen;

	SC_DEBUG(periph, SCSIPI_DB2, ("cdstart "));

	mutex_enter(chan_mtx(chan));

	if (periph->periph_active >= periph->periph_openings) {
		error = EAGAIN;
		goto out;
	}

	/*
	 * there is excess capacity, but a special waits
	 * It'll need the adapter as soon as we clear out of the
	 * way and let it run (user level wait).
	 */
	if (periph->periph_flags & PERIPH_WAITING) {
		periph->periph_flags &= ~PERIPH_WAITING;
		cv_broadcast(periph_cv_periph(periph));
		error = EAGAIN;
		goto out;
	}

	/*
	 * If the device has become invalid, abort all the
	 * reads and writes until all files have been closed and
	 * re-opened
	 */
	if (__predict_false(
	    (periph->periph_flags & PERIPH_MEDIA_LOADED) == 0)) {
		error = EIO;
		goto out;
	}

	nblks = howmany(bp->b_bcount, cd->params.blksize);

	/*
	 *  Fill out the scsi command.  If the transfer will
	 *  fit in a "small" cdb, use it.
	 */
	if (((bp->b_rawblkno & 0x1fffff) == bp->b_rawblkno) &&
	    ((nblks & 0xff) == nblks) &&
	    !(periph->periph_quirks & PQUIRK_ONLYBIG)) {
		/*
		 * We can fit in a small cdb.
		 */
		memset(&cmd_small, 0, sizeof(cmd_small));
		cmd_small.opcode = (bp->b_flags & B_READ) ?
		    SCSI_READ_6_COMMAND : SCSI_WRITE_6_COMMAND;
		_lto3b(bp->b_rawblkno, cmd_small.addr);
		cmd_small.length = nblks & 0xff;
		cmdlen = sizeof(cmd_small);
		cmdp = (struct scsipi_generic *)&cmd_small;
	} else {
		/*
		 * Need a large cdb.
		 */
		memset(&cmd_big, 0, sizeof(cmd_big));
		cmd_big.opcode = (bp->b_flags & B_READ) ?
		    READ_10 : WRITE_10;
		_lto4b(bp->b_rawblkno, cmd_big.addr);
		_lto2b(nblks, cmd_big.length);
		cmdlen = sizeof(cmd_big);
		cmdp = (struct scsipi_generic *)&cmd_big;
	}

	/*
	 * Figure out what flags to use.
	 */
	flags = XS_CTL_NOSLEEP|XS_CTL_ASYNC|XS_CTL_SIMPLE_TAG;
	if (bp->b_flags & B_READ)
		flags |= XS_CTL_DATA_IN;
	else
		flags |= XS_CTL_DATA_OUT;

	/*
	 * Call the routine that chats with the adapter.
	 * Note: we cannot sleep as we may be an interrupt
	 */
	xs = scsipi_make_xs_locked(periph, cmdp, cmdlen,
	    (u_char *)bp->b_data, bp->b_bcount,
	    CDRETRIES, 30000, bp, flags);
	if (__predict_false(xs == NULL)) {
		/*
		 * out of memory. Keep this buffer in the queue, and
		 * retry later.
		 */
		callout_reset(&cd->sc_callout, hz / 2, cdrestart, cd);
		error = EAGAIN;
		goto out;
	}

	error = scsipi_execute_xs(xs);
	/* with a scsipi_xfer preallocated, scsipi_command can't fail */
	KASSERT(error == 0);

out:
	mutex_exit(chan_mtx(chan));

	return error;
}

/*
 * Recover I/O request after memory shortage
 *
 * Called from callout
 */
static void
cdrestart(void *v)
{
	struct cd_softc *cd = v;
	struct dk_softc *dksc = &cd->sc_dksc;

	dk_start(dksc, NULL);
}

/*
 * Recover I/O request after memory shortage
 *
 * Called from scsipi midlayer when resources have been freed
 * with channel lock held
 */
static void
cdstart(struct scsipi_periph *periph)
{
	struct cd_softc *cd = device_private(periph->periph_dev);
	struct dk_softc *dksc = &cd->sc_dksc;
	struct scsipi_channel *chan = periph->periph_channel;

	/*
	 * release channel lock as dk_start may need to acquire
	 * other locks
	 *
	 * cdstart is called from scsipi_put_xs and all its callers
	 * release the lock afterwards. So releasing it here
	 * doesn't matter.
	 */
	mutex_exit(chan_mtx(chan));

	dk_start(dksc, NULL);

	mutex_enter(chan_mtx(chan));
}

static void
cddone(struct scsipi_xfer *xs, int error)
{
	struct cd_softc *cd = device_private(xs->xs_periph->periph_dev);
	struct dk_softc *dksc = &cd->sc_dksc;
	struct buf *bp = xs->bp;

	if (bp) {
		bp->b_error = error;
		bp->b_resid = xs->resid;
		if (error) {
			/* on a read/write error bp->b_resid is zero, so fix */
			bp->b_resid = bp->b_bcount;
		}

		dk_done(dksc, bp);
		/* dk_start is called from scsipi_complete */
	}
}

static int
cd_interpret_sense(struct scsipi_xfer *xs)
{
	struct scsipi_periph *periph = xs->xs_periph;
	struct scsi_sense_data *sense = &xs->sense.scsi_sense;
	int retval = EJUSTRETURN;

	/*
	 * If it isn't a extended or extended/deferred error, let
	 * the generic code handle it.
	 */
	if (SSD_RCODE(sense->response_code) != SSD_RCODE_CURRENT &&
	    SSD_RCODE(sense->response_code) != SSD_RCODE_DEFERRED)
		return (retval);

	/*
	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Logical Unit
	 * Is In The Process of Becoming Ready" (Sense code 0x04,0x01), then
	 * wait a bit for the drive to spin up
	 */

	if ((SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY) &&
	    (sense->asc == 0x04) && (sense->ascq == 0x01)) {
		/*
		 * Sleep for 5 seconds to wait for the drive to spin up
		 */

		SC_DEBUG(periph, SCSIPI_DB1, ("Waiting 5 sec for CD "
						"spinup\n"));
		if (!callout_pending(&periph->periph_callout))
			scsipi_periph_freeze(periph, 1);
		callout_reset(&periph->periph_callout,
		    5 * hz, scsipi_periph_timed_thaw, periph);
		retval = ERESTART;
	}

	/*
	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Logical Unit Not
	 * Ready, Operation In Progress" (Sense code 0x04, 0x07),
	 * then wait for the specified time
	 */
	 
	if ((SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY) &&
	    (sense->asc == 0x04) && (sense->ascq == 0x07)) {
		/*
		 * we could listen to the delay; but it looks like the skey
		 * data is not always returned.
		 */
		/* cd_delay = _2btol(sense->sks.sks_bytes); */

		/* wait for a half second and get going again */
		if (!callout_pending(&periph->periph_callout))
			scsipi_periph_freeze(periph, 1);
		callout_reset(&periph->periph_callout,
		    hz/2, scsipi_periph_timed_thaw, periph);
		retval = ERESTART;
	}

	/*
	 * If we got a "Unit not ready" (SKEY_NOT_READY) and "Long write in
	 * progress" (Sense code 0x04, 0x08), then wait for the specified
	 * time
	 */
	 
	if ((SSD_SENSE_KEY(sense->flags) == SKEY_NOT_READY) &&
	    (sense->asc == 0x04) && (sense->ascq == 0x08)) {
		/*
		 * long write in process; we could listen to the delay; but it
		 * looks like the skey data is not always returned.
		 */
		/* cd_delay = _2btol(sense->sks.sks_bytes); */

		/* wait for a half second and get going again */
		if (!callout_pending(&periph->periph_callout))
			scsipi_periph_freeze(periph, 1);
		callout_reset(&periph->periph_callout,
		    hz/2, scsipi_periph_timed_thaw, periph);
		retval = ERESTART;
	}

	return (retval);
}

static void
cdminphys(struct buf *bp)
{
	struct cd_softc *cd = device_lookup_private(&cd_cd, CDUNIT(bp->b_dev));
	struct dk_softc *dksc = &cd->sc_dksc;
	long xmax;

	/*
	 * If the device is ancient, we want to make sure that
	 * the transfer fits into a 6-byte cdb.
	 *
	 * XXX Note that the SCSI-I spec says that 256-block transfers
	 * are allowed in a 6-byte read/write, and are specified
	 * by settng the "length" to 0.  However, we're conservative
	 * here, allowing only 255-block transfers in case an
	 * ancient device gets confused by length == 0.  A length of 0
	 * in a 10-byte read/write actually means 0 blocks.
	 */
	if (cd->flags & CDF_ANCIENT) {
		xmax = dksc->sc_dkdev.dk_geom.dg_secsize * 0xff;

		if (bp->b_bcount > xmax)
			bp->b_bcount = xmax;
	}

	scsipi_adapter_minphys(cd->sc_periph->periph_channel, bp);
}

static void
cd_iosize(device_t dev, int *count)
{
	struct buf B;
	int bmaj;

	bmaj       = bdevsw_lookup_major(&cd_bdevsw);
	B.b_dev    = MAKECDDEV(bmaj,device_unit(dev),RAW_PART);
	B.b_bcount = *count;

	cdminphys(&B);

	*count = B.b_bcount;
}

static int
cdread(dev_t dev, struct uio *uio, int ioflag)
{
	return (physio(cdstrategy, NULL, dev, B_READ, cdminphys, uio));
}

static int
cdwrite(dev_t dev, struct uio *uio, int ioflag)
{
	return (physio(cdstrategy, NULL, dev, B_WRITE, cdminphys, uio));
}

#if 0	/* XXX Not used */
/*
 * conversion between minute-seconde-frame and logical block address
 * addresses format
 */
static void
lba2msf(u_long lba, u_char *m, u_char *s, u_char *f)
{
	u_long tmp;

	tmp = lba + CD_BLOCK_OFFSET;	/* offset of first logical frame */
	tmp &= 0xffffff;		/* negative lbas use only 24 bits */
	*m = tmp / (CD_SECS * CD_FRAMES);
	tmp %= (CD_SECS * CD_FRAMES);
	*s = tmp / CD_FRAMES;
	*f = tmp % CD_FRAMES;
}
#endif /* XXX Not used */

/*
 * Convert an hour:minute:second:frame address to a logical block adres. In
 * theory the number of secs/minute and number of frames/second could be
 * configured differently in the device  as could the block offset but in
 * practice these values are rock solid and most drives don't even allow
 * theses values to be changed.
 */
static uint32_t
hmsf2lba(uint8_t h, uint8_t m, uint8_t s, uint8_t f)
{
	return (((((uint32_t) h * 60 + m) * CD_SECS) + s) * CD_FRAMES + f)
		- CD_BLOCK_OFFSET;
}

static int
cdreadmsaddr(struct cd_softc *cd, struct cd_formatted_toc *toc, int *addr)
{
	struct scsipi_periph *periph = cd->sc_periph;
	int error;
	struct cd_toc_entry *cte;

	error = cd_read_toc(cd, CD_TOC_FORM, 0, 0, toc,
	    sizeof(struct ioc_toc_header) + sizeof(struct cd_toc_entry),
	    0, 0x40 /* control word for "get MS info" */);

	if (error)
		return (error);

	cte = &toc->entries[0];
	if (periph->periph_quirks & PQUIRK_LITTLETOC) {
		cte->addr.lba = le32toh(cte->addr.lba);
		toc->header.len = le16toh(toc->header.len);
	} else {
		cte->addr.lba = be32toh(cte->addr.lba);
		toc->header.len = be16toh(toc->header.len);
	}

	*addr = (toc->header.len >= 10 && cte->track > 1) ?
		cte->addr.lba : 0;
	return 0;
}

/* synchronise caches code from cd.c, move to scsipi_ioctl.c ? */
static int
cdcachesync(struct scsipi_periph *periph, int flags) {
	struct scsi_synchronize_cache_10 cmd;

	/*
	 * Issue a SYNCHRONIZE CACHE. MMC devices have to issue with address 0
	 * and length 0 as it can't synchronise parts of the disc per spec.
	 * We ignore ILLEGAL REQUEST in the event that the command is not
	 * supported by the device, and poll for completion so that we know
	 * that the cache has actually been flushed.
	 *
	 * XXX should we handle the PQUIRK_NOSYNCCACHE ?
	 */

	memset(&cmd, 0, sizeof(cmd));
	cmd.opcode = SCSI_SYNCHRONIZE_CACHE_10;

	return (scsipi_command(periph, (void *)&cmd, sizeof(cmd), 0, 0,
	    CDRETRIES, 30000, NULL, flags | XS_CTL_IGNORE_ILLEGAL_REQUEST));
}

static int
do_cdioreadentries(struct cd_softc *cd, struct ioc_read_toc_entry *te,
    struct cd_formatted_toc *toc)
{
	/* READ TOC format 0 command, entries */
	struct ioc_toc_header *th;
	struct cd_toc_entry *cte;
	u_int len = te->data_len;
	int ntracks;
	int error;

	th = &toc->header;

	if (len > sizeof(toc->entries) ||
	    len < sizeof(toc->entries[0]))
		return (EINVAL);
	error = cd_read_toc(cd, CD_TOC_FORM, te->address_format,
	    te->starting_track, toc,
	    sizeof(toc->header) + len,
	    0, 0);
	if (error)
		return (error);
	if (te->address_format == CD_LBA_FORMAT)
		for (ntracks =
		    th->ending_track - th->starting_track + 1;
		    ntracks >= 0; ntracks--) {
			cte = &toc->entries[ntracks];
			cte->addr_type = CD_LBA_FORMAT;
			if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
				cte->addr.lba = le32toh(cte->addr.lba);
			else
				cte->addr.lba = be32toh(cte->addr.lba);
		}
	if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
		th->len = le16toh(th->len);
	else
		th->len = be16toh(th->len);
	return 0;
}

/*
 * Perform special action on behalf of the user.
 * Knows about the internals of this device
 */
static int
cdioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
{
	struct cd_softc *cd = device_lookup_private(&cd_cd, CDUNIT(dev));
	struct dk_softc *dksc = &cd->sc_dksc;
	struct scsipi_periph *periph = cd->sc_periph;
	struct cd_formatted_toc toc;
	int part = CDPART(dev);
	int error;

	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cdioctl 0x%lx ", cmd));

	/*
	 * If the device is not valid, some IOCTLs can still be
	 * handled on the raw partition. Check this here.
	 */
	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) == 0 &&
	    part != RAW_PART)
		return (EIO);

	switch (cmd) {
	case DIOCTUR: {
		/* test unit ready */
		error = scsipi_test_unit_ready(cd->sc_periph, XS_CTL_SILENT);
		*((int*)addr) = (error == 0);
		if (error == ENODEV || error == EIO || error == 0)
			return 0;                       
		return error;
	}
	case CDIOCPLAYTRACKS: {
		/* PLAY_MSF command */
		struct ioc_play_track *args = addr;

		if ((error = cd_set_pa_immed(cd, 0)) != 0)
			return (error);
		return (cd_play_tracks(cd, &toc, args->start_track,
		    args->start_index, args->end_track, args->end_index));
	}
	case CDIOCPLAYMSF: {
		/* PLAY_MSF command */
		struct ioc_play_msf *args = addr;

		if ((error = cd_set_pa_immed(cd, 0)) != 0)
			return (error);
		return (cd_play_msf(cd, args->start_m, args->start_s,
		    args->start_f, args->end_m, args->end_s, args->end_f));
	}
	case CDIOCPLAYBLOCKS: {
		/* PLAY command */
		struct ioc_play_blocks *args = addr;

		if ((error = cd_set_pa_immed(cd, 0)) != 0)
			return (error);
		return (cd_play(cd, args->blk, args->len));
	}
	case CDIOCREADSUBCHANNEL: {
		/* READ_SUBCHANNEL command */
		struct ioc_read_subchannel *args = addr;
		struct cd_sub_channel_info data;
		u_int len = args->data_len;

		if (len > sizeof(data) ||
		    len < sizeof(struct cd_sub_channel_header))
			return (EINVAL);
		error = cd_read_subchannel(cd, args->address_format,
		    args->data_format, args->track, &data, len, 0);
		if (error)
			return (error);
		len = uimin(len, _2btol(data.header.data_len) +
		    sizeof(struct cd_sub_channel_header));
		return (copyout(&data, args->data, len));
	}
	case CDIOCREADSUBCHANNEL_BUF: {
		/* As CDIOCREADSUBCHANNEL, but without a 2nd buffer area */
		struct ioc_read_subchannel_buf *args = addr;
		if (args->req.data_len != sizeof args->info)
			return EINVAL;
		return cd_read_subchannel(cd, args->req.address_format,
		    args->req.data_format, args->req.track, &args->info,
		    sizeof(args->info), 0);
	}
	case CDIOREADTOCHEADER: {
		/* READ TOC format 0 command, static header */
		if ((error = cd_read_toc(cd, CD_TOC_FORM, 0, 0,
		    &toc, sizeof(toc.header), 0, 0)) != 0)
			return (error);
		if (cd->sc_periph->periph_quirks & PQUIRK_LITTLETOC)
			toc.header.len = le16toh(toc.header.len);
		else
			toc.header.len = be16toh(toc.header.len);
		memcpy(addr, &toc.header, sizeof(toc.header));
		return (0);
	}
	case CDIOREADTOCENTRYS: {
		struct ioc_read_toc_entry *te = addr;
		error = do_cdioreadentries(cd, te, &toc);
		if (error != 0)
			return error;
		return copyout(toc.entries, te->data, uimin(te->data_len,
		    toc.header.len - (sizeof(toc.header.starting_track)
			+ sizeof(toc.header.ending_track))));
	}
	case CDIOREADTOCENTRIES_BUF: {
		struct ioc_read_toc_entry_buf *te = addr;
		error = do_cdioreadentries(cd, &te->req, &toc);
		if (error != 0)
			return error;
		memcpy(te->entry, toc.entries, uimin(te->req.data_len,
		    toc.header.len - (sizeof(toc.header.starting_track)
			+ sizeof(toc.header.ending_track))));
		return 0;
	}
	case CDIOREADMSADDR: {
		/* READ TOC format 0 command, length of first track only */
		int sessno = *(int*)addr;

		if (sessno != 0)
			return (EINVAL);

		return (cdreadmsaddr(cd, &toc, addr));
	}
	case CDIOCSETPATCH: {
		struct ioc_patch *arg = addr;

		return (cd_setchan(cd, arg->patch[0], arg->patch[1],
		    arg->patch[2], arg->patch[3], 0));
	}
	case CDIOCGETVOL: {
		/* MODE SENSE command (AUDIO page) */
		struct ioc_vol *arg = addr;

		return (cd_getvol(cd, arg, 0));
	}
	case CDIOCSETVOL: {
		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
		struct ioc_vol *arg = addr;

		return (cd_setvol(cd, arg, 0));
	}
	case CDIOCSETMONO:
		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
		return (cd_setchan(cd, BOTH_CHANNEL, BOTH_CHANNEL,
		    MUTE_CHANNEL, MUTE_CHANNEL, 0));

	case CDIOCSETSTEREO:
		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
		return (cd_setchan(cd, LEFT_CHANNEL, RIGHT_CHANNEL,
		    MUTE_CHANNEL, MUTE_CHANNEL, 0));

	case CDIOCSETMUTE:
		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
		return (cd_setchan(cd, MUTE_CHANNEL, MUTE_CHANNEL,
		    MUTE_CHANNEL, MUTE_CHANNEL, 0));

	case CDIOCSETLEFT:
		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
		return (cd_setchan(cd, LEFT_CHANNEL, LEFT_CHANNEL,
		    MUTE_CHANNEL, MUTE_CHANNEL, 0));

	case CDIOCSETRIGHT:
		/* MODE SENSE/MODE SELECT commands (AUDIO page) */
		return (cd_setchan(cd, RIGHT_CHANNEL, RIGHT_CHANNEL,
		    MUTE_CHANNEL, MUTE_CHANNEL, 0));

	case CDIOCRESUME:
		/* PAUSE command */
		return (cd_pause(cd, PA_RESUME));
	case CDIOCPAUSE:
		/* PAUSE command */
		return (cd_pause(cd, PA_PAUSE));
	case CDIOCSTART:
		return (scsipi_start(periph, SSS_START, 0));
	case CDIOCSTOP:
		return (scsipi_start(periph, SSS_STOP, 0));
	case CDIOCCLOSE:
		return (scsipi_start(periph, SSS_START|SSS_LOEJ,
		    XS_CTL_IGNORE_NOT_READY | XS_CTL_IGNORE_MEDIA_CHANGE));
	case DIOCEJECT:
		if (*(int *)addr == 0) {
			int pmask = __BIT(part);
			/*
			 * Don't force eject: check that we are the only
			 * partition open. If so, unlock it.
			 */
			if (DK_BUSY(dksc, pmask) == 0) {
				error = scsipi_prevent(periph, SPAMR_ALLOW,
				    XS_CTL_IGNORE_NOT_READY);
				if (error)
					return (error);
			} else {
				return (EBUSY);
			}
		}
		/* FALLTHROUGH */
	case CDIOCEJECT: /* FALLTHROUGH */
	case ODIOCEJECT:
		error = scsipi_start(periph, SSS_STOP|SSS_LOEJ, 0);
		if (error == 0)
			/* Make sure cdclose() will do silent operations */
			cd->flags |= CDF_EJECTED;
		return error;
	case DIOCCACHESYNC:
		/* SYNCHRONISE CACHES command */
		return (cdcachesync(periph, 0));
	case CDIOCALLOW:
		return (scsipi_prevent(periph, SPAMR_ALLOW, 0));
	case CDIOCPREVENT:
		return (scsipi_prevent(periph, SPAMR_PREVENT_DT, 0));
	case DIOCLOCK:
		return (scsipi_prevent(periph,
		    (*(int *)addr) ? SPAMR_PREVENT_DT : SPAMR_ALLOW, 0));
	case CDIOCSETDEBUG:
		cd->sc_periph->periph_dbflags |= (SCSIPI_DB1 | SCSIPI_DB2);
		return (0);
	case CDIOCCLRDEBUG:
		cd->sc_periph->periph_dbflags &= ~(SCSIPI_DB1 | SCSIPI_DB2);
		return (0);
	case CDIOCRESET:
	case SCIOCRESET:
		return (cd_reset(cd));
	case CDIOCLOADUNLOAD:
		/* LOAD_UNLOAD command */
		return (cd_load_unload(cd, addr));
	case DVD_AUTH:
		/* GPCMD_REPORT_KEY or GPCMD_SEND_KEY command */
		return (dvd_auth(cd, addr));
	case DVD_READ_STRUCT:
		/* GPCMD_READ_DVD_STRUCTURE command */
		return (dvd_read_struct(cd, addr));
	case MMCGETDISCINFO:
		/*
		 * GET_CONFIGURATION, READ_DISCINFO, READ_TRACKINFO,
		 * (READ_TOCf2, READ_CD_CAPACITY and GET_CONFIGURATION) commands
		 */
		return mmc_getdiscinfo(periph, (struct mmc_discinfo *) addr);
	case MMCGETTRACKINFO:
		/* READ TOCf2, READ_CD_CAPACITY and READ_TRACKINFO commands */
		return mmc_gettrackinfo(periph, (struct mmc_trackinfo *) addr);
	case MMCOP:
		/*
		 * CLOSE TRACK/SESSION, RESERVE_TRACK, REPAIR_TRACK,
		 * SYNCHRONISE_CACHE commands
		 */
		return mmc_do_op(periph, (struct mmc_op *) addr);
	case MMCSETUPWRITEPARAMS :
		/* MODE SENSE page 5, MODE_SELECT page 5 commands */
		return mmc_setup_writeparams(periph, (struct mmc_writeparams *) addr);
	default:
		error = dk_ioctl(dksc, dev, cmd, addr, flag, l); 
		if (error == ENOTTY)
			error = scsipi_do_ioctl(periph, dev, cmd, addr, flag, l);
		return (error);
	}

#ifdef DIAGNOSTIC
	panic("cdioctl: impossible");
#endif
}

static void
cd_label(device_t self, struct disklabel *lp)
{
	struct cd_softc *cd = device_private(self);
	struct scsipi_periph *periph = cd->sc_periph;
	struct cd_formatted_toc toc;
	int lastsession = 0;

	strncpy(lp->d_typename, "optical media", 16);
	lp->d_rpm = 300;
	lp->d_flags |= D_REMOVABLE;

	if ((periph->periph_flags & PERIPH_MEDIA_LOADED) != 0) {
		lp->d_flags |= D_SCSI_MMC;
		(void) cdreadmsaddr(cd, &toc, &lastsession);
	}

	lp->d_partitions[0].p_offset = 0;
	lp->d_partitions[0].p_size = lp->d_secperunit;
	lp->d_partitions[0].p_cdsession = lastsession;
	lp->d_partitions[0].p_fstype = FS_ISO9660;

	lp->d_partitions[RAW_PART].p_offset = 0;
	lp->d_partitions[RAW_PART].p_size = lp->d_secperunit;
	lp->d_partitions[RAW_PART].p_fstype = FS_UDF;
}

/*
 * Reading a disc's total capacity is apparently a very difficult issue for the
 * SCSI standardisation group. Every disc type seems to have its own
 * (re)invented size request method and modifiers. The failsafe way of
 * determining the total (max) capacity i.e. not the recorded capacity but the
 * total maximum capacity is to request the info on the last track and
 * calculate the last lba.
 *
 * For ROM drives, we go for the CD recorded capacity. For recordable devices
 * we count.
 */
static int
read_cd_capacity(struct scsipi_periph *periph, uint32_t *blksize, u_long *last_lba)
{
	struct scsipi_read_cd_capacity    cap_cmd;
	/*
	 * XXX: see PR 48550 and PR 48754:
	 * the ahcisata(4) driver can not deal with unaligned
	 * data, so align this "a bit"
	 */
	struct scsipi_read_cd_cap_data    cap __aligned(2);
	struct scsipi_read_discinfo       di_cmd;
	struct scsipi_read_discinfo_data  di __aligned(2);
	struct scsipi_read_trackinfo      ti_cmd;
	struct scsipi_read_trackinfo_data ti __aligned(2);
	uint32_t track_start, track_size;
	int error, flags, msb, lsb, last_track;

	/* if the device doesn't grok capacity, return the dummies */
	if (periph->periph_quirks & PQUIRK_NOCAPACITY)
		return 0;

	/* first try read CD capacity for blksize and last recorded lba */
	/* issue the cd capacity request */
	flags = XS_CTL_DATA_IN;
	memset(&cap_cmd, 0, sizeof(cap_cmd));
	memset(&cap, 0, sizeof(cap));
	cap_cmd.opcode = READ_CD_CAPACITY;

	error = scsipi_command(periph,
	    (void *) &cap_cmd, sizeof(cap_cmd),
	    (void *) &cap,     sizeof(cap),
	    CDRETRIES, 30000, NULL, flags);
	if (error)
		return error;

	/* retrieve values and sanity check them */
	*blksize  = _4btol(cap.length);
	*last_lba = _4btol(cap.addr);

	/* blksize is 2048 for CD, but some drives give gibberish */
	if ((*blksize < 512) || ((*blksize & 511) != 0)
	    || (*blksize > 16*1024)) {
		if (*blksize > 16*1024)
			aprint_error("read_cd_capacity: extra large block "
			    "size %u found - limiting to 2kByte\n",
			    *blksize);
		*blksize = 2048;	/* some drives lie ! */
	}

	/* recordables have READ_DISCINFO implemented */
	flags = XS_CTL_DATA_IN | XS_CTL_SILENT;
	memset(&di_cmd, 0, sizeof(di_cmd));
	di_cmd.opcode = READ_DISCINFO;
	_lto2b(READ_DISCINFO_BIGSIZE, di_cmd.data_len);

	error = scsipi_command(periph,
	    (void *) &di_cmd,  sizeof(di_cmd),
	    (void *) &di,      READ_DISCINFO_BIGSIZE,
	    CDRETRIES, 30000, NULL, flags);
	if (error == 0) {
		msb = di.last_track_last_session_msb;
		lsb = di.last_track_last_session_lsb;
		last_track = (msb << 8) | lsb;

		/* request info on last track */
		memset(&ti_cmd, 0, sizeof(ti_cmd));
		ti_cmd.opcode = READ_TRACKINFO;
		ti_cmd.addr_type = 1;			/* on tracknr */
		_lto4b(last_track, ti_cmd.address);	/* tracknr    */
		_lto2b(sizeof(ti), ti_cmd.data_len);

		error = scsipi_command(periph,
		    (void *) &ti_cmd,  sizeof(ti_cmd),
		    (void *) &ti,      sizeof(ti),
		    CDRETRIES, 30000, NULL, flags);
		if (error == 0) {
			track_start = _4btol(ti.track_start);
			track_size  = _4btol(ti.track_size);

			/* overwrite only with a sane value */
			if (track_start + track_size >= 100)
				*last_lba = (u_long) track_start + track_size -1;
		}
	}

	/* sanity check for lba_size */
	if (*last_lba < 100)
		*last_lba = 400000-1;

	return 0;
}

/*
 * Find out from the device what its capacity is
 */
static u_long
cd_size(struct cd_softc *cd, int flags)
{
	uint32_t blksize = 2048;
	u_long last_lba = 0, size;
	int error;

	error = read_cd_capacity(cd->sc_periph, &blksize, &last_lba);
	if (error)
		goto error;

	if (blksize != 2048) {
		if (cd_setblksize(cd) == 0) {
			blksize = 2048;
			error = read_cd_capacity(cd->sc_periph,
			    &blksize, &last_lba);
			if (error)
				goto error;
		}
	}

	size = last_lba + 1;
	cd->params.blksize     = blksize;
	cd->params.disksize    = size;
	cd->params.disksize512 = ((u_int64_t)cd->params.disksize * blksize) / DEV_BSIZE;

	SC_DEBUG(cd->sc_periph, SCSIPI_DB2,
	    ("cd_size: %u %lu\n", blksize, size));

	return size;

error:
	/* something went wrong */
	cd->params.blksize     = 2048;
	cd->params.disksize    = 0;
	cd->params.disksize512 = 0;

	SC_DEBUG(cd->sc_periph, SCSIPI_DB2, ("cd_size: failed\n"));

	return 0;
}

/*
 * Get scsi driver to send a "start playing" command
 */
static int
cd_play(struct cd_softc *cd, int blkno, int nblks)
{
	struct scsipi_play cmd;

	memset(&cmd, 0, sizeof(cmd));
	cmd.opcode = PLAY;
	_lto4b(blkno, cmd.blk_addr);
	_lto2b(nblks, cmd.xfer_len);

	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
	    CDRETRIES, 30000, NULL, 0));
}

/*
 * Get scsi driver to send a "start playing" command
 */
static int
cd_play_tracks(struct cd_softc *cd, struct cd_formatted_toc *toc, int strack,
    int sindex, int etrack, int eindex)
{
	int error;

	if (!etrack)
		return (EIO);
	if (strack > etrack)
		return (EINVAL);

	error = cd_load_toc(cd, CD_TOC_FORM, toc, 0);
	if (error)
		return (error);

	if (++etrack > (toc->header.ending_track+1))
		etrack = toc->header.ending_track+1;

	strack -= toc->header.starting_track;
	etrack -= toc->header.starting_track;
	if (strack < 0)
		return (EINVAL);

	return (cd_play_msf(cd, toc->entries[strack].addr.msf.minute,
	    toc->entries[strack].addr.msf.second,
	    toc->entries[strack].addr.msf.frame,
	    toc->entries[etrack].addr.msf.minute,
	    toc->entries[etrack].addr.msf.second,
	    toc->entries[etrack].addr.msf.frame));
}

/*
 * Get scsi driver to send a "play msf" command
 */
static int
cd_play_msf(struct cd_softc *cd, int startm, int starts, int startf, int endm,
    int ends, int endf)
{
	struct scsipi_play_msf cmd;

	memset(&cmd, 0, sizeof(cmd));
	cmd.opcode = PLAY_MSF;
	cmd.start_m = startm;
	cmd.start_s = starts;
	cmd.start_f = startf;
	cmd.end_m = endm;
	cmd.end_s = ends;
	cmd.end_f = endf;

	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
	    CDRETRIES, 30000, NULL, 0));
}

/*
 * Get scsi driver to send a "start up" command
 */
static int
cd_pause(struct cd_softc *cd, int go)
{
	struct scsipi_pause cmd;

	memset(&cmd, 0, sizeof(cmd));
	cmd.opcode = PAUSE;
	cmd.resume = go & 0xff;

	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
	    CDRETRIES, 30000, NULL, 0));
}

/*
 * Get scsi driver to send a "RESET" command
 */
static int
cd_reset(struct cd_softc *cd)
{

	return (scsipi_command(cd->sc_periph, 0, 0, 0, 0,
	    CDRETRIES, 30000, NULL, XS_CTL_RESET));
}

/*
 * Read subchannel
 */
static int
cd_read_subchannel(struct cd_softc *cd, int mode, int format, int track,
    struct cd_sub_channel_info *data, int len, int flags)
{
	struct scsipi_read_subchannel cmd;

	memset(&cmd, 0, sizeof(cmd));
	cmd.opcode = READ_SUBCHANNEL;
	if (mode == CD_MSF_FORMAT)
		cmd.byte2 |= CD_MSF;
	cmd.byte3 = SRS_SUBQ;
	cmd.subchan_format = format;
	cmd.track = track;
	_lto2b(len, cmd.data_len);

	return (scsipi_command(cd->sc_periph,
	    (void *)&cmd, sizeof(struct scsipi_read_subchannel),
	    (void *)data, len,
	    CDRETRIES, 30000, NULL, flags | XS_CTL_DATA_IN | XS_CTL_SILENT));
}

/*
 * Read table of contents
 */
static int
cd_read_toc(struct cd_softc *cd, int respf, int mode, int start,
    struct cd_formatted_toc *toc, int len, int flags, int control)
{
	struct scsipi_read_toc cmd;
	int ntoc;

	memset(&cmd, 0, sizeof(cmd));
#if 0
	if (len != sizeof(struct ioc_toc_header))
		ntoc = ((len) - sizeof(struct ioc_toc_header)) /
		    sizeof(struct cd_toc_entry);
	else
#endif
	ntoc = len;
	cmd.opcode = READ_TOC;
	if (mode == CD_MSF_FORMAT)
		cmd.addr_mode |= CD_MSF;
	cmd.resp_format = respf;
	cmd.from_track = start;
	_lto2b(ntoc, cmd.data_len);
	cmd.control = control;

	return (scsipi_command(cd->sc_periph,
	    (void *)&cmd, sizeof(cmd), (void *)toc, len, CDRETRIES,
	    30000, NULL, flags | XS_CTL_DATA_IN));
}

static int
cd_load_toc(struct cd_softc *cd, int respf, struct cd_formatted_toc *toc, int flags)
{
	int ntracks, len, error;

	if ((error = cd_read_toc(cd, respf, 0, 0, toc, sizeof(toc->header),
	    flags, 0)) != 0)
		return (error);

	ntracks = toc->header.ending_track - toc->header.starting_track + 1;
	len = (ntracks + 1) * sizeof(struct cd_toc_entry) +
	    sizeof(toc->header);
	if ((error = cd_read_toc(cd, respf, CD_MSF_FORMAT, 0, toc, len,
	    flags, 0)) != 0)
		return (error);
	return (0);
}

/*
 * Get the scsi driver to send a full inquiry to the device and use the
 * results to fill out the disk parameter structure.
 */
static int
cd_get_parms(struct cd_softc *cd, int flags)
{

	/*
	 * give a number of sectors so that sec * trks * cyls
	 * is <= disk_size
	 */
	if (cd_size(cd, flags) == 0)
		return (ENXIO);
	return (0);
}

static int
cdsize(dev_t dev)
{

	/* CD-ROMs are read-only. */
	return (-1);
}

static int
cddump(dev_t dev, daddr_t blkno, void *va, size_t size)
{

	/* Not implemented. */
	return (ENXIO);
}

#define	dvd_copy_key(dst, src)		memcpy((dst), (src), sizeof(dvd_key))
#define	dvd_copy_challenge(dst, src)	memcpy((dst), (src), sizeof(dvd_challenge))

static int
dvd_auth(struct cd_softc *cd, dvd_authinfo *a)
{
	struct scsipi_generic cmd;
	u_int8_t bf[20];
	int error;

	memset(cmd.bytes, 0, 15);
	memset(bf, 0, sizeof(bf));

	switch (a->type) {
	case DVD_LU_SEND_AGID:
		cmd.opcode = GPCMD_REPORT_KEY;
		cmd.bytes[8] = 8;
		cmd.bytes[9] = 0 | (0 << 6);
		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
		    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
		if (error)
			return (error);
		a->lsa.agid = bf[7] >> 6;
		return (0);

	case DVD_LU_SEND_CHALLENGE:
		cmd.opcode = GPCMD_REPORT_KEY;
		cmd.bytes[8] = 16;
		cmd.bytes[9] = 1 | (a->lsc.agid << 6);
		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
		    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
		if (error)
			return (error);
		dvd_copy_challenge(a->lsc.chal, &bf[4]);
		return (0);

	case DVD_LU_SEND_KEY1:
		cmd.opcode = GPCMD_REPORT_KEY;
		cmd.bytes[8] = 12;
		cmd.bytes[9] = 2 | (a->lsk.agid << 6);
		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
		    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
		if (error)
			return (error);
		dvd_copy_key(a->lsk.key, &bf[4]);
		return (0);

	case DVD_LU_SEND_TITLE_KEY:
		cmd.opcode = GPCMD_REPORT_KEY;
		_lto4b(a->lstk.lba, &cmd.bytes[1]);
		cmd.bytes[8] = 12;
		cmd.bytes[9] = 4 | (a->lstk.agid << 6);
		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
		    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
		if (error)
			return (error);
		a->lstk.cpm = (bf[4] >> 7) & 1;
		a->lstk.cp_sec = (bf[4] >> 6) & 1;
		a->lstk.cgms = (bf[4] >> 4) & 3;
		dvd_copy_key(a->lstk.title_key, &bf[5]);
		return (0);

	case DVD_LU_SEND_ASF:
		cmd.opcode = GPCMD_REPORT_KEY;
		cmd.bytes[8] = 8;
		cmd.bytes[9] = 5 | (a->lsasf.agid << 6);
		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
		    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
		if (error)
			return (error);
		a->lsasf.asf = bf[7] & 1;
		return (0);

	case DVD_HOST_SEND_CHALLENGE:
		cmd.opcode = GPCMD_SEND_KEY;
		cmd.bytes[8] = 16;
		cmd.bytes[9] = 1 | (a->hsc.agid << 6);
		bf[1] = 14;
		dvd_copy_challenge(&bf[4], a->hsc.chal);
		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
		    CDRETRIES, 30000, NULL, XS_CTL_DATA_OUT);
		if (error)
			return (error);
		a->type = DVD_LU_SEND_KEY1;
		return (0);

	case DVD_HOST_SEND_KEY2:
		cmd.opcode = GPCMD_SEND_KEY;
		cmd.bytes[8] = 12;
		cmd.bytes[9] = 3 | (a->hsk.agid << 6);
		bf[1] = 10;
		dvd_copy_key(&bf[4], a->hsk.key);
		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 12,
		    CDRETRIES, 30000, NULL, XS_CTL_DATA_OUT);
		if (error) {
			a->type = DVD_AUTH_FAILURE;
			return (error);
		}
		a->type = DVD_AUTH_ESTABLISHED;
		return (0);

	case DVD_INVALIDATE_AGID:
		cmd.opcode = GPCMD_REPORT_KEY;
		cmd.bytes[9] = 0x3f | (a->lsa.agid << 6);
		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 16,
		    CDRETRIES, 30000, NULL, 0);
		if (error)
			return (error);
		return (0);

	case DVD_LU_SEND_RPC_STATE:
		cmd.opcode = GPCMD_REPORT_KEY;
		cmd.bytes[8] = 8;
		cmd.bytes[9] = 8 | (0 << 6);
		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
		    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
		if (error)
			return (error);
		a->lrpcs.type = (bf[4] >> 6) & 3;
		a->lrpcs.vra = (bf[4] >> 3) & 7;
		a->lrpcs.ucca = (bf[4]) & 7;
		a->lrpcs.region_mask = bf[5];
		a->lrpcs.rpc_scheme = bf[6];
		return (0);

	case DVD_HOST_SEND_RPC_STATE:
		cmd.opcode = GPCMD_SEND_KEY;
		cmd.bytes[8] = 8;
		cmd.bytes[9] = 6 | (0 << 6);
		bf[1] = 6;
		bf[4] = a->hrpcs.pdrc;
		error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 8,
		    CDRETRIES, 30000, NULL, XS_CTL_DATA_OUT);
		if (error)
			return (error);
		return (0);

	default:
		return (ENOTTY);
	}
}

static int
dvd_read_physical(struct cd_softc *cd, dvd_struct *s)
{
	struct scsipi_generic cmd;
	u_int8_t bf[4 + 4 * 20], *bufp;
	int error;
	struct dvd_layer *layer;
	int i;

	memset(cmd.bytes, 0, 15);
	memset(bf, 0, sizeof(bf));
	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
	cmd.bytes[6] = s->type;
	_lto2b(sizeof(bf), &cmd.bytes[7]);

	cmd.bytes[5] = s->physical.layer_num;
	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
	if (error)
		return (error);
	for (i = 0, bufp = &bf[4], layer = &s->physical.layer[0]; i < 4;
	     i++, bufp += 20, layer++) {
		memset(layer, 0, sizeof(*layer));
                layer->book_version = bufp[0] & 0xf;
                layer->book_type = bufp[0] >> 4;
                layer->min_rate = bufp[1] & 0xf;
                layer->disc_size = bufp[1] >> 4;
                layer->layer_type = bufp[2] & 0xf;
                layer->track_path = (bufp[2] >> 4) & 1;
                layer->nlayers = (bufp[2] >> 5) & 3;
                layer->track_density = bufp[3] & 0xf;
                layer->linear_density = bufp[3] >> 4;
                layer->start_sector = _4btol(&bufp[4]);
                layer->end_sector = _4btol(&bufp[8]);
                layer->end_sector_l0 = _4btol(&bufp[12]);
                layer->bca = bufp[16] >> 7;
	}
	return (0);
}

static int
dvd_read_copyright(struct cd_softc *cd, dvd_struct *s)
{
	struct scsipi_generic cmd;
	u_int8_t bf[8];
	int error;

	memset(cmd.bytes, 0, 15);
	memset(bf, 0, sizeof(bf));
	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
	cmd.bytes[6] = s->type;
	_lto2b(sizeof(bf), &cmd.bytes[7]);

	cmd.bytes[5] = s->copyright.layer_num;
	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
	if (error)
		return (error);
	s->copyright.cpst = bf[4];
	s->copyright.rmi = bf[5];
	return (0);
}

static int
dvd_read_disckey(struct cd_softc *cd, dvd_struct *s)
{
	struct scsipi_generic cmd;
	u_int8_t *bf;
	int error;

	bf = malloc(4 + 2048, M_TEMP, M_WAITOK|M_ZERO);
	if (bf == NULL)
		return EIO;
	memset(cmd.bytes, 0, 15);
	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
	cmd.bytes[6] = s->type;
	_lto2b(4 + 2048, &cmd.bytes[7]);

	cmd.bytes[9] = s->disckey.agid << 6;
	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 4 + 2048,
	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
	if (error == 0)
		memcpy(s->disckey.value, &bf[4], 2048);
	free(bf, M_TEMP);
	return error;
}

static int
dvd_read_bca(struct cd_softc *cd, dvd_struct *s)
{
	struct scsipi_generic cmd;
	u_int8_t bf[4 + 188];
	int error;

	memset(cmd.bytes, 0, 15);
	memset(bf, 0, sizeof(bf));
	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
	cmd.bytes[6] = s->type;
	_lto2b(sizeof(bf), &cmd.bytes[7]);

	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, sizeof(bf),
	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
	if (error)
		return (error);
	s->bca.len = _2btol(&bf[0]);
	if (s->bca.len < 12 || s->bca.len > 188)
		return (EIO);
	memcpy(s->bca.value, &bf[4], s->bca.len);
	return (0);
}

static int
dvd_read_manufact(struct cd_softc *cd, dvd_struct *s)
{
	struct scsipi_generic cmd;
	u_int8_t *bf;
	int error;

	bf = malloc(4 + 2048, M_TEMP, M_WAITOK|M_ZERO);
	if (bf == NULL)
		return (EIO);
	memset(cmd.bytes, 0, 15);
	cmd.opcode = GPCMD_READ_DVD_STRUCTURE;
	cmd.bytes[6] = s->type;
	_lto2b(4 + 2048, &cmd.bytes[7]);

	error = scsipi_command(cd->sc_periph, &cmd, 12, bf, 4 + 2048,
	    CDRETRIES, 30000, NULL, XS_CTL_DATA_IN);
	if (error == 0) {
		s->manufact.len = _2btol(&bf[0]);
		if (s->manufact.len >= 0 && s->manufact.len <= 2048)
			memcpy(s->manufact.value, &bf[4], s->manufact.len);
		else
			error = EIO;
	}
	free(bf, M_TEMP);
	return error;
}

static int
dvd_read_struct(struct cd_softc *cd, dvd_struct *s)
{

	switch (s->type) {
	case DVD_STRUCT_PHYSICAL:
		return (dvd_read_physical(cd, s));
	case DVD_STRUCT_COPYRIGHT:
		return (dvd_read_copyright(cd, s));
	case DVD_STRUCT_DISCKEY:
		return (dvd_read_disckey(cd, s));
	case DVD_STRUCT_BCA:
		return (dvd_read_bca(cd, s));
	case DVD_STRUCT_MANUFACT:
		return (dvd_read_manufact(cd, s));
	default:
		return (EINVAL);
	}
}

static int
cd_mode_sense(struct cd_softc *cd, u_int8_t byte2, void *sense, size_t size,
    int page, int flags, int *big)
{

	if (cd->sc_periph->periph_quirks & PQUIRK_ONLYBIG) {
		*big = 1;
		return scsipi_mode_sense_big(cd->sc_periph, byte2, page, sense,
		    size + sizeof(struct scsi_mode_parameter_header_10),
		    flags, CDRETRIES, 20000);
	} else {
		*big = 0;
		return scsipi_mode_sense(cd->sc_periph, byte2, page, sense,
		    size + sizeof(struct scsi_mode_parameter_header_6),
		    flags, CDRETRIES, 20000);
	}
}

static int
cd_mode_select(struct cd_softc *cd, u_int8_t byte2, void *sense, size_t size,
    int flags, int big)
{

	if (big) {
		struct scsi_mode_parameter_header_10 *header = sense;

		_lto2b(0, header->data_length);
		return scsipi_mode_select_big(cd->sc_periph, byte2, sense,
		    size + sizeof(struct scsi_mode_parameter_header_10),
		    flags, CDRETRIES, 20000);
	} else {
		struct scsi_mode_parameter_header_6 *header = sense;

		header->data_length = 0;
		return scsipi_mode_select(cd->sc_periph, byte2, sense,
		    size + sizeof(struct scsi_mode_parameter_header_6),
		    flags, CDRETRIES, 20000);
	}
}

static int
cd_set_pa_immed(struct cd_softc *cd, int flags)
{
	struct {
		union {
			struct scsi_mode_parameter_header_6 small;
			struct scsi_mode_parameter_header_10 big;
		} header;
		struct cd_audio_page page;
	} data;
	int error;
	uint8_t oflags;
	int big, byte2;
	struct cd_audio_page *page;

	byte2 = SMS_DBD;
try_again:
	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
	    AUDIO_PAGE, flags, &big)) != 0) {
		if (byte2 == SMS_DBD) {
			/* Device may not understand DBD; retry without */
			byte2 = 0;
			goto try_again;
		}
		return (error);
	}

	if (big)
		page = (void *)((u_long)&data.header.big +
				sizeof data.header.big +
				_2btol(data.header.big.blk_desc_len));
	else
		page = (void *)((u_long)&data.header.small +
				sizeof data.header.small +
				data.header.small.blk_desc_len);

	oflags = page->flags;
	page->flags &= ~CD_PA_SOTC;
	page->flags |= CD_PA_IMMED;
	if (oflags == page->flags)
		return (0);

	return (cd_mode_select(cd, SMS_PF, &data,
	    sizeof(struct scsi_mode_page_header) + page->pg_length,
	    flags, big));
}

static int
cd_setchan(struct cd_softc *cd, int p0, int p1, int p2, int p3, int flags)
{
	struct {
		union {
			struct scsi_mode_parameter_header_6 small;
			struct scsi_mode_parameter_header_10 big;
		} header;
		struct cd_audio_page page;
	} data;
	int error;
	int big, byte2;
	struct cd_audio_page *page;

	byte2 = SMS_DBD;
try_again:
	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
	    AUDIO_PAGE, flags, &big)) != 0) {
		if (byte2 == SMS_DBD) {
			/* Device may not understand DBD; retry without */
			byte2 = 0;
			goto try_again;
		}
		return (error);
	}

	if (big)
		page = (void *)((u_long)&data.header.big +
				sizeof data.header.big +
				_2btol(data.header.big.blk_desc_len));
	else
		page = (void *)((u_long)&data.header.small +
				sizeof data.header.small +
				data.header.small.blk_desc_len);

	page->port[0].channels = p0;
	page->port[1].channels = p1;
	page->port[2].channels = p2;
	page->port[3].channels = p3;

	return (cd_mode_select(cd, SMS_PF, &data,
	    sizeof(struct scsi_mode_page_header) + page->pg_length,
	    flags, big));
}

static int
cd_getvol(struct cd_softc *cd, struct ioc_vol *arg, int flags)
{
	struct {
		union {
			struct scsi_mode_parameter_header_6 small;
			struct scsi_mode_parameter_header_10 big;
		} header;
		struct cd_audio_page page;
	} data;
	int error;
	int big, byte2;
	struct cd_audio_page *page;

	byte2 = SMS_DBD;
try_again:
	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
	    AUDIO_PAGE, flags, &big)) != 0) {
		if (byte2 == SMS_DBD) {
			/* Device may not understand DBD; retry without */
			byte2 = 0;
			goto try_again;
		}
		return (error);
	}

	if (big)
		page = (void *)((u_long)&data.header.big +
				sizeof data.header.big +
				_2btol(data.header.big.blk_desc_len));
	else
		page = (void *)((u_long)&data.header.small +
				sizeof data.header.small +
				data.header.small.blk_desc_len);

	arg->vol[0] = page->port[0].volume;
	arg->vol[1] = page->port[1].volume;
	arg->vol[2] = page->port[2].volume;
	arg->vol[3] = page->port[3].volume;

	return (0);
}

static int
cd_setvol(struct cd_softc *cd, const struct ioc_vol *arg, int flags)
{
	struct {
		union {
			struct scsi_mode_parameter_header_6 small;
			struct scsi_mode_parameter_header_10 big;
		} header;
		struct cd_audio_page page;
	} data, mask;
	int error;
	int big, byte2;
	struct cd_audio_page *page, *page2;

	byte2 = SMS_DBD;
try_again:
	if ((error = cd_mode_sense(cd, byte2, &data, sizeof(data.page),
	    AUDIO_PAGE, flags, &big)) != 0) {
		if (byte2 == SMS_DBD) {
			/* Device may not understand DBD; retry without */
			byte2 = 0;
			goto try_again;
		}
		return (error);
	}
	if ((error = cd_mode_sense(cd, byte2, &mask, sizeof(mask.page),
	    AUDIO_PAGE|SMS_PCTRL_CHANGEABLE, flags, &big)) != 0)
		return (error);

	if (big) {
		page = (void *)((u_long)&data.header.big +
				sizeof data.header.big +
				_2btol(data.header.big.blk_desc_len));
		page2 = (void *)((u_long)&mask.header.big +
				sizeof mask.header.big +
				_2btol(mask.header.big.blk_desc_len));
	} else {
		page = (void *)((u_long)&data.header.small +
				sizeof data.header.small +
				data.header.small.blk_desc_len);
		page2 = (void *)((u_long)&mask.header.small +
				sizeof mask.header.small +
				mask.header.small.blk_desc_len);
	}

	page->port[0].volume = arg->vol[0] & page2->port[0].volume;
	page->port[1].volume = arg->vol[1] & page2->port[1].volume;
	page->port[2].volume = arg->vol[2] & page2->port[2].volume;
	page->port[3].volume = arg->vol[3] & page2->port[3].volume;

	page->port[0].channels = CHANNEL_0;
	page->port[1].channels = CHANNEL_1;

	return (cd_mode_select(cd, SMS_PF, &data,
	    sizeof(struct scsi_mode_page_header) + page->pg_length,
	    flags, big));
}

static int
cd_load_unload(struct cd_softc *cd, struct ioc_load_unload *args)
{
	struct scsipi_load_unload cmd;

	memset(&cmd, 0, sizeof(cmd));
	cmd.opcode = LOAD_UNLOAD;
	cmd.options = args->options;    /* ioctl uses MMC values */
	cmd.slot = args->slot;

	return (scsipi_command(cd->sc_periph, (void *)&cmd, sizeof(cmd), 0, 0,
	    CDRETRIES, 200000, NULL, 0));
}

static int
cd_setblksize(struct cd_softc *cd)
{
	struct {
		union {
			struct scsi_mode_parameter_header_6 small;
			struct scsi_mode_parameter_header_10 big;
		} header;
		struct scsi_general_block_descriptor blk_desc;
	} data;
	int error;
	int big, bsize;
	struct scsi_general_block_descriptor *bdesc;

	if ((error = cd_mode_sense(cd, 0, &data, sizeof(data.blk_desc), 0, 0,
	    &big)) != 0)
		return (error);

	if (big) {
		bdesc = (void *)(&data.header.big + 1);
		bsize = _2btol(data.header.big.blk_desc_len);
	} else {
		bdesc = (void *)(&data.header.small + 1);
		bsize = data.header.small.blk_desc_len;
	}

	if (bsize == 0) {
printf("cd_setblksize: trying to change bsize, but no blk_desc\n");
		return (EINVAL);
	}
	if (_3btol(bdesc->blklen) == 2048) {
printf("cd_setblksize: trying to change bsize, but blk_desc is correct\n");
		return (EINVAL);
	}

	_lto3b(2048, bdesc->blklen);

	return (cd_mode_select(cd, SMS_PF, &data, sizeof(data.blk_desc), 0,
	    big));
}


static int
mmc_profile2class(uint16_t mmc_profile)
{
	switch (mmc_profile) {
	case 0x01 : /* SCSI discs */
	case 0x02 :
		/* this can't happen really, cd.c wouldn't have matched */
		return MMC_CLASS_DISC;
	case 0x03 : /* Magneto Optical with sector erase */
	case 0x04 : /* Magneto Optical write once        */
	case 0x05 : /* Advance Storage Magneto Optical   */
		return MMC_CLASS_MO;
	case 0x00 : /* Unknown MMC profile, can also be CD-ROM */
	case 0x08 : /* CD-ROM  */
	case 0x09 : /* CD-R    */
	case 0x0a : /* CD-RW   */
		return MMC_CLASS_CD;
	case 0x10 : /* DVD-ROM */
	case 0x11 : /* DVD-R   */
	case 0x12 : /* DVD-RAM */
	case 0x13 : /* DVD-RW restricted overwrite */
	case 0x14 : /* DVD-RW sequential */
	case 0x1a : /* DVD+RW  */
	case 0x1b : /* DVD+R   */
	case 0x2a : /* DVD+RW Dual layer */
	case 0x2b : /* DVD+R Dual layer */
	case 0x50 : /* HD DVD-ROM */
	case 0x51 : /* HD DVD-R   */
	case 0x52 : /* HD DVD-RW; DVD-RAM like */
		return MMC_CLASS_DVD;
	case 0x40 : /* BD-ROM  */
	case 0x41 : /* BD-R Sequential recording (SRM) */
	case 0x42 : /* BD-R Ramdom Recording (RRM) */
	case 0x43 : /* BD-RE */
		return MMC_CLASS_BD;
	}
	return MMC_CLASS_UNKN;
}


/*
 * Drive/media combination is reflected in a series of features that can
 * either be current or dormant. We try to make sense out of them to create a
 * set of easy to use flags that abstract the device/media capabilities.
 */

static void
mmc_process_feature(struct mmc_discinfo *mmc_discinfo,
		    uint16_t feature, int cur, uint8_t *rpos)
{
	uint32_t blockingnr;
	uint64_t flags;

	if (cur == 1) {
		flags = mmc_discinfo->mmc_cur;
	} else {
		flags = mmc_discinfo->mmc_cap;
	}

	switch (feature) {
	case 0x0010 :	/* random readable feature */
		blockingnr  =  rpos[5] | (rpos[4] << 8);
		if (blockingnr > 1)
			flags |= MMC_CAP_PACKET;

		/* RW error page */
		break;
	case 0x0020 :	/* random writable feature */
		flags |= MMC_CAP_RECORDABLE;
		flags |= MMC_CAP_REWRITABLE;
		blockingnr  =  rpos[9] | (rpos[8] << 8);
		if (blockingnr > 1)
			flags |= MMC_CAP_PACKET;
		break;
	case 0x0021 :	/* incremental streaming write feature */
		flags |= MMC_CAP_RECORDABLE;
		flags |= MMC_CAP_SEQUENTIAL;
		if (cur)
			mmc_discinfo->link_block_penalty = rpos[4];
		if (rpos[2] & 1)
			flags |= MMC_CAP_ZEROLINKBLK;
		break;
	case 0x0022 : 	/* (obsolete) erase support feature */
		flags |= MMC_CAP_RECORDABLE;
		flags |= MMC_CAP_ERASABLE;
		break;
	case 0x0023 :	/* formatting media support feature */
		flags |= MMC_CAP_RECORDABLE;
		flags |= MMC_CAP_FORMATTABLE;
		break;
	case 0x0024 :	/* hardware assised defect management feature */
		flags |= MMC_CAP_HW_DEFECTFREE;
		break;
	case 0x0025 : 	/* write once */
		flags |= MMC_CAP_RECORDABLE;
		break;
	case 0x0026 :	/* restricted overwrite feature */
		flags |= MMC_CAP_RECORDABLE;
		flags |= MMC_CAP_REWRITABLE;
		flags |= MMC_CAP_STRICTOVERWRITE;
		break;
	case 0x0028 :	/* MRW formatted media support feature */
		flags |= MMC_CAP_MRW;
		break;
	case 0x002b :	/* DVD+R read (and opt. write) support */
		flags |= MMC_CAP_SEQUENTIAL;
		if (rpos[0] & 1) /* write support */
			flags |= MMC_CAP_RECORDABLE;
		break;
	case 0x002c :	/* rigid restricted overwrite feature */
		flags |= MMC_CAP_RECORDABLE;
		flags |= MMC_CAP_REWRITABLE;
		flags |= MMC_CAP_STRICTOVERWRITE;
		if (rpos[0] & 1) /* blank bit */
			flags |= MMC_CAP_BLANKABLE;
		break;
	case 0x002d :	/* track at once recording feature */
		flags |= MMC_CAP_RECORDABLE;
		flags |= MMC_CAP_SEQUENTIAL;
		break;
	case 0x002f :	/* DVD-R/-RW write feature */
		flags |= MMC_CAP_RECORDABLE;
		if (rpos[0] & 2) /* DVD-RW bit */
			flags |= MMC_CAP_BLANKABLE;
		break;
	case 0x0038 :	/* BD-R SRM with pseudo overwrite */
		flags |= MMC_CAP_PSEUDOOVERWRITE;
		break;
	default :
		/* ignore */
		break;
	}

	if (cur == 1) {
		mmc_discinfo->mmc_cur = flags;
	} else {
		mmc_discinfo->mmc_cap = flags;
	}
}

static int
mmc_getdiscinfo_cdrom(struct scsipi_periph *periph,
		      struct mmc_discinfo *mmc_discinfo)
{
	struct scsipi_read_toc      gtoc_cmd;
	struct scsipi_toc_header   *toc_hdr;
	struct scsipi_toc_msinfo   *toc_msinfo;
	const uint32_t buffer_size = 1024;
	uint32_t req_size;
	uint8_t  *buffer;
	int error, flags;

	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
	/*
	 * Fabricate mmc_discinfo for CD-ROM. Some values are really `dont
	 * care' but others might be of interest to programs.
	 */

	mmc_discinfo->disc_state	 = MMC_STATE_FULL;
	mmc_discinfo->last_session_state = MMC_STATE_FULL;
	mmc_discinfo->bg_format_state    = MMC_BGFSTATE_COMPLETED;
	mmc_discinfo->link_block_penalty = 7;	/* not relevant */

	/* get number of sessions and first tracknr in last session */
	flags = XS_CTL_DATA_IN;
	memset(&gtoc_cmd, 0, sizeof(gtoc_cmd));
	gtoc_cmd.opcode      = READ_TOC;
	gtoc_cmd.addr_mode   = CD_MSF;		/* not relevant        */
	gtoc_cmd.resp_format = CD_TOC_MSINFO;	/* multisession info   */
	gtoc_cmd.from_track  = 0;		/* reserved, must be 0 */
	req_size = sizeof(*toc_hdr) + sizeof(*toc_msinfo);
	_lto2b(req_size, gtoc_cmd.data_len);

	error = scsipi_command(periph,
		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
		(void *)buffer,    req_size,
		CDRETRIES, 30000, NULL, flags);
	if (error)
		goto out;
	toc_hdr    = (struct scsipi_toc_header *)  buffer;
	toc_msinfo = (struct scsipi_toc_msinfo *) (buffer + 4);
	mmc_discinfo->num_sessions = toc_hdr->last - toc_hdr->first + 1;
	mmc_discinfo->first_track  = toc_hdr->first;
	mmc_discinfo->first_track_last_session = toc_msinfo->tracknr;

	/* get last track of last session */
	flags = XS_CTL_DATA_IN;
	gtoc_cmd.resp_format  = CD_TOC_FORM;	/* formatted toc */
	req_size = sizeof(*toc_hdr);
	_lto2b(req_size, gtoc_cmd.data_len);

	error = scsipi_command(periph,
		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
		(void *)buffer,    req_size,
		CDRETRIES, 30000, NULL, flags);
	if (error)
		goto out;
	toc_hdr    = (struct scsipi_toc_header *) buffer;
	mmc_discinfo->last_track_last_session = toc_hdr->last;
	mmc_discinfo->num_tracks = toc_hdr->last - toc_hdr->first + 1;

	/* TODO how to handle disc_barcode and disc_id */
	/* done */

out:
	free(buffer, M_TEMP);
	return error;
}

static int
mmc_getdiscinfo_dvdrom(struct scsipi_periph *periph,
		       struct mmc_discinfo *mmc_discinfo)
{
	struct scsipi_read_toc   gtoc_cmd;
	struct scsipi_toc_header toc_hdr;
	uint32_t req_size;
	int error, flags;

	/*
	 * Fabricate mmc_discinfo for DVD-ROM. Some values are really `dont
	 * care' but others might be of interest to programs.
	 */

	mmc_discinfo->disc_state	 = MMC_STATE_FULL;
	mmc_discinfo->last_session_state = MMC_STATE_FULL;
	mmc_discinfo->bg_format_state    = MMC_BGFSTATE_COMPLETED;
	mmc_discinfo->link_block_penalty = 16;	/* not relevant */

	/* get number of sessions and first tracknr in last session */
	flags = XS_CTL_DATA_IN;
	memset(&gtoc_cmd, 0, sizeof(gtoc_cmd));
	gtoc_cmd.opcode      = READ_TOC;
	gtoc_cmd.addr_mode   = 0;		/* LBA                 */
	gtoc_cmd.resp_format = CD_TOC_FORM;	/* multisession info   */
	gtoc_cmd.from_track  = 1;		/* first track         */
	req_size = sizeof(toc_hdr);
	_lto2b(req_size, gtoc_cmd.data_len);

	error = scsipi_command(periph,
		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
		(void *)&toc_hdr,  req_size,
		CDRETRIES, 30000, NULL, flags);
	if (error)
		return error;

	/* DVD-ROM squashes the track/session space */
	mmc_discinfo->num_sessions = toc_hdr.last - toc_hdr.first + 1;
	mmc_discinfo->num_tracks   = mmc_discinfo->num_sessions;
	mmc_discinfo->first_track  = toc_hdr.first;
	mmc_discinfo->first_track_last_session = toc_hdr.last;
	mmc_discinfo->last_track_last_session  = toc_hdr.last;

	/* TODO how to handle disc_barcode and disc_id */
	/* done */
	return 0;
}

static int
mmc_getdiscinfo(struct scsipi_periph *periph,
		struct mmc_discinfo *mmc_discinfo)
{
	struct scsipi_get_configuration   gc_cmd;
	struct scsipi_get_conf_data      *gc;
	struct scsipi_get_conf_feature   *gcf;
	struct scsipi_read_discinfo       di_cmd;
	struct scsipi_read_discinfo_data  di __aligned(2);
	const uint32_t buffer_size = 0x200; /* XXX RPZ USB3 SCSI size issue */
	uint32_t pos;
	u_long   last_lba = 0;
	uint8_t  *buffer, *fpos;
	int feature, last_feature, features_len, feature_cur, feature_len;
	int lsb, msb, error, flags;

	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);

	/* initialise structure */
	memset(mmc_discinfo, 0, sizeof(struct mmc_discinfo));
	mmc_discinfo->mmc_profile = 0x00;	/* unknown */
	mmc_discinfo->mmc_class   = MMC_CLASS_UNKN;
	mmc_discinfo->mmc_cur     = 0;
	mmc_discinfo->mmc_cap     = 0;
	mmc_discinfo->link_block_penalty = 0;

	/* determine mmc profile and class */
	flags = XS_CTL_DATA_IN;
	memset(&gc_cmd, 0, sizeof(gc_cmd));
	gc_cmd.opcode = GET_CONFIGURATION;
	_lto2b(GET_CONF_NO_FEATURES_LEN, gc_cmd.data_len);

	gc = (struct scsipi_get_conf_data *) buffer;

	error = scsipi_command(periph,
		(void *)&gc_cmd, sizeof(gc_cmd),
		(void *) gc,     GET_CONF_NO_FEATURES_LEN,
		CDRETRIES, 30000, NULL, flags);
	if (error)
		goto out;

	mmc_discinfo->mmc_profile = _2btol(gc->mmc_profile);
	mmc_discinfo->mmc_class = mmc_profile2class(mmc_discinfo->mmc_profile);

	/* assume 2048 sector size unless told otherwise */
	mmc_discinfo->sector_size = 2048;
	error = read_cd_capacity(periph, &mmc_discinfo->sector_size, &last_lba);
	if (error)
		goto out;

	mmc_discinfo->last_possible_lba = (uint32_t) last_lba;

	/* Read in all features to determine device capabilities */
	last_feature = feature = 0;
	do {
		/* determine mmc profile and class */
		flags = XS_CTL_DATA_IN;
		memset(&gc_cmd, 0, sizeof(gc_cmd));
		gc_cmd.opcode = GET_CONFIGURATION;
		_lto2b(last_feature, gc_cmd.start_at_feature);
		_lto2b(buffer_size, gc_cmd.data_len);
		memset(gc, 0, buffer_size);

		error = scsipi_command(periph,
			(void *)&gc_cmd, sizeof(gc_cmd),
			(void *) gc,     buffer_size,
			CDRETRIES, 30000, NULL, flags);
		if (error) {
			/* ieeek... break out of loop... i dunno what to do */
			break;
		}

		features_len = _4btol(gc->data_len);
		if (features_len < 4 || features_len > buffer_size)
			break;

		pos  = 0;
		fpos = &gc->feature_desc[0];
		while (pos < features_len - 4) {
			gcf = (struct scsipi_get_conf_feature *) fpos;

			feature     = _2btol(gcf->featurecode);
			feature_cur = gcf->flags & 1;
			feature_len = gcf->additional_length;

			mmc_process_feature(mmc_discinfo,
					    feature, feature_cur,
					    gcf->feature_dependent);

			last_feature = MAX(last_feature, feature);
#ifdef DIAGNOSTIC
			/* assert((feature_len & 3) == 0); */
			if ((feature_len & 3) != 0) {
				printf("feature %d having length %d\n",
					feature, feature_len);
			}
#endif

			pos  += 4 + feature_len;
			fpos += 4 + feature_len;
		}
		/* unlikely to ever grow past our 1kb buffer */
	} while (features_len >= 0xffff);

	/*
	 * Fixup CD-RW drives that are on crack.
	 *
	 * Some drives report the capability to incrementally write
	 * sequentially on CD-R(W) media...  nice, but this should not be
	 * active for a fixed packet formatted CD-RW media. Other report the
	 * ability of HW_DEFECTFREE even when the media is NOT MRW
	 * formatted....
	 */
	if (mmc_discinfo->mmc_profile == 0x0a) {
		if ((mmc_discinfo->mmc_cur & MMC_CAP_SEQUENTIAL) == 0)
			mmc_discinfo->mmc_cur |= MMC_CAP_STRICTOVERWRITE;
		if (mmc_discinfo->mmc_cur & MMC_CAP_STRICTOVERWRITE)
			mmc_discinfo->mmc_cur &= ~MMC_CAP_SEQUENTIAL;
		if (mmc_discinfo->mmc_cur & MMC_CAP_MRW) {
			mmc_discinfo->mmc_cur &= ~MMC_CAP_SEQUENTIAL;
			mmc_discinfo->mmc_cur &= ~MMC_CAP_STRICTOVERWRITE;
		} else {
			mmc_discinfo->mmc_cur &= ~MMC_CAP_HW_DEFECTFREE;
		}
	}
	if (mmc_discinfo->mmc_profile == 0x09) {
		mmc_discinfo->mmc_cur &= ~MMC_CAP_REWRITABLE;
	}

#ifdef DEBUG
	printf("CD mmc %d, mmc_cur 0x%"PRIx64", mmc_cap 0x%"PRIx64"\n",
		mmc_discinfo->mmc_profile,
	 	mmc_discinfo->mmc_cur, mmc_discinfo->mmc_cap);
#endif

	/* read in disc state and number of sessions and tracks */
	flags = XS_CTL_DATA_IN | XS_CTL_SILENT;
	memset(&di_cmd, 0, sizeof(di_cmd));
	di_cmd.opcode = READ_DISCINFO;
	di_cmd.data_len[1] = READ_DISCINFO_BIGSIZE;

	error = scsipi_command(periph,
		(void *)&di_cmd, sizeof(di_cmd),
		(void *)&di,     READ_DISCINFO_BIGSIZE,
		CDRETRIES, 30000, NULL, flags);

	if (error) {
		/* discinfo call failed, emulate for cd-rom/dvd-rom */
		if (mmc_discinfo->mmc_profile == 0x08) /* CD-ROM */
			error = mmc_getdiscinfo_cdrom(periph, mmc_discinfo);
		else if (mmc_discinfo->mmc_profile == 0x10) /* DVD-ROM */
			error = mmc_getdiscinfo_dvdrom(periph, mmc_discinfo);
		else /* CD/DVD drive is violating specs */
			error = EIO;
		goto out;
	}

	/* call went OK */
	mmc_discinfo->disc_state         =  di.disc_state & 3;
	mmc_discinfo->last_session_state = (di.disc_state >> 2) & 3;
	mmc_discinfo->bg_format_state    = (di.disc_state2 & 3);

	lsb = di.num_sessions_lsb;
	msb = di.num_sessions_msb;
	mmc_discinfo->num_sessions = lsb | (msb << 8);

	mmc_discinfo->first_track = di.first_track;
	lsb = di.first_track_last_session_lsb;
	msb = di.first_track_last_session_msb;
	mmc_discinfo->first_track_last_session = lsb | (msb << 8);
	lsb = di.last_track_last_session_lsb;
	msb = di.last_track_last_session_msb;
	mmc_discinfo->last_track_last_session  = lsb | (msb << 8);

	mmc_discinfo->num_tracks = mmc_discinfo->last_track_last_session -
		mmc_discinfo->first_track + 1;

	/* set misc. flags and parameters from this disc info */
	if (di.disc_state  &  16)
		mmc_discinfo->mmc_cur |= MMC_CAP_BLANKABLE;

	if (di.disc_state2 & 128) {
		mmc_discinfo->disc_id = _4btol(di.discid);
		mmc_discinfo->disc_flags |= MMC_DFLAGS_DISCIDVALID;
	}
	if (di.disc_state2 &  64) {
		mmc_discinfo->disc_barcode = _8btol(di.disc_bar_code);
		mmc_discinfo->disc_flags |= MMC_DFLAGS_BARCODEVALID;
	}
	if (di.disc_state2 &  32)
		mmc_discinfo->disc_flags |= MMC_DFLAGS_UNRESTRICTED;

	if (di.disc_state2 &  16) {
		mmc_discinfo->application_code = di.application_code;
		mmc_discinfo->disc_flags |= MMC_DFLAGS_APPCODEVALID;
	}

	/* done */

out:
	free(buffer, M_TEMP);
	return error;
}

static int
mmc_gettrackinfo_cdrom(struct scsipi_periph *periph,
		       struct mmc_trackinfo *trackinfo)
{
	struct scsipi_read_toc            gtoc_cmd;
	struct scsipi_toc_header         *toc_hdr;
	struct scsipi_toc_rawtoc         *rawtoc;
	uint32_t track_start, track_size;
	uint32_t last_recorded, next_writable;
	uint32_t lba, next_track_start, lead_out;
	const uint32_t buffer_size = 4 * 1024;	/* worst case TOC estimate */
	uint8_t *buffer;
	uint8_t track_sessionnr, sessionnr, adr, tno, point;
	uint8_t control, tmin, tsec, tframe, pmin, psec, pframe;
	int size, req_size;
	int error, flags;

	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);

	/*
	 * Emulate read trackinfo for CD-ROM using the raw-TOC.
	 *
	 * Not all information is present and this presents a problem.  Track
	 * starts are known for each track but other values are deducted.
	 *
	 * For a complete overview of `magic' values used here, see the
	 * SCSI/ATAPI MMC documentation. Note that the `magic' values have no
	 * names, they are specified as numbers.
	 */

	/* get raw toc to process, first header to check size */
	flags = XS_CTL_DATA_IN | XS_CTL_SILENT;
	memset(&gtoc_cmd, 0, sizeof(gtoc_cmd));
	gtoc_cmd.opcode      = READ_TOC;
	gtoc_cmd.addr_mode   = CD_MSF;		/* not relevant     */
	gtoc_cmd.resp_format = CD_TOC_RAW;	/* raw toc          */
	gtoc_cmd.from_track  = 1;		/* first session    */
	req_size = sizeof(*toc_hdr);
	_lto2b(req_size, gtoc_cmd.data_len);

	error = scsipi_command(periph,
		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
		(void *)buffer,    req_size,
		CDRETRIES, 30000, NULL, flags);
	if (error)
		goto out;
	toc_hdr = (struct scsipi_toc_header *) buffer;
	if (_2btol(toc_hdr->length) > buffer_size - 2) {
#ifdef DIAGNOSTIC
		printf("increase buffersize in mmc_readtrackinfo_cdrom\n");
#endif
		error = ENOBUFS;
		goto out;
	}

	/* read in complete raw toc */
	req_size = _2btol(toc_hdr->length);
	req_size = 2*((req_size + 1) / 2);	/* for ATAPI */
	_lto2b(req_size, gtoc_cmd.data_len);

	error = scsipi_command(periph,
		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
		(void *)buffer,    req_size,
		CDRETRIES, 30000, NULL, flags);
	if (error)
		goto out;

	toc_hdr = (struct scsipi_toc_header *) buffer;
	rawtoc  = (struct scsipi_toc_rawtoc *) (buffer + 4);

	track_start      = 0;
	track_size       = 0;
	last_recorded    = 0;
	next_writable    = 0;
	flags            = 0;

	next_track_start = 0;
	track_sessionnr  = MAXTRACK;	/* by definition */
	lead_out         = 0;

	size = req_size - sizeof(struct scsipi_toc_header) + 1;
	while (size > 0) {
		/* get track start and session end */
		tno       = rawtoc->tno;
		sessionnr = rawtoc->sessionnr;
		adr       = rawtoc->adrcontrol >> 4;
		control   = rawtoc->adrcontrol & 0xf;
		point     = rawtoc->point;
		tmin      = rawtoc->min;
		tsec      = rawtoc->sec;
		tframe    = rawtoc->frame;
		pmin      = rawtoc->pmin;
		psec      = rawtoc->psec;
		pframe    = rawtoc->pframe;

		if (tno == 0 && sessionnr && adr == 1) {
			lba = hmsf2lba(0, pmin, psec, pframe);
			if (point == trackinfo->tracknr) {
				track_start = lba;
				track_sessionnr = sessionnr;
			}
			if (point == trackinfo->tracknr + 1) {
				/* estimate size */
				track_size = lba - track_start;
				next_track_start = lba;
			}
			if (point == 0xa2) {
				lead_out = lba;
			}
			if (point <= 0x63) {
				/* CD's ok, DVD are glued */
				/* last_tracknr = point; */
			}
			if (sessionnr == track_sessionnr) {
				last_recorded = lead_out;
			}
		}
		if (tno == 0 && sessionnr && adr == 5) {
			lba = hmsf2lba(0, tmin, tsec, tframe);
			if (sessionnr == track_sessionnr) {
				next_writable = lba;
			}
		}

		if ((control & (3<<2)) == 4)		/* 01xxb */
			flags |= MMC_TRACKINFO_DATA;
		if ((control & (1<<2)) == 0) {		/* x0xxb */
			flags |= MMC_TRACKINFO_AUDIO;
			if (control & 1)		/* xxx1b */
				flags |= MMC_TRACKINFO_PRE_EMPH;
		}

		rawtoc++;
		size -= sizeof(struct scsipi_toc_rawtoc);
	}

	/* process found values; some voodoo */
	/* if no tracksize tracknr is the last of the disc */
	if ((track_size == 0) && last_recorded) {
		track_size = last_recorded - track_start;
	}
	/* if last_recorded < tracksize, tracksize is overestimated */
	if (last_recorded) {
		if (last_recorded - track_start <= track_size) {
			track_size = last_recorded - track_start;
			flags |= MMC_TRACKINFO_LRA_VALID;
		}
	}
	/* check if its a the last track of the sector */
	if (next_writable) {
		if (next_track_start > next_writable)
			flags |= MMC_TRACKINFO_NWA_VALID;
	}

	/* no flag set -> no values */
	if ((flags & MMC_TRACKINFO_LRA_VALID) == 0)
		last_recorded = 0;
	if ((flags & MMC_TRACKINFO_NWA_VALID) == 0)
		next_writable = 0;

	/* fill in */
	/* trackinfo->tracknr preserved */
	trackinfo->sessionnr  = track_sessionnr;
	trackinfo->track_mode = 7;	/* data, incremental  */
	trackinfo->data_mode  = 8;	/* 2048 bytes mode1   */

	trackinfo->flags = flags;
	trackinfo->track_start   = track_start;
	trackinfo->next_writable = next_writable;
	trackinfo->free_blocks   = 0;
	trackinfo->packet_size   = 1;
	trackinfo->track_size    = track_size;
	trackinfo->last_recorded = last_recorded;

out:
	free(buffer, M_TEMP);
	return error;

}

static int
mmc_gettrackinfo_dvdrom(struct scsipi_periph *periph, 
			struct mmc_trackinfo *trackinfo)
{
	struct scsipi_read_toc            gtoc_cmd;
	struct scsipi_toc_header         *toc_hdr;
	struct scsipi_toc_formatted      *toc;
	uint32_t tracknr, track_start, track_size;
	uint32_t lba, lead_out;
	const uint32_t buffer_size = 4 * 1024;	/* worst case TOC estimate */
	uint8_t *buffer;
	uint8_t control, last_tracknr;
	int size, req_size;
	int error, flags;

	
	buffer = malloc(buffer_size, M_TEMP, M_WAITOK);
	/*
	 * Emulate read trackinfo for DVD-ROM. We can't use the raw-TOC as the
	 * CD-ROM emulation uses since the specification tells us that no such
	 * thing is defined for DVD's. The reason for this is due to the large
	 * number of tracks and that would clash with the `magic' values. This
	 * suxs.
	 *
	 * Not all information is present and this presents a problem.
	 * Track starts are known for each track but other values are
	 * deducted.
	 */

	/* get formatted toc to process, first header to check size */
	flags = XS_CTL_DATA_IN | XS_CTL_SILENT;
	memset(&gtoc_cmd, 0, sizeof(gtoc_cmd));
	gtoc_cmd.opcode      = READ_TOC;
	gtoc_cmd.addr_mode   = 0;		/* lba's please     */
	gtoc_cmd.resp_format = CD_TOC_FORM;	/* formatted toc    */
	gtoc_cmd.from_track  = 1;		/* first track      */
	req_size = sizeof(*toc_hdr);
	_lto2b(req_size, gtoc_cmd.data_len);

	error = scsipi_command(periph,
		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
		(void *)buffer,    req_size,
		CDRETRIES, 30000, NULL, flags);
	if (error)
		goto out;
	toc_hdr = (struct scsipi_toc_header *) buffer;
	if (_2btol(toc_hdr->length) > buffer_size - 2) {
#ifdef DIAGNOSTIC
		printf("incease buffersize in mmc_readtrackinfo_dvdrom\n");
#endif
		error = ENOBUFS;
		goto out;
	}

	/* read in complete formatted toc */
	req_size = _2btol(toc_hdr->length);
	_lto2b(req_size, gtoc_cmd.data_len);

	error = scsipi_command(periph,
		(void *)&gtoc_cmd, sizeof(gtoc_cmd),
		(void *)buffer,    req_size,
		CDRETRIES, 30000, NULL, flags);
	if (error)
		goto out;

	toc_hdr = (struct scsipi_toc_header *)     buffer;
	toc     = (struct scsipi_toc_formatted *) (buffer + 4);

	/* as in read disc info, all sessions are converted to tracks      */
	/* track 1..  -> offsets, sizes can be (rougly) estimated (16 ECC) */
	/* last track -> we got the size from the lead-out                 */

	tracknr      = 0;
	last_tracknr = toc_hdr->last;
	track_start  = 0;
	track_size   = 0;
	lead_out     = 0;
	flags        = 0;

	size = req_size - sizeof(struct scsipi_toc_header) + 1;
	while (size > 0) {
		/* remember, DVD-ROM: tracknr == sessionnr */
		lba     = _4btol(toc->msf_lba);
		tracknr = toc->tracknr;
		control = toc->adrcontrol & 0xf;

		if (trackinfo->tracknr == tracknr) {
			track_start = lba;
		}
		if (trackinfo->tracknr == tracknr+1) {
			track_size  = lba - track_start;
			track_size -= 16;	/* link block ? */
		}
		if (tracknr == 0xAA) {
			lead_out = lba;
		}

		if ((control & (3<<2)) == 4)		/* 01xxb */
			flags |= MMC_TRACKINFO_DATA;
		if ((control & (1<<2)) == 0) {		/* x0xxb */
			flags |= MMC_TRACKINFO_AUDIO;
			if (control & (1<<3))		/* 10xxb */
				flags |= MMC_TRACKINFO_AUDIO_4CHAN;
			if (control & 1)		/* xxx1b */
				flags |= MMC_TRACKINFO_PRE_EMPH;
		}

		toc++;
		size -= sizeof(struct scsipi_toc_formatted);
	}
	if (trackinfo->tracknr == last_tracknr) {
		track_size = lead_out - track_start;
	}

	/* fill in */
	/* trackinfo->tracknr preserved */
	trackinfo->sessionnr  = trackinfo->tracknr;
	trackinfo->track_mode = 0;	/* unknown */
	trackinfo->data_mode  = 8;	/* 2048 bytes mode1   */

	trackinfo->flags         = flags;
	trackinfo->track_start   = track_start;
	trackinfo->next_writable = 0;
	trackinfo->free_blocks   = 0;
	trackinfo->packet_size   = 16;	/* standard length 16 blocks ECC */
	trackinfo->track_size    = track_size;
	trackinfo->last_recorded = 0;

out:
	free(buffer, M_TEMP);
	return error;
}

static int
mmc_gettrackinfo(struct scsipi_periph *periph, 
		 struct mmc_trackinfo *trackinfo)
{
	struct scsipi_read_trackinfo      ti_cmd;
	struct scsipi_read_trackinfo_data ti __aligned(2);
	struct scsipi_get_configuration   gc_cmd;
	struct scsipi_get_conf_data       gc __aligned(2);
	int error, flags;
	int mmc_profile;

	/* set up SCSI call with track number from trackinfo.tracknr */
	flags = XS_CTL_DATA_IN | XS_CTL_SILENT;
	memset(&ti_cmd, 0, sizeof(ti_cmd));
	ti_cmd.opcode    = READ_TRACKINFO;
	ti_cmd.addr_type = READ_TRACKINFO_ADDR_TRACK;
	ti_cmd.data_len[1] = READ_TRACKINFO_RETURNSIZE;

	/* trackinfo.tracknr contains number of tracks to query */
	_lto4b(trackinfo->tracknr, ti_cmd.address);
	error = scsipi_command(periph,
		(void *)&ti_cmd, sizeof(ti_cmd),
		(void *)&ti,     READ_TRACKINFO_RETURNSIZE,
		CDRETRIES, 30000, NULL, flags);

	if (error) {
		/* trackinfo call failed, emulate for cd-rom/dvd-rom */
		/* first determine mmc profile */
		flags = XS_CTL_DATA_IN;
		memset(&gc_cmd, 0, sizeof(gc_cmd));
		gc_cmd.opcode = GET_CONFIGURATION;
		_lto2b(GET_CONF_NO_FEATURES_LEN, gc_cmd.data_len);

		error = scsipi_command(periph,
			(void *)&gc_cmd, sizeof(gc_cmd),
			(void *)&gc,     GET_CONF_NO_FEATURES_LEN,
			CDRETRIES, 30000, NULL, flags);
		if (error)
			return error;
		mmc_profile = _2btol(gc.mmc_profile);

		/* choose emulation */
		if (mmc_profile == 0x08) /* CD-ROM */
			return mmc_gettrackinfo_cdrom(periph, trackinfo);
		if (mmc_profile == 0x10) /* DVD-ROM */
			return mmc_gettrackinfo_dvdrom(periph, trackinfo);
		/* CD/DVD drive is violating specs */
		return EIO;
	}

	/* (re)initialise structure */
	memset(trackinfo, 0, sizeof(struct mmc_trackinfo));

	/* account for short returns screwing up track and session msb */
	if ((ti.data_len[1] | (ti.data_len[0] << 8)) <= 32) {
		ti.track_msb   = 0;
		ti.session_msb = 0;
	}

	trackinfo->tracknr    = ti.track_lsb   | (ti.track_msb   << 8);
	trackinfo->sessionnr  = ti.session_lsb | (ti.session_msb << 8);
	trackinfo->track_mode = ti.track_info_1 & 0xf;
	trackinfo->data_mode  = ti.track_info_2 & 0xf;

	flags = 0;
	if (ti.track_info_1 & 0x10)
		flags |= MMC_TRACKINFO_COPY;
	if (ti.track_info_1 & 0x20)
		flags |= MMC_TRACKINFO_DAMAGED;
	if (ti.track_info_2 & 0x10)
		flags |= MMC_TRACKINFO_FIXED_PACKET;
	if (ti.track_info_2 & 0x20)
		flags |= MMC_TRACKINFO_INCREMENTAL;
	if (ti.track_info_2 & 0x40)
		flags |= MMC_TRACKINFO_BLANK;
	if (ti.track_info_2 & 0x80)
		flags |= MMC_TRACKINFO_RESERVED;
	if (ti.data_valid   & 0x01)
		flags |= MMC_TRACKINFO_NWA_VALID;
	if (ti.data_valid   & 0x02)
		flags |= MMC_TRACKINFO_LRA_VALID;
	if ((trackinfo->track_mode & (3<<2)) == 4)		/* 01xxb */
		flags |= MMC_TRACKINFO_DATA;
	if ((trackinfo->track_mode & (1<<2)) == 0) {		/* x0xxb */
		flags |= MMC_TRACKINFO_AUDIO;
		if (trackinfo->track_mode & (1<<3))		/* 10xxb */
			flags |= MMC_TRACKINFO_AUDIO_4CHAN;
		if (trackinfo->track_mode & 1)			/* xxx1b */
			flags |= MMC_TRACKINFO_PRE_EMPH;
	}

	trackinfo->flags = flags;
	trackinfo->track_start    = _4btol(ti.track_start);
	trackinfo->next_writable  = _4btol(ti.next_writable);
	trackinfo->free_blocks    = _4btol(ti.free_blocks);
	trackinfo->packet_size    = _4btol(ti.packet_size);
	trackinfo->track_size     = _4btol(ti.track_size);
	trackinfo->last_recorded  = _4btol(ti.last_recorded);

	return 0;
}

static int
mmc_doclose(struct scsipi_periph *periph, int param, int func) {
	struct scsipi_close_tracksession close_cmd;
	int error, flags;

	/* set up SCSI call with track number */
	flags = XS_CTL_DATA_OUT;
	memset(&close_cmd, 0, sizeof(close_cmd));
	close_cmd.opcode    = CLOSE_TRACKSESSION;
	close_cmd.function  = func;
	_lto2b(param, close_cmd.tracksessionnr);

	error = scsipi_command(periph,
		(void *) &close_cmd, sizeof(close_cmd),
		NULL, 0,
		CDRETRIES, 120000, NULL, flags);

	return error;
}

static int
mmc_do_closetrack(struct scsipi_periph *periph, struct mmc_op *mmc_op)
{
	int mmc_profile = mmc_op->mmc_profile;

	switch (mmc_profile) {
	case 0x12 : /* DVD-RAM */
	case 0x1a : /* DVD+RW  */
	case 0x2a : /* DVD+RW Dual layer */
	case 0x42 : /* BD-R Ramdom Recording (RRM) */
	case 0x43 : /* BD-RE */
	case 0x52 : /* HD DVD-RW ; DVD-RAM like */
		return EINVAL;
	}

	return mmc_doclose(periph, mmc_op->tracknr, 1);
}

static int
mmc_do_close_or_finalise(struct scsipi_periph *periph, struct mmc_op *mmc_op)
{
	uint8_t blob[MS5LEN], *page5;
	int mmc_profile = mmc_op->mmc_profile;
	int func, close, flags;
	int error;

	close = (mmc_op->operation == MMC_OP_CLOSESESSION);

	switch (mmc_profile) {
	case 0x09 : /* CD-R       */
	case 0x0a : /* CD-RW      */
		/* Special case : need to update MS field in mode page 5 */
		memset(blob, 0, sizeof(blob));
		page5 = blob+8;

		flags = XS_CTL_DATA_IN;
		error = scsipi_mode_sense_big(periph, SMS_PF, 5,
		    (void *)blob, sizeof(blob), flags, CDRETRIES, 20000);
		if (error)
			return error;

		/* set multi session field when closing a session only */
		page5[3] &= 63;
		if (close)
			page5[3] |= 3 << 6;

		flags = XS_CTL_DATA_OUT;
		error = scsipi_mode_select_big(periph, SMS_PF,
		    (void *)blob, sizeof(blob), flags, CDRETRIES, 20000);
		if (error)
			return error;
		/* and use funtion 2 */
		func = 2;
		break;
	case 0x11 : /* DVD-R (DL) */
	case 0x13 : /* DVD-RW restricted overwrite */
	case 0x14 : /* DVD-RW sequential */
		func = close ? 2 : 3;
		break;
	case 0x1b : /* DVD+R   */
	case 0x2b : /* DVD+R Dual layer */
	case 0x51 : /* HD DVD-R   */
	case 0x41 : /* BD-R Sequential recording (SRM) */
		func = close ? 2 : 6;
		break;
	case 0x12 : /* DVD-RAM */
	case 0x1a : /* DVD+RW  */
	case 0x2a : /* DVD+RW Dual layer */
	case 0x42 : /* BD-R Ramdom Recording (RRM) */
	case 0x43 : /* BD-RE */
	case 0x52 : /* HD DVD-RW; DVD-RAM like */
		return EINVAL;
	default:
		printf("MMC close/finalise passed wrong device type! (%d)\n",
		    mmc_profile);
		return EINVAL;
	}

	return mmc_doclose(periph, mmc_op->sessionnr, func);
}

static int
mmc_do_reserve_track(struct scsipi_periph *periph, struct mmc_op *mmc_op)
{
	struct scsipi_reserve_track reserve_cmd;
	uint32_t extent;
	int error, flags;

	/* TODO make mmc safeguards? */
	extent = mmc_op->extent;
	/* TODO min/max support? */

	/* set up SCSI call with requested space */
	flags = XS_CTL_DATA_OUT;
	memset(&reserve_cmd, 0, sizeof(reserve_cmd));
	reserve_cmd.opcode = RESERVE_TRACK;
	_lto4b(extent, reserve_cmd.reservation_size);

	error = scsipi_command(periph,
		(void *) &reserve_cmd, sizeof(reserve_cmd),
		NULL, 0,
		CDRETRIES, 30000, NULL, flags);

	return error;
}

static int
mmc_do_reserve_track_nwa(struct scsipi_periph *periph, struct mmc_op *mmc_op)
{
	/* XXX assumes that NWA given is valid */
	switch (mmc_op->mmc_profile) {
	case 0x09 : /* CD-R       */
		/* XXX unknown boundary checks XXX */
		if (mmc_op->extent <= 152)
			return EINVAL;
		/* CD-R takes 152 sectors to close track */
		mmc_op->extent -= 152;
		return mmc_do_reserve_track(periph, mmc_op);
	case 0x11 : /* DVD-R (DL) */
	case 0x1b : /* DVD+R   */
	case 0x2b : /* DVD+R Dual layer */
		if (mmc_op->extent % 16)
			return EINVAL;
		/* upto one ECC block of 16 sectors lost */
		mmc_op->extent -= 16;
		return mmc_do_reserve_track(periph, mmc_op);
	case 0x41 : /* BD-R Sequential recording (SRM) */
	case 0x51 : /* HD DVD-R   */
		if (mmc_op->extent % 32)
			return EINVAL;
		/* one ECC block of 32 sectors lost (AFAIK) */
		mmc_op->extent -= 32;
		return mmc_do_reserve_track(periph, mmc_op);
	}

	/* unknown behaviour or invalid disc type */
	return EINVAL;
}

static int
mmc_do_repair_track(struct scsipi_periph *periph, struct mmc_op *mmc_op)
{
	struct scsipi_repair_track repair_cmd;
	int error, flags;

	/* TODO make mmc safeguards? */

	/* set up SCSI call with track number */
	flags = XS_CTL_DATA_OUT;
	memset(&repair_cmd, 0, sizeof(repair_cmd));
	repair_cmd.opcode = REPAIR_TRACK;
	_lto2b(mmc_op->tracknr, repair_cmd.tracknr);

	error = scsipi_command(periph,
		(void *) &repair_cmd, sizeof(repair_cmd),
		NULL, 0,
		CDRETRIES, 30000, NULL, flags);

	return error;
}

static int
mmc_do_op(struct scsipi_periph *periph, struct mmc_op *mmc_op)
{
	/* guard operation value */
	if (mmc_op->operation < 1 || mmc_op->operation > MMC_OP_MAX)
		return EINVAL;

	/* synchronise cache is special since it doesn't rely on mmc_profile */
	if (mmc_op->operation == MMC_OP_SYNCHRONISECACHE)
		return cdcachesync(periph, 0);

	/* zero mmc_profile means unknown disc so operations are not defined */
	if (mmc_op->mmc_profile == 0) {
#ifdef DEBUG
		printf("mmc_do_op called with mmc_profile = 0\n");
#endif
		return EINVAL;
	}

	/* do the operations */
	switch (mmc_op->operation) {
	case MMC_OP_CLOSETRACK   :
		return mmc_do_closetrack(periph, mmc_op);
	case MMC_OP_CLOSESESSION :
	case MMC_OP_FINALISEDISC :
		return mmc_do_close_or_finalise(periph, mmc_op);
	case MMC_OP_RESERVETRACK :
		return mmc_do_reserve_track(periph, mmc_op);
	case MMC_OP_RESERVETRACK_NWA :
		return mmc_do_reserve_track_nwa(periph, mmc_op);
	case MMC_OP_REPAIRTRACK  :
		return mmc_do_repair_track(periph, mmc_op);
	case MMC_OP_UNCLOSELASTSESSION :
		/* TODO unclose last session support */
		return EINVAL;
	default :
		printf("mmc_do_op: unhandled operation %d\n", mmc_op->operation);
	}

	return EINVAL;
}

static int
mmc_setup_writeparams(struct scsipi_periph *periph,
		      struct mmc_writeparams *mmc_writeparams)
{
	struct mmc_trackinfo trackinfo;
	uint8_t blob[MS5LEN];
	uint8_t *page5;
	int flags, error;
	int track_mode, data_mode;

	/* setup mode page 5 for CD only */
	if (mmc_writeparams->mmc_class != MMC_CLASS_CD)
		return 0;

	memset(blob, 0, sizeof(blob));
	page5 = blob+8;

	/* read mode page 5 (with header) */
	flags = XS_CTL_DATA_IN;
	error = scsipi_mode_sense_big(periph, SMS_PF, 5, (void *)blob,
	    sizeof(blob), flags, CDRETRIES, 20000);
	if (error)
		return error;

	/* set page length for reasurance */
	page5[1] = P5LEN;	/* page length */

	/* write type packet/incremental */
	page5[2] &= 0xf0;

	/* set specified mode parameters */
	track_mode = mmc_writeparams->track_mode;
	data_mode  = mmc_writeparams->data_mode;
	if (track_mode <= 0 || track_mode > 15)
		return EINVAL;
	if (data_mode < 1 || data_mode > 2)
		return EINVAL;

	/* if a tracknr is passed, setup according to the track */
	if (mmc_writeparams->tracknr > 0) {
		trackinfo.tracknr = mmc_writeparams->tracknr;
		error = mmc_gettrackinfo(periph, &trackinfo);
		if (error)
			return error;
		if ((trackinfo.flags & MMC_TRACKINFO_BLANK) == 0) {
			track_mode = trackinfo.track_mode;
			data_mode  = trackinfo.data_mode;
		}
		mmc_writeparams->blockingnr = trackinfo.packet_size;
	}

	/* copy track mode and data mode from trackinfo */
	page5[3] &= 16;		/* keep only `Copy' bit */
	page5[3] |= (3 << 6) | track_mode;
	page5[4] &= 0xf0;	/* wipe data block type */
	if (data_mode == 1) {
		/* select ISO mode 1 (CD only) */
		page5[4] |= 8;
		/* select session format normal disc (CD only) */
		page5[8] = 0;
	} else {
		/* select ISO mode 2; XA form 1 (CD only) */
		page5[4] |= 10;
		/* select session format CD-ROM XA disc (CD only) */
		page5[8] = 0x20;
	}
	if (mmc_writeparams->mmc_cur & MMC_CAP_SEQUENTIAL) {
		if (mmc_writeparams->mmc_cur & MMC_CAP_ZEROLINKBLK) {
			/* set BUFE buffer underrun protection */
			page5[2] |= 1<<6;
		}
		/* allow for multi session */
		page5[3] |= 3 << 6;
	} else {
		/* select fixed packets */
		page5[3] |= 1<<5;
		_lto4b(mmc_writeparams->blockingnr, &(page5[10]));
	}

	/* write out updated mode page 5 (with header) */
	flags = XS_CTL_DATA_OUT;
	error = scsipi_mode_select_big(periph, SMS_PF, (void *)blob,
	    sizeof(blob), flags, CDRETRIES, 20000);
	if (error)
		return error;

	return 0;
}

static void
cd_set_geometry(struct cd_softc *cd)
{
	struct dk_softc *dksc = &cd->sc_dksc;
	struct disk_geom *dg = &dksc->sc_dkdev.dk_geom;

	memset(dg, 0, sizeof(*dg));

	dg->dg_secperunit = cd->params.disksize;
	dg->dg_secsize = cd->params.blksize;
	dg->dg_nsectors = 100;
	dg->dg_ntracks = 1;

	disk_set_info(dksc->sc_dev, &dksc->sc_dkdev, NULL);
}