summaryrefslogtreecommitdiff
path: root/sys/dev/softraid.c
blob: 9fdccfdb417a9f80bc115340c80d442b62b23205 (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
/* $OpenBSD: softraid.c,v 1.259 2011/12/25 15:28:17 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/mount.h>
#include <sys/sensors.h>
#include <sys/stat.h>
#include <sys/conf.h>
#include <sys/uio.h>
#include <sys/workq.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 */
		;
#endif

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

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_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);
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);

/* utility functions */
void			sr_shutdown(struct sr_softc *);
void			sr_shutdownhook(void *);
void			sr_uuid_get(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 *);
void			sr_map_root(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(void *);
void			sr_rebuild_thread(void *);
void			sr_roam_chunks(struct sr_discipline *);
int			sr_chunk_in_use(struct sr_softc *, dev_t);
void			sr_startwu_callback(void *, void *);
int			sr_rw(struct sr_softc *, dev_t, char *, size_t,
			    daddr64_t, long);

/* 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, daddr64_t, long);
int			sr_meta_clear(struct sr_discipline *);
void			sr_meta_chunks_create(struct sr_softc *,
			    struct sr_chunk_head *);
void			sr_meta_init(struct sr_discipline *,
			    struct sr_chunk_head *);
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 {
	daddr64_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) {
		printf("%s: could not allocate memory for metadata\n",
		    DEVNAME(sc));
		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 */
			printf("%s: could not allocate memory for foreign "
			    "metadata\n", DEVNAME(sc));
			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)) {
				printf("%s:, sr_meta_probe: can't allocate "
				    "vnode\n", DEVNAME(sc));
				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, daddr64_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, %d, %llu 0x%x)\n",
	    DEVNAME(sc), dev, buf, size, 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,
    daddr64_t offset, long flags)
{
	int			rv = 1;

	DNPRINTF(SR_D_META, "%s: sr_meta_rw(0x%x, %p, %d, %llu 0x%x)\n",
	    DEVNAME(sd->sd_sc), dev, md, size, 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) {
		printf("%s: sr_meta_clear can not clear foreign metadata\n",
		    DEVNAME(sc));
		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_chunks_create(struct sr_softc *sc, struct sr_chunk_head *cl)
{
	struct sr_chunk		*ch_entry;
	struct sr_uuid		uuid;
	int			cid = 0;
	char			*name;
	u_int64_t		max_chunk_sz = 0, min_chunk_sz;

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

	sr_uuid_get(&uuid);

	/* fill out stuff and get largest chunk size while looping */
	SLIST_FOREACH(ch_entry, cl, src_link) {
		name = ch_entry->src_devname;
		ch_entry->src_meta.scmi.scm_size = ch_entry->src_size;
		ch_entry->src_meta.scmi.scm_chunk_id = cid++;
		ch_entry->src_meta.scm_status = BIOC_SDONLINE;
		strlcpy(ch_entry->src_meta.scmi.scm_devname, name,
		    sizeof(ch_entry->src_meta.scmi.scm_devname));
		bcopy(&uuid, &ch_entry->src_meta.scmi.scm_uuid,
		    sizeof(ch_entry->src_meta.scmi.scm_uuid));

		if (ch_entry->src_meta.scmi.scm_size > max_chunk_sz)
			max_chunk_sz = ch_entry->src_meta.scmi.scm_size;
	}

	/* get smallest chunk size */
	min_chunk_sz = max_chunk_sz;
	SLIST_FOREACH(ch_entry, cl, src_link)
		if (ch_entry->src_meta.scmi.scm_size < min_chunk_sz)
			min_chunk_sz = ch_entry->src_meta.scmi.scm_size;

	/* equalize all sizes */
	SLIST_FOREACH(ch_entry, cl, src_link)
		ch_entry->src_meta.scmi.scm_coerced_size = min_chunk_sz;

	/* whine if chunks are not the same size */
	if (min_chunk_sz != max_chunk_sz)
		printf("%s: chunk sizes are not equal; up to %llu blocks "
		    "wasted per chunk\n",
		    DEVNAME(sc), max_chunk_sz - min_chunk_sz);
}

void
sr_meta_init(struct sr_discipline *sd, struct sr_chunk_head *cl)
{
	struct sr_softc		*sc = sd->sd_sc;
	struct sr_metadata	*sm = sd->sd_meta;
	struct sr_meta_chunk	*im_sc;
	int			i, chunk_no;

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

	if (!sm)
		return;

	/* initial metadata */
	sm->ssdi.ssd_magic = SR_MAGIC;
	sm->ssdi.ssd_version = SR_META_VERSION;
	sm->ssd_ondisk = 0;
	sm->ssdi.ssd_vol_flags = sd->sd_meta_flags;
	sm->ssd_data_offset = SR_DATA_OFFSET;

	/* get uuid from chunk 0 */
	bcopy(&sd->sd_vol.sv_chunks[0]->src_meta.scmi.scm_uuid,
	    &sm->ssdi.ssd_uuid,
	    sizeof(struct sr_uuid));

	/* volume is filled in createraid */

	/* add missing chunk bits */
	chunk_no = sm->ssdi.ssd_chunk_no;
	for (i = 0; i < chunk_no; i++) {
		im_sc = &sd->sd_vol.sv_chunks[i]->src_meta;
		im_sc->scmi.scm_volid = sm->ssdi.ssd_volid;
		sr_checksum(sc, im_sc, &im_sc->scm_checksum,
		    sizeof(struct sr_meta_chunk_invariant));
	}
}

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_fake = 1;
		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)) {
			printf("%s: invalid foreign metadata\n", DEVNAME(sc));
			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) {
		printf("%s: not valid softraid metadata\n", DEVNAME(sc));
		goto done;
	}

	/* Verify metadata checksum. */
	sr_checksum(sc, sm, &checksum, sizeof(struct sr_meta_invariant));
	if (bcmp(&checksum, &sm->ssd_checksum, sizeof(checksum))) {
		printf("%s: invalid metadata checksum\n", DEVNAME(sc));
		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 {

		printf("%s: %s can not read metadata version %u, expected %u\n",
		    DEVNAME(sc), devname, sm->ssdi.ssd_version,
		    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)) {
		printf("%s:, sr_meta_native_bootprobe: can't allocate vnode\n",
		    DEVNAME(sc));
		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);

	md = malloc(SR_META_SIZE * 512, M_DEVBUF, M_ZERO | M_NOWAIT);
	if (md == NULL) {
		printf("%s: not enough memory for metadata buffer\n",
		    DEVNAME(sc));
		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) {
		printf("%s: not enough memory for fake discipline\n",
		    DEVNAME(sc));
		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)) {
			printf("%s:, sr_meta_native_bootprobe: can't allocate "
			    "vnode for partition\n", DEVNAME(sc));
			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)) {
			printf("%s: native bootprobe could not read native "
			    "metadata\n", DEVNAME(sc));
			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) {
			if (md->ssdi.ssd_vol_flags & BIOC_SCNOAUTOASSEMBLE) {
				DNPRINTF(SR_D_META, "%s: don't save %s\n",
				    DEVNAME(sc), devname);
			} else {
				/* XXX fix M_WAITOK, this is boot time */
				bc = malloc(sizeof(*bc), M_DEVBUF,
				    M_WAITOK | M_ZERO);
				bcopy(md, &bc->sbc_metadata,
				    sizeof(bc->sbc_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;
	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 = 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 */
		sr_meta_native_bootprobe(sc, dk->dk_devno, &bch);

		/* 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;
			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_dev_no++;
	}

	/* 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(&bc, sizeof(bc));

		/* 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 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_dev_no--;
				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_dev_no) {
			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;

		rw_enter_write(&sc->sc_lock);
		sr_ioctl_createraid(sc, &bcr, 0);
		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);
			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);
		free(bc1, M_DEVBUF);
	}
	/* Free unallocated chunks. */
	for (bc1 = SLIST_FIRST(&bch); bc1 != SLIST_END(&bch); bc1 = bc2) {
		bc2 = SLIST_NEXT(bc1, sbc_link);
		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(struct sr_softc *sc)
{
	struct sr_meta_opt_item	*omi;
	struct sr_meta_boot	*sbm;
	u_char			duid[8];
	int			i, j;

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

	for (i = 0; i < SR_MAX_LD; i++) {
		if (sc->sc_dis[i] == NULL)
			continue;
		SLIST_FOREACH(omi, &sc->sc_dis[i]->sd_meta_opt, omi_link) {
			if (omi->omi_som->som_type != SR_OPT_BOOT)
				continue;
			sbm = (struct sr_meta_boot *)omi->omi_som;
			for (j = 0; j < SR_MAX_BOOT_DISKS; j++) {
				if (bcmp(rootduid, sbm->sbm_boot_duid[j],
				    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;
	daddr64_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 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_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 %d\n", DEVNAME(sc),
	    devname, 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) {
		printf("%s: not enough memory for metadata buffer\n",
		    DEVNAME(sc));
		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)) {
			printf("%s: could not read native metadata\n",
			    DEVNAME(sc));
			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)) {
				printf("%s: not part of the same volume\n",
				    DEVNAME(sc));
				goto bad;
			}
			if (md->ssd_ondisk != version) {
				old_meta++;
				version = MAX(md->ssd_ondisk, version);
			}
		} else
			not_sr++;
	}

	if (sr && not_sr) {
		printf("%s: not all chunks are of the native metadata format\n",
		    DEVNAME(sc));
		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))
				printf("%s: could not read native metadata\n",
				    DEVNAME(sc));
			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));

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

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

#if NBIO > 0
	if (bio_register(&sc->sc_dev, sr_ioctl) != 0)
		printf("%s: controller registration failed", DEVNAME(sc));
	else
		sc->sc_ioctl = sr_ioctl;
#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);

	sr_map_root(sc);
}

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);

	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 (rv);
}

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: %d\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);
}

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

	if (!sd)
		return (1);

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

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

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

	sd->sd_wu = malloc(sizeof(struct sr_workunit) * no_wu,
	    M_DEVBUF, M_WAITOK | M_ZERO);
	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 = &sd->sd_wu[i];
		wu->swu_dis = sd;
		sr_wu_put(sd, wu);
	}

	return (0);
}

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

	if (!sd)
		return;

	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);

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

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

	int			s;

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

	s = splbio();
	if (wu->swu_cb_active == 1)
		panic("%s: sr_wu_put got active wu", DEVNAME(sd->sd_sc));
	while ((ccb = TAILQ_FIRST(&wu->swu_ccb)) != NULL) {
		TAILQ_REMOVE(&wu->swu_ccb, ccb, ccb_link);
		sr_ccb_put(ccb);
	}
	splx(s);

	bzero(wu, sizeof(*wu));
	TAILQ_INIT(&wu->swu_ccb);
	wu->swu_dis = sd;

	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_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_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);

	scsi_done(xs);
}

void
sr_scsi_cmd(struct scsi_xfer *xs)
{
	int			s;
	struct scsi_link	*link = xs->sc_link;
	struct sr_softc		*sc = link->adapter_softc;
	struct sr_workunit	*wu = NULL;
	struct sr_discipline	*sd;
	struct sr_ccb		*ccb;

	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_dis[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;
	}

	wu = xs->io;
	/* scsi layer *can* re-send wu without calling sr_wu_put(). */
	s = splbio();
	if (wu->swu_cb_active == 1)
		panic("%s: sr_scsi_cmd got active wu", DEVNAME(sd->sd_sc));
	while ((ccb = TAILQ_FIRST(&wu->swu_ccb)) != NULL) {
		TAILQ_REMOVE(&wu->swu_ccb, ccb, ccb_link);
		sr_ccb_put(ccb);
	}
	splx(s);

	bzero(wu, sizeof(*wu));
	TAILQ_INIT(&wu->swu_ccb);
	wu->swu_state = SR_WU_INPROGRESS;
	wu->swu_dis = sd;
	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_dis[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);

	switch (cmd) {
	case DIOCGCACHE:
	case DIOCSCACHE:
		return (EOPNOTSUPP);
	default:
		return (sr_ioctl(link->adapter_softc, cmd, addr));
	}
}

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

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

	rw_enter_write(&sc->sc_lock);

	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);
		break;

	case BIOCDELETERAID:
		rv = sr_ioctl_deleteraid(sc, (struct bioc_deleteraid *)addr);
		break;

	case BIOCDISCIPLINE:
		rv = sr_ioctl_discipline(sc, (struct bioc_discipline *)addr);
		break;

	case BIOCINSTALLBOOT:
		rv = sr_ioctl_installboot(sc, (struct bioc_installboot *)addr);
		break;

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

	rw_exit_write(&sc->sc_lock);

	return (rv);
}

int
sr_ioctl_inq(struct sr_softc *sc, struct bioc_inq *bi)
{
	int			i, vol, disk;

	for (i = 0, vol = 0, disk = 0; i < SR_MAX_LD; i++)
		/* XXX this will not work when we stagger disciplines */
		if (sc->sc_dis[i]) {
			vol++;
			disk += sc->sc_dis[i]->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			i, vol, rv = EINVAL;
	struct sr_discipline	*sd;
	struct sr_chunk		*hotspare;
	daddr64_t		rb, sz;

	for (i = 0, vol = -1; i < SR_MAX_LD; i++) {
		/* XXX this will not work when we stagger disciplines */
		if (sc->sc_dis[i])
			vol++;
		if (vol != bv->bv_volid)
			continue;

		if (sc->sc_dis[i] == NULL)
			goto done;

		sd = sc->sc_dis[i];
		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)
{
	int			i, vol, rv = EINVAL, id;
	struct sr_chunk		*src, *hotspare;

	for (i = 0, vol = -1; i < SR_MAX_LD; i++) {
		/* XXX this will not work when we stagger disciplines */
		if (sc->sc_dis[i])
			vol++;
		if (vol != bd->bd_volid)
			continue;

		if (sc->sc_dis[i] == NULL)
			goto done;

		id = bd->bd_diskid;

		if (id < sc->sc_dis[i]->sd_meta->ssdi.ssd_chunk_no)
			src = sc->sc_dis[i]->sd_vol.sv_chunks[id];
#ifdef CRYPTO
		else if (id == sc->sc_dis[i]->sd_meta->ssdi.ssd_chunk_no &&
		    sc->sc_dis[i]->sd_meta->ssdi.ssd_level == 'C' &&
		    sc->sc_dis[i]->mds.mdd_crypto.key_disk != NULL)
			src = sc->sc_dis[i]->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 = id;
		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			i, vol, found, c;
	struct sr_discipline	*sd = NULL;
	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;
	}

	for (i = 0, vol = -1; i < SR_MAX_LD; i++) {
		/* XXX this will not work when we stagger disciplines */
		if (sc->sc_dis[i])
			vol++;
		if (vol != bs->bs_volid)
			continue;
		sd = sc->sc_dis[i];
		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) {
			printf("%s: chunk not part of array\n", DEVNAME(sc));
			goto done;
		}

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

		if (sr_meta_save(sd, SR_META_DIRTY)) {
			printf("%s: could not save metadata to %s\n",
			    DEVNAME(sc), 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:
		printf("%s: unsupported state request %d\n",
		    DEVNAME(sc), 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, c;

	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. */
	for (i = 0; i < SR_MAX_LD; i++) {
		if (sc->sc_dis[i] == NULL)
			continue;
		sd = sc->sc_dis[i];
		for (c = 0; c < sd->sd_meta->ssdi.ssd_chunk_no; c++) {
			chunk = sd->sd_vol.sv_chunks[c];
			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;
	daddr64_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)
			printf("%s: %s is already a hotspare\n",
			    DEVNAME(sc), devname);
		else
			printf("%s: %s is already in use\n",
			    DEVNAME(sc), devname);
		goto done;
	}

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

	/* Open device. */
	if (bdevvp(dev, &vn)) {
		printf("%s:, sr_hotspare: can't allocate vnode\n", DEVNAME(sc));
		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_partitions[part].p_fstype != FS_RAID) {
		printf("%s: %s partition not of type RAID (%d)\n",
		    DEVNAME(sc), devname,
		    label.d_partitions[part].p_fstype);
		goto fail;
	}

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

	/*
	 * Create and populate chunk metadata.
	 */

	sr_uuid_get(&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)) {
		printf("%s: could not save metadata to %s\n",
		    DEVNAME(sc), 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_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(sd->sd_sc), sd->sd_meta->ssd_devname);
		return;
	}

	/* See if we have a suitable hotspare... */
	rw_enter_write(&sd->sd_sc->sc_hs_lock);
	cl = &sd->sd_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(sd->sd_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(sd->sd_sc),
		    i, chunk->src_devname);

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

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

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

		}
		rw_exit_write(&sd->sd_sc->sc_lock);
		splx(s);
	}
done:
	rw_exit_write(&sd->sd_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;
	daddr64_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)) {
		printf("%s: discipline does not support rebuild\n",
		    DEVNAME(sc));
		goto done;
	}

	/* make sure volume is in the right state */
	if (sd->sd_vol_status == BIOC_SVREBUILD) {
		printf("%s: rebuild already in progress\n", DEVNAME(sc));
		goto done;
	}
	if (sd->sd_vol_status != BIOC_SVDEGRADED) {
		printf("%s: %s not degraded\n", DEVNAME(sc),
		    sd->sd_meta->ssd_devname);
		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) {
		printf("%s: no offline chunks available for rebuild\n",
		    DEVNAME(sc));
		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_partitions[part].p_fstype != FS_RAID) {
		printf("%s: %s partition not of type RAID (%d)\n",
		    DEVNAME(sc), devname,
		    label.d_partitions[part].p_fstype);
		goto done;
	}

	/* Is the partition large enough? */
	size = DL_GETPSIZE(&label.d_partitions[part]) - SR_DATA_OFFSET;
	if (size < csize) {
		printf("%s: partition too small, at least %llu B required\n",
		    DEVNAME(sc), csize << DEV_BSHIFT);
		goto done;
	} else if (size > csize)
		printf("%s: partition too large, wasting %llu B\n",
		    DEVNAME(sc), (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)) {
		printf("%s: %s is already in use\n", DEVNAME(sc), 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)) {
		printf("%s: could not save metadata to %s\n",
		    DEVNAME(sc), devname);
		open = 1;
		goto done;
	}

	printf("%s: rebuild of %s started on %s\n", DEVNAME(sc),
	    sd->sd_meta->ssd_devname, devname);

	sd->sd_reb_abort = 0;
	kthread_create_deferred(sr_rebuild, 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)
{
	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			devname[32];
	dev_t			*dt;
	int			i, no_chunk, rv = EINVAL, target, vol;
	int			no_meta, updatemeta = 0;

	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_workq = workq_create("srdis", 1, IPL_BIO);
	if (sd->sd_workq == NULL) {
		printf("%s: could not create workq\n", DEVNAME(sc));
		goto unwind;
	}
	if (sr_discipline_init(sd, bc->bc_level)) {
		printf("%s: could not initialize discipline\n", DEVNAME(sc));
		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));
			printf("%s: chunk %s already in use\n",
			    DEVNAME(sc), devname);
			goto unwind;
		}
	}

	sd->sd_meta_type = sr_meta_probe(sd, dt, no_chunk);
	if (sd->sd_meta_type == SR_META_F_INVALID) {
		printf("%s: invalid metadata format\n", DEVNAME(sc));
		goto unwind;
	}

	if (sr_meta_attach(sd, no_chunk, bc->bc_flags & BIOC_SCFORCE)) {
		printf("%s: can't attach metadata type %d\n", DEVNAME(sc),
		    sd->sd_meta_type);
		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)) {
				printf("%s: disk ", DEVNAME(sc));
				sr_uuid_print(&sd->sd_meta->ssdi.ssd_uuid, 0);
				printf(" is currently in use; can't force "
				    "create\n");
				goto unwind;
			}

		if (sr_meta_clear(sd)) {
			printf("%s: failed to clear metadata\n", DEVNAME(sc));
			goto unwind;
		}
	}

	no_meta = sr_meta_read(sd);
	if (no_meta == -1) {
		printf("%s: one of the chunks has corrupt metadata; aborting "
		    "assembly\n", DEVNAME(sc));
		goto unwind;
	} else if (no_meta == 0) {
		/* fill out all chunk metadata */
		sr_meta_chunks_create(sc, cl);
		ch_entry = SLIST_FIRST(cl);

		sd->sd_vol_status = BIOC_SVONLINE;
		sd->sd_meta->ssdi.ssd_level = bc->bc_level;
		sd->sd_meta->ssdi.ssd_chunk_no = no_chunk;

		/* Make the volume UUID available. */
		bcopy(&ch_entry->src_meta.scmi.scm_uuid,
		    &sd->sd_meta->ssdi.ssd_uuid,
		    sizeof(sd->sd_meta->ssdi.ssd_uuid));

		if (sd->sd_create) {
			if ((i = sd->sd_create(sd, bc, no_chunk,
			    ch_entry->src_meta.scmi.scm_coerced_size))) {
				rv = i;
				goto unwind;
			}
		}

		/* fill out all volume metadata */
		DNPRINTF(SR_D_IOCTL,
		    "%s: sr_ioctl_createraid: vol_size: %lld\n",
		    DEVNAME(sc), sd->sd_meta->ssdi.ssd_size);
		strlcpy(sd->sd_meta->ssdi.ssd_vendor, "OPENBSD",
		    sizeof(sd->sd_meta->ssdi.ssd_vendor));
		snprintf(sd->sd_meta->ssdi.ssd_product,
		    sizeof(sd->sd_meta->ssdi.ssd_product), "SR %s",
		    sd->sd_name);
		snprintf(sd->sd_meta->ssdi.ssd_revision,
		    sizeof(sd->sd_meta->ssdi.ssd_revision), "%03d",
		    SR_META_VERSION);

		sd->sd_meta_flags = bc->bc_flags & BIOC_SCNOAUTOASSEMBLE;
		updatemeta = 1;
	} else {
		if (no_meta != no_chunk)
			printf("%s: trying to bring up %s degraded\n",
			    DEVNAME(sc), sd->sd_meta->ssd_devname);

		if (sd->sd_meta->ssd_meta_flags & SR_META_DIRTY)
			printf("%s: %s was not shutdown properly\n",
			    DEVNAME(sc), sd->sd_meta->ssd_devname);

		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 (sr_already_assembled(sd)) {
			printf("%s: disk ", DEVNAME(sc));
			sr_uuid_print(&sd->sd_meta->ssdi.ssd_uuid, 0);
			printf(" already assembled\n");
			goto unwind;
		}

		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))) {
				rv = i;
				goto unwind;
			}
		}

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

	/* metadata SHALL be fully filled in at this point */

	/* Make sure that metadata level matches assembly level. */
	if (sd->sd_meta->ssdi.ssd_level != bc->bc_level) {
		printf("%s: volume level does not match metadata level!\n",
		    DEVNAME(sc));
		goto unwind;
	}

	/* 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) {
		/* set volume status */
		sd->sd_set_vol_state(sd);
		if (sd->sd_vol_status == BIOC_SVOFFLINE) {
			printf("%s: %s offline, will not be brought online\n",
			    DEVNAME(sc), sd->sd_meta->ssd_devname);
			goto unwind;
		}

		/* setup scsi iopool */
		mtx_init(&sd->sd_wu_mtx, IPL_BIO);
		scsi_iopool_init(&sd->sd_iopool, sd, sr_wu_get, sr_wu_put);

		/*
		 * we passed all checks return ENXIO if volume can't be created
		 */
		rv = ENXIO;

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

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

		/* attach disclipline and kick midlayer to probe it */
		sd->sd_target = target;
		sc->sc_dis[target] = sd;
		if (scsi_probe_lun(sc->sc_scsibus, target, 0) != 0) {
			printf("%s: scsi_probe_lun failed\n", DEVNAME(sc));
			sc->sc_dis[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);

		for (i = 0, vol = -1; i <= sd->sd_target; i++)
			if (sc->sc_dis[i])
				vol++;

		rv = 0;
		if (updatemeta) {
			/* fill out 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_meta_init(sd, cl);
		} else {
			if (strncmp(sd->sd_meta->ssd_devname, dev->dv_xname,
			    sizeof(dev->dv_xname))) {
				printf("%s: volume %s is roaming, it used to "
				    "be %s, updating metadata\n",
				    DEVNAME(sc), dev->dv_xname,
				    sd->sd_meta->ssd_devname);

				sd->sd_meta->ssdi.ssd_volid = vol;
				strlcpy(sd->sd_meta->ssd_devname, dev->dv_xname,
				    sizeof(sd->sd_meta->ssd_devname));
			}
		}

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

#ifndef SMALL_KERNEL
		if (sr_sensors_create(sd))
			printf("%s: unable to create sensor for %s\n",
			    DEVNAME(sc), dev->dv_xname);
#endif /* SMALL_KERNEL */
	} else {
		/* we are not an os disk */
		if (updatemeta) {
			/* fill out remaining volume metadata */
			sd->sd_meta->ssdi.ssd_volid = 0;
			strlcpy(sd->sd_meta->ssd_devname, ch_entry->src_devname,
			    sizeof(sd->sd_meta->ssd_devname));
			sr_meta_init(sd, cl);
		}
		if (sd->sd_start_discipline(sd))
			goto unwind;
	}

	/* save metadata to disk */
	rv = sr_meta_save(sd, SR_META_DIRTY);

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

	sd->sd_ready = 1;

	return (rv);
unwind:
	sr_discipline_shutdown(sd, 0);

	/* XXX - use internal status values! */
	if (rv == EAGAIN)
		rv = 0;

	return (rv);
}

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

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

	for (i = 0; i < SR_MAX_LD; i++)
		if (sc->sc_dis[i]) {
			if (!strncmp(sc->sc_dis[i]->sd_meta->ssd_devname,
			    dr->bd_dev,
			    sizeof(sc->sc_dis[i]->sd_meta->ssd_devname))) {
				sd = sc->sc_dis[i];
				break;
			}
		}

	if (sd == NULL)
		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 = NULL;
	int			i, rv = 1;

	/* Dispatch a discipline specific ioctl. */

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

	for (i = 0; i < SR_MAX_LD; i++)
		if (sc->sc_dis[i]) {
			if (!strncmp(sc->sc_dis[i]->sd_meta->ssd_devname,
			    bd->bd_dev,
			    sizeof(sc->sc_dis[i]->sd_meta->ssd_devname))) {
				sd = sc->sc_dis[i];
				break;
			}
		}

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

	return (rv);
}

int
sr_ioctl_installboot(struct sr_softc *sc, struct bioc_installboot *bb)
{
	void			*bootblk = NULL, *bootldr = NULL;
	struct sr_discipline	*sd = NULL;
	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);

	for (i = 0; i < SR_MAX_LD; i++)
		if (sc->sc_dis[i]) {
			if (!strncmp(sc->sc_dis[i]->sd_meta->ssd_devname,
			    bb->bb_dev,
			    sizeof(sc->sc_dis[i]->sd_meta->ssd_devname))) {
				sd = sc->sc_dis[i];
				break;
			}
		}

	if (sd == NULL)
		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 ||
	    bcmp(dk->dk_label->d_uid, &duid, sizeof(duid)) == 0) {
		printf("%s: failed to get DUID for softraid volume!\n",
		    DEVNAME(sd->sd_sc));
		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)) {
		printf("%s: insufficient boot storage!\n", DEVNAME(sd->sd_sc));
		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)) {
			printf("%s: failed to write boot block\n", 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)) {
			printf("%s: failed to write boot loader\n",
			   DEVNAME(sc));
			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)) {
		printf("%s: could not save metadata to %s\n",
		    DEVNAME(sc), 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_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_dis[sd->sd_target] == sd);
		sc->sc_dis[sd->sd_target] = NULL;
	}

	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_workq)
		workq_destroy(sd->sd_workq);

	if (sd)
		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 = NULL;
	sd->sd_assemble = NULL;
	sd->sd_create = NULL;
	sd->sd_free_resources = NULL;
	sd->sd_ioctl_handler = NULL;
	sd->sd_openings = NULL;
	sd->sd_meta_opt_handler = NULL;
	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_set_chunk_state = NULL;
	sd->sd_set_vol_state = NULL;
	sd->sd_start_discipline = NULL;

	switch (level) {
	case 0:
		sr_raid0_discipline_init(sd);
		break;
	case 1:
		sr_raid1_discipline_init(sd);
		break;
	case 4:
		sr_raidp_discipline_init(sd, SR_MD_RAID4);
		break;
	case 5:
		sr_raidp_discipline_init(sd, SR_MD_RAID5);
		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
	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;
	daddr64_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_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_startwu_callback(void *arg1, void *arg2)
{
	struct sr_discipline	*sd = arg1;
	struct sr_workunit	*wu = arg2;
	struct sr_ccb		*ccb;
	int			s;

	s = splbio();
	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;
	splx(s);
}

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

	splassert(IPL_BIO);

	if (wu->swu_state == SR_WU_RESTART)
		/*
		 * no need to put the wu on the pending queue since we
		 * are restarting the io
		 */
		 ;
	else
		/* move wu to pending queue */
		TAILQ_INSERT_TAIL(&sd->sd_wu_pendq, wu, swu_link);

	/* start all individual ios */
	workq_queue_task(sd->sd_workq, &wu->swu_wqt, 0, sr_startwu_callback,
	    sd, wu);
}

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_get(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;
}

void
sr_uuid_print(struct sr_uuid *uuid, int cr)
{
	printf("%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]);

	if (cr)
		printf("\n");
}

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

	for (i = 0; i < SR_MAX_LD; i++)
		if (sc->sc_dis[i])
			if (!bcmp(&sd->sd_meta->ssdi.ssd_uuid,
			    &sc->sc_dis[i]->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)
{
	int			i;

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

	/* XXX this will not work when we stagger disciplines */
	for (i = 0; i < SR_MAX_LD; i++)
		if (sc->sc_dis[i])
			sr_discipline_shutdown(sc->sc_dis[i], 1);
}

int
sr_validate_io(struct sr_workunit *wu, daddr64_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, wu->swu_blk_start,
		    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);
}

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

	splassert(IPL_BIO);

	/* 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;

		/* we have an LBA collision, defer wu */
		wu->swu_state = SR_WU_DEFERRED;
		if (wup->swu_collider)
			/* wu is on deferred queue, append to last wu */
			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;
	}

	return (0);
queued:
	return (1);
}

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

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

void
sr_rebuild_thread(void *arg)
{
	struct sr_discipline	*sd = arg;
	struct sr_softc		*sc = sd->sd_sc;
	daddr64_t		whole_blk, partial_blk, blk, sz, lba;
	daddr64_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);
	}

	sd->sd_reb_active = 1;

	/* 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 */
		if ((wu_r = scsi_io_get(&sd->sd_iopool, 0)) == NULL)
			panic("%s: rebuild exhausted wu_r", DEVNAME(sc));
		if ((wu_w = scsi_io_get(&sd->sd_iopool, 0)) == NULL)
			panic("%s: rebuild exhausted wu_w", DEVNAME(sc));

		/* 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_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_flags |= SR_WUF_REBUILD;
		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);

		/* schedule io */
		if (sr_check_io_collision(wu_r))
			goto queued;

		sr_raid_startwu(wu_r);
queued:
		splx(s);

		/* wait for read 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);

		scsi_io_put(&sd->sd_iopool, wu_r);
		scsi_io_put(&sd->sd_iopool, wu_w);

		sd->sd_meta->ssd_rebuild = lba;

		/* 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);
	sd->sd_reb_active = 0;
	kthread_exit(0);
}

#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;
	int			i, vol;

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

	for (i = 0, vol = -1; i < SR_MAX_LD; i++) {
		/* XXX this will not work when we stagger disciplines */
		if (!sc->sc_dis[i])
			continue;

		sd = sc->sc_dis[i];
		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;
	struct sr_discipline	*sd;
	int			i, vol;

	for (i = 0; i < softraid_cd.cd_ndevs; i++)
		if (softraid_cd.cd_devs[i]) {
			sc = softraid_cd.cd_devs[i];
			/* we'll only have one softc */
			break;
		}

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

	for (i = 0, vol = -1; i < SR_MAX_LD; i++) {
		/* XXX this will not work when we stagger disciplines */
		if (!sc->sc_dis[i])
			continue;

		sd = sc->sc_dis[i];
		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_mem(u_int8_t *p, int len)
{
	int			i;

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

#endif /* SR_DEBUG */