aboutsummaryrefslogtreecommitdiff
path: root/sys/cam/ata/ata_da.c
blob: 5077b77914266ae40e5d1e8a7753a6b0f9b78e6f (plain) (blame)
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
/*-
 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
 *
 * Copyright (c) 2009 Alexander Motin <mav@FreeBSD.org>
 * All rights reserved.
 *
 * 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,
 *    without modification, immediately at the beginning of the file.
 * 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 AUTHOR ``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 AUTHOR 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.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");

#include "opt_ada.h"

#include <sys/param.h>

#ifdef _KERNEL
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/bio.h>
#include <sys/sysctl.h>
#include <sys/taskqueue.h>
#include <sys/lock.h>
#include <sys/mutex.h>
#include <sys/conf.h>
#include <sys/devicestat.h>
#include <sys/eventhandler.h>
#include <sys/malloc.h>
#include <sys/endian.h>
#include <sys/cons.h>
#include <sys/proc.h>
#include <sys/reboot.h>
#include <sys/sbuf.h>
#include <geom/geom_disk.h>
#endif /* _KERNEL */

#ifndef _KERNEL
#include <stdio.h>
#include <string.h>
#endif /* _KERNEL */

#include <cam/cam.h>
#include <cam/cam_ccb.h>
#include <cam/cam_periph.h>
#include <cam/cam_xpt_periph.h>
#include <cam/scsi/scsi_all.h>
#include <cam/scsi/scsi_da.h>
#include <cam/cam_sim.h>
#include <cam/cam_iosched.h>

#include <cam/ata/ata_all.h>

#include <machine/md_var.h>	/* geometry translation */

#ifdef _KERNEL

#define ATA_MAX_28BIT_LBA               268435455UL

extern int iosched_debug;

typedef enum {
	ADA_STATE_RAHEAD,
	ADA_STATE_WCACHE,
	ADA_STATE_LOGDIR,
	ADA_STATE_IDDIR,
	ADA_STATE_SUP_CAP,
	ADA_STATE_ZONE,
	ADA_STATE_NORMAL
} ada_state;

typedef enum {
	ADA_FLAG_CAN_48BIT	= 0x00000002,
	ADA_FLAG_CAN_FLUSHCACHE	= 0x00000004,
	ADA_FLAG_CAN_NCQ	= 0x00000008,
	ADA_FLAG_CAN_DMA	= 0x00000010,
	ADA_FLAG_NEED_OTAG	= 0x00000020,
	ADA_FLAG_WAS_OTAG	= 0x00000040,
	ADA_FLAG_CAN_TRIM	= 0x00000080,
	ADA_FLAG_OPEN		= 0x00000100,
	ADA_FLAG_SCTX_INIT	= 0x00000200,
	ADA_FLAG_CAN_CFA        = 0x00000400,
	ADA_FLAG_CAN_POWERMGT   = 0x00000800,
	ADA_FLAG_CAN_DMA48	= 0x00001000,
	ADA_FLAG_CAN_LOG	= 0x00002000,
	ADA_FLAG_CAN_IDLOG	= 0x00004000,
	ADA_FLAG_CAN_SUPCAP	= 0x00008000,
	ADA_FLAG_CAN_ZONE	= 0x00010000,
	ADA_FLAG_CAN_WCACHE	= 0x00020000,
	ADA_FLAG_CAN_RAHEAD	= 0x00040000,
	ADA_FLAG_PROBED		= 0x00080000,
	ADA_FLAG_ANNOUNCED	= 0x00100000,
	ADA_FLAG_DIRTY		= 0x00200000,
	ADA_FLAG_CAN_NCQ_TRIM	= 0x00400000,	/* CAN_TRIM also set */
	ADA_FLAG_PIM_ATA_EXT	= 0x00800000
} ada_flags;

typedef enum {
	ADA_Q_NONE		= 0x00,
	ADA_Q_4K		= 0x01,
	ADA_Q_NCQ_TRIM_BROKEN	= 0x02,
	ADA_Q_LOG_BROKEN	= 0x04,
	ADA_Q_SMR_DM		= 0x08,
	ADA_Q_NO_TRIM		= 0x10,
	ADA_Q_128KB		= 0x20
} ada_quirks;

#define ADA_Q_BIT_STRING	\
	"\020"			\
	"\0014K"		\
	"\002NCQ_TRIM_BROKEN"	\
	"\003LOG_BROKEN"	\
	"\004SMR_DM"		\
	"\005NO_TRIM"		\
	"\006128KB"

typedef enum {
	ADA_CCB_RAHEAD		= 0x01,
	ADA_CCB_WCACHE		= 0x02,
	ADA_CCB_BUFFER_IO	= 0x03,
	ADA_CCB_DUMP		= 0x05,
	ADA_CCB_TRIM		= 0x06,
	ADA_CCB_LOGDIR		= 0x07,
	ADA_CCB_IDDIR		= 0x08,
	ADA_CCB_SUP_CAP		= 0x09,
	ADA_CCB_ZONE		= 0x0a,
	ADA_CCB_TYPE_MASK	= 0x0F,
} ada_ccb_state;

typedef enum {
	ADA_ZONE_NONE		= 0x00,
	ADA_ZONE_DRIVE_MANAGED	= 0x01,
	ADA_ZONE_HOST_AWARE	= 0x02,
	ADA_ZONE_HOST_MANAGED	= 0x03
} ada_zone_mode;

typedef enum {
	ADA_ZONE_FLAG_RZ_SUP		= 0x0001,
	ADA_ZONE_FLAG_OPEN_SUP		= 0x0002,
	ADA_ZONE_FLAG_CLOSE_SUP		= 0x0004,
	ADA_ZONE_FLAG_FINISH_SUP	= 0x0008,
	ADA_ZONE_FLAG_RWP_SUP		= 0x0010,
	ADA_ZONE_FLAG_SUP_MASK		= (ADA_ZONE_FLAG_RZ_SUP |
					   ADA_ZONE_FLAG_OPEN_SUP |
					   ADA_ZONE_FLAG_CLOSE_SUP |
					   ADA_ZONE_FLAG_FINISH_SUP |
					   ADA_ZONE_FLAG_RWP_SUP),
	ADA_ZONE_FLAG_URSWRZ		= 0x0020,
	ADA_ZONE_FLAG_OPT_SEQ_SET	= 0x0040,
	ADA_ZONE_FLAG_OPT_NONSEQ_SET	= 0x0080,
	ADA_ZONE_FLAG_MAX_SEQ_SET	= 0x0100,
	ADA_ZONE_FLAG_SET_MASK		= (ADA_ZONE_FLAG_OPT_SEQ_SET |
					   ADA_ZONE_FLAG_OPT_NONSEQ_SET |
					   ADA_ZONE_FLAG_MAX_SEQ_SET)
} ada_zone_flags;

static struct ada_zone_desc {
	ada_zone_flags value;
	const char *desc;
} ada_zone_desc_table[] = {
	{ADA_ZONE_FLAG_RZ_SUP, "Report Zones" },
	{ADA_ZONE_FLAG_OPEN_SUP, "Open" },
	{ADA_ZONE_FLAG_CLOSE_SUP, "Close" },
	{ADA_ZONE_FLAG_FINISH_SUP, "Finish" },
	{ADA_ZONE_FLAG_RWP_SUP, "Reset Write Pointer" },
};


/* Offsets into our private area for storing information */
#define ccb_state	ppriv_field0
#define ccb_bp		ppriv_ptr1

typedef enum {
	ADA_DELETE_NONE,
	ADA_DELETE_DISABLE,
	ADA_DELETE_CFA_ERASE,
	ADA_DELETE_DSM_TRIM,
	ADA_DELETE_NCQ_DSM_TRIM,
	ADA_DELETE_MIN = ADA_DELETE_CFA_ERASE,
	ADA_DELETE_MAX = ADA_DELETE_NCQ_DSM_TRIM,
} ada_delete_methods;

static const char *ada_delete_method_names[] =
    { "NONE", "DISABLE", "CFA_ERASE", "DSM_TRIM", "NCQ_DSM_TRIM" };
#if 0
static const char *ada_delete_method_desc[] =
    { "NONE", "DISABLED", "CFA Erase", "DSM Trim", "DSM Trim via NCQ" };
#endif

struct disk_params {
	u_int8_t  heads;
	u_int8_t  secs_per_track;
	u_int32_t cylinders;
	u_int32_t secsize;	/* Number of bytes/logical sector */
	u_int64_t sectors;	/* Total number sectors */
};

#define TRIM_MAX_BLOCKS	8
#define TRIM_MAX_RANGES	(TRIM_MAX_BLOCKS * ATA_DSM_BLK_RANGES)
struct trim_request {
	uint8_t		data[TRIM_MAX_RANGES * ATA_DSM_RANGE_SIZE];
	TAILQ_HEAD(, bio) bps;
};

struct ada_softc {
	struct   cam_iosched_softc *cam_iosched;
	int	 outstanding_cmds;	/* Number of active commands */
	int	 refcount;		/* Active xpt_action() calls */
	ada_state state;
	ada_flags flags;
	ada_zone_mode zone_mode;
	ada_zone_flags zone_flags;
	struct ata_gp_log_dir ata_logdir;
	int valid_logdir_len;
	struct ata_identify_log_pages ata_iddir;
	int valid_iddir_len;
	uint64_t optimal_seq_zones;
	uint64_t optimal_nonseq_zones;
	uint64_t max_seq_zones;
	ada_quirks quirks;
	ada_delete_methods delete_method;
	int	 trim_max_ranges;
	int	 read_ahead;
	int	 write_cache;
	int	 unmappedio;
	int	 rotating;
#ifdef CAM_TEST_FAILURE
	int      force_read_error;
	int      force_write_error;
	int      periodic_read_error;
	int      periodic_read_count;
#endif
	struct ccb_pathinq	cpi;
	struct disk_params	params;
	struct disk		*disk;
	struct task		sysctl_task;
	struct sysctl_ctx_list	sysctl_ctx;
	struct sysctl_oid	*sysctl_tree;
	struct callout		sendordered_c;
	struct trim_request	trim_req;
	uint64_t		trim_count;
	uint64_t		trim_ranges;
	uint64_t		trim_lbas;
#ifdef CAM_IO_STATS
	struct sysctl_ctx_list	sysctl_stats_ctx;
	struct sysctl_oid	*sysctl_stats_tree;
	u_int	timeouts;
	u_int	errors;
	u_int	invalidations;
#endif
#define ADA_ANNOUNCETMP_SZ 80
	char	announce_temp[ADA_ANNOUNCETMP_SZ];
#define ADA_ANNOUNCE_SZ 400
	char	announce_buffer[ADA_ANNOUNCE_SZ];
};

struct ada_quirk_entry {
	struct scsi_inquiry_pattern inq_pat;
	ada_quirks quirks;
};

static struct ada_quirk_entry ada_quirk_table[] =
{
	{
		/* Sandisk X400 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SanDisk?SD8SB8U1T00*", "X4162000*" },
		/*quirks*/ADA_Q_128KB
	},
	{
		/* Hitachi Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Hitachi H??????????E3*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Samsung Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD155UI*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Samsung Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD204UI*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Seagate Barracuda Green Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST????DL*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Seagate Barracuda Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST???DM*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Seagate Barracuda Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST????DM*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Seagate Momentus Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9500423AS*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Seagate Momentus Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9500424AS*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Seagate Momentus Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9640423AS*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Seagate Momentus Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9640424AS*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Seagate Momentus Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750420AS*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Seagate Momentus Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750422AS*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Seagate Momentus Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST9750423AS*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* Seagate Momentus Thin Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST???LT*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* WDC Caviar Red Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????CX*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* WDC Caviar Green Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????RS*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* WDC Caviar Green/Red Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????RX*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* WDC Caviar Red Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????CX*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* WDC Caviar Black Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????AZEX*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* WDC Caviar Black Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD????FZEX*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* WDC Caviar Green Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????RS*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* WDC Caviar Green Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD??????RX*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* WDC Scorpio Black Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD???PKT*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* WDC Scorpio Black Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD?????PKT*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* WDC Scorpio Blue Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD???PVT*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/* WDC Scorpio Blue Advanced Format (4k) drives */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "WDC WD?????PVT*", "*" },
		/*quirks*/ADA_Q_4K
	},
	/* SSDs */
	{
		/*
		 * Corsair Force 2 SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair CSSD-F*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Corsair Force 3 SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Force 3*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Corsair Neutron GTX SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Neutron GTX*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Corsair Force GT & GS SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Corsair Force G*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Crucial M4 SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "M4-CT???M4SSD2*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Crucial M500 SSDs MU07 firmware
		 * NCQ Trim works
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M500*", "MU07" },
		/*quirks*/0
	},
	{
		/*
		 * Crucial M500 SSDs all other firmware
		 * NCQ Trim doesn't work
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M500*", "*" },
		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * Crucial M550 SSDs
		 * NCQ Trim doesn't work, but only on MU01 firmware
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*M550*", "MU01" },
		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * Crucial MX100 SSDs
		 * NCQ Trim doesn't work, but only on MU01 firmware
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Crucial CT*MX100*", "MU01" },
		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * Crucial RealSSD C300 SSDs
		 * 4k optimised
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "C300-CTFDDAC???MAG*",
		"*" }, /*quirks*/ADA_Q_4K
	},
	{
		/*
		 * FCCT M500 SSDs
		 * NCQ Trim doesn't work
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "FCCT*M500*", "*" },
		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * Intel 320 Series SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSA2CW*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Intel 330 Series SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2CT*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Intel 510 Series SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2MH*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Intel 520 Series SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2BW*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Intel S3610 Series SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSC2BX*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Intel X25-M Series SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "INTEL SSDSA2M*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * KingDian S200 60GB P0921B
		 * Trimming crash the SSD
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "KingDian S200 *", "*" },
		/*quirks*/ADA_Q_NO_TRIM
	},
	{
		/*
		 * Kingston E100 Series SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "KINGSTON SE100S3*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Kingston HyperX 3k SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "KINGSTON SH103S3*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Marvell SSDs (entry taken from OpenSolaris)
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "MARVELL SD88SA02*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Micron M500 SSDs firmware MU07
		 * NCQ Trim works?
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M500*", "MU07" },
		/*quirks*/0
	},
	{
		/*
		 * Micron M500 SSDs all other firmware
		 * NCQ Trim doesn't work
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M500*", "*" },
		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * Micron M5[15]0 SSDs
		 * NCQ Trim doesn't work, but only MU01 firmware
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron M5[15]0*", "MU01" },
		/*quirks*/ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * Micron 5100 SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Micron 5100 MTFDDAK*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * OCZ Agility 2 SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-AGILITY2*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * OCZ Agility 3 SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-AGILITY3*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * OCZ Deneva R Series SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "DENRSTE251M45*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * OCZ Vertex 2 SSDs (inc pro series)
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ?VERTEX2*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * OCZ Vertex 3 SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-VERTEX3*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * OCZ Vertex 4 SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "OCZ-VERTEX4*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Samsung 750 SSDs
		 * 4k optimised, NCQ TRIM seems to work
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 750*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Samsung 830 Series SSDs
		 * 4k optimised, NCQ TRIM Broken (normal TRIM is fine)
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG SSD 830 Series*", "*" },
		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * Samsung 840 SSDs
		 * 4k optimised, NCQ TRIM Broken (normal TRIM is fine)
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 840*", "*" },
		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * Samsung 845 SSDs
		 * 4k optimised, NCQ TRIM Broken (normal TRIM is fine)
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 845*", "*" },
		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * Samsung 850 SSDs
		 * 4k optimised, NCQ TRIM broken (normal TRIM fine)
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "Samsung SSD 850*", "*" },
		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * Samsung SM863 Series SSDs (MZ7KM*)
		 * 4k optimised, NCQ believed to be working
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG MZ7KM*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Samsung 843T Series SSDs (MZ7WD*)
		 * Samsung PM851 Series SSDs (MZ7TE*)
		 * Samsung PM853T Series SSDs (MZ7GE*)
		 * 4k optimised, NCQ believed to be broken since these are
		 * appear to be built with the same controllers as the 840/850.
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG MZ7*", "*" },
		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * Same as for SAMSUNG MZ7* but enable the quirks for SSD
		 * starting with MZ7* too
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "MZ7*", "*" },
		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * Samsung PM851 Series SSDs Dell OEM
		 * device model          "SAMSUNG SSD PM851 mSATA 256GB"
		 * 4k optimised, NCQ broken
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG SSD PM851*", "*" },
		/*quirks*/ADA_Q_4K | ADA_Q_NCQ_TRIM_BROKEN
	},
	{
		/*
		 * SuperTalent TeraDrive CT SSDs
		 * 4k optimised & trim only works in 4k requests + 4k aligned
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "FTM??CT25H*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * XceedIOPS SATA SSDs
		 * 4k optimised
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SG9XCS2D*", "*" },
		/*quirks*/ADA_Q_4K
	},
	{
		/*
		 * Samsung drive that doesn't support READ LOG EXT or
		 * READ LOG DMA EXT, despite reporting that it does in
		 * ATA identify data:
		 * SAMSUNG HD200HJ KF100-06
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD200*", "*" },
		/*quirks*/ADA_Q_LOG_BROKEN
	},
	{
		/*
		 * Samsung drive that doesn't support READ LOG EXT or
		 * READ LOG DMA EXT, despite reporting that it does in
		 * ATA identify data:
		 * SAMSUNG HD501LJ CR100-10
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "SAMSUNG HD501*", "*" },
		/*quirks*/ADA_Q_LOG_BROKEN
	},
	{
		/*
		 * Seagate Lamarr 8TB Shingled Magnetic Recording (SMR)
		 * Drive Managed SATA hard drive.  This drive doesn't report
		 * in firmware that it is a drive managed SMR drive.
		 */
		{ T_DIRECT, SIP_MEDIA_FIXED, "*", "ST8000AS000[23]*", "*" },
		/*quirks*/ADA_Q_SMR_DM
	},
	{
		/* Default */
		{
		  T_ANY, SIP_MEDIA_REMOVABLE|SIP_MEDIA_FIXED,
		  /*vendor*/"*", /*product*/"*", /*revision*/"*"
		},
		/*quirks*/0
	},
};

static	disk_strategy_t	adastrategy;
static	dumper_t	adadump;
static	periph_init_t	adainit;
static	void		adadiskgonecb(struct disk *dp);
static	periph_oninv_t	adaoninvalidate;
static	periph_dtor_t	adacleanup;
static	void		adaasync(void *callback_arg, u_int32_t code,
				struct cam_path *path, void *arg);
static	int		adazonemodesysctl(SYSCTL_HANDLER_ARGS);
static	int		adazonesupsysctl(SYSCTL_HANDLER_ARGS);
static	void		adasysctlinit(void *context, int pending);
static	int		adagetattr(struct bio *bp);
static	void		adasetflags(struct ada_softc *softc,
				    struct ccb_getdev *cgd);
static void		adasetgeom(struct ada_softc *softc,
				   struct ccb_getdev *cgd);
static	periph_ctor_t	adaregister;
static	void		ada_dsmtrim(struct ada_softc *softc, struct bio *bp,
				    struct ccb_ataio *ataio);
static	void 		ada_cfaerase(struct ada_softc *softc, struct bio *bp,
				     struct ccb_ataio *ataio);
static	int		ada_zone_bio_to_ata(int disk_zone_cmd);
static	int		ada_zone_cmd(struct cam_periph *periph, union ccb *ccb,
				     struct bio *bp, int *queue_ccb);
static	periph_start_t	adastart;
static	void		adaprobedone(struct cam_periph *periph, union ccb *ccb);
static	void		adazonedone(struct cam_periph *periph, union ccb *ccb);
static	void		adadone(struct cam_periph *periph,
			       union ccb *done_ccb);
static  int		adaerror(union ccb *ccb, u_int32_t cam_flags,
				u_int32_t sense_flags);
static timeout_t	adasendorderedtag;
static void		adashutdown(void *arg, int howto);
static void		adasuspend(void *arg);
static void		adaresume(void *arg);

#ifndef ADA_DEFAULT_TIMEOUT
#define ADA_DEFAULT_TIMEOUT 30	/* Timeout in seconds */
#endif

#ifndef	ADA_DEFAULT_RETRY
#define	ADA_DEFAULT_RETRY	4
#endif

#ifndef	ADA_DEFAULT_SEND_ORDERED
#define	ADA_DEFAULT_SEND_ORDERED	1
#endif

#ifndef	ADA_DEFAULT_SPINDOWN_SHUTDOWN
#define	ADA_DEFAULT_SPINDOWN_SHUTDOWN	1
#endif

#ifndef	ADA_DEFAULT_SPINDOWN_SUSPEND
#define	ADA_DEFAULT_SPINDOWN_SUSPEND	1
#endif

#ifndef	ADA_DEFAULT_READ_AHEAD
#define	ADA_DEFAULT_READ_AHEAD	1
#endif

#ifndef	ADA_DEFAULT_WRITE_CACHE
#define	ADA_DEFAULT_WRITE_CACHE	1
#endif

#define	ADA_RA	(softc->read_ahead >= 0 ? \
		 softc->read_ahead : ada_read_ahead)
#define	ADA_WC	(softc->write_cache >= 0 ? \
		 softc->write_cache : ada_write_cache)

/*
 * Most platforms map firmware geometry to actual, but some don't.  If
 * not overridden, default to nothing.
 */
#ifndef ata_disk_firmware_geom_adjust
#define	ata_disk_firmware_geom_adjust(disk)
#endif

static int ada_retry_count = ADA_DEFAULT_RETRY;
static int ada_default_timeout = ADA_DEFAULT_TIMEOUT;
static int ada_send_ordered = ADA_DEFAULT_SEND_ORDERED;
static int ada_spindown_shutdown = ADA_DEFAULT_SPINDOWN_SHUTDOWN;
static int ada_spindown_suspend = ADA_DEFAULT_SPINDOWN_SUSPEND;
static int ada_read_ahead = ADA_DEFAULT_READ_AHEAD;
static int ada_write_cache = ADA_DEFAULT_WRITE_CACHE;

static SYSCTL_NODE(_kern_cam, OID_AUTO, ada, CTLFLAG_RD, 0,
            "CAM Direct Access Disk driver");
SYSCTL_INT(_kern_cam_ada, OID_AUTO, retry_count, CTLFLAG_RWTUN,
           &ada_retry_count, 0, "Normal I/O retry count");
SYSCTL_INT(_kern_cam_ada, OID_AUTO, default_timeout, CTLFLAG_RWTUN,
           &ada_default_timeout, 0, "Normal I/O timeout (in seconds)");
SYSCTL_INT(_kern_cam_ada, OID_AUTO, send_ordered, CTLFLAG_RWTUN,
           &ada_send_ordered, 0, "Send Ordered Tags");
SYSCTL_INT(_kern_cam_ada, OID_AUTO, spindown_shutdown, CTLFLAG_RWTUN,
           &ada_spindown_shutdown, 0, "Spin down upon shutdown");
SYSCTL_INT(_kern_cam_ada, OID_AUTO, spindown_suspend, CTLFLAG_RWTUN,
           &ada_spindown_suspend, 0, "Spin down upon suspend");
SYSCTL_INT(_kern_cam_ada, OID_AUTO, read_ahead, CTLFLAG_RWTUN,
           &ada_read_ahead, 0, "Enable disk read-ahead");
SYSCTL_INT(_kern_cam_ada, OID_AUTO, write_cache, CTLFLAG_RWTUN,
           &ada_write_cache, 0, "Enable disk write cache");

/*
 * ADA_ORDEREDTAG_INTERVAL determines how often, relative
 * to the default timeout, we check to see whether an ordered
 * tagged transaction is appropriate to prevent simple tag
 * starvation.  Since we'd like to ensure that there is at least
 * 1/2 of the timeout length left for a starved transaction to
 * complete after we've sent an ordered tag, we must poll at least
 * four times in every timeout period.  This takes care of the worst
 * case where a starved transaction starts during an interval that
 * meets the requirement "don't send an ordered tag" test so it takes
 * us two intervals to determine that a tag must be sent.
 */
#ifndef ADA_ORDEREDTAG_INTERVAL
#define ADA_ORDEREDTAG_INTERVAL 4
#endif

static struct periph_driver adadriver =
{
	adainit, "ada",
	TAILQ_HEAD_INITIALIZER(adadriver.units), /* generation */ 0
};

static int adadeletemethodsysctl(SYSCTL_HANDLER_ARGS);

PERIPHDRIVER_DECLARE(ada, adadriver);

static MALLOC_DEFINE(M_ATADA, "ata_da", "ata_da buffers");

static int
adaopen(struct disk *dp)
{
	struct cam_periph *periph;
	struct ada_softc *softc;
	int error;

	periph = (struct cam_periph *)dp->d_drv1;
	if (cam_periph_acquire(periph) != 0) {
		return(ENXIO);
	}

	cam_periph_lock(periph);
	if ((error = cam_periph_hold(periph, PRIBIO|PCATCH)) != 0) {
		cam_periph_unlock(periph);
		cam_periph_release(periph);
		return (error);
	}

	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
	    ("adaopen\n"));

	softc = (struct ada_softc *)periph->softc;
	softc->flags |= ADA_FLAG_OPEN;

	cam_periph_unhold(periph);
	cam_periph_unlock(periph);
	return (0);
}

static int
adaclose(struct disk *dp)
{
	struct	cam_periph *periph;
	struct	ada_softc *softc;
	union ccb *ccb;
	int error;

	periph = (struct cam_periph *)dp->d_drv1;
	softc = (struct ada_softc *)periph->softc;
	cam_periph_lock(periph);

	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE | CAM_DEBUG_PERIPH,
	    ("adaclose\n"));

	/* We only sync the cache if the drive is capable of it. */
	if ((softc->flags & ADA_FLAG_DIRTY) != 0 &&
	    (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) != 0 &&
	    (periph->flags & CAM_PERIPH_INVALID) == 0 &&
	    cam_periph_hold(periph, PRIBIO) == 0) {

		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
		cam_fill_ataio(&ccb->ataio,
				    1,
				    NULL,
				    CAM_DIR_NONE,
				    0,
				    NULL,
				    0,
				    ada_default_timeout*1000);

		if (softc->flags & ADA_FLAG_CAN_48BIT)
			ata_48bit_cmd(&ccb->ataio, ATA_FLUSHCACHE48, 0, 0, 0);
		else
			ata_28bit_cmd(&ccb->ataio, ATA_FLUSHCACHE, 0, 0, 0);
		error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
		    /*sense_flags*/0, softc->disk->d_devstat);

		if (error != 0)
			xpt_print(periph->path, "Synchronize cache failed\n");
		softc->flags &= ~ADA_FLAG_DIRTY;
		xpt_release_ccb(ccb);
		cam_periph_unhold(periph);
	}

	softc->flags &= ~ADA_FLAG_OPEN;

	while (softc->refcount != 0)
		cam_periph_sleep(periph, &softc->refcount, PRIBIO, "adaclose", 1);
	cam_periph_unlock(periph);
	cam_periph_release(periph);
	return (0);
}

static void
adaschedule(struct cam_periph *periph)
{
	struct ada_softc *softc = (struct ada_softc *)periph->softc;

	if (softc->state != ADA_STATE_NORMAL)
		return;

	cam_iosched_schedule(softc->cam_iosched, periph);
}

/*
 * 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
adastrategy(struct bio *bp)
{
	struct cam_periph *periph;
	struct ada_softc *softc;

	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
	softc = (struct ada_softc *)periph->softc;

	cam_periph_lock(periph);

	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("adastrategy(%p)\n", bp));

	/*
	 * If the device has been made invalid, error out
	 */
	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
		cam_periph_unlock(periph);
		biofinish(bp, NULL, ENXIO);
		return;
	}

	/*
	 * Zone commands must be ordered, because they can depend on the
	 * effects of previously issued commands, and they may affect
	 * commands after them.
	 */
	if (bp->bio_cmd == BIO_ZONE)
		bp->bio_flags |= BIO_ORDERED;

	/*
	 * Place it in the queue of disk activities for this disk
	 */
	cam_iosched_queue_work(softc->cam_iosched, bp);

	/*
	 * Schedule ourselves for performing the work.
	 */
	adaschedule(periph);
	cam_periph_unlock(periph);

	return;
}

static int
adadump(void *arg, void *virtual, vm_offset_t physical, off_t offset, size_t length)
{
	struct	    cam_periph *periph;
	struct	    ada_softc *softc;
	u_int	    secsize;
	struct	    ccb_ataio ataio;
	struct	    disk *dp;
	uint64_t    lba;
	uint16_t    count;
	int	    error = 0;

	dp = arg;
	periph = dp->d_drv1;
	softc = (struct ada_softc *)periph->softc;
	secsize = softc->params.secsize;
	lba = offset / secsize;
	count = length / secsize;
	if ((periph->flags & CAM_PERIPH_INVALID) != 0)
		return (ENXIO);

	memset(&ataio, 0, sizeof(ataio));
	if (length > 0) {
		xpt_setup_ccb(&ataio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
		ataio.ccb_h.ccb_state = ADA_CCB_DUMP;
		cam_fill_ataio(&ataio,
		    0,
		    NULL,
		    CAM_DIR_OUT,
		    0,
		    (u_int8_t *) virtual,
		    length,
		    ada_default_timeout*1000);
		if ((softc->flags & ADA_FLAG_CAN_48BIT) &&
		    (lba + count >= ATA_MAX_28BIT_LBA ||
		    count >= 256)) {
			ata_48bit_cmd(&ataio, ATA_WRITE_DMA48,
			    0, lba, count);
		} else {
			ata_28bit_cmd(&ataio, ATA_WRITE_DMA,
			    0, lba, count);
		}
		error = cam_periph_runccb((union ccb *)&ataio, adaerror,
		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
		if (error != 0)
			printf("Aborting dump due to I/O error.\n");

		return (error);
	}

	if (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) {
		xpt_setup_ccb(&ataio.ccb_h, periph->path, CAM_PRIORITY_NORMAL);

		/*
		 * Tell the drive to flush its internal cache. if we
		 * can't flush in 5s we have big problems. No need to
		 * wait the default 60s to detect problems.
		 */
		ataio.ccb_h.ccb_state = ADA_CCB_DUMP;
		cam_fill_ataio(&ataio,
				    0,
				    NULL,
				    CAM_DIR_NONE,
				    0,
				    NULL,
				    0,
				    5*1000);

		if (softc->flags & ADA_FLAG_CAN_48BIT)
			ata_48bit_cmd(&ataio, ATA_FLUSHCACHE48, 0, 0, 0);
		else
			ata_28bit_cmd(&ataio, ATA_FLUSHCACHE, 0, 0, 0);
		error = cam_periph_runccb((union ccb *)&ataio, adaerror,
		    0, SF_NO_RECOVERY | SF_NO_RETRY, NULL);
		if (error != 0)
			xpt_print(periph->path, "Synchronize cache failed\n");
	}
	return (error);
}

static void
adainit(void)
{
	cam_status status;

	/*
	 * Install a global async callback.  This callback will
	 * receive async callbacks like "new device found".
	 */
	status = xpt_register_async(AC_FOUND_DEVICE, adaasync, NULL, NULL);

	if (status != CAM_REQ_CMP) {
		printf("ada: Failed to attach master async callback "
		       "due to status 0x%x!\n", status);
	} else if (ada_send_ordered) {

		/* Register our event handlers */
		if ((EVENTHANDLER_REGISTER(power_suspend, adasuspend,
					   NULL, EVENTHANDLER_PRI_LAST)) == NULL)
		    printf("adainit: power event registration failed!\n");
		if ((EVENTHANDLER_REGISTER(power_resume, adaresume,
					   NULL, EVENTHANDLER_PRI_LAST)) == NULL)
		    printf("adainit: power event registration failed!\n");
		if ((EVENTHANDLER_REGISTER(shutdown_post_sync, adashutdown,
					   NULL, SHUTDOWN_PRI_DEFAULT)) == NULL)
		    printf("adainit: shutdown event registration failed!\n");
	}
}

/*
 * Callback from GEOM, called when it has finished cleaning up its
 * resources.
 */
static void
adadiskgonecb(struct disk *dp)
{
	struct cam_periph *periph;

	periph = (struct cam_periph *)dp->d_drv1;

	cam_periph_release(periph);
}

static void
adaoninvalidate(struct cam_periph *periph)
{
	struct ada_softc *softc;

	softc = (struct ada_softc *)periph->softc;

	/*
	 * De-register any async callbacks.
	 */
	xpt_register_async(0, adaasync, periph, periph->path);
#ifdef CAM_IO_STATS
	softc->invalidations++;
#endif

	/*
	 * Return all queued I/O with ENXIO.
	 * XXX Handle any transactions queued to the card
	 *     with XPT_ABORT_CCB.
	 */
	cam_iosched_flush(softc->cam_iosched, NULL, ENXIO);

	disk_gone(softc->disk);
}

static void
adacleanup(struct cam_periph *periph)
{
	struct ada_softc *softc;

	softc = (struct ada_softc *)periph->softc;

	cam_periph_unlock(periph);

	cam_iosched_fini(softc->cam_iosched);

	/*
	 * If we can't free the sysctl tree, oh well...
	 */
	if ((softc->flags & ADA_FLAG_SCTX_INIT) != 0) {
#ifdef CAM_IO_STATS
		if (sysctl_ctx_free(&softc->sysctl_stats_ctx) != 0)
			xpt_print(periph->path,
			    "can't remove sysctl stats context\n");
#endif
		if (sysctl_ctx_free(&softc->sysctl_ctx) != 0)
			xpt_print(periph->path,
			    "can't remove sysctl context\n");
	}

	disk_destroy(softc->disk);
	callout_drain(&softc->sendordered_c);
	free(softc, M_DEVBUF);
	cam_periph_lock(periph);
}

static void
adasetdeletemethod(struct ada_softc *softc)
{

	if (softc->flags & ADA_FLAG_CAN_NCQ_TRIM)
		softc->delete_method = ADA_DELETE_NCQ_DSM_TRIM;
	else if (softc->flags & ADA_FLAG_CAN_TRIM)
		softc->delete_method = ADA_DELETE_DSM_TRIM;
	else if ((softc->flags & ADA_FLAG_CAN_CFA) && !(softc->flags & ADA_FLAG_CAN_48BIT))
		softc->delete_method = ADA_DELETE_CFA_ERASE;
	else
		softc->delete_method = ADA_DELETE_NONE;
}

static void
adaasync(void *callback_arg, u_int32_t code,
	struct cam_path *path, void *arg)
{
	struct ccb_getdev cgd;
	struct cam_periph *periph;
	struct ada_softc *softc;

	periph = (struct cam_periph *)callback_arg;
	switch (code) {
	case AC_FOUND_DEVICE:
	{
		struct ccb_getdev *cgd;
		cam_status status;

		cgd = (struct ccb_getdev *)arg;
		if (cgd == NULL)
			break;

		if (cgd->protocol != PROTO_ATA)
			break;

		/*
		 * Allocate a peripheral instance for
		 * this device and start the probe
		 * process.
		 */
		status = cam_periph_alloc(adaregister, adaoninvalidate,
					  adacleanup, adastart,
					  "ada", CAM_PERIPH_BIO,
					  path, adaasync,
					  AC_FOUND_DEVICE, cgd);

		if (status != CAM_REQ_CMP
		 && status != CAM_REQ_INPROG)
			printf("adaasync: Unable to attach to new device "
				"due to status 0x%x\n", status);
		break;
	}
	case AC_GETDEV_CHANGED:
	{
		softc = (struct ada_softc *)periph->softc;
		xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
		xpt_action((union ccb *)&cgd);

		/*
		 * Update our information based on the new Identify data.
		 */
		adasetflags(softc, &cgd);
		adasetgeom(softc, &cgd);
		disk_resize(softc->disk, M_NOWAIT);

		cam_periph_async(periph, code, path, arg);
		break;
	}
	case AC_ADVINFO_CHANGED:
	{
		uintptr_t buftype;

		buftype = (uintptr_t)arg;
		if (buftype == CDAI_TYPE_PHYS_PATH) {
			struct ada_softc *softc;

			softc = periph->softc;
			disk_attr_changed(softc->disk, "GEOM::physpath",
					  M_NOWAIT);
		}
		break;
	}
	case AC_SENT_BDR:
	case AC_BUS_RESET:
	{
		softc = (struct ada_softc *)periph->softc;
		cam_periph_async(periph, code, path, arg);
		if (softc->state != ADA_STATE_NORMAL)
			break;
		xpt_setup_ccb(&cgd.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
		cgd.ccb_h.func_code = XPT_GDEV_TYPE;
		xpt_action((union ccb *)&cgd);
		if (ADA_RA >= 0 && softc->flags & ADA_FLAG_CAN_RAHEAD)
			softc->state = ADA_STATE_RAHEAD;
		else if (ADA_WC >= 0 && softc->flags & ADA_FLAG_CAN_WCACHE)
			softc->state = ADA_STATE_WCACHE;
		else if ((softc->flags & ADA_FLAG_CAN_LOG)
		      && (softc->zone_mode != ADA_ZONE_NONE))
			softc->state = ADA_STATE_LOGDIR;
		else
		    break;
		if (cam_periph_acquire(periph) != 0)
			softc->state = ADA_STATE_NORMAL;
		else
			xpt_schedule(periph, CAM_PRIORITY_DEV);
	}
	default:
		cam_periph_async(periph, code, path, arg);
		break;
	}
}

static int
adazonemodesysctl(SYSCTL_HANDLER_ARGS)
{
	char tmpbuf[40];
	struct ada_softc *softc;
	int error;

	softc = (struct ada_softc *)arg1;

	switch (softc->zone_mode) {
	case ADA_ZONE_DRIVE_MANAGED:
		snprintf(tmpbuf, sizeof(tmpbuf), "Drive Managed");
		break;
	case ADA_ZONE_HOST_AWARE:
		snprintf(tmpbuf, sizeof(tmpbuf), "Host Aware");
		break;
	case ADA_ZONE_HOST_MANAGED:
		snprintf(tmpbuf, sizeof(tmpbuf), "Host Managed");
		break;
	case ADA_ZONE_NONE:
	default:
		snprintf(tmpbuf, sizeof(tmpbuf), "Not Zoned");
		break;
	}

	error = sysctl_handle_string(oidp, tmpbuf, sizeof(tmpbuf), req);

	return (error);
}

static int
adazonesupsysctl(SYSCTL_HANDLER_ARGS)
{
	char tmpbuf[180];
	struct ada_softc *softc;
	struct sbuf sb;
	int error, first;
	unsigned int i;

	softc = (struct ada_softc *)arg1;

	error = 0;
	first = 1;
	sbuf_new(&sb, tmpbuf, sizeof(tmpbuf), 0);

	for (i = 0; i < sizeof(ada_zone_desc_table) /
	     sizeof(ada_zone_desc_table[0]); i++) {
		if (softc->zone_flags & ada_zone_desc_table[i].value) {
			if (first == 0)
				sbuf_printf(&sb, ", ");
			else
				first = 0;
			sbuf_cat(&sb, ada_zone_desc_table[i].desc);
		}
	}

	if (first == 1)
		sbuf_printf(&sb, "None");

	sbuf_finish(&sb);

	error = sysctl_handle_string(oidp, sbuf_data(&sb), sbuf_len(&sb), req);

	return (error);
}


static void
adasysctlinit(void *context, int pending)
{
	struct cam_periph *periph;
	struct ada_softc *softc;
	char tmpstr[32], tmpstr2[16];

	periph = (struct cam_periph *)context;

	/* periph was held for us when this task was enqueued */
	if ((periph->flags & CAM_PERIPH_INVALID) != 0) {
		cam_periph_release(periph);
		return;
	}

	softc = (struct ada_softc *)periph->softc;
	snprintf(tmpstr, sizeof(tmpstr), "CAM ADA unit %d",periph->unit_number);
	snprintf(tmpstr2, sizeof(tmpstr2), "%d", periph->unit_number);

	sysctl_ctx_init(&softc->sysctl_ctx);
	softc->flags |= ADA_FLAG_SCTX_INIT;
	softc->sysctl_tree = SYSCTL_ADD_NODE_WITH_LABEL(&softc->sysctl_ctx,
		SYSCTL_STATIC_CHILDREN(_kern_cam_ada), OID_AUTO, tmpstr2,
		CTLFLAG_RD, 0, tmpstr, "device_index");
	if (softc->sysctl_tree == NULL) {
		printf("adasysctlinit: unable to allocate sysctl tree\n");
		cam_periph_release(periph);
		return;
	}

	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
		OID_AUTO, "delete_method", CTLTYPE_STRING | CTLFLAG_RW,
		softc, 0, adadeletemethodsysctl, "A",
		"BIO_DELETE execution method");
	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
		"trim_count", CTLFLAG_RD, &softc->trim_count,
		"Total number of dsm commands sent");
	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
		"trim_ranges", CTLFLAG_RD, &softc->trim_ranges,
		"Total number of ranges in dsm commands");
	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
		"trim_lbas", CTLFLAG_RD, &softc->trim_lbas,
		"Total lbas in the dsm commands sent");
	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
		OID_AUTO, "read_ahead", CTLFLAG_RW | CTLFLAG_MPSAFE,
		&softc->read_ahead, 0, "Enable disk read ahead.");
	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
		OID_AUTO, "write_cache", CTLFLAG_RW | CTLFLAG_MPSAFE,
		&softc->write_cache, 0, "Enable disk write cache.");
	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
		OID_AUTO, "unmapped_io", CTLFLAG_RD | CTLFLAG_MPSAFE,
		&softc->unmappedio, 0, "Unmapped I/O leaf");
	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
		OID_AUTO, "rotating", CTLFLAG_RD | CTLFLAG_MPSAFE,
		&softc->rotating, 0, "Rotating media");
	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
		OID_AUTO, "zone_mode", CTLTYPE_STRING | CTLFLAG_RD,
		softc, 0, adazonemodesysctl, "A",
		"Zone Mode");
	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
		OID_AUTO, "zone_support", CTLTYPE_STRING | CTLFLAG_RD,
		softc, 0, adazonesupsysctl, "A",
		"Zone Support");
	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
		"optimal_seq_zones", CTLFLAG_RD, &softc->optimal_seq_zones,
		"Optimal Number of Open Sequential Write Preferred Zones");
	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
		"optimal_nonseq_zones", CTLFLAG_RD,
		&softc->optimal_nonseq_zones,
		"Optimal Number of Non-Sequentially Written Sequential Write "
		"Preferred Zones");
	SYSCTL_ADD_UQUAD(&softc->sysctl_ctx,
		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO,
		"max_seq_zones", CTLFLAG_RD, &softc->max_seq_zones,
		"Maximum Number of Open Sequential Write Required Zones");

#ifdef CAM_TEST_FAILURE
	/*
	 * Add a 'door bell' sysctl which allows one to set it from userland
	 * and cause something bad to happen.  For the moment, we only allow
	 * whacking the next read or write.
	 */
	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
		OID_AUTO, "force_read_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
		&softc->force_read_error, 0,
		"Force a read error for the next N reads.");
	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
		OID_AUTO, "force_write_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
		&softc->force_write_error, 0,
		"Force a write error for the next N writes.");
	SYSCTL_ADD_INT(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
		OID_AUTO, "periodic_read_error", CTLFLAG_RW | CTLFLAG_MPSAFE,
		&softc->periodic_read_error, 0,
		"Force a read error every N reads (don't set too low).");
	SYSCTL_ADD_PROC(&softc->sysctl_ctx, SYSCTL_CHILDREN(softc->sysctl_tree),
		OID_AUTO, "invalidate", CTLTYPE_U64 | CTLFLAG_RW | CTLFLAG_MPSAFE,
		periph, 0, cam_periph_invalidate_sysctl, "I",
		"Write 1 to invalidate the drive immediately");
#endif

#ifdef CAM_IO_STATS
	softc->sysctl_stats_tree = SYSCTL_ADD_NODE(&softc->sysctl_stats_ctx,
		SYSCTL_CHILDREN(softc->sysctl_tree), OID_AUTO, "stats",
		CTLFLAG_RD, 0, "Statistics");
	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
		OID_AUTO, "timeouts", CTLFLAG_RD | CTLFLAG_MPSAFE,
		&softc->timeouts, 0,
		"Device timeouts reported by the SIM");
	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
		OID_AUTO, "errors", CTLFLAG_RD | CTLFLAG_MPSAFE,
		&softc->errors, 0,
		"Transport errors reported by the SIM.");
	SYSCTL_ADD_INT(&softc->sysctl_stats_ctx,
		SYSCTL_CHILDREN(softc->sysctl_stats_tree),
		OID_AUTO, "pack_invalidations", CTLFLAG_RD | CTLFLAG_MPSAFE,
		&softc->invalidations, 0,
		"Device pack invalidations.");
#endif

	cam_iosched_sysctl_init(softc->cam_iosched, &softc->sysctl_ctx,
	    softc->sysctl_tree);

	cam_periph_release(periph);
}

static int
adagetattr(struct bio *bp)
{
	int ret;
	struct cam_periph *periph;

	periph = (struct cam_periph *)bp->bio_disk->d_drv1;
	cam_periph_lock(periph);
	ret = xpt_getattr(bp->bio_data, bp->bio_length, bp->bio_attribute,
	    periph->path);
	cam_periph_unlock(periph);
	if (ret == 0)
		bp->bio_completed = bp->bio_length;
	return ret;
}

static int
adadeletemethodsysctl(SYSCTL_HANDLER_ARGS)
{
	char buf[16];
	const char *p;
	struct ada_softc *softc;
	int i, error, value, methods;

	softc = (struct ada_softc *)arg1;

	value = softc->delete_method;
	if (value < 0 || value > ADA_DELETE_MAX)
		p = "UNKNOWN";
	else
		p = ada_delete_method_names[value];
	strncpy(buf, p, sizeof(buf));
	error = sysctl_handle_string(oidp, buf, sizeof(buf), req);
	if (error != 0 || req->newptr == NULL)
		return (error);
	methods = 1 << ADA_DELETE_DISABLE;
	if ((softc->flags & ADA_FLAG_CAN_CFA) &&
	    !(softc->flags & ADA_FLAG_CAN_48BIT))
		methods |= 1 << ADA_DELETE_CFA_ERASE;
	if (softc->flags & ADA_FLAG_CAN_TRIM)
		methods |= 1 << ADA_DELETE_DSM_TRIM;
	if (softc->flags & ADA_FLAG_CAN_NCQ_TRIM)
		methods |= 1 << ADA_DELETE_NCQ_DSM_TRIM;
	for (i = 0; i <= ADA_DELETE_MAX; i++) {
		if (!(methods & (1 << i)) ||
		    strcmp(buf, ada_delete_method_names[i]) != 0)
			continue;
		softc->delete_method = i;
		return (0);
	}
	return (EINVAL);
}

static void
adasetflags(struct ada_softc *softc, struct ccb_getdev *cgd)
{
	if ((cgd->ident_data.capabilities1 & ATA_SUPPORT_DMA) &&
	    (cgd->inq_flags & SID_DMA))
		softc->flags |= ADA_FLAG_CAN_DMA;
	else
		softc->flags &= ~ADA_FLAG_CAN_DMA;

	if (cgd->ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) {
		softc->flags |= ADA_FLAG_CAN_48BIT;
		if (cgd->inq_flags & SID_DMA48)
			softc->flags |= ADA_FLAG_CAN_DMA48;
		else
			softc->flags &= ~ADA_FLAG_CAN_DMA48;
	} else
		softc->flags &= ~(ADA_FLAG_CAN_48BIT | ADA_FLAG_CAN_DMA48);

	if (cgd->ident_data.support.command2 & ATA_SUPPORT_FLUSHCACHE)
		softc->flags |= ADA_FLAG_CAN_FLUSHCACHE;
	else
		softc->flags &= ~ADA_FLAG_CAN_FLUSHCACHE;

	if (cgd->ident_data.support.command1 & ATA_SUPPORT_POWERMGT)
		softc->flags |= ADA_FLAG_CAN_POWERMGT;
	else
		softc->flags &= ~ADA_FLAG_CAN_POWERMGT;

	if ((cgd->ident_data.satacapabilities & ATA_SUPPORT_NCQ) &&
	    (cgd->inq_flags & SID_DMA) && (cgd->inq_flags & SID_CmdQue))
		softc->flags |= ADA_FLAG_CAN_NCQ;
	else
		softc->flags &= ~ADA_FLAG_CAN_NCQ;

	if ((cgd->ident_data.support_dsm & ATA_SUPPORT_DSM_TRIM) &&
	    (cgd->inq_flags & SID_DMA) &&
	    (softc->quirks & ADA_Q_NO_TRIM) == 0) {
		softc->flags |= ADA_FLAG_CAN_TRIM;
		softc->trim_max_ranges = TRIM_MAX_RANGES;
		if (cgd->ident_data.max_dsm_blocks != 0) {
			softc->trim_max_ranges =
			    min(cgd->ident_data.max_dsm_blocks *
				ATA_DSM_BLK_RANGES, softc->trim_max_ranges);
		}
		/*
		 * If we can do RCVSND_FPDMA_QUEUED commands, we may be able
		 * to do NCQ trims, if we support trims at all. We also need
		 * support from the SIM to do things properly. Perhaps we
		 * should look at log 13 dword 0 bit 0 and dword 1 bit 0 are
		 * set too...
		 */
		if ((softc->quirks & ADA_Q_NCQ_TRIM_BROKEN) == 0 &&
		    (softc->flags & ADA_FLAG_PIM_ATA_EXT) != 0 &&
		    (cgd->ident_data.satacapabilities2 &
		     ATA_SUPPORT_RCVSND_FPDMA_QUEUED) != 0 &&
		    (softc->flags & ADA_FLAG_CAN_TRIM) != 0)
			softc->flags |= ADA_FLAG_CAN_NCQ_TRIM;
		else
			softc->flags &= ~ADA_FLAG_CAN_NCQ_TRIM;
	} else
		softc->flags &= ~(ADA_FLAG_CAN_TRIM | ADA_FLAG_CAN_NCQ_TRIM);

	if (cgd->ident_data.support.command2 & ATA_SUPPORT_CFA)
		softc->flags |= ADA_FLAG_CAN_CFA;
	else
		softc->flags &= ~ADA_FLAG_CAN_CFA;

	/*
	 * Now that we've set the appropriate flags, setup the delete
	 * method.
	 */
	adasetdeletemethod(softc);

	if ((cgd->ident_data.support.extension & ATA_SUPPORT_GENLOG)
	 && ((softc->quirks & ADA_Q_LOG_BROKEN) == 0))
		softc->flags |= ADA_FLAG_CAN_LOG;
	else
		softc->flags &= ~ADA_FLAG_CAN_LOG;

	if ((cgd->ident_data.support3 & ATA_SUPPORT_ZONE_MASK) ==
	     ATA_SUPPORT_ZONE_HOST_AWARE)
		softc->zone_mode = ADA_ZONE_HOST_AWARE;
	else if (((cgd->ident_data.support3 & ATA_SUPPORT_ZONE_MASK) ==
		   ATA_SUPPORT_ZONE_DEV_MANAGED)
	      || (softc->quirks & ADA_Q_SMR_DM))
		softc->zone_mode = ADA_ZONE_DRIVE_MANAGED;
	else
		softc->zone_mode = ADA_ZONE_NONE;

	if (cgd->ident_data.support.command1 & ATA_SUPPORT_LOOKAHEAD)
		softc->flags |= ADA_FLAG_CAN_RAHEAD;
	else
		softc->flags &= ~ADA_FLAG_CAN_RAHEAD;

	if (cgd->ident_data.support.command1 & ATA_SUPPORT_WRITECACHE)
		softc->flags |= ADA_FLAG_CAN_WCACHE;
	else
		softc->flags &= ~ADA_FLAG_CAN_WCACHE;
}

static cam_status
adaregister(struct cam_periph *periph, void *arg)
{
	struct ada_softc *softc;
	struct ccb_getdev *cgd;
	struct disk_params *dp;
	struct sbuf sb;
	char   *announce_buf;
	caddr_t match;
	int quirks;

	cgd = (struct ccb_getdev *)arg;
	if (cgd == NULL) {
		printf("adaregister: no getdev CCB, can't register device\n");
		return(CAM_REQ_CMP_ERR);
	}

	softc = (struct ada_softc *)malloc(sizeof(*softc), M_DEVBUF,
	    M_NOWAIT|M_ZERO);

	if (softc == NULL) {
		printf("adaregister: Unable to probe new device. "
		    "Unable to allocate softc\n");
		return(CAM_REQ_CMP_ERR);
	}

	announce_buf = softc->announce_temp;
	bzero(announce_buf, ADA_ANNOUNCETMP_SZ);

	if (cam_iosched_init(&softc->cam_iosched, periph) != 0) {
		printf("adaregister: Unable to probe new device. "
		       "Unable to allocate iosched memory\n");
		free(softc, M_DEVBUF);
		return(CAM_REQ_CMP_ERR);
	}

	periph->softc = softc;
	xpt_path_inq(&softc->cpi, periph->path);

	/*
	 * See if this device has any quirks.
	 */
	match = cam_quirkmatch((caddr_t)&cgd->ident_data,
			       (caddr_t)ada_quirk_table,
			       nitems(ada_quirk_table),
			       sizeof(*ada_quirk_table), ata_identify_match);
	if (match != NULL)
		softc->quirks = ((struct ada_quirk_entry *)match)->quirks;
	else
		softc->quirks = ADA_Q_NONE;

	TASK_INIT(&softc->sysctl_task, 0, adasysctlinit, periph);

	/*
	 * Register this media as a disk
	 */
	(void)cam_periph_hold(periph, PRIBIO);
	cam_periph_unlock(periph);
	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
	    "kern.cam.ada.%d.quirks", periph->unit_number);
	quirks = softc->quirks;
	TUNABLE_INT_FETCH(announce_buf, &quirks);
	softc->quirks = quirks;
	softc->read_ahead = -1;
	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
	    "kern.cam.ada.%d.read_ahead", periph->unit_number);
	TUNABLE_INT_FETCH(announce_buf, &softc->read_ahead);
	softc->write_cache = -1;
	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
	    "kern.cam.ada.%d.write_cache", periph->unit_number);
	TUNABLE_INT_FETCH(announce_buf, &softc->write_cache);

	/*
	 * Set support flags based on the Identify data and quirks.
	 */
	adasetflags(softc, cgd);
	if (softc->cpi.hba_misc & PIM_ATA_EXT)
		softc->flags |= ADA_FLAG_PIM_ATA_EXT;

	/* Disable queue sorting for non-rotational media by default. */
	if (cgd->ident_data.media_rotation_rate == ATA_RATE_NON_ROTATING) {
		softc->rotating = 0;
	} else {
		softc->rotating = 1;
	}
	cam_iosched_set_sort_queue(softc->cam_iosched,  softc->rotating ? -1 : 0);
	softc->disk = disk_alloc();
	adasetgeom(softc, cgd);
	softc->disk->d_devstat = devstat_new_entry(periph->periph_name,
			  periph->unit_number, softc->params.secsize,
			  DEVSTAT_ALL_SUPPORTED,
			  DEVSTAT_TYPE_DIRECT |
			  XPORT_DEVSTAT_TYPE(softc->cpi.transport),
			  DEVSTAT_PRIORITY_DISK);
	softc->disk->d_open = adaopen;
	softc->disk->d_close = adaclose;
	softc->disk->d_strategy = adastrategy;
	softc->disk->d_getattr = adagetattr;
	softc->disk->d_dump = adadump;
	softc->disk->d_gone = adadiskgonecb;
	softc->disk->d_name = "ada";
	softc->disk->d_drv1 = periph;
	softc->disk->d_unit = periph->unit_number;

	/*
	 * Acquire a reference to the periph before we register with GEOM.
	 * We'll release this reference once GEOM calls us back (via
	 * adadiskgonecb()) telling us that our provider has been freed.
	 */
	if (cam_periph_acquire(periph) != 0) {
		xpt_print(periph->path, "%s: lost periph during "
			  "registration!\n", __func__);
		cam_periph_lock(periph);
		return (CAM_REQ_CMP_ERR);
	}
	disk_create(softc->disk, DISK_VERSION);
	cam_periph_lock(periph);

	dp = &softc->params;
	snprintf(announce_buf, ADA_ANNOUNCETMP_SZ,
	    "%juMB (%ju %u byte sectors)",
	    ((uintmax_t)dp->secsize * dp->sectors) / (1024 * 1024),
	    (uintmax_t)dp->sectors, dp->secsize);

	sbuf_new(&sb, softc->announce_buffer, ADA_ANNOUNCE_SZ, SBUF_FIXEDLEN);
	xpt_announce_periph_sbuf(periph, &sb, announce_buf);
	xpt_announce_quirks_sbuf(periph, &sb, softc->quirks, ADA_Q_BIT_STRING);
	sbuf_finish(&sb);
	sbuf_putbuf(&sb);

	/*
	 * Create our sysctl variables, now that we know
	 * we have successfully attached.
	 */
	if (cam_periph_acquire(periph) == 0)
		taskqueue_enqueue(taskqueue_thread, &softc->sysctl_task);

	/*
	 * Add async callbacks for bus reset and
	 * bus device reset calls.  I don't bother
	 * checking if this fails as, in most cases,
	 * the system will function just fine without
	 * them and the only alternative would be to
	 * not attach the device on failure.
	 */
	xpt_register_async(AC_SENT_BDR | AC_BUS_RESET | AC_LOST_DEVICE |
	    AC_GETDEV_CHANGED | AC_ADVINFO_CHANGED,
	    adaasync, periph, periph->path);

	/*
	 * Schedule a periodic event to occasionally send an
	 * ordered tag to a device.
	 */
	callout_init_mtx(&softc->sendordered_c, cam_periph_mtx(periph), 0);
	callout_reset(&softc->sendordered_c,
	    (ada_default_timeout * hz) / ADA_ORDEREDTAG_INTERVAL,
	    adasendorderedtag, softc);

	if (ADA_RA >= 0 && softc->flags & ADA_FLAG_CAN_RAHEAD) {
		softc->state = ADA_STATE_RAHEAD;
	} else if (ADA_WC >= 0 && softc->flags & ADA_FLAG_CAN_WCACHE) {
		softc->state = ADA_STATE_WCACHE;
	} else if ((softc->flags & ADA_FLAG_CAN_LOG)
		&& (softc->zone_mode != ADA_ZONE_NONE)) {
		softc->state = ADA_STATE_LOGDIR;
	} else {
		/*
		 * Nothing to probe, so we can just transition to the
		 * normal state.
		 */
		adaprobedone(periph, NULL);
		return(CAM_REQ_CMP);
	}

	xpt_schedule(periph, CAM_PRIORITY_DEV);

	return(CAM_REQ_CMP);
}

static int
ada_dsmtrim_req_create(struct ada_softc *softc, struct bio *bp, struct trim_request *req)
{
	uint64_t lastlba = (uint64_t)-1, lbas = 0;
	int c, lastcount = 0, off, ranges = 0;

	bzero(req, sizeof(*req));
	TAILQ_INIT(&req->bps);
	do {
		uint64_t lba = bp->bio_pblkno;
		int count = bp->bio_bcount / softc->params.secsize;

		/* Try to extend the previous range. */
		if (lba == lastlba) {
			c = min(count, ATA_DSM_RANGE_MAX - lastcount);
			lastcount += c;
			off = (ranges - 1) * ATA_DSM_RANGE_SIZE;
			req->data[off + 6] = lastcount & 0xff;
			req->data[off + 7] =
				(lastcount >> 8) & 0xff;
			count -= c;
			lba += c;
			lbas += c;
		}

		while (count > 0) {
			c = min(count, ATA_DSM_RANGE_MAX);
			off = ranges * ATA_DSM_RANGE_SIZE;
			req->data[off + 0] = lba & 0xff;
			req->data[off + 1] = (lba >> 8) & 0xff;
			req->data[off + 2] = (lba >> 16) & 0xff;
			req->data[off + 3] = (lba >> 24) & 0xff;
			req->data[off + 4] = (lba >> 32) & 0xff;
			req->data[off + 5] = (lba >> 40) & 0xff;
			req->data[off + 6] = c & 0xff;
			req->data[off + 7] = (c >> 8) & 0xff;
			lba += c;
			lbas += c;
			count -= c;
			lastcount = c;
			ranges++;
			/*
			 * Its the caller's responsibility to ensure the
			 * request will fit so we don't need to check for
			 * overrun here
			 */
		}
		lastlba = lba;
		TAILQ_INSERT_TAIL(&req->bps, bp, bio_queue);

		bp = cam_iosched_next_trim(softc->cam_iosched);
		if (bp == NULL)
			break;
		if (bp->bio_bcount / softc->params.secsize >
		    (softc->trim_max_ranges - ranges) * ATA_DSM_RANGE_MAX) {
			cam_iosched_put_back_trim(softc->cam_iosched, bp);
			break;
		}
	} while (1);
	softc->trim_count++;
	softc->trim_ranges += ranges;
	softc->trim_lbas += lbas;

	return (ranges);
}

static void
ada_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
{
	struct trim_request *req = &softc->trim_req;
	int ranges;

	ranges = ada_dsmtrim_req_create(softc, bp, req);
	cam_fill_ataio(ataio,
	    ada_retry_count,
	    adadone,
	    CAM_DIR_OUT,
	    0,
	    req->data,
	    howmany(ranges, ATA_DSM_BLK_RANGES) * ATA_DSM_BLK_SIZE,
	    ada_default_timeout * 1000);
	ata_48bit_cmd(ataio, ATA_DATA_SET_MANAGEMENT,
	    ATA_DSM_TRIM, 0, howmany(ranges, ATA_DSM_BLK_RANGES));
}

static void
ada_ncq_dsmtrim(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
{
	struct trim_request *req = &softc->trim_req;
	int ranges;

	ranges = ada_dsmtrim_req_create(softc, bp, req);
	cam_fill_ataio(ataio,
	    ada_retry_count,
	    adadone,
	    CAM_DIR_OUT,
	    0,
	    req->data,
	    howmany(ranges, ATA_DSM_BLK_RANGES) * ATA_DSM_BLK_SIZE,
	    ada_default_timeout * 1000);
	ata_ncq_cmd(ataio,
	    ATA_SEND_FPDMA_QUEUED,
	    0,
	    howmany(ranges, ATA_DSM_BLK_RANGES));
	ataio->cmd.sector_count_exp = ATA_SFPDMA_DSM;
	ataio->ata_flags |= ATA_FLAG_AUX;
	ataio->aux = 1;
}

static void
ada_cfaerase(struct ada_softc *softc, struct bio *bp, struct ccb_ataio *ataio)
{
	struct trim_request *req = &softc->trim_req;
	uint64_t lba = bp->bio_pblkno;
	uint16_t count = bp->bio_bcount / softc->params.secsize;

	bzero(req, sizeof(*req));
	TAILQ_INIT(&req->bps);
	TAILQ_INSERT_TAIL(&req->bps, bp, bio_queue);

	cam_fill_ataio(ataio,
	    ada_retry_count,
	    adadone,
	    CAM_DIR_NONE,
	    0,
	    NULL,
	    0,
	    ada_default_timeout*1000);

	if (count >= 256)
		count = 0;
	ata_28bit_cmd(ataio, ATA_CFA_ERASE, 0, lba, count);
}

static int
ada_zone_bio_to_ata(int disk_zone_cmd)
{
	switch (disk_zone_cmd) {
	case DISK_ZONE_OPEN:
		return ATA_ZM_OPEN_ZONE;
	case DISK_ZONE_CLOSE:
		return ATA_ZM_CLOSE_ZONE;
	case DISK_ZONE_FINISH:
		return ATA_ZM_FINISH_ZONE;
	case DISK_ZONE_RWP:
		return ATA_ZM_RWP;
	}

	return -1;
}

static int
ada_zone_cmd(struct cam_periph *periph, union ccb *ccb, struct bio *bp,
	     int *queue_ccb)
{
	struct ada_softc *softc;
	int error;

	error = 0;

	if (bp->bio_cmd != BIO_ZONE) {
		error = EINVAL;
		goto bailout;
	}

	softc = periph->softc;

	switch (bp->bio_zone.zone_cmd) {
	case DISK_ZONE_OPEN:
	case DISK_ZONE_CLOSE:
	case DISK_ZONE_FINISH:
	case DISK_ZONE_RWP: {
		int zone_flags;
		int zone_sa;
		uint64_t lba;

		zone_sa = ada_zone_bio_to_ata(bp->bio_zone.zone_cmd);
		if (zone_sa == -1) {
			xpt_print(periph->path, "Cannot translate zone "
			    "cmd %#x to ATA\n", bp->bio_zone.zone_cmd);
			error = EINVAL;
			goto bailout;
		}

		zone_flags = 0;
		lba = bp->bio_zone.zone_params.rwp.id;

		if (bp->bio_zone.zone_params.rwp.flags &
		    DISK_ZONE_RWP_FLAG_ALL)
			zone_flags |= ZBC_OUT_ALL;

		ata_zac_mgmt_out(&ccb->ataio,
				 /*retries*/ ada_retry_count,
				 /*cbfcnp*/ adadone,
				 /*use_ncq*/ (softc->flags &
					      ADA_FLAG_PIM_ATA_EXT) ? 1 : 0,
				 /*zm_action*/ zone_sa,
				 /*zone_id*/ lba,
				 /*zone_flags*/ zone_flags,
				 /*sector_count*/ 0,
				 /*data_ptr*/ NULL,
				 /*dxfer_len*/ 0,
				 /*timeout*/ ada_default_timeout * 1000);
		*queue_ccb = 1;

		break;
	}
	case DISK_ZONE_REPORT_ZONES: {
		uint8_t *rz_ptr;
		uint32_t num_entries, alloc_size;
		struct disk_zone_report *rep;

		rep = &bp->bio_zone.zone_params.report;

		num_entries = rep->entries_allocated;
		if (num_entries == 0) {
			xpt_print(periph->path, "No entries allocated for "
			    "Report Zones request\n");
			error = EINVAL;
			goto bailout;
		}
		alloc_size = sizeof(struct scsi_report_zones_hdr) +
		    (sizeof(struct scsi_report_zones_desc) * num_entries);
		alloc_size = min(alloc_size, softc->disk->d_maxsize);
		rz_ptr = malloc(alloc_size, M_ATADA, M_NOWAIT | M_ZERO);
		if (rz_ptr == NULL) {
			xpt_print(periph->path, "Unable to allocate memory "
			   "for Report Zones request\n");
			error = ENOMEM;
			goto bailout;
		}

		ata_zac_mgmt_in(&ccb->ataio,
				/*retries*/ ada_retry_count,
				/*cbcfnp*/ adadone,
				/*use_ncq*/ (softc->flags &
					     ADA_FLAG_PIM_ATA_EXT) ? 1 : 0,
				/*zm_action*/ ATA_ZM_REPORT_ZONES,
				/*zone_id*/ rep->starting_id,
				/*zone_flags*/ rep->rep_options,
				/*data_ptr*/ rz_ptr,
				/*dxfer_len*/ alloc_size,
				/*timeout*/ ada_default_timeout * 1000);

		/*
		 * For BIO_ZONE, this isn't normally needed.  However, it
		 * is used by devstat_end_transaction_bio() to determine
		 * how much data was transferred.
		 */
		/*
		 * XXX KDM we have a problem.  But I'm not sure how to fix
		 * it.  devstat uses bio_bcount - bio_resid to calculate
		 * the amount of data transferred.   The GEOM disk code
		 * uses bio_length - bio_resid to calculate the amount of
		 * data in bio_completed.  We have different structure
		 * sizes above and below the ada(4) driver.  So, if we
		 * use the sizes above, the amount transferred won't be
		 * quite accurate for devstat.  If we use different sizes
		 * for bio_bcount and bio_length (above and below
		 * respectively), then the residual needs to match one or
		 * the other.  Everything is calculated after the bio
		 * leaves the driver, so changing the values around isn't
		 * really an option.  For now, just set the count to the
		 * passed in length.  This means that the calculations
		 * above (e.g. bio_completed) will be correct, but the
		 * amount of data reported to devstat will be slightly
		 * under or overstated.
		 */
		bp->bio_bcount = bp->bio_length;

		*queue_ccb = 1;

		break;
	}
	case DISK_ZONE_GET_PARAMS: {
		struct disk_zone_disk_params *params;

		params = &bp->bio_zone.zone_params.disk_params;
		bzero(params, sizeof(*params));

		switch (softc->zone_mode) {
		case ADA_ZONE_DRIVE_MANAGED:
			params->zone_mode = DISK_ZONE_MODE_DRIVE_MANAGED;
			break;
		case ADA_ZONE_HOST_AWARE:
			params->zone_mode = DISK_ZONE_MODE_HOST_AWARE;
			break;
		case ADA_ZONE_HOST_MANAGED:
			params->zone_mode = DISK_ZONE_MODE_HOST_MANAGED;
			break;
		default:
		case ADA_ZONE_NONE:
			params->zone_mode = DISK_ZONE_MODE_NONE;
			break;
		}

		if (softc->zone_flags & ADA_ZONE_FLAG_URSWRZ)
			params->flags |= DISK_ZONE_DISK_URSWRZ;

		if (softc->zone_flags & ADA_ZONE_FLAG_OPT_SEQ_SET) {
			params->optimal_seq_zones = softc->optimal_seq_zones;
			params->flags |= DISK_ZONE_OPT_SEQ_SET;
		}

		if (softc->zone_flags & ADA_ZONE_FLAG_OPT_NONSEQ_SET) {
			params->optimal_nonseq_zones =
			    softc->optimal_nonseq_zones;
			params->flags |= DISK_ZONE_OPT_NONSEQ_SET;
		}

		if (softc->zone_flags & ADA_ZONE_FLAG_MAX_SEQ_SET) {
			params->max_seq_zones = softc->max_seq_zones;
			params->flags |= DISK_ZONE_MAX_SEQ_SET;
		}
		if (softc->zone_flags & ADA_ZONE_FLAG_RZ_SUP)
			params->flags |= DISK_ZONE_RZ_SUP;

		if (softc->zone_flags & ADA_ZONE_FLAG_OPEN_SUP)
			params->flags |= DISK_ZONE_OPEN_SUP;

		if (softc->zone_flags & ADA_ZONE_FLAG_CLOSE_SUP)
			params->flags |= DISK_ZONE_CLOSE_SUP;

		if (softc->zone_flags & ADA_ZONE_FLAG_FINISH_SUP)
			params->flags |= DISK_ZONE_FINISH_SUP;

		if (softc->zone_flags & ADA_ZONE_FLAG_RWP_SUP)
			params->flags |= DISK_ZONE_RWP_SUP;
		break;
	}
	default:
		break;
	}
bailout:
	return (error);
}

static void
adastart(struct cam_periph *periph, union ccb *start_ccb)
{
	struct ada_softc *softc = (struct ada_softc *)periph->softc;
	struct ccb_ataio *ataio = &start_ccb->ataio;

	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("adastart\n"));

	switch (softc->state) {
	case ADA_STATE_NORMAL:
	{
		struct bio *bp;
		u_int8_t tag_code;

		bp = cam_iosched_next_bio(softc->cam_iosched);
		if (bp == NULL) {
			xpt_release_ccb(start_ccb);
			break;
		}

		if ((bp->bio_flags & BIO_ORDERED) != 0 ||
		    (bp->bio_cmd != BIO_DELETE && (softc->flags & ADA_FLAG_NEED_OTAG) != 0)) {
			softc->flags &= ~ADA_FLAG_NEED_OTAG;
			softc->flags |= ADA_FLAG_WAS_OTAG;
			tag_code = 0;
		} else {
			tag_code = 1;
		}
		switch (bp->bio_cmd) {
		case BIO_WRITE:
		case BIO_READ:
		{
			uint64_t lba = bp->bio_pblkno;
			uint16_t count = bp->bio_bcount / softc->params.secsize;
			void *data_ptr;
			int rw_op;

			if (bp->bio_cmd == BIO_WRITE) {
				softc->flags |= ADA_FLAG_DIRTY;
				rw_op = CAM_DIR_OUT;
			} else {
				rw_op = CAM_DIR_IN;
			}

			data_ptr = bp->bio_data;
			if ((bp->bio_flags & (BIO_UNMAPPED|BIO_VLIST)) != 0) {
				rw_op |= CAM_DATA_BIO;
				data_ptr = bp;
			}

#ifdef CAM_TEST_FAILURE
			int fail = 0;

			/*
			 * Support the failure ioctls.  If the command is a
			 * read, and there are pending forced read errors, or
			 * if a write and pending write errors, then fail this
			 * operation with EIO.  This is useful for testing
			 * purposes.  Also, support having every Nth read fail.
			 *
			 * This is a rather blunt tool.
			 */
			if (bp->bio_cmd == BIO_READ) {
				if (softc->force_read_error) {
					softc->force_read_error--;
					fail = 1;
				}
				if (softc->periodic_read_error > 0) {
					if (++softc->periodic_read_count >=
					    softc->periodic_read_error) {
						softc->periodic_read_count = 0;
						fail = 1;
					}
				}
			} else {
				if (softc->force_write_error) {
					softc->force_write_error--;
					fail = 1;
				}
			}
			if (fail) {
				biofinish(bp, NULL, EIO);
				xpt_release_ccb(start_ccb);
				adaschedule(periph);
				return;
			}
#endif
			KASSERT((bp->bio_flags & BIO_UNMAPPED) == 0 ||
			    round_page(bp->bio_bcount + bp->bio_ma_offset) /
			    PAGE_SIZE == bp->bio_ma_n,
			    ("Short bio %p", bp));
			cam_fill_ataio(ataio,
			    ada_retry_count,
			    adadone,
			    rw_op,
			    0,
			    data_ptr,
			    bp->bio_bcount,
			    ada_default_timeout*1000);

			if ((softc->flags & ADA_FLAG_CAN_NCQ) && tag_code) {
				if (bp->bio_cmd == BIO_READ) {
					ata_ncq_cmd(ataio, ATA_READ_FPDMA_QUEUED,
					    lba, count);
				} else {
					ata_ncq_cmd(ataio, ATA_WRITE_FPDMA_QUEUED,
					    lba, count);
				}
			} else if ((softc->flags & ADA_FLAG_CAN_48BIT) &&
			    (lba + count >= ATA_MAX_28BIT_LBA ||
			    count > 256)) {
				if (softc->flags & ADA_FLAG_CAN_DMA48) {
					if (bp->bio_cmd == BIO_READ) {
						ata_48bit_cmd(ataio, ATA_READ_DMA48,
						    0, lba, count);
					} else {
						ata_48bit_cmd(ataio, ATA_WRITE_DMA48,
						    0, lba, count);
					}
				} else {
					if (bp->bio_cmd == BIO_READ) {
						ata_48bit_cmd(ataio, ATA_READ_MUL48,
						    0, lba, count);
					} else {
						ata_48bit_cmd(ataio, ATA_WRITE_MUL48,
						    0, lba, count);
					}
				}
			} else {
				if (count == 256)
					count = 0;
				if (softc->flags & ADA_FLAG_CAN_DMA) {
					if (bp->bio_cmd == BIO_READ) {
						ata_28bit_cmd(ataio, ATA_READ_DMA,
						    0, lba, count);
					} else {
						ata_28bit_cmd(ataio, ATA_WRITE_DMA,
						    0, lba, count);
					}
				} else {
					if (bp->bio_cmd == BIO_READ) {
						ata_28bit_cmd(ataio, ATA_READ_MUL,
						    0, lba, count);
					} else {
						ata_28bit_cmd(ataio, ATA_WRITE_MUL,
						    0, lba, count);
					}
				}
			}
			break;
		}
		case BIO_DELETE:
			switch (softc->delete_method) {
			case ADA_DELETE_NCQ_DSM_TRIM:
				ada_ncq_dsmtrim(softc, bp, ataio);
				break;
			case ADA_DELETE_DSM_TRIM:
				ada_dsmtrim(softc, bp, ataio);
				break;
			case ADA_DELETE_CFA_ERASE:
				ada_cfaerase(softc, bp, ataio);
				break;
			default:
				biofinish(bp, NULL, EOPNOTSUPP);
				xpt_release_ccb(start_ccb);
				adaschedule(periph);
				return;
			}
			start_ccb->ccb_h.ccb_state = ADA_CCB_TRIM;
			start_ccb->ccb_h.flags |= CAM_UNLOCKED;
			cam_iosched_submit_trim(softc->cam_iosched);
			goto out;
		case BIO_FLUSH:
			cam_fill_ataio(ataio,
			    1,
			    adadone,
			    CAM_DIR_NONE,
			    0,
			    NULL,
			    0,
			    ada_default_timeout*1000);

			if (softc->flags & ADA_FLAG_CAN_48BIT)
				ata_48bit_cmd(ataio, ATA_FLUSHCACHE48, 0, 0, 0);
			else
				ata_28bit_cmd(ataio, ATA_FLUSHCACHE, 0, 0, 0);
			break;
		case BIO_ZONE: {
			int error, queue_ccb;

			queue_ccb = 0;

			error = ada_zone_cmd(periph, start_ccb, bp, &queue_ccb);
			if ((error != 0)
			 || (queue_ccb == 0)) {
				biofinish(bp, NULL, error);
				xpt_release_ccb(start_ccb);
				return;
			}
			break;
		}
		}
		start_ccb->ccb_h.ccb_state = ADA_CCB_BUFFER_IO;
		start_ccb->ccb_h.flags |= CAM_UNLOCKED;
out:
		start_ccb->ccb_h.ccb_bp = bp;
		softc->outstanding_cmds++;
		softc->refcount++;
		cam_periph_unlock(periph);
		xpt_action(start_ccb);
		cam_periph_lock(periph);

		/* May have more work to do, so ensure we stay scheduled */
		adaschedule(periph);
		break;
	}
	case ADA_STATE_RAHEAD:
	case ADA_STATE_WCACHE:
	{
		cam_fill_ataio(ataio,
		    1,
		    adadone,
		    CAM_DIR_NONE,
		    0,
		    NULL,
		    0,
		    ada_default_timeout*1000);

		if (softc->state == ADA_STATE_RAHEAD) {
			ata_28bit_cmd(ataio, ATA_SETFEATURES, ADA_RA ?
			    ATA_SF_ENAB_RCACHE : ATA_SF_DIS_RCACHE, 0, 0);
			start_ccb->ccb_h.ccb_state = ADA_CCB_RAHEAD;
		} else {
			ata_28bit_cmd(ataio, ATA_SETFEATURES, ADA_WC ?
			    ATA_SF_ENAB_WCACHE : ATA_SF_DIS_WCACHE, 0, 0);
			start_ccb->ccb_h.ccb_state = ADA_CCB_WCACHE;
		}
		start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
		xpt_action(start_ccb);
		break;
	}
	case ADA_STATE_LOGDIR:
	{
		struct ata_gp_log_dir *log_dir;

		if ((softc->flags & ADA_FLAG_CAN_LOG) == 0) {
			adaprobedone(periph, start_ccb);
			break;
		}

		log_dir = malloc(sizeof(*log_dir), M_ATADA, M_NOWAIT|M_ZERO);
		if (log_dir == NULL) {
			xpt_print(periph->path, "Couldn't malloc log_dir "
			    "data\n");
			softc->state = ADA_STATE_NORMAL;
			xpt_release_ccb(start_ccb);
			break;
		}


		ata_read_log(ataio,
		    /*retries*/1,
		    /*cbfcnp*/adadone,
		    /*log_address*/ ATA_LOG_DIRECTORY,
		    /*page_number*/ 0,
		    /*block_count*/ 1,
		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
				 CAM_ATAIO_DMA : 0,
		    /*data_ptr*/ (uint8_t *)log_dir,
		    /*dxfer_len*/sizeof(*log_dir),
		    /*timeout*/ada_default_timeout*1000);

		start_ccb->ccb_h.ccb_state = ADA_CCB_LOGDIR;
		xpt_action(start_ccb);
		break;
	}
	case ADA_STATE_IDDIR:
	{
		struct ata_identify_log_pages *id_dir;

		id_dir = malloc(sizeof(*id_dir), M_ATADA, M_NOWAIT | M_ZERO);
		if (id_dir == NULL) {
			xpt_print(periph->path, "Couldn't malloc id_dir "
			    "data\n");
			adaprobedone(periph, start_ccb);
			break;
		}

		ata_read_log(ataio,
		    /*retries*/1,
		    /*cbfcnp*/adadone,
		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
		    /*page_number*/ ATA_IDL_PAGE_LIST,
		    /*block_count*/ 1,
		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
				 CAM_ATAIO_DMA : 0,
		    /*data_ptr*/ (uint8_t *)id_dir,
		    /*dxfer_len*/ sizeof(*id_dir),
		    /*timeout*/ada_default_timeout*1000);

		start_ccb->ccb_h.ccb_state = ADA_CCB_IDDIR;
		xpt_action(start_ccb);
		break;
	}
	case ADA_STATE_SUP_CAP:
	{
		struct ata_identify_log_sup_cap *sup_cap;

		sup_cap = malloc(sizeof(*sup_cap), M_ATADA, M_NOWAIT|M_ZERO);
		if (sup_cap == NULL) {
			xpt_print(periph->path, "Couldn't malloc sup_cap "
			    "data\n");
			adaprobedone(periph, start_ccb);
			break;
		}

		ata_read_log(ataio,
		    /*retries*/1,
		    /*cbfcnp*/adadone,
		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
		    /*page_number*/ ATA_IDL_SUP_CAP,
		    /*block_count*/ 1,
		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
				 CAM_ATAIO_DMA : 0,
		    /*data_ptr*/ (uint8_t *)sup_cap,
		    /*dxfer_len*/ sizeof(*sup_cap),
		    /*timeout*/ada_default_timeout*1000);

		start_ccb->ccb_h.ccb_state = ADA_CCB_SUP_CAP;
		xpt_action(start_ccb);
		break;
	}
	case ADA_STATE_ZONE:
	{
		struct ata_zoned_info_log *ata_zone;

		ata_zone = malloc(sizeof(*ata_zone), M_ATADA, M_NOWAIT|M_ZERO);
		if (ata_zone == NULL) {
			xpt_print(periph->path, "Couldn't malloc ata_zone "
			    "data\n");
			adaprobedone(periph, start_ccb);
			break;
		}

		ata_read_log(ataio,
		    /*retries*/1,
		    /*cbfcnp*/adadone,
		    /*log_address*/ ATA_IDENTIFY_DATA_LOG,
		    /*page_number*/ ATA_IDL_ZDI,
		    /*block_count*/ 1,
		    /*protocol*/ softc->flags & ADA_FLAG_CAN_DMA ?
				 CAM_ATAIO_DMA : 0,
		    /*data_ptr*/ (uint8_t *)ata_zone,
		    /*dxfer_len*/ sizeof(*ata_zone),
		    /*timeout*/ada_default_timeout*1000);

		start_ccb->ccb_h.ccb_state = ADA_CCB_ZONE;
		xpt_action(start_ccb);
		break;
	}
	}
}

static void
adaprobedone(struct cam_periph *periph, union ccb *ccb)
{
	struct ada_softc *softc;

	softc = (struct ada_softc *)periph->softc;

	if (ccb != NULL)
		xpt_release_ccb(ccb);

	softc->state = ADA_STATE_NORMAL;
	softc->flags |= ADA_FLAG_PROBED;
	adaschedule(periph);
	if ((softc->flags & ADA_FLAG_ANNOUNCED) == 0) {
		softc->flags |= ADA_FLAG_ANNOUNCED;
		cam_periph_unhold(periph);
	} else {
		cam_periph_release_locked(periph);
	}
}

static void
adazonedone(struct cam_periph *periph, union ccb *ccb)
{
	struct bio *bp;

	bp = (struct bio *)ccb->ccb_h.ccb_bp;

	switch (bp->bio_zone.zone_cmd) {
	case DISK_ZONE_OPEN:
	case DISK_ZONE_CLOSE:
	case DISK_ZONE_FINISH:
	case DISK_ZONE_RWP:
		break;
	case DISK_ZONE_REPORT_ZONES: {
		uint32_t avail_len;
		struct disk_zone_report *rep;
		struct scsi_report_zones_hdr *hdr;
		struct scsi_report_zones_desc *desc;
		struct disk_zone_rep_entry *entry;
		uint32_t hdr_len, num_avail;
		uint32_t num_to_fill, i;

		rep = &bp->bio_zone.zone_params.report;
		avail_len = ccb->ataio.dxfer_len - ccb->ataio.resid;
		/*
		 * Note that bio_resid isn't normally used for zone
		 * commands, but it is used by devstat_end_transaction_bio()
		 * to determine how much data was transferred.  Because
		 * the size of the SCSI/ATA data structures is different
		 * than the size of the BIO interface structures, the
		 * amount of data actually transferred from the drive will
		 * be different than the amount of data transferred to
		 * the user.
		 */
		hdr = (struct scsi_report_zones_hdr *)ccb->ataio.data_ptr;
		if (avail_len < sizeof(*hdr)) {
			/*
			 * Is there a better error than EIO here?  We asked
			 * for at least the header, and we got less than
			 * that.
			 */
			bp->bio_error = EIO;
			bp->bio_flags |= BIO_ERROR;
			bp->bio_resid = bp->bio_bcount;
			break;
		}

		hdr_len = le32dec(hdr->length);
		if (hdr_len > 0)
			rep->entries_available = hdr_len / sizeof(*desc);
		else
			rep->entries_available = 0;
		/*
		 * NOTE: using the same values for the BIO version of the
		 * same field as the SCSI/ATA values.  This means we could
		 * get some additional values that aren't defined in bio.h
		 * if more values of the same field are defined later.
		 */
		rep->header.same = hdr->byte4 & SRZ_SAME_MASK;
		rep->header.maximum_lba = le64dec(hdr->maximum_lba);
		/*
		 * If the drive reports no entries that match the query,
		 * we're done.
		 */
		if (hdr_len == 0) {
			rep->entries_filled = 0;
			bp->bio_resid = bp->bio_bcount;
			break;
		}

		num_avail = min((avail_len - sizeof(*hdr)) / sizeof(*desc),
				hdr_len / sizeof(*desc));
		/*
		 * If the drive didn't return any data, then we're done.
		 */
		if (num_avail == 0) {
			rep->entries_filled = 0;
			bp->bio_resid = bp->bio_bcount;
			break;
		}

		num_to_fill = min(num_avail, rep->entries_allocated);
		/*
		 * If the user didn't allocate any entries for us to fill,
		 * we're done.
		 */
		if (num_to_fill == 0) {
			rep->entries_filled = 0;
			bp->bio_resid = bp->bio_bcount;
			break;
		}

		for (i = 0, desc = &hdr->desc_list[0], entry=&rep->entries[0];
		     i < num_to_fill; i++, desc++, entry++) {
			/*
			 * NOTE: we're mapping the values here directly
			 * from the SCSI/ATA bit definitions to the bio.h
			 * definitions.  There is also a warning in
			 * disk_zone.h, but the impact is that if
			 * additional values are added in the SCSI/ATA
			 * specs these will be visible to consumers of
			 * this interface.
			 */
			entry->zone_type = desc->zone_type & SRZ_TYPE_MASK;
			entry->zone_condition =
			    (desc->zone_flags & SRZ_ZONE_COND_MASK) >>
			    SRZ_ZONE_COND_SHIFT;
			entry->zone_flags |= desc->zone_flags &
			    (SRZ_ZONE_NON_SEQ|SRZ_ZONE_RESET);
			entry->zone_length = le64dec(desc->zone_length);
			entry->zone_start_lba = le64dec(desc->zone_start_lba);
			entry->write_pointer_lba =
			    le64dec(desc->write_pointer_lba);
		}
		rep->entries_filled = num_to_fill;
		/*
		 * Note that this residual is accurate from the user's
		 * standpoint, but the amount transferred isn't accurate
		 * from the standpoint of what actually came back from the
		 * drive.
		 */
		bp->bio_resid = bp->bio_bcount - (num_to_fill * sizeof(*entry));
		break;
	}
	case DISK_ZONE_GET_PARAMS:
	default:
		/*
		 * In theory we should not get a GET_PARAMS bio, since it
		 * should be handled without queueing the command to the
		 * drive.
		 */
		panic("%s: Invalid zone command %d", __func__,
		    bp->bio_zone.zone_cmd);
		break;
	}

	if (bp->bio_zone.zone_cmd == DISK_ZONE_REPORT_ZONES)
		free(ccb->ataio.data_ptr, M_ATADA);
}


static void
adadone(struct cam_periph *periph, union ccb *done_ccb)
{
	struct ada_softc *softc;
	struct ccb_ataio *ataio;
	struct cam_path *path;
	uint32_t priority;
	int state;

	softc = (struct ada_softc *)periph->softc;
	ataio = &done_ccb->ataio;
	path = done_ccb->ccb_h.path;
	priority = done_ccb->ccb_h.pinfo.priority;

	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("adadone\n"));

	state = ataio->ccb_h.ccb_state & ADA_CCB_TYPE_MASK;
	switch (state) {
	case ADA_CCB_BUFFER_IO:
	case ADA_CCB_TRIM:
	{
		struct bio *bp;
		int error;

		cam_periph_lock(periph);
		bp = (struct bio *)done_ccb->ccb_h.ccb_bp;
		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
			error = adaerror(done_ccb, 0, 0);
			if (error == ERESTART) {
				/* A retry was scheduled, so just return. */
				cam_periph_unlock(periph);
				return;
			}
			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
				cam_release_devq(path,
						 /*relsim_flags*/0,
						 /*reduction*/0,
						 /*timeout*/0,
						 /*getcount_only*/0);
			/*
			 * If we get an error on an NCQ DSM TRIM, fall back
			 * to a non-NCQ DSM TRIM forever. Please note that if
			 * CAN_NCQ_TRIM is set, CAN_TRIM is necessarily set too.
			 * However, for this one trim, we treat it as advisory
			 * and return success up the stack.
			 */
			if (state == ADA_CCB_TRIM &&
			    error != 0 &&
			    (softc->flags & ADA_FLAG_CAN_NCQ_TRIM) != 0) {
				softc->flags &= ~ADA_FLAG_CAN_NCQ_TRIM;
				error = 0;
				adasetdeletemethod(softc);
			}
		} else {
			if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0)
				panic("REQ_CMP with QFRZN");

			error = 0;
		}
		bp->bio_error = error;
		if (error != 0) {
			bp->bio_resid = bp->bio_bcount;
			bp->bio_flags |= BIO_ERROR;
		} else {
			if (bp->bio_cmd == BIO_ZONE)
				adazonedone(periph, done_ccb);
			else if (state == ADA_CCB_TRIM)
				bp->bio_resid = 0;
			else
				bp->bio_resid = ataio->resid;

			if ((bp->bio_resid > 0)
			 && (bp->bio_cmd != BIO_ZONE))
				bp->bio_flags |= BIO_ERROR;
		}
		softc->outstanding_cmds--;
		if (softc->outstanding_cmds == 0)
			softc->flags |= ADA_FLAG_WAS_OTAG;

		/*
		 * We need to call cam_iosched before we call biodone so that we
		 * don't measure any activity that happens in the completion
		 * routine, which in the case of sendfile can be quite
		 * extensive.  Release the periph refcount taken in adastart()
		 * for each CCB.
		 */
		cam_iosched_bio_complete(softc->cam_iosched, bp, done_ccb);
		xpt_release_ccb(done_ccb);
		KASSERT(softc->refcount >= 1, ("adadone softc %p refcount %d", softc, softc->refcount));
		softc->refcount--;
		if (state == ADA_CCB_TRIM) {
			TAILQ_HEAD(, bio) queue;
			struct bio *bp1;

			TAILQ_INIT(&queue);
			TAILQ_CONCAT(&queue, &softc->trim_req.bps, bio_queue);
			/*
			 * Normally, the xpt_release_ccb() above would make sure
			 * that when we have more work to do, that work would
			 * get kicked off. However, we specifically keep
			 * trim_running set to 0 before the call above to allow
			 * other I/O to progress when many BIO_DELETE requests
			 * are pushed down. We set trim_running to 0 and call
			 * daschedule again so that we don't stall if there are
			 * no other I/Os pending apart from BIO_DELETEs.
			 */
			cam_iosched_trim_done(softc->cam_iosched);
			adaschedule(periph);
			cam_periph_unlock(periph);
			while ((bp1 = TAILQ_FIRST(&queue)) != NULL) {
				TAILQ_REMOVE(&queue, bp1, bio_queue);
				bp1->bio_error = error;
				if (error != 0) {
					bp1->bio_flags |= BIO_ERROR;
					bp1->bio_resid = bp1->bio_bcount;
				} else
					bp1->bio_resid = 0;
				biodone(bp1);
			}
		} else {
			adaschedule(periph);
			cam_periph_unlock(periph);
			biodone(bp);
		}
		return;
	}
	case ADA_CCB_RAHEAD:
	{
		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
			if (adaerror(done_ccb, 0, 0) == ERESTART) {
				/* Drop freeze taken due to CAM_DEV_QFREEZE */
				cam_release_devq(path, 0, 0, 0, FALSE);
				return;
			} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
				cam_release_devq(path,
				    /*relsim_flags*/0,
				    /*reduction*/0,
				    /*timeout*/0,
				    /*getcount_only*/0);
			}
		}

		/*
		 * Since our peripheral may be invalidated by an error
		 * above or an external event, we must release our CCB
		 * before releasing the reference on the peripheral.
		 * The peripheral will only go away once the last reference
		 * is removed, and we need it around for the CCB release
		 * operation.
		 */

		xpt_release_ccb(done_ccb);
		softc->state = ADA_STATE_WCACHE;
		xpt_schedule(periph, priority);
		/* Drop freeze taken due to CAM_DEV_QFREEZE */
		cam_release_devq(path, 0, 0, 0, FALSE);
		return;
	}
	case ADA_CCB_WCACHE:
	{
		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
			if (adaerror(done_ccb, 0, 0) == ERESTART) {
				/* Drop freeze taken due to CAM_DEV_QFREEZE */
				cam_release_devq(path, 0, 0, 0, FALSE);
				return;
			} else if ((done_ccb->ccb_h.status & CAM_DEV_QFRZN) != 0) {
				cam_release_devq(path,
				    /*relsim_flags*/0,
				    /*reduction*/0,
				    /*timeout*/0,
				    /*getcount_only*/0);
			}
		}

		/* Drop freeze taken due to CAM_DEV_QFREEZE */
		cam_release_devq(path, 0, 0, 0, FALSE);

		if ((softc->flags & ADA_FLAG_CAN_LOG)
		 && (softc->zone_mode != ADA_ZONE_NONE)) {
			xpt_release_ccb(done_ccb);
			softc->state = ADA_STATE_LOGDIR;
			xpt_schedule(periph, priority);
		} else {
			adaprobedone(periph, done_ccb);
		}
		return;
	}
	case ADA_CCB_LOGDIR:
	{
		int error;

		if ((done_ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
			error = 0;
			softc->valid_logdir_len = 0;
			bzero(&softc->ata_logdir, sizeof(softc->ata_logdir));
			softc->valid_logdir_len =
				ataio->dxfer_len - ataio->resid;
			if (softc->valid_logdir_len > 0)
				bcopy(ataio->data_ptr, &softc->ata_logdir,
				    min(softc->valid_logdir_len,
					sizeof(softc->ata_logdir)));
			/*
			 * Figure out whether the Identify Device log is
			 * supported.  The General Purpose log directory
			 * has a header, and lists the number of pages
			 * available for each GP log identified by the
			 * offset into the list.
			 */
			if ((softc->valid_logdir_len >=
			    ((ATA_IDENTIFY_DATA_LOG + 1) * sizeof(uint16_t)))
			 && (le16dec(softc->ata_logdir.header) ==
			     ATA_GP_LOG_DIR_VERSION)
			 && (le16dec(&softc->ata_logdir.num_pages[
			     (ATA_IDENTIFY_DATA_LOG *
			     sizeof(uint16_t)) - sizeof(uint16_t)]) > 0)){
				softc->flags |= ADA_FLAG_CAN_IDLOG;
			} else {
				softc->flags &= ~ADA_FLAG_CAN_IDLOG;
			}
		} else {
			error = adaerror(done_ccb, CAM_RETRY_SELTO,
					 SF_RETRY_UA|SF_NO_PRINT);
			if (error == ERESTART)
				return;
			else if (error != 0) {
				/*
				 * If we can't get the ATA log directory,
				 * then ATA logs are effectively not
				 * supported even if the bit is set in the
				 * identify data.
				 */
				softc->flags &= ~(ADA_FLAG_CAN_LOG |
						  ADA_FLAG_CAN_IDLOG);
				if ((done_ccb->ccb_h.status &
				     CAM_DEV_QFRZN) != 0) {
					/* Don't wedge this device's queue */
					cam_release_devq(done_ccb->ccb_h.path,
							 /*relsim_flags*/0,
							 /*reduction*/0,
							 /*timeout*/0,
							 /*getcount_only*/0);
				}
			}


		}

		free(ataio->data_ptr, M_ATADA);

		if ((error == 0)
		 && (softc->flags & ADA_FLAG_CAN_IDLOG)) {
			softc->state = ADA_STATE_IDDIR;
			xpt_release_ccb(done_ccb);
			xpt_schedule(periph, priority);
		} else
			adaprobedone(periph, done_ccb);

		return;
	}
	case ADA_CCB_IDDIR: {
		int error;

		if ((ataio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
			off_t entries_offset, max_entries;
			error = 0;

			softc->valid_iddir_len = 0;
			bzero(&softc->ata_iddir, sizeof(softc->ata_iddir));
			softc->flags &= ~(ADA_FLAG_CAN_SUPCAP |
					  ADA_FLAG_CAN_ZONE);
			softc->valid_iddir_len =
				ataio->dxfer_len - ataio->resid;
			if (softc->valid_iddir_len > 0)
				bcopy(ataio->data_ptr, &softc->ata_iddir,
				    min(softc->valid_iddir_len,
					sizeof(softc->ata_iddir)));

			entries_offset =
			    __offsetof(struct ata_identify_log_pages,entries);
			max_entries = softc->valid_iddir_len - entries_offset;
			if ((softc->valid_iddir_len > (entries_offset + 1))
			 && (le64dec(softc->ata_iddir.header) ==
			     ATA_IDLOG_REVISION)
			 && (softc->ata_iddir.entry_count > 0)) {
				int num_entries, i;

				num_entries = softc->ata_iddir.entry_count;
				num_entries = min(num_entries,
				   softc->valid_iddir_len - entries_offset);
				for (i = 0; i < num_entries &&
				     i < max_entries; i++) {
					if (softc->ata_iddir.entries[i] ==
					    ATA_IDL_SUP_CAP)
						softc->flags |=
						    ADA_FLAG_CAN_SUPCAP;
					else if (softc->ata_iddir.entries[i]==
						 ATA_IDL_ZDI)
						softc->flags |=
						    ADA_FLAG_CAN_ZONE;

					if ((softc->flags &
					     ADA_FLAG_CAN_SUPCAP)
					 && (softc->flags &
					     ADA_FLAG_CAN_ZONE))
						break;
				}
			}
		} else {
			error = adaerror(done_ccb, CAM_RETRY_SELTO,
					 SF_RETRY_UA|SF_NO_PRINT);
			if (error == ERESTART)
				return;
			else if (error != 0) {
				/*
				 * If we can't get the ATA Identify Data log
				 * directory, then it effectively isn't
				 * supported even if the ATA Log directory
				 * a non-zero number of pages present for
				 * this log.
				 */
				softc->flags &= ~ADA_FLAG_CAN_IDLOG;
				if ((done_ccb->ccb_h.status &
				     CAM_DEV_QFRZN) != 0) {
					/* Don't wedge this device's queue */
					cam_release_devq(done_ccb->ccb_h.path,
							 /*relsim_flags*/0,
							 /*reduction*/0,
							 /*timeout*/0,
							 /*getcount_only*/0);
				}
			}
		}

		free(ataio->data_ptr, M_ATADA);

		if ((error == 0)
		 && (softc->flags & ADA_FLAG_CAN_SUPCAP)) {
			softc->state = ADA_STATE_SUP_CAP;
			xpt_release_ccb(done_ccb);
			xpt_schedule(periph, priority);
		} else
			adaprobedone(periph, done_ccb);
		return;
	}
	case ADA_CCB_SUP_CAP: {
		int error;

		if ((ataio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
			uint32_t valid_len;
			size_t needed_size;
			struct ata_identify_log_sup_cap *sup_cap;
			error = 0;

			sup_cap = (struct ata_identify_log_sup_cap *)
			    ataio->data_ptr;
			valid_len = ataio->dxfer_len - ataio->resid;
			needed_size =
			    __offsetof(struct ata_identify_log_sup_cap,
			    sup_zac_cap) + 1 + sizeof(sup_cap->sup_zac_cap);
			if (valid_len >= needed_size) {
				uint64_t zoned, zac_cap;

				zoned = le64dec(sup_cap->zoned_cap);
				if (zoned & ATA_ZONED_VALID) {
					/*
					 * This should have already been
					 * set, because this is also in the
					 * ATA identify data.
					 */
					if ((zoned & ATA_ZONED_MASK) ==
					    ATA_SUPPORT_ZONE_HOST_AWARE)
						softc->zone_mode =
						    ADA_ZONE_HOST_AWARE;
					else if ((zoned & ATA_ZONED_MASK) ==
					    ATA_SUPPORT_ZONE_DEV_MANAGED)
						softc->zone_mode =
						    ADA_ZONE_DRIVE_MANAGED;
				}

				zac_cap = le64dec(sup_cap->sup_zac_cap);
				if (zac_cap & ATA_SUP_ZAC_CAP_VALID) {
					if (zac_cap & ATA_REPORT_ZONES_SUP)
						softc->zone_flags |=
						    ADA_ZONE_FLAG_RZ_SUP;
					if (zac_cap & ATA_ND_OPEN_ZONE_SUP)
						softc->zone_flags |=
						    ADA_ZONE_FLAG_OPEN_SUP;
					if (zac_cap & ATA_ND_CLOSE_ZONE_SUP)
						softc->zone_flags |=
						    ADA_ZONE_FLAG_CLOSE_SUP;
					if (zac_cap & ATA_ND_FINISH_ZONE_SUP)
						softc->zone_flags |=
						    ADA_ZONE_FLAG_FINISH_SUP;
					if (zac_cap & ATA_ND_RWP_SUP)
						softc->zone_flags |=
						    ADA_ZONE_FLAG_RWP_SUP;
				} else {
					/*
					 * This field was introduced in
					 * ACS-4, r08 on April 28th, 2015.
					 * If the drive firmware was written
					 * to an earlier spec, it won't have
					 * the field.  So, assume all
					 * commands are supported.
					 */
					softc->zone_flags |=
					    ADA_ZONE_FLAG_SUP_MASK;
				}
			}
		} else {
			error = adaerror(done_ccb, CAM_RETRY_SELTO,
					 SF_RETRY_UA|SF_NO_PRINT);
			if (error == ERESTART)
				return;
			else if (error != 0) {
				/*
				 * If we can't get the ATA Identify Data
				 * Supported Capabilities page, clear the
				 * flag...
				 */
				softc->flags &= ~ADA_FLAG_CAN_SUPCAP;
				/*
				 * And clear zone capabilities.
				 */
				softc->zone_flags &= ~ADA_ZONE_FLAG_SUP_MASK;
				if ((done_ccb->ccb_h.status &
				     CAM_DEV_QFRZN) != 0) {
					/* Don't wedge this device's queue */
					cam_release_devq(done_ccb->ccb_h.path,
							 /*relsim_flags*/0,
							 /*reduction*/0,
							 /*timeout*/0,
							 /*getcount_only*/0);
				}
			}
		}

		free(ataio->data_ptr, M_ATADA);

		if ((error == 0)
		 && (softc->flags & ADA_FLAG_CAN_ZONE)) {
			softc->state = ADA_STATE_ZONE;
			xpt_release_ccb(done_ccb);
			xpt_schedule(periph, priority);
		} else
			adaprobedone(periph, done_ccb);
		return;
	}
	case ADA_CCB_ZONE: {
		int error;

		if ((ataio->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
			struct ata_zoned_info_log *zi_log;
			uint32_t valid_len;
			size_t needed_size;

			zi_log = (struct ata_zoned_info_log *)ataio->data_ptr;

			valid_len = ataio->dxfer_len - ataio->resid;
			needed_size = __offsetof(struct ata_zoned_info_log,
			    version_info) + 1 + sizeof(zi_log->version_info);
			if (valid_len >= needed_size) {
				uint64_t tmpvar;

				tmpvar = le64dec(zi_log->zoned_cap);
				if (tmpvar & ATA_ZDI_CAP_VALID) {
					if (tmpvar & ATA_ZDI_CAP_URSWRZ)
						softc->zone_flags |=
						    ADA_ZONE_FLAG_URSWRZ;
					else
						softc->zone_flags &=
						    ~ADA_ZONE_FLAG_URSWRZ;
				}
				tmpvar = le64dec(zi_log->optimal_seq_zones);
				if (tmpvar & ATA_ZDI_OPT_SEQ_VALID) {
					softc->zone_flags |=
					    ADA_ZONE_FLAG_OPT_SEQ_SET;
					softc->optimal_seq_zones = (tmpvar &
					    ATA_ZDI_OPT_SEQ_MASK);
				} else {
					softc->zone_flags &=
					    ~ADA_ZONE_FLAG_OPT_SEQ_SET;
					softc->optimal_seq_zones = 0;
				}

				tmpvar =le64dec(zi_log->optimal_nonseq_zones);
				if (tmpvar & ATA_ZDI_OPT_NS_VALID) {
					softc->zone_flags |=
					    ADA_ZONE_FLAG_OPT_NONSEQ_SET;
					softc->optimal_nonseq_zones =
					    (tmpvar & ATA_ZDI_OPT_NS_MASK);
				} else {
					softc->zone_flags &=
					    ~ADA_ZONE_FLAG_OPT_NONSEQ_SET;
					softc->optimal_nonseq_zones = 0;
				}

				tmpvar = le64dec(zi_log->max_seq_req_zones);
				if (tmpvar & ATA_ZDI_MAX_SEQ_VALID) {
					softc->zone_flags |=
					    ADA_ZONE_FLAG_MAX_SEQ_SET;
					softc->max_seq_zones =
					    (tmpvar & ATA_ZDI_MAX_SEQ_MASK);
				} else {
					softc->zone_flags &=
					    ~ADA_ZONE_FLAG_MAX_SEQ_SET;
					softc->max_seq_zones = 0;
				}
			}
		} else {
			error = adaerror(done_ccb, CAM_RETRY_SELTO,
					 SF_RETRY_UA|SF_NO_PRINT);
			if (error == ERESTART)
				return;
			else if (error != 0) {
				softc->flags &= ~ADA_FLAG_CAN_ZONE;
				softc->flags &= ~ADA_ZONE_FLAG_SET_MASK;

				if ((done_ccb->ccb_h.status &
				     CAM_DEV_QFRZN) != 0) {
					/* Don't wedge this device's queue */
					cam_release_devq(done_ccb->ccb_h.path,
							 /*relsim_flags*/0,
							 /*reduction*/0,
							 /*timeout*/0,
							 /*getcount_only*/0);
				}
			}
		}
		free(ataio->data_ptr, M_ATADA);

		adaprobedone(periph, done_ccb);
		return;
	}
	case ADA_CCB_DUMP:
		/* No-op.  We're polling */
		return;
	default:
		break;
	}
	xpt_release_ccb(done_ccb);
}

static int
adaerror(union ccb *ccb, u_int32_t cam_flags, u_int32_t sense_flags)
{
#ifdef CAM_IO_STATS
	struct ada_softc *softc;
	struct cam_periph *periph;

	periph = xpt_path_periph(ccb->ccb_h.path);
	softc = (struct ada_softc *)periph->softc;

	switch (ccb->ccb_h.status & CAM_STATUS_MASK) {
	case CAM_CMD_TIMEOUT:
		softc->timeouts++;
		break;
	case CAM_REQ_ABORTED:
	case CAM_REQ_CMP_ERR:
	case CAM_REQ_TERMIO:
	case CAM_UNREC_HBA_ERROR:
	case CAM_DATA_RUN_ERR:
	case CAM_ATA_STATUS_ERROR:
		softc->errors++;
		break;
	default:
		break;
	}
#endif

	return(cam_periph_error(ccb, cam_flags, sense_flags));
}

static void
adasetgeom(struct ada_softc *softc, struct ccb_getdev *cgd)
{
	struct disk_params *dp = &softc->params;
	u_int64_t lbasize48;
	u_int32_t lbasize;
	u_int maxio, d_flags;

	dp->secsize = ata_logical_sector_size(&cgd->ident_data);
	if ((cgd->ident_data.atavalid & ATA_FLAG_54_58) &&
	    cgd->ident_data.current_heads != 0 &&
	    cgd->ident_data.current_sectors != 0) {
		dp->heads = cgd->ident_data.current_heads;
		dp->secs_per_track = cgd->ident_data.current_sectors;
		dp->cylinders = cgd->ident_data.cylinders;
		dp->sectors = (u_int32_t)cgd->ident_data.current_size_1 |
			  ((u_int32_t)cgd->ident_data.current_size_2 << 16);
	} else {
		dp->heads = cgd->ident_data.heads;
		dp->secs_per_track = cgd->ident_data.sectors;
		dp->cylinders = cgd->ident_data.cylinders;
		dp->sectors = cgd->ident_data.cylinders *
			      (u_int32_t)(dp->heads * dp->secs_per_track);
	}
	lbasize = (u_int32_t)cgd->ident_data.lba_size_1 |
		  ((u_int32_t)cgd->ident_data.lba_size_2 << 16);

	/* use the 28bit LBA size if valid or bigger than the CHS mapping */
	if (cgd->ident_data.cylinders == 16383 || dp->sectors < lbasize)
		dp->sectors = lbasize;

	/* use the 48bit LBA size if valid */
	lbasize48 = ((u_int64_t)cgd->ident_data.lba_size48_1) |
		    ((u_int64_t)cgd->ident_data.lba_size48_2 << 16) |
		    ((u_int64_t)cgd->ident_data.lba_size48_3 << 32) |
		    ((u_int64_t)cgd->ident_data.lba_size48_4 << 48);
	if ((cgd->ident_data.support.command2 & ATA_SUPPORT_ADDRESS48) &&
	    lbasize48 > ATA_MAX_28BIT_LBA)
		dp->sectors = lbasize48;

	maxio = softc->cpi.maxio;		/* Honor max I/O size of SIM */
	if (maxio == 0)
		maxio = DFLTPHYS;	/* traditional default */
	else if (maxio > MAXPHYS)
		maxio = MAXPHYS;	/* for safety */
	if (softc->flags & ADA_FLAG_CAN_48BIT)
		maxio = min(maxio, 65536 * softc->params.secsize);
	else					/* 28bit ATA command limit */
		maxio = min(maxio, 256 * softc->params.secsize);
	if (softc->quirks & ADA_Q_128KB)
		maxio = min(maxio, 128 * 1024);
	softc->disk->d_maxsize = maxio;
	d_flags = DISKFLAG_DIRECT_COMPLETION | DISKFLAG_CANZONE;
	if (softc->flags & ADA_FLAG_CAN_FLUSHCACHE)
		d_flags |= DISKFLAG_CANFLUSHCACHE;
	if (softc->flags & ADA_FLAG_CAN_TRIM) {
		d_flags |= DISKFLAG_CANDELETE;
		softc->disk->d_delmaxsize = softc->params.secsize *
		    ATA_DSM_RANGE_MAX * softc->trim_max_ranges;
	} else if ((softc->flags & ADA_FLAG_CAN_CFA) &&
	    !(softc->flags & ADA_FLAG_CAN_48BIT)) {
		d_flags |= DISKFLAG_CANDELETE;
		softc->disk->d_delmaxsize = 256 * softc->params.secsize;
	} else
		softc->disk->d_delmaxsize = maxio;
	if ((softc->cpi.hba_misc & PIM_UNMAPPED) != 0) {
		d_flags |= DISKFLAG_UNMAPPED_BIO;
		softc->unmappedio = 1;
	}
	softc->disk->d_flags = d_flags;
	strlcpy(softc->disk->d_descr, cgd->ident_data.model,
	    MIN(sizeof(softc->disk->d_descr), sizeof(cgd->ident_data.model)));
	strlcpy(softc->disk->d_ident, cgd->ident_data.serial,
	    MIN(sizeof(softc->disk->d_ident), sizeof(cgd->ident_data.serial)));

	softc->disk->d_sectorsize = softc->params.secsize;
	softc->disk->d_mediasize = (off_t)softc->params.sectors *
	    softc->params.secsize;
	if (ata_physical_sector_size(&cgd->ident_data) !=
	    softc->params.secsize) {
		softc->disk->d_stripesize =
		    ata_physical_sector_size(&cgd->ident_data);
		softc->disk->d_stripeoffset = (softc->disk->d_stripesize -
		    ata_logical_sector_offset(&cgd->ident_data)) %
		    softc->disk->d_stripesize;
	} else if (softc->quirks & ADA_Q_4K) {
		softc->disk->d_stripesize = 4096;
		softc->disk->d_stripeoffset = 0;
	}
	softc->disk->d_fwsectors = softc->params.secs_per_track;
	softc->disk->d_fwheads = softc->params.heads;
	ata_disk_firmware_geom_adjust(softc->disk);
	softc->disk->d_rotation_rate = cgd->ident_data.media_rotation_rate;
	snprintf(softc->disk->d_attachment, sizeof(softc->disk->d_attachment),
	    "%s%d", softc->cpi.dev_name, softc->cpi.unit_number);
}

static void
adasendorderedtag(void *arg)
{
	struct ada_softc *softc = arg;

	if (ada_send_ordered) {
		if (softc->outstanding_cmds > 0) {
			if ((softc->flags & ADA_FLAG_WAS_OTAG) == 0)
				softc->flags |= ADA_FLAG_NEED_OTAG;
			softc->flags &= ~ADA_FLAG_WAS_OTAG;
		}
	}
	/* Queue us up again */
	callout_reset(&softc->sendordered_c,
	    (ada_default_timeout * hz) / ADA_ORDEREDTAG_INTERVAL,
	    adasendorderedtag, softc);
}

/*
 * Step through all ADA peripheral drivers, and if the device is still open,
 * sync the disk cache to physical media.
 */
static void
adaflush(void)
{
	struct cam_periph *periph;
	struct ada_softc *softc;
	union ccb *ccb;
	int error;

	CAM_PERIPH_FOREACH(periph, &adadriver) {
		softc = (struct ada_softc *)periph->softc;
		if (SCHEDULER_STOPPED()) {
			/* If we paniced with the lock held, do not recurse. */
			if (!cam_periph_owned(periph) &&
			    (softc->flags & ADA_FLAG_OPEN)) {
				adadump(softc->disk, NULL, 0, 0, 0);
			}
			continue;
		}
		cam_periph_lock(periph);
		/*
		 * We only sync the cache if the drive is still open, and
		 * if the drive is capable of it..
		 */
		if (((softc->flags & ADA_FLAG_OPEN) == 0) ||
		    (softc->flags & ADA_FLAG_CAN_FLUSHCACHE) == 0) {
			cam_periph_unlock(periph);
			continue;
		}

		ccb = cam_periph_getccb(periph, CAM_PRIORITY_NORMAL);
		cam_fill_ataio(&ccb->ataio,
				    0,
				    NULL,
				    CAM_DIR_NONE,
				    0,
				    NULL,
				    0,
				    ada_default_timeout*1000);
		if (softc->flags & ADA_FLAG_CAN_48BIT)
			ata_48bit_cmd(&ccb->ataio, ATA_FLUSHCACHE48, 0, 0, 0);
		else
			ata_28bit_cmd(&ccb->ataio, ATA_FLUSHCACHE, 0, 0, 0);

		error = cam_periph_runccb(ccb, adaerror, /*cam_flags*/0,
		    /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
		    softc->disk->d_devstat);
		if (error != 0)
			xpt_print(periph->path, "Synchronize cache failed\n");
		xpt_release_ccb(ccb);
		cam_periph_unlock(periph);
	}
}

static void
adaspindown(uint8_t cmd, int flags)
{
	struct cam_periph *periph;
	struct ada_softc *softc;
	struct ccb_ataio local_ccb;
	int error;

	CAM_PERIPH_FOREACH(periph, &adadriver) {
		/* If we paniced with lock held - not recurse here. */
		if (cam_periph_owned(periph))
			continue;
		cam_periph_lock(periph);
		softc = (struct ada_softc *)periph->softc;
		/*
		 * We only spin-down the drive if it is capable of it..
		 */
		if ((softc->flags & ADA_FLAG_CAN_POWERMGT) == 0) {
			cam_periph_unlock(periph);
			continue;
		}

		if (bootverbose)
			xpt_print(periph->path, "spin-down\n");

		memset(&local_ccb, 0, sizeof(local_ccb));
		xpt_setup_ccb(&local_ccb.ccb_h, periph->path, CAM_PRIORITY_NORMAL);
		local_ccb.ccb_h.ccb_state = ADA_CCB_DUMP;

		cam_fill_ataio(&local_ccb,
				    0,
				    NULL,
				    CAM_DIR_NONE | flags,
				    0,
				    NULL,
				    0,
				    ada_default_timeout*1000);
		ata_28bit_cmd(&local_ccb, cmd, 0, 0, 0);
		error = cam_periph_runccb((union ccb *)&local_ccb, adaerror,
		    /*cam_flags*/0, /*sense_flags*/ SF_NO_RECOVERY | SF_NO_RETRY,
		    softc->disk->d_devstat);
		if (error != 0)
			xpt_print(periph->path, "Spin-down disk failed\n");
		cam_periph_unlock(periph);
	}
}

static void
adashutdown(void *arg, int howto)
{
	int how;

	adaflush();

	/*
	 * STANDBY IMMEDIATE saves any volatile data to the drive. It also spins
	 * down hard drives. IDLE IMMEDIATE also saves the volatile data without
	 * a spindown. We send the former when we expect to lose power soon. For
	 * a warm boot, we send the latter to avoid a thundering herd of spinups
	 * just after the kernel loads while probing. We have to do something to
	 * flush the data because the BIOS in many systems resets the HBA
	 * causing a COMINIT/COMRESET negotiation, which some drives interpret
	 * as license to toss the volatile data, and others count as unclean
	 * shutdown when in the Active PM state in SMART attributes.
	 *
	 * adaspindown will ensure that we don't send this to a drive that
	 * doesn't support it.
	 */
	if (ada_spindown_shutdown != 0) {
		how = (howto & (RB_HALT | RB_POWEROFF | RB_POWERCYCLE)) ?
		    ATA_STANDBY_IMMEDIATE : ATA_IDLE_IMMEDIATE;
		adaspindown(how, 0);
	}
}

static void
adasuspend(void *arg)
{

	adaflush();
	/*
	 * SLEEP also fushes any volatile data, like STANDBY IMEDIATE,
	 * so we don't need to send it as well.
	 */
	if (ada_spindown_suspend != 0)
		adaspindown(ATA_SLEEP, CAM_DEV_QFREEZE);
}

static void
adaresume(void *arg)
{
	struct cam_periph *periph;
	struct ada_softc *softc;

	if (ada_spindown_suspend == 0)
		return;

	CAM_PERIPH_FOREACH(periph, &adadriver) {
		cam_periph_lock(periph);
		softc = (struct ada_softc *)periph->softc;
		/*
		 * We only spin-down the drive if it is capable of it..
		 */
		if ((softc->flags & ADA_FLAG_CAN_POWERMGT) == 0) {
			cam_periph_unlock(periph);
			continue;
		}

		if (bootverbose)
			xpt_print(periph->path, "resume\n");

		/*
		 * Drop freeze taken due to CAM_DEV_QFREEZE flag set on
		 * sleep request.
		 */
		cam_release_devq(periph->path,
			 /*relsim_flags*/0,
			 /*openings*/0,
			 /*timeout*/0,
			 /*getcount_only*/0);

		cam_periph_unlock(periph);
	}
}

#endif /* _KERNEL */