aboutsummaryrefslogtreecommitdiff
path: root/sys/cam/cam_xpt.c
blob: 9cfee80a60494dc91f50f9180d6e0c72ee96647d (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
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
/*-
 * Implementation of the Common Access Method Transport (XPT) layer.
 *
 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
 *
 * Copyright (c) 1997, 1998, 1999 Justin T. Gibbs.
 * Copyright (c) 1997, 1998, 1999 Kenneth D. Merry.
 * 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. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "opt_printf.h"

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

#include <sys/param.h>
#include <sys/bio.h>
#include <sys/bus.h>
#include <sys/systm.h>
#include <sys/types.h>
#include <sys/malloc.h>
#include <sys/kernel.h>
#include <sys/time.h>
#include <sys/conf.h>
#include <sys/fcntl.h>
#include <sys/proc.h>
#include <sys/sbuf.h>
#include <sys/smp.h>
#include <sys/taskqueue.h>

#include <sys/lock.h>
#include <sys/mutex.h>
#include <sys/sysctl.h>
#include <sys/kthread.h>

#include <cam/cam.h>
#include <cam/cam_ccb.h>
#include <cam/cam_iosched.h>
#include <cam/cam_periph.h>
#include <cam/cam_queue.h>
#include <cam/cam_sim.h>
#include <cam/cam_xpt.h>
#include <cam/cam_xpt_sim.h>
#include <cam/cam_xpt_periph.h>
#include <cam/cam_xpt_internal.h>
#include <cam/cam_debug.h>
#include <cam/cam_compat.h>

#include <cam/scsi/scsi_all.h>
#include <cam/scsi/scsi_message.h>
#include <cam/scsi/scsi_pass.h>

#include <machine/stdarg.h>	/* for xpt_print below */

#include "opt_cam.h"

/* Wild guess based on not wanting to grow the stack too much */
#define XPT_PRINT_MAXLEN	512
#ifdef PRINTF_BUFR_SIZE
#define XPT_PRINT_LEN	PRINTF_BUFR_SIZE
#else
#define XPT_PRINT_LEN	128
#endif
_Static_assert(XPT_PRINT_LEN <= XPT_PRINT_MAXLEN, "XPT_PRINT_LEN is too large");

/*
 * This is the maximum number of high powered commands (e.g. start unit)
 * that can be outstanding at a particular time.
 */
#ifndef CAM_MAX_HIGHPOWER
#define CAM_MAX_HIGHPOWER  4
#endif

/* Datastructures internal to the xpt layer */
MALLOC_DEFINE(M_CAMXPT, "CAM XPT", "CAM XPT buffers");
MALLOC_DEFINE(M_CAMDEV, "CAM DEV", "CAM devices");
MALLOC_DEFINE(M_CAMCCB, "CAM CCB", "CAM CCBs");
MALLOC_DEFINE(M_CAMPATH, "CAM path", "CAM paths");

struct xpt_softc {
	uint32_t		xpt_generation;

	/* number of high powered commands that can go through right now */
	struct mtx		xpt_highpower_lock;
	STAILQ_HEAD(highpowerlist, cam_ed)	highpowerq;
	int			num_highpower;

	/* queue for handling async rescan requests. */
	TAILQ_HEAD(, ccb_hdr) ccb_scanq;
	int buses_to_config;
	int buses_config_done;
	int announce_nosbuf;

	/*
	 * Registered buses
	 *
	 * N.B., "busses" is an archaic spelling of "buses".  In new code
	 * "buses" is preferred.
	 */
	TAILQ_HEAD(,cam_eb)	xpt_busses;
	u_int			bus_generation;

	int			boot_delay;
	struct callout 		boot_callout;
	struct task		boot_task;
	struct root_hold_token	xpt_rootmount;

	struct mtx		xpt_topo_lock;
	struct taskqueue	*xpt_taskq;
};

typedef enum {
	DM_RET_COPY		= 0x01,
	DM_RET_FLAG_MASK	= 0x0f,
	DM_RET_NONE		= 0x00,
	DM_RET_STOP		= 0x10,
	DM_RET_DESCEND		= 0x20,
	DM_RET_ERROR		= 0x30,
	DM_RET_ACTION_MASK	= 0xf0
} dev_match_ret;

typedef enum {
	XPT_DEPTH_BUS,
	XPT_DEPTH_TARGET,
	XPT_DEPTH_DEVICE,
	XPT_DEPTH_PERIPH
} xpt_traverse_depth;

struct xpt_traverse_config {
	xpt_traverse_depth	depth;
	void			*tr_func;
	void			*tr_arg;
};

typedef	int	xpt_busfunc_t (struct cam_eb *bus, void *arg);
typedef	int	xpt_targetfunc_t (struct cam_et *target, void *arg);
typedef	int	xpt_devicefunc_t (struct cam_ed *device, void *arg);
typedef	int	xpt_periphfunc_t (struct cam_periph *periph, void *arg);
typedef int	xpt_pdrvfunc_t (struct periph_driver **pdrv, void *arg);

/* Transport layer configuration information */
static struct xpt_softc xsoftc;

MTX_SYSINIT(xpt_topo_init, &xsoftc.xpt_topo_lock, "XPT topology lock", MTX_DEF);

SYSCTL_INT(_kern_cam, OID_AUTO, boot_delay, CTLFLAG_RDTUN,
           &xsoftc.boot_delay, 0, "Bus registration wait time");
SYSCTL_UINT(_kern_cam, OID_AUTO, xpt_generation, CTLFLAG_RD,
	    &xsoftc.xpt_generation, 0, "CAM peripheral generation count");
SYSCTL_INT(_kern_cam, OID_AUTO, announce_nosbuf, CTLFLAG_RWTUN,
	    &xsoftc.announce_nosbuf, 0, "Don't use sbuf for announcements");

struct cam_doneq {
	struct mtx_padalign	cam_doneq_mtx;
	STAILQ_HEAD(, ccb_hdr)	cam_doneq;
	int			cam_doneq_sleep;
};

static struct cam_doneq cam_doneqs[MAXCPU];
static u_int __read_mostly cam_num_doneqs;
static struct proc *cam_proc;

SYSCTL_INT(_kern_cam, OID_AUTO, num_doneqs, CTLFLAG_RDTUN,
           &cam_num_doneqs, 0, "Number of completion queues/threads");

struct cam_periph *xpt_periph;

static periph_init_t xpt_periph_init;

static struct periph_driver xpt_driver =
{
	xpt_periph_init, "xpt",
	TAILQ_HEAD_INITIALIZER(xpt_driver.units), /* generation */ 0,
	CAM_PERIPH_DRV_EARLY
};

PERIPHDRIVER_DECLARE(xpt, xpt_driver);

static d_open_t xptopen;
static d_close_t xptclose;
static d_ioctl_t xptioctl;
static d_ioctl_t xptdoioctl;

static struct cdevsw xpt_cdevsw = {
	.d_version =	D_VERSION,
	.d_flags =	0,
	.d_open =	xptopen,
	.d_close =	xptclose,
	.d_ioctl =	xptioctl,
	.d_name =	"xpt",
};

/* Storage for debugging datastructures */
struct cam_path *cam_dpath;
u_int32_t __read_mostly cam_dflags = CAM_DEBUG_FLAGS;
SYSCTL_UINT(_kern_cam, OID_AUTO, dflags, CTLFLAG_RWTUN,
	&cam_dflags, 0, "Enabled debug flags");
u_int32_t cam_debug_delay = CAM_DEBUG_DELAY;
SYSCTL_UINT(_kern_cam, OID_AUTO, debug_delay, CTLFLAG_RWTUN,
	&cam_debug_delay, 0, "Delay in us after each debug message");

/* Our boot-time initialization hook */
static int cam_module_event_handler(module_t, int /*modeventtype_t*/, void *);

static moduledata_t cam_moduledata = {
	"cam",
	cam_module_event_handler,
	NULL
};

static int	xpt_init(void *);

DECLARE_MODULE(cam, cam_moduledata, SI_SUB_CONFIGURE, SI_ORDER_SECOND);
MODULE_VERSION(cam, 1);

static void		xpt_async_bcast(struct async_list *async_head,
					u_int32_t async_code,
					struct cam_path *path,
					void *async_arg);
static path_id_t xptnextfreepathid(void);
static path_id_t xptpathid(const char *sim_name, int sim_unit, int sim_bus);
static union ccb *xpt_get_ccb(struct cam_periph *periph);
static union ccb *xpt_get_ccb_nowait(struct cam_periph *periph);
static void	 xpt_run_allocq(struct cam_periph *periph, int sleep);
static void	 xpt_run_allocq_task(void *context, int pending);
static void	 xpt_run_devq(struct cam_devq *devq);
static callout_func_t xpt_release_devq_timeout;
static void	 xpt_acquire_bus(struct cam_eb *bus);
static void	 xpt_release_bus(struct cam_eb *bus);
static uint32_t	 xpt_freeze_devq_device(struct cam_ed *dev, u_int count);
static int	 xpt_release_devq_device(struct cam_ed *dev, u_int count,
		    int run_queue);
static struct cam_et*
		 xpt_alloc_target(struct cam_eb *bus, target_id_t target_id);
static void	 xpt_acquire_target(struct cam_et *target);
static void	 xpt_release_target(struct cam_et *target);
static struct cam_eb*
		 xpt_find_bus(path_id_t path_id);
static struct cam_et*
		 xpt_find_target(struct cam_eb *bus, target_id_t target_id);
static struct cam_ed*
		 xpt_find_device(struct cam_et *target, lun_id_t lun_id);
static void	 xpt_config(void *arg);
static void	 xpt_hold_boot_locked(void);
static int	 xpt_schedule_dev(struct camq *queue, cam_pinfo *dev_pinfo,
				 u_int32_t new_priority);
static xpt_devicefunc_t xptpassannouncefunc;
static void	 xptaction(struct cam_sim *sim, union ccb *work_ccb);
static void	 xptpoll(struct cam_sim *sim);
static void	 camisr_runqueue(void);
static void	 xpt_done_process(struct ccb_hdr *ccb_h);
static void	 xpt_done_td(void *);
static dev_match_ret	xptbusmatch(struct dev_match_pattern *patterns,
				    u_int num_patterns, struct cam_eb *bus);
static dev_match_ret	xptdevicematch(struct dev_match_pattern *patterns,
				       u_int num_patterns,
				       struct cam_ed *device);
static dev_match_ret	xptperiphmatch(struct dev_match_pattern *patterns,
				       u_int num_patterns,
				       struct cam_periph *periph);
static xpt_busfunc_t	xptedtbusfunc;
static xpt_targetfunc_t	xptedttargetfunc;
static xpt_devicefunc_t	xptedtdevicefunc;
static xpt_periphfunc_t	xptedtperiphfunc;
static xpt_pdrvfunc_t	xptplistpdrvfunc;
static xpt_periphfunc_t	xptplistperiphfunc;
static int		xptedtmatch(struct ccb_dev_match *cdm);
static int		xptperiphlistmatch(struct ccb_dev_match *cdm);
static int		xptbustraverse(struct cam_eb *start_bus,
				       xpt_busfunc_t *tr_func, void *arg);
static int		xpttargettraverse(struct cam_eb *bus,
					  struct cam_et *start_target,
					  xpt_targetfunc_t *tr_func, void *arg);
static int		xptdevicetraverse(struct cam_et *target,
					  struct cam_ed *start_device,
					  xpt_devicefunc_t *tr_func, void *arg);
static int		xptperiphtraverse(struct cam_ed *device,
					  struct cam_periph *start_periph,
					  xpt_periphfunc_t *tr_func, void *arg);
static int		xptpdrvtraverse(struct periph_driver **start_pdrv,
					xpt_pdrvfunc_t *tr_func, void *arg);
static int		xptpdperiphtraverse(struct periph_driver **pdrv,
					    struct cam_periph *start_periph,
					    xpt_periphfunc_t *tr_func,
					    void *arg);
static xpt_busfunc_t	xptdefbusfunc;
static xpt_targetfunc_t	xptdeftargetfunc;
static xpt_devicefunc_t	xptdefdevicefunc;
static xpt_periphfunc_t	xptdefperiphfunc;
static void		xpt_finishconfig_task(void *context, int pending);
static void		xpt_dev_async_default(u_int32_t async_code,
					      struct cam_eb *bus,
					      struct cam_et *target,
					      struct cam_ed *device,
					      void *async_arg);
static struct cam_ed *	xpt_alloc_device_default(struct cam_eb *bus,
						 struct cam_et *target,
						 lun_id_t lun_id);
static xpt_devicefunc_t	xptsetasyncfunc;
static xpt_busfunc_t	xptsetasyncbusfunc;
static cam_status	xptregister(struct cam_periph *periph,
				    void *arg);

static __inline int
xpt_schedule_devq(struct cam_devq *devq, struct cam_ed *dev)
{
	int	retval;

	mtx_assert(&devq->send_mtx, MA_OWNED);
	if ((dev->ccbq.queue.entries > 0) &&
	    (dev->ccbq.dev_openings > 0) &&
	    (dev->ccbq.queue.qfrozen_cnt == 0)) {
		/*
		 * The priority of a device waiting for controller
		 * resources is that of the highest priority CCB
		 * enqueued.
		 */
		retval =
		    xpt_schedule_dev(&devq->send_queue,
				     &dev->devq_entry,
				     CAMQ_GET_PRIO(&dev->ccbq.queue));
	} else {
		retval = 0;
	}
	return (retval);
}

static __inline int
device_is_queued(struct cam_ed *device)
{
	return (device->devq_entry.index != CAM_UNQUEUED_INDEX);
}

static void
xpt_periph_init(void)
{
	make_dev(&xpt_cdevsw, 0, UID_ROOT, GID_OPERATOR, 0600, "xpt0");
}

static int
xptopen(struct cdev *dev, int flags, int fmt, struct thread *td)
{

	/*
	 * Only allow read-write access.
	 */
	if (((flags & FWRITE) == 0) || ((flags & FREAD) == 0))
		return(EPERM);

	/*
	 * We don't allow nonblocking access.
	 */
	if ((flags & O_NONBLOCK) != 0) {
		printf("%s: can't do nonblocking access\n", devtoname(dev));
		return(ENODEV);
	}

	return(0);
}

static int
xptclose(struct cdev *dev, int flag, int fmt, struct thread *td)
{

	return(0);
}

/*
 * Don't automatically grab the xpt softc lock here even though this is going
 * through the xpt device.  The xpt device is really just a back door for
 * accessing other devices and SIMs, so the right thing to do is to grab
 * the appropriate SIM lock once the bus/SIM is located.
 */
static int
xptioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
{
	int error;

	if ((error = xptdoioctl(dev, cmd, addr, flag, td)) == ENOTTY) {
		error = cam_compat_ioctl(dev, cmd, addr, flag, td, xptdoioctl);
	}
	return (error);
}

static int
xptdoioctl(struct cdev *dev, u_long cmd, caddr_t addr, int flag, struct thread *td)
{
	int error;

	error = 0;

	switch(cmd) {
	/*
	 * For the transport layer CAMIOCOMMAND ioctl, we really only want
	 * to accept CCB types that don't quite make sense to send through a
	 * passthrough driver. XPT_PATH_INQ is an exception to this, as stated
	 * in the CAM spec.
	 */
	case CAMIOCOMMAND: {
		union ccb *ccb;
		union ccb *inccb;
		struct cam_eb *bus;

		inccb = (union ccb *)addr;
#if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
		if (inccb->ccb_h.func_code == XPT_SCSI_IO)
			inccb->csio.bio = NULL;
#endif

		if (inccb->ccb_h.flags & CAM_UNLOCKED)
			return (EINVAL);

		bus = xpt_find_bus(inccb->ccb_h.path_id);
		if (bus == NULL)
			return (EINVAL);

		switch (inccb->ccb_h.func_code) {
		case XPT_SCAN_BUS:
		case XPT_RESET_BUS:
			if (inccb->ccb_h.target_id != CAM_TARGET_WILDCARD ||
			    inccb->ccb_h.target_lun != CAM_LUN_WILDCARD) {
				xpt_release_bus(bus);
				return (EINVAL);
			}
			break;
		case XPT_SCAN_TGT:
			if (inccb->ccb_h.target_id == CAM_TARGET_WILDCARD ||
			    inccb->ccb_h.target_lun != CAM_LUN_WILDCARD) {
				xpt_release_bus(bus);
				return (EINVAL);
			}
			break;
		default:
			break;
		}

		switch(inccb->ccb_h.func_code) {
		case XPT_SCAN_BUS:
		case XPT_RESET_BUS:
		case XPT_PATH_INQ:
		case XPT_ENG_INQ:
		case XPT_SCAN_LUN:
		case XPT_SCAN_TGT:

			ccb = xpt_alloc_ccb();

			/*
			 * Create a path using the bus, target, and lun the
			 * user passed in.
			 */
			if (xpt_create_path(&ccb->ccb_h.path, NULL,
					    inccb->ccb_h.path_id,
					    inccb->ccb_h.target_id,
					    inccb->ccb_h.target_lun) !=
					    CAM_REQ_CMP){
				error = EINVAL;
				xpt_free_ccb(ccb);
				break;
			}
			/* Ensure all of our fields are correct */
			xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path,
				      inccb->ccb_h.pinfo.priority);
			xpt_merge_ccb(ccb, inccb);
			xpt_path_lock(ccb->ccb_h.path);
			cam_periph_runccb(ccb, NULL, 0, 0, NULL);
			xpt_path_unlock(ccb->ccb_h.path);
			bcopy(ccb, inccb, sizeof(union ccb));
			xpt_free_path(ccb->ccb_h.path);
			xpt_free_ccb(ccb);
			break;

		case XPT_DEBUG: {
			union ccb ccb;

			/*
			 * This is an immediate CCB, so it's okay to
			 * allocate it on the stack.
			 */

			/*
			 * Create a path using the bus, target, and lun the
			 * user passed in.
			 */
			if (xpt_create_path(&ccb.ccb_h.path, NULL,
					    inccb->ccb_h.path_id,
					    inccb->ccb_h.target_id,
					    inccb->ccb_h.target_lun) !=
					    CAM_REQ_CMP){
				error = EINVAL;
				break;
			}
			/* Ensure all of our fields are correct */
			xpt_setup_ccb(&ccb.ccb_h, ccb.ccb_h.path,
				      inccb->ccb_h.pinfo.priority);
			xpt_merge_ccb(&ccb, inccb);
			xpt_action(&ccb);
			bcopy(&ccb, inccb, sizeof(union ccb));
			xpt_free_path(ccb.ccb_h.path);
			break;
		}
		case XPT_DEV_MATCH: {
			struct cam_periph_map_info mapinfo;
			struct cam_path *old_path;

			/*
			 * We can't deal with physical addresses for this
			 * type of transaction.
			 */
			if ((inccb->ccb_h.flags & CAM_DATA_MASK) !=
			    CAM_DATA_VADDR) {
				error = EINVAL;
				break;
			}

			/*
			 * Save this in case the caller had it set to
			 * something in particular.
			 */
			old_path = inccb->ccb_h.path;

			/*
			 * We really don't need a path for the matching
			 * code.  The path is needed because of the
			 * debugging statements in xpt_action().  They
			 * assume that the CCB has a valid path.
			 */
			inccb->ccb_h.path = xpt_periph->path;

			bzero(&mapinfo, sizeof(mapinfo));

			/*
			 * Map the pattern and match buffers into kernel
			 * virtual address space.
			 */
			error = cam_periph_mapmem(inccb, &mapinfo, maxphys);

			if (error) {
				inccb->ccb_h.path = old_path;
				break;
			}

			/*
			 * This is an immediate CCB, we can send it on directly.
			 */
			xpt_action(inccb);

			/*
			 * Map the buffers back into user space.
			 */
			cam_periph_unmapmem(inccb, &mapinfo);

			inccb->ccb_h.path = old_path;

			error = 0;
			break;
		}
		default:
			error = ENOTSUP;
			break;
		}
		xpt_release_bus(bus);
		break;
	}
	/*
	 * This is the getpassthru ioctl. It takes a XPT_GDEVLIST ccb as input,
	 * with the periphal driver name and unit name filled in.  The other
	 * fields don't really matter as input.  The passthrough driver name
	 * ("pass"), and unit number are passed back in the ccb.  The current
	 * device generation number, and the index into the device peripheral
	 * driver list, and the status are also passed back.  Note that
	 * since we do everything in one pass, unlike the XPT_GDEVLIST ccb,
	 * we never return a status of CAM_GDEVLIST_LIST_CHANGED.  It is
	 * (or rather should be) impossible for the device peripheral driver
	 * list to change since we look at the whole thing in one pass, and
	 * we do it with lock protection.
	 *
	 */
	case CAMGETPASSTHRU: {
		union ccb *ccb;
		struct cam_periph *periph;
		struct periph_driver **p_drv;
		char   *name;
		u_int unit;
		int base_periph_found;

		ccb = (union ccb *)addr;
		unit = ccb->cgdl.unit_number;
		name = ccb->cgdl.periph_name;
		base_periph_found = 0;
#if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
		if (ccb->ccb_h.func_code == XPT_SCSI_IO)
			ccb->csio.bio = NULL;
#endif

		/*
		 * Sanity check -- make sure we don't get a null peripheral
		 * driver name.
		 */
		if (*ccb->cgdl.periph_name == '\0') {
			error = EINVAL;
			break;
		}

		/* Keep the list from changing while we traverse it */
		xpt_lock_buses();

		/* first find our driver in the list of drivers */
		for (p_drv = periph_drivers; *p_drv != NULL; p_drv++)
			if (strcmp((*p_drv)->driver_name, name) == 0)
				break;

		if (*p_drv == NULL) {
			xpt_unlock_buses();
			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
			ccb->cgdl.status = CAM_GDEVLIST_ERROR;
			*ccb->cgdl.periph_name = '\0';
			ccb->cgdl.unit_number = 0;
			error = ENOENT;
			break;
		}

		/*
		 * Run through every peripheral instance of this driver
		 * and check to see whether it matches the unit passed
		 * in by the user.  If it does, get out of the loops and
		 * find the passthrough driver associated with that
		 * peripheral driver.
		 */
		for (periph = TAILQ_FIRST(&(*p_drv)->units); periph != NULL;
		     periph = TAILQ_NEXT(periph, unit_links)) {
			if (periph->unit_number == unit)
				break;
		}
		/*
		 * If we found the peripheral driver that the user passed
		 * in, go through all of the peripheral drivers for that
		 * particular device and look for a passthrough driver.
		 */
		if (periph != NULL) {
			struct cam_ed *device;
			int i;

			base_periph_found = 1;
			device = periph->path->device;
			for (i = 0, periph = SLIST_FIRST(&device->periphs);
			     periph != NULL;
			     periph = SLIST_NEXT(periph, periph_links), i++) {
				/*
				 * Check to see whether we have a
				 * passthrough device or not.
				 */
				if (strcmp(periph->periph_name, "pass") == 0) {
					/*
					 * Fill in the getdevlist fields.
					 */
					strlcpy(ccb->cgdl.periph_name,
					       periph->periph_name,
					       sizeof(ccb->cgdl.periph_name));
					ccb->cgdl.unit_number =
						periph->unit_number;
					if (SLIST_NEXT(periph, periph_links))
						ccb->cgdl.status =
							CAM_GDEVLIST_MORE_DEVS;
					else
						ccb->cgdl.status =
						       CAM_GDEVLIST_LAST_DEVICE;
					ccb->cgdl.generation =
						device->generation;
					ccb->cgdl.index = i;
					/*
					 * Fill in some CCB header fields
					 * that the user may want.
					 */
					ccb->ccb_h.path_id =
						periph->path->bus->path_id;
					ccb->ccb_h.target_id =
						periph->path->target->target_id;
					ccb->ccb_h.target_lun =
						periph->path->device->lun_id;
					ccb->ccb_h.status = CAM_REQ_CMP;
					break;
				}
			}
		}

		/*
		 * If the periph is null here, one of two things has
		 * happened.  The first possibility is that we couldn't
		 * find the unit number of the particular peripheral driver
		 * that the user is asking about.  e.g. the user asks for
		 * the passthrough driver for "da11".  We find the list of
		 * "da" peripherals all right, but there is no unit 11.
		 * The other possibility is that we went through the list
		 * of peripheral drivers attached to the device structure,
		 * but didn't find one with the name "pass".  Either way,
		 * we return ENOENT, since we couldn't find something.
		 */
		if (periph == NULL) {
			ccb->ccb_h.status = CAM_REQ_CMP_ERR;
			ccb->cgdl.status = CAM_GDEVLIST_ERROR;
			*ccb->cgdl.periph_name = '\0';
			ccb->cgdl.unit_number = 0;
			error = ENOENT;
			/*
			 * It is unfortunate that this is even necessary,
			 * but there are many, many clueless users out there.
			 * If this is true, the user is looking for the
			 * passthrough driver, but doesn't have one in his
			 * kernel.
			 */
			if (base_periph_found == 1) {
				printf("xptioctl: pass driver is not in the "
				       "kernel\n");
				printf("xptioctl: put \"device pass\" in "
				       "your kernel config file\n");
			}
		}
		xpt_unlock_buses();
		break;
		}
	default:
		error = ENOTTY;
		break;
	}

	return(error);
}

static int
cam_module_event_handler(module_t mod, int what, void *arg)
{
	int error;

	switch (what) {
	case MOD_LOAD:
		if ((error = xpt_init(NULL)) != 0)
			return (error);
		break;
	case MOD_UNLOAD:
		return EBUSY;
	default:
		return EOPNOTSUPP;
	}

	return 0;
}

static struct xpt_proto *
xpt_proto_find(cam_proto proto)
{
	struct xpt_proto **pp;

	SET_FOREACH(pp, cam_xpt_proto_set) {
		if ((*pp)->proto == proto)
			return *pp;
	}

	return NULL;
}

static void
xpt_rescan_done(struct cam_periph *periph, union ccb *done_ccb)
{

	if (done_ccb->ccb_h.ppriv_ptr1 == NULL) {
		xpt_free_path(done_ccb->ccb_h.path);
		xpt_free_ccb(done_ccb);
	} else {
		done_ccb->ccb_h.cbfcnp = done_ccb->ccb_h.ppriv_ptr1;
		(*done_ccb->ccb_h.cbfcnp)(periph, done_ccb);
	}
	xpt_release_boot();
}

/* thread to handle bus rescans */
static void
xpt_scanner_thread(void *dummy)
{
	union ccb	*ccb;
	struct mtx	*mtx;
	struct cam_ed	*device;

	xpt_lock_buses();
	for (;;) {
		if (TAILQ_EMPTY(&xsoftc.ccb_scanq))
			msleep(&xsoftc.ccb_scanq, &xsoftc.xpt_topo_lock, PRIBIO,
			       "-", 0);
		if ((ccb = (union ccb *)TAILQ_FIRST(&xsoftc.ccb_scanq)) != NULL) {
			TAILQ_REMOVE(&xsoftc.ccb_scanq, &ccb->ccb_h, sim_links.tqe);
			xpt_unlock_buses();

			/*
			 * We need to lock the device's mutex which we use as
			 * the path mutex. We can't do it directly because the
			 * cam_path in the ccb may wind up going away because
			 * the path lock may be dropped and the path retired in
			 * the completion callback. We do this directly to keep
			 * the reference counts in cam_path sane. We also have
			 * to copy the device pointer because ccb_h.path may
			 * be freed in the callback.
			 */
			mtx = xpt_path_mtx(ccb->ccb_h.path);
			device = ccb->ccb_h.path->device;
			xpt_acquire_device(device);
			mtx_lock(mtx);
			xpt_action(ccb);
			mtx_unlock(mtx);
			xpt_release_device(device);

			xpt_lock_buses();
		}
	}
}

void
xpt_rescan(union ccb *ccb)
{
	struct ccb_hdr *hdr;

	/* Prepare request */
	if (ccb->ccb_h.path->target->target_id == CAM_TARGET_WILDCARD &&
	    ccb->ccb_h.path->device->lun_id == CAM_LUN_WILDCARD)
		ccb->ccb_h.func_code = XPT_SCAN_BUS;
	else if (ccb->ccb_h.path->target->target_id != CAM_TARGET_WILDCARD &&
	    ccb->ccb_h.path->device->lun_id == CAM_LUN_WILDCARD)
		ccb->ccb_h.func_code = XPT_SCAN_TGT;
	else if (ccb->ccb_h.path->target->target_id != CAM_TARGET_WILDCARD &&
	    ccb->ccb_h.path->device->lun_id != CAM_LUN_WILDCARD)
		ccb->ccb_h.func_code = XPT_SCAN_LUN;
	else {
		xpt_print(ccb->ccb_h.path, "illegal scan path\n");
		xpt_free_path(ccb->ccb_h.path);
		xpt_free_ccb(ccb);
		return;
	}
	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
	    ("xpt_rescan: func %#x %s\n", ccb->ccb_h.func_code,
 		xpt_action_name(ccb->ccb_h.func_code)));

	ccb->ccb_h.ppriv_ptr1 = ccb->ccb_h.cbfcnp;
	ccb->ccb_h.cbfcnp = xpt_rescan_done;
	xpt_setup_ccb(&ccb->ccb_h, ccb->ccb_h.path, CAM_PRIORITY_XPT);
	/* Don't make duplicate entries for the same paths. */
	xpt_lock_buses();
	if (ccb->ccb_h.ppriv_ptr1 == NULL) {
		TAILQ_FOREACH(hdr, &xsoftc.ccb_scanq, sim_links.tqe) {
			if (xpt_path_comp(hdr->path, ccb->ccb_h.path) == 0) {
				wakeup(&xsoftc.ccb_scanq);
				xpt_unlock_buses();
				xpt_print(ccb->ccb_h.path, "rescan already queued\n");
				xpt_free_path(ccb->ccb_h.path);
				xpt_free_ccb(ccb);
				return;
			}
		}
	}
	TAILQ_INSERT_TAIL(&xsoftc.ccb_scanq, &ccb->ccb_h, sim_links.tqe);
	xpt_hold_boot_locked();
	wakeup(&xsoftc.ccb_scanq);
	xpt_unlock_buses();
}

/* Functions accessed by the peripheral drivers */
static int
xpt_init(void *dummy)
{
	struct cam_sim *xpt_sim;
	struct cam_path *path;
	struct cam_devq *devq;
	cam_status status;
	int error, i;

	TAILQ_INIT(&xsoftc.xpt_busses);
	TAILQ_INIT(&xsoftc.ccb_scanq);
	STAILQ_INIT(&xsoftc.highpowerq);
	xsoftc.num_highpower = CAM_MAX_HIGHPOWER;

	mtx_init(&xsoftc.xpt_highpower_lock, "XPT highpower lock", NULL, MTX_DEF);
	xsoftc.xpt_taskq = taskqueue_create("CAM XPT task", M_WAITOK,
	    taskqueue_thread_enqueue, /*context*/&xsoftc.xpt_taskq);

#ifdef CAM_BOOT_DELAY
	/*
	 * Override this value at compile time to assist our users
	 * who don't use loader to boot a kernel.
	 */
	xsoftc.boot_delay = CAM_BOOT_DELAY;
#endif

	/*
	 * The xpt layer is, itself, the equivalent of a SIM.
	 * Allow 16 ccbs in the ccb pool for it.  This should
	 * give decent parallelism when we probe buses and
	 * perform other XPT functions.
	 */
	devq = cam_simq_alloc(16);
	xpt_sim = cam_sim_alloc(xptaction,
				xptpoll,
				"xpt",
				/*softc*/NULL,
				/*unit*/0,
				/*mtx*/NULL,
				/*max_dev_transactions*/0,
				/*max_tagged_dev_transactions*/0,
				devq);
	if (xpt_sim == NULL)
		return (ENOMEM);

	if ((status = xpt_bus_register(xpt_sim, NULL, 0)) != CAM_SUCCESS) {
		printf("xpt_init: xpt_bus_register failed with status %#x,"
		       " failing attach\n", status);
		return (EINVAL);
	}

	/*
	 * Looking at the XPT from the SIM layer, the XPT is
	 * the equivalent of a peripheral driver.  Allocate
	 * a peripheral driver entry for us.
	 */
	if ((status = xpt_create_path(&path, NULL, CAM_XPT_PATH_ID,
				      CAM_TARGET_WILDCARD,
				      CAM_LUN_WILDCARD)) != CAM_REQ_CMP) {
		printf("xpt_init: xpt_create_path failed with status %#x,"
		       " failing attach\n", status);
		return (EINVAL);
	}
	xpt_path_lock(path);
	cam_periph_alloc(xptregister, NULL, NULL, NULL, "xpt", CAM_PERIPH_BIO,
			 path, NULL, 0, xpt_sim);
	xpt_path_unlock(path);
	xpt_free_path(path);

	if (cam_num_doneqs < 1)
		cam_num_doneqs = 1 + mp_ncpus / 6;
	else if (cam_num_doneqs > MAXCPU)
		cam_num_doneqs = MAXCPU;
	for (i = 0; i < cam_num_doneqs; i++) {
		mtx_init(&cam_doneqs[i].cam_doneq_mtx, "CAM doneq", NULL,
		    MTX_DEF);
		STAILQ_INIT(&cam_doneqs[i].cam_doneq);
		error = kproc_kthread_add(xpt_done_td, &cam_doneqs[i],
		    &cam_proc, NULL, 0, 0, "cam", "doneq%d", i);
		if (error != 0) {
			cam_num_doneqs = i;
			break;
		}
	}
	if (cam_num_doneqs < 1) {
		printf("xpt_init: Cannot init completion queues "
		       "- failing attach\n");
		return (ENOMEM);
	}

	/*
	 * Register a callback for when interrupts are enabled.
	 */
	config_intrhook_oneshot(xpt_config, NULL);

	return (0);
}

static cam_status
xptregister(struct cam_periph *periph, void *arg)
{
	struct cam_sim *xpt_sim;

	if (periph == NULL) {
		printf("xptregister: periph was NULL!!\n");
		return(CAM_REQ_CMP_ERR);
	}

	xpt_sim = (struct cam_sim *)arg;
	xpt_sim->softc = periph;
	xpt_periph = periph;
	periph->softc = NULL;

	return(CAM_REQ_CMP);
}

int32_t
xpt_add_periph(struct cam_periph *periph)
{
	struct cam_ed *device;
	int32_t	 status;

	TASK_INIT(&periph->periph_run_task, 0, xpt_run_allocq_task, periph);
	device = periph->path->device;
	status = CAM_REQ_CMP;
	if (device != NULL) {
		mtx_lock(&device->target->bus->eb_mtx);
		device->generation++;
		SLIST_INSERT_HEAD(&device->periphs, periph, periph_links);
		mtx_unlock(&device->target->bus->eb_mtx);
		atomic_add_32(&xsoftc.xpt_generation, 1);
	}

	return (status);
}

void
xpt_remove_periph(struct cam_periph *periph)
{
	struct cam_ed *device;

	device = periph->path->device;
	if (device != NULL) {
		mtx_lock(&device->target->bus->eb_mtx);
		device->generation++;
		SLIST_REMOVE(&device->periphs, periph, cam_periph, periph_links);
		mtx_unlock(&device->target->bus->eb_mtx);
		atomic_add_32(&xsoftc.xpt_generation, 1);
	}
}

void
xpt_announce_periph(struct cam_periph *periph, char *announce_string)
{
	struct	cam_path *path = periph->path;
	struct  xpt_proto *proto;

	cam_periph_assert(periph, MA_OWNED);
	periph->flags |= CAM_PERIPH_ANNOUNCED;

	printf("%s%d at %s%d bus %d scbus%d target %d lun %jx\n",
	       periph->periph_name, periph->unit_number,
	       path->bus->sim->sim_name,
	       path->bus->sim->unit_number,
	       path->bus->sim->bus_id,
	       path->bus->path_id,
	       path->target->target_id,
	       (uintmax_t)path->device->lun_id);
	printf("%s%d: ", periph->periph_name, periph->unit_number);
	proto = xpt_proto_find(path->device->protocol);
	if (proto)
		proto->ops->announce(path->device);
	else
		printf("%s%d: Unknown protocol device %d\n",
		    periph->periph_name, periph->unit_number,
		    path->device->protocol);
	if (path->device->serial_num_len > 0) {
		/* Don't wrap the screen  - print only the first 60 chars */
		printf("%s%d: Serial Number %.60s\n", periph->periph_name,
		       periph->unit_number, path->device->serial_num);
	}
	/* Announce transport details. */
	path->bus->xport->ops->announce(periph);
	/* Announce command queueing. */
	if (path->device->inq_flags & SID_CmdQue
	 || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
		printf("%s%d: Command Queueing enabled\n",
		       periph->periph_name, periph->unit_number);
	}
	/* Announce caller's details if they've passed in. */
	if (announce_string != NULL)
		printf("%s%d: %s\n", periph->periph_name,
		       periph->unit_number, announce_string);
}

void
xpt_announce_periph_sbuf(struct cam_periph *periph, struct sbuf *sb,
    char *announce_string)
{
	struct	cam_path *path = periph->path;
	struct  xpt_proto *proto;

	cam_periph_assert(periph, MA_OWNED);
	periph->flags |= CAM_PERIPH_ANNOUNCED;

	/* Fall back to the non-sbuf method if necessary */
	if (xsoftc.announce_nosbuf != 0) {
		xpt_announce_periph(periph, announce_string);
		return;
	}
	proto = xpt_proto_find(path->device->protocol);
	if (((proto != NULL) && (proto->ops->announce_sbuf == NULL)) ||
	    (path->bus->xport->ops->announce_sbuf == NULL)) {
		xpt_announce_periph(periph, announce_string);
		return;
	}

	sbuf_printf(sb, "%s%d at %s%d bus %d scbus%d target %d lun %jx\n",
	    periph->periph_name, periph->unit_number,
	    path->bus->sim->sim_name,
	    path->bus->sim->unit_number,
	    path->bus->sim->bus_id,
	    path->bus->path_id,
	    path->target->target_id,
	    (uintmax_t)path->device->lun_id);
	sbuf_printf(sb, "%s%d: ", periph->periph_name, periph->unit_number);

	if (proto)
		proto->ops->announce_sbuf(path->device, sb);
	else
		sbuf_printf(sb, "%s%d: Unknown protocol device %d\n",
		    periph->periph_name, periph->unit_number,
		    path->device->protocol);
	if (path->device->serial_num_len > 0) {
		/* Don't wrap the screen  - print only the first 60 chars */
		sbuf_printf(sb, "%s%d: Serial Number %.60s\n",
		    periph->periph_name, periph->unit_number,
		    path->device->serial_num);
	}
	/* Announce transport details. */
	path->bus->xport->ops->announce_sbuf(periph, sb);
	/* Announce command queueing. */
	if (path->device->inq_flags & SID_CmdQue
	 || path->device->flags & CAM_DEV_TAG_AFTER_COUNT) {
		sbuf_printf(sb, "%s%d: Command Queueing enabled\n",
		    periph->periph_name, periph->unit_number);
	}
	/* Announce caller's details if they've passed in. */
	if (announce_string != NULL)
		sbuf_printf(sb, "%s%d: %s\n", periph->periph_name,
		    periph->unit_number, announce_string);
}

void
xpt_announce_quirks(struct cam_periph *periph, int quirks, char *bit_string)
{
	if (quirks != 0) {
		printf("%s%d: quirks=0x%b\n", periph->periph_name,
		    periph->unit_number, quirks, bit_string);
	}
}

void
xpt_announce_quirks_sbuf(struct cam_periph *periph, struct sbuf *sb,
			 int quirks, char *bit_string)
{
	if (xsoftc.announce_nosbuf != 0) {
		xpt_announce_quirks(periph, quirks, bit_string);
		return;
	}

	if (quirks != 0) {
		sbuf_printf(sb, "%s%d: quirks=0x%b\n", periph->periph_name,
		    periph->unit_number, quirks, bit_string);
	}
}

void
xpt_denounce_periph(struct cam_periph *periph)
{
	struct	cam_path *path = periph->path;
	struct  xpt_proto *proto;

	cam_periph_assert(periph, MA_OWNED);
	printf("%s%d at %s%d bus %d scbus%d target %d lun %jx\n",
	       periph->periph_name, periph->unit_number,
	       path->bus->sim->sim_name,
	       path->bus->sim->unit_number,
	       path->bus->sim->bus_id,
	       path->bus->path_id,
	       path->target->target_id,
	       (uintmax_t)path->device->lun_id);
	printf("%s%d: ", periph->periph_name, periph->unit_number);
	proto = xpt_proto_find(path->device->protocol);
	if (proto)
		proto->ops->denounce(path->device);
	else
		printf("%s%d: Unknown protocol device %d\n",
		    periph->periph_name, periph->unit_number,
		    path->device->protocol);
	if (path->device->serial_num_len > 0)
		printf(" s/n %.60s", path->device->serial_num);
	printf(" detached\n");
}

void
xpt_denounce_periph_sbuf(struct cam_periph *periph, struct sbuf *sb)
{
	struct cam_path *path = periph->path;
	struct xpt_proto *proto;

	cam_periph_assert(periph, MA_OWNED);

	/* Fall back to the non-sbuf method if necessary */
	if (xsoftc.announce_nosbuf != 0) {
		xpt_denounce_periph(periph);
		return;
	}
	proto = xpt_proto_find(path->device->protocol);
	if ((proto != NULL) && (proto->ops->denounce_sbuf == NULL)) {
		xpt_denounce_periph(periph);
		return;
	}

	sbuf_printf(sb, "%s%d at %s%d bus %d scbus%d target %d lun %jx\n",
	    periph->periph_name, periph->unit_number,
	    path->bus->sim->sim_name,
	    path->bus->sim->unit_number,
	    path->bus->sim->bus_id,
	    path->bus->path_id,
	    path->target->target_id,
	    (uintmax_t)path->device->lun_id);
	sbuf_printf(sb, "%s%d: ", periph->periph_name, periph->unit_number);

	if (proto)
		proto->ops->denounce_sbuf(path->device, sb);
	else
		sbuf_printf(sb, "%s%d: Unknown protocol device %d\n",
		    periph->periph_name, periph->unit_number,
		    path->device->protocol);
	if (path->device->serial_num_len > 0)
		sbuf_printf(sb, " s/n %.60s", path->device->serial_num);
	sbuf_printf(sb, " detached\n");
}

int
xpt_getattr(char *buf, size_t len, const char *attr, struct cam_path *path)
{
	int ret = -1, l, o;
	struct ccb_dev_advinfo cdai;
	struct scsi_vpd_device_id *did;
	struct scsi_vpd_id_descriptor *idd;

	xpt_path_assert(path, MA_OWNED);

	memset(&cdai, 0, sizeof(cdai));
	xpt_setup_ccb(&cdai.ccb_h, path, CAM_PRIORITY_NORMAL);
	cdai.ccb_h.func_code = XPT_DEV_ADVINFO;
	cdai.flags = CDAI_FLAG_NONE;
	cdai.bufsiz = len;
	cdai.buf = buf;

	if (!strcmp(attr, "GEOM::ident"))
		cdai.buftype = CDAI_TYPE_SERIAL_NUM;
	else if (!strcmp(attr, "GEOM::physpath"))
		cdai.buftype = CDAI_TYPE_PHYS_PATH;
	else if (strcmp(attr, "GEOM::lunid") == 0 ||
		 strcmp(attr, "GEOM::lunname") == 0) {
		cdai.buftype = CDAI_TYPE_SCSI_DEVID;
		cdai.bufsiz = CAM_SCSI_DEVID_MAXLEN;
		cdai.buf = malloc(cdai.bufsiz, M_CAMXPT, M_NOWAIT);
		if (cdai.buf == NULL) {
			ret = ENOMEM;
			goto out;
		}
	} else
		goto out;

	xpt_action((union ccb *)&cdai); /* can only be synchronous */
	if ((cdai.ccb_h.status & CAM_DEV_QFRZN) != 0)
		cam_release_devq(cdai.ccb_h.path, 0, 0, 0, FALSE);
	if (cdai.provsiz == 0)
		goto out;
	switch(cdai.buftype) {
	case CDAI_TYPE_SCSI_DEVID:
		did = (struct scsi_vpd_device_id *)cdai.buf;
		if (strcmp(attr, "GEOM::lunid") == 0) {
			idd = scsi_get_devid(did, cdai.provsiz,
			    scsi_devid_is_lun_naa);
			if (idd == NULL)
				idd = scsi_get_devid(did, cdai.provsiz,
				    scsi_devid_is_lun_eui64);
			if (idd == NULL)
				idd = scsi_get_devid(did, cdai.provsiz,
				    scsi_devid_is_lun_uuid);
			if (idd == NULL)
				idd = scsi_get_devid(did, cdai.provsiz,
				    scsi_devid_is_lun_md5);
		} else
			idd = NULL;

		if (idd == NULL)
			idd = scsi_get_devid(did, cdai.provsiz,
			    scsi_devid_is_lun_t10);
		if (idd == NULL)
			idd = scsi_get_devid(did, cdai.provsiz,
			    scsi_devid_is_lun_name);
		if (idd == NULL)
			break;

		ret = 0;
		if ((idd->proto_codeset & SVPD_ID_CODESET_MASK) ==
		    SVPD_ID_CODESET_ASCII) {
			if (idd->length < len) {
				for (l = 0; l < idd->length; l++)
					buf[l] = idd->identifier[l] ?
					    idd->identifier[l] : ' ';
				buf[l] = 0;
			} else
				ret = EFAULT;
			break;
		}
		if ((idd->proto_codeset & SVPD_ID_CODESET_MASK) ==
		    SVPD_ID_CODESET_UTF8) {
			l = strnlen(idd->identifier, idd->length);
			if (l < len) {
				bcopy(idd->identifier, buf, l);
				buf[l] = 0;
			} else
				ret = EFAULT;
			break;
		}
		if ((idd->id_type & SVPD_ID_TYPE_MASK) ==
		    SVPD_ID_TYPE_UUID && idd->identifier[0] == 0x10) {
			if ((idd->length - 2) * 2 + 4 >= len) {
				ret = EFAULT;
				break;
			}
			for (l = 2, o = 0; l < idd->length; l++) {
				if (l == 6 || l == 8 || l == 10 || l == 12)
				    o += sprintf(buf + o, "-");
				o += sprintf(buf + o, "%02x",
				    idd->identifier[l]);
			}
			break;
		}
		if (idd->length * 2 < len) {
			for (l = 0; l < idd->length; l++)
				sprintf(buf + l * 2, "%02x",
				    idd->identifier[l]);
		} else
				ret = EFAULT;
		break;
	default:
		if (cdai.provsiz < len) {
			cdai.buf[cdai.provsiz] = 0;
			ret = 0;
		} else
			ret = EFAULT;
		break;
	}

out:
	if ((char *)cdai.buf != buf)
		free(cdai.buf, M_CAMXPT);
	return ret;
}

static dev_match_ret
xptbusmatch(struct dev_match_pattern *patterns, u_int num_patterns,
	    struct cam_eb *bus)
{
	dev_match_ret retval;
	u_int i;

	retval = DM_RET_NONE;

	/*
	 * If we aren't given something to match against, that's an error.
	 */
	if (bus == NULL)
		return(DM_RET_ERROR);

	/*
	 * If there are no match entries, then this bus matches no
	 * matter what.
	 */
	if ((patterns == NULL) || (num_patterns == 0))
		return(DM_RET_DESCEND | DM_RET_COPY);

	for (i = 0; i < num_patterns; i++) {
		struct bus_match_pattern *cur_pattern;

		/*
		 * If the pattern in question isn't for a bus node, we
		 * aren't interested.  However, we do indicate to the
		 * calling routine that we should continue descending the
		 * tree, since the user wants to match against lower-level
		 * EDT elements.
		 */
		if (patterns[i].type != DEV_MATCH_BUS) {
			if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
				retval |= DM_RET_DESCEND;
			continue;
		}

		cur_pattern = &patterns[i].pattern.bus_pattern;

		/*
		 * If they want to match any bus node, we give them any
		 * device node.
		 */
		if (cur_pattern->flags == BUS_MATCH_ANY) {
			/* set the copy flag */
			retval |= DM_RET_COPY;

			/*
			 * If we've already decided on an action, go ahead
			 * and return.
			 */
			if ((retval & DM_RET_ACTION_MASK) != DM_RET_NONE)
				return(retval);
		}

		/*
		 * Not sure why someone would do this...
		 */
		if (cur_pattern->flags == BUS_MATCH_NONE)
			continue;

		if (((cur_pattern->flags & BUS_MATCH_PATH) != 0)
		 && (cur_pattern->path_id != bus->path_id))
			continue;

		if (((cur_pattern->flags & BUS_MATCH_BUS_ID) != 0)
		 && (cur_pattern->bus_id != bus->sim->bus_id))
			continue;

		if (((cur_pattern->flags & BUS_MATCH_UNIT) != 0)
		 && (cur_pattern->unit_number != bus->sim->unit_number))
			continue;

		if (((cur_pattern->flags & BUS_MATCH_NAME) != 0)
		 && (strncmp(cur_pattern->dev_name, bus->sim->sim_name,
			     DEV_IDLEN) != 0))
			continue;

		/*
		 * If we get to this point, the user definitely wants
		 * information on this bus.  So tell the caller to copy the
		 * data out.
		 */
		retval |= DM_RET_COPY;

		/*
		 * If the return action has been set to descend, then we
		 * know that we've already seen a non-bus matching
		 * expression, therefore we need to further descend the tree.
		 * This won't change by continuing around the loop, so we
		 * go ahead and return.  If we haven't seen a non-bus
		 * matching expression, we keep going around the loop until
		 * we exhaust the matching expressions.  We'll set the stop
		 * flag once we fall out of the loop.
		 */
		if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
			return(retval);
	}

	/*
	 * If the return action hasn't been set to descend yet, that means
	 * we haven't seen anything other than bus matching patterns.  So
	 * tell the caller to stop descending the tree -- the user doesn't
	 * want to match against lower level tree elements.
	 */
	if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
		retval |= DM_RET_STOP;

	return(retval);
}

static dev_match_ret
xptdevicematch(struct dev_match_pattern *patterns, u_int num_patterns,
	       struct cam_ed *device)
{
	dev_match_ret retval;
	u_int i;

	retval = DM_RET_NONE;

	/*
	 * If we aren't given something to match against, that's an error.
	 */
	if (device == NULL)
		return(DM_RET_ERROR);

	/*
	 * If there are no match entries, then this device matches no
	 * matter what.
	 */
	if ((patterns == NULL) || (num_patterns == 0))
		return(DM_RET_DESCEND | DM_RET_COPY);

	for (i = 0; i < num_patterns; i++) {
		struct device_match_pattern *cur_pattern;
		struct scsi_vpd_device_id *device_id_page;

		/*
		 * If the pattern in question isn't for a device node, we
		 * aren't interested.
		 */
		if (patterns[i].type != DEV_MATCH_DEVICE) {
			if ((patterns[i].type == DEV_MATCH_PERIPH)
			 && ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE))
				retval |= DM_RET_DESCEND;
			continue;
		}

		cur_pattern = &patterns[i].pattern.device_pattern;

		/* Error out if mutually exclusive options are specified. */
		if ((cur_pattern->flags & (DEV_MATCH_INQUIRY|DEV_MATCH_DEVID))
		 == (DEV_MATCH_INQUIRY|DEV_MATCH_DEVID))
			return(DM_RET_ERROR);

		/*
		 * If they want to match any device node, we give them any
		 * device node.
		 */
		if (cur_pattern->flags == DEV_MATCH_ANY)
			goto copy_dev_node;

		/*
		 * Not sure why someone would do this...
		 */
		if (cur_pattern->flags == DEV_MATCH_NONE)
			continue;

		if (((cur_pattern->flags & DEV_MATCH_PATH) != 0)
		 && (cur_pattern->path_id != device->target->bus->path_id))
			continue;

		if (((cur_pattern->flags & DEV_MATCH_TARGET) != 0)
		 && (cur_pattern->target_id != device->target->target_id))
			continue;

		if (((cur_pattern->flags & DEV_MATCH_LUN) != 0)
		 && (cur_pattern->target_lun != device->lun_id))
			continue;

		if (((cur_pattern->flags & DEV_MATCH_INQUIRY) != 0)
		 && (cam_quirkmatch((caddr_t)&device->inq_data,
				    (caddr_t)&cur_pattern->data.inq_pat,
				    1, sizeof(cur_pattern->data.inq_pat),
				    scsi_static_inquiry_match) == NULL))
			continue;

		device_id_page = (struct scsi_vpd_device_id *)device->device_id;
		if (((cur_pattern->flags & DEV_MATCH_DEVID) != 0)
		 && (device->device_id_len < SVPD_DEVICE_ID_HDR_LEN
		  || scsi_devid_match((uint8_t *)device_id_page->desc_list,
				      device->device_id_len
				    - SVPD_DEVICE_ID_HDR_LEN,
				      cur_pattern->data.devid_pat.id,
				      cur_pattern->data.devid_pat.id_len) != 0))
			continue;

copy_dev_node:
		/*
		 * If we get to this point, the user definitely wants
		 * information on this device.  So tell the caller to copy
		 * the data out.
		 */
		retval |= DM_RET_COPY;

		/*
		 * If the return action has been set to descend, then we
		 * know that we've already seen a peripheral matching
		 * expression, therefore we need to further descend the tree.
		 * This won't change by continuing around the loop, so we
		 * go ahead and return.  If we haven't seen a peripheral
		 * matching expression, we keep going around the loop until
		 * we exhaust the matching expressions.  We'll set the stop
		 * flag once we fall out of the loop.
		 */
		if ((retval & DM_RET_ACTION_MASK) == DM_RET_DESCEND)
			return(retval);
	}

	/*
	 * If the return action hasn't been set to descend yet, that means
	 * we haven't seen any peripheral matching patterns.  So tell the
	 * caller to stop descending the tree -- the user doesn't want to
	 * match against lower level tree elements.
	 */
	if ((retval & DM_RET_ACTION_MASK) == DM_RET_NONE)
		retval |= DM_RET_STOP;

	return(retval);
}

/*
 * Match a single peripheral against any number of match patterns.
 */
static dev_match_ret
xptperiphmatch(struct dev_match_pattern *patterns, u_int num_patterns,
	       struct cam_periph *periph)
{
	dev_match_ret retval;
	u_int i;

	/*
	 * If we aren't given something to match against, that's an error.
	 */
	if (periph == NULL)
		return(DM_RET_ERROR);

	/*
	 * If there are no match entries, then this peripheral matches no
	 * matter what.
	 */
	if ((patterns == NULL) || (num_patterns == 0))
		return(DM_RET_STOP | DM_RET_COPY);

	/*
	 * There aren't any nodes below a peripheral node, so there's no
	 * reason to descend the tree any further.
	 */
	retval = DM_RET_STOP;

	for (i = 0; i < num_patterns; i++) {
		struct periph_match_pattern *cur_pattern;

		/*
		 * If the pattern in question isn't for a peripheral, we
		 * aren't interested.
		 */
		if (patterns[i].type != DEV_MATCH_PERIPH)
			continue;

		cur_pattern = &patterns[i].pattern.periph_pattern;

		/*
		 * If they want to match on anything, then we will do so.
		 */
		if (cur_pattern->flags == PERIPH_MATCH_ANY) {
			/* set the copy flag */
			retval |= DM_RET_COPY;

			/*
			 * We've already set the return action to stop,
			 * since there are no nodes below peripherals in
			 * the tree.
			 */
			return(retval);
		}

		/*
		 * Not sure why someone would do this...
		 */
		if (cur_pattern->flags == PERIPH_MATCH_NONE)
			continue;

		if (((cur_pattern->flags & PERIPH_MATCH_PATH) != 0)
		 && (cur_pattern->path_id != periph->path->bus->path_id))
			continue;

		/*
		 * For the target and lun id's, we have to make sure the
		 * target and lun pointers aren't NULL.  The xpt peripheral
		 * has a wildcard target and device.
		 */
		if (((cur_pattern->flags & PERIPH_MATCH_TARGET) != 0)
		 && ((periph->path->target == NULL)
		 ||(cur_pattern->target_id != periph->path->target->target_id)))
			continue;

		if (((cur_pattern->flags & PERIPH_MATCH_LUN) != 0)
		 && ((periph->path->device == NULL)
		 || (cur_pattern->target_lun != periph->path->device->lun_id)))
			continue;

		if (((cur_pattern->flags & PERIPH_MATCH_UNIT) != 0)
		 && (cur_pattern->unit_number != periph->unit_number))
			continue;

		if (((cur_pattern->flags & PERIPH_MATCH_NAME) != 0)
		 && (strncmp(cur_pattern->periph_name, periph->periph_name,
			     DEV_IDLEN) != 0))
			continue;

		/*
		 * If we get to this point, the user definitely wants
		 * information on this peripheral.  So tell the caller to
		 * copy the data out.
		 */
		retval |= DM_RET_COPY;

		/*
		 * The return action has already been set to stop, since
		 * peripherals don't have any nodes below them in the EDT.
		 */
		return(retval);
	}

	/*
	 * If we get to this point, the peripheral that was passed in
	 * doesn't match any of the patterns.
	 */
	return(retval);
}

static int
xptedtbusfunc(struct cam_eb *bus, void *arg)
{
	struct ccb_dev_match *cdm;
	struct cam_et *target;
	dev_match_ret retval;

	cdm = (struct ccb_dev_match *)arg;

	/*
	 * If our position is for something deeper in the tree, that means
	 * that we've already seen this node.  So, we keep going down.
	 */
	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
	 && (cdm->pos.cookie.bus == bus)
	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
	 && (cdm->pos.cookie.target != NULL))
		retval = DM_RET_DESCEND;
	else
		retval = xptbusmatch(cdm->patterns, cdm->num_patterns, bus);

	/*
	 * If we got an error, bail out of the search.
	 */
	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
		cdm->status = CAM_DEV_MATCH_ERROR;
		return(0);
	}

	/*
	 * If the copy flag is set, copy this bus out.
	 */
	if (retval & DM_RET_COPY) {
		int spaceleft, j;

		spaceleft = cdm->match_buf_len - (cdm->num_matches *
			sizeof(struct dev_match_result));

		/*
		 * If we don't have enough space to put in another
		 * match result, save our position and tell the
		 * user there are more devices to check.
		 */
		if (spaceleft < sizeof(struct dev_match_result)) {
			bzero(&cdm->pos, sizeof(cdm->pos));
			cdm->pos.position_type =
				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS;

			cdm->pos.cookie.bus = bus;
			cdm->pos.generations[CAM_BUS_GENERATION]=
				xsoftc.bus_generation;
			cdm->status = CAM_DEV_MATCH_MORE;
			return(0);
		}
		j = cdm->num_matches;
		cdm->num_matches++;
		cdm->matches[j].type = DEV_MATCH_BUS;
		cdm->matches[j].result.bus_result.path_id = bus->path_id;
		cdm->matches[j].result.bus_result.bus_id = bus->sim->bus_id;
		cdm->matches[j].result.bus_result.unit_number =
			bus->sim->unit_number;
		strlcpy(cdm->matches[j].result.bus_result.dev_name,
			bus->sim->sim_name,
			sizeof(cdm->matches[j].result.bus_result.dev_name));
	}

	/*
	 * If the user is only interested in buses, there's no
	 * reason to descend to the next level in the tree.
	 */
	if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
		return(1);

	/*
	 * If there is a target generation recorded, check it to
	 * make sure the target list hasn't changed.
	 */
	mtx_lock(&bus->eb_mtx);
	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
	 && (cdm->pos.cookie.bus == bus)
	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
	 && (cdm->pos.cookie.target != NULL)) {
		if ((cdm->pos.generations[CAM_TARGET_GENERATION] !=
		    bus->generation)) {
			mtx_unlock(&bus->eb_mtx);
			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
			return (0);
		}
		target = (struct cam_et *)cdm->pos.cookie.target;
		target->refcount++;
	} else
		target = NULL;
	mtx_unlock(&bus->eb_mtx);

	return (xpttargettraverse(bus, target, xptedttargetfunc, arg));
}

static int
xptedttargetfunc(struct cam_et *target, void *arg)
{
	struct ccb_dev_match *cdm;
	struct cam_eb *bus;
	struct cam_ed *device;

	cdm = (struct ccb_dev_match *)arg;
	bus = target->bus;

	/*
	 * If there is a device list generation recorded, check it to
	 * make sure the device list hasn't changed.
	 */
	mtx_lock(&bus->eb_mtx);
	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
	 && (cdm->pos.cookie.bus == bus)
	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
	 && (cdm->pos.cookie.target == target)
	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
	 && (cdm->pos.cookie.device != NULL)) {
		if (cdm->pos.generations[CAM_DEV_GENERATION] !=
		    target->generation) {
			mtx_unlock(&bus->eb_mtx);
			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
			return(0);
		}
		device = (struct cam_ed *)cdm->pos.cookie.device;
		device->refcount++;
	} else
		device = NULL;
	mtx_unlock(&bus->eb_mtx);

	return (xptdevicetraverse(target, device, xptedtdevicefunc, arg));
}

static int
xptedtdevicefunc(struct cam_ed *device, void *arg)
{
	struct cam_eb *bus;
	struct cam_periph *periph;
	struct ccb_dev_match *cdm;
	dev_match_ret retval;

	cdm = (struct ccb_dev_match *)arg;
	bus = device->target->bus;

	/*
	 * If our position is for something deeper in the tree, that means
	 * that we've already seen this node.  So, we keep going down.
	 */
	if ((cdm->pos.position_type & CAM_DEV_POS_DEVICE)
	 && (cdm->pos.cookie.device == device)
	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
	 && (cdm->pos.cookie.periph != NULL))
		retval = DM_RET_DESCEND;
	else
		retval = xptdevicematch(cdm->patterns, cdm->num_patterns,
					device);

	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
		cdm->status = CAM_DEV_MATCH_ERROR;
		return(0);
	}

	/*
	 * If the copy flag is set, copy this device out.
	 */
	if (retval & DM_RET_COPY) {
		int spaceleft, j;

		spaceleft = cdm->match_buf_len - (cdm->num_matches *
			sizeof(struct dev_match_result));

		/*
		 * If we don't have enough space to put in another
		 * match result, save our position and tell the
		 * user there are more devices to check.
		 */
		if (spaceleft < sizeof(struct dev_match_result)) {
			bzero(&cdm->pos, sizeof(cdm->pos));
			cdm->pos.position_type =
				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
				CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE;

			cdm->pos.cookie.bus = device->target->bus;
			cdm->pos.generations[CAM_BUS_GENERATION]=
				xsoftc.bus_generation;
			cdm->pos.cookie.target = device->target;
			cdm->pos.generations[CAM_TARGET_GENERATION] =
				device->target->bus->generation;
			cdm->pos.cookie.device = device;
			cdm->pos.generations[CAM_DEV_GENERATION] =
				device->target->generation;
			cdm->status = CAM_DEV_MATCH_MORE;
			return(0);
		}
		j = cdm->num_matches;
		cdm->num_matches++;
		cdm->matches[j].type = DEV_MATCH_DEVICE;
		cdm->matches[j].result.device_result.path_id =
			device->target->bus->path_id;
		cdm->matches[j].result.device_result.target_id =
			device->target->target_id;
		cdm->matches[j].result.device_result.target_lun =
			device->lun_id;
		cdm->matches[j].result.device_result.protocol =
			device->protocol;
		bcopy(&device->inq_data,
		      &cdm->matches[j].result.device_result.inq_data,
		      sizeof(struct scsi_inquiry_data));
		bcopy(&device->ident_data,
		      &cdm->matches[j].result.device_result.ident_data,
		      sizeof(struct ata_params));

		/* Let the user know whether this device is unconfigured */
		if (device->flags & CAM_DEV_UNCONFIGURED)
			cdm->matches[j].result.device_result.flags =
				DEV_RESULT_UNCONFIGURED;
		else
			cdm->matches[j].result.device_result.flags =
				DEV_RESULT_NOFLAG;
	}

	/*
	 * If the user isn't interested in peripherals, don't descend
	 * the tree any further.
	 */
	if ((retval & DM_RET_ACTION_MASK) == DM_RET_STOP)
		return(1);

	/*
	 * If there is a peripheral list generation recorded, make sure
	 * it hasn't changed.
	 */
	xpt_lock_buses();
	mtx_lock(&bus->eb_mtx);
	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
	 && (cdm->pos.cookie.bus == bus)
	 && (cdm->pos.position_type & CAM_DEV_POS_TARGET)
	 && (cdm->pos.cookie.target == device->target)
	 && (cdm->pos.position_type & CAM_DEV_POS_DEVICE)
	 && (cdm->pos.cookie.device == device)
	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
	 && (cdm->pos.cookie.periph != NULL)) {
		if (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
		    device->generation) {
			mtx_unlock(&bus->eb_mtx);
			xpt_unlock_buses();
			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
			return(0);
		}
		periph = (struct cam_periph *)cdm->pos.cookie.periph;
		periph->refcount++;
	} else
		periph = NULL;
	mtx_unlock(&bus->eb_mtx);
	xpt_unlock_buses();

	return (xptperiphtraverse(device, periph, xptedtperiphfunc, arg));
}

static int
xptedtperiphfunc(struct cam_periph *periph, void *arg)
{
	struct ccb_dev_match *cdm;
	dev_match_ret retval;

	cdm = (struct ccb_dev_match *)arg;

	retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);

	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
		cdm->status = CAM_DEV_MATCH_ERROR;
		return(0);
	}

	/*
	 * If the copy flag is set, copy this peripheral out.
	 */
	if (retval & DM_RET_COPY) {
		int spaceleft, j;
		size_t l;

		spaceleft = cdm->match_buf_len - (cdm->num_matches *
			sizeof(struct dev_match_result));

		/*
		 * If we don't have enough space to put in another
		 * match result, save our position and tell the
		 * user there are more devices to check.
		 */
		if (spaceleft < sizeof(struct dev_match_result)) {
			bzero(&cdm->pos, sizeof(cdm->pos));
			cdm->pos.position_type =
				CAM_DEV_POS_EDT | CAM_DEV_POS_BUS |
				CAM_DEV_POS_TARGET | CAM_DEV_POS_DEVICE |
				CAM_DEV_POS_PERIPH;

			cdm->pos.cookie.bus = periph->path->bus;
			cdm->pos.generations[CAM_BUS_GENERATION]=
				xsoftc.bus_generation;
			cdm->pos.cookie.target = periph->path->target;
			cdm->pos.generations[CAM_TARGET_GENERATION] =
				periph->path->bus->generation;
			cdm->pos.cookie.device = periph->path->device;
			cdm->pos.generations[CAM_DEV_GENERATION] =
				periph->path->target->generation;
			cdm->pos.cookie.periph = periph;
			cdm->pos.generations[CAM_PERIPH_GENERATION] =
				periph->path->device->generation;
			cdm->status = CAM_DEV_MATCH_MORE;
			return(0);
		}

		j = cdm->num_matches;
		cdm->num_matches++;
		cdm->matches[j].type = DEV_MATCH_PERIPH;
		cdm->matches[j].result.periph_result.path_id =
			periph->path->bus->path_id;
		cdm->matches[j].result.periph_result.target_id =
			periph->path->target->target_id;
		cdm->matches[j].result.periph_result.target_lun =
			periph->path->device->lun_id;
		cdm->matches[j].result.periph_result.unit_number =
			periph->unit_number;
		l = sizeof(cdm->matches[j].result.periph_result.periph_name);
		strlcpy(cdm->matches[j].result.periph_result.periph_name,
			periph->periph_name, l);
	}

	return(1);
}

static int
xptedtmatch(struct ccb_dev_match *cdm)
{
	struct cam_eb *bus;
	int ret;

	cdm->num_matches = 0;

	/*
	 * Check the bus list generation.  If it has changed, the user
	 * needs to reset everything and start over.
	 */
	xpt_lock_buses();
	if ((cdm->pos.position_type & CAM_DEV_POS_BUS)
	 && (cdm->pos.cookie.bus != NULL)) {
		if (cdm->pos.generations[CAM_BUS_GENERATION] !=
		    xsoftc.bus_generation) {
			xpt_unlock_buses();
			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
			return(0);
		}
		bus = (struct cam_eb *)cdm->pos.cookie.bus;
		bus->refcount++;
	} else
		bus = NULL;
	xpt_unlock_buses();

	ret = xptbustraverse(bus, xptedtbusfunc, cdm);

	/*
	 * If we get back 0, that means that we had to stop before fully
	 * traversing the EDT.  It also means that one of the subroutines
	 * has set the status field to the proper value.  If we get back 1,
	 * we've fully traversed the EDT and copied out any matching entries.
	 */
	if (ret == 1)
		cdm->status = CAM_DEV_MATCH_LAST;

	return(ret);
}

static int
xptplistpdrvfunc(struct periph_driver **pdrv, void *arg)
{
	struct cam_periph *periph;
	struct ccb_dev_match *cdm;

	cdm = (struct ccb_dev_match *)arg;

	xpt_lock_buses();
	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
	 && (cdm->pos.cookie.pdrv == pdrv)
	 && (cdm->pos.position_type & CAM_DEV_POS_PERIPH)
	 && (cdm->pos.cookie.periph != NULL)) {
		if (cdm->pos.generations[CAM_PERIPH_GENERATION] !=
		    (*pdrv)->generation) {
			xpt_unlock_buses();
			cdm->status = CAM_DEV_MATCH_LIST_CHANGED;
			return(0);
		}
		periph = (struct cam_periph *)cdm->pos.cookie.periph;
		periph->refcount++;
	} else
		periph = NULL;
	xpt_unlock_buses();

	return (xptpdperiphtraverse(pdrv, periph, xptplistperiphfunc, arg));
}

static int
xptplistperiphfunc(struct cam_periph *periph, void *arg)
{
	struct ccb_dev_match *cdm;
	dev_match_ret retval;

	cdm = (struct ccb_dev_match *)arg;

	retval = xptperiphmatch(cdm->patterns, cdm->num_patterns, periph);

	if ((retval & DM_RET_ACTION_MASK) == DM_RET_ERROR) {
		cdm->status = CAM_DEV_MATCH_ERROR;
		return(0);
	}

	/*
	 * If the copy flag is set, copy this peripheral out.
	 */
	if (retval & DM_RET_COPY) {
		int spaceleft, j;
		size_t l;

		spaceleft = cdm->match_buf_len - (cdm->num_matches *
			sizeof(struct dev_match_result));

		/*
		 * If we don't have enough space to put in another
		 * match result, save our position and tell the
		 * user there are more devices to check.
		 */
		if (spaceleft < sizeof(struct dev_match_result)) {
			struct periph_driver **pdrv;

			pdrv = NULL;
			bzero(&cdm->pos, sizeof(cdm->pos));
			cdm->pos.position_type =
				CAM_DEV_POS_PDRV | CAM_DEV_POS_PDPTR |
				CAM_DEV_POS_PERIPH;

			/*
			 * This may look a bit non-sensical, but it is
			 * actually quite logical.  There are very few
			 * peripheral drivers, and bloating every peripheral
			 * structure with a pointer back to its parent
			 * peripheral driver linker set entry would cost
			 * more in the long run than doing this quick lookup.
			 */
			for (pdrv = periph_drivers; *pdrv != NULL; pdrv++) {
				if (strcmp((*pdrv)->driver_name,
				    periph->periph_name) == 0)
					break;
			}

			if (*pdrv == NULL) {
				cdm->status = CAM_DEV_MATCH_ERROR;
				return(0);
			}

			cdm->pos.cookie.pdrv = pdrv;
			/*
			 * The periph generation slot does double duty, as
			 * does the periph pointer slot.  They are used for
			 * both edt and pdrv lookups and positioning.
			 */
			cdm->pos.cookie.periph = periph;
			cdm->pos.generations[CAM_PERIPH_GENERATION] =
				(*pdrv)->generation;
			cdm->status = CAM_DEV_MATCH_MORE;
			return(0);
		}

		j = cdm->num_matches;
		cdm->num_matches++;
		cdm->matches[j].type = DEV_MATCH_PERIPH;
		cdm->matches[j].result.periph_result.path_id =
			periph->path->bus->path_id;

		/*
		 * The transport layer peripheral doesn't have a target or
		 * lun.
		 */
		if (periph->path->target)
			cdm->matches[j].result.periph_result.target_id =
				periph->path->target->target_id;
		else
			cdm->matches[j].result.periph_result.target_id =
				CAM_TARGET_WILDCARD;

		if (periph->path->device)
			cdm->matches[j].result.periph_result.target_lun =
				periph->path->device->lun_id;
		else
			cdm->matches[j].result.periph_result.target_lun =
				CAM_LUN_WILDCARD;

		cdm->matches[j].result.periph_result.unit_number =
			periph->unit_number;
		l = sizeof(cdm->matches[j].result.periph_result.periph_name);
		strlcpy(cdm->matches[j].result.periph_result.periph_name,
			periph->periph_name, l);
	}

	return(1);
}

static int
xptperiphlistmatch(struct ccb_dev_match *cdm)
{
	int ret;

	cdm->num_matches = 0;

	/*
	 * At this point in the edt traversal function, we check the bus
	 * list generation to make sure that no buses have been added or
	 * removed since the user last sent a XPT_DEV_MATCH ccb through.
	 * For the peripheral driver list traversal function, however, we
	 * don't have to worry about new peripheral driver types coming or
	 * going; they're in a linker set, and therefore can't change
	 * without a recompile.
	 */

	if ((cdm->pos.position_type & CAM_DEV_POS_PDPTR)
	 && (cdm->pos.cookie.pdrv != NULL))
		ret = xptpdrvtraverse(
				(struct periph_driver **)cdm->pos.cookie.pdrv,
				xptplistpdrvfunc, cdm);
	else
		ret = xptpdrvtraverse(NULL, xptplistpdrvfunc, cdm);

	/*
	 * If we get back 0, that means that we had to stop before fully
	 * traversing the peripheral driver tree.  It also means that one of
	 * the subroutines has set the status field to the proper value.  If
	 * we get back 1, we've fully traversed the EDT and copied out any
	 * matching entries.
	 */
	if (ret == 1)
		cdm->status = CAM_DEV_MATCH_LAST;

	return(ret);
}

static int
xptbustraverse(struct cam_eb *start_bus, xpt_busfunc_t *tr_func, void *arg)
{
	struct cam_eb *bus, *next_bus;
	int retval;

	retval = 1;
	if (start_bus)
		bus = start_bus;
	else {
		xpt_lock_buses();
		bus = TAILQ_FIRST(&xsoftc.xpt_busses);
		if (bus == NULL) {
			xpt_unlock_buses();
			return (retval);
		}
		bus->refcount++;
		xpt_unlock_buses();
	}
	for (; bus != NULL; bus = next_bus) {
		retval = tr_func(bus, arg);
		if (retval == 0) {
			xpt_release_bus(bus);
			break;
		}
		xpt_lock_buses();
		next_bus = TAILQ_NEXT(bus, links);
		if (next_bus)
			next_bus->refcount++;
		xpt_unlock_buses();
		xpt_release_bus(bus);
	}
	return(retval);
}

static int
xpttargettraverse(struct cam_eb *bus, struct cam_et *start_target,
		  xpt_targetfunc_t *tr_func, void *arg)
{
	struct cam_et *target, *next_target;
	int retval;

	retval = 1;
	if (start_target)
		target = start_target;
	else {
		mtx_lock(&bus->eb_mtx);
		target = TAILQ_FIRST(&bus->et_entries);
		if (target == NULL) {
			mtx_unlock(&bus->eb_mtx);
			return (retval);
		}
		target->refcount++;
		mtx_unlock(&bus->eb_mtx);
	}
	for (; target != NULL; target = next_target) {
		retval = tr_func(target, arg);
		if (retval == 0) {
			xpt_release_target(target);
			break;
		}
		mtx_lock(&bus->eb_mtx);
		next_target = TAILQ_NEXT(target, links);
		if (next_target)
			next_target->refcount++;
		mtx_unlock(&bus->eb_mtx);
		xpt_release_target(target);
	}
	return(retval);
}

static int
xptdevicetraverse(struct cam_et *target, struct cam_ed *start_device,
		  xpt_devicefunc_t *tr_func, void *arg)
{
	struct cam_eb *bus;
	struct cam_ed *device, *next_device;
	int retval;

	retval = 1;
	bus = target->bus;
	if (start_device)
		device = start_device;
	else {
		mtx_lock(&bus->eb_mtx);
		device = TAILQ_FIRST(&target->ed_entries);
		if (device == NULL) {
			mtx_unlock(&bus->eb_mtx);
			return (retval);
		}
		device->refcount++;
		mtx_unlock(&bus->eb_mtx);
	}
	for (; device != NULL; device = next_device) {
		mtx_lock(&device->device_mtx);
		retval = tr_func(device, arg);
		mtx_unlock(&device->device_mtx);
		if (retval == 0) {
			xpt_release_device(device);
			break;
		}
		mtx_lock(&bus->eb_mtx);
		next_device = TAILQ_NEXT(device, links);
		if (next_device)
			next_device->refcount++;
		mtx_unlock(&bus->eb_mtx);
		xpt_release_device(device);
	}
	return(retval);
}

static int
xptperiphtraverse(struct cam_ed *device, struct cam_periph *start_periph,
		  xpt_periphfunc_t *tr_func, void *arg)
{
	struct cam_eb *bus;
	struct cam_periph *periph, *next_periph;
	int retval;

	retval = 1;

	bus = device->target->bus;
	if (start_periph)
		periph = start_periph;
	else {
		xpt_lock_buses();
		mtx_lock(&bus->eb_mtx);
		periph = SLIST_FIRST(&device->periphs);
		while (periph != NULL && (periph->flags & CAM_PERIPH_FREE) != 0)
			periph = SLIST_NEXT(periph, periph_links);
		if (periph == NULL) {
			mtx_unlock(&bus->eb_mtx);
			xpt_unlock_buses();
			return (retval);
		}
		periph->refcount++;
		mtx_unlock(&bus->eb_mtx);
		xpt_unlock_buses();
	}
	for (; periph != NULL; periph = next_periph) {
		retval = tr_func(periph, arg);
		if (retval == 0) {
			cam_periph_release_locked(periph);
			break;
		}
		xpt_lock_buses();
		mtx_lock(&bus->eb_mtx);
		next_periph = SLIST_NEXT(periph, periph_links);
		while (next_periph != NULL &&
		    (next_periph->flags & CAM_PERIPH_FREE) != 0)
			next_periph = SLIST_NEXT(next_periph, periph_links);
		if (next_periph)
			next_periph->refcount++;
		mtx_unlock(&bus->eb_mtx);
		xpt_unlock_buses();
		cam_periph_release_locked(periph);
	}
	return(retval);
}

static int
xptpdrvtraverse(struct periph_driver **start_pdrv,
		xpt_pdrvfunc_t *tr_func, void *arg)
{
	struct periph_driver **pdrv;
	int retval;

	retval = 1;

	/*
	 * We don't traverse the peripheral driver list like we do the
	 * other lists, because it is a linker set, and therefore cannot be
	 * changed during runtime.  If the peripheral driver list is ever
	 * re-done to be something other than a linker set (i.e. it can
	 * change while the system is running), the list traversal should
	 * be modified to work like the other traversal functions.
	 */
	for (pdrv = (start_pdrv ? start_pdrv : periph_drivers);
	     *pdrv != NULL; pdrv++) {
		retval = tr_func(pdrv, arg);

		if (retval == 0)
			return(retval);
	}

	return(retval);
}

static int
xptpdperiphtraverse(struct periph_driver **pdrv,
		    struct cam_periph *start_periph,
		    xpt_periphfunc_t *tr_func, void *arg)
{
	struct cam_periph *periph, *next_periph;
	int retval;

	retval = 1;

	if (start_periph)
		periph = start_periph;
	else {
		xpt_lock_buses();
		periph = TAILQ_FIRST(&(*pdrv)->units);
		while (periph != NULL && (periph->flags & CAM_PERIPH_FREE) != 0)
			periph = TAILQ_NEXT(periph, unit_links);
		if (periph == NULL) {
			xpt_unlock_buses();
			return (retval);
		}
		periph->refcount++;
		xpt_unlock_buses();
	}
	for (; periph != NULL; periph = next_periph) {
		cam_periph_lock(periph);
		retval = tr_func(periph, arg);
		cam_periph_unlock(periph);
		if (retval == 0) {
			cam_periph_release(periph);
			break;
		}
		xpt_lock_buses();
		next_periph = TAILQ_NEXT(periph, unit_links);
		while (next_periph != NULL &&
		    (next_periph->flags & CAM_PERIPH_FREE) != 0)
			next_periph = TAILQ_NEXT(next_periph, unit_links);
		if (next_periph)
			next_periph->refcount++;
		xpt_unlock_buses();
		cam_periph_release(periph);
	}
	return(retval);
}

static int
xptdefbusfunc(struct cam_eb *bus, void *arg)
{
	struct xpt_traverse_config *tr_config;

	tr_config = (struct xpt_traverse_config *)arg;

	if (tr_config->depth == XPT_DEPTH_BUS) {
		xpt_busfunc_t *tr_func;

		tr_func = (xpt_busfunc_t *)tr_config->tr_func;

		return(tr_func(bus, tr_config->tr_arg));
	} else
		return(xpttargettraverse(bus, NULL, xptdeftargetfunc, arg));
}

static int
xptdeftargetfunc(struct cam_et *target, void *arg)
{
	struct xpt_traverse_config *tr_config;

	tr_config = (struct xpt_traverse_config *)arg;

	if (tr_config->depth == XPT_DEPTH_TARGET) {
		xpt_targetfunc_t *tr_func;

		tr_func = (xpt_targetfunc_t *)tr_config->tr_func;

		return(tr_func(target, tr_config->tr_arg));
	} else
		return(xptdevicetraverse(target, NULL, xptdefdevicefunc, arg));
}

static int
xptdefdevicefunc(struct cam_ed *device, void *arg)
{
	struct xpt_traverse_config *tr_config;

	tr_config = (struct xpt_traverse_config *)arg;

	if (tr_config->depth == XPT_DEPTH_DEVICE) {
		xpt_devicefunc_t *tr_func;

		tr_func = (xpt_devicefunc_t *)tr_config->tr_func;

		return(tr_func(device, tr_config->tr_arg));
	} else
		return(xptperiphtraverse(device, NULL, xptdefperiphfunc, arg));
}

static int
xptdefperiphfunc(struct cam_periph *periph, void *arg)
{
	struct xpt_traverse_config *tr_config;
	xpt_periphfunc_t *tr_func;

	tr_config = (struct xpt_traverse_config *)arg;

	tr_func = (xpt_periphfunc_t *)tr_config->tr_func;

	/*
	 * Unlike the other default functions, we don't check for depth
	 * here.  The peripheral driver level is the last level in the EDT,
	 * so if we're here, we should execute the function in question.
	 */
	return(tr_func(periph, tr_config->tr_arg));
}

/*
 * Execute the given function for every bus in the EDT.
 */
static int
xpt_for_all_busses(xpt_busfunc_t *tr_func, void *arg)
{
	struct xpt_traverse_config tr_config;

	tr_config.depth = XPT_DEPTH_BUS;
	tr_config.tr_func = tr_func;
	tr_config.tr_arg = arg;

	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
}

/*
 * Execute the given function for every device in the EDT.
 */
static int
xpt_for_all_devices(xpt_devicefunc_t *tr_func, void *arg)
{
	struct xpt_traverse_config tr_config;

	tr_config.depth = XPT_DEPTH_DEVICE;
	tr_config.tr_func = tr_func;
	tr_config.tr_arg = arg;

	return(xptbustraverse(NULL, xptdefbusfunc, &tr_config));
}

static int
xptsetasyncfunc(struct cam_ed *device, void *arg)
{
	struct cam_path path;
	struct ccb_getdev cgd;
	struct ccb_setasync *csa = (struct ccb_setasync *)arg;

	/*
	 * Don't report unconfigured devices (Wildcard devs,
	 * devices only for target mode, device instances
	 * that have been invalidated but are waiting for
	 * their last reference count to be released).
	 */
	if ((device->flags & CAM_DEV_UNCONFIGURED) != 0)
		return (1);

	xpt_compile_path(&path,
			 NULL,
			 device->target->bus->path_id,
			 device->target->target_id,
			 device->lun_id);
	xpt_setup_ccb(&cgd.ccb_h, &path, CAM_PRIORITY_NORMAL);
	cgd.ccb_h.func_code = XPT_GDEV_TYPE;
	xpt_action((union ccb *)&cgd);
	csa->callback(csa->callback_arg,
			    AC_FOUND_DEVICE,
			    &path, &cgd);
	xpt_release_path(&path);

	return(1);
}

static int
xptsetasyncbusfunc(struct cam_eb *bus, void *arg)
{
	struct cam_path path;
	struct ccb_pathinq cpi;
	struct ccb_setasync *csa = (struct ccb_setasync *)arg;

	xpt_compile_path(&path, /*periph*/NULL,
			 bus->path_id,
			 CAM_TARGET_WILDCARD,
			 CAM_LUN_WILDCARD);
	xpt_path_lock(&path);
	xpt_path_inq(&cpi, &path);
	csa->callback(csa->callback_arg,
			    AC_PATH_REGISTERED,
			    &path, &cpi);
	xpt_path_unlock(&path);
	xpt_release_path(&path);

	return(1);
}

void
xpt_action(union ccb *start_ccb)
{

	CAM_DEBUG(start_ccb->ccb_h.path, CAM_DEBUG_TRACE,
	    ("xpt_action: func %#x %s\n", start_ccb->ccb_h.func_code,
		xpt_action_name(start_ccb->ccb_h.func_code)));

	start_ccb->ccb_h.status = CAM_REQ_INPROG;
	(*(start_ccb->ccb_h.path->bus->xport->ops->action))(start_ccb);
}

void
xpt_action_default(union ccb *start_ccb)
{
	struct cam_path *path;
	struct cam_sim *sim;
	struct mtx *mtx;

	path = start_ccb->ccb_h.path;
	CAM_DEBUG(path, CAM_DEBUG_TRACE,
	    ("xpt_action_default: func %#x %s\n", start_ccb->ccb_h.func_code,
		xpt_action_name(start_ccb->ccb_h.func_code)));

	switch (start_ccb->ccb_h.func_code) {
	case XPT_SCSI_IO:
	{
		struct cam_ed *device;

		/*
		 * For the sake of compatibility with SCSI-1
		 * devices that may not understand the identify
		 * message, we include lun information in the
		 * second byte of all commands.  SCSI-1 specifies
		 * that luns are a 3 bit value and reserves only 3
		 * bits for lun information in the CDB.  Later
		 * revisions of the SCSI spec allow for more than 8
		 * luns, but have deprecated lun information in the
		 * CDB.  So, if the lun won't fit, we must omit.
		 *
		 * Also be aware that during initial probing for devices,
		 * the inquiry information is unknown but initialized to 0.
		 * This means that this code will be exercised while probing
		 * devices with an ANSI revision greater than 2.
		 */
		device = path->device;
		if (device->protocol_version <= SCSI_REV_2
		 && start_ccb->ccb_h.target_lun < 8
		 && (start_ccb->ccb_h.flags & CAM_CDB_POINTER) == 0) {
			start_ccb->csio.cdb_io.cdb_bytes[1] |=
			    start_ccb->ccb_h.target_lun << 5;
		}
		start_ccb->csio.scsi_status = SCSI_STATUS_OK;
	}
	/* FALLTHROUGH */
	case XPT_TARGET_IO:
	case XPT_CONT_TARGET_IO:
		start_ccb->csio.sense_resid = 0;
		start_ccb->csio.resid = 0;
		/* FALLTHROUGH */
	case XPT_ATA_IO:
		if (start_ccb->ccb_h.func_code == XPT_ATA_IO)
			start_ccb->ataio.resid = 0;
		/* FALLTHROUGH */
	case XPT_NVME_IO:
	case XPT_NVME_ADMIN:
	case XPT_MMC_IO:
	case XPT_RESET_DEV:
	case XPT_ENG_EXEC:
	case XPT_SMP_IO:
	{
		struct cam_devq *devq;

		devq = path->bus->sim->devq;
		mtx_lock(&devq->send_mtx);
		cam_ccbq_insert_ccb(&path->device->ccbq, start_ccb);
		if (xpt_schedule_devq(devq, path->device) != 0)
			xpt_run_devq(devq);
		mtx_unlock(&devq->send_mtx);
		break;
	}
	case XPT_CALC_GEOMETRY:
		/* Filter out garbage */
		if (start_ccb->ccg.block_size == 0
		 || start_ccb->ccg.volume_size == 0) {
			start_ccb->ccg.cylinders = 0;
			start_ccb->ccg.heads = 0;
			start_ccb->ccg.secs_per_track = 0;
			start_ccb->ccb_h.status = CAM_REQ_CMP;
			break;
		}
		goto call_sim;
	case XPT_ABORT:
	{
		union ccb* abort_ccb;

		abort_ccb = start_ccb->cab.abort_ccb;
		if (XPT_FC_IS_DEV_QUEUED(abort_ccb)) {
			struct cam_ed *device;
			struct cam_devq *devq;

			device = abort_ccb->ccb_h.path->device;
			devq = device->sim->devq;

			mtx_lock(&devq->send_mtx);
			if (abort_ccb->ccb_h.pinfo.index > 0) {
				cam_ccbq_remove_ccb(&device->ccbq, abort_ccb);
				abort_ccb->ccb_h.status =
				    CAM_REQ_ABORTED|CAM_DEV_QFRZN;
				xpt_freeze_devq_device(device, 1);
				mtx_unlock(&devq->send_mtx);
				xpt_done(abort_ccb);
				start_ccb->ccb_h.status = CAM_REQ_CMP;
				break;
			}
			mtx_unlock(&devq->send_mtx);

			if (abort_ccb->ccb_h.pinfo.index == CAM_UNQUEUED_INDEX
			 && (abort_ccb->ccb_h.status & CAM_SIM_QUEUED) == 0) {
				/*
				 * We've caught this ccb en route to
				 * the SIM.  Flag it for abort and the
				 * SIM will do so just before starting
				 * real work on the CCB.
				 */
				abort_ccb->ccb_h.status =
				    CAM_REQ_ABORTED|CAM_DEV_QFRZN;
				xpt_freeze_devq(abort_ccb->ccb_h.path, 1);
				start_ccb->ccb_h.status = CAM_REQ_CMP;
				break;
			}
		}
		if (XPT_FC_IS_QUEUED(abort_ccb)
		 && (abort_ccb->ccb_h.pinfo.index == CAM_DONEQ_INDEX)) {
			/*
			 * It's already completed but waiting
			 * for our SWI to get to it.
			 */
			start_ccb->ccb_h.status = CAM_UA_ABORT;
			break;
		}
		/*
		 * If we weren't able to take care of the abort request
		 * in the XPT, pass the request down to the SIM for processing.
		 */
	}
	/* FALLTHROUGH */
	case XPT_ACCEPT_TARGET_IO:
	case XPT_EN_LUN:
	case XPT_IMMED_NOTIFY:
	case XPT_NOTIFY_ACK:
	case XPT_RESET_BUS:
	case XPT_IMMEDIATE_NOTIFY:
	case XPT_NOTIFY_ACKNOWLEDGE:
	case XPT_GET_SIM_KNOB_OLD:
	case XPT_GET_SIM_KNOB:
	case XPT_SET_SIM_KNOB:
	case XPT_GET_TRAN_SETTINGS:
	case XPT_SET_TRAN_SETTINGS:
	case XPT_PATH_INQ:
call_sim:
		sim = path->bus->sim;
		mtx = sim->mtx;
		if (mtx && !mtx_owned(mtx))
			mtx_lock(mtx);
		else
			mtx = NULL;

		CAM_DEBUG(path, CAM_DEBUG_TRACE,
		    ("Calling sim->sim_action(): func=%#x\n", start_ccb->ccb_h.func_code));
		(*(sim->sim_action))(sim, start_ccb);
		CAM_DEBUG(path, CAM_DEBUG_TRACE,
		    ("sim->sim_action returned: status=%#x\n", start_ccb->ccb_h.status));
		if (mtx)
			mtx_unlock(mtx);
		break;
	case XPT_PATH_STATS:
		start_ccb->cpis.last_reset = path->bus->last_reset;
		start_ccb->ccb_h.status = CAM_REQ_CMP;
		break;
	case XPT_GDEV_TYPE:
	{
		struct cam_ed *dev;

		dev = path->device;
		if ((dev->flags & CAM_DEV_UNCONFIGURED) != 0) {
			start_ccb->ccb_h.status = CAM_DEV_NOT_THERE;
		} else {
			struct ccb_getdev *cgd;

			cgd = &start_ccb->cgd;
			cgd->protocol = dev->protocol;
			cgd->inq_data = dev->inq_data;
			cgd->ident_data = dev->ident_data;
			cgd->inq_flags = dev->inq_flags;
			cgd->ccb_h.status = CAM_REQ_CMP;
			cgd->serial_num_len = dev->serial_num_len;
			if ((dev->serial_num_len > 0)
			 && (dev->serial_num != NULL))
				bcopy(dev->serial_num, cgd->serial_num,
				      dev->serial_num_len);
		}
		break;
	}
	case XPT_GDEV_STATS:
	{
		struct ccb_getdevstats *cgds = &start_ccb->cgds;
		struct cam_ed *dev = path->device;
		struct cam_eb *bus = path->bus;
		struct cam_et *tar = path->target;
		struct cam_devq *devq = bus->sim->devq;

		mtx_lock(&devq->send_mtx);
		cgds->dev_openings = dev->ccbq.dev_openings;
		cgds->dev_active = dev->ccbq.dev_active;
		cgds->allocated = dev->ccbq.allocated;
		cgds->queued = cam_ccbq_pending_ccb_count(&dev->ccbq);
		cgds->held = cgds->allocated - cgds->dev_active - cgds->queued;
		cgds->last_reset = tar->last_reset;
		cgds->maxtags = dev->maxtags;
		cgds->mintags = dev->mintags;
		if (timevalcmp(&tar->last_reset, &bus->last_reset, <))
			cgds->last_reset = bus->last_reset;
		mtx_unlock(&devq->send_mtx);
		cgds->ccb_h.status = CAM_REQ_CMP;
		break;
	}
	case XPT_GDEVLIST:
	{
		struct cam_periph	*nperiph;
		struct periph_list	*periph_head;
		struct ccb_getdevlist	*cgdl;
		u_int			i;
		struct cam_ed		*device;
		int			found;

		found = 0;

		/*
		 * Don't want anyone mucking with our data.
		 */
		device = path->device;
		periph_head = &device->periphs;
		cgdl = &start_ccb->cgdl;

		/*
		 * Check and see if the list has changed since the user
		 * last requested a list member.  If so, tell them that the
		 * list has changed, and therefore they need to start over
		 * from the beginning.
		 */
		if ((cgdl->index != 0) &&
		    (cgdl->generation != device->generation)) {
			cgdl->status = CAM_GDEVLIST_LIST_CHANGED;
			break;
		}

		/*
		 * Traverse the list of peripherals and attempt to find
		 * the requested peripheral.
		 */
		for (nperiph = SLIST_FIRST(periph_head), i = 0;
		     (nperiph != NULL) && (i <= cgdl->index);
		     nperiph = SLIST_NEXT(nperiph, periph_links), i++) {
			if (i == cgdl->index) {
				strlcpy(cgdl->periph_name,
					nperiph->periph_name,
					sizeof(cgdl->periph_name));
				cgdl->unit_number = nperiph->unit_number;
				found = 1;
			}
		}
		if (found == 0) {
			cgdl->status = CAM_GDEVLIST_ERROR;
			break;
		}

		if (nperiph == NULL)
			cgdl->status = CAM_GDEVLIST_LAST_DEVICE;
		else
			cgdl->status = CAM_GDEVLIST_MORE_DEVS;

		cgdl->index++;
		cgdl->generation = device->generation;

		cgdl->ccb_h.status = CAM_REQ_CMP;
		break;
	}
	case XPT_DEV_MATCH:
	{
		dev_pos_type position_type;
		struct ccb_dev_match *cdm;

		cdm = &start_ccb->cdm;

		/*
		 * There are two ways of getting at information in the EDT.
		 * The first way is via the primary EDT tree.  It starts
		 * with a list of buses, then a list of targets on a bus,
		 * then devices/luns on a target, and then peripherals on a
		 * device/lun.  The "other" way is by the peripheral driver
		 * lists.  The peripheral driver lists are organized by
		 * peripheral driver.  (obviously)  So it makes sense to
		 * use the peripheral driver list if the user is looking
		 * for something like "da1", or all "da" devices.  If the
		 * user is looking for something on a particular bus/target
		 * or lun, it's generally better to go through the EDT tree.
		 */

		if (cdm->pos.position_type != CAM_DEV_POS_NONE)
			position_type = cdm->pos.position_type;
		else {
			u_int i;

			position_type = CAM_DEV_POS_NONE;

			for (i = 0; i < cdm->num_patterns; i++) {
				if ((cdm->patterns[i].type == DEV_MATCH_BUS)
				 ||(cdm->patterns[i].type == DEV_MATCH_DEVICE)){
					position_type = CAM_DEV_POS_EDT;
					break;
				}
			}

			if (cdm->num_patterns == 0)
				position_type = CAM_DEV_POS_EDT;
			else if (position_type == CAM_DEV_POS_NONE)
				position_type = CAM_DEV_POS_PDRV;
		}

		switch(position_type & CAM_DEV_POS_TYPEMASK) {
		case CAM_DEV_POS_EDT:
			xptedtmatch(cdm);
			break;
		case CAM_DEV_POS_PDRV:
			xptperiphlistmatch(cdm);
			break;
		default:
			cdm->status = CAM_DEV_MATCH_ERROR;
			break;
		}

		if (cdm->status == CAM_DEV_MATCH_ERROR)
			start_ccb->ccb_h.status = CAM_REQ_CMP_ERR;
		else
			start_ccb->ccb_h.status = CAM_REQ_CMP;

		break;
	}
	case XPT_SASYNC_CB:
	{
		struct ccb_setasync *csa;
		struct async_node *cur_entry;
		struct async_list *async_head;
		u_int32_t added;

		csa = &start_ccb->csa;
		added = csa->event_enable;
		async_head = &path->device->asyncs;

		/*
		 * If there is already an entry for us, simply
		 * update it.
		 */
		cur_entry = SLIST_FIRST(async_head);
		while (cur_entry != NULL) {
			if ((cur_entry->callback_arg == csa->callback_arg)
			 && (cur_entry->callback == csa->callback))
				break;
			cur_entry = SLIST_NEXT(cur_entry, links);
		}

		if (cur_entry != NULL) {
		 	/*
			 * If the request has no flags set,
			 * remove the entry.
			 */
			added &= ~cur_entry->event_enable;
			if (csa->event_enable == 0) {
				SLIST_REMOVE(async_head, cur_entry,
					     async_node, links);
				xpt_release_device(path->device);
				free(cur_entry, M_CAMXPT);
			} else {
				cur_entry->event_enable = csa->event_enable;
			}
			csa->event_enable = added;
		} else {
			cur_entry = malloc(sizeof(*cur_entry), M_CAMXPT,
					   M_NOWAIT);
			if (cur_entry == NULL) {
				csa->ccb_h.status = CAM_RESRC_UNAVAIL;
				break;
			}
			cur_entry->event_enable = csa->event_enable;
			cur_entry->event_lock = (path->bus->sim->mtx &&
			    mtx_owned(path->bus->sim->mtx)) ? 1 : 0;
			cur_entry->callback_arg = csa->callback_arg;
			cur_entry->callback = csa->callback;
			SLIST_INSERT_HEAD(async_head, cur_entry, links);
			xpt_acquire_device(path->device);
		}
		start_ccb->ccb_h.status = CAM_REQ_CMP;
		break;
	}
	case XPT_REL_SIMQ:
	{
		struct ccb_relsim *crs;
		struct cam_ed *dev;

		crs = &start_ccb->crs;
		dev = path->device;
		if (dev == NULL) {
			crs->ccb_h.status = CAM_DEV_NOT_THERE;
			break;
		}

		if ((crs->release_flags & RELSIM_ADJUST_OPENINGS) != 0) {
			/* Don't ever go below one opening */
			if (crs->openings > 0) {
				xpt_dev_ccbq_resize(path, crs->openings);
				if (bootverbose) {
					xpt_print(path,
					    "number of openings is now %d\n",
					    crs->openings);
				}
			}
		}

		mtx_lock(&dev->sim->devq->send_mtx);
		if ((crs->release_flags & RELSIM_RELEASE_AFTER_TIMEOUT) != 0) {
			if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
				/*
				 * Just extend the old timeout and decrement
				 * the freeze count so that a single timeout
				 * is sufficient for releasing the queue.
				 */
				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
				callout_stop(&dev->callout);
			} else {
				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
			}

			callout_reset_sbt(&dev->callout,
			    SBT_1MS * crs->release_timeout, 0,
			    xpt_release_devq_timeout, dev, 0);

			dev->flags |= CAM_DEV_REL_TIMEOUT_PENDING;
		}

		if ((crs->release_flags & RELSIM_RELEASE_AFTER_CMDCMPLT) != 0) {
			if ((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0) {
				/*
				 * Decrement the freeze count so that a single
				 * completion is still sufficient to unfreeze
				 * the queue.
				 */
				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
			} else {
				dev->flags |= CAM_DEV_REL_ON_COMPLETE;
				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
			}
		}

		if ((crs->release_flags & RELSIM_RELEASE_AFTER_QEMPTY) != 0) {
			if ((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
			 || (dev->ccbq.dev_active == 0)) {
				start_ccb->ccb_h.flags &= ~CAM_DEV_QFREEZE;
			} else {
				dev->flags |= CAM_DEV_REL_ON_QUEUE_EMPTY;
				start_ccb->ccb_h.flags |= CAM_DEV_QFREEZE;
			}
		}
		mtx_unlock(&dev->sim->devq->send_mtx);

		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) == 0)
			xpt_release_devq(path, /*count*/1, /*run_queue*/TRUE);
		start_ccb->crs.qfrozen_cnt = dev->ccbq.queue.qfrozen_cnt;
		start_ccb->ccb_h.status = CAM_REQ_CMP;
		break;
	}
	case XPT_DEBUG: {
		struct cam_path *oldpath;

		/* Check that all request bits are supported. */
		if (start_ccb->cdbg.flags & ~(CAM_DEBUG_COMPILE)) {
			start_ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
			break;
		}

		cam_dflags = CAM_DEBUG_NONE;
		if (cam_dpath != NULL) {
			oldpath = cam_dpath;
			cam_dpath = NULL;
			xpt_free_path(oldpath);
		}
		if (start_ccb->cdbg.flags != CAM_DEBUG_NONE) {
			if (xpt_create_path(&cam_dpath, NULL,
					    start_ccb->ccb_h.path_id,
					    start_ccb->ccb_h.target_id,
					    start_ccb->ccb_h.target_lun) !=
					    CAM_REQ_CMP) {
				start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
			} else {
				cam_dflags = start_ccb->cdbg.flags;
				start_ccb->ccb_h.status = CAM_REQ_CMP;
				xpt_print(cam_dpath, "debugging flags now %x\n",
				    cam_dflags);
			}
		} else
			start_ccb->ccb_h.status = CAM_REQ_CMP;
		break;
	}
	case XPT_NOOP:
		if ((start_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0)
			xpt_freeze_devq(path, 1);
		start_ccb->ccb_h.status = CAM_REQ_CMP;
		break;
	case XPT_REPROBE_LUN:
		xpt_async(AC_INQ_CHANGED, path, NULL);
		start_ccb->ccb_h.status = CAM_REQ_CMP;
		xpt_done(start_ccb);
		break;
	case XPT_ASYNC:
		start_ccb->ccb_h.status = CAM_REQ_CMP;
		xpt_done(start_ccb);
		break;
	default:
	case XPT_SDEV_TYPE:
	case XPT_TERM_IO:
	case XPT_ENG_INQ:
		/* XXX Implement */
		xpt_print(start_ccb->ccb_h.path,
		    "%s: CCB type %#x %s not supported\n", __func__,
		    start_ccb->ccb_h.func_code,
		    xpt_action_name(start_ccb->ccb_h.func_code));
		start_ccb->ccb_h.status = CAM_PROVIDE_FAIL;
		if (start_ccb->ccb_h.func_code & XPT_FC_DEV_QUEUED) {
			xpt_done(start_ccb);
		}
		break;
	}
	CAM_DEBUG(path, CAM_DEBUG_TRACE,
	    ("xpt_action_default: func= %#x %s status %#x\n",
		start_ccb->ccb_h.func_code,
 		xpt_action_name(start_ccb->ccb_h.func_code),
		start_ccb->ccb_h.status));
}

/*
 * Call the sim poll routine to allow the sim to complete
 * any inflight requests, then call camisr_runqueue to
 * complete any CCB that the polling completed.
 */
void
xpt_sim_poll(struct cam_sim *sim)
{
	struct mtx *mtx;

	KASSERT(cam_sim_pollable(sim), ("%s: non-pollable sim", __func__));
	mtx = sim->mtx;
	if (mtx)
		mtx_lock(mtx);
	(*(sim->sim_poll))(sim);
	if (mtx)
		mtx_unlock(mtx);
	camisr_runqueue();
}

uint32_t
xpt_poll_setup(union ccb *start_ccb)
{
	u_int32_t timeout;
	struct	  cam_sim *sim;
	struct	  cam_devq *devq;
	struct	  cam_ed *dev;

	timeout = start_ccb->ccb_h.timeout * 10;
	sim = start_ccb->ccb_h.path->bus->sim;
	devq = sim->devq;
	dev = start_ccb->ccb_h.path->device;

	KASSERT(cam_sim_pollable(sim), ("%s: non-pollable sim", __func__));

	/*
	 * Steal an opening so that no other queued requests
	 * can get it before us while we simulate interrupts.
	 */
	mtx_lock(&devq->send_mtx);
	dev->ccbq.dev_openings--;
	while((devq->send_openings <= 0 || dev->ccbq.dev_openings < 0) &&
	    (--timeout > 0)) {
		mtx_unlock(&devq->send_mtx);
		DELAY(100);
		xpt_sim_poll(sim);
		mtx_lock(&devq->send_mtx);
	}
	dev->ccbq.dev_openings++;
	mtx_unlock(&devq->send_mtx);

	return (timeout);
}

void
xpt_pollwait(union ccb *start_ccb, uint32_t timeout)
{

	KASSERT(cam_sim_pollable(start_ccb->ccb_h.path->bus->sim),
	    ("%s: non-pollable sim", __func__));
	while (--timeout > 0) {
		xpt_sim_poll(start_ccb->ccb_h.path->bus->sim);
		if ((start_ccb->ccb_h.status & CAM_STATUS_MASK)
		    != CAM_REQ_INPROG)
			break;
		DELAY(100);
	}

	if (timeout == 0) {
		/*
		 * XXX Is it worth adding a sim_timeout entry
		 * point so we can attempt recovery?  If
		 * this is only used for dumps, I don't think
		 * it is.
		 */
		start_ccb->ccb_h.status = CAM_CMD_TIMEOUT;
	}
}

void
xpt_polled_action(union ccb *start_ccb)
{
	uint32_t	timeout;
	struct cam_ed	*dev;

	timeout = start_ccb->ccb_h.timeout * 10;
	dev = start_ccb->ccb_h.path->device;

	mtx_unlock(&dev->device_mtx);

	timeout = xpt_poll_setup(start_ccb);
	if (timeout > 0) {
		xpt_action(start_ccb);
		xpt_pollwait(start_ccb, timeout);
	} else {
		start_ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
	}

	mtx_lock(&dev->device_mtx);
}

/*
 * Schedule a peripheral driver to receive a ccb when its
 * target device has space for more transactions.
 */
void
xpt_schedule(struct cam_periph *periph, u_int32_t new_priority)
{

	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("xpt_schedule\n"));
	cam_periph_assert(periph, MA_OWNED);
	if (new_priority < periph->scheduled_priority) {
		periph->scheduled_priority = new_priority;
		xpt_run_allocq(periph, 0);
	}
}

/*
 * Schedule a device to run on a given queue.
 * If the device was inserted as a new entry on the queue,
 * return 1 meaning the device queue should be run. If we
 * were already queued, implying someone else has already
 * started the queue, return 0 so the caller doesn't attempt
 * to run the queue.
 */
static int
xpt_schedule_dev(struct camq *queue, cam_pinfo *pinfo,
		 u_int32_t new_priority)
{
	int retval;
	u_int32_t old_priority;

	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_schedule_dev\n"));

	old_priority = pinfo->priority;

	/*
	 * Are we already queued?
	 */
	if (pinfo->index != CAM_UNQUEUED_INDEX) {
		/* Simply reorder based on new priority */
		if (new_priority < old_priority) {
			camq_change_priority(queue, pinfo->index,
					     new_priority);
			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
					("changed priority to %d\n",
					 new_priority));
			retval = 1;
		} else
			retval = 0;
	} else {
		/* New entry on the queue */
		if (new_priority < old_priority)
			pinfo->priority = new_priority;

		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
				("Inserting onto queue\n"));
		pinfo->generation = ++queue->generation;
		camq_insert(queue, pinfo);
		retval = 1;
	}
	return (retval);
}

static void
xpt_run_allocq_task(void *context, int pending)
{
	struct cam_periph *periph = context;

	cam_periph_lock(periph);
	periph->flags &= ~CAM_PERIPH_RUN_TASK;
	xpt_run_allocq(periph, 1);
	cam_periph_unlock(periph);
	cam_periph_release(periph);
}

static void
xpt_run_allocq(struct cam_periph *periph, int sleep)
{
	struct cam_ed	*device;
	union ccb	*ccb;
	uint32_t	 prio;

	cam_periph_assert(periph, MA_OWNED);
	if (periph->periph_allocating)
		return;
	cam_periph_doacquire(periph);
	periph->periph_allocating = 1;
	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_allocq(%p)\n", periph));
	device = periph->path->device;
	ccb = NULL;
restart:
	while ((prio = min(periph->scheduled_priority,
	    periph->immediate_priority)) != CAM_PRIORITY_NONE &&
	    (periph->periph_allocated - (ccb != NULL ? 1 : 0) <
	     device->ccbq.total_openings || prio <= CAM_PRIORITY_OOB)) {
		if (ccb == NULL &&
		    (ccb = xpt_get_ccb_nowait(periph)) == NULL) {
			if (sleep) {
				ccb = xpt_get_ccb(periph);
				goto restart;
			}
			if (periph->flags & CAM_PERIPH_RUN_TASK)
				break;
			cam_periph_doacquire(periph);
			periph->flags |= CAM_PERIPH_RUN_TASK;
			taskqueue_enqueue(xsoftc.xpt_taskq,
			    &periph->periph_run_task);
			break;
		}
		xpt_setup_ccb(&ccb->ccb_h, periph->path, prio);
		if (prio == periph->immediate_priority) {
			periph->immediate_priority = CAM_PRIORITY_NONE;
			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
					("waking cam_periph_getccb()\n"));
			SLIST_INSERT_HEAD(&periph->ccb_list, &ccb->ccb_h,
					  periph_links.sle);
			wakeup(&periph->ccb_list);
		} else {
			periph->scheduled_priority = CAM_PRIORITY_NONE;
			CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
					("calling periph_start()\n"));
			periph->periph_start(periph, ccb);
		}
		ccb = NULL;
	}
	if (ccb != NULL)
		xpt_release_ccb(ccb);
	periph->periph_allocating = 0;
	cam_periph_release_locked(periph);
}

static void
xpt_run_devq(struct cam_devq *devq)
{
	struct mtx *mtx;

	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_run_devq\n"));

	devq->send_queue.qfrozen_cnt++;
	while ((devq->send_queue.entries > 0)
	    && (devq->send_openings > 0)
	    && (devq->send_queue.qfrozen_cnt <= 1)) {
		struct	cam_ed *device;
		union ccb *work_ccb;
		struct	cam_sim *sim;
		struct xpt_proto *proto;

		device = (struct cam_ed *)camq_remove(&devq->send_queue,
							   CAMQ_HEAD);
		CAM_DEBUG_PRINT(CAM_DEBUG_XPT,
				("running device %p\n", device));

		work_ccb = cam_ccbq_peek_ccb(&device->ccbq, CAMQ_HEAD);
		if (work_ccb == NULL) {
			printf("device on run queue with no ccbs???\n");
			continue;
		}

		if ((work_ccb->ccb_h.flags & CAM_HIGH_POWER) != 0) {
			mtx_lock(&xsoftc.xpt_highpower_lock);
		 	if (xsoftc.num_highpower <= 0) {
				/*
				 * We got a high power command, but we
				 * don't have any available slots.  Freeze
				 * the device queue until we have a slot
				 * available.
				 */
				xpt_freeze_devq_device(device, 1);
				STAILQ_INSERT_TAIL(&xsoftc.highpowerq, device,
						   highpowerq_entry);

				mtx_unlock(&xsoftc.xpt_highpower_lock);
				continue;
			} else {
				/*
				 * Consume a high power slot while
				 * this ccb runs.
				 */
				xsoftc.num_highpower--;
			}
			mtx_unlock(&xsoftc.xpt_highpower_lock);
		}
		cam_ccbq_remove_ccb(&device->ccbq, work_ccb);
		cam_ccbq_send_ccb(&device->ccbq, work_ccb);
		devq->send_openings--;
		devq->send_active++;
		xpt_schedule_devq(devq, device);
		mtx_unlock(&devq->send_mtx);

		if ((work_ccb->ccb_h.flags & CAM_DEV_QFREEZE) != 0) {
			/*
			 * The client wants to freeze the queue
			 * after this CCB is sent.
			 */
			xpt_freeze_devq(work_ccb->ccb_h.path, 1);
		}

		/* In Target mode, the peripheral driver knows best... */
		if (work_ccb->ccb_h.func_code == XPT_SCSI_IO) {
			if ((device->inq_flags & SID_CmdQue) != 0
			 && work_ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
				work_ccb->ccb_h.flags |= CAM_TAG_ACTION_VALID;
			else
				/*
				 * Clear this in case of a retried CCB that
				 * failed due to a rejected tag.
				 */
				work_ccb->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
		}

		KASSERT(device == work_ccb->ccb_h.path->device,
		    ("device (%p) / path->device (%p) mismatch",
			device, work_ccb->ccb_h.path->device));
		proto = xpt_proto_find(device->protocol);
		if (proto && proto->ops->debug_out)
			proto->ops->debug_out(work_ccb);

		/*
		 * Device queues can be shared among multiple SIM instances
		 * that reside on different buses.  Use the SIM from the
		 * queued device, rather than the one from the calling bus.
		 */
		sim = device->sim;
		mtx = sim->mtx;
		if (mtx && !mtx_owned(mtx))
			mtx_lock(mtx);
		else
			mtx = NULL;
		work_ccb->ccb_h.qos.periph_data = cam_iosched_now();
		(*(sim->sim_action))(sim, work_ccb);
		if (mtx)
			mtx_unlock(mtx);
		mtx_lock(&devq->send_mtx);
	}
	devq->send_queue.qfrozen_cnt--;
}

/*
 * This function merges stuff from the src ccb into the dst ccb, while keeping
 * important fields in the dst ccb constant.
 */
void
xpt_merge_ccb(union ccb *dst_ccb, union ccb *src_ccb)
{

	/*
	 * Pull fields that are valid for peripheral drivers to set
	 * into the dst CCB along with the CCB "payload".
	 */
	dst_ccb->ccb_h.retry_count = src_ccb->ccb_h.retry_count;
	dst_ccb->ccb_h.func_code = src_ccb->ccb_h.func_code;
	dst_ccb->ccb_h.timeout = src_ccb->ccb_h.timeout;
	dst_ccb->ccb_h.flags = src_ccb->ccb_h.flags;
	bcopy(&(&src_ccb->ccb_h)[1], &(&dst_ccb->ccb_h)[1],
	      sizeof(union ccb) - sizeof(struct ccb_hdr));
}

void
xpt_setup_ccb_flags(struct ccb_hdr *ccb_h, struct cam_path *path,
		    u_int32_t priority, u_int32_t flags)
{

	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_setup_ccb\n"));
	ccb_h->pinfo.priority = priority;
	ccb_h->path = path;
	ccb_h->path_id = path->bus->path_id;
	if (path->target)
		ccb_h->target_id = path->target->target_id;
	else
		ccb_h->target_id = CAM_TARGET_WILDCARD;
	if (path->device) {
		ccb_h->target_lun = path->device->lun_id;
		ccb_h->pinfo.generation = ++path->device->ccbq.queue.generation;
	} else {
		ccb_h->target_lun = CAM_TARGET_WILDCARD;
	}
	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
	ccb_h->flags = flags;
	ccb_h->xflags = 0;
}

void
xpt_setup_ccb(struct ccb_hdr *ccb_h, struct cam_path *path, u_int32_t priority)
{
	xpt_setup_ccb_flags(ccb_h, path, priority, /*flags*/ 0);
}

/* Path manipulation functions */
cam_status
xpt_create_path(struct cam_path **new_path_ptr, struct cam_periph *perph,
		path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
{
	struct	   cam_path *path;
	cam_status status;

	path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);

	if (path == NULL) {
		status = CAM_RESRC_UNAVAIL;
		return(status);
	}
	status = xpt_compile_path(path, perph, path_id, target_id, lun_id);
	if (status != CAM_REQ_CMP) {
		free(path, M_CAMPATH);
		path = NULL;
	}
	*new_path_ptr = path;
	return (status);
}

cam_status
xpt_create_path_unlocked(struct cam_path **new_path_ptr,
			 struct cam_periph *periph, path_id_t path_id,
			 target_id_t target_id, lun_id_t lun_id)
{

	return (xpt_create_path(new_path_ptr, periph, path_id, target_id,
	    lun_id));
}

cam_status
xpt_compile_path(struct cam_path *new_path, struct cam_periph *perph,
		 path_id_t path_id, target_id_t target_id, lun_id_t lun_id)
{
	struct	     cam_eb *bus;
	struct	     cam_et *target;
	struct	     cam_ed *device;
	cam_status   status;

	status = CAM_REQ_CMP;	/* Completed without error */
	target = NULL;		/* Wildcarded */
	device = NULL;		/* Wildcarded */

	/*
	 * We will potentially modify the EDT, so block interrupts
	 * that may attempt to create cam paths.
	 */
	bus = xpt_find_bus(path_id);
	if (bus == NULL) {
		status = CAM_PATH_INVALID;
	} else {
		xpt_lock_buses();
		mtx_lock(&bus->eb_mtx);
		target = xpt_find_target(bus, target_id);
		if (target == NULL) {
			/* Create one */
			struct cam_et *new_target;

			new_target = xpt_alloc_target(bus, target_id);
			if (new_target == NULL) {
				status = CAM_RESRC_UNAVAIL;
			} else {
				target = new_target;
			}
		}
		xpt_unlock_buses();
		if (target != NULL) {
			device = xpt_find_device(target, lun_id);
			if (device == NULL) {
				/* Create one */
				struct cam_ed *new_device;

				new_device =
				    (*(bus->xport->ops->alloc_device))(bus,
								       target,
								       lun_id);
				if (new_device == NULL) {
					status = CAM_RESRC_UNAVAIL;
				} else {
					device = new_device;
				}
			}
		}
		mtx_unlock(&bus->eb_mtx);
	}

	/*
	 * Only touch the user's data if we are successful.
	 */
	if (status == CAM_REQ_CMP) {
		new_path->periph = perph;
		new_path->bus = bus;
		new_path->target = target;
		new_path->device = device;
		CAM_DEBUG(new_path, CAM_DEBUG_TRACE, ("xpt_compile_path\n"));
	} else {
		if (device != NULL)
			xpt_release_device(device);
		if (target != NULL)
			xpt_release_target(target);
		if (bus != NULL)
			xpt_release_bus(bus);
	}
	return (status);
}

cam_status
xpt_clone_path(struct cam_path **new_path_ptr, struct cam_path *path)
{
	struct	   cam_path *new_path;

	new_path = (struct cam_path *)malloc(sizeof(*path), M_CAMPATH, M_NOWAIT);
	if (new_path == NULL)
		return(CAM_RESRC_UNAVAIL);
	*new_path = *path;
	if (path->bus != NULL)
		xpt_acquire_bus(path->bus);
	if (path->target != NULL)
		xpt_acquire_target(path->target);
	if (path->device != NULL)
		xpt_acquire_device(path->device);
	*new_path_ptr = new_path;
	return (CAM_REQ_CMP);
}

void
xpt_release_path(struct cam_path *path)
{
	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_path\n"));
	if (path->device != NULL) {
		xpt_release_device(path->device);
		path->device = NULL;
	}
	if (path->target != NULL) {
		xpt_release_target(path->target);
		path->target = NULL;
	}
	if (path->bus != NULL) {
		xpt_release_bus(path->bus);
		path->bus = NULL;
	}
}

void
xpt_free_path(struct cam_path *path)
{

	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_free_path\n"));
	xpt_release_path(path);
	free(path, M_CAMPATH);
}

void
xpt_path_counts(struct cam_path *path, uint32_t *bus_ref,
    uint32_t *periph_ref, uint32_t *target_ref, uint32_t *device_ref)
{

	xpt_lock_buses();
	if (bus_ref) {
		if (path->bus)
			*bus_ref = path->bus->refcount;
		else
			*bus_ref = 0;
	}
	if (periph_ref) {
		if (path->periph)
			*periph_ref = path->periph->refcount;
		else
			*periph_ref = 0;
	}
	xpt_unlock_buses();
	if (target_ref) {
		if (path->target)
			*target_ref = path->target->refcount;
		else
			*target_ref = 0;
	}
	if (device_ref) {
		if (path->device)
			*device_ref = path->device->refcount;
		else
			*device_ref = 0;
	}
}

/*
 * Return -1 for failure, 0 for exact match, 1 for match with wildcards
 * in path1, 2 for match with wildcards in path2.
 */
int
xpt_path_comp(struct cam_path *path1, struct cam_path *path2)
{
	int retval = 0;

	if (path1->bus != path2->bus) {
		if (path1->bus->path_id == CAM_BUS_WILDCARD)
			retval = 1;
		else if (path2->bus->path_id == CAM_BUS_WILDCARD)
			retval = 2;
		else
			return (-1);
	}
	if (path1->target != path2->target) {
		if (path1->target->target_id == CAM_TARGET_WILDCARD) {
			if (retval == 0)
				retval = 1;
		} else if (path2->target->target_id == CAM_TARGET_WILDCARD)
			retval = 2;
		else
			return (-1);
	}
	if (path1->device != path2->device) {
		if (path1->device->lun_id == CAM_LUN_WILDCARD) {
			if (retval == 0)
				retval = 1;
		} else if (path2->device->lun_id == CAM_LUN_WILDCARD)
			retval = 2;
		else
			return (-1);
	}
	return (retval);
}

int
xpt_path_comp_dev(struct cam_path *path, struct cam_ed *dev)
{
	int retval = 0;

	if (path->bus != dev->target->bus) {
		if (path->bus->path_id == CAM_BUS_WILDCARD)
			retval = 1;
		else if (dev->target->bus->path_id == CAM_BUS_WILDCARD)
			retval = 2;
		else
			return (-1);
	}
	if (path->target != dev->target) {
		if (path->target->target_id == CAM_TARGET_WILDCARD) {
			if (retval == 0)
				retval = 1;
		} else if (dev->target->target_id == CAM_TARGET_WILDCARD)
			retval = 2;
		else
			return (-1);
	}
	if (path->device != dev) {
		if (path->device->lun_id == CAM_LUN_WILDCARD) {
			if (retval == 0)
				retval = 1;
		} else if (dev->lun_id == CAM_LUN_WILDCARD)
			retval = 2;
		else
			return (-1);
	}
	return (retval);
}

void
xpt_print_path(struct cam_path *path)
{
	struct sbuf sb;
	char buffer[XPT_PRINT_LEN];

	sbuf_new(&sb, buffer, XPT_PRINT_LEN, SBUF_FIXEDLEN);
	xpt_path_sbuf(path, &sb);
	sbuf_finish(&sb);
	printf("%s", sbuf_data(&sb));
	sbuf_delete(&sb);
}

void
xpt_print_device(struct cam_ed *device)
{

	if (device == NULL)
		printf("(nopath): ");
	else {
		printf("(noperiph:%s%d:%d:%d:%jx): ", device->sim->sim_name,
		       device->sim->unit_number,
		       device->sim->bus_id,
		       device->target->target_id,
		       (uintmax_t)device->lun_id);
	}
}

void
xpt_print(struct cam_path *path, const char *fmt, ...)
{
	va_list ap;
	struct sbuf sb;
	char buffer[XPT_PRINT_LEN];

	sbuf_new(&sb, buffer, XPT_PRINT_LEN, SBUF_FIXEDLEN);

	xpt_path_sbuf(path, &sb);
	va_start(ap, fmt);
	sbuf_vprintf(&sb, fmt, ap);
	va_end(ap);

	sbuf_finish(&sb);
	printf("%s", sbuf_data(&sb));
	sbuf_delete(&sb);
}

int
xpt_path_string(struct cam_path *path, char *str, size_t str_len)
{
	struct sbuf sb;
	int len;

	sbuf_new(&sb, str, str_len, 0);
	len = xpt_path_sbuf(path, &sb);
	sbuf_finish(&sb);
	return (len);
}

int
xpt_path_sbuf(struct cam_path *path, struct sbuf *sb)
{

	if (path == NULL)
		sbuf_printf(sb, "(nopath): ");
	else {
		if (path->periph != NULL)
			sbuf_printf(sb, "(%s%d:", path->periph->periph_name,
				    path->periph->unit_number);
		else
			sbuf_printf(sb, "(noperiph:");

		if (path->bus != NULL)
			sbuf_printf(sb, "%s%d:%d:", path->bus->sim->sim_name,
				    path->bus->sim->unit_number,
				    path->bus->sim->bus_id);
		else
			sbuf_printf(sb, "nobus:");

		if (path->target != NULL)
			sbuf_printf(sb, "%d:", path->target->target_id);
		else
			sbuf_printf(sb, "X:");

		if (path->device != NULL)
			sbuf_printf(sb, "%jx): ",
			    (uintmax_t)path->device->lun_id);
		else
			sbuf_printf(sb, "X): ");
	}

	return(sbuf_len(sb));
}

path_id_t
xpt_path_path_id(struct cam_path *path)
{
	return(path->bus->path_id);
}

target_id_t
xpt_path_target_id(struct cam_path *path)
{
	if (path->target != NULL)
		return (path->target->target_id);
	else
		return (CAM_TARGET_WILDCARD);
}

lun_id_t
xpt_path_lun_id(struct cam_path *path)
{
	if (path->device != NULL)
		return (path->device->lun_id);
	else
		return (CAM_LUN_WILDCARD);
}

struct cam_sim *
xpt_path_sim(struct cam_path *path)
{

	return (path->bus->sim);
}

struct cam_periph*
xpt_path_periph(struct cam_path *path)
{

	return (path->periph);
}

/*
 * Release a CAM control block for the caller.  Remit the cost of the structure
 * to the device referenced by the path.  If the this device had no 'credits'
 * and peripheral drivers have registered async callbacks for this notification
 * call them now.
 */
void
xpt_release_ccb(union ccb *free_ccb)
{
	struct	 cam_ed *device;
	struct	 cam_periph *periph;

	CAM_DEBUG_PRINT(CAM_DEBUG_XPT, ("xpt_release_ccb\n"));
	xpt_path_assert(free_ccb->ccb_h.path, MA_OWNED);
	device = free_ccb->ccb_h.path->device;
	periph = free_ccb->ccb_h.path->periph;

	xpt_free_ccb(free_ccb);
	periph->periph_allocated--;
	cam_ccbq_release_opening(&device->ccbq);
	xpt_run_allocq(periph, 0);
}

/* Functions accessed by SIM drivers */

static struct xpt_xport_ops xport_default_ops = {
	.alloc_device = xpt_alloc_device_default,
	.action = xpt_action_default,
	.async = xpt_dev_async_default,
};
static struct xpt_xport xport_default = {
	.xport = XPORT_UNKNOWN,
	.name = "unknown",
	.ops = &xport_default_ops,
};

CAM_XPT_XPORT(xport_default);

/*
 * A sim structure, listing the SIM entry points and instance
 * identification info is passed to xpt_bus_register to hook the SIM
 * into the CAM framework.  xpt_bus_register creates a cam_eb entry
 * for this new bus and places it in the array of buses and assigns
 * it a path_id.  The path_id may be influenced by "hard wiring"
 * information specified by the user.  Once interrupt services are
 * available, the bus will be probed.
 */
int32_t
xpt_bus_register(struct cam_sim *sim, device_t parent, u_int32_t bus)
{
	struct cam_eb *new_bus;
	struct cam_eb *old_bus;
	struct ccb_pathinq cpi;
	struct cam_path *path;
	cam_status status;

	sim->bus_id = bus;
	new_bus = (struct cam_eb *)malloc(sizeof(*new_bus),
					  M_CAMXPT, M_NOWAIT|M_ZERO);
	if (new_bus == NULL) {
		/* Couldn't satisfy request */
		return (CAM_RESRC_UNAVAIL);
	}

	mtx_init(&new_bus->eb_mtx, "CAM bus lock", NULL, MTX_DEF);
	TAILQ_INIT(&new_bus->et_entries);
	cam_sim_hold(sim);
	new_bus->sim = sim;
	timevalclear(&new_bus->last_reset);
	new_bus->flags = 0;
	new_bus->refcount = 1;	/* Held until a bus_deregister event */
	new_bus->generation = 0;

	xpt_lock_buses();
	sim->path_id = new_bus->path_id =
	    xptpathid(sim->sim_name, sim->unit_number, sim->bus_id);
	old_bus = TAILQ_FIRST(&xsoftc.xpt_busses);
	while (old_bus != NULL
	    && old_bus->path_id < new_bus->path_id)
		old_bus = TAILQ_NEXT(old_bus, links);
	if (old_bus != NULL)
		TAILQ_INSERT_BEFORE(old_bus, new_bus, links);
	else
		TAILQ_INSERT_TAIL(&xsoftc.xpt_busses, new_bus, links);
	xsoftc.bus_generation++;
	xpt_unlock_buses();

	/*
	 * Set a default transport so that a PATH_INQ can be issued to
	 * the SIM.  This will then allow for probing and attaching of
	 * a more appropriate transport.
	 */
	new_bus->xport = &xport_default;

	status = xpt_create_path(&path, /*periph*/NULL, sim->path_id,
				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
	if (status != CAM_REQ_CMP) {
		xpt_release_bus(new_bus);
		return (CAM_RESRC_UNAVAIL);
	}

	xpt_path_inq(&cpi, path);

	if (cpi.ccb_h.status == CAM_REQ_CMP) {
		struct xpt_xport **xpt;

		SET_FOREACH(xpt, cam_xpt_xport_set) {
			if ((*xpt)->xport == cpi.transport) {
				new_bus->xport = *xpt;
				break;
			}
		}
		if (new_bus->xport == NULL) {
			xpt_print(path,
			    "No transport found for %d\n", cpi.transport);
			xpt_release_bus(new_bus);
			free(path, M_CAMXPT);
			return (CAM_RESRC_UNAVAIL);
		}
	}

	/* Notify interested parties */
	if (sim->path_id != CAM_XPT_PATH_ID) {
		xpt_async(AC_PATH_REGISTERED, path, &cpi);
		if ((cpi.hba_misc & PIM_NOSCAN) == 0) {
			union	ccb *scan_ccb;

			/* Initiate bus rescan. */
			scan_ccb = xpt_alloc_ccb_nowait();
			if (scan_ccb != NULL) {
				scan_ccb->ccb_h.path = path;
				scan_ccb->ccb_h.func_code = XPT_SCAN_BUS;
				scan_ccb->crcn.flags = 0;
				xpt_rescan(scan_ccb);
			} else {
				xpt_print(path,
					  "Can't allocate CCB to scan bus\n");
				xpt_free_path(path);
			}
		} else
			xpt_free_path(path);
	} else
		xpt_free_path(path);
	return (CAM_SUCCESS);
}

int32_t
xpt_bus_deregister(path_id_t pathid)
{
	struct cam_path bus_path;
	cam_status status;

	status = xpt_compile_path(&bus_path, NULL, pathid,
				  CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
	if (status != CAM_REQ_CMP)
		return (status);

	xpt_async(AC_LOST_DEVICE, &bus_path, NULL);
	xpt_async(AC_PATH_DEREGISTERED, &bus_path, NULL);

	/* Release the reference count held while registered. */
	xpt_release_bus(bus_path.bus);
	xpt_release_path(&bus_path);

	return (CAM_REQ_CMP);
}

static path_id_t
xptnextfreepathid(void)
{
	struct cam_eb *bus;
	path_id_t pathid;
	const char *strval;

	mtx_assert(&xsoftc.xpt_topo_lock, MA_OWNED);
	pathid = 0;
	bus = TAILQ_FIRST(&xsoftc.xpt_busses);
retry:
	/* Find an unoccupied pathid */
	while (bus != NULL && bus->path_id <= pathid) {
		if (bus->path_id == pathid)
			pathid++;
		bus = TAILQ_NEXT(bus, links);
	}

	/*
	 * Ensure that this pathid is not reserved for
	 * a bus that may be registered in the future.
	 */
	if (resource_string_value("scbus", pathid, "at", &strval) == 0) {
		++pathid;
		/* Start the search over */
		goto retry;
	}
	return (pathid);
}

static path_id_t
xptpathid(const char *sim_name, int sim_unit, int sim_bus)
{
	path_id_t pathid;
	int i, dunit, val;
	char buf[32];
	const char *dname;

	pathid = CAM_XPT_PATH_ID;
	snprintf(buf, sizeof(buf), "%s%d", sim_name, sim_unit);
	if (strcmp(buf, "xpt0") == 0 && sim_bus == 0)
		return (pathid);
	i = 0;
	while ((resource_find_match(&i, &dname, &dunit, "at", buf)) == 0) {
		if (strcmp(dname, "scbus")) {
			/* Avoid a bit of foot shooting. */
			continue;
		}
		if (dunit < 0)		/* unwired?! */
			continue;
		if (resource_int_value("scbus", dunit, "bus", &val) == 0) {
			if (sim_bus == val) {
				pathid = dunit;
				break;
			}
		} else if (sim_bus == 0) {
			/* Unspecified matches bus 0 */
			pathid = dunit;
			break;
		} else {
			printf("Ambiguous scbus configuration for %s%d "
			       "bus %d, cannot wire down.  The kernel "
			       "config entry for scbus%d should "
			       "specify a controller bus.\n"
			       "Scbus will be assigned dynamically.\n",
			       sim_name, sim_unit, sim_bus, dunit);
			break;
		}
	}

	if (pathid == CAM_XPT_PATH_ID)
		pathid = xptnextfreepathid();
	return (pathid);
}

static const char *
xpt_async_string(u_int32_t async_code)
{

	switch (async_code) {
	case AC_BUS_RESET: return ("AC_BUS_RESET");
	case AC_UNSOL_RESEL: return ("AC_UNSOL_RESEL");
	case AC_SCSI_AEN: return ("AC_SCSI_AEN");
	case AC_SENT_BDR: return ("AC_SENT_BDR");
	case AC_PATH_REGISTERED: return ("AC_PATH_REGISTERED");
	case AC_PATH_DEREGISTERED: return ("AC_PATH_DEREGISTERED");
	case AC_FOUND_DEVICE: return ("AC_FOUND_DEVICE");
	case AC_LOST_DEVICE: return ("AC_LOST_DEVICE");
	case AC_TRANSFER_NEG: return ("AC_TRANSFER_NEG");
	case AC_INQ_CHANGED: return ("AC_INQ_CHANGED");
	case AC_GETDEV_CHANGED: return ("AC_GETDEV_CHANGED");
	case AC_CONTRACT: return ("AC_CONTRACT");
	case AC_ADVINFO_CHANGED: return ("AC_ADVINFO_CHANGED");
	case AC_UNIT_ATTENTION: return ("AC_UNIT_ATTENTION");
	}
	return ("AC_UNKNOWN");
}

static int
xpt_async_size(u_int32_t async_code)
{

	switch (async_code) {
	case AC_BUS_RESET: return (0);
	case AC_UNSOL_RESEL: return (0);
	case AC_SCSI_AEN: return (0);
	case AC_SENT_BDR: return (0);
	case AC_PATH_REGISTERED: return (sizeof(struct ccb_pathinq));
	case AC_PATH_DEREGISTERED: return (0);
	case AC_FOUND_DEVICE: return (sizeof(struct ccb_getdev));
	case AC_LOST_DEVICE: return (0);
	case AC_TRANSFER_NEG: return (sizeof(struct ccb_trans_settings));
	case AC_INQ_CHANGED: return (0);
	case AC_GETDEV_CHANGED: return (0);
	case AC_CONTRACT: return (sizeof(struct ac_contract));
	case AC_ADVINFO_CHANGED: return (-1);
	case AC_UNIT_ATTENTION: return (sizeof(struct ccb_scsiio));
	}
	return (0);
}

static int
xpt_async_process_dev(struct cam_ed *device, void *arg)
{
	union ccb *ccb = arg;
	struct cam_path *path = ccb->ccb_h.path;
	void *async_arg = ccb->casync.async_arg_ptr;
	u_int32_t async_code = ccb->casync.async_code;
	int relock;

	if (path->device != device
	 && path->device->lun_id != CAM_LUN_WILDCARD
	 && device->lun_id != CAM_LUN_WILDCARD)
		return (1);

	/*
	 * The async callback could free the device.
	 * If it is a broadcast async, it doesn't hold
	 * device reference, so take our own reference.
	 */
	xpt_acquire_device(device);

	/*
	 * If async for specific device is to be delivered to
	 * the wildcard client, take the specific device lock.
	 * XXX: We may need a way for client to specify it.
	 */
	if ((device->lun_id == CAM_LUN_WILDCARD &&
	     path->device->lun_id != CAM_LUN_WILDCARD) ||
	    (device->target->target_id == CAM_TARGET_WILDCARD &&
	     path->target->target_id != CAM_TARGET_WILDCARD) ||
	    (device->target->bus->path_id == CAM_BUS_WILDCARD &&
	     path->target->bus->path_id != CAM_BUS_WILDCARD)) {
		mtx_unlock(&device->device_mtx);
		xpt_path_lock(path);
		relock = 1;
	} else
		relock = 0;

	(*(device->target->bus->xport->ops->async))(async_code,
	    device->target->bus, device->target, device, async_arg);
	xpt_async_bcast(&device->asyncs, async_code, path, async_arg);

	if (relock) {
		xpt_path_unlock(path);
		mtx_lock(&device->device_mtx);
	}
	xpt_release_device(device);
	return (1);
}

static int
xpt_async_process_tgt(struct cam_et *target, void *arg)
{
	union ccb *ccb = arg;
	struct cam_path *path = ccb->ccb_h.path;

	if (path->target != target
	 && path->target->target_id != CAM_TARGET_WILDCARD
	 && target->target_id != CAM_TARGET_WILDCARD)
		return (1);

	if (ccb->casync.async_code == AC_SENT_BDR) {
		/* Update our notion of when the last reset occurred */
		microtime(&target->last_reset);
	}

	return (xptdevicetraverse(target, NULL, xpt_async_process_dev, ccb));
}

static void
xpt_async_process(struct cam_periph *periph, union ccb *ccb)
{
	struct cam_eb *bus;
	struct cam_path *path;
	void *async_arg;
	u_int32_t async_code;

	path = ccb->ccb_h.path;
	async_code = ccb->casync.async_code;
	async_arg = ccb->casync.async_arg_ptr;
	CAM_DEBUG(path, CAM_DEBUG_TRACE | CAM_DEBUG_INFO,
	    ("xpt_async(%s)\n", xpt_async_string(async_code)));
	bus = path->bus;

	if (async_code == AC_BUS_RESET) {
		/* Update our notion of when the last reset occurred */
		microtime(&bus->last_reset);
	}

	xpttargettraverse(bus, NULL, xpt_async_process_tgt, ccb);

	/*
	 * If this wasn't a fully wildcarded async, tell all
	 * clients that want all async events.
	 */
	if (bus != xpt_periph->path->bus) {
		xpt_path_lock(xpt_periph->path);
		xpt_async_process_dev(xpt_periph->path->device, ccb);
		xpt_path_unlock(xpt_periph->path);
	}

	if (path->device != NULL && path->device->lun_id != CAM_LUN_WILDCARD)
		xpt_release_devq(path, 1, TRUE);
	else
		xpt_release_simq(path->bus->sim, TRUE);
	if (ccb->casync.async_arg_size > 0)
		free(async_arg, M_CAMXPT);
	xpt_free_path(path);
	xpt_free_ccb(ccb);
}

static void
xpt_async_bcast(struct async_list *async_head,
		u_int32_t async_code,
		struct cam_path *path, void *async_arg)
{
	struct async_node *cur_entry;
	struct mtx *mtx;

	cur_entry = SLIST_FIRST(async_head);
	while (cur_entry != NULL) {
		struct async_node *next_entry;
		/*
		 * Grab the next list entry before we call the current
		 * entry's callback.  This is because the callback function
		 * can delete its async callback entry.
		 */
		next_entry = SLIST_NEXT(cur_entry, links);
		if ((cur_entry->event_enable & async_code) != 0) {
			mtx = cur_entry->event_lock ?
			    path->device->sim->mtx : NULL;
			if (mtx)
				mtx_lock(mtx);
			cur_entry->callback(cur_entry->callback_arg,
					    async_code, path,
					    async_arg);
			if (mtx)
				mtx_unlock(mtx);
		}
		cur_entry = next_entry;
	}
}

void
xpt_async(u_int32_t async_code, struct cam_path *path, void *async_arg)
{
	union ccb *ccb;
	int size;

	ccb = xpt_alloc_ccb_nowait();
	if (ccb == NULL) {
		xpt_print(path, "Can't allocate CCB to send %s\n",
		    xpt_async_string(async_code));
		return;
	}

	if (xpt_clone_path(&ccb->ccb_h.path, path) != CAM_REQ_CMP) {
		xpt_print(path, "Can't allocate path to send %s\n",
		    xpt_async_string(async_code));
		xpt_free_ccb(ccb);
		return;
	}
	ccb->ccb_h.path->periph = NULL;
	ccb->ccb_h.func_code = XPT_ASYNC;
	ccb->ccb_h.cbfcnp = xpt_async_process;
	ccb->ccb_h.flags |= CAM_UNLOCKED;
	ccb->casync.async_code = async_code;
	ccb->casync.async_arg_size = 0;
	size = xpt_async_size(async_code);
	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE,
	    ("xpt_async: func %#x %s aync_code %d %s\n",
		ccb->ccb_h.func_code,
		xpt_action_name(ccb->ccb_h.func_code),
		async_code,
		xpt_async_string(async_code)));
	if (size > 0 && async_arg != NULL) {
		ccb->casync.async_arg_ptr = malloc(size, M_CAMXPT, M_NOWAIT);
		if (ccb->casync.async_arg_ptr == NULL) {
			xpt_print(path, "Can't allocate argument to send %s\n",
			    xpt_async_string(async_code));
			xpt_free_path(ccb->ccb_h.path);
			xpt_free_ccb(ccb);
			return;
		}
		memcpy(ccb->casync.async_arg_ptr, async_arg, size);
		ccb->casync.async_arg_size = size;
	} else if (size < 0) {
		ccb->casync.async_arg_ptr = async_arg;
		ccb->casync.async_arg_size = size;
	}
	if (path->device != NULL && path->device->lun_id != CAM_LUN_WILDCARD)
		xpt_freeze_devq(path, 1);
	else
		xpt_freeze_simq(path->bus->sim, 1);
	xpt_action(ccb);
}

static void
xpt_dev_async_default(u_int32_t async_code, struct cam_eb *bus,
		      struct cam_et *target, struct cam_ed *device,
		      void *async_arg)
{

	/*
	 * We only need to handle events for real devices.
	 */
	if (target->target_id == CAM_TARGET_WILDCARD
	 || device->lun_id == CAM_LUN_WILDCARD)
		return;

	printf("%s called\n", __func__);
}

static uint32_t
xpt_freeze_devq_device(struct cam_ed *dev, u_int count)
{
	struct cam_devq	*devq;
	uint32_t freeze;

	devq = dev->sim->devq;
	mtx_assert(&devq->send_mtx, MA_OWNED);
	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE,
	    ("xpt_freeze_devq_device(%d) %u->%u\n", count,
	    dev->ccbq.queue.qfrozen_cnt, dev->ccbq.queue.qfrozen_cnt + count));
	freeze = (dev->ccbq.queue.qfrozen_cnt += count);
	/* Remove frozen device from sendq. */
	if (device_is_queued(dev))
		camq_remove(&devq->send_queue, dev->devq_entry.index);
	return (freeze);
}

u_int32_t
xpt_freeze_devq(struct cam_path *path, u_int count)
{
	struct cam_ed	*dev = path->device;
	struct cam_devq	*devq;
	uint32_t	 freeze;

	devq = dev->sim->devq;
	mtx_lock(&devq->send_mtx);
	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_freeze_devq(%d)\n", count));
	freeze = xpt_freeze_devq_device(dev, count);
	mtx_unlock(&devq->send_mtx);
	return (freeze);
}

u_int32_t
xpt_freeze_simq(struct cam_sim *sim, u_int count)
{
	struct cam_devq	*devq;
	uint32_t	 freeze;

	devq = sim->devq;
	mtx_lock(&devq->send_mtx);
	freeze = (devq->send_queue.qfrozen_cnt += count);
	mtx_unlock(&devq->send_mtx);
	return (freeze);
}

static void
xpt_release_devq_timeout(void *arg)
{
	struct cam_ed *dev;
	struct cam_devq *devq;

	dev = (struct cam_ed *)arg;
	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE, ("xpt_release_devq_timeout\n"));
	devq = dev->sim->devq;
	mtx_assert(&devq->send_mtx, MA_OWNED);
	if (xpt_release_devq_device(dev, /*count*/1, /*run_queue*/TRUE))
		xpt_run_devq(devq);
}

void
xpt_release_devq(struct cam_path *path, u_int count, int run_queue)
{
	struct cam_ed *dev;
	struct cam_devq *devq;

	CAM_DEBUG(path, CAM_DEBUG_TRACE, ("xpt_release_devq(%d, %d)\n",
	    count, run_queue));
	dev = path->device;
	devq = dev->sim->devq;
	mtx_lock(&devq->send_mtx);
	if (xpt_release_devq_device(dev, count, run_queue))
		xpt_run_devq(dev->sim->devq);
	mtx_unlock(&devq->send_mtx);
}

static int
xpt_release_devq_device(struct cam_ed *dev, u_int count, int run_queue)
{

	mtx_assert(&dev->sim->devq->send_mtx, MA_OWNED);
	CAM_DEBUG_DEV(dev, CAM_DEBUG_TRACE,
	    ("xpt_release_devq_device(%d, %d) %u->%u\n", count, run_queue,
	    dev->ccbq.queue.qfrozen_cnt, dev->ccbq.queue.qfrozen_cnt - count));
	if (count > dev->ccbq.queue.qfrozen_cnt) {
#ifdef INVARIANTS
		printf("xpt_release_devq(): requested %u > present %u\n",
		    count, dev->ccbq.queue.qfrozen_cnt);
#endif
		count = dev->ccbq.queue.qfrozen_cnt;
	}
	dev->ccbq.queue.qfrozen_cnt -= count;
	if (dev->ccbq.queue.qfrozen_cnt == 0) {
		/*
		 * No longer need to wait for a successful
		 * command completion.
		 */
		dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
		/*
		 * Remove any timeouts that might be scheduled
		 * to release this queue.
		 */
		if ((dev->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0) {
			callout_stop(&dev->callout);
			dev->flags &= ~CAM_DEV_REL_TIMEOUT_PENDING;
		}
		/*
		 * Now that we are unfrozen schedule the
		 * device so any pending transactions are
		 * run.
		 */
		xpt_schedule_devq(dev->sim->devq, dev);
	} else
		run_queue = 0;
	return (run_queue);
}

void
xpt_release_simq(struct cam_sim *sim, int run_queue)
{
	struct cam_devq	*devq;

	devq = sim->devq;
	mtx_lock(&devq->send_mtx);
	if (devq->send_queue.qfrozen_cnt <= 0) {
#ifdef INVARIANTS
		printf("xpt_release_simq: requested 1 > present %u\n",
		    devq->send_queue.qfrozen_cnt);
#endif
	} else
		devq->send_queue.qfrozen_cnt--;
	if (devq->send_queue.qfrozen_cnt == 0) {
		/*
		 * If there is a timeout scheduled to release this
		 * sim queue, remove it.  The queue frozen count is
		 * already at 0.
		 */
		if ((sim->flags & CAM_SIM_REL_TIMEOUT_PENDING) != 0){
			callout_stop(&sim->callout);
			sim->flags &= ~CAM_SIM_REL_TIMEOUT_PENDING;
		}
		if (run_queue) {
			/*
			 * Now that we are unfrozen run the send queue.
			 */
			xpt_run_devq(sim->devq);
		}
	}
	mtx_unlock(&devq->send_mtx);
}

void
xpt_done(union ccb *done_ccb)
{
	struct cam_doneq *queue;
	int	run, hash;

#if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
	if (done_ccb->ccb_h.func_code == XPT_SCSI_IO &&
	    done_ccb->csio.bio != NULL)
		biotrack(done_ccb->csio.bio, __func__);
#endif

	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
	    ("xpt_done: func= %#x %s status %#x\n",
		done_ccb->ccb_h.func_code,
		xpt_action_name(done_ccb->ccb_h.func_code),
		done_ccb->ccb_h.status));
	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0)
		return;

	/* Store the time the ccb was in the sim */
	done_ccb->ccb_h.qos.periph_data = cam_iosched_delta_t(done_ccb->ccb_h.qos.periph_data);
	hash = (u_int)(done_ccb->ccb_h.path_id + done_ccb->ccb_h.target_id +
	    done_ccb->ccb_h.target_lun) % cam_num_doneqs;
	queue = &cam_doneqs[hash];
	mtx_lock(&queue->cam_doneq_mtx);
	run = (queue->cam_doneq_sleep && STAILQ_EMPTY(&queue->cam_doneq));
	STAILQ_INSERT_TAIL(&queue->cam_doneq, &done_ccb->ccb_h, sim_links.stqe);
	done_ccb->ccb_h.pinfo.index = CAM_DONEQ_INDEX;
	mtx_unlock(&queue->cam_doneq_mtx);
	if (run)
		wakeup(&queue->cam_doneq);
}

void
xpt_done_direct(union ccb *done_ccb)
{

	CAM_DEBUG(done_ccb->ccb_h.path, CAM_DEBUG_TRACE,
	    ("xpt_done_direct: status %#x\n", done_ccb->ccb_h.status));
	if ((done_ccb->ccb_h.func_code & XPT_FC_QUEUED) == 0)
		return;

	/* Store the time the ccb was in the sim */
	done_ccb->ccb_h.qos.periph_data = cam_iosched_delta_t(done_ccb->ccb_h.qos.periph_data);
	xpt_done_process(&done_ccb->ccb_h);
}

union ccb *
xpt_alloc_ccb(void)
{
	union ccb *new_ccb;

	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
	return (new_ccb);
}

union ccb *
xpt_alloc_ccb_nowait(void)
{
	union ccb *new_ccb;

	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
	return (new_ccb);
}

void
xpt_free_ccb(union ccb *free_ccb)
{
	free(free_ccb, M_CAMCCB);
}

/* Private XPT functions */

/*
 * Get a CAM control block for the caller. Charge the structure to the device
 * referenced by the path.  If we don't have sufficient resources to allocate
 * more ccbs, we return NULL.
 */
static union ccb *
xpt_get_ccb_nowait(struct cam_periph *periph)
{
	union ccb *new_ccb;

	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_NOWAIT);
	if (new_ccb == NULL)
		return (NULL);
	periph->periph_allocated++;
	cam_ccbq_take_opening(&periph->path->device->ccbq);
	return (new_ccb);
}

static union ccb *
xpt_get_ccb(struct cam_periph *periph)
{
	union ccb *new_ccb;

	cam_periph_unlock(periph);
	new_ccb = malloc(sizeof(*new_ccb), M_CAMCCB, M_ZERO|M_WAITOK);
	cam_periph_lock(periph);
	periph->periph_allocated++;
	cam_ccbq_take_opening(&periph->path->device->ccbq);
	return (new_ccb);
}

union ccb *
cam_periph_getccb(struct cam_periph *periph, u_int32_t priority)
{
	struct ccb_hdr *ccb_h;

	CAM_DEBUG(periph->path, CAM_DEBUG_TRACE, ("cam_periph_getccb\n"));
	cam_periph_assert(periph, MA_OWNED);
	while ((ccb_h = SLIST_FIRST(&periph->ccb_list)) == NULL ||
	    ccb_h->pinfo.priority != priority) {
		if (priority < periph->immediate_priority) {
			periph->immediate_priority = priority;
			xpt_run_allocq(periph, 0);
		} else
			cam_periph_sleep(periph, &periph->ccb_list, PRIBIO,
			    "cgticb", 0);
	}
	SLIST_REMOVE_HEAD(&periph->ccb_list, periph_links.sle);
	return ((union ccb *)ccb_h);
}

static void
xpt_acquire_bus(struct cam_eb *bus)
{

	xpt_lock_buses();
	bus->refcount++;
	xpt_unlock_buses();
}

static void
xpt_release_bus(struct cam_eb *bus)
{

	xpt_lock_buses();
	KASSERT(bus->refcount >= 1, ("bus->refcount >= 1"));
	if (--bus->refcount > 0) {
		xpt_unlock_buses();
		return;
	}
	TAILQ_REMOVE(&xsoftc.xpt_busses, bus, links);
	xsoftc.bus_generation++;
	xpt_unlock_buses();
	KASSERT(TAILQ_EMPTY(&bus->et_entries),
	    ("destroying bus, but target list is not empty"));
	cam_sim_release(bus->sim);
	mtx_destroy(&bus->eb_mtx);
	free(bus, M_CAMXPT);
}

static struct cam_et *
xpt_alloc_target(struct cam_eb *bus, target_id_t target_id)
{
	struct cam_et *cur_target, *target;

	mtx_assert(&xsoftc.xpt_topo_lock, MA_OWNED);
	mtx_assert(&bus->eb_mtx, MA_OWNED);
	target = (struct cam_et *)malloc(sizeof(*target), M_CAMXPT,
					 M_NOWAIT|M_ZERO);
	if (target == NULL)
		return (NULL);

	TAILQ_INIT(&target->ed_entries);
	target->bus = bus;
	target->target_id = target_id;
	target->refcount = 1;
	target->generation = 0;
	target->luns = NULL;
	mtx_init(&target->luns_mtx, "CAM LUNs lock", NULL, MTX_DEF);
	timevalclear(&target->last_reset);
	/*
	 * Hold a reference to our parent bus so it
	 * will not go away before we do.
	 */
	bus->refcount++;

	/* Insertion sort into our bus's target list */
	cur_target = TAILQ_FIRST(&bus->et_entries);
	while (cur_target != NULL && cur_target->target_id < target_id)
		cur_target = TAILQ_NEXT(cur_target, links);
	if (cur_target != NULL) {
		TAILQ_INSERT_BEFORE(cur_target, target, links);
	} else {
		TAILQ_INSERT_TAIL(&bus->et_entries, target, links);
	}
	bus->generation++;
	return (target);
}

static void
xpt_acquire_target(struct cam_et *target)
{
	struct cam_eb *bus = target->bus;

	mtx_lock(&bus->eb_mtx);
	target->refcount++;
	mtx_unlock(&bus->eb_mtx);
}

static void
xpt_release_target(struct cam_et *target)
{
	struct cam_eb *bus = target->bus;

	mtx_lock(&bus->eb_mtx);
	if (--target->refcount > 0) {
		mtx_unlock(&bus->eb_mtx);
		return;
	}
	TAILQ_REMOVE(&bus->et_entries, target, links);
	bus->generation++;
	mtx_unlock(&bus->eb_mtx);
	KASSERT(TAILQ_EMPTY(&target->ed_entries),
	    ("destroying target, but device list is not empty"));
	xpt_release_bus(bus);
	mtx_destroy(&target->luns_mtx);
	if (target->luns)
		free(target->luns, M_CAMXPT);
	free(target, M_CAMXPT);
}

static struct cam_ed *
xpt_alloc_device_default(struct cam_eb *bus, struct cam_et *target,
			 lun_id_t lun_id)
{
	struct cam_ed *device;

	device = xpt_alloc_device(bus, target, lun_id);
	if (device == NULL)
		return (NULL);

	device->mintags = 1;
	device->maxtags = 1;
	return (device);
}

static void
xpt_destroy_device(void *context, int pending)
{
	struct cam_ed	*device = context;

	mtx_lock(&device->device_mtx);
	mtx_destroy(&device->device_mtx);
	free(device, M_CAMDEV);
}

struct cam_ed *
xpt_alloc_device(struct cam_eb *bus, struct cam_et *target, lun_id_t lun_id)
{
	struct cam_ed	*cur_device, *device;
	struct cam_devq	*devq;
	cam_status status;

	mtx_assert(&bus->eb_mtx, MA_OWNED);
	/* Make space for us in the device queue on our bus */
	devq = bus->sim->devq;
	mtx_lock(&devq->send_mtx);
	status = cam_devq_resize(devq, devq->send_queue.array_size + 1);
	mtx_unlock(&devq->send_mtx);
	if (status != CAM_REQ_CMP)
		return (NULL);

	device = (struct cam_ed *)malloc(sizeof(*device),
					 M_CAMDEV, M_NOWAIT|M_ZERO);
	if (device == NULL)
		return (NULL);

	cam_init_pinfo(&device->devq_entry);
	device->target = target;
	device->lun_id = lun_id;
	device->sim = bus->sim;
	if (cam_ccbq_init(&device->ccbq,
			  bus->sim->max_dev_openings) != 0) {
		free(device, M_CAMDEV);
		return (NULL);
	}
	SLIST_INIT(&device->asyncs);
	SLIST_INIT(&device->periphs);
	device->generation = 0;
	device->flags = CAM_DEV_UNCONFIGURED;
	device->tag_delay_count = 0;
	device->tag_saved_openings = 0;
	device->refcount = 1;
	mtx_init(&device->device_mtx, "CAM device lock", NULL, MTX_DEF);
	callout_init_mtx(&device->callout, &devq->send_mtx, 0);
	TASK_INIT(&device->device_destroy_task, 0, xpt_destroy_device, device);
	/*
	 * Hold a reference to our parent bus so it
	 * will not go away before we do.
	 */
	target->refcount++;

	cur_device = TAILQ_FIRST(&target->ed_entries);
	while (cur_device != NULL && cur_device->lun_id < lun_id)
		cur_device = TAILQ_NEXT(cur_device, links);
	if (cur_device != NULL)
		TAILQ_INSERT_BEFORE(cur_device, device, links);
	else
		TAILQ_INSERT_TAIL(&target->ed_entries, device, links);
	target->generation++;
	return (device);
}

void
xpt_acquire_device(struct cam_ed *device)
{
	struct cam_eb *bus = device->target->bus;

	mtx_lock(&bus->eb_mtx);
	device->refcount++;
	mtx_unlock(&bus->eb_mtx);
}

void
xpt_release_device(struct cam_ed *device)
{
	struct cam_eb *bus = device->target->bus;
	struct cam_devq *devq;

	mtx_lock(&bus->eb_mtx);
	if (--device->refcount > 0) {
		mtx_unlock(&bus->eb_mtx);
		return;
	}

	TAILQ_REMOVE(&device->target->ed_entries, device,links);
	device->target->generation++;
	mtx_unlock(&bus->eb_mtx);

	/* Release our slot in the devq */
	devq = bus->sim->devq;
	mtx_lock(&devq->send_mtx);
	cam_devq_resize(devq, devq->send_queue.array_size - 1);

	KASSERT(SLIST_EMPTY(&device->periphs),
	    ("destroying device, but periphs list is not empty"));
	KASSERT(device->devq_entry.index == CAM_UNQUEUED_INDEX,
	    ("destroying device while still queued for ccbs"));

	/* The send_mtx must be held when accessing the callout */
	if ((device->flags & CAM_DEV_REL_TIMEOUT_PENDING) != 0)
		callout_stop(&device->callout);

	mtx_unlock(&devq->send_mtx);

	xpt_release_target(device->target);

	cam_ccbq_fini(&device->ccbq);
	/*
	 * Free allocated memory.  free(9) does nothing if the
	 * supplied pointer is NULL, so it is safe to call without
	 * checking.
	 */
	free(device->supported_vpds, M_CAMXPT);
	free(device->device_id, M_CAMXPT);
	free(device->ext_inq, M_CAMXPT);
	free(device->physpath, M_CAMXPT);
	free(device->rcap_buf, M_CAMXPT);
	free(device->serial_num, M_CAMXPT);
	free(device->nvme_data, M_CAMXPT);
	free(device->nvme_cdata, M_CAMXPT);
	taskqueue_enqueue(xsoftc.xpt_taskq, &device->device_destroy_task);
}

u_int32_t
xpt_dev_ccbq_resize(struct cam_path *path, int newopenings)
{
	int	result;
	struct	cam_ed *dev;

	dev = path->device;
	mtx_lock(&dev->sim->devq->send_mtx);
	result = cam_ccbq_resize(&dev->ccbq, newopenings);
	mtx_unlock(&dev->sim->devq->send_mtx);
	if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
	 || (dev->inq_flags & SID_CmdQue) != 0)
		dev->tag_saved_openings = newopenings;
	return (result);
}

static struct cam_eb *
xpt_find_bus(path_id_t path_id)
{
	struct cam_eb *bus;

	xpt_lock_buses();
	for (bus = TAILQ_FIRST(&xsoftc.xpt_busses);
	     bus != NULL;
	     bus = TAILQ_NEXT(bus, links)) {
		if (bus->path_id == path_id) {
			bus->refcount++;
			break;
		}
	}
	xpt_unlock_buses();
	return (bus);
}

static struct cam_et *
xpt_find_target(struct cam_eb *bus, target_id_t	target_id)
{
	struct cam_et *target;

	mtx_assert(&bus->eb_mtx, MA_OWNED);
	for (target = TAILQ_FIRST(&bus->et_entries);
	     target != NULL;
	     target = TAILQ_NEXT(target, links)) {
		if (target->target_id == target_id) {
			target->refcount++;
			break;
		}
	}
	return (target);
}

static struct cam_ed *
xpt_find_device(struct cam_et *target, lun_id_t lun_id)
{
	struct cam_ed *device;

	mtx_assert(&target->bus->eb_mtx, MA_OWNED);
	for (device = TAILQ_FIRST(&target->ed_entries);
	     device != NULL;
	     device = TAILQ_NEXT(device, links)) {
		if (device->lun_id == lun_id) {
			device->refcount++;
			break;
		}
	}
	return (device);
}

void
xpt_start_tags(struct cam_path *path)
{
	struct ccb_relsim crs;
	struct cam_ed *device;
	struct cam_sim *sim;
	int    newopenings;

	device = path->device;
	sim = path->bus->sim;
	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
	xpt_freeze_devq(path, /*count*/1);
	device->inq_flags |= SID_CmdQue;
	if (device->tag_saved_openings != 0)
		newopenings = device->tag_saved_openings;
	else
		newopenings = min(device->maxtags,
				  sim->max_tagged_dev_openings);
	xpt_dev_ccbq_resize(path, newopenings);
	xpt_async(AC_GETDEV_CHANGED, path, NULL);
	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
	crs.ccb_h.func_code = XPT_REL_SIMQ;
	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
	crs.openings
	    = crs.release_timeout
	    = crs.qfrozen_cnt
	    = 0;
	xpt_action((union ccb *)&crs);
}

void
xpt_stop_tags(struct cam_path *path)
{
	struct ccb_relsim crs;
	struct cam_ed *device;
	struct cam_sim *sim;

	device = path->device;
	sim = path->bus->sim;
	device->flags &= ~CAM_DEV_TAG_AFTER_COUNT;
	device->tag_delay_count = 0;
	xpt_freeze_devq(path, /*count*/1);
	device->inq_flags &= ~SID_CmdQue;
	xpt_dev_ccbq_resize(path, sim->max_dev_openings);
	xpt_async(AC_GETDEV_CHANGED, path, NULL);
	xpt_setup_ccb(&crs.ccb_h, path, CAM_PRIORITY_NORMAL);
	crs.ccb_h.func_code = XPT_REL_SIMQ;
	crs.release_flags = RELSIM_RELEASE_AFTER_QEMPTY;
	crs.openings
	    = crs.release_timeout
	    = crs.qfrozen_cnt
	    = 0;
	xpt_action((union ccb *)&crs);
}

/*
 * Assume all possible buses are detected by this time, so allow boot
 * as soon as they all are scanned.
 */
static void
xpt_boot_delay(void *arg)
{

	xpt_release_boot();
}

/*
 * Now that all config hooks have completed, start boot_delay timer,
 * waiting for possibly still undetected buses (USB) to appear.
 */
static void
xpt_ch_done(void *arg)
{

	callout_init(&xsoftc.boot_callout, 1);
	callout_reset_sbt(&xsoftc.boot_callout, SBT_1MS * xsoftc.boot_delay, 0,
	    xpt_boot_delay, NULL, 0);
}
SYSINIT(xpt_hw_delay, SI_SUB_INT_CONFIG_HOOKS, SI_ORDER_ANY, xpt_ch_done, NULL);

/*
 * Now that interrupts are enabled, go find our devices
 */
static void
xpt_config(void *arg)
{
	if (taskqueue_start_threads(&xsoftc.xpt_taskq, 1, PRIBIO, "CAM taskq"))
		printf("xpt_config: failed to create taskqueue thread.\n");

	/* Setup debugging path */
	if (cam_dflags != CAM_DEBUG_NONE) {
		if (xpt_create_path(&cam_dpath, NULL,
				    CAM_DEBUG_BUS, CAM_DEBUG_TARGET,
				    CAM_DEBUG_LUN) != CAM_REQ_CMP) {
			printf("xpt_config: xpt_create_path() failed for debug"
			       " target %d:%d:%d, debugging disabled\n",
			       CAM_DEBUG_BUS, CAM_DEBUG_TARGET, CAM_DEBUG_LUN);
			cam_dflags = CAM_DEBUG_NONE;
		}
	} else
		cam_dpath = NULL;

	periphdriver_init(1);
	xpt_hold_boot();

	/* Fire up rescan thread. */
	if (kproc_kthread_add(xpt_scanner_thread, NULL, &cam_proc, NULL, 0, 0,
	    "cam", "scanner")) {
		printf("xpt_config: failed to create rescan thread.\n");
	}
}

void
xpt_hold_boot_locked(void)
{

	if (xsoftc.buses_to_config++ == 0)
		root_mount_hold_token("CAM", &xsoftc.xpt_rootmount);
}

void
xpt_hold_boot(void)
{

	xpt_lock_buses();
	xpt_hold_boot_locked();
	xpt_unlock_buses();
}

void
xpt_release_boot(void)
{

	xpt_lock_buses();
	if (--xsoftc.buses_to_config == 0) {
		if (xsoftc.buses_config_done == 0) {
			xsoftc.buses_config_done = 1;
			xsoftc.buses_to_config++;
			TASK_INIT(&xsoftc.boot_task, 0, xpt_finishconfig_task,
			    NULL);
			taskqueue_enqueue(taskqueue_thread, &xsoftc.boot_task);
		} else
			root_mount_rel(&xsoftc.xpt_rootmount);
	}
	xpt_unlock_buses();
}

/*
 * If the given device only has one peripheral attached to it, and if that
 * peripheral is the passthrough driver, announce it.  This insures that the
 * user sees some sort of announcement for every peripheral in their system.
 */
static int
xptpassannouncefunc(struct cam_ed *device, void *arg)
{
	struct cam_periph *periph;
	int i;

	for (periph = SLIST_FIRST(&device->periphs), i = 0; periph != NULL;
	     periph = SLIST_NEXT(periph, periph_links), i++);

	periph = SLIST_FIRST(&device->periphs);
	if ((i == 1)
	 && (strncmp(periph->periph_name, "pass", 4) == 0))
		xpt_announce_periph(periph, NULL);

	return(1);
}

static void
xpt_finishconfig_task(void *context, int pending)
{

	periphdriver_init(2);
	/*
	 * Check for devices with no "standard" peripheral driver
	 * attached.  For any devices like that, announce the
	 * passthrough driver so the user will see something.
	 */
	if (!bootverbose)
		xpt_for_all_devices(xptpassannouncefunc, NULL);

	xpt_release_boot();
}

cam_status
xpt_register_async(int event, ac_callback_t *cbfunc, void *cbarg,
		   struct cam_path *path)
{
	struct ccb_setasync csa;
	cam_status status;
	int xptpath = 0;

	if (path == NULL) {
		status = xpt_create_path(&path, /*periph*/NULL, CAM_XPT_PATH_ID,
					 CAM_TARGET_WILDCARD, CAM_LUN_WILDCARD);
		if (status != CAM_REQ_CMP)
			return (status);
		xpt_path_lock(path);
		xptpath = 1;
	}

	xpt_setup_ccb(&csa.ccb_h, path, CAM_PRIORITY_NORMAL);
	csa.ccb_h.func_code = XPT_SASYNC_CB;
	csa.event_enable = event;
	csa.callback = cbfunc;
	csa.callback_arg = cbarg;
	xpt_action((union ccb *)&csa);
	status = csa.ccb_h.status;

	CAM_DEBUG(csa.ccb_h.path, CAM_DEBUG_TRACE,
	    ("xpt_register_async: func %p\n", cbfunc));

	if (xptpath) {
		xpt_path_unlock(path);
		xpt_free_path(path);
	}

	if ((status == CAM_REQ_CMP) &&
	    (csa.event_enable & AC_FOUND_DEVICE)) {
		/*
		 * Get this peripheral up to date with all
		 * the currently existing devices.
		 */
		xpt_for_all_devices(xptsetasyncfunc, &csa);
	}
	if ((status == CAM_REQ_CMP) &&
	    (csa.event_enable & AC_PATH_REGISTERED)) {
		/*
		 * Get this peripheral up to date with all
		 * the currently existing buses.
		 */
		xpt_for_all_busses(xptsetasyncbusfunc, &csa);
	}

	return (status);
}

static void
xptaction(struct cam_sim *sim, union ccb *work_ccb)
{
	CAM_DEBUG(work_ccb->ccb_h.path, CAM_DEBUG_TRACE, ("xptaction\n"));

	switch (work_ccb->ccb_h.func_code) {
	/* Common cases first */
	case XPT_PATH_INQ:		/* Path routing inquiry */
	{
		struct ccb_pathinq *cpi;

		cpi = &work_ccb->cpi;
		cpi->version_num = 1; /* XXX??? */
		cpi->hba_inquiry = 0;
		cpi->target_sprt = 0;
		cpi->hba_misc = 0;
		cpi->hba_eng_cnt = 0;
		cpi->max_target = 0;
		cpi->max_lun = 0;
		cpi->initiator_id = 0;
		strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
		strlcpy(cpi->hba_vid, "", HBA_IDLEN);
		strlcpy(cpi->dev_name, sim->sim_name, DEV_IDLEN);
		cpi->unit_number = sim->unit_number;
		cpi->bus_id = sim->bus_id;
		cpi->base_transfer_speed = 0;
		cpi->protocol = PROTO_UNSPECIFIED;
		cpi->protocol_version = PROTO_VERSION_UNSPECIFIED;
		cpi->transport = XPORT_UNSPECIFIED;
		cpi->transport_version = XPORT_VERSION_UNSPECIFIED;
		cpi->ccb_h.status = CAM_REQ_CMP;
		break;
	}
	default:
		work_ccb->ccb_h.status = CAM_REQ_INVALID;
		break;
	}
	xpt_done(work_ccb);
}

/*
 * The xpt as a "controller" has no interrupt sources, so polling
 * is a no-op.
 */
static void
xptpoll(struct cam_sim *sim)
{
}

void
xpt_lock_buses(void)
{
	mtx_lock(&xsoftc.xpt_topo_lock);
}

void
xpt_unlock_buses(void)
{
	mtx_unlock(&xsoftc.xpt_topo_lock);
}

struct mtx *
xpt_path_mtx(struct cam_path *path)
{

	return (&path->device->device_mtx);
}

static void
xpt_done_process(struct ccb_hdr *ccb_h)
{
	struct cam_sim *sim = NULL;
	struct cam_devq *devq = NULL;
	struct mtx *mtx = NULL;

#if defined(BUF_TRACKING) || defined(FULL_BUF_TRACKING)
	struct ccb_scsiio *csio;

	if (ccb_h->func_code == XPT_SCSI_IO) {
		csio = &((union ccb *)ccb_h)->csio;
		if (csio->bio != NULL)
			biotrack(csio->bio, __func__);
	}
#endif

	if (ccb_h->flags & CAM_HIGH_POWER) {
		struct highpowerlist	*hphead;
		struct cam_ed		*device;

		mtx_lock(&xsoftc.xpt_highpower_lock);
		hphead = &xsoftc.highpowerq;

		device = STAILQ_FIRST(hphead);

		/*
		 * Increment the count since this command is done.
		 */
		xsoftc.num_highpower++;

		/*
		 * Any high powered commands queued up?
		 */
		if (device != NULL) {
			STAILQ_REMOVE_HEAD(hphead, highpowerq_entry);
			mtx_unlock(&xsoftc.xpt_highpower_lock);

			mtx_lock(&device->sim->devq->send_mtx);
			xpt_release_devq_device(device,
					 /*count*/1, /*runqueue*/TRUE);
			mtx_unlock(&device->sim->devq->send_mtx);
		} else
			mtx_unlock(&xsoftc.xpt_highpower_lock);
	}

	/*
	 * Insulate against a race where the periph is destroyed but CCBs are
	 * still not all processed. This shouldn't happen, but allows us better
	 * bug diagnostic when it does.
	 */
	if (ccb_h->path->bus)
		sim = ccb_h->path->bus->sim;

	if (ccb_h->status & CAM_RELEASE_SIMQ) {
		KASSERT(sim, ("sim missing for CAM_RELEASE_SIMQ request"));
		xpt_release_simq(sim, /*run_queue*/FALSE);
		ccb_h->status &= ~CAM_RELEASE_SIMQ;
	}

	if ((ccb_h->flags & CAM_DEV_QFRZDIS)
	 && (ccb_h->status & CAM_DEV_QFRZN)) {
		xpt_release_devq(ccb_h->path, /*count*/1, /*run_queue*/TRUE);
		ccb_h->status &= ~CAM_DEV_QFRZN;
	}

	if ((ccb_h->func_code & XPT_FC_USER_CCB) == 0) {
		struct cam_ed *dev = ccb_h->path->device;

		if (sim)
			devq = sim->devq;
		KASSERT(devq, ("Periph disappeared with CCB %p %s request pending.",
			ccb_h, xpt_action_name(ccb_h->func_code)));

		mtx_lock(&devq->send_mtx);
		devq->send_active--;
		devq->send_openings++;
		cam_ccbq_ccb_done(&dev->ccbq, (union ccb *)ccb_h);

		if (((dev->flags & CAM_DEV_REL_ON_QUEUE_EMPTY) != 0
		  && (dev->ccbq.dev_active == 0))) {
			dev->flags &= ~CAM_DEV_REL_ON_QUEUE_EMPTY;
			xpt_release_devq_device(dev, /*count*/1,
					 /*run_queue*/FALSE);
		}

		if (((dev->flags & CAM_DEV_REL_ON_COMPLETE) != 0
		  && (ccb_h->status&CAM_STATUS_MASK) != CAM_REQUEUE_REQ)) {
			dev->flags &= ~CAM_DEV_REL_ON_COMPLETE;
			xpt_release_devq_device(dev, /*count*/1,
					 /*run_queue*/FALSE);
		}

		if (!device_is_queued(dev))
			(void)xpt_schedule_devq(devq, dev);
		xpt_run_devq(devq);
		mtx_unlock(&devq->send_mtx);

		if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0) {
			mtx = xpt_path_mtx(ccb_h->path);
			mtx_lock(mtx);

			if ((dev->flags & CAM_DEV_TAG_AFTER_COUNT) != 0
			 && (--dev->tag_delay_count == 0))
				xpt_start_tags(ccb_h->path);
		}
	}

	if ((ccb_h->flags & CAM_UNLOCKED) == 0) {
		if (mtx == NULL) {
			mtx = xpt_path_mtx(ccb_h->path);
			mtx_lock(mtx);
		}
	} else {
		if (mtx != NULL) {
			mtx_unlock(mtx);
			mtx = NULL;
		}
	}

	/* Call the peripheral driver's callback */
	ccb_h->pinfo.index = CAM_UNQUEUED_INDEX;
	(*ccb_h->cbfcnp)(ccb_h->path->periph, (union ccb *)ccb_h);
	if (mtx != NULL)
		mtx_unlock(mtx);
}

void
xpt_done_td(void *arg)
{
	struct cam_doneq *queue = arg;
	struct ccb_hdr *ccb_h;
	STAILQ_HEAD(, ccb_hdr)	doneq;

	STAILQ_INIT(&doneq);
	mtx_lock(&queue->cam_doneq_mtx);
	while (1) {
		while (STAILQ_EMPTY(&queue->cam_doneq)) {
			queue->cam_doneq_sleep = 1;
			msleep(&queue->cam_doneq, &queue->cam_doneq_mtx,
			    PRIBIO, "-", 0);
			queue->cam_doneq_sleep = 0;
		}
		STAILQ_CONCAT(&doneq, &queue->cam_doneq);
		mtx_unlock(&queue->cam_doneq_mtx);

		THREAD_NO_SLEEPING();
		while ((ccb_h = STAILQ_FIRST(&doneq)) != NULL) {
			STAILQ_REMOVE_HEAD(&doneq, sim_links.stqe);
			xpt_done_process(ccb_h);
		}
		THREAD_SLEEPING_OK();

		mtx_lock(&queue->cam_doneq_mtx);
	}
}

static void
camisr_runqueue(void)
{
	struct	ccb_hdr *ccb_h;
	struct cam_doneq *queue;
	int i;

	/* Process global queues. */
	for (i = 0; i < cam_num_doneqs; i++) {
		queue = &cam_doneqs[i];
		mtx_lock(&queue->cam_doneq_mtx);
		while ((ccb_h = STAILQ_FIRST(&queue->cam_doneq)) != NULL) {
			STAILQ_REMOVE_HEAD(&queue->cam_doneq, sim_links.stqe);
			mtx_unlock(&queue->cam_doneq_mtx);
			xpt_done_process(ccb_h);
			mtx_lock(&queue->cam_doneq_mtx);
		}
		mtx_unlock(&queue->cam_doneq_mtx);
	}
}

struct kv 
{
	uint32_t v;
	const char *name;
};

static struct kv map[] = {
	{ XPT_NOOP, "XPT_NOOP" },
	{ XPT_SCSI_IO, "XPT_SCSI_IO" },
	{ XPT_GDEV_TYPE, "XPT_GDEV_TYPE" },
	{ XPT_GDEVLIST, "XPT_GDEVLIST" },
	{ XPT_PATH_INQ, "XPT_PATH_INQ" },
	{ XPT_REL_SIMQ, "XPT_REL_SIMQ" },
	{ XPT_SASYNC_CB, "XPT_SASYNC_CB" },
	{ XPT_SDEV_TYPE, "XPT_SDEV_TYPE" },
	{ XPT_SCAN_BUS, "XPT_SCAN_BUS" },
	{ XPT_DEV_MATCH, "XPT_DEV_MATCH" },
	{ XPT_DEBUG, "XPT_DEBUG" },
	{ XPT_PATH_STATS, "XPT_PATH_STATS" },
	{ XPT_GDEV_STATS, "XPT_GDEV_STATS" },
	{ XPT_DEV_ADVINFO, "XPT_DEV_ADVINFO" },
	{ XPT_ASYNC, "XPT_ASYNC" },
	{ XPT_ABORT, "XPT_ABORT" },
	{ XPT_RESET_BUS, "XPT_RESET_BUS" },
	{ XPT_RESET_DEV, "XPT_RESET_DEV" },
	{ XPT_TERM_IO, "XPT_TERM_IO" },
	{ XPT_SCAN_LUN, "XPT_SCAN_LUN" },
	{ XPT_GET_TRAN_SETTINGS, "XPT_GET_TRAN_SETTINGS" },
	{ XPT_SET_TRAN_SETTINGS, "XPT_SET_TRAN_SETTINGS" },
	{ XPT_CALC_GEOMETRY, "XPT_CALC_GEOMETRY" },
	{ XPT_ATA_IO, "XPT_ATA_IO" },
	{ XPT_GET_SIM_KNOB, "XPT_GET_SIM_KNOB" },
	{ XPT_SET_SIM_KNOB, "XPT_SET_SIM_KNOB" },
	{ XPT_NVME_IO, "XPT_NVME_IO" },
	{ XPT_MMC_IO, "XPT_MMC_IO" },
	{ XPT_SMP_IO, "XPT_SMP_IO" },
	{ XPT_SCAN_TGT, "XPT_SCAN_TGT" },
	{ XPT_NVME_ADMIN, "XPT_NVME_ADMIN" },
	{ XPT_ENG_INQ, "XPT_ENG_INQ" },
	{ XPT_ENG_EXEC, "XPT_ENG_EXEC" },
	{ XPT_EN_LUN, "XPT_EN_LUN" },
	{ XPT_TARGET_IO, "XPT_TARGET_IO" },
	{ XPT_ACCEPT_TARGET_IO, "XPT_ACCEPT_TARGET_IO" },
	{ XPT_CONT_TARGET_IO, "XPT_CONT_TARGET_IO" },
	{ XPT_IMMED_NOTIFY, "XPT_IMMED_NOTIFY" },
	{ XPT_NOTIFY_ACK, "XPT_NOTIFY_ACK" },
	{ XPT_IMMEDIATE_NOTIFY, "XPT_IMMEDIATE_NOTIFY" },
	{ XPT_NOTIFY_ACKNOWLEDGE, "XPT_NOTIFY_ACKNOWLEDGE" },
	{ 0, 0 }
};

const char *
xpt_action_name(uint32_t action) 
{
	static char buffer[32];	/* Only for unknown messages -- racy */
	struct kv *walker = map;

	while (walker->name != NULL) {
		if (walker->v == action)
			return (walker->name);
		walker++;
	}

	snprintf(buffer, sizeof(buffer), "%#x", action);
	return (buffer);
}