summaryrefslogtreecommitdiff
path: root/sys/dev/softraid.c
blob: 1318d134bb8df0c9f1e1654c04319ce953f47d34 (plain)
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
/* $OpenBSD: softraid.c,v 1.331 2014/01/22 23:32:42 jsing Exp $ */
/*
 * Copyright (c) 2007, 2008, 2009 Marco Peereboom <marco@peereboom.us>
 * Copyright (c) 2008 Chris Kuethe <ckuethe@openbsd.org>
 * Copyright (c) 2009 Joel Sing <jsing@openbsd.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include "bio.h"

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/buf.h>
#include <sys/device.h>
#include <sys/ioctl.h>
#include <sys/proc.h>
#include <sys/malloc.h>
#include <sys/pool.h>
#include <sys/kernel.h>
#include <sys/disk.h>
#include <sys/rwlock.h>
#include <sys/queue.h>
#include <sys/fcntl.h>
#include <sys/disklabel.h>
#include <sys/vnode.h>
#include <sys/mount.h>
#include <sys/sensors.h>
#include <sys/stat.h>
#include <sys/conf.h>
#include <sys/uio.h>
#include <sys/task.h>
#include <sys/kthread.h>
#include <sys/dkio.h>

#ifdef AOE
#include <sys/mbuf.h>
#include <net/if_aoe.h>
#endif /* AOE */

#include <crypto/cryptodev.h>

#include <scsi/scsi_all.h>
#include <scsi/scsiconf.h>
#include <scsi/scsi_disk.h>

#include <dev/softraidvar.h>
#include <dev/rndvar.h>

/* #define SR_FANCY_STATS */

#ifdef SR_DEBUG
#define SR_FANCY_STATS
uint32_t	sr_debug = 0
		    /* | SR_D_CMD */
		    /* | SR_D_MISC */
		    /* | SR_D_INTR */
		    /* | SR_D_IOCTL */
		    /* | SR_D_CCB */
		    /* | SR_D_WU */
		    /* | SR_D_META */
		    /* | SR_D_DIS */
		    /* | SR_D_STATE */
		    /* | SR_D_REBUILD */
		;
#endif

struct sr_softc	*softraid0;
struct sr_uuid	sr_bootuuid;
u_int8_t	sr_bootkey[SR_CRYPTO_MAXKEYBYTES];

int		sr_match(struct device *, void *, void *);
void		sr_attach(struct device *, struct device *, void *);
int		sr_detach(struct device *, int);
void		sr_map_root(void);

struct cfattach softraid_ca = {
	sizeof(struct sr_softc), sr_match, sr_attach, sr_detach,
};

struct cfdriver softraid_cd = {
	NULL, "softraid", DV_DULL
};

/* scsi & discipline */
void			sr_scsi_cmd(struct scsi_xfer *);
void			sr_minphys(struct buf *, struct scsi_link *);
int			sr_scsi_probe(struct scsi_link *);
void			sr_copy_internal_data(struct scsi_xfer *,
			    void *, size_t);
int			sr_scsi_ioctl(struct scsi_link *, u_long,
			    caddr_t, int);
int			sr_bio_ioctl(struct device *, u_long, caddr_t);
int			sr_ioctl_inq(struct sr_softc *, struct bioc_inq *);
int			sr_ioctl_vol(struct sr_softc *, struct bioc_vol *);
int			sr_ioctl_disk(struct sr_softc *, struct bioc_disk *);
int			sr_ioctl_setstate(struct sr_softc *,
			    struct bioc_setstate *);
int			sr_ioctl_createraid(struct sr_softc *,
			    struct bioc_createraid *, int, void *);
int			sr_ioctl_deleteraid(struct sr_softc *,
			    struct bioc_deleteraid *);
int			sr_ioctl_discipline(struct sr_softc *,
			    struct bioc_discipline *);
int			sr_ioctl_installboot(struct sr_softc *,
			    struct bioc_installboot *);
void			sr_chunks_unwind(struct sr_softc *,
			    struct sr_chunk_head *);
void			sr_discipline_free(struct sr_discipline *);
void			sr_discipline_shutdown(struct sr_discipline *, int);
int			sr_discipline_init(struct sr_discipline *, int);
int			sr_alloc_resources(struct sr_discipline *);
void			sr_free_resources(struct sr_discipline *);
void			sr_set_chunk_state(struct sr_discipline *, int, int);
void			sr_set_vol_state(struct sr_discipline *);

/* utility functions */
void			sr_shutdown(struct sr_softc *);
void			sr_shutdownhook(void *);
void			sr_uuid_generate(struct sr_uuid *);
char			*sr_uuid_format(struct sr_uuid *);
void			sr_uuid_print(struct sr_uuid *, int);
void			sr_checksum_print(u_int8_t *);
int			sr_boot_assembly(struct sr_softc *);
int			sr_already_assembled(struct sr_discipline *);
int			sr_hotspare(struct sr_softc *, dev_t);
void			sr_hotspare_rebuild(struct sr_discipline *);
int			sr_rebuild_init(struct sr_discipline *, dev_t, int);
void			sr_rebuild_start(void *);
void			sr_rebuild_thread(void *);
void			sr_rebuild(struct sr_discipline *);
void			sr_roam_chunks(struct sr_discipline *);
int			sr_chunk_in_use(struct sr_softc *, dev_t);
int			sr_rw(struct sr_softc *, dev_t, char *, size_t,
			    daddr_t, long);
void			sr_wu_done_callback(void *, void *);

/* don't include these on RAMDISK */
#ifndef SMALL_KERNEL
void			sr_sensors_refresh(void *);
int			sr_sensors_create(struct sr_discipline *);
void			sr_sensors_delete(struct sr_discipline *);
#endif

/* metadata */
int			sr_meta_probe(struct sr_discipline *, dev_t *, int);
int			sr_meta_attach(struct sr_discipline *, int, int);
int			sr_meta_rw(struct sr_discipline *, dev_t, void *,
			    size_t, daddr_t, long);
int			sr_meta_clear(struct sr_discipline *);
void			sr_meta_init(struct sr_discipline *, int, int);
void			sr_meta_init_complete(struct sr_discipline *);
void			sr_meta_opt_handler(struct sr_discipline *,
			    struct sr_meta_opt_hdr *);

/* hotplug magic */
void			sr_disk_attach(struct disk *, int);

struct sr_hotplug_list {
	void			(*sh_hotplug)(struct sr_discipline *,
				    struct disk *, int);
	struct sr_discipline	*sh_sd;

	SLIST_ENTRY(sr_hotplug_list) shl_link;
};
SLIST_HEAD(sr_hotplug_list_head, sr_hotplug_list);

struct			sr_hotplug_list_head	sr_hotplug_callbacks;
extern void		(*softraid_disk_attach)(struct disk *, int);

/* scsi glue */
struct scsi_adapter sr_switch = {
	sr_scsi_cmd, sr_minphys, sr_scsi_probe, NULL, sr_scsi_ioctl
};

/* native metadata format */
int			sr_meta_native_bootprobe(struct sr_softc *, dev_t,
			    struct sr_boot_chunk_head *);
#define SR_META_NOTCLAIMED	(0)
#define SR_META_CLAIMED		(1)
int			sr_meta_native_probe(struct sr_softc *,
			   struct sr_chunk *);
int			sr_meta_native_attach(struct sr_discipline *, int);
int			sr_meta_native_write(struct sr_discipline *, dev_t,
			    struct sr_metadata *,void *);

#ifdef SR_DEBUG
void			sr_meta_print(struct sr_metadata *);
#else
#define			sr_meta_print(m)
#endif

/* the metadata driver should remain stateless */
struct sr_meta_driver {
	daddr_t			smd_offset;	/* metadata location */
	u_int32_t		smd_size;	/* size of metadata */

	int			(*smd_probe)(struct sr_softc *,
				   struct sr_chunk *);
	int			(*smd_attach)(struct sr_discipline *, int);
	int			(*smd_detach)(struct sr_discipline *);
	int			(*smd_read)(struct sr_discipline *, dev_t,
				    struct sr_metadata *, void *);
	int			(*smd_write)(struct sr_discipline *, dev_t,
				    struct sr_metadata *, void *);
	int			(*smd_validate)(struct sr_discipline *,
				    struct sr_metadata *, void *);
} smd[] = {
	{ SR_META_OFFSET, SR_META_SIZE * 512,
	  sr_meta_native_probe, sr_meta_native_attach, NULL,
	  sr_meta_native_read, sr_meta_native_write, NULL },
	{ 0, 0, NULL, NULL, NULL, NULL }
};

int
sr_meta_attach(struct sr_discipline *sd, int chunk_no, int force)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct sr_chunk_head	*cl;
	struct sr_chunk		*ch_entry, *chunk1, *chunk2;
	int			rv = 1, i = 0;

	DNPRINTF(SR_D_META, "%s: sr_meta_attach(%d)\n", DEVNAME(sc));

	/* in memory copy of metadata */
	sd->sd_meta = malloc(SR_META_SIZE * 512, M_DEVBUF, M_ZERO | M_NOWAIT);
	if (!sd->sd_meta) {
		sr_error(sc, "could not allocate memory for metadata");
		goto bad;
	}

	if (sd->sd_meta_type != SR_META_F_NATIVE) {
		/* in memory copy of foreign metadata */
		sd->sd_meta_foreign = malloc(smd[sd->sd_meta_type].smd_size,
		    M_DEVBUF, M_ZERO | M_NOWAIT);
		if (!sd->sd_meta_foreign) {
			/* unwind frees sd_meta */
			sr_error(sc, "could not allocate memory for foreign "
			    "metadata");
			goto bad;
		}
	}

	/* we have a valid list now create an array index */
	cl = &sd->sd_vol.sv_chunk_list;
	sd->sd_vol.sv_chunks = malloc(sizeof(struct sr_chunk *) * chunk_no,
	    M_DEVBUF, M_WAITOK | M_ZERO);

	/* fill out chunk array */
	i = 0;
	SLIST_FOREACH(ch_entry, cl, src_link)
		sd->sd_vol.sv_chunks[i++] = ch_entry;

	/* attach metadata */
	if (smd[sd->sd_meta_type].smd_attach(sd, force))
		goto bad;

	/* Force chunks into correct order now that metadata is attached. */
	SLIST_FOREACH(ch_entry, cl, src_link)
		SLIST_REMOVE(cl, ch_entry, sr_chunk, src_link);
	for (i = 0; i < chunk_no; i++) {
		ch_entry = sd->sd_vol.sv_chunks[i];
		chunk2 = NULL;
		SLIST_FOREACH(chunk1, cl, src_link) {
			if (chunk1->src_meta.scmi.scm_chunk_id >
			    ch_entry->src_meta.scmi.scm_chunk_id)
				break;
			chunk2 = chunk1;
		}
		if (chunk2 == NULL)
			SLIST_INSERT_HEAD(cl, ch_entry, src_link);
		else
			SLIST_INSERT_AFTER(chunk2, ch_entry, src_link);
	}
	i = 0;
	SLIST_FOREACH(ch_entry, cl, src_link)
		sd->sd_vol.sv_chunks[i++] = ch_entry;

	rv = 0;
bad:
	return (rv);
}

int
sr_meta_probe(struct sr_discipline *sd, dev_t *dt, int no_chunk)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct vnode		*vn;
	struct sr_chunk		*ch_entry, *ch_prev = NULL;
	struct sr_chunk_head	*cl;
	char			devname[32];
	int			i, d, type, found, prevf, error;
	dev_t			dev;

	DNPRINTF(SR_D_META, "%s: sr_meta_probe(%d)\n", DEVNAME(sc), no_chunk);

	if (no_chunk == 0)
		goto unwind;

	cl = &sd->sd_vol.sv_chunk_list;

	for (d = 0, prevf = SR_META_F_INVALID; d < no_chunk; d++) {
		ch_entry = malloc(sizeof(struct sr_chunk), M_DEVBUF,
		    M_WAITOK | M_ZERO);
		/* keep disks in user supplied order */
		if (ch_prev)
			SLIST_INSERT_AFTER(ch_prev, ch_entry, src_link);
		else
			SLIST_INSERT_HEAD(cl, ch_entry, src_link);
		ch_prev = ch_entry;
		dev = dt[d];
		ch_entry->src_dev_mm = dev;

		if (dev == NODEV) {
			ch_entry->src_meta.scm_status = BIOC_SDOFFLINE;
			continue;
		} else {
			sr_meta_getdevname(sc, dev, devname, sizeof(devname));
			if (bdevvp(dev, &vn)) {
				sr_error(sc, "sr_meta_probe: cannot allocate "
				    "vnode");
				goto unwind;
			}

			/*
			 * XXX leaving dev open for now; move this to attach
			 * and figure out the open/close dance for unwind.
			 */
			error = VOP_OPEN(vn, FREAD | FWRITE, NOCRED, curproc);
			if (error) {
				DNPRINTF(SR_D_META,"%s: sr_meta_probe can't "
				    "open %s\n", DEVNAME(sc), devname);
				vput(vn);
				goto unwind;
			}

			strlcpy(ch_entry->src_devname, devname,
			    sizeof(ch_entry->src_devname));
			ch_entry->src_vn = vn;
		}

		/* determine if this is a device we understand */
		for (i = 0, found = SR_META_F_INVALID; smd[i].smd_probe; i++) {
			type = smd[i].smd_probe(sc, ch_entry);
			if (type == SR_META_F_INVALID)
				continue;
			else {
				found = type;
				break;
			}
		}

		if (found == SR_META_F_INVALID)
			goto unwind;
		if (prevf == SR_META_F_INVALID)
			prevf = found;
		if (prevf != found) {
			DNPRINTF(SR_D_META, "%s: prevf != found\n",
			    DEVNAME(sc));
			goto unwind;
		}
	}

	return (prevf);
unwind:
	return (SR_META_F_INVALID);
}

void
sr_meta_getdevname(struct sr_softc *sc, dev_t dev, char *buf, int size)
{
	int			maj, unit, part;
	char			*name;

	DNPRINTF(SR_D_META, "%s: sr_meta_getdevname(%p, %d)\n",
	    DEVNAME(sc), buf, size);

	if (!buf)
		return;

	maj = major(dev);
	part = DISKPART(dev);
	unit = DISKUNIT(dev);

	name = findblkname(maj);
	if (name == NULL)
		return;

	snprintf(buf, size, "%s%d%c", name, unit, part + 'a');
}

int
sr_rw(struct sr_softc *sc, dev_t dev, char *buf, size_t size, daddr_t offset,
    long flags)
{
	struct vnode		*vp;
	struct buf		b;
	size_t			bufsize, dma_bufsize;
	int			rv = 1;
	char			*dma_buf;

	DNPRINTF(SR_D_MISC, "%s: sr_rw(0x%x, %p, %zu, %lld 0x%x)\n",
	    DEVNAME(sc), dev, buf, size, (long long)offset, flags);

	dma_bufsize = (size > MAXPHYS) ? MAXPHYS : size;
	dma_buf = dma_alloc(dma_bufsize, PR_WAITOK);

	if (bdevvp(dev, &vp)) {
		printf("%s: sr_rw: failed to allocate vnode\n", DEVNAME(sc));
		goto done;
	}

	while (size > 0) {
		DNPRINTF(SR_D_MISC, "%s: dma_buf %p, size %d, offset %llu)\n",
		    DEVNAME(sc), dma_buf, size, offset);

		bufsize = (size > MAXPHYS) ? MAXPHYS : size;
		if (flags == B_WRITE)
			bcopy(buf, dma_buf, bufsize);

		bzero(&b, sizeof(b));
		b.b_flags = flags | B_PHYS;
		b.b_proc = curproc;
		b.b_dev = dev;
		b.b_iodone = NULL;
		b.b_error = 0;
		b.b_blkno = offset;
		b.b_data = dma_buf;
		b.b_bcount = bufsize;
		b.b_bufsize = bufsize;
		b.b_resid = bufsize;
		b.b_vp = vp;

		if ((b.b_flags & B_READ) == 0)
			vp->v_numoutput++;

		LIST_INIT(&b.b_dep);
		VOP_STRATEGY(&b);
		biowait(&b);

		if (b.b_flags & B_ERROR) {
			printf("%s: I/O error %d on dev 0x%x at block %llu\n",
			    DEVNAME(sc), b.b_error, dev, b.b_blkno);
			goto done;
		}

		if (flags == B_READ)
			bcopy(dma_buf, buf, bufsize);

		size -= bufsize;
		buf += bufsize;
		offset += howmany(bufsize, DEV_BSIZE);
	}

	rv = 0;

done:
	if (vp)
		vput(vp);

	dma_free(dma_buf, dma_bufsize);

	return (rv);
}

int
sr_meta_rw(struct sr_discipline *sd, dev_t dev, void *md, size_t size,
    daddr_t offset, long flags)
{
	int			rv = 1;

	DNPRINTF(SR_D_META, "%s: sr_meta_rw(0x%x, %p, %zu, %lld 0x%x)\n",
	    DEVNAME(sd->sd_sc), dev, md, size, (long long)offset, flags);

	if (md == NULL) {
		printf("%s: sr_meta_rw: invalid metadata pointer\n",
		    DEVNAME(sd->sd_sc));
		goto done;
	}

	rv = sr_rw(sd->sd_sc, dev, md, size, offset, flags);

done:
	return (rv);
}

int
sr_meta_clear(struct sr_discipline *sd)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct sr_chunk_head	*cl = &sd->sd_vol.sv_chunk_list;
	struct sr_chunk		*ch_entry;
	void			*m;
	int			rv = 1;

	DNPRINTF(SR_D_META, "%s: sr_meta_clear\n", DEVNAME(sc));

	if (sd->sd_meta_type != SR_META_F_NATIVE) {
		sr_error(sc, "cannot clear foreign metadata");
		goto done;
	}

	m = malloc(SR_META_SIZE * 512, M_DEVBUF, M_WAITOK | M_ZERO);
	SLIST_FOREACH(ch_entry, cl, src_link) {
		if (sr_meta_native_write(sd, ch_entry->src_dev_mm, m, NULL)) {
			/* XXX mark disk offline */
			DNPRINTF(SR_D_META, "%s: sr_meta_clear failed to "
			    "clear %s\n", ch_entry->src_devname);
			rv++;
			continue;
		}
		bzero(&ch_entry->src_meta, sizeof(ch_entry->src_meta));
	}

	bzero(sd->sd_meta, SR_META_SIZE * 512);

	free(m, M_DEVBUF);
	rv = 0;
done:
	return (rv);
}

void
sr_meta_init(struct sr_discipline *sd, int level, int no_chunk)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct sr_metadata	*sm = sd->sd_meta;
	struct sr_chunk_head	*cl = &sd->sd_vol.sv_chunk_list;
	struct sr_meta_chunk	*scm;
	struct sr_chunk		*chunk;
	int			cid = 0;
	u_int64_t		max_chunk_sz = 0, min_chunk_sz = 0;

	DNPRINTF(SR_D_META, "%s: sr_meta_init\n", DEVNAME(sc));

	if (!sm)
		return;

	/* Initialise volume metadata. */
	sm->ssdi.ssd_magic = SR_MAGIC;
	sm->ssdi.ssd_version = SR_META_VERSION;
	sm->ssdi.ssd_vol_flags = sd->sd_meta_flags;
	sm->ssdi.ssd_volid = 0;
	sm->ssdi.ssd_chunk_no = no_chunk;
	sm->ssdi.ssd_level = level;

	sm->ssd_data_offset = SR_DATA_OFFSET;
	sm->ssd_ondisk = 0;

	sr_uuid_generate(&sm->ssdi.ssd_uuid);

	/* Initialise chunk metadata and get min/max chunk sizes. */
	SLIST_FOREACH(chunk, cl, src_link) {
		scm = &chunk->src_meta;
		scm->scmi.scm_size = chunk->src_size;
		scm->scmi.scm_chunk_id = cid++;
		scm->scm_status = BIOC_SDONLINE;
		scm->scmi.scm_volid = 0;
		strlcpy(scm->scmi.scm_devname, chunk->src_devname,
		    sizeof(scm->scmi.scm_devname));
		bcopy(&sm->ssdi.ssd_uuid, &scm->scmi.scm_uuid,
		    sizeof(scm->scmi.scm_uuid));
		sr_checksum(sc, scm, &scm->scm_checksum,
		    sizeof(scm->scm_checksum));

		if (min_chunk_sz == 0)
			min_chunk_sz = scm->scmi.scm_size;
		min_chunk_sz = MIN(min_chunk_sz, scm->scmi.scm_size);
		max_chunk_sz = MAX(max_chunk_sz, scm->scmi.scm_size);
	}

	/* Equalize chunk sizes. */
	SLIST_FOREACH(chunk, cl, src_link)
		chunk->src_meta.scmi.scm_coerced_size = min_chunk_sz;

	sd->sd_vol.sv_chunk_minsz = min_chunk_sz;
	sd->sd_vol.sv_chunk_maxsz = max_chunk_sz;
}

void
sr_meta_init_complete(struct sr_discipline *sd)
{
#ifdef SR_DEBUG
	struct sr_softc		*sc = sd->sd_sc;
#endif
	struct sr_metadata	*sm = sd->sd_meta;

	DNPRINTF(SR_D_META, "%s: sr_meta_complete\n", DEVNAME(sc));

	/* Complete initialisation of volume metadata. */
	strlcpy(sm->ssdi.ssd_vendor, "OPENBSD", sizeof(sm->ssdi.ssd_vendor));
	snprintf(sm->ssdi.ssd_product, sizeof(sm->ssdi.ssd_product),
	    "SR %s", sd->sd_name);
	snprintf(sm->ssdi.ssd_revision, sizeof(sm->ssdi.ssd_revision),
	    "%03d", sm->ssdi.ssd_version);
}

void
sr_meta_opt_handler(struct sr_discipline *sd, struct sr_meta_opt_hdr *om)
{
	if (om->som_type != SR_OPT_BOOT)
		panic("unknown optional metadata type");
}

void
sr_meta_save_callback(void *arg1, void *arg2)
{
	struct sr_discipline	*sd = arg1;
	int			s;

	s = splbio();

	if (sr_meta_save(arg1, SR_META_DIRTY))
		printf("%s: save metadata failed\n", DEVNAME(sd->sd_sc));

	sd->sd_must_flush = 0;
	splx(s);
}

int
sr_meta_save(struct sr_discipline *sd, u_int32_t flags)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct sr_metadata	*sm = sd->sd_meta, *m;
	struct sr_meta_driver	*s;
	struct sr_chunk		*src;
	struct sr_meta_chunk	*cm;
	struct sr_workunit	wu;
	struct sr_meta_opt_hdr	*omh;
	struct sr_meta_opt_item *omi;
	int			i;

	DNPRINTF(SR_D_META, "%s: sr_meta_save %s\n",
	    DEVNAME(sc), sd->sd_meta->ssd_devname);

	if (!sm) {
		printf("%s: no in memory copy of metadata\n", DEVNAME(sc));
		goto bad;
	}

	/* meta scratchpad */
	s = &smd[sd->sd_meta_type];
	m = malloc(SR_META_SIZE * 512, M_DEVBUF, M_ZERO | M_NOWAIT);
	if (!m) {
		printf("%s: could not allocate metadata scratch area\n",
		    DEVNAME(sc));
		goto bad;
	}

	/* from here on out metadata is updated */
restart:
	sm->ssd_ondisk++;
	sm->ssd_meta_flags = flags;
	bcopy(sm, m, sizeof(*m));

	/* Chunk metadata. */
	cm = (struct sr_meta_chunk *)(m + 1);
	for (i = 0; i < sm->ssdi.ssd_chunk_no; i++) {
		src = sd->sd_vol.sv_chunks[i];
		bcopy(&src->src_meta, cm, sizeof(*cm));
		cm++;
	}

	/* Optional metadata. */
	omh = (struct sr_meta_opt_hdr *)(cm);
	SLIST_FOREACH(omi, &sd->sd_meta_opt, omi_link) {
		DNPRINTF(SR_D_META, "%s: saving optional metadata type %u with "
		    "length %u\n", DEVNAME(sc), omi->omi_som->som_type,
		    omi->omi_som->som_length);
		bzero(&omi->omi_som->som_checksum, MD5_DIGEST_LENGTH);
		sr_checksum(sc, omi->omi_som, &omi->omi_som->som_checksum,
		    omi->omi_som->som_length);
		bcopy(omi->omi_som, omh, omi->omi_som->som_length);
		omh = (struct sr_meta_opt_hdr *)((u_int8_t *)omh +
		    omi->omi_som->som_length);
	}

	for (i = 0; i < sm->ssdi.ssd_chunk_no; i++) {
		src = sd->sd_vol.sv_chunks[i];

		/* skip disks that are offline */
		if (src->src_meta.scm_status == BIOC_SDOFFLINE)
			continue;

		/* calculate metadata checksum for correct chunk */
		m->ssdi.ssd_chunk_id = i;
		sr_checksum(sc, m, &m->ssd_checksum,
		    sizeof(struct sr_meta_invariant));

#ifdef SR_DEBUG
		DNPRINTF(SR_D_META, "%s: sr_meta_save %s: volid: %d "
		    "chunkid: %d checksum: ",
		    DEVNAME(sc), src->src_meta.scmi.scm_devname,
		    m->ssdi.ssd_volid, m->ssdi.ssd_chunk_id);

		if (sr_debug & SR_D_META)
			sr_checksum_print((u_int8_t *)&m->ssd_checksum);
		DNPRINTF(SR_D_META, "\n");
		sr_meta_print(m);
#endif

		/* translate and write to disk */
		if (s->smd_write(sd, src->src_dev_mm, m, NULL /* XXX */)) {
			printf("%s: could not write metadata to %s\n",
			    DEVNAME(sc), src->src_devname);
			/* restart the meta write */
			src->src_meta.scm_status = BIOC_SDOFFLINE;
			/* XXX recalculate volume status */
			goto restart;
		}
	}

	/* not all disciplines have sync */
	if (sd->sd_scsi_sync) {
		bzero(&wu, sizeof(wu));
		wu.swu_flags |= SR_WUF_FAKE;
		wu.swu_dis = sd;
		sd->sd_scsi_sync(&wu);
	}
	free(m, M_DEVBUF);
	return (0);
bad:
	return (1);
}

int
sr_meta_read(struct sr_discipline *sd)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct sr_chunk_head 	*cl = &sd->sd_vol.sv_chunk_list;
	struct sr_metadata	*sm;
	struct sr_chunk		*ch_entry;
	struct sr_meta_chunk	*cp;
	struct sr_meta_driver	*s;
	void			*fm = NULL;
	int			no_disk = 0, got_meta = 0;

	DNPRINTF(SR_D_META, "%s: sr_meta_read\n", DEVNAME(sc));

	sm = malloc(SR_META_SIZE * 512, M_DEVBUF, M_WAITOK | M_ZERO);
	s = &smd[sd->sd_meta_type];
	if (sd->sd_meta_type != SR_META_F_NATIVE)
		fm = malloc(s->smd_size, M_DEVBUF, M_WAITOK | M_ZERO);

	cp = (struct sr_meta_chunk *)(sm + 1);
	SLIST_FOREACH(ch_entry, cl, src_link) {
		/* skip disks that are offline */
		if (ch_entry->src_meta.scm_status == BIOC_SDOFFLINE) {
			DNPRINTF(SR_D_META,
			    "%s: %s chunk marked offline, spoofing status\n",
			    DEVNAME(sc), ch_entry->src_devname);
			cp++; /* adjust chunk pointer to match failure */
			continue;
		} else if (s->smd_read(sd, ch_entry->src_dev_mm, sm, fm)) {
			/* read and translate */
			/* XXX mark chunk offline, elsewhere!! */
			ch_entry->src_meta.scm_status = BIOC_SDOFFLINE;
			cp++; /* adjust chunk pointer to match failure */
			DNPRINTF(SR_D_META, "%s: sr_meta_read failed\n",
			    DEVNAME(sc));
			continue;
		}

		if (sm->ssdi.ssd_magic != SR_MAGIC) {
			DNPRINTF(SR_D_META, "%s: sr_meta_read !SR_MAGIC\n",
			    DEVNAME(sc));
			continue;
		}

		/* validate metadata */
		if (sr_meta_validate(sd, ch_entry->src_dev_mm, sm, fm)) {
			DNPRINTF(SR_D_META, "%s: invalid metadata\n",
			    DEVNAME(sc));
			no_disk = -1;
			goto done;
		}

		/* assume first chunk contains metadata */
		if (got_meta == 0) {
			sr_meta_opt_load(sc, sm, &sd->sd_meta_opt);
			bcopy(sm, sd->sd_meta, sizeof(*sd->sd_meta));
			got_meta = 1;
		}

		bcopy(cp, &ch_entry->src_meta, sizeof(ch_entry->src_meta));

		no_disk++;
		cp++;
	}

	free(sm, M_DEVBUF);
	if (fm)
		free(fm, M_DEVBUF);

done:
	DNPRINTF(SR_D_META, "%s: sr_meta_read found %d parts\n", DEVNAME(sc),
	    no_disk);
	return (no_disk);
}

void
sr_meta_opt_load(struct sr_softc *sc, struct sr_metadata *sm,
    struct sr_meta_opt_head *som)
{
	struct sr_meta_opt_hdr	*omh;
	struct sr_meta_opt_item *omi;
	u_int8_t		checksum[MD5_DIGEST_LENGTH];
	int			i;

	/* Process optional metadata. */
	omh = (struct sr_meta_opt_hdr *)((u_int8_t *)(sm + 1) +
	    sizeof(struct sr_meta_chunk) * sm->ssdi.ssd_chunk_no);
	for (i = 0; i < sm->ssdi.ssd_opt_no; i++) {

		omi = malloc(sizeof(struct sr_meta_opt_item), M_DEVBUF,
		    M_WAITOK | M_ZERO);
		SLIST_INSERT_HEAD(som, omi, omi_link);

		if (omh->som_length == 0) {

			/* Load old fixed length optional metadata. */
			DNPRINTF(SR_D_META, "%s: old optional metadata of type "
			    "%u\n", DEVNAME(sc), omh->som_type);

			/* Validate checksum. */
			sr_checksum(sc, (void *)omh, &checksum,
			    SR_OLD_META_OPT_SIZE - MD5_DIGEST_LENGTH);
			if (bcmp(&checksum, (void *)omh + SR_OLD_META_OPT_MD5,
			    sizeof(checksum)))
				panic("%s: invalid optional metadata "
				    "checksum", DEVNAME(sc));

			/* Determine correct length. */
			switch (omh->som_type) {
			case SR_OPT_CRYPTO:
				omh->som_length = sizeof(struct sr_meta_crypto);
				break;
			case SR_OPT_BOOT:
				omh->som_length = sizeof(struct sr_meta_boot);
				break;
			case SR_OPT_KEYDISK:
				omh->som_length =
				    sizeof(struct sr_meta_keydisk);
				break;
			default:
				panic("unknown old optional metadata "
				    "type %u\n", omh->som_type);
			}

			omi->omi_som = malloc(omh->som_length, M_DEVBUF,
			    M_WAITOK | M_ZERO);
			bcopy((u_int8_t *)omh + SR_OLD_META_OPT_OFFSET,
			    (u_int8_t *)omi->omi_som + sizeof(*omi->omi_som),
			    omh->som_length - sizeof(*omi->omi_som));
			omi->omi_som->som_type = omh->som_type;
			omi->omi_som->som_length = omh->som_length;

			omh = (struct sr_meta_opt_hdr *)((void *)omh +
			    SR_OLD_META_OPT_SIZE);
		} else {

			/* Load variable length optional metadata. */
			DNPRINTF(SR_D_META, "%s: optional metadata of type %u, "
			    "length %u\n", DEVNAME(sc), omh->som_type,
			    omh->som_length);
			omi->omi_som = malloc(omh->som_length, M_DEVBUF,
			    M_WAITOK | M_ZERO);
			bcopy(omh, omi->omi_som, omh->som_length);

			/* Validate checksum. */
			bcopy(&omi->omi_som->som_checksum, &checksum,
			    MD5_DIGEST_LENGTH);
			bzero(&omi->omi_som->som_checksum, MD5_DIGEST_LENGTH);
			sr_checksum(sc, omi->omi_som,
			    &omi->omi_som->som_checksum, omh->som_length);
			if (bcmp(&checksum, &omi->omi_som->som_checksum,
			    sizeof(checksum)))
				panic("%s: invalid optional metadata checksum",
				    DEVNAME(sc));

			omh = (struct sr_meta_opt_hdr *)((void *)omh +
			    omh->som_length);
		}
	}
}

int
sr_meta_validate(struct sr_discipline *sd, dev_t dev, struct sr_metadata *sm,
    void *fm)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct sr_meta_driver	*s;
#ifdef SR_DEBUG
	struct sr_meta_chunk	*mc;
#endif
	u_int8_t		checksum[MD5_DIGEST_LENGTH];
	char			devname[32];
	int			rv = 1;

	DNPRINTF(SR_D_META, "%s: sr_meta_validate(%p)\n", DEVNAME(sc), sm);

	sr_meta_getdevname(sc, dev, devname, sizeof(devname));

	s = &smd[sd->sd_meta_type];
	if (sd->sd_meta_type != SR_META_F_NATIVE)
		if (s->smd_validate(sd, sm, fm)) {
			sr_error(sc, "invalid foreign metadata");
			goto done;
		}

	/*
	 * at this point all foreign metadata has been translated to the native
	 * format and will be treated just like the native format
	 */

	if (sm->ssdi.ssd_magic != SR_MAGIC) {
		sr_error(sc, "not valid softraid metadata");
		goto done;
	}

	/* Verify metadata checksum. */
	sr_checksum(sc, sm, &checksum, sizeof(struct sr_meta_invariant));
	if (bcmp(&checksum, &sm->ssd_checksum, sizeof(checksum))) {
		sr_error(sc, "invalid metadata checksum");
		goto done;
	}

	/* Handle changes between versions. */
	if (sm->ssdi.ssd_version == 3) {

		/*
		 * Version 3 - update metadata version and fix up data offset
		 * value since this did not exist in version 3.
		 */
		if (sm->ssd_data_offset == 0)
			sm->ssd_data_offset = SR_META_V3_DATA_OFFSET;

	} else if (sm->ssdi.ssd_version == 4) {

		/*
		 * Version 4 - original metadata format did not store
		 * data offset so fix this up if necessary.
		 */
		if (sm->ssd_data_offset == 0)
			sm->ssd_data_offset = SR_DATA_OFFSET;

	} else if (sm->ssdi.ssd_version == SR_META_VERSION) {

		/*
		 * Version 5 - variable length optional metadata. Migration
		 * from earlier fixed length optional metadata is handled
		 * in sr_meta_read().
		 */

	} else {

		sr_error(sc, "cannot read metadata version %u on %s, "
		    "expected version %u or earlier",
		    sm->ssdi.ssd_version, devname, SR_META_VERSION);
		goto done;

	}

	/* Update version number and revision string. */
	sm->ssdi.ssd_version = SR_META_VERSION;
	snprintf(sm->ssdi.ssd_revision, sizeof(sm->ssdi.ssd_revision),
	    "%03d", SR_META_VERSION);

#ifdef SR_DEBUG
	/* warn if disk changed order */
	mc = (struct sr_meta_chunk *)(sm + 1);
	if (strncmp(mc[sm->ssdi.ssd_chunk_id].scmi.scm_devname, devname,
	    sizeof(mc[sm->ssdi.ssd_chunk_id].scmi.scm_devname)))
		DNPRINTF(SR_D_META, "%s: roaming device %s -> %s\n",
		    DEVNAME(sc), mc[sm->ssdi.ssd_chunk_id].scmi.scm_devname,
		    devname);
#endif

	/* we have meta data on disk */
	DNPRINTF(SR_D_META, "%s: sr_meta_validate valid metadata %s\n",
	    DEVNAME(sc), devname);

	rv = 0;
done:
	return (rv);
}

int
sr_meta_native_bootprobe(struct sr_softc *sc, dev_t devno,
    struct sr_boot_chunk_head *bch)
{
	struct vnode		*vn;
	struct disklabel	label;
	struct sr_metadata	*md = NULL;
	struct sr_discipline	*fake_sd = NULL;
	struct sr_boot_chunk	*bc;
	char			devname[32];
	dev_t			chrdev, rawdev;
	int			error, i;
	int			rv = SR_META_NOTCLAIMED;

	DNPRINTF(SR_D_META, "%s: sr_meta_native_bootprobe\n", DEVNAME(sc));

	/*
	 * Use character raw device to avoid SCSI complaints about missing
	 * media on removable media devices.
	 */
	chrdev = blktochr(devno);
	rawdev = MAKEDISKDEV(major(chrdev), DISKUNIT(devno), RAW_PART);
	if (cdevvp(rawdev, &vn)) {
		sr_error(sc, "sr_meta_native_bootprobe: cannot allocate vnode");
		goto done;
	}

	/* open device */
	error = VOP_OPEN(vn, FREAD, NOCRED, curproc);
	if (error) {
		DNPRINTF(SR_D_META, "%s: sr_meta_native_bootprobe open "
		    "failed\n", DEVNAME(sc));
		vput(vn);
		goto done;
	}

	/* get disklabel */
	error = VOP_IOCTL(vn, DIOCGDINFO, (caddr_t)&label, FREAD, NOCRED,
	    curproc);
	if (error) {
		DNPRINTF(SR_D_META, "%s: sr_meta_native_bootprobe ioctl "
		    "failed\n", DEVNAME(sc));
		VOP_CLOSE(vn, FREAD, NOCRED, curproc);
		vput(vn);
		goto done;
	}

	/* we are done, close device */
	error = VOP_CLOSE(vn, FREAD, NOCRED, curproc);
	if (error) {
		DNPRINTF(SR_D_META, "%s: sr_meta_native_bootprobe close "
		    "failed\n", DEVNAME(sc));
		vput(vn);
		goto done;
	}
	vput(vn);

	/* Make sure this is a 512-byte/sector device. */
	if (label.d_secsize != DEV_BSIZE) {
		DNPRINTF(SR_D_META, "%s: %s has unsupported sector size (%d)",
		    DEVNAME(sc), devname, label.d_secsize);
		goto done;
	}

	md = malloc(SR_META_SIZE * 512, M_DEVBUF, M_ZERO | M_NOWAIT);
	if (md == NULL) {
		sr_error(sc, "not enough memory for metadata buffer");
		goto done;
	}

	/* create fake sd to use utility functions */
	fake_sd = malloc(sizeof(struct sr_discipline), M_DEVBUF,
	    M_ZERO | M_NOWAIT);
	if (fake_sd == NULL) {
		sr_error(sc, "not enough memory for fake discipline");
		goto done;
	}
	fake_sd->sd_sc = sc;
	fake_sd->sd_meta_type = SR_META_F_NATIVE;

	for (i = 0; i < MAXPARTITIONS; i++) {
		if (label.d_partitions[i].p_fstype != FS_RAID)
			continue;

		/* open partition */
		rawdev = MAKEDISKDEV(major(devno), DISKUNIT(devno), i);
		if (bdevvp(rawdev, &vn)) {
			sr_error(sc, "sr_meta_native_bootprobe: cannot "
			    "allocate vnode for partition");
			goto done;
		}
		error = VOP_OPEN(vn, FREAD, NOCRED, curproc);
		if (error) {
			DNPRINTF(SR_D_META, "%s: sr_meta_native_bootprobe "
			    "open failed, partition %d\n",
			    DEVNAME(sc), i);
			vput(vn);
			continue;
		}

		if (sr_meta_native_read(fake_sd, rawdev, md, NULL)) {
			sr_error(sc, "native bootprobe could not read native "
			    "metadata");
			VOP_CLOSE(vn, FREAD, NOCRED, curproc);
			vput(vn);
			continue;
		}

		/* are we a softraid partition? */
		if (md->ssdi.ssd_magic != SR_MAGIC) {
			VOP_CLOSE(vn, FREAD, NOCRED, curproc);
			vput(vn);
			continue;
		}

		sr_meta_getdevname(sc, rawdev, devname, sizeof(devname));
		if (sr_meta_validate(fake_sd, rawdev, md, NULL) == 0) {
			/* XXX fix M_WAITOK, this is boot time */
			bc = malloc(sizeof(struct sr_boot_chunk),
			    M_DEVBUF, M_WAITOK | M_ZERO);
			bc->sbc_metadata = malloc(sizeof(struct sr_metadata),
			    M_DEVBUF, M_WAITOK | M_ZERO);
			bcopy(md, bc->sbc_metadata, sizeof(struct sr_metadata));
			bc->sbc_mm = rawdev;
			SLIST_INSERT_HEAD(bch, bc, sbc_link);
			rv = SR_META_CLAIMED;
		}

		/* we are done, close partition */
		VOP_CLOSE(vn, FREAD, NOCRED, curproc);
		vput(vn);
	}

done:
	if (fake_sd)
		free(fake_sd, M_DEVBUF);
	if (md)
		free(md, M_DEVBUF);

	return (rv);
}

int
sr_boot_assembly(struct sr_softc *sc)
{
	struct sr_boot_volume_head bvh;
	struct sr_boot_chunk_head bch, kdh;
	struct sr_boot_volume	*bv, *bv1, *bv2;
	struct sr_boot_chunk	*bc, *bcnext, *bc1, *bc2;
	struct sr_disk_head	sdklist;
	struct sr_disk		*sdk;
	struct disk		*dk;
	struct bioc_createraid	bcr;
	struct sr_meta_chunk	*hm;
	struct sr_chunk_head	*cl;
	struct sr_chunk		*hotspare, *chunk, *last;
	u_int64_t		*ondisk = NULL;
	dev_t			*devs = NULL;
	void			*data;
	char			devname[32];
	int			rv = 0, i;

	DNPRINTF(SR_D_META, "%s: sr_boot_assembly\n", DEVNAME(sc));

	SLIST_INIT(&sdklist);
	SLIST_INIT(&bvh);
	SLIST_INIT(&bch);
	SLIST_INIT(&kdh);

	dk = TAILQ_FIRST(&disklist);
	while (dk != TAILQ_END(&disklist)) {

		/* See if this disk has been checked. */
		SLIST_FOREACH(sdk, &sdklist, sdk_link)
			if (sdk->sdk_devno == dk->dk_devno)
				break;

		if (sdk != NULL || dk->dk_devno == NODEV) {
			dk = TAILQ_NEXT(dk, dk_link);
			continue;
		}

		/* Add this disk to the list that we've checked. */
		sdk = malloc(sizeof(struct sr_disk), M_DEVBUF,
		    M_NOWAIT | M_CANFAIL | M_ZERO);
		if (sdk == NULL)
			goto unwind;
		sdk->sdk_devno = dk->dk_devno;
		SLIST_INSERT_HEAD(&sdklist, sdk, sdk_link);

		/* Only check sd(4) and wd(4) devices. */
		if (strncmp(dk->dk_name, "sd", 2) &&
		    strncmp(dk->dk_name, "wd", 2)) {
			dk = TAILQ_NEXT(dk, dk_link);
			continue;
		}

		/* native softraid uses partitions */
		rw_enter_write(&sc->sc_lock);
		bio_status_init(&sc->sc_status, &sc->sc_dev);
		sr_meta_native_bootprobe(sc, dk->dk_devno, &bch);
		rw_exit_write(&sc->sc_lock);

		/* probe non-native disks if native failed. */

		/* Restart scan since we may have slept. */
		dk = TAILQ_FIRST(&disklist);
	}

	/*
	 * Create a list of volumes and associate chunks with each volume.
	 */
	for (bc = SLIST_FIRST(&bch); bc != SLIST_END(&bch); bc = bcnext) {

		bcnext = SLIST_NEXT(bc, sbc_link);
		SLIST_REMOVE(&bch, bc, sr_boot_chunk, sbc_link);
		bc->sbc_chunk_id = bc->sbc_metadata->ssdi.ssd_chunk_id;

		/* Handle key disks separately. */
		if (bc->sbc_metadata->ssdi.ssd_level == SR_KEYDISK_LEVEL) {
			SLIST_INSERT_HEAD(&kdh, bc, sbc_link);
			continue;
		}

		SLIST_FOREACH(bv, &bvh, sbv_link) {
			if (bcmp(&bc->sbc_metadata->ssdi.ssd_uuid,
			    &bv->sbv_uuid,
			    sizeof(bc->sbc_metadata->ssdi.ssd_uuid)) == 0)
				break;
		}

		if (bv == NULL) {
			bv = malloc(sizeof(struct sr_boot_volume),
			    M_DEVBUF, M_NOWAIT | M_CANFAIL | M_ZERO);
			if (bv == NULL) {
				printf("%s: failed to allocate boot volume\n",
				    DEVNAME(sc));
				goto unwind;
			}

			bv->sbv_level = bc->sbc_metadata->ssdi.ssd_level;
			bv->sbv_volid = bc->sbc_metadata->ssdi.ssd_volid;
			bv->sbv_chunk_no = bc->sbc_metadata->ssdi.ssd_chunk_no;
			bv->sbv_flags = bc->sbc_metadata->ssdi.ssd_vol_flags;
			bcopy(&bc->sbc_metadata->ssdi.ssd_uuid, &bv->sbv_uuid,
			    sizeof(bc->sbc_metadata->ssdi.ssd_uuid));
			SLIST_INIT(&bv->sbv_chunks);

			/* Maintain volume order. */
			bv2 = NULL;
			SLIST_FOREACH(bv1, &bvh, sbv_link) {
				if (bv1->sbv_volid > bv->sbv_volid)
					break;
				bv2 = bv1;
			}
			if (bv2 == NULL) {
				DNPRINTF(SR_D_META, "%s: insert volume %u "
				    "at head\n", DEVNAME(sc), bv->sbv_volid);
				SLIST_INSERT_HEAD(&bvh, bv, sbv_link);
			} else {
				DNPRINTF(SR_D_META, "%s: insert volume %u "
				    "after %u\n", DEVNAME(sc), bv->sbv_volid,
				    bv2->sbv_volid);
				SLIST_INSERT_AFTER(bv2, bv, sbv_link);
			}
		}

		/* Maintain chunk order. */
		bc2 = NULL;
		SLIST_FOREACH(bc1, &bv->sbv_chunks, sbc_link) {
			if (bc1->sbc_chunk_id > bc->sbc_chunk_id)
				break;
			bc2 = bc1;
		}
		if (bc2 == NULL) {
			DNPRINTF(SR_D_META, "%s: volume %u insert chunk %u "
			    "at head\n", DEVNAME(sc), bv->sbv_volid,
			    bc->sbc_chunk_id);
			SLIST_INSERT_HEAD(&bv->sbv_chunks, bc, sbc_link);
		} else {
			DNPRINTF(SR_D_META, "%s: volume %u insert chunk %u "
			    "after %u\n", DEVNAME(sc), bv->sbv_volid,
			    bc->sbc_chunk_id, bc2->sbc_chunk_id);
			SLIST_INSERT_AFTER(bc2, bc, sbc_link);
		}

		bv->sbv_chunks_found++;
	}

	/* Allocate memory for device and ondisk version arrays. */
	devs = malloc(BIOC_CRMAXLEN * sizeof(dev_t), M_DEVBUF,
	    M_NOWAIT | M_CANFAIL);
	if (devs == NULL) {
		printf("%s: failed to allocate device array\n", DEVNAME(sc));
		goto unwind;
	}
	ondisk = malloc(BIOC_CRMAXLEN * sizeof(u_int64_t), M_DEVBUF,
	    M_NOWAIT | M_CANFAIL);
	if (ondisk == NULL) {
		printf("%s: failed to allocate ondisk array\n", DEVNAME(sc));
		goto unwind;
	}

	/*
	 * Assemble hotspare "volumes".
	 */
	SLIST_FOREACH(bv, &bvh, sbv_link) {

		/* Check if this is a hotspare "volume". */
		if (bv->sbv_level != SR_HOTSPARE_LEVEL ||
		    bv->sbv_chunk_no != 1)
			continue;

#ifdef SR_DEBUG
		DNPRINTF(SR_D_META, "%s: assembling hotspare volume ",
		    DEVNAME(sc));
		if (sr_debug & SR_D_META)
			sr_uuid_print(&bv->sbv_uuid, 0);
		DNPRINTF(SR_D_META, " volid %u with %u chunks\n",
		    bv->sbv_volid, bv->sbv_chunk_no);
#endif

		/* Create hotspare chunk metadata. */
		hotspare = malloc(sizeof(struct sr_chunk), M_DEVBUF,
		    M_NOWAIT | M_CANFAIL | M_ZERO);
		if (hotspare == NULL) {
			printf("%s: failed to allocate hotspare\n",
			    DEVNAME(sc));
			goto unwind;
		}

		bc = SLIST_FIRST(&bv->sbv_chunks);
		sr_meta_getdevname(sc, bc->sbc_mm, devname, sizeof(devname));
		hotspare->src_dev_mm = bc->sbc_mm;
		strlcpy(hotspare->src_devname, devname,
		    sizeof(hotspare->src_devname));
		hotspare->src_size = bc->sbc_metadata->ssdi.ssd_size;

		hm = &hotspare->src_meta;
		hm->scmi.scm_volid = SR_HOTSPARE_VOLID;
		hm->scmi.scm_chunk_id = 0;
		hm->scmi.scm_size = bc->sbc_metadata->ssdi.ssd_size;
		hm->scmi.scm_coerced_size = bc->sbc_metadata->ssdi.ssd_size;
		strlcpy(hm->scmi.scm_devname, devname,
		    sizeof(hm->scmi.scm_devname));
		bcopy(&bc->sbc_metadata->ssdi.ssd_uuid, &hm->scmi.scm_uuid,
		    sizeof(struct sr_uuid));

		sr_checksum(sc, hm, &hm->scm_checksum,
		    sizeof(struct sr_meta_chunk_invariant));

		hm->scm_status = BIOC_SDHOTSPARE;

		/* Add chunk to hotspare list. */
		rw_enter_write(&sc->sc_hs_lock);
		cl = &sc->sc_hotspare_list;
		if (SLIST_EMPTY(cl))
			SLIST_INSERT_HEAD(cl, hotspare, src_link);
		else {
			SLIST_FOREACH(chunk, cl, src_link)
				last = chunk;
			SLIST_INSERT_AFTER(last, hotspare, src_link);
		}
		sc->sc_hotspare_no++;
		rw_exit_write(&sc->sc_hs_lock);

	}

	/*
	 * Assemble RAID volumes.
	 */
	SLIST_FOREACH(bv, &bvh, sbv_link) {

		bzero(&bcr, sizeof(bcr));
		data = NULL;

		/* Check if this is a hotspare "volume". */
		if (bv->sbv_level == SR_HOTSPARE_LEVEL &&
		    bv->sbv_chunk_no == 1)
			continue;

		/*
		 * Skip volumes that are marked as no auto assemble, unless
		 * this was the volume which we actually booted from.
		 */
		if (bcmp(&sr_bootuuid, &bv->sbv_uuid, sizeof(sr_bootuuid)) != 0)
			if (bv->sbv_flags & BIOC_SCNOAUTOASSEMBLE)
				continue;

#ifdef SR_DEBUG
		DNPRINTF(SR_D_META, "%s: assembling volume ", DEVNAME(sc));
		if (sr_debug & SR_D_META)
			sr_uuid_print(&bv->sbv_uuid, 0);
		DNPRINTF(SR_D_META, " volid %u with %u chunks\n",
		    bv->sbv_volid, bv->sbv_chunk_no);
#endif

		/*
		 * If this is a crypto volume, try to find a matching
		 * key disk...
		 */
		bcr.bc_key_disk = NODEV;
		if (bv->sbv_level == 'C') {
			SLIST_FOREACH(bc, &kdh, sbc_link) {
				if (bcmp(&bc->sbc_metadata->ssdi.ssd_uuid,
				    &bv->sbv_uuid,
				    sizeof(bc->sbc_metadata->ssdi.ssd_uuid))
				    == 0)
					bcr.bc_key_disk = bc->sbc_mm;
			}
		}

		for (i = 0; i < BIOC_CRMAXLEN; i++) {
			devs[i] = NODEV; /* mark device as illegal */
			ondisk[i] = 0;
		}

		SLIST_FOREACH(bc, &bv->sbv_chunks, sbc_link) {
			if (devs[bc->sbc_chunk_id] != NODEV) {
				bv->sbv_chunks_found--;
				sr_meta_getdevname(sc, bc->sbc_mm, devname,
				    sizeof(devname));
				printf("%s: found duplicate chunk %u for "
				    "volume %u on device %s\n", DEVNAME(sc),
				    bc->sbc_chunk_id, bv->sbv_volid, devname);
			}

			if (devs[bc->sbc_chunk_id] == NODEV ||
			    bc->sbc_metadata->ssd_ondisk >
			    ondisk[bc->sbc_chunk_id]) {
				devs[bc->sbc_chunk_id] = bc->sbc_mm;
				ondisk[bc->sbc_chunk_id] =
				    bc->sbc_metadata->ssd_ondisk;
				DNPRINTF(SR_D_META, "%s: using ondisk "
				    "metadata version %llu for chunk %u\n",
				    DEVNAME(sc), ondisk[bc->sbc_chunk_id],
				    bc->sbc_chunk_id);
			}
		}

		if (bv->sbv_chunk_no != bv->sbv_chunks_found) {
			printf("%s: not all chunks were provided; "
			    "attempting to bring volume %d online\n",
			    DEVNAME(sc), bv->sbv_volid);
		}

		bcr.bc_level = bv->sbv_level;
		bcr.bc_dev_list_len = bv->sbv_chunk_no * sizeof(dev_t);
		bcr.bc_dev_list = devs;
		bcr.bc_flags = BIOC_SCDEVT |
		    (bv->sbv_flags & BIOC_SCNOAUTOASSEMBLE);

		if (bv->sbv_level == 'C' &&
		    bcmp(&sr_bootuuid, &bv->sbv_uuid, sizeof(sr_bootuuid)) == 0)
			data = sr_bootkey;

		rw_enter_write(&sc->sc_lock);
		bio_status_init(&sc->sc_status, &sc->sc_dev);
		sr_ioctl_createraid(sc, &bcr, 0, data);
		rw_exit_write(&sc->sc_lock);

		rv++;
	}

	/* done with metadata */
unwind:
	/* Free boot volumes and associated chunks. */
	for (bv1 = SLIST_FIRST(&bvh); bv1 != SLIST_END(&bvh); bv1 = bv2) {
		bv2 = SLIST_NEXT(bv1, sbv_link);
		for (bc1 = SLIST_FIRST(&bv1->sbv_chunks);
		    bc1 != SLIST_END(&bv1->sbv_chunks); bc1 = bc2) {
			bc2 = SLIST_NEXT(bc1, sbc_link);
			if (bc1->sbc_metadata)
				free(bc1->sbc_metadata, M_DEVBUF);
			free(bc1, M_DEVBUF);
		}
		free(bv1, M_DEVBUF);
	}
	/* Free keydisks chunks. */
	for (bc1 = SLIST_FIRST(&kdh); bc1 != SLIST_END(&kdh); bc1 = bc2) {
		bc2 = SLIST_NEXT(bc1, sbc_link);
		if (bc1->sbc_metadata)
			free(bc1->sbc_metadata, M_DEVBUF);
		free(bc1, M_DEVBUF);
	}
	/* Free unallocated chunks. */
	for (bc1 = SLIST_FIRST(&bch); bc1 != SLIST_END(&bch); bc1 = bc2) {
		bc2 = SLIST_NEXT(bc1, sbc_link);
		if (bc1->sbc_metadata)
			free(bc1->sbc_metadata, M_DEVBUF);
		free(bc1, M_DEVBUF);
	}

	while (!SLIST_EMPTY(&sdklist)) {
		sdk = SLIST_FIRST(&sdklist);
		SLIST_REMOVE_HEAD(&sdklist, sdk_link);
		free(sdk, M_DEVBUF);
	}

	if (devs)
		free(devs, M_DEVBUF);
	if (ondisk)
		free(ondisk, M_DEVBUF);

	return (rv);
}

void
sr_map_root(void)
{
	struct sr_softc		*sc = softraid0;
	struct sr_discipline	*sd;
	struct sr_meta_opt_item	*omi;
	struct sr_meta_boot	*sbm;
	u_char			duid[8];
	int			i;

	DNPRINTF(SR_D_MISC, "%s: sr_map_root\n", DEVNAME(sc));

	if (sc == NULL)
		return;

	bzero(duid, sizeof(duid));
	if (bcmp(rootduid, duid, sizeof(duid)) == 0) {
		DNPRINTF(SR_D_MISC, "%s: root duid is zero\n", DEVNAME(sc));
		return;
	}

	TAILQ_FOREACH(sd, &sc->sc_dis_list, sd_link) {
		SLIST_FOREACH(omi, &sd->sd_meta_opt, omi_link) {
			if (omi->omi_som->som_type != SR_OPT_BOOT)
				continue;
			sbm = (struct sr_meta_boot *)omi->omi_som;
			for (i = 0; i < SR_MAX_BOOT_DISKS; i++) {
				if (bcmp(rootduid, sbm->sbm_boot_duid[i],
				    sizeof(rootduid)) == 0) {
					bcopy(sbm->sbm_root_duid, rootduid,
					    sizeof(rootduid));
					DNPRINTF(SR_D_MISC, "%s: root duid "
					    "mapped to %02hx%02hx%02hx%02hx"
					    "%02hx%02hx%02hx%02hx\n",
					    DEVNAME(sc), rootduid[0],
					    rootduid[1], rootduid[2],
					    rootduid[3], rootduid[4],
					    rootduid[5], rootduid[6],
					    rootduid[7]);
					return;
				}
			}
		}
	}
}

int
sr_meta_native_probe(struct sr_softc *sc, struct sr_chunk *ch_entry)
{
	struct disklabel	label;
	char			*devname;
	int			error, part;
	daddr_t			size;

	DNPRINTF(SR_D_META, "%s: sr_meta_native_probe(%s)\n",
	   DEVNAME(sc), ch_entry->src_devname);

	devname = ch_entry->src_devname;
	part = DISKPART(ch_entry->src_dev_mm);

	/* get disklabel */
	error = VOP_IOCTL(ch_entry->src_vn, DIOCGDINFO, (caddr_t)&label, FREAD,
	    NOCRED, curproc);
	if (error) {
		DNPRINTF(SR_D_META, "%s: %s can't obtain disklabel\n",
		    DEVNAME(sc), devname);
		goto unwind;
	}
	bcopy(label.d_uid, ch_entry->src_duid, sizeof(ch_entry->src_duid));

	/* Make sure this is a 512-byte/sector device. */
	if (label.d_secsize != DEV_BSIZE) {
		sr_error(sc, "%s has unsupported sector size (%u)",
		    devname, label.d_secsize);
		goto unwind;
	}

	/* make sure the partition is of the right type */
	if (label.d_partitions[part].p_fstype != FS_RAID) {
		DNPRINTF(SR_D_META,
		    "%s: %s partition not of type RAID (%d)\n", DEVNAME(sc),
		    devname,
		    label.d_partitions[part].p_fstype);
		goto unwind;
	}

	size = DL_SECTOBLK(&label, DL_GETPSIZE(&label.d_partitions[part])) -
	    SR_DATA_OFFSET;
	if (size <= 0) {
		DNPRINTF(SR_D_META, "%s: %s partition too small\n", DEVNAME(sc),
		    devname);
		goto unwind;
	}
	ch_entry->src_size = size;

	DNPRINTF(SR_D_META, "%s: probe found %s size %lld\n", DEVNAME(sc),
	    devname, (long long)size);

	return (SR_META_F_NATIVE);
unwind:
	DNPRINTF(SR_D_META, "%s: invalid device: %s\n", DEVNAME(sc),
	    devname ? devname : "nodev");
	return (SR_META_F_INVALID);
}

int
sr_meta_native_attach(struct sr_discipline *sd, int force)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct sr_chunk_head 	*cl = &sd->sd_vol.sv_chunk_list;
	struct sr_metadata	*md = NULL;
	struct sr_chunk		*ch_entry, *ch_next;
	struct sr_uuid		uuid;
	u_int64_t		version = 0;
	int			sr, not_sr, rv = 1, d, expected = -1, old_meta = 0;

	DNPRINTF(SR_D_META, "%s: sr_meta_native_attach\n", DEVNAME(sc));

	md = malloc(SR_META_SIZE * 512, M_DEVBUF, M_ZERO | M_NOWAIT);
	if (md == NULL) {
		sr_error(sc, "not enough memory for metadata buffer");
		goto bad;
	}

	bzero(&uuid, sizeof uuid);

	sr = not_sr = d = 0;
	SLIST_FOREACH(ch_entry, cl, src_link) {
		if (ch_entry->src_dev_mm == NODEV)
			continue;

		if (sr_meta_native_read(sd, ch_entry->src_dev_mm, md, NULL)) {
			sr_error(sc, "could not read native metadata");
			goto bad;
		}

		if (md->ssdi.ssd_magic == SR_MAGIC) {
			sr++;
			ch_entry->src_meta.scmi.scm_chunk_id =
			    md->ssdi.ssd_chunk_id;
			if (d == 0) {
				bcopy(&md->ssdi.ssd_uuid, &uuid, sizeof uuid);
				expected = md->ssdi.ssd_chunk_no;
				version = md->ssd_ondisk;
				d++;
				continue;
			} else if (bcmp(&md->ssdi.ssd_uuid, &uuid,
			    sizeof uuid)) {
				sr_error(sc, "not part of the same volume");
				goto bad;
			}
			if (md->ssd_ondisk != version) {
				old_meta++;
				version = MAX(md->ssd_ondisk, version);
			}
		} else
			not_sr++;
	}

	if (sr && not_sr) {
		sr_error(sc, "not all chunks are of the native metadata "
		    "format");
		goto bad;
	}

	/* mixed metadata versions; mark bad disks offline */
	if (old_meta) {
		d = 0;
		for (ch_entry = SLIST_FIRST(cl); ch_entry != SLIST_END(cl);
		    ch_entry = ch_next, d++) {
			ch_next = SLIST_NEXT(ch_entry, src_link);

			/* XXX do we want to read this again? */
			if (ch_entry->src_dev_mm == NODEV)
				panic("src_dev_mm == NODEV");
			if (sr_meta_native_read(sd, ch_entry->src_dev_mm, md,
			    NULL))
				sr_warn(sc, "could not read native metadata");
			if (md->ssd_ondisk != version)
				sd->sd_vol.sv_chunks[d]->src_meta.scm_status =
				    BIOC_SDOFFLINE;
		}
	}

	if (expected != sr && !force && expected != -1) {
		DNPRINTF(SR_D_META, "%s: not all chunks were provided, trying "
		    "anyway\n", DEVNAME(sc));
	}

	rv = 0;
bad:
	if (md)
		free(md, M_DEVBUF);
	return (rv);
}

int
sr_meta_native_read(struct sr_discipline *sd, dev_t dev,
    struct sr_metadata *md, void *fm)
{
#ifdef SR_DEBUG
	struct sr_softc		*sc = sd->sd_sc;
#endif
	DNPRINTF(SR_D_META, "%s: sr_meta_native_read(0x%x, %p)\n",
	    DEVNAME(sc), dev, md);

	return (sr_meta_rw(sd, dev, md, SR_META_SIZE * 512, SR_META_OFFSET,
	    B_READ));
}

int
sr_meta_native_write(struct sr_discipline *sd, dev_t dev,
    struct sr_metadata *md, void *fm)
{
#ifdef SR_DEBUG
	struct sr_softc		*sc = sd->sd_sc;
#endif
	DNPRINTF(SR_D_META, "%s: sr_meta_native_write(0x%x, %p)\n",
	    DEVNAME(sc), dev, md);

	return (sr_meta_rw(sd, dev, md, SR_META_SIZE * 512, SR_META_OFFSET,
	    B_WRITE));
}

void
sr_hotplug_register(struct sr_discipline *sd, void *func)
{
	struct sr_hotplug_list	*mhe;

	DNPRINTF(SR_D_MISC, "%s: sr_hotplug_register: %p\n",
	    DEVNAME(sd->sd_sc), func);

	/* make sure we aren't on the list yet */
	SLIST_FOREACH(mhe, &sr_hotplug_callbacks, shl_link)
		if (mhe->sh_hotplug == func)
			return;

	mhe = malloc(sizeof(struct sr_hotplug_list), M_DEVBUF,
	    M_WAITOK | M_ZERO);
	mhe->sh_hotplug = func;
	mhe->sh_sd = sd;
	SLIST_INSERT_HEAD(&sr_hotplug_callbacks, mhe, shl_link);
}

void
sr_hotplug_unregister(struct sr_discipline *sd, void *func)
{
	struct sr_hotplug_list	*mhe;

	DNPRINTF(SR_D_MISC, "%s: sr_hotplug_unregister: %s %p\n",
	    DEVNAME(sd->sd_sc), sd->sd_meta->ssd_devname, func);

	/* make sure we are on the list yet */
	SLIST_FOREACH(mhe, &sr_hotplug_callbacks, shl_link)
		if (mhe->sh_hotplug == func) {
			SLIST_REMOVE(&sr_hotplug_callbacks, mhe,
			    sr_hotplug_list, shl_link);
			free(mhe, M_DEVBUF);
			if (SLIST_EMPTY(&sr_hotplug_callbacks))
				SLIST_INIT(&sr_hotplug_callbacks);
			return;
		}
}

void
sr_disk_attach(struct disk *diskp, int action)
{
	struct sr_hotplug_list	*mhe;

	SLIST_FOREACH(mhe, &sr_hotplug_callbacks, shl_link)
		if (mhe->sh_sd->sd_ready)
			mhe->sh_hotplug(mhe->sh_sd, diskp, action);
}

int
sr_match(struct device *parent, void *match, void *aux)
{
	return (1);
}

void
sr_attach(struct device *parent, struct device *self, void *aux)
{
	struct sr_softc		*sc = (void *)self;
	struct scsibus_attach_args saa;

	DNPRINTF(SR_D_MISC, "\n%s: sr_attach", DEVNAME(sc));

	if (softraid0 == NULL)
		softraid0 = sc;

	rw_init(&sc->sc_lock, "sr_lock");
	rw_init(&sc->sc_hs_lock, "sr_hs_lock");

	SLIST_INIT(&sr_hotplug_callbacks);
	TAILQ_INIT(&sc->sc_dis_list);
	SLIST_INIT(&sc->sc_hotspare_list);

#if NBIO > 0
	if (bio_register(&sc->sc_dev, sr_bio_ioctl) != 0)
		printf("%s: controller registration failed", DEVNAME(sc));
#endif /* NBIO > 0 */

#ifndef SMALL_KERNEL
	strlcpy(sc->sc_sensordev.xname, DEVNAME(sc),
	    sizeof(sc->sc_sensordev.xname));
	sensordev_install(&sc->sc_sensordev);
#endif /* SMALL_KERNEL */

	printf("\n");

	sc->sc_link.adapter_softc = sc;
	sc->sc_link.adapter = &sr_switch;
	sc->sc_link.adapter_target = SR_MAX_LD;
	sc->sc_link.adapter_buswidth = SR_MAX_LD;
	sc->sc_link.luns = 1;

	bzero(&saa, sizeof(saa));
	saa.saa_sc_link = &sc->sc_link;

	sc->sc_scsibus = (struct scsibus_softc *)config_found(&sc->sc_dev,
	    &saa, scsiprint);

	softraid_disk_attach = sr_disk_attach;

	sc->sc_shutdownhook = shutdownhook_establish(sr_shutdownhook, sc);

	sr_boot_assembly(sc);

	explicit_bzero(sr_bootkey, sizeof(sr_bootkey));
}

int
sr_detach(struct device *self, int flags)
{
	struct sr_softc		*sc = (void *)self;
	int			rv;

	DNPRINTF(SR_D_MISC, "%s: sr_detach\n", DEVNAME(sc));

	if (sc->sc_shutdownhook)
		shutdownhook_disestablish(sc->sc_shutdownhook);

	softraid_disk_attach = NULL;

	sr_shutdown(sc);

#ifndef SMALL_KERNEL
	if (sc->sc_sensor_task != NULL)
		sensor_task_unregister(sc->sc_sensor_task);
	sensordev_deinstall(&sc->sc_sensordev);
#endif /* SMALL_KERNEL */

	if (sc->sc_scsibus != NULL) {
		rv = config_detach((struct device *)sc->sc_scsibus, flags);
		if (rv != 0)
			return (rv);
		sc->sc_scsibus = NULL;
	}

	return (0);
}

void
sr_info(struct sr_softc *sc, const char *fmt, ...)
{
	va_list			ap;

	rw_assert_wrlock(&sc->sc_lock);

	va_start(ap, fmt);
	bio_status(&sc->sc_status, 0, BIO_MSG_INFO, fmt, &ap);
	va_end(ap);
}

void
sr_warn(struct sr_softc *sc, const char *fmt, ...)
{
	va_list			ap;

	rw_assert_wrlock(&sc->sc_lock);

	va_start(ap, fmt);
	bio_status(&sc->sc_status, 1, BIO_MSG_WARN, fmt, &ap);
	va_end(ap);
}

void
sr_error(struct sr_softc *sc, const char *fmt, ...)
{
	va_list			ap;

	rw_assert_wrlock(&sc->sc_lock);

	va_start(ap, fmt);
	bio_status(&sc->sc_status, 1, BIO_MSG_ERROR, fmt, &ap);
	va_end(ap);
}

void
sr_minphys(struct buf *bp, struct scsi_link *sl)
{
	DNPRINTF(SR_D_MISC, "sr_minphys: %d\n", bp->b_bcount);

	/* XXX currently using SR_MAXFER = MAXPHYS */
	if (bp->b_bcount > SR_MAXFER)
		bp->b_bcount = SR_MAXFER;
	minphys(bp);
}

void
sr_copy_internal_data(struct scsi_xfer *xs, void *v, size_t size)
{
	size_t			copy_cnt;

	DNPRINTF(SR_D_MISC, "sr_copy_internal_data xs: %p size: %zu\n",
	    xs, size);

	if (xs->datalen) {
		copy_cnt = MIN(size, xs->datalen);
		bcopy(v, xs->data, copy_cnt);
	}
}

int
sr_ccb_alloc(struct sr_discipline *sd)
{
	struct sr_ccb		*ccb;
	int			i;

	if (!sd)
		return (1);

	DNPRINTF(SR_D_CCB, "%s: sr_ccb_alloc\n", DEVNAME(sd->sd_sc));

	if (sd->sd_ccb)
		return (1);

	sd->sd_ccb = malloc(sizeof(struct sr_ccb) *
	    sd->sd_max_wu * sd->sd_max_ccb_per_wu, M_DEVBUF, M_WAITOK | M_ZERO);
	TAILQ_INIT(&sd->sd_ccb_freeq);
	for (i = 0; i < sd->sd_max_wu * sd->sd_max_ccb_per_wu; i++) {
		ccb = &sd->sd_ccb[i];
		ccb->ccb_dis = sd;
		sr_ccb_put(ccb);
	}

	DNPRINTF(SR_D_CCB, "%s: sr_ccb_alloc ccb: %d\n",
	    DEVNAME(sd->sd_sc), sd->sd_max_wu * sd->sd_max_ccb_per_wu);

	return (0);
}

void
sr_ccb_free(struct sr_discipline *sd)
{
	struct sr_ccb		*ccb;

	if (!sd)
		return;

	DNPRINTF(SR_D_CCB, "%s: sr_ccb_free %p\n", DEVNAME(sd->sd_sc), sd);

	while ((ccb = TAILQ_FIRST(&sd->sd_ccb_freeq)) != NULL)
		TAILQ_REMOVE(&sd->sd_ccb_freeq, ccb, ccb_link);

	if (sd->sd_ccb)
		free(sd->sd_ccb, M_DEVBUF);
}

struct sr_ccb *
sr_ccb_get(struct sr_discipline *sd)
{
	struct sr_ccb		*ccb;
	int			s;

	s = splbio();

	ccb = TAILQ_FIRST(&sd->sd_ccb_freeq);
	if (ccb) {
		TAILQ_REMOVE(&sd->sd_ccb_freeq, ccb, ccb_link);
		ccb->ccb_state = SR_CCB_INPROGRESS;
	}

	splx(s);

	DNPRINTF(SR_D_CCB, "%s: sr_ccb_get: %p\n", DEVNAME(sd->sd_sc),
	    ccb);

	return (ccb);
}

void
sr_ccb_put(struct sr_ccb *ccb)
{
	struct sr_discipline	*sd = ccb->ccb_dis;
	int			s;

	DNPRINTF(SR_D_CCB, "%s: sr_ccb_put: %p\n", DEVNAME(sd->sd_sc),
	    ccb);

	s = splbio();

	ccb->ccb_wu = NULL;
	ccb->ccb_state = SR_CCB_FREE;
	ccb->ccb_target = -1;
	ccb->ccb_opaque = NULL;

	TAILQ_INSERT_TAIL(&sd->sd_ccb_freeq, ccb, ccb_link);

	splx(s);
}

struct sr_ccb *
sr_ccb_rw(struct sr_discipline *sd, int chunk, daddr_t blkno,
    daddr_t len, u_int8_t *data, int xsflags, int ccbflags)
{
	struct sr_chunk		*sc = sd->sd_vol.sv_chunks[chunk];
	struct sr_ccb		*ccb = NULL;

	ccb = sr_ccb_get(sd);
	if (ccb == NULL)
		goto out;

	ccb->ccb_flags = ccbflags;
	ccb->ccb_target = chunk;

	ccb->ccb_buf.b_flags = B_PHYS | B_CALL;
	if (ISSET(xsflags, SCSI_DATA_IN))
		ccb->ccb_buf.b_flags |= B_READ;
	else
		ccb->ccb_buf.b_flags |= B_WRITE;

	ccb->ccb_buf.b_blkno = blkno;
	ccb->ccb_buf.b_bcount = len;
	ccb->ccb_buf.b_bufsize = len;
	ccb->ccb_buf.b_resid = len;
	ccb->ccb_buf.b_data = data;
	ccb->ccb_buf.b_error = 0;
	ccb->ccb_buf.b_iodone = sd->sd_scsi_intr;
	ccb->ccb_buf.b_proc = curproc;
	ccb->ccb_buf.b_dev = sc->src_dev_mm;
	ccb->ccb_buf.b_vp = sc->src_vn;
	ccb->ccb_buf.b_bq = NULL;

	if (!ISSET(ccb->ccb_buf.b_flags, B_READ))
		ccb->ccb_buf.b_vp->v_numoutput++;

	LIST_INIT(&ccb->ccb_buf.b_dep);

	DNPRINTF(SR_D_DIS, "%s: %s %s ccb "
	    "b_bcount %d b_blkno %lld b_flags 0x%0x b_data %p\n",
	    DEVNAME(sd->sd_sc), sd->sd_meta->ssd_devname, sd->sd_name,
	    ccb->ccb_buf.b_bcount, (long long)ccb->ccb_buf.b_blkno,
	    ccb->ccb_buf.b_flags, ccb->ccb_buf.b_data);

out:
	return ccb;
}

void
sr_ccb_done(struct sr_ccb *ccb)
{
	struct sr_workunit	*wu = ccb->ccb_wu;
	struct sr_discipline	*sd = wu->swu_dis;
	struct sr_softc		*sc = sd->sd_sc;

	DNPRINTF(SR_D_INTR, "%s: %s %s ccb done b_bcount %d b_resid %d"
	    " b_flags 0x%0x block %lld target %d\n",
	    DEVNAME(sc), sd->sd_meta->ssd_devname, sd->sd_name,
	    ccb->ccb_buf.b_bcount, ccb->ccb_buf.b_resid, ccb->ccb_buf.b_flags,
	    (long long)ccb->ccb_buf.b_blkno, ccb->ccb_target);

	splassert(IPL_BIO);

	if (ccb->ccb_target == -1)
		panic("%s: invalid target on wu: %p", DEVNAME(sc), wu);

	if (ccb->ccb_buf.b_flags & B_ERROR) {
		DNPRINTF(SR_D_INTR, "%s: i/o error on block %lld target %d\n",
		    DEVNAME(sc), (long long)ccb->ccb_buf.b_blkno,
		    ccb->ccb_target);
		if (ISSET(sd->sd_capabilities, SR_CAP_REDUNDANT))
			sd->sd_set_chunk_state(sd, ccb->ccb_target,
			    BIOC_SDOFFLINE);
		else
			printf("%s: i/o error on block %lld target %d "
			    "b_error %d\n", DEVNAME(sc),
			    (long long)ccb->ccb_buf.b_blkno, ccb->ccb_target,
			    ccb->ccb_buf.b_error);
		ccb->ccb_state = SR_CCB_FAILED;
		wu->swu_ios_failed++;
	} else {
		ccb->ccb_state = SR_CCB_OK;
		wu->swu_ios_succeeded++;
	}

	wu->swu_ios_complete++;
}

int
sr_wu_alloc(struct sr_discipline *sd, int wu_size)
{
	struct sr_workunit	*wu;
	int			i, no_wu;

	DNPRINTF(SR_D_WU, "%s: sr_wu_alloc %p %d\n", DEVNAME(sd->sd_sc),
	    sd, sd->sd_max_wu);

	no_wu = sd->sd_max_wu;
	sd->sd_wu_pending = no_wu;

	mtx_init(&sd->sd_wu_mtx, IPL_BIO);
	TAILQ_INIT(&sd->sd_wu);
	TAILQ_INIT(&sd->sd_wu_freeq);
	TAILQ_INIT(&sd->sd_wu_pendq);
	TAILQ_INIT(&sd->sd_wu_defq);

	for (i = 0; i < no_wu; i++) {
		wu = malloc(wu_size, M_DEVBUF, M_WAITOK | M_ZERO);
		TAILQ_INSERT_TAIL(&sd->sd_wu, wu, swu_next);
		TAILQ_INIT(&wu->swu_ccb);
		task_set(&wu->swu_task, sr_wu_done_callback, sd, wu);
		wu->swu_dis = sd;
		sr_wu_put(sd, wu);
	}

	return (0);
}

void
sr_wu_free(struct sr_discipline *sd)
{
	struct sr_workunit	*wu;

	DNPRINTF(SR_D_WU, "%s: sr_wu_free %p\n", DEVNAME(sd->sd_sc), sd);

	while ((wu = TAILQ_FIRST(&sd->sd_wu_freeq)) != NULL)
		TAILQ_REMOVE(&sd->sd_wu_freeq, wu, swu_link);
	while ((wu = TAILQ_FIRST(&sd->sd_wu_pendq)) != NULL)
		TAILQ_REMOVE(&sd->sd_wu_pendq, wu, swu_link);
	while ((wu = TAILQ_FIRST(&sd->sd_wu_defq)) != NULL)
		TAILQ_REMOVE(&sd->sd_wu_defq, wu, swu_link);

	while ((wu = TAILQ_FIRST(&sd->sd_wu)) != NULL) {
		TAILQ_REMOVE(&sd->sd_wu, wu, swu_next);
		free(wu, M_DEVBUF);
	}
}

void *
sr_wu_get(void *xsd)
{
	struct sr_discipline	*sd = (struct sr_discipline *)xsd;
	struct sr_workunit	*wu;

	mtx_enter(&sd->sd_wu_mtx);
	wu = TAILQ_FIRST(&sd->sd_wu_freeq);
	if (wu) {
		TAILQ_REMOVE(&sd->sd_wu_freeq, wu, swu_link);
		sd->sd_wu_pending++;
	}
	mtx_leave(&sd->sd_wu_mtx);

	DNPRINTF(SR_D_WU, "%s: sr_wu_get: %p\n", DEVNAME(sd->sd_sc), wu);

	return (wu);
}

void
sr_wu_put(void *xsd, void *xwu)
{
	struct sr_discipline	*sd = (struct sr_discipline *)xsd;
	struct sr_workunit	*wu = (struct sr_workunit *)xwu;

	DNPRINTF(SR_D_WU, "%s: sr_wu_put: %p\n", DEVNAME(sd->sd_sc), wu);

	sr_wu_release_ccbs(wu);
	sr_wu_init(sd, wu);

	mtx_enter(&sd->sd_wu_mtx);
	TAILQ_INSERT_TAIL(&sd->sd_wu_freeq, wu, swu_link);
	sd->sd_wu_pending--;
	mtx_leave(&sd->sd_wu_mtx);
}

void
sr_wu_init(struct sr_discipline *sd, struct sr_workunit *wu)
{
	int			s;

	s = splbio();
	if (wu->swu_cb_active == 1)
		panic("%s: sr_wu_init got active wu", DEVNAME(sd->sd_sc));
	splx(s);

	wu->swu_xs = NULL;
	wu->swu_state = SR_WU_FREE;
	wu->swu_flags = 0;
	wu->swu_blk_start = 0;
	wu->swu_blk_end = 0;
	wu->swu_collider = NULL;
}

void
sr_wu_enqueue_ccb(struct sr_workunit *wu, struct sr_ccb *ccb)
{
	struct sr_discipline	*sd = wu->swu_dis;
	int			s;

	s = splbio();
	if (wu->swu_cb_active == 1)
		panic("%s: sr_wu_enqueue_ccb got active wu",
		    DEVNAME(sd->sd_sc));
	ccb->ccb_wu = wu;
	wu->swu_io_count++;
	TAILQ_INSERT_TAIL(&wu->swu_ccb, ccb, ccb_link);
	splx(s);
}

void
sr_wu_release_ccbs(struct sr_workunit *wu)
{
	struct sr_ccb		*ccb;

	/* Return all ccbs that are associated with this workunit. */
	while ((ccb = TAILQ_FIRST(&wu->swu_ccb)) != NULL) {
		TAILQ_REMOVE(&wu->swu_ccb, ccb, ccb_link);
		sr_ccb_put(ccb);
	}

	wu->swu_io_count = 0;
	wu->swu_ios_complete = 0;
	wu->swu_ios_failed = 0;
	wu->swu_ios_succeeded = 0;
}

void
sr_wu_done(struct sr_workunit *wu)
{
	struct sr_discipline	*sd = wu->swu_dis;

	DNPRINTF(SR_D_INTR, "%s: sr_wu_done count %d completed %d failed %d\n",
	    DEVNAME(sd->sd_sc), wu->swu_io_count, wu->swu_ios_complete,
	    wu->swu_ios_failed);

	if (wu->swu_ios_complete < wu->swu_io_count)
		return;

	task_add(sd->sd_taskq, &wu->swu_task);
}

void
sr_wu_done_callback(void *arg1, void *arg2)
{
	struct sr_discipline	*sd = (struct sr_discipline *)arg1;
	struct sr_workunit	*wu = (struct sr_workunit *)arg2;
	struct scsi_xfer	*xs = wu->swu_xs;
	struct sr_workunit	*wup;
	int			s;

	/*
	 * The SR_WUF_DISCIPLINE or SR_WUF_REBUILD flag must be set if
	 * the work unit is not associated with a scsi_xfer.
	 */
	KASSERT(xs != NULL ||
	    (wu->swu_flags & (SR_WUF_DISCIPLINE|SR_WUF_REBUILD)));

	s = splbio();

	if (xs != NULL) {
		if (wu->swu_ios_failed)
			xs->error = XS_DRIVER_STUFFUP;
		else
			xs->error = XS_NOERROR;
	}

	if (sd->sd_scsi_wu_done) {
		if (sd->sd_scsi_wu_done(wu) == SR_WU_RESTART)
			goto done;
	}

	/* Remove work unit from pending queue. */
	TAILQ_FOREACH(wup, &sd->sd_wu_pendq, swu_link)
		if (wup == wu)
			break;
	if (wup == NULL)
		panic("%s: wu %p not on pending queue",
		    DEVNAME(sd->sd_sc), wu);
	TAILQ_REMOVE(&sd->sd_wu_pendq, wu, swu_link);

	if (wu->swu_collider) {
		if (wu->swu_ios_failed)
			sr_raid_recreate_wu(wu->swu_collider);

		/* XXX Should the collider be failed if this xs failed? */
		sr_raid_startwu(wu->swu_collider);
	}

	/*
	 * If a discipline provides its own sd_scsi_done function, then it
	 * is responsible for calling sr_scsi_done() once I/O is complete.
	 */
	if (wu->swu_flags & SR_WUF_REBUILD)
		wu->swu_flags |= SR_WUF_REBUILDIOCOMP;
	if (wu->swu_flags & SR_WUF_WAKEUP)
		wakeup(wu);
	if (sd->sd_scsi_done)
		sd->sd_scsi_done(wu);
	else if (wu->swu_flags & SR_WUF_DISCIPLINE)
		sr_scsi_wu_put(sd, wu);
	else if (!(wu->swu_flags & SR_WUF_REBUILD))
		sr_scsi_done(sd, xs);

done:
	splx(s);
}

struct sr_workunit *
sr_scsi_wu_get(struct sr_discipline *sd, int flags)
{
	return scsi_io_get(&sd->sd_iopool, flags);
}

void
sr_scsi_wu_put(struct sr_discipline *sd, struct sr_workunit *wu)
{
	scsi_io_put(&sd->sd_iopool, wu);

	if (sd->sd_sync && sd->sd_wu_pending == 0)
		wakeup(sd);
}

void
sr_scsi_done(struct sr_discipline *sd, struct scsi_xfer *xs)
{
	DNPRINTF(SR_D_DIS, "%s: sr_scsi_done: xs %p\n", DEVNAME(sd->sd_sc), xs);

	if (xs->error == XS_NOERROR)
		xs->resid = 0;

	scsi_done(xs);

	if (sd->sd_sync && sd->sd_wu_pending == 0)
		wakeup(sd);
}

void
sr_scsi_cmd(struct scsi_xfer *xs)
{
	struct scsi_link	*link = xs->sc_link;
	struct sr_softc		*sc = link->adapter_softc;
	struct sr_workunit	*wu = xs->io;
	struct sr_discipline	*sd;

	DNPRINTF(SR_D_CMD, "%s: sr_scsi_cmd target %d xs %p flags %#x\n",
	    DEVNAME(sc), link->target, xs, xs->flags);

	sd = sc->sc_targets[link->target];
	if (sd == NULL) {
		printf("%s: sr_scsi_cmd NULL discipline\n", DEVNAME(sc));
		goto stuffup;
	}

	if (sd->sd_deleted) {
		printf("%s: %s device is being deleted, failing io\n",
		    DEVNAME(sc), sd->sd_meta->ssd_devname);
		goto stuffup;
	}

	/* scsi layer *can* re-send wu without calling sr_wu_put(). */
	sr_wu_release_ccbs(wu);
	sr_wu_init(sd, wu);
	wu->swu_state = SR_WU_INPROGRESS;
	wu->swu_xs = xs;

	switch (xs->cmd->opcode) {
	case READ_COMMAND:
	case READ_BIG:
	case READ_16:
	case WRITE_COMMAND:
	case WRITE_BIG:
	case WRITE_16:
		DNPRINTF(SR_D_CMD, "%s: sr_scsi_cmd: READ/WRITE %02x\n",
		    DEVNAME(sc), xs->cmd->opcode);
		if (sd->sd_scsi_rw(wu))
			goto stuffup;
		break;

	case SYNCHRONIZE_CACHE:
		DNPRINTF(SR_D_CMD, "%s: sr_scsi_cmd: SYNCHRONIZE_CACHE\n",
		    DEVNAME(sc));
		if (sd->sd_scsi_sync(wu))
			goto stuffup;
		goto complete;

	case TEST_UNIT_READY:
		DNPRINTF(SR_D_CMD, "%s: sr_scsi_cmd: TEST_UNIT_READY\n",
		    DEVNAME(sc));
		if (sd->sd_scsi_tur(wu))
			goto stuffup;
		goto complete;

	case START_STOP:
		DNPRINTF(SR_D_CMD, "%s: sr_scsi_cmd: START_STOP\n",
		    DEVNAME(sc));
		if (sd->sd_scsi_start_stop(wu))
			goto stuffup;
		goto complete;

	case INQUIRY:
		DNPRINTF(SR_D_CMD, "%s: sr_scsi_cmd: INQUIRY\n",
		    DEVNAME(sc));
		if (sd->sd_scsi_inquiry(wu))
			goto stuffup;
		goto complete;

	case READ_CAPACITY:
	case READ_CAPACITY_16:
		DNPRINTF(SR_D_CMD, "%s: sr_scsi_cmd READ CAPACITY 0x%02x\n",
		    DEVNAME(sc), xs->cmd->opcode);
		if (sd->sd_scsi_read_cap(wu))
			goto stuffup;
		goto complete;

	case REQUEST_SENSE:
		DNPRINTF(SR_D_CMD, "%s: sr_scsi_cmd REQUEST SENSE\n",
		    DEVNAME(sc));
		if (sd->sd_scsi_req_sense(wu))
			goto stuffup;
		goto complete;

	default:
		DNPRINTF(SR_D_CMD, "%s: unsupported scsi command %x\n",
		    DEVNAME(sc), xs->cmd->opcode);
		/* XXX might need to add generic function to handle others */
		goto stuffup;
	}

	return;
stuffup:
	if (sd && sd->sd_scsi_sense.error_code) {
		xs->error = XS_SENSE;
		bcopy(&sd->sd_scsi_sense, &xs->sense, sizeof(xs->sense));
		bzero(&sd->sd_scsi_sense, sizeof(sd->sd_scsi_sense));
	} else {
		xs->error = XS_DRIVER_STUFFUP;
	}
complete:
	sr_scsi_done(sd, xs);
}

int
sr_scsi_probe(struct scsi_link *link)
{
	struct sr_softc		*sc = link->adapter_softc;
	struct sr_discipline	*sd;

	KASSERT(link->target < SR_MAX_LD && link->lun == 0);

	sd = sc->sc_targets[link->target];
	if (sd == NULL)
		return (ENODEV);

	link->pool = &sd->sd_iopool;
	if (sd->sd_openings)
		link->openings = sd->sd_openings(sd);
	else
		link->openings = sd->sd_max_wu;

	return (0);
}

int
sr_scsi_ioctl(struct scsi_link *link, u_long cmd, caddr_t addr, int flag)
{
	DNPRINTF(SR_D_IOCTL, "%s: sr_scsi_ioctl cmd: %#x\n",
	    DEVNAME((struct sr_softc *)link->adapter_softc), cmd);

	/* Pass bio ioctls through to bio handler. */
	if (IOCGROUP(cmd) == 'B')
		return (sr_bio_ioctl(link->adapter_softc, cmd, addr));

	switch (cmd) {
	case DIOCGCACHE:
	case DIOCSCACHE:
		return (EOPNOTSUPP);
	default:
		return (ENOTTY);
	}
}

int
sr_bio_ioctl(struct device *dev, u_long cmd, caddr_t addr)
{
	struct sr_softc		*sc = (struct sr_softc *)dev;
	struct bio		*bio = (struct bio *)addr;
	int			rv = 0;

	DNPRINTF(SR_D_IOCTL, "%s: sr_bio_ioctl ", DEVNAME(sc));

	rw_enter_write(&sc->sc_lock);

	bio_status_init(&sc->sc_status, &sc->sc_dev);

	switch (cmd) {
	case BIOCINQ:
		DNPRINTF(SR_D_IOCTL, "inq\n");
		rv = sr_ioctl_inq(sc, (struct bioc_inq *)addr);
		break;

	case BIOCVOL:
		DNPRINTF(SR_D_IOCTL, "vol\n");
		rv = sr_ioctl_vol(sc, (struct bioc_vol *)addr);
		break;

	case BIOCDISK:
		DNPRINTF(SR_D_IOCTL, "disk\n");
		rv = sr_ioctl_disk(sc, (struct bioc_disk *)addr);
		break;

	case BIOCALARM:
		DNPRINTF(SR_D_IOCTL, "alarm\n");
		/*rv = sr_ioctl_alarm(sc, (struct bioc_alarm *)addr); */
		break;

	case BIOCBLINK:
		DNPRINTF(SR_D_IOCTL, "blink\n");
		/*rv = sr_ioctl_blink(sc, (struct bioc_blink *)addr); */
		break;

	case BIOCSETSTATE:
		DNPRINTF(SR_D_IOCTL, "setstate\n");
		rv = sr_ioctl_setstate(sc, (struct bioc_setstate *)addr);
		break;

	case BIOCCREATERAID:
		DNPRINTF(SR_D_IOCTL, "createraid\n");
		rv = sr_ioctl_createraid(sc, (struct bioc_createraid *)addr,
		    1, NULL);
		break;

	case BIOCDELETERAID:
		DNPRINTF(SR_D_IOCTL, "deleteraid\n");
		rv = sr_ioctl_deleteraid(sc, (struct bioc_deleteraid *)addr);
		break;

	case BIOCDISCIPLINE:
		DNPRINTF(SR_D_IOCTL, "discipline\n");
		rv = sr_ioctl_discipline(sc, (struct bioc_discipline *)addr);
		break;

	case BIOCINSTALLBOOT:
		DNPRINTF(SR_D_IOCTL, "installboot\n");
		rv = sr_ioctl_installboot(sc, (struct bioc_installboot *)addr);
		break;

	default:
		DNPRINTF(SR_D_IOCTL, "invalid ioctl\n");
		rv = ENOTTY;
	}

	sc->sc_status.bs_status = (rv ? BIO_STATUS_ERROR : BIO_STATUS_SUCCESS);

	bcopy(&sc->sc_status, &bio->bio_status, sizeof(struct bio_status));

	rw_exit_write(&sc->sc_lock);

	return (0);
}

int
sr_ioctl_inq(struct sr_softc *sc, struct bioc_inq *bi)
{
	struct sr_discipline	*sd;
	int			vol = 0, disk = 0;

	TAILQ_FOREACH(sd, &sc->sc_dis_list, sd_link) {
		vol++;
		disk += sd->sd_meta->ssdi.ssd_chunk_no;
	}

	strlcpy(bi->bi_dev, sc->sc_dev.dv_xname, sizeof(bi->bi_dev));
	bi->bi_novol = vol + sc->sc_hotspare_no;
	bi->bi_nodisk = disk + sc->sc_hotspare_no;

	return (0);
}

int
sr_ioctl_vol(struct sr_softc *sc, struct bioc_vol *bv)
{
	int			vol = -1, rv = EINVAL;
	struct sr_discipline	*sd;
	struct sr_chunk		*hotspare;
	daddr_t			rb, sz;

	TAILQ_FOREACH(sd, &sc->sc_dis_list, sd_link) {
		vol++;
		if (vol != bv->bv_volid)
			continue;

		bv->bv_status = sd->sd_vol_status;
		bv->bv_size = sd->sd_meta->ssdi.ssd_size << DEV_BSHIFT;
		bv->bv_level = sd->sd_meta->ssdi.ssd_level;
		bv->bv_nodisk = sd->sd_meta->ssdi.ssd_chunk_no;

#ifdef CRYPTO
		if (sd->sd_meta->ssdi.ssd_level == 'C' &&
		    sd->mds.mdd_crypto.key_disk != NULL)
			bv->bv_nodisk++;
#endif

		if (bv->bv_status == BIOC_SVREBUILD) {
			sz = sd->sd_meta->ssdi.ssd_size;
			rb = sd->sd_meta->ssd_rebuild;
			if (rb > 0)
				bv->bv_percent = 100 -
				    ((sz * 100 - rb * 100) / sz) - 1;
			else
				bv->bv_percent = 0;
		}
		strlcpy(bv->bv_dev, sd->sd_meta->ssd_devname,
		    sizeof(bv->bv_dev));
		strlcpy(bv->bv_vendor, sd->sd_meta->ssdi.ssd_vendor,
		    sizeof(bv->bv_vendor));
		rv = 0;
		goto done;
	}

	/* Check hotspares list. */
	SLIST_FOREACH(hotspare, &sc->sc_hotspare_list, src_link) {
		vol++;
		if (vol != bv->bv_volid)
			continue;

		bv->bv_status = BIOC_SVONLINE;
		bv->bv_size = hotspare->src_meta.scmi.scm_size << DEV_BSHIFT;
		bv->bv_level = -1;	/* Hotspare. */
		bv->bv_nodisk = 1;
		strlcpy(bv->bv_dev, hotspare->src_meta.scmi.scm_devname,
		    sizeof(bv->bv_dev));
		strlcpy(bv->bv_vendor, hotspare->src_meta.scmi.scm_devname,
		    sizeof(bv->bv_vendor));
		rv = 0;
		goto done;
	}

done:
	return (rv);
}

int
sr_ioctl_disk(struct sr_softc *sc, struct bioc_disk *bd)
{
	struct sr_discipline	*sd;
	struct sr_chunk		*src, *hotspare;
	int			vol = -1, rv = EINVAL;

	if (bd->bd_diskid < 0)
		goto done;

	TAILQ_FOREACH(sd, &sc->sc_dis_list, sd_link) {
		vol++;
		if (vol != bd->bd_volid)
			continue;

		if (bd->bd_diskid < sd->sd_meta->ssdi.ssd_chunk_no)
			src = sd->sd_vol.sv_chunks[bd->bd_diskid];
#ifdef CRYPTO
		else if (bd->bd_diskid == sd->sd_meta->ssdi.ssd_chunk_no &&
		    sd->sd_meta->ssdi.ssd_level == 'C' &&
		    sd->mds.mdd_crypto.key_disk != NULL)
			src = sd->mds.mdd_crypto.key_disk;
#endif
		else
			break;

		bd->bd_status = src->src_meta.scm_status;
		bd->bd_size = src->src_meta.scmi.scm_size << DEV_BSHIFT;
		bd->bd_channel = vol;
		bd->bd_target = bd->bd_diskid;
		strlcpy(bd->bd_vendor, src->src_meta.scmi.scm_devname,
		    sizeof(bd->bd_vendor));
		rv = 0;
		goto done;
	}

	/* Check hotspares list. */
	SLIST_FOREACH(hotspare, &sc->sc_hotspare_list, src_link) {
		vol++;
		if (vol != bd->bd_volid)
			continue;

		if (bd->bd_diskid != 0)
			break;

		bd->bd_status = hotspare->src_meta.scm_status;
		bd->bd_size = hotspare->src_meta.scmi.scm_size << DEV_BSHIFT;
		bd->bd_channel = vol;
		bd->bd_target = bd->bd_diskid;
		strlcpy(bd->bd_vendor, hotspare->src_meta.scmi.scm_devname,
		    sizeof(bd->bd_vendor));
		rv = 0;
		goto done;
	}

done:
	return (rv);
}

int
sr_ioctl_setstate(struct sr_softc *sc, struct bioc_setstate *bs)
{
	int			rv = EINVAL;
	int			vol = -1, found, c;
	struct sr_discipline	*sd;
	struct sr_chunk		*ch_entry;
	struct sr_chunk_head	*cl;

	if (bs->bs_other_id_type == BIOC_SSOTHER_UNUSED)
		goto done;

	if (bs->bs_status == BIOC_SSHOTSPARE) {
		rv = sr_hotspare(sc, (dev_t)bs->bs_other_id);
		goto done;
	}

	TAILQ_FOREACH(sd, &sc->sc_dis_list, sd_link) {
		vol++;
		if (vol == bs->bs_volid)
			break;
	}
	if (sd == NULL)
		goto done;

	switch (bs->bs_status) {
	case BIOC_SSOFFLINE:
		/* Take chunk offline */
		found = c = 0;
		cl = &sd->sd_vol.sv_chunk_list;
		SLIST_FOREACH(ch_entry, cl, src_link) {
			if (ch_entry->src_dev_mm == bs->bs_other_id) {
				found = 1;
				break;
			}
			c++;
		}
		if (found == 0) {
			sr_error(sc, "chunk not part of array");
			goto done;
		}

		/* XXX: check current state first */
		sd->sd_set_chunk_state(sd, c, BIOC_SDOFFLINE);

		if (sr_meta_save(sd, SR_META_DIRTY)) {
			sr_error(sc, "could not save metadata for %s",
			    sd->sd_meta->ssd_devname);
			goto done;
		}
		rv = 0;
		break;

	case BIOC_SDSCRUB:
		break;

	case BIOC_SSREBUILD:
		rv = sr_rebuild_init(sd, (dev_t)bs->bs_other_id, 0);
		break;

	default:
		sr_error(sc, "unsupported state request %d", bs->bs_status);
	}

done:
	return (rv);
}

int
sr_chunk_in_use(struct sr_softc *sc, dev_t dev)
{
	struct sr_discipline	*sd;
	struct sr_chunk		*chunk;
	int			i;

	DNPRINTF(SR_D_MISC, "%s: sr_chunk_in_use(%d)\n", DEVNAME(sc), dev);

	if (dev == NODEV)
		return BIOC_SDINVALID;

	/* See if chunk is already in use. */
	TAILQ_FOREACH(sd, &sc->sc_dis_list, sd_link) {
		for (i = 0; i < sd->sd_meta->ssdi.ssd_chunk_no; i++) {
			chunk = sd->sd_vol.sv_chunks[i];
			if (chunk->src_dev_mm == dev)
				return chunk->src_meta.scm_status;
		}
	}

	/* Check hotspares list. */
	SLIST_FOREACH(chunk, &sc->sc_hotspare_list, src_link)
		if (chunk->src_dev_mm == dev)
			return chunk->src_meta.scm_status;

	return BIOC_SDINVALID;
}

int
sr_hotspare(struct sr_softc *sc, dev_t dev)
{
	struct sr_discipline	*sd = NULL;
	struct sr_metadata	*sm = NULL;
	struct sr_meta_chunk    *hm;
	struct sr_chunk_head	*cl;
	struct sr_chunk		*chunk, *last, *hotspare = NULL;
	struct sr_uuid		uuid;
	struct disklabel	label;
	struct vnode		*vn;
	daddr_t			size;
	char			devname[32];
	int			rv = EINVAL;
	int			c, part, open = 0;

	/*
	 * Add device to global hotspares list.
	 */

	sr_meta_getdevname(sc, dev, devname, sizeof(devname));

	/* Make sure chunk is not already in use. */
	c = sr_chunk_in_use(sc, dev);
	if (c != BIOC_SDINVALID && c != BIOC_SDOFFLINE) {
		if (c == BIOC_SDHOTSPARE)
			sr_error(sc, "%s is already a hotspare", devname);
		else
			sr_error(sc, "%s is already in use", devname);
		goto done;
	}

	/* XXX - See if there is an existing degraded volume... */

	/* Open device. */
	if (bdevvp(dev, &vn)) {
		sr_error(sc, "sr_hotspare: cannot allocate vnode");
		goto done;
	}
	if (VOP_OPEN(vn, FREAD | FWRITE, NOCRED, curproc)) {
		DNPRINTF(SR_D_META,"%s: sr_hotspare cannot open %s\n",
		    DEVNAME(sc), devname);
		vput(vn);
		goto fail;
	}
	open = 1; /* close dev on error */

	/* Get partition details. */
	part = DISKPART(dev);
	if (VOP_IOCTL(vn, DIOCGDINFO, (caddr_t)&label, FREAD,
	    NOCRED, curproc)) {
		DNPRINTF(SR_D_META, "%s: sr_hotspare ioctl failed\n",
		    DEVNAME(sc));
		VOP_CLOSE(vn, FREAD | FWRITE, NOCRED, curproc);
		vput(vn);
		goto fail;
	}
	if (label.d_secsize != DEV_BSIZE) {
		sr_error(sc, "%s has unsupported sector size (%u)",
		    devname, label.d_secsize);
		goto fail;
	}
	if (label.d_partitions[part].p_fstype != FS_RAID) {
		sr_error(sc, "%s partition not of type RAID (%d)",
		    devname, label.d_partitions[part].p_fstype);
		goto fail;
	}

	/* Calculate partition size. */
	size = DL_SECTOBLK(&label, DL_GETPSIZE(&label.d_partitions[part])) -
	    SR_DATA_OFFSET;

	/*
	 * Create and populate chunk metadata.
	 */

	sr_uuid_generate(&uuid);
	hotspare = malloc(sizeof(struct sr_chunk), M_DEVBUF, M_WAITOK | M_ZERO);

	hotspare->src_dev_mm = dev;
	hotspare->src_vn = vn;
	strlcpy(hotspare->src_devname, devname, sizeof(hm->scmi.scm_devname));
	hotspare->src_size = size;

	hm = &hotspare->src_meta;
	hm->scmi.scm_volid = SR_HOTSPARE_VOLID;
	hm->scmi.scm_chunk_id = 0;
	hm->scmi.scm_size = size;
	hm->scmi.scm_coerced_size = size;
	strlcpy(hm->scmi.scm_devname, devname, sizeof(hm->scmi.scm_devname));
	bcopy(&uuid, &hm->scmi.scm_uuid, sizeof(struct sr_uuid));

	sr_checksum(sc, hm, &hm->scm_checksum,
	    sizeof(struct sr_meta_chunk_invariant));

	hm->scm_status = BIOC_SDHOTSPARE;

	/*
	 * Create and populate our own discipline and metadata.
	 */

	sm = malloc(sizeof(struct sr_metadata), M_DEVBUF, M_WAITOK | M_ZERO);
	sm->ssdi.ssd_magic = SR_MAGIC;
	sm->ssdi.ssd_version = SR_META_VERSION;
	sm->ssd_ondisk = 0;
	sm->ssdi.ssd_vol_flags = 0;
	bcopy(&uuid, &sm->ssdi.ssd_uuid, sizeof(struct sr_uuid));
	sm->ssdi.ssd_chunk_no = 1;
	sm->ssdi.ssd_volid = SR_HOTSPARE_VOLID;
	sm->ssdi.ssd_level = SR_HOTSPARE_LEVEL;
	sm->ssdi.ssd_size = size;
	strlcpy(sm->ssdi.ssd_vendor, "OPENBSD", sizeof(sm->ssdi.ssd_vendor));
	snprintf(sm->ssdi.ssd_product, sizeof(sm->ssdi.ssd_product),
	    "SR %s", "HOTSPARE");
	snprintf(sm->ssdi.ssd_revision, sizeof(sm->ssdi.ssd_revision),
	    "%03d", SR_META_VERSION);

	sd = malloc(sizeof(struct sr_discipline), M_DEVBUF, M_WAITOK | M_ZERO);
	sd->sd_sc = sc;
	sd->sd_meta = sm;
	sd->sd_meta_type = SR_META_F_NATIVE;
	sd->sd_vol_status = BIOC_SVONLINE;
	strlcpy(sd->sd_name, "HOTSPARE", sizeof(sd->sd_name));
	SLIST_INIT(&sd->sd_meta_opt);

	/* Add chunk to volume. */
	sd->sd_vol.sv_chunks = malloc(sizeof(struct sr_chunk *), M_DEVBUF,
	    M_WAITOK | M_ZERO);
	sd->sd_vol.sv_chunks[0] = hotspare;
	SLIST_INIT(&sd->sd_vol.sv_chunk_list);
	SLIST_INSERT_HEAD(&sd->sd_vol.sv_chunk_list, hotspare, src_link);

	/* Save metadata. */
	if (sr_meta_save(sd, SR_META_DIRTY)) {
		sr_error(sc, "could not save metadata to %s", devname);
		goto fail;
	}

	/*
	 * Add chunk to hotspare list.
	 */
	rw_enter_write(&sc->sc_hs_lock);
	cl = &sc->sc_hotspare_list;
	if (SLIST_EMPTY(cl))
		SLIST_INSERT_HEAD(cl, hotspare, src_link);
	else {
		SLIST_FOREACH(chunk, cl, src_link)
			last = chunk;
		SLIST_INSERT_AFTER(last, hotspare, src_link);
	}
	sc->sc_hotspare_no++;
	rw_exit_write(&sc->sc_hs_lock);

	rv = 0;
	goto done;

fail:
	if (hotspare)
		free(hotspare, M_DEVBUF);

done:
	if (sd && sd->sd_vol.sv_chunks)
		free(sd->sd_vol.sv_chunks, M_DEVBUF);
	if (sd)
		free(sd, M_DEVBUF);
	if (sm)
		free(sm, M_DEVBUF);
	if (open) {
		VOP_CLOSE(vn, FREAD | FWRITE, NOCRED, curproc);
		vput(vn);
	}

	return (rv);
}

void
sr_hotspare_rebuild_callback(void *arg1, void *arg2)
{
	sr_hotspare_rebuild((struct sr_discipline *)arg1);
}

void
sr_hotspare_rebuild(struct sr_discipline *sd)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct sr_chunk_head	*cl;
	struct sr_chunk		*hotspare, *chunk = NULL;
	struct sr_workunit	*wu;
	struct sr_ccb		*ccb;
	int			i, s, chunk_no, busy;

	/*
	 * Attempt to locate a hotspare and initiate rebuild.
	 */

	for (i = 0; i < sd->sd_meta->ssdi.ssd_chunk_no; i++) {
		if (sd->sd_vol.sv_chunks[i]->src_meta.scm_status ==
		    BIOC_SDOFFLINE) {
			chunk_no = i;
			chunk = sd->sd_vol.sv_chunks[i];
			break;
		}
	}

	if (chunk == NULL) {
		printf("%s: no offline chunk found on %s!\n",
		    DEVNAME(sc), sd->sd_meta->ssd_devname);
		return;
	}

	/* See if we have a suitable hotspare... */
	rw_enter_write(&sc->sc_hs_lock);
	cl = &sc->sc_hotspare_list;
	SLIST_FOREACH(hotspare, cl, src_link)
		if (hotspare->src_size >= chunk->src_size)
			break;

	if (hotspare != NULL) {

		printf("%s: %s volume degraded, will attempt to "
		    "rebuild on hotspare %s\n", DEVNAME(sc),
		    sd->sd_meta->ssd_devname, hotspare->src_devname);

		/*
		 * Ensure that all pending I/O completes on the failed chunk
		 * before trying to initiate a rebuild.
		 */
		i = 0;
		do {
			busy = 0;

			s = splbio();
			TAILQ_FOREACH(wu, &sd->sd_wu_pendq, swu_link) {
				TAILQ_FOREACH(ccb, &wu->swu_ccb, ccb_link) {
					if (ccb->ccb_target == chunk_no)
						busy = 1;
				}
			}
			TAILQ_FOREACH(wu, &sd->sd_wu_defq, swu_link) {
				TAILQ_FOREACH(ccb, &wu->swu_ccb, ccb_link) {
					if (ccb->ccb_target == chunk_no)
						busy = 1;
				}
			}
			splx(s);

			if (busy) {
				tsleep(sd, PRIBIO, "sr_hotspare", hz);
				i++;
			}

		} while (busy && i < 120);

		DNPRINTF(SR_D_META, "%s: waited %i seconds for I/O to "
		    "complete on failed chunk %s\n", DEVNAME(sc),
		    i, chunk->src_devname);

		if (busy) {
			printf("%s: pending I/O failed to complete on "
			    "failed chunk %s, hotspare rebuild aborted...\n",
			    DEVNAME(sc), chunk->src_devname);
			goto done;
		}

		s = splbio();
		rw_enter_write(&sc->sc_lock);
		bio_status_init(&sc->sc_status, &sc->sc_dev);
		if (sr_rebuild_init(sd, hotspare->src_dev_mm, 1) == 0) {

			/* Remove hotspare from available list. */
			sc->sc_hotspare_no--;
			SLIST_REMOVE(cl, hotspare, sr_chunk, src_link);
			free(hotspare, M_DEVBUF);

		}
		rw_exit_write(&sc->sc_lock);
		splx(s);
	}
done:
	rw_exit_write(&sc->sc_hs_lock);
}

int
sr_rebuild_init(struct sr_discipline *sd, dev_t dev, int hotspare)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct sr_chunk		*chunk = NULL;
	struct sr_meta_chunk	*meta;
	struct disklabel	label;
	struct vnode		*vn;
	daddr_t			size, csize;
	char			devname[32];
	int			rv = EINVAL, open = 0;
	int			cid, i, part, status;

	/*
	 * Attempt to initiate a rebuild onto the specified device.
	 */

	if (!(sd->sd_capabilities & SR_CAP_REBUILD)) {
		sr_error(sc, "discipline does not support rebuild");
		goto done;
	}

	/* make sure volume is in the right state */
	if (sd->sd_vol_status == BIOC_SVREBUILD) {
		sr_error(sc, "rebuild already in progress");
		goto done;
	}
	if (sd->sd_vol_status != BIOC_SVDEGRADED) {
		sr_error(sc, "volume not degraded");
		goto done;
	}

	/* Find first offline chunk. */
	for (cid = 0; cid < sd->sd_meta->ssdi.ssd_chunk_no; cid++) {
		if (sd->sd_vol.sv_chunks[cid]->src_meta.scm_status ==
		    BIOC_SDOFFLINE) {
			chunk = sd->sd_vol.sv_chunks[cid];
			break;
		}
	}
	if (chunk == NULL) {
		sr_error(sc, "no offline chunks available to rebuild");
		goto done;
	}

	/* Get coerced size from another online chunk. */
	for (i = 0; i < sd->sd_meta->ssdi.ssd_chunk_no; i++) {
		if (sd->sd_vol.sv_chunks[i]->src_meta.scm_status ==
		    BIOC_SDONLINE) {
			meta = &sd->sd_vol.sv_chunks[i]->src_meta;
			csize = meta->scmi.scm_coerced_size;
			break;
		}
	}

	sr_meta_getdevname(sc, dev, devname, sizeof(devname));
	if (bdevvp(dev, &vn)) {
		printf("%s: sr_rebuild_init: can't allocate vnode\n",
		    DEVNAME(sc));
		goto done;
	}
	if (VOP_OPEN(vn, FREAD | FWRITE, NOCRED, curproc)) {
		DNPRINTF(SR_D_META,"%s: sr_ioctl_setstate can't "
		    "open %s\n", DEVNAME(sc), devname);
		vput(vn);
		goto done;
	}
	open = 1; /* close dev on error */

	/* Get disklabel and check partition. */
	part = DISKPART(dev);
	if (VOP_IOCTL(vn, DIOCGDINFO, (caddr_t)&label, FREAD,
	    NOCRED, curproc)) {
		DNPRINTF(SR_D_META, "%s: sr_ioctl_setstate ioctl failed\n",
		    DEVNAME(sc));
		goto done;
	}
	if (label.d_secsize != DEV_BSIZE) {
		sr_error(sc, "%s has unsupported sector size (%u)",
		    devname, label.d_secsize);
		goto done;
	}
	if (label.d_partitions[part].p_fstype != FS_RAID) {
		sr_error(sc, "%s partition not of type RAID (%d)",
		    devname, label.d_partitions[part].p_fstype);
		goto done;
	}

	/* Is the partition large enough? */
	size = DL_SECTOBLK(&label, DL_GETPSIZE(&label.d_partitions[part])) -
	    SR_DATA_OFFSET;
	if (size < csize) {
		sr_error(sc, "%s partition too small, at least %lld bytes "
		    "required", devname, (long long)(csize << DEV_BSHIFT));
		goto done;
	} else if (size > csize)
		sr_warn(sc, "%s partition too large, wasting %lld bytes",
		    devname, (long long)((size - csize) << DEV_BSHIFT));

	/* Ensure that this chunk is not already in use. */
	status = sr_chunk_in_use(sc, dev);
	if (status != BIOC_SDINVALID && status != BIOC_SDOFFLINE &&
	    !(hotspare && status == BIOC_SDHOTSPARE)) {
		sr_error(sc, "%s is already in use", devname);
		goto done;
	}

	/* Reset rebuild counter since we rebuilding onto a new chunk. */
	sd->sd_meta->ssd_rebuild = 0;

	open = 0; /* leave dev open from here on out */

	/* Fix up chunk. */
	bcopy(label.d_uid, chunk->src_duid, sizeof(chunk->src_duid));
	chunk->src_dev_mm = dev;
	chunk->src_vn = vn;

	/* Reconstruct metadata. */
	meta = &chunk->src_meta;
	meta->scmi.scm_volid = sd->sd_meta->ssdi.ssd_volid;
	meta->scmi.scm_chunk_id = cid;
	strlcpy(meta->scmi.scm_devname, devname,
	    sizeof(meta->scmi.scm_devname));
	meta->scmi.scm_size = size;
	meta->scmi.scm_coerced_size = csize;
	bcopy(&sd->sd_meta->ssdi.ssd_uuid, &meta->scmi.scm_uuid,
	    sizeof(meta->scmi.scm_uuid));
	sr_checksum(sc, meta, &meta->scm_checksum,
	    sizeof(struct sr_meta_chunk_invariant));

	sd->sd_set_chunk_state(sd, cid, BIOC_SDREBUILD);

	if (sr_meta_save(sd, SR_META_DIRTY)) {
		sr_error(sc, "could not save metadata to %s", devname);
		open = 1;
		goto done;
	}

	sr_warn(sc, "rebuild of %s started on %s",
	    sd->sd_meta->ssd_devname, devname);

	sd->sd_reb_abort = 0;
	kthread_create_deferred(sr_rebuild_start, sd);

	rv = 0;
done:
	if (open) {
		VOP_CLOSE(vn, FREAD | FWRITE, NOCRED, curproc);
		vput(vn);
	}

	return (rv);
}

void
sr_roam_chunks(struct sr_discipline *sd)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct sr_chunk		*chunk;
	struct sr_meta_chunk	*meta;
	int			roamed = 0;

	/* Have any chunks roamed? */
	SLIST_FOREACH(chunk, &sd->sd_vol.sv_chunk_list, src_link) {
		meta = &chunk->src_meta;
		if (strncmp(meta->scmi.scm_devname, chunk->src_devname,
		    sizeof(meta->scmi.scm_devname))) {

			printf("%s: roaming device %s -> %s\n", DEVNAME(sc),
			    meta->scmi.scm_devname, chunk->src_devname);

			strlcpy(meta->scmi.scm_devname, chunk->src_devname,
			    sizeof(meta->scmi.scm_devname));

			roamed++;
		}
	}

	if (roamed)
		sr_meta_save(sd, SR_META_DIRTY);
}

int
sr_ioctl_createraid(struct sr_softc *sc, struct bioc_createraid *bc,
    int user, void *data)
{
	struct sr_meta_opt_item *omi;
	struct sr_chunk_head	*cl;
	struct sr_discipline	*sd = NULL;
	struct sr_chunk		*ch_entry;
	struct scsi_link	*link;
	struct device		*dev;
	char			*uuid, devname[32];
	dev_t			*dt;
	int			i, no_chunk, rv = EINVAL, target, vol;
	int			no_meta;

	DNPRINTF(SR_D_IOCTL, "%s: sr_ioctl_createraid(%d)\n",
	    DEVNAME(sc), user);

	/* user input */
	if (bc->bc_dev_list_len > BIOC_CRMAXLEN)
		goto unwind;

	dt = malloc(bc->bc_dev_list_len, M_DEVBUF, M_WAITOK | M_ZERO);
	if (user) {
		if (copyin(bc->bc_dev_list, dt, bc->bc_dev_list_len) != 0)
			goto unwind;
	} else
		bcopy(bc->bc_dev_list, dt, bc->bc_dev_list_len);

	/* Initialise discipline. */
	sd = malloc(sizeof(struct sr_discipline), M_DEVBUF, M_WAITOK | M_ZERO);
	sd->sd_sc = sc;
	SLIST_INIT(&sd->sd_meta_opt);
	sd->sd_taskq = taskq_create("srdis", 1, IPL_BIO);
	if (sd->sd_taskq == NULL) {
		sr_error(sc, "could not create discipline taskq");
		goto unwind;
	}
	if (sr_discipline_init(sd, bc->bc_level)) {
		sr_error(sc, "could not initialize discipline");
		goto unwind;
	}

	no_chunk = bc->bc_dev_list_len / sizeof(dev_t);
	cl = &sd->sd_vol.sv_chunk_list;
	SLIST_INIT(cl);

	/* Ensure that chunks are not already in use. */
	for (i = 0; i < no_chunk; i++) {
		if (sr_chunk_in_use(sc, dt[i]) != BIOC_SDINVALID) {
			sr_meta_getdevname(sc, dt[i], devname, sizeof(devname));
			sr_error(sc, "chunk %s already in use", devname);
			goto unwind;
		}
	}

	sd->sd_meta_type = sr_meta_probe(sd, dt, no_chunk);
	if (sd->sd_meta_type == SR_META_F_INVALID) {
		sr_error(sc, "invalid metadata format");
		goto unwind;
	}

	if (sr_meta_attach(sd, no_chunk, bc->bc_flags & BIOC_SCFORCE))
		goto unwind;

	/* force the raid volume by clearing metadata region */
	if (bc->bc_flags & BIOC_SCFORCE) {
		/* make sure disk isn't up and running */
		if (sr_meta_read(sd))
			if (sr_already_assembled(sd)) {
				uuid = sr_uuid_format(
				    &sd->sd_meta->ssdi.ssd_uuid);
				sr_error(sc, "disk %s is currently in use; "
				    "cannot force create", uuid);
				free(uuid, M_DEVBUF);
				goto unwind;
			}

		if (sr_meta_clear(sd)) {
			sr_error(sc, "failed to clear metadata");
			goto unwind;
		}
	}

	no_meta = sr_meta_read(sd);
	if (no_meta == -1) {

		/* Corrupt metadata on one or more chunks. */
		sr_error(sc, "one of the chunks has corrupt metadata; "
		    "aborting assembly");
		goto unwind;

	} else if (no_meta == 0) {

		/* Initialise volume and chunk metadata. */
		sr_meta_init(sd, bc->bc_level, no_chunk);
		sd->sd_vol_status = BIOC_SVONLINE;
		sd->sd_meta_flags = bc->bc_flags & BIOC_SCNOAUTOASSEMBLE;
		if (sd->sd_create) {
			if ((i = sd->sd_create(sd, bc, no_chunk,
			    sd->sd_vol.sv_chunk_minsz))) {
				rv = i;
				goto unwind;
			}
		}
		sr_meta_init_complete(sd);

		DNPRINTF(SR_D_IOCTL,
		    "%s: sr_ioctl_createraid: vol_size: %lld\n",
		    DEVNAME(sc), sd->sd_meta->ssdi.ssd_size);

		/* Warn if we've wasted chunk space due to coercing. */
		if ((sd->sd_capabilities & SR_CAP_NON_COERCED) == 0 &&
		    sd->sd_vol.sv_chunk_minsz != sd->sd_vol.sv_chunk_maxsz)
			sr_warn(sc, "chunk sizes are not equal; up to %llu "
			    "blocks wasted per chunk",
			    sd->sd_vol.sv_chunk_maxsz -
			    sd->sd_vol.sv_chunk_minsz);

	} else {

		/* Ensure metadata level matches requested assembly level. */
		if (sd->sd_meta->ssdi.ssd_level != bc->bc_level) {
			sr_error(sc, "volume level does not match metadata "
			    "level");
			goto unwind;
		}

		if (sr_already_assembled(sd)) {
			uuid = sr_uuid_format(&sd->sd_meta->ssdi.ssd_uuid);
			sr_error(sc, "disk %s already assembled", uuid);
			free(uuid, M_DEVBUF);
			goto unwind;
		}

		if (user == 0 && sd->sd_meta_flags & BIOC_SCNOAUTOASSEMBLE) {
			DNPRINTF(SR_D_META, "%s: disk not auto assembled from "
			    "metadata\n", DEVNAME(sc));
			goto unwind;
		}

		if (no_meta != no_chunk)
			sr_warn(sc, "trying to bring up %s degraded",
			    sd->sd_meta->ssd_devname);

		if (sd->sd_meta->ssd_meta_flags & SR_META_DIRTY)
			sr_warn(sc, "%s was not shutdown properly",
			    sd->sd_meta->ssd_devname);

		SLIST_FOREACH(omi, &sd->sd_meta_opt, omi_link)
			if (sd->sd_meta_opt_handler == NULL ||
			    sd->sd_meta_opt_handler(sd, omi->omi_som) != 0)
				sr_meta_opt_handler(sd, omi->omi_som);

		if (sd->sd_assemble) {
			if ((i = sd->sd_assemble(sd, bc, no_chunk, data))) {
				rv = i;
				goto unwind;
			}
		}

		DNPRINTF(SR_D_META, "%s: disk assembled from metadata\n",
		    DEVNAME(sc));

	}

	/* Metadata MUST be fully populated by this point. */
	TAILQ_INSERT_TAIL(&sc->sc_dis_list, sd, sd_link);

	/* Allocate all resources. */
	if ((rv = sd->sd_alloc_resources(sd)))
		goto unwind;

	/* Adjust flags if necessary. */
	if ((sd->sd_capabilities & SR_CAP_AUTO_ASSEMBLE) &&
	    (bc->bc_flags & BIOC_SCNOAUTOASSEMBLE) !=
	    (sd->sd_meta->ssdi.ssd_vol_flags & BIOC_SCNOAUTOASSEMBLE)) {
		sd->sd_meta->ssdi.ssd_vol_flags &= ~BIOC_SCNOAUTOASSEMBLE;
		sd->sd_meta->ssdi.ssd_vol_flags |=
		    bc->bc_flags & BIOC_SCNOAUTOASSEMBLE;
	}

	if (sd->sd_capabilities & SR_CAP_SYSTEM_DISK) {
		
		/* Initialise volume state. */
		sd->sd_set_vol_state(sd);
		if (sd->sd_vol_status == BIOC_SVOFFLINE) {
			sr_error(sc, "%s is offline, will not be brought "
			    "online", sd->sd_meta->ssd_devname);
			goto unwind;
		}

		/* Setup SCSI iopool. */
		scsi_iopool_init(&sd->sd_iopool, sd, sr_wu_get, sr_wu_put);

		/*
		 * All checks passed - return ENXIO if volume cannot be created.
		 */
		rv = ENXIO;

		/*
		 * Find a free target.
		 *
		 * XXX: We reserve sd_target == 0 to indicate the
		 * discipline is not linked into sc->sc_targets, so begin
		 * the search with target = 1.
		 */
		for (target = 1; target < SR_MAX_LD; target++)
			if (sc->sc_targets[target] == NULL)
				break;
		if (target == SR_MAX_LD) {
			sr_error(sc, "no free target for %s",
			    sd->sd_meta->ssd_devname);
			goto unwind;
		}

		/* Clear sense data. */
		bzero(&sd->sd_scsi_sense, sizeof(sd->sd_scsi_sense));

		/* Attach discipline and get midlayer to probe it. */
		sd->sd_target = target;
		sc->sc_targets[target] = sd;
		if (scsi_probe_lun(sc->sc_scsibus, target, 0) != 0) {
			sr_error(sc, "scsi_probe_lun failed");
			sc->sc_targets[target] = NULL;
			sd->sd_target = 0;
			goto unwind;
		}

		link = scsi_get_link(sc->sc_scsibus, target, 0);
		dev = link->device_softc;
		DNPRINTF(SR_D_IOCTL, "%s: sr device added: %s at target %d\n",
		    DEVNAME(sc), dev->dv_xname, sd->sd_target);

		/* XXX - Count volumes, not targets. */
		for (i = 0, vol = -1; i <= sd->sd_target; i++)
			if (sc->sc_targets[i])
				vol++;

		rv = 0;

		if (sd->sd_meta->ssd_devname[0] != '\0' &&
		    strncmp(sd->sd_meta->ssd_devname, dev->dv_xname,
		    sizeof(dev->dv_xname)))
			sr_warn(sc, "volume %s is roaming, it used to be %s, "
			    "updating metadata", dev->dv_xname,
			    sd->sd_meta->ssd_devname);

		/* Populate remaining volume metadata. */
		sd->sd_meta->ssdi.ssd_volid = vol;
		strlcpy(sd->sd_meta->ssd_devname, dev->dv_xname,
		    sizeof(sd->sd_meta->ssd_devname));

		sr_info(sc, "%s volume attached as %s",
		    sd->sd_name, sd->sd_meta->ssd_devname); 

		/* Update device name on any roaming chunks. */
		sr_roam_chunks(sd);

#ifndef SMALL_KERNEL
		if (sr_sensors_create(sd))
			sr_warn(sc, "unable to create sensor for %s",
			    dev->dv_xname);
#endif /* SMALL_KERNEL */
	} else {
		/* This volume does not attach as a system disk. */
		ch_entry = SLIST_FIRST(cl); /* XXX */
		strlcpy(sd->sd_meta->ssd_devname, ch_entry->src_devname,
		    sizeof(sd->sd_meta->ssd_devname));

		if (sd->sd_start_discipline(sd))
			goto unwind;
	}

	/* Save current metadata to disk. */
	rv = sr_meta_save(sd, SR_META_DIRTY);

	if (sd->sd_vol_status == BIOC_SVREBUILD)
		kthread_create_deferred(sr_rebuild_start, sd);

	sd->sd_ready = 1;

	return (rv);

unwind:
	sr_discipline_shutdown(sd, 0);

	if (rv == EAGAIN)
		rv = 0;

	return (rv);
}

int
sr_ioctl_deleteraid(struct sr_softc *sc, struct bioc_deleteraid *bd)
{
	struct sr_discipline	*sd;
	int			rv = 1;

	DNPRINTF(SR_D_IOCTL, "%s: sr_ioctl_deleteraid %s\n",
	    DEVNAME(sc), bd->bd_dev);

	TAILQ_FOREACH(sd, &sc->sc_dis_list, sd_link) {
		if (!strncmp(sd->sd_meta->ssd_devname, bd->bd_dev,
		    sizeof(sd->sd_meta->ssd_devname)))
			break;
	}
	if (sd == NULL) {
		sr_error(sc, "volume %s not found", bd->bd_dev);
		goto bad;
	}

	sd->sd_deleted = 1;
	sd->sd_meta->ssdi.ssd_vol_flags = BIOC_SCNOAUTOASSEMBLE;
	sr_discipline_shutdown(sd, 1);

	rv = 0;
bad:
	return (rv);
}

int
sr_ioctl_discipline(struct sr_softc *sc, struct bioc_discipline *bd)
{
	struct sr_discipline	*sd;
	int			rv = 1;

	/* Dispatch a discipline specific ioctl. */

	DNPRINTF(SR_D_IOCTL, "%s: sr_ioctl_discipline %s\n", DEVNAME(sc),
	    bd->bd_dev);

	TAILQ_FOREACH(sd, &sc->sc_dis_list, sd_link) {
		if (!strncmp(sd->sd_meta->ssd_devname, bd->bd_dev,
		    sizeof(sd->sd_meta->ssd_devname)))
			break;
	}
	if (sd == NULL) {
		sr_error(sc, "volume %s not found", bd->bd_dev);
		goto bad;
	}

	if (sd->sd_ioctl_handler)
		rv = sd->sd_ioctl_handler(sd, bd);

bad:
	return (rv);
}

int
sr_ioctl_installboot(struct sr_softc *sc, struct bioc_installboot *bb)
{
	void			*bootblk = NULL, *bootldr = NULL;
	struct sr_discipline	*sd;
	struct sr_chunk		*chunk;
	struct sr_meta_opt_item *omi;
	struct sr_meta_boot	*sbm;
	struct disk		*dk;
	u_int32_t		bbs, bls;
	u_char			duid[8];
	int			rv = EINVAL;
	int			i;

	DNPRINTF(SR_D_IOCTL, "%s: sr_ioctl_installboot %s\n", DEVNAME(sc),
	    bb->bb_dev);

	TAILQ_FOREACH(sd, &sc->sc_dis_list, sd_link) {
		if (!strncmp(sd->sd_meta->ssd_devname, bb->bb_dev,
		    sizeof(sd->sd_meta->ssd_devname)))
			break;
	}
	if (sd == NULL) {
		sr_error(sc, "volume %s not found", bb->bb_dev);
		goto done;
	}

	bzero(duid, sizeof(duid));
	TAILQ_FOREACH(dk, &disklist,  dk_link)
		if (!strncmp(dk->dk_name, bb->bb_dev, sizeof(bb->bb_dev)))
			break;
	if (dk == NULL || dk->dk_label == NULL ||
	    (dk->dk_flags & DKF_LABELVALID) == 0 ||
	    bcmp(dk->dk_label->d_uid, &duid, sizeof(duid)) == 0) {
		sr_error(sc, "failed to get DUID for softraid volume");
		goto done;
	}
	bcopy(dk->dk_label->d_uid, duid, sizeof(duid));

	/* Ensure that boot storage area is large enough. */
	if (sd->sd_meta->ssd_data_offset < (SR_BOOT_OFFSET + SR_BOOT_SIZE)) {
		sr_error(sc, "insufficient boot storage");
		goto done;
	}

	if (bb->bb_bootblk_size > SR_BOOT_BLOCKS_SIZE * 512)
		goto done;

	if (bb->bb_bootldr_size > SR_BOOT_LOADER_SIZE * 512)
		goto done;

	/* Copy in boot block. */
	bbs = howmany(bb->bb_bootblk_size, DEV_BSIZE) * DEV_BSIZE;
	bootblk = malloc(bbs, M_DEVBUF, M_WAITOK | M_ZERO);
	if (copyin(bb->bb_bootblk, bootblk, bb->bb_bootblk_size) != 0)
		goto done;

	/* Copy in boot loader. */
	bls = howmany(bb->bb_bootldr_size, DEV_BSIZE) * DEV_BSIZE;
	bootldr = malloc(bls, M_DEVBUF, M_WAITOK | M_ZERO);
	if (copyin(bb->bb_bootldr, bootldr, bb->bb_bootldr_size) != 0)
		goto done;

	/* Create or update optional meta for bootable volumes. */
	SLIST_FOREACH(omi, &sd->sd_meta_opt, omi_link)
		if (omi->omi_som->som_type == SR_OPT_BOOT)
			break;
	if (omi == NULL) {
		omi = malloc(sizeof(struct sr_meta_opt_item), M_DEVBUF,
		    M_WAITOK | M_ZERO);
		omi->omi_som = malloc(sizeof(struct sr_meta_crypto), M_DEVBUF,
		    M_WAITOK | M_ZERO);
		omi->omi_som->som_type = SR_OPT_BOOT;
		omi->omi_som->som_length = sizeof(struct sr_meta_boot);
		SLIST_INSERT_HEAD(&sd->sd_meta_opt, omi, omi_link);
		sd->sd_meta->ssdi.ssd_opt_no++;
	}
	sbm = (struct sr_meta_boot *)omi->omi_som;

	bcopy(duid, sbm->sbm_root_duid, sizeof(sbm->sbm_root_duid));
	bzero(&sbm->sbm_boot_duid, sizeof(sbm->sbm_boot_duid));
	sbm->sbm_bootblk_size = bbs;
	sbm->sbm_bootldr_size = bls;

	DNPRINTF(SR_D_IOCTL, "sr_ioctl_installboot: root duid is "
	    "%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx%02hhx\n",
	    sbm->sbm_root_duid[0], sbm->sbm_root_duid[1],
	    sbm->sbm_root_duid[2], sbm->sbm_root_duid[3],
	    sbm->sbm_root_duid[4], sbm->sbm_root_duid[5],
	    sbm->sbm_root_duid[6], sbm->sbm_root_duid[7]);

	/* Save boot block and boot loader to each chunk. */
	for (i = 0; i < sd->sd_meta->ssdi.ssd_chunk_no; i++) {

		chunk = sd->sd_vol.sv_chunks[i];
		if (chunk->src_meta.scm_status != BIOC_SDONLINE &&
		    chunk->src_meta.scm_status != BIOC_SDREBUILD)
			continue;

		if (i < SR_MAX_BOOT_DISKS)
			bcopy(chunk->src_duid, &sbm->sbm_boot_duid[i],
			    sizeof(sbm->sbm_boot_duid[i]));

		/* Save boot blocks. */
		DNPRINTF(SR_D_IOCTL,
		    "sr_ioctl_installboot: saving boot block to %s "
		    "(%u bytes)\n", chunk->src_devname, bbs);

		if (sr_rw(sc, chunk->src_dev_mm, bootblk, bbs,
		    SR_BOOT_BLOCKS_OFFSET, B_WRITE)) {
			sr_error(sc, "failed to write boot block", DEVNAME(sc));
			goto done;
		}

		/* Save boot loader.*/
		DNPRINTF(SR_D_IOCTL,
		    "sr_ioctl_installboot: saving boot loader to %s "
		    "(%u bytes)\n", chunk->src_devname, bls);

		if (sr_rw(sc, chunk->src_dev_mm, bootldr, bls,
		    SR_BOOT_LOADER_OFFSET, B_WRITE)) {
			sr_error(sc, "failed to write boot loader");
			goto done;
		}

	}

	/* XXX - Install boot block on disk - MD code. */

	/* Mark volume as bootable and save metadata. */
	sd->sd_meta->ssdi.ssd_vol_flags |= BIOC_SCBOOTABLE;
	if (sr_meta_save(sd, SR_META_DIRTY)) {
		sr_error(sc, "could not save metadata to %s",
		    chunk->src_devname);
		goto done;
	}

	rv = 0;

done:
	if (bootblk)
		free(bootblk, M_DEVBUF);
	if (bootldr)
		free(bootldr, M_DEVBUF);

	return (rv);
}

void
sr_chunks_unwind(struct sr_softc *sc, struct sr_chunk_head *cl)
{
	struct sr_chunk		*ch_entry, *ch_next;

	DNPRINTF(SR_D_IOCTL, "%s: sr_chunks_unwind\n", DEVNAME(sc));

	if (!cl)
		return;

	for (ch_entry = SLIST_FIRST(cl);
	    ch_entry != SLIST_END(cl); ch_entry = ch_next) {
		ch_next = SLIST_NEXT(ch_entry, src_link);

		DNPRINTF(SR_D_IOCTL, "%s: sr_chunks_unwind closing: %s\n",
		    DEVNAME(sc), ch_entry->src_devname);
		if (ch_entry->src_vn) {
			/*
			 * XXX - explicitly lock the vnode until we can resolve
			 * the problem introduced by vnode aliasing... specfs
			 * has no locking, whereas ufs/ffs does!
			 */
			vn_lock(ch_entry->src_vn, LK_EXCLUSIVE |
			    LK_RETRY, curproc);
			VOP_CLOSE(ch_entry->src_vn, FREAD | FWRITE, NOCRED,
			    curproc);
			vput(ch_entry->src_vn);
		}
		free(ch_entry, M_DEVBUF);
	}
	SLIST_INIT(cl);
}

void
sr_discipline_free(struct sr_discipline *sd)
{
	struct sr_softc		*sc;
	struct sr_discipline	*sdtmp1, *sdtmp2;
	struct sr_meta_opt_head *som;
	struct sr_meta_opt_item	*omi, *omi_next;

	if (!sd)
		return;

	sc = sd->sd_sc;

	DNPRINTF(SR_D_DIS, "%s: sr_discipline_free %s\n",
	    DEVNAME(sc),
	    sd->sd_meta ? sd->sd_meta->ssd_devname : "nodev");
	if (sd->sd_free_resources)
		sd->sd_free_resources(sd);
	if (sd->sd_vol.sv_chunks)
		free(sd->sd_vol.sv_chunks, M_DEVBUF);
	if (sd->sd_meta)
		free(sd->sd_meta, M_DEVBUF);
	if (sd->sd_meta_foreign)
		free(sd->sd_meta_foreign, M_DEVBUF);

	som = &sd->sd_meta_opt;
	for (omi = SLIST_FIRST(som); omi != SLIST_END(som); omi = omi_next) {
		omi_next = SLIST_NEXT(omi, omi_link);
		if (omi->omi_som)
			free(omi->omi_som, M_DEVBUF);
		free(omi, M_DEVBUF);
	}

	if (sd->sd_target != 0) {
		KASSERT(sc->sc_targets[sd->sd_target] == sd);
		sc->sc_targets[sd->sd_target] = NULL;
	}

	TAILQ_FOREACH_SAFE(sdtmp1, &sc->sc_dis_list, sd_link, sdtmp2) {
		if (sdtmp1 == sd) {
			TAILQ_REMOVE(&sc->sc_dis_list, sd, sd_link);
			break;
		}
	}

	explicit_bzero(sd, sizeof *sd);
	free(sd, M_DEVBUF);
}

void
sr_discipline_shutdown(struct sr_discipline *sd, int meta_save)
{
	struct sr_softc		*sc;
	int			s;

	if (!sd)
		return;
	sc = sd->sd_sc;

	DNPRINTF(SR_D_DIS, "%s: sr_discipline_shutdown %s\n", DEVNAME(sc),
	    sd->sd_meta ? sd->sd_meta->ssd_devname : "nodev");

	/* If rebuilding, abort rebuild and drain I/O. */
	if (sd->sd_reb_active) {
		sd->sd_reb_abort = 1;
		while (sd->sd_reb_active)
			tsleep(sd, PWAIT, "sr_shutdown", 1);
	}

	if (meta_save)
		sr_meta_save(sd, 0);

	s = splbio();

	sd->sd_ready = 0;

	/* make sure there isn't a sync pending and yield */
	wakeup(sd);
	while (sd->sd_sync || sd->sd_must_flush)
		if (tsleep(&sd->sd_sync, MAXPRI, "sr_down", 60 * hz) ==
		    EWOULDBLOCK)
			break;

#ifndef SMALL_KERNEL
	sr_sensors_delete(sd);
#endif /* SMALL_KERNEL */

	if (sd->sd_target != 0)
		scsi_detach_lun(sc->sc_scsibus, sd->sd_target, 0, DETACH_FORCE);

	sr_chunks_unwind(sc, &sd->sd_vol.sv_chunk_list);

	if (sd->sd_taskq)
		taskq_destroy(sd->sd_taskq);

	sr_discipline_free(sd);

	splx(s);
}

int
sr_discipline_init(struct sr_discipline *sd, int level)
{
	int			rv = 1;

	/* Initialise discipline function pointers with defaults. */
	sd->sd_alloc_resources = sr_alloc_resources;
	sd->sd_assemble = NULL;
	sd->sd_create = NULL;
	sd->sd_free_resources = sr_free_resources;
	sd->sd_ioctl_handler = NULL;
	sd->sd_openings = NULL;
	sd->sd_meta_opt_handler = NULL;
	sd->sd_rebuild = sr_rebuild;
	sd->sd_scsi_inquiry = sr_raid_inquiry;
	sd->sd_scsi_read_cap = sr_raid_read_cap;
	sd->sd_scsi_tur = sr_raid_tur;
	sd->sd_scsi_req_sense = sr_raid_request_sense;
	sd->sd_scsi_start_stop = sr_raid_start_stop;
	sd->sd_scsi_sync = sr_raid_sync;
	sd->sd_scsi_rw = NULL;
	sd->sd_scsi_intr = sr_raid_intr;
	sd->sd_scsi_wu_done = NULL;
	sd->sd_scsi_done = NULL;
	sd->sd_set_chunk_state = sr_set_chunk_state;
	sd->sd_set_vol_state = sr_set_vol_state;
	sd->sd_start_discipline = NULL;

	task_set(&sd->sd_meta_save_task, sr_meta_save_callback, sd, NULL);

	switch (level) {
	case 0:
		sr_raid0_discipline_init(sd);
		break;
	case 1:
		sr_raid1_discipline_init(sd);
		break;
	case 5:
		sr_raid5_discipline_init(sd);
		break;
	case 6:
		sr_raid6_discipline_init(sd);
		break;
#ifdef AOE
	/* AOE target. */
	case 'A':
		sr_aoe_server_discipline_init(sd);
		break;
	/* AOE initiator. */
	case 'a':
		sr_aoe_discipline_init(sd);
		break;
#endif
#ifdef CRYPTO
	case 'C':
		sr_crypto_discipline_init(sd);
		break;
#endif
	case 'c':
		sr_concat_discipline_init(sd);
		break;
	default:
		goto bad;
	}

	rv = 0;
bad:
	return (rv);
}

int
sr_raid_inquiry(struct sr_workunit *wu)
{
	struct sr_discipline	*sd = wu->swu_dis;
	struct scsi_xfer	*xs = wu->swu_xs;
	struct scsi_inquiry	*cdb = (struct scsi_inquiry *)xs->cmd;
	struct scsi_inquiry_data inq;

	DNPRINTF(SR_D_DIS, "%s: sr_raid_inquiry\n", DEVNAME(sd->sd_sc));

	if (xs->cmdlen != sizeof(*cdb))
		return (EINVAL);

	if (ISSET(cdb->flags, SI_EVPD))
		return (EOPNOTSUPP);

	bzero(&inq, sizeof(inq));
	inq.device = T_DIRECT;
	inq.dev_qual2 = 0;
	inq.version = 2;
	inq.response_format = 2;
	inq.additional_length = 32;
	inq.flags |= SID_CmdQue;
	strlcpy(inq.vendor, sd->sd_meta->ssdi.ssd_vendor,
	    sizeof(inq.vendor));
	strlcpy(inq.product, sd->sd_meta->ssdi.ssd_product,
	    sizeof(inq.product));
	strlcpy(inq.revision, sd->sd_meta->ssdi.ssd_revision,
	    sizeof(inq.revision));
	sr_copy_internal_data(xs, &inq, sizeof(inq));

	return (0);
}

int
sr_raid_read_cap(struct sr_workunit *wu)
{
	struct sr_discipline	*sd = wu->swu_dis;
	struct scsi_xfer	*xs = wu->swu_xs;
	struct scsi_read_cap_data rcd;
	struct scsi_read_cap_data_16 rcd16;
	daddr_t			addr;
	int			rv = 1;

	DNPRINTF(SR_D_DIS, "%s: sr_raid_read_cap\n", DEVNAME(sd->sd_sc));

	addr = sd->sd_meta->ssdi.ssd_size - 1;
	if (xs->cmd->opcode == READ_CAPACITY) {
		bzero(&rcd, sizeof(rcd));
		if (addr > 0xffffffffllu)
			_lto4b(0xffffffff, rcd.addr);
		else
			_lto4b(addr, rcd.addr);
		_lto4b(512, rcd.length);
		sr_copy_internal_data(xs, &rcd, sizeof(rcd));
		rv = 0;
	} else if (xs->cmd->opcode == READ_CAPACITY_16) {
		bzero(&rcd16, sizeof(rcd16));
		_lto8b(addr, rcd16.addr);
		_lto4b(512, rcd16.length);
		sr_copy_internal_data(xs, &rcd16, sizeof(rcd16));
		rv = 0;
	}

	return (rv);
}

int
sr_raid_tur(struct sr_workunit *wu)
{
	struct sr_discipline	*sd = wu->swu_dis;

	DNPRINTF(SR_D_DIS, "%s: sr_raid_tur\n", DEVNAME(sd->sd_sc));

	if (sd->sd_vol_status == BIOC_SVOFFLINE) {
		sd->sd_scsi_sense.error_code = SSD_ERRCODE_CURRENT;
		sd->sd_scsi_sense.flags = SKEY_NOT_READY;
		sd->sd_scsi_sense.add_sense_code = 0x04;
		sd->sd_scsi_sense.add_sense_code_qual = 0x11;
		sd->sd_scsi_sense.extra_len = 4;
		return (1);
	} else if (sd->sd_vol_status == BIOC_SVINVALID) {
		sd->sd_scsi_sense.error_code = SSD_ERRCODE_CURRENT;
		sd->sd_scsi_sense.flags = SKEY_HARDWARE_ERROR;
		sd->sd_scsi_sense.add_sense_code = 0x05;
		sd->sd_scsi_sense.add_sense_code_qual = 0x00;
		sd->sd_scsi_sense.extra_len = 4;
		return (1);
	}

	return (0);
}

int
sr_raid_request_sense(struct sr_workunit *wu)
{
	struct sr_discipline	*sd = wu->swu_dis;
	struct scsi_xfer	*xs = wu->swu_xs;

	DNPRINTF(SR_D_DIS, "%s: sr_raid_request_sense\n",
	    DEVNAME(sd->sd_sc));

	/* use latest sense data */
	bcopy(&sd->sd_scsi_sense, &xs->sense, sizeof(xs->sense));

	/* clear sense data */
	bzero(&sd->sd_scsi_sense, sizeof(sd->sd_scsi_sense));

	return (0);
}

int
sr_raid_start_stop(struct sr_workunit *wu)
{
	struct scsi_xfer	*xs = wu->swu_xs;
	struct scsi_start_stop	*ss = (struct scsi_start_stop *)xs->cmd;

	DNPRINTF(SR_D_DIS, "%s: sr_raid_start_stop\n",
	    DEVNAME(wu->swu_dis->sd_sc));

	if (!ss)
		return (1);

	/*
	 * do nothing!
	 * a softraid discipline should always reflect correct status
	 */
	return (0);
}

int
sr_raid_sync(struct sr_workunit *wu)
{
	struct sr_discipline	*sd = wu->swu_dis;
	int			s, rv = 0, ios;

	DNPRINTF(SR_D_DIS, "%s: sr_raid_sync\n", DEVNAME(sd->sd_sc));

	/* when doing a fake sync don't count the wu */
	ios = (wu->swu_flags & SR_WUF_FAKE) ? 0 : 1;

	s = splbio();
	sd->sd_sync = 1;
	while (sd->sd_wu_pending > ios) {
		if (tsleep(sd, PRIBIO, "sr_sync", 15 * hz) == EWOULDBLOCK) {
			DNPRINTF(SR_D_DIS, "%s: sr_raid_sync timeout\n",
			    DEVNAME(sd->sd_sc));
			rv = 1;
			break;
		}
	}
	sd->sd_sync = 0;
	splx(s);

	wakeup(&sd->sd_sync);

	return (rv);
}

void
sr_raid_intr(struct buf *bp)
{
	struct sr_ccb		*ccb = (struct sr_ccb *)bp;
	struct sr_workunit	*wu = ccb->ccb_wu;
#ifdef SR_DEBUG
	struct sr_discipline	*sd = wu->swu_dis;
	struct scsi_xfer	*xs = wu->swu_xs;
#endif
	int			s;

	DNPRINTF(SR_D_INTR, "%s: %s %s intr bp %p xs %p\n",
	    DEVNAME(sd->sd_sc), sd->sd_meta->ssd_devname, sd->sd_name, bp, xs);

	s = splbio();
	sr_ccb_done(ccb);
	sr_wu_done(wu);
	splx(s);
}

void
sr_schedule_wu(struct sr_workunit *wu)
{
	struct sr_discipline	*sd = wu->swu_dis;
	struct sr_workunit	*wup;
	int			s;

	DNPRINTF(SR_D_WU, "sr_schedule_wu: schedule wu %p state %i "
	    "flags 0x%x\n", wu, wu->swu_state, wu->swu_flags);

	KASSERT(wu->swu_io_count > 0);

	s = splbio();

	/* Construct the work unit, do not schedule it. */
	if (wu->swu_state == SR_WU_CONSTRUCT)
		goto queued;

	/* Deferred work unit being reconstructed, do not start. */
	if (wu->swu_state == SR_WU_REQUEUE)
		goto queued;

	/* Current work unit failed, restart. */
	if (wu->swu_state == SR_WU_RESTART)
		goto start;

	if (wu->swu_state != SR_WU_INPROGRESS)
		panic("sr_schedule_wu: work unit not in progress (state %i)\n",
		    wu->swu_state);

	/* Walk queue backwards and fill in collider if we have one. */
	TAILQ_FOREACH_REVERSE(wup, &sd->sd_wu_pendq, sr_wu_list, swu_link) {
		if (wu->swu_blk_end < wup->swu_blk_start ||
		    wup->swu_blk_end < wu->swu_blk_start)
			continue;

		/* Defer work unit due to LBA collision. */
		DNPRINTF(SR_D_WU, "sr_schedule_wu: deferring work unit %p\n",
		    wu);
		wu->swu_state = SR_WU_DEFERRED;
		while (wup->swu_collider)
			wup = wup->swu_collider;
		wup->swu_collider = wu;
		TAILQ_INSERT_TAIL(&sd->sd_wu_defq, wu, swu_link);
		sd->sd_wu_collisions++;
		goto queued;
	}

start:
	sr_raid_startwu(wu);

queued:
	splx(s);
}

void
sr_raid_startwu(struct sr_workunit *wu)
{
	struct sr_discipline	*sd = wu->swu_dis;
	struct sr_ccb		*ccb;

	DNPRINTF(SR_D_WU, "sr_raid_startwu: start wu %p\n", wu);

	splassert(IPL_BIO);

	if (wu->swu_state == SR_WU_DEFERRED) {
		TAILQ_REMOVE(&sd->sd_wu_defq, wu, swu_link);
		wu->swu_state = SR_WU_INPROGRESS;
	}

	if (wu->swu_state != SR_WU_RESTART)
		TAILQ_INSERT_TAIL(&sd->sd_wu_pendq, wu, swu_link);

	/* Start all of the individual I/Os. */
	if (wu->swu_cb_active == 1)
		panic("%s: sr_startwu_callback", DEVNAME(sd->sd_sc));
	wu->swu_cb_active = 1;

	TAILQ_FOREACH(ccb, &wu->swu_ccb, ccb_link)
		VOP_STRATEGY(&ccb->ccb_buf);

	wu->swu_cb_active = 0;
}

void
sr_raid_recreate_wu(struct sr_workunit *wu)
{
	struct sr_discipline	*sd = wu->swu_dis;
	struct sr_workunit	*wup = wu;

	/*
	 * Recreate a work unit by releasing the associated CCBs and reissuing
	 * the SCSI I/O request. This process is then repeated for all of the
	 * colliding work units.
	 */
	do {
		sr_wu_release_ccbs(wup);

		wup->swu_state = SR_WU_REQUEUE;
		if (sd->sd_scsi_rw(wup))
			panic("could not requeue I/O");

		wup = wup->swu_collider;
	} while (wup);
}

int
sr_alloc_resources(struct sr_discipline *sd)
{
	if (sr_wu_alloc(sd, sizeof(struct sr_workunit))) {
		sr_error(sd->sd_sc, "unable to allocate work units");
		return (ENOMEM);
	}
	if (sr_ccb_alloc(sd)) {
		sr_error(sd->sd_sc, "unable to allocate ccbs");
		return (ENOMEM);
	}

	return (0);
}

void
sr_free_resources(struct sr_discipline *sd)
{
	sr_wu_free(sd);
	sr_ccb_free(sd);
}

void
sr_set_chunk_state(struct sr_discipline *sd, int c, int new_state)
{
	int			old_state, s;

	DNPRINTF(SR_D_STATE, "%s: %s: %s: sr_set_chunk_state %d -> %d\n",
	    DEVNAME(sd->sd_sc), sd->sd_meta->ssd_devname,
	    sd->sd_vol.sv_chunks[c]->src_meta.scmi.scm_devname, c, new_state);

	/* ok to go to splbio since this only happens in error path */
	s = splbio();
	old_state = sd->sd_vol.sv_chunks[c]->src_meta.scm_status;

	/* multiple IOs to the same chunk that fail will come through here */
	if (old_state == new_state)
		goto done;

	switch (old_state) {
	case BIOC_SDONLINE:
		if (new_state == BIOC_SDOFFLINE)
			break;
		else
			goto die;
		break;

	case BIOC_SDOFFLINE:
		goto die;

	default:
die:
		splx(s); /* XXX */
		panic("%s: %s: %s: invalid chunk state transition "
		    "%d -> %d\n", DEVNAME(sd->sd_sc),
		    sd->sd_meta->ssd_devname,
		    sd->sd_vol.sv_chunks[c]->src_meta.scmi.scm_devname,
		    old_state, new_state);
		/* NOTREACHED */
	}

	sd->sd_vol.sv_chunks[c]->src_meta.scm_status = new_state;
	sd->sd_set_vol_state(sd);

	sd->sd_must_flush = 1;
	task_add(systq, &sd->sd_meta_save_task);
done:
	splx(s);
}

void
sr_set_vol_state(struct sr_discipline *sd)
{
	int			states[SR_MAX_STATES];
	int			new_state, i, s, nd;
	int			old_state = sd->sd_vol_status;

	DNPRINTF(SR_D_STATE, "%s: %s: sr_set_vol_state\n",
	    DEVNAME(sd->sd_sc), sd->sd_meta->ssd_devname);

	nd = sd->sd_meta->ssdi.ssd_chunk_no;

	for (i = 0; i < SR_MAX_STATES; i++)
		states[i] = 0;

	for (i = 0; i < nd; i++) {
		s = sd->sd_vol.sv_chunks[i]->src_meta.scm_status;
		if (s >= SR_MAX_STATES)
			panic("%s: %s: %s: invalid chunk state",
			    DEVNAME(sd->sd_sc),
			    sd->sd_meta->ssd_devname,
			    sd->sd_vol.sv_chunks[i]->src_meta.scmi.scm_devname);
		states[s]++;
	}

	if (states[BIOC_SDONLINE] == nd)
		new_state = BIOC_SVONLINE;
	else 
		new_state = BIOC_SVOFFLINE;

	DNPRINTF(SR_D_STATE, "%s: %s: sr_set_vol_state %d -> %d\n",
	    DEVNAME(sd->sd_sc), sd->sd_meta->ssd_devname,
	    old_state, new_state);

	switch (old_state) {
	case BIOC_SVONLINE:
		if (new_state == BIOC_SVOFFLINE || new_state == BIOC_SVONLINE)
			break;
		else
			goto die;
		break;

	case BIOC_SVOFFLINE:
		/* XXX this might be a little too much */
		goto die;

	default:
die:
		panic("%s: %s: invalid volume state transition "
		    "%d -> %d\n", DEVNAME(sd->sd_sc),
		    sd->sd_meta->ssd_devname,
		    old_state, new_state);
		/* NOTREACHED */
	}

	sd->sd_vol_status = new_state;
}

void *
sr_block_get(struct sr_discipline *sd, int length)
{
	return dma_alloc(length, PR_NOWAIT | PR_ZERO);
}

void
sr_block_put(struct sr_discipline *sd, void *ptr, int length)
{
	dma_free(ptr, length);
}

void
sr_checksum_print(u_int8_t *md5)
{
	int			i;

	for (i = 0; i < MD5_DIGEST_LENGTH; i++)
		printf("%02x", md5[i]);
}

void
sr_checksum(struct sr_softc *sc, void *src, void *md5, u_int32_t len)
{
	MD5_CTX			ctx;

	DNPRINTF(SR_D_MISC, "%s: sr_checksum(%p %p %d)\n", DEVNAME(sc), src,
	    md5, len);

	MD5Init(&ctx);
	MD5Update(&ctx, src, len);
	MD5Final(md5, &ctx);
}

void
sr_uuid_generate(struct sr_uuid *uuid)
{
	arc4random_buf(uuid->sui_id, sizeof(uuid->sui_id));
	/* UUID version 4: random */
	uuid->sui_id[6] &= 0x0f;
	uuid->sui_id[6] |= 0x40;
	/* RFC4122 variant */
	uuid->sui_id[8] &= 0x3f;
	uuid->sui_id[8] |= 0x80;
}

char *
sr_uuid_format(struct sr_uuid *uuid)
{
	char *uuidstr;

	uuidstr = malloc(37, M_DEVBUF, M_WAITOK);

	snprintf(uuidstr, 37,
	    "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-"
	    "%02x%02x%02x%02x%02x%02x",
	    uuid->sui_id[0], uuid->sui_id[1],
	    uuid->sui_id[2], uuid->sui_id[3],
	    uuid->sui_id[4], uuid->sui_id[5],
	    uuid->sui_id[6], uuid->sui_id[7],
	    uuid->sui_id[8], uuid->sui_id[9],
	    uuid->sui_id[10], uuid->sui_id[11],
	    uuid->sui_id[12], uuid->sui_id[13],
	    uuid->sui_id[14], uuid->sui_id[15]);

	return uuidstr;
}

void
sr_uuid_print(struct sr_uuid *uuid, int cr)
{
	char *uuidstr;

	uuidstr = sr_uuid_format(uuid);
	printf("%s%s", uuidstr, (cr ? "\n" : ""));
	free(uuidstr, M_DEVBUF);
}

int
sr_already_assembled(struct sr_discipline *sd)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct sr_discipline	*sdtmp;

	TAILQ_FOREACH(sdtmp, &sc->sc_dis_list, sd_link) {
		if (!bcmp(&sd->sd_meta->ssdi.ssd_uuid,
		    &sdtmp->sd_meta->ssdi.ssd_uuid,
		    sizeof(sd->sd_meta->ssdi.ssd_uuid)))
			return (1);
	}

	return (0);
}

int32_t
sr_validate_stripsize(u_int32_t b)
{
	int			s = 0;

	if (b % 512)
		return (-1);

	while ((b & 1) == 0) {
		b >>= 1;
		s++;
	}

	/* only multiple of twos */
	b >>= 1;
	if (b)
		return(-1);

	return (s);
}

void
sr_shutdownhook(void *arg)
{
	sr_shutdown((struct sr_softc *)arg);
}

void
sr_shutdown(struct sr_softc *sc)
{
	struct sr_discipline	*sd;

	DNPRINTF(SR_D_MISC, "%s: sr_shutdown\n", DEVNAME(sc));

	/* Shutdown disciplines in reverse attach order. */
	while ((sd = TAILQ_LAST(&sc->sc_dis_list, sr_discipline_list)) != NULL)
		sr_discipline_shutdown(sd, 1);
}

int
sr_validate_io(struct sr_workunit *wu, daddr_t *blk, char *func)
{
	struct sr_discipline	*sd = wu->swu_dis;
	struct scsi_xfer	*xs = wu->swu_xs;
	int			rv = 1;

	DNPRINTF(SR_D_DIS, "%s: %s 0x%02x\n", DEVNAME(sd->sd_sc), func,
	    xs->cmd->opcode);

	if (sd->sd_meta->ssd_data_offset == 0)
		panic("invalid data offset");

	if (sd->sd_vol_status == BIOC_SVOFFLINE) {
		DNPRINTF(SR_D_DIS, "%s: %s device offline\n",
		    DEVNAME(sd->sd_sc), func);
		goto bad;
	}

	if (xs->datalen == 0) {
		printf("%s: %s: illegal block count for %s\n",
		    DEVNAME(sd->sd_sc), func, sd->sd_meta->ssd_devname);
		goto bad;
	}

	if (xs->cmdlen == 10)
		*blk = _4btol(((struct scsi_rw_big *)xs->cmd)->addr);
	else if (xs->cmdlen == 16)
		*blk = _8btol(((struct scsi_rw_16 *)xs->cmd)->addr);
	else if (xs->cmdlen == 6)
		*blk = _3btol(((struct scsi_rw *)xs->cmd)->addr);
	else {
		printf("%s: %s: illegal cmdlen for %s\n",
		    DEVNAME(sd->sd_sc), func, sd->sd_meta->ssd_devname);
		goto bad;
	}

	wu->swu_blk_start = *blk;
	wu->swu_blk_end = *blk + (xs->datalen >> DEV_BSHIFT) - 1;

	if (wu->swu_blk_end > sd->sd_meta->ssdi.ssd_size) {
		DNPRINTF(SR_D_DIS, "%s: %s out of bounds start: %lld "
		    "end: %lld length: %d\n",
		    DEVNAME(sd->sd_sc), func, (long long)wu->swu_blk_start,
		    (long long)wu->swu_blk_end, xs->datalen);

		sd->sd_scsi_sense.error_code = SSD_ERRCODE_CURRENT |
		    SSD_ERRCODE_VALID;
		sd->sd_scsi_sense.flags = SKEY_ILLEGAL_REQUEST;
		sd->sd_scsi_sense.add_sense_code = 0x21;
		sd->sd_scsi_sense.add_sense_code_qual = 0x00;
		sd->sd_scsi_sense.extra_len = 4;
		goto bad;
	}

	rv = 0;
bad:
	return (rv);
}

void
sr_rebuild_start(void *arg)
{
	struct sr_discipline	*sd = arg;
	struct sr_softc		*sc = sd->sd_sc;

	DNPRINTF(SR_D_REBUILD, "%s: %s starting rebuild thread\n",
	    DEVNAME(sd->sd_sc), sd->sd_meta->ssd_devname);

	if (kthread_create(sr_rebuild_thread, sd, &sd->sd_background_proc,
	    DEVNAME(sc)) != 0)
		printf("%s: unable to start background operation\n",
		    DEVNAME(sc));
}

void
sr_rebuild_thread(void *arg)
{
	struct sr_discipline	*sd = arg;

	DNPRINTF(SR_D_REBUILD, "%s: %s rebuild thread started\n",
	    DEVNAME(sd->sd_sc), sd->sd_meta->ssd_devname);

	sd->sd_reb_active = 1;
	sd->sd_rebuild(sd);
	sd->sd_reb_active = 0;

	kthread_exit(0);
}

void
sr_rebuild(struct sr_discipline *sd)
{
	struct sr_softc		*sc = sd->sd_sc;
	daddr_t			whole_blk, partial_blk, blk, sz, lba;
	daddr_t			psz, rb, restart;
	struct sr_workunit	*wu_r, *wu_w;
	struct scsi_xfer	xs_r, xs_w;
	struct scsi_rw_16	*cr, *cw;
	int			c, s, slept, percent = 0, old_percent = -1;
	u_int8_t		*buf;

	whole_blk = sd->sd_meta->ssdi.ssd_size / SR_REBUILD_IO_SIZE;
	partial_blk = sd->sd_meta->ssdi.ssd_size % SR_REBUILD_IO_SIZE;

	restart = sd->sd_meta->ssd_rebuild / SR_REBUILD_IO_SIZE;
	if (restart > whole_blk) {
		printf("%s: bogus rebuild restart offset, starting from 0\n",
		    DEVNAME(sc));
		restart = 0;
	}
	if (restart) {
		/*
		 * XXX there is a hole here; there is a posibility that we
		 * had a restart however the chunk that was supposed to
		 * be rebuilt is no longer valid; we can reach this situation
		 * when a rebuild is in progress and the box crashes and
		 * on reboot the rebuild chunk is different (like zero'd or
		 * replaced).  We need to check the uuid of the chunk that is
		 * being rebuilt to assert this.
		 */
		psz = sd->sd_meta->ssdi.ssd_size;
		rb = sd->sd_meta->ssd_rebuild;
		if (rb > 0)
			percent = 100 - ((psz * 100 - rb * 100) / psz) - 1;
		else
			percent = 0;
		printf("%s: resuming rebuild on %s at %d%%\n",
		    DEVNAME(sc), sd->sd_meta->ssd_devname, percent);
	}

	/* currently this is 64k therefore we can use dma_alloc */
	buf = dma_alloc(SR_REBUILD_IO_SIZE << DEV_BSHIFT, PR_WAITOK);
	for (blk = restart; blk <= whole_blk; blk++) {
		lba = blk * SR_REBUILD_IO_SIZE;
		sz = SR_REBUILD_IO_SIZE;
		if (blk == whole_blk) {
			if (partial_blk == 0)
				break;
			sz = partial_blk;
		}

		/* get some wu */
		wu_r = sr_scsi_wu_get(sd, 0);
		wu_w = sr_scsi_wu_get(sd, 0);

		DNPRINTF(SR_D_REBUILD, "%s: %s rebuild wu_r %p, wu_w %p\n",
		    DEVNAME(sd->sd_sc), sd->sd_meta->ssd_devname, wu_r, wu_w);

		/* setup read io */
		bzero(&xs_r, sizeof xs_r);
		xs_r.error = XS_NOERROR;
		xs_r.flags = SCSI_DATA_IN;
		xs_r.datalen = sz << DEV_BSHIFT;
		xs_r.data = buf;
		xs_r.cmdlen = sizeof(*cr);
		xs_r.cmd = &xs_r.cmdstore;
		cr = (struct scsi_rw_16 *)xs_r.cmd;
		cr->opcode = READ_16;
		_lto4b(sz, cr->length);
		_lto8b(lba, cr->addr);
		wu_r->swu_state = SR_WU_CONSTRUCT;
		wu_r->swu_flags |= SR_WUF_REBUILD;
		wu_r->swu_xs = &xs_r;
		if (sd->sd_scsi_rw(wu_r)) {
			printf("%s: could not create read io\n",
			    DEVNAME(sc));
			goto fail;
		}

		/* setup write io */
		bzero(&xs_w, sizeof xs_w);
		xs_w.error = XS_NOERROR;
		xs_w.flags = SCSI_DATA_OUT;
		xs_w.datalen = sz << DEV_BSHIFT;
		xs_w.data = buf;
		xs_w.cmdlen = sizeof(*cw);
		xs_w.cmd = &xs_w.cmdstore;
		cw = (struct scsi_rw_16 *)xs_w.cmd;
		cw->opcode = WRITE_16;
		_lto4b(sz, cw->length);
		_lto8b(lba, cw->addr);
		wu_w->swu_state = SR_WU_CONSTRUCT;
		wu_w->swu_flags |= SR_WUF_REBUILD | SR_WUF_WAKEUP;
		wu_w->swu_xs = &xs_w;
		if (sd->sd_scsi_rw(wu_w)) {
			printf("%s: could not create write io\n",
			    DEVNAME(sc));
			goto fail;
		}

		/*
		 * collide with the read io so that we get automatically
		 * started when the read is done
		 */
		wu_w->swu_state = SR_WU_DEFERRED;
		wu_r->swu_collider = wu_w;
		s = splbio();
		TAILQ_INSERT_TAIL(&sd->sd_wu_defq, wu_w, swu_link);
		splx(s);

		DNPRINTF(SR_D_REBUILD, "%s: %s rebuild scheduling wu_r %p\n",
		    DEVNAME(sd->sd_sc), sd->sd_meta->ssd_devname, wu_r);

		wu_r->swu_state = SR_WU_INPROGRESS;
		sr_schedule_wu(wu_r);

		/* wait for write completion */
		slept = 0;
		while ((wu_w->swu_flags & SR_WUF_REBUILDIOCOMP) == 0) {
			tsleep(wu_w, PRIBIO, "sr_rebuild", 0);
			slept = 1;
		}
		/* yield if we didn't sleep */
		if (slept == 0)
			tsleep(sc, PWAIT, "sr_yield", 1);

		sr_scsi_wu_put(sd, wu_r);
		sr_scsi_wu_put(sd, wu_w);

		sd->sd_meta->ssd_rebuild = lba;

		/* XXX - this should be based on size, not percentage. */
		/* save metadata every percent */
		psz = sd->sd_meta->ssdi.ssd_size;
		rb = sd->sd_meta->ssd_rebuild;
		if (rb > 0)
			percent = 100 - ((psz * 100 - rb * 100) / psz) - 1;
		else
			percent = 0;
		if (percent != old_percent && blk != whole_blk) {
			if (sr_meta_save(sd, SR_META_DIRTY))
				printf("%s: could not save metadata to %s\n",
				    DEVNAME(sc), sd->sd_meta->ssd_devname);
			old_percent = percent;
		}

		if (sd->sd_reb_abort)
			goto abort;
	}

	/* all done */
	sd->sd_meta->ssd_rebuild = 0;
	for (c = 0; c < sd->sd_meta->ssdi.ssd_chunk_no; c++) {
		if (sd->sd_vol.sv_chunks[c]->src_meta.scm_status ==
		    BIOC_SDREBUILD) {
			sd->sd_set_chunk_state(sd, c, BIOC_SDONLINE);
			break;
		}
	}

abort:
	if (sr_meta_save(sd, SR_META_DIRTY))
		printf("%s: could not save metadata to %s\n",
		    DEVNAME(sc), sd->sd_meta->ssd_devname);
fail:
	dma_free(buf, SR_REBUILD_IO_SIZE << DEV_BSHIFT);
}

#ifndef SMALL_KERNEL
int
sr_sensors_create(struct sr_discipline *sd)
{
	struct sr_softc		*sc = sd->sd_sc;
	int			rv = 1;

	DNPRINTF(SR_D_STATE, "%s: %s: sr_sensors_create\n",
	    DEVNAME(sc), sd->sd_meta->ssd_devname);

	sd->sd_vol.sv_sensor.type = SENSOR_DRIVE;
	sd->sd_vol.sv_sensor.status = SENSOR_S_UNKNOWN;
	strlcpy(sd->sd_vol.sv_sensor.desc, sd->sd_meta->ssd_devname,
	    sizeof(sd->sd_vol.sv_sensor.desc));

	sensor_attach(&sc->sc_sensordev, &sd->sd_vol.sv_sensor);
	sd->sd_vol.sv_sensor_attached = 1;

	if (sc->sc_sensor_task == NULL) {
		sc->sc_sensor_task = sensor_task_register(sc,
		    sr_sensors_refresh, 10);
		if (sc->sc_sensor_task == NULL)
			goto bad;
	}

	rv = 0;
bad:
	return (rv);
}

void
sr_sensors_delete(struct sr_discipline *sd)
{
	DNPRINTF(SR_D_STATE, "%s: sr_sensors_delete\n", DEVNAME(sd->sd_sc));

	if (sd->sd_vol.sv_sensor_attached)
		sensor_detach(&sd->sd_sc->sc_sensordev, &sd->sd_vol.sv_sensor);
}

void
sr_sensors_refresh(void *arg)
{
	struct sr_softc		*sc = arg;
	struct sr_volume	*sv;
	struct sr_discipline	*sd;

	DNPRINTF(SR_D_STATE, "%s: sr_sensors_refresh\n", DEVNAME(sc));

	TAILQ_FOREACH(sd, &sc->sc_dis_list, sd_link) {
		sv = &sd->sd_vol;

		switch(sd->sd_vol_status) {
		case BIOC_SVOFFLINE:
			sv->sv_sensor.value = SENSOR_DRIVE_FAIL;
			sv->sv_sensor.status = SENSOR_S_CRIT;
			break;

		case BIOC_SVDEGRADED:
			sv->sv_sensor.value = SENSOR_DRIVE_PFAIL;
			sv->sv_sensor.status = SENSOR_S_WARN;
			break;

		case BIOC_SVSCRUB:
		case BIOC_SVONLINE:
			sv->sv_sensor.value = SENSOR_DRIVE_ONLINE;
			sv->sv_sensor.status = SENSOR_S_OK;
			break;

		default:
			sv->sv_sensor.value = 0; /* unknown */
			sv->sv_sensor.status = SENSOR_S_UNKNOWN;
		}
	}
}
#endif /* SMALL_KERNEL */

#ifdef SR_FANCY_STATS
void				sr_print_stats(void);

void
sr_print_stats(void)
{
	struct sr_softc		*sc = softraid0;
	struct sr_discipline	*sd;

	if (sc == NULL) {
		printf("no softraid softc found\n");
		return;
	}

	TAILQ_FOREACH(sd, &sc->sc_dis_list, sd_link) {
		printf("%s: ios pending %d, collisions %llu\n",
		    sd->sd_meta->ssd_devname,
		    sd->sd_wu_pending,
		    sd->sd_wu_collisions);
	}
}
#endif /* SR_FANCY_STATS */

#ifdef SR_DEBUG
void
sr_meta_print(struct sr_metadata *m)
{
	int			i;
	struct sr_meta_chunk	*mc;
	struct sr_meta_opt_hdr	*omh;

	if (!(sr_debug & SR_D_META))
		return;

	printf("\tssd_magic 0x%llx\n", m->ssdi.ssd_magic);
	printf("\tssd_version %d\n", m->ssdi.ssd_version);
	printf("\tssd_vol_flags 0x%x\n", m->ssdi.ssd_vol_flags);
	printf("\tssd_uuid ");
	sr_uuid_print(&m->ssdi.ssd_uuid, 1);
	printf("\tssd_chunk_no %d\n", m->ssdi.ssd_chunk_no);
	printf("\tssd_chunk_id %d\n", m->ssdi.ssd_chunk_id);
	printf("\tssd_opt_no %d\n", m->ssdi.ssd_opt_no);
	printf("\tssd_volid %d\n", m->ssdi.ssd_volid);
	printf("\tssd_level %d\n", m->ssdi.ssd_level);
	printf("\tssd_size %lld\n", m->ssdi.ssd_size);
	printf("\tssd_devname %s\n", m->ssd_devname);
	printf("\tssd_vendor %s\n", m->ssdi.ssd_vendor);
	printf("\tssd_product %s\n", m->ssdi.ssd_product);
	printf("\tssd_revision %s\n", m->ssdi.ssd_revision);
	printf("\tssd_strip_size %d\n", m->ssdi.ssd_strip_size);
	printf("\tssd_checksum ");
	sr_checksum_print(m->ssd_checksum);
	printf("\n");
	printf("\tssd_meta_flags 0x%x\n", m->ssd_meta_flags);
	printf("\tssd_ondisk %llu\n", m->ssd_ondisk);

	mc = (struct sr_meta_chunk *)(m + 1);
	for (i = 0; i < m->ssdi.ssd_chunk_no; i++, mc++) {
		printf("\t\tscm_volid %d\n", mc->scmi.scm_volid);
		printf("\t\tscm_chunk_id %d\n", mc->scmi.scm_chunk_id);
		printf("\t\tscm_devname %s\n", mc->scmi.scm_devname);
		printf("\t\tscm_size %lld\n", mc->scmi.scm_size);
		printf("\t\tscm_coerced_size %lld\n",mc->scmi.scm_coerced_size);
		printf("\t\tscm_uuid ");
		sr_uuid_print(&mc->scmi.scm_uuid, 1);
		printf("\t\tscm_checksum ");
		sr_checksum_print(mc->scm_checksum);
		printf("\n");
		printf("\t\tscm_status %d\n", mc->scm_status);
	}

	omh = (struct sr_meta_opt_hdr *)((u_int8_t *)(m + 1) +
	    sizeof(struct sr_meta_chunk) * m->ssdi.ssd_chunk_no);
	for (i = 0; i < m->ssdi.ssd_opt_no; i++) {
		printf("\t\t\tsom_type %d\n", omh->som_type);
		printf("\t\t\tsom_checksum ");
		sr_checksum_print(omh->som_checksum);
		printf("\n");
		omh = (struct sr_meta_opt_hdr *)((void *)omh +
		    omh->som_length);
	}
}

void
sr_dump_block(void *blk, int len)
{
	uint8_t			*b = blk;
	int			i, j, c;

	for (i = 0; i < len; i += 16) {
		for (j = 0; j < 16; j++)
			printf("%.2x ", b[i + j]);
		printf("  ");
		for (j = 0; j < 16; j++) {
			c = b[i + j];
			if (c < ' ' || c > 'z' || i + j > len)
				c = '.';
			printf("%c", c);
		}
		printf("\n");
	}
}

void
sr_dump_mem(u_int8_t *p, int len)
{
	int			i;

	for (i = 0; i < len; i++)
		printf("%02x ", *p++);
	printf("\n");
}

#endif /* SR_DEBUG */