summaryrefslogtreecommitdiff
path: root/lib/metadata/raid_manip.c
blob: cdd7af8d6739ae4326bc539e7d86cb64ce12f74c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
/*
 * Copyright (C) 2011-2017 Red Hat, Inc. All rights reserved.
 *
 * This file is part of LVM2.
 *
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU Lesser General Public License v.2.1.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include "lib.h"
#include "archiver.h"
#include "metadata.h"
#include "toolcontext.h"
#include "segtype.h"
#include "display.h"
#include "activate.h"
#include "lv_alloc.h"
#include "lvm-string.h"

static int _check_restriping(uint32_t new_stripes, struct logical_volume *lv)
{
	if (new_stripes && new_stripes != first_seg(lv)->area_count) {
		log_error("Cannot restripe LV %s from %" PRIu32 " to %u stripes during conversion.",
			  display_lvname(lv), first_seg(lv)->area_count, new_stripes);
		return 0;
	}

	return 1;
}

__attribute__ ((__unused__))
/* Check that all lv has segments have exactly the required number of areas */
static int _check_num_areas_in_lv_segments(struct logical_volume *lv, unsigned num_areas)
{
	struct lv_segment *seg;

	dm_list_iterate_items(seg, &lv->segments)
		if (seg->area_count != num_areas) {
			log_error("For this operation LV %s needs exactly %u data areas per segment.",
				  display_lvname(lv), num_areas);
			return 0;
		}

	return 1;
}

/*
 * Ensure region size exceeds the minimum for @lv because
 * MD's bitmap is limited to tracking 2^21 regions.
 *
 * Pass in @lv_size, because funcion can be called with an empty @lv.
 */
uint32_t raid_ensure_min_region_size(const struct logical_volume *lv, uint64_t raid_size, uint32_t region_size)
{
	uint32_t min_region_size = raid_size / (1 << 21);
	uint32_t region_size_sav = region_size;

	while (region_size < min_region_size)
		region_size *= 2;

	if (region_size != region_size_sav)
		log_very_verbose("Adjusting region_size from %s to %s for %s.",
				 display_size(lv->vg->cmd, region_size_sav),
				 display_size(lv->vg->cmd, region_size),
				 display_lvname(lv));
	return region_size;
}

/*
 * Check for maximum number of raid devices.
 * Constrained by kernel MD maximum device limits _and_ dm-raid superblock
 * bitfield constraints.
 */
static int _check_max_raid_devices(uint32_t image_count)
{
	if (image_count > DEFAULT_RAID_MAX_IMAGES) {
		log_error("Unable to handle raid arrays with more than %u devices.",
			  DEFAULT_RAID_MAX_IMAGES);
		return 0;
	}

	return 1;
}

static int _check_max_mirror_devices(uint32_t image_count)
{
	if (image_count > DEFAULT_MIRROR_MAX_IMAGES) {
		log_error("Unable to handle mirrors with more than %u devices.",
			  DEFAULT_MIRROR_MAX_IMAGES);
		return 0;
	}

	return 1;
}

/*
 * Fix up LV region_size if not yet set.
 */
/* FIXME Check this happens exactly once at the right place. */
static void _check_and_adjust_region_size(const struct logical_volume *lv)
{
	struct lv_segment *seg = first_seg(lv);

	seg->region_size = seg->region_size ? : get_default_region_size(lv->vg->cmd);
	seg->region_size = raid_ensure_min_region_size(lv, lv->size, seg->region_size);
}

/* Strip any raid suffix off LV name */
char *top_level_lv_name(struct volume_group *vg, const char *lv_name)
{
	char *new_lv_name, *suffix;

	if (!(new_lv_name = dm_pool_strdup(vg->vgmem, lv_name))) {
		log_error("Failed to allocate string for new LV name.");
		return NULL;
	}
        
	if ((suffix = first_substring(new_lv_name, "_rimage_", "_rmeta_",
						   "_mimage_", "_mlog_", NULL)))
		*suffix = '\0';

	return new_lv_name;
}

static int _lv_is_raid_with_tracking(const struct logical_volume *lv,
				     struct logical_volume **tracking)
{
	uint32_t s;
	const struct lv_segment *seg = first_seg(lv);

	*tracking = NULL;

	if (!lv_is_raid(lv))
		return 0;

	for (s = 0; s < seg->area_count; s++)
		if (lv_is_visible(seg_lv(seg, s)) &&
		    !(seg_lv(seg, s)->status & LVM_WRITE))
			*tracking = seg_lv(seg, s);

	return *tracking ? 1 : 0;
}

int lv_is_raid_with_tracking(const struct logical_volume *lv)
{
	struct logical_volume *tracking;

	return _lv_is_raid_with_tracking(lv, &tracking);
}

uint32_t lv_raid_image_count(const struct logical_volume *lv)
{
	struct lv_segment *seg = first_seg(lv);

	if (!seg_is_raid(seg))
		return 1;

	return seg->area_count;
}

/* HM Helper: prohibit allocation on @pv if @lv already has segments allocated on it */
static int _avoid_pv_of_lv(struct logical_volume *lv, struct physical_volume *pv)
{
	if (!lv_is_partial(lv) && lv_is_on_pv(lv, pv))
		pv->status |= PV_ALLOCATION_PROHIBITED;

	return 1;
}

static int _avoid_pvs_of_lv(struct logical_volume *lv, void *data)
{
	struct dm_list *allocate_pvs = (struct dm_list *) data;
	struct pv_list *pvl;

	dm_list_iterate_items(pvl, allocate_pvs)
		_avoid_pv_of_lv(lv, pvl->pv);

	return 1;
}

/*
 * Prevent any PVs holding other image components of @lv from being used for allocation
 * by setting the internal PV_ALLOCATION_PROHIBITED flag to use it to avoid generating
 * pv maps for those PVs.
 */
static int _avoid_pvs_with_other_images_of_lv(struct logical_volume *lv, struct dm_list *allocate_pvs)
{
	/* HM FIXME: check fails in case we will ever have mixed AREA_PV/AREA_LV segments */
	if ((seg_type(first_seg(lv), 0) == AREA_PV ? _avoid_pvs_of_lv(lv, allocate_pvs):
						     for_each_sub_lv(lv, _avoid_pvs_of_lv, allocate_pvs)))
		return 1;

	log_error("Failed to prevent PVs holding image components "
		  "from LV %s being used for allocation.",
		  display_lvname(lv));
	return 0;
}

static void _clear_allocation_prohibited(struct dm_list *pvs)
{
	struct pv_list *pvl;

	if (pvs)
		dm_list_iterate_items(pvl, pvs)
			pvl->pv->status &= ~PV_ALLOCATION_PROHIBITED;
}

/*
 * Deactivate and remove the LVs on removal_lvs list from vg.
 */
static int _deactivate_and_remove_lvs(struct volume_group *vg, struct dm_list *removal_lvs)
{
	struct lv_list *lvl;

	dm_list_iterate_items(lvl, removal_lvs) {
		if (!deactivate_lv(vg->cmd, lvl->lv))
			return_0;
		if (!lv_remove(lvl->lv))
			return_0;
	}

	return 1;
}

/*
 * _raid_in_sync
 * @lv
 *
 * _raid_in_sync works for all types of RAID segtypes, as well
 * as 'mirror' segtype.  (This is because 'lv_raid_percent' is
 * simply a wrapper around 'lv_mirror_percent'.
 *
 * Returns: 1 if in-sync, 0 otherwise.
 */
#define _RAID_IN_SYNC_RETRIES  6
static int _raid_in_sync(struct logical_volume *lv)
{
	int retries = _RAID_IN_SYNC_RETRIES;
	dm_percent_t sync_percent;

	if (seg_is_striped(first_seg(lv)))
		return 1;

	do {
		/*
		 * FIXME We repeat the status read here to workaround an
		 * unresolved kernel bug when we see 0 even though the
		 * the array is 100% in sync.
		 * https://bugzilla.redhat.com/1210637
		 */
		if (!lv_raid_percent(lv, &sync_percent)) {
			log_error("Unable to determine sync status of %s.",
				  display_lvname(lv));
			return 0;
		}
		if (sync_percent > DM_PERCENT_0)
			break;
		if (retries == _RAID_IN_SYNC_RETRIES)
			log_warn("WARNING: Sync status for %s is inconsistent.",
				 display_lvname(lv));
		usleep(500000);
	} while (--retries);

	return (sync_percent == DM_PERCENT_100) ? 1 : 0;
}

/* Check if RaidLV @lv is synced or any raid legs of @lv are not synced */
static int _raid_devs_sync_healthy(struct logical_volume *lv)
{
	char *raid_health;

	if (!_raid_in_sync(lv))
		return 0;

	if (!seg_is_raid1(first_seg(lv)))
		return 1;

	if (!lv_raid_dev_health(lv, &raid_health))
		return_0;

	return (strchr(raid_health, 'a') || strchr(raid_health, 'D')) ? 0 : 1;
}

/*
 * _raid_remove_top_layer
 * @lv
 * @removal_lvs
 *
 * Remove top layer of RAID LV in order to convert to linear.
 * This function makes no on-disk changes.  The residual LVs
 * returned in 'removal_lvs' must be freed by the caller.
 *
 * Returns: 1 on succes, 0 on failure
 */
static int _raid_remove_top_layer(struct logical_volume *lv,
				  struct dm_list *removal_lvs)
{
	struct lv_list *lvl_array, *lvl;
	struct lv_segment *seg = first_seg(lv);

	if (!seg_is_mirrored(seg)) {
		log_error(INTERNAL_ERROR
			  "Unable to remove RAID layer from segment type %s.",
			  lvseg_name(seg));
		return 0;
	}

	if (seg->area_count != 1) {
		log_error(INTERNAL_ERROR
			  "Unable to remove RAID layer when there is "
			  "more than one sub-lv.");
		return 0;
	}

	if (!(lvl_array = dm_pool_alloc(lv->vg->vgmem, 2 * sizeof(*lvl))))
		return_0;

	/* Add last metadata area to removal_lvs */
	lvl_array[0].lv = seg_metalv(seg, 0);
	lv_set_visible(seg_metalv(seg, 0));
	if (!remove_seg_from_segs_using_this_lv(seg_metalv(seg, 0), seg))
		return_0;
	seg_metatype(seg, 0) = AREA_UNASSIGNED;
	dm_list_add(removal_lvs, &(lvl_array[0].list));

	/* Remove RAID layer and add residual LV to removal_lvs*/
	seg_lv(seg, 0)->status &= ~RAID_IMAGE;
	lv_set_visible(seg_lv(seg, 0));
	lvl_array[1].lv = seg_lv(seg, 0);
	dm_list_add(removal_lvs, &(lvl_array[1].list));

	if (!remove_layer_from_lv(lv, seg_lv(seg, 0)))
		return_0;

	lv->status &= ~(MIRRORED | RAID);

	return 1;
}

/*
 * Assisted excl_local activation of lvl listed LVs before resume
 *
 * FIXME: code which needs to use this function is usually unsafe
 *	  againt crashes as it's doing more then 1 operation per commit
 *	  and as such is currently irreversible on error path.
 *
 * Function is not making backup as this is usually not the last
 * metadata changing operation.
 *
 * Also we should take 'struct lv_list'...
 */
static int _lv_update_and_reload_list(struct logical_volume *lv, int origin_only, struct dm_list *lv_list)
{
	struct volume_group *vg = lv->vg;
	const struct logical_volume *lock_lv = lv_lock_holder(lv);
	struct lv_list *lvl;
	int r;

	log_very_verbose("Updating logical volume %s on disk(s)%s.",
			 display_lvname(lock_lv), origin_only ? " (origin only)": "");

	if (!vg_write(vg))
		return_0;

	if (!(r = (origin_only ? suspend_lv_origin(vg->cmd, lock_lv) : suspend_lv(vg->cmd, lock_lv)))) {
		log_error("Failed to lock logical volume %s.",
			  display_lvname(lock_lv));
		vg_revert(vg);
	} else if (!(r = vg_commit(vg)))
		stack; /* !vg_commit() has implict vg_revert() */

	if (r && lv_list) {
		dm_list_iterate_items(lvl, lv_list) {
			log_very_verbose("Activating logical volume %s before %s in kernel.",
					 display_lvname(lvl->lv), display_lvname(lock_lv));
			if (!activate_lv_excl_local(vg->cmd, lvl->lv)) {
				log_error("Failed to activate %s before resuming %s.",
					  display_lvname(lvl->lv), display_lvname(lock_lv));
				r = 0; /* But lets try with the rest */
			}
		}
	}

	log_very_verbose("Updating logical volume %s in kernel.",
			 display_lvname(lock_lv));

	if (!(origin_only ? resume_lv_origin(vg->cmd, lock_lv) : resume_lv(vg->cmd, lock_lv))) {
		log_error("Problem reactivating logical volume %s.",
			  display_lvname(lock_lv));
		r = 0;
	}

	return r;
}

/* Makes on-disk metadata changes
 * If LV is active:
 *	clear first block of device
 * otherwise:
 *	activate, clear, deactivate
 *
 * Returns: 1 on success, 0 on failure
 */
static int _clear_lvs(struct dm_list *lv_list)
{
	struct lv_list *lvl;
	struct volume_group *vg = NULL;
	unsigned i = 0, sz = dm_list_size(lv_list);
	char *was_active;
	int r = 1;

	if (!sz) {
		log_debug_metadata(INTERNAL_ERROR "Empty list of LVs given for clearing.");
		return 1;
	}

	dm_list_iterate_items(lvl, lv_list) {
		if (!lv_is_visible(lvl->lv)) {
			log_error(INTERNAL_ERROR
				  "LVs must be set visible before clearing.");
			return 0;
		}
		vg = lvl->lv->vg;
	}

	if (test_mode())
		return 1;

	/*
	 * FIXME: only vg_[write|commit] if LVs are not already written
	 * as visible in the LVM metadata (which is never the case yet).
	 */
	if (!vg || !vg_write(vg) || !vg_commit(vg))
		return_0;

	was_active = alloca(sz);

	dm_list_iterate_items(lvl, lv_list)
		if (!(was_active[i++] = lv_is_active_locally(lvl->lv))) {
			lvl->lv->status |= LV_TEMPORARY;
			if (!activate_lv_excl_local(vg->cmd, lvl->lv)) {
				log_error("Failed to activate localy %s for clearing.",
					  display_lvname(lvl->lv));
				r = 0;
				goto out;
			}
			lvl->lv->status &= ~LV_TEMPORARY;
		}

	dm_list_iterate_items(lvl, lv_list) {
		log_verbose("Clearing metadata area %s.", display_lvname(lvl->lv));
		/*
		 * Rather than wiping lv->size, we can simply
		 * wipe the first sector to remove the superblock of any previous
		 * RAID devices.  It is much quicker.
		 */
		if (!wipe_lv(lvl->lv, (struct wipe_params) { .do_zero = 1, .zero_sectors = 1 })) {
			log_error("Failed to zero %s.", display_lvname(lvl->lv));
			r = 0;
			goto out;
		}
	}
out:
	/* TODO:   deactivation is only needed with clustered locking
	 *         in normal case we should keep device active
	 */
	sz = 0;
	dm_list_iterate_items(lvl, lv_list)
		if ((i > sz) && !was_active[sz++] &&
		    !deactivate_lv(vg->cmd, lvl->lv)) {
			log_error("Failed to deactivate %s.", display_lvname(lvl->lv));
			r = 0; /* continue deactivating */
		}

	return r;
}

/* raid0* <-> raid10_near area reorder helper: swap 2 LV segment areas @a1 and @a2 */
static void _swap_areas(struct lv_segment_area *a1, struct lv_segment_area *a2)
{
	struct lv_segment_area tmp;

	tmp = *a1;
	*a1 = *a2;
	*a2 = tmp;
}

/*
 * Reorder the areas in the first segment of @seg to suit raid10_{near,far}/raid0 layout.
 *
 * raid10_{near,far} can only be reordered to raid0 if !mod(#total_devs, #mirrors)
 *
 * Examples with 6 disks indexed 0..5 with 3 stripes:
 * raid0             (012345) -> raid10_{near,far} (031425) order
 * idx                024135
 * raid10_{near,far} (012345) -> raid0  (024135/135024) order depending on mirror leg selection (TBD)
 * idx                031425
 * _or_ (variations possible)
 * idx                304152
 *
 * Examples 3 stripes with 9 disks indexed 0..8 to create a 3 striped raid0 with 3 data_copies per leg:
 *         vvv
 * raid0  (012345678) -> raid10 (034156278) order
 *         v  v  v
 * raid10 (012345678) -> raid0  (036124578) order depending on mirror leg selection (TBD)
 *
 */
enum raid0_raid10_conversion { reorder_to_raid10_near, reorder_from_raid10_near };
static int _reorder_raid10_near_seg_areas(struct lv_segment *seg, enum raid0_raid10_conversion conv)
{
	unsigned dc, idx1, idx1_sav, idx2, s, ss, str, xchg;
	uint32_t data_copies = 2; /* seg->data_copies */
	uint32_t *idx, stripes = seg->area_count;
	unsigned i = 0;

	/* Internal sanity checks... */
	if (!(conv == reorder_to_raid10_near || conv == reorder_from_raid10_near))
		return_0;
	if ((conv == reorder_to_raid10_near && !(seg_is_striped(seg) || seg_is_any_raid0(seg))) ||
	    (conv == reorder_from_raid10_near && !seg_is_raid10_near(seg)))
		return_0;

	/* FIXME: once more data copies supported with raid10 */
	if (seg_is_raid10_near(seg) && (stripes % data_copies)) {
		log_error("Can't convert %s LV %s with number of stripes not divisable by number of data copies",
			  lvseg_name(seg), display_lvname(seg->lv));
		return 0;
	}

	/* FIXME: once more data copies supported with raid10 */
	stripes /= data_copies;

	if (!(idx = dm_pool_zalloc(seg_lv(seg, 0)->vg->vgmem, seg->area_count * sizeof(*idx))))
		return 0;

	/* Set up positional index array */
	switch (conv) {
	case reorder_to_raid10_near:
		/*
		 * raid0  (012 345) with 3 stripes/2 data copies     -> raid10 (031425)
		 *
		 * _reorder_raid10_near_seg_areas 2137 idx[0]=0
		 * _reorder_raid10_near_seg_areas 2137 idx[1]=2
		 * _reorder_raid10_near_seg_areas 2137 idx[2]=4
		 * _reorder_raid10_near_seg_areas 2137 idx[3]=1
		 * _reorder_raid10_near_seg_areas 2137 idx[4]=3
		 * _reorder_raid10_near_seg_areas 2137 idx[5]=5
		 *
		 * raid0  (012 345 678) with 3 stripes/3 data copies -> raid10 (036147258)
		 *
		 * _reorder_raid10_near_seg_areas 2137 idx[0]=0
		 * _reorder_raid10_near_seg_areas 2137 idx[1]=3
		 * _reorder_raid10_near_seg_areas 2137 idx[2]=6
		 *
		 * _reorder_raid10_near_seg_areas 2137 idx[3]=1
		 * _reorder_raid10_near_seg_areas 2137 idx[4]=4
		 * _reorder_raid10_near_seg_areas 2137 idx[5]=7
		 * _reorder_raid10_near_seg_areas 2137 idx[6]=2
		 * _reorder_raid10_near_seg_areas 2137 idx[7]=5
		 * _reorder_raid10_near_seg_areas 2137 idx[8]=8
		 */
		/* idx[from] = to */
		for (s = ss = 0; s < seg->area_count; s++)
			if (s < stripes)
				idx[s] = s * data_copies;

			else {
				uint32_t factor = s % stripes;

				if (!factor)
					ss++;

				idx[s] = ss + factor * data_copies;
			}

		break;

	case reorder_from_raid10_near:
		/*
		 * Order depending on mirror leg selection (TBD)
		 *
		 * raid10 (012345) with 3 stripes/2 data copies    -> raid0  (024135/135024)
		 * raid10 (012345678) with 3 stripes/3 data copies -> raid0  (036147258/147036258/...)
		 */
		/* idx[from] = to */
		for (s = 0; s < seg->area_count; s++)
			idx[s] = -1; /* = unused */

		idx1 = 0;
		idx2 = stripes;
		for (str = 0; str < stripes; str++) {
			idx1_sav = idx1;
			for (dc = 0; dc < data_copies; dc++) {
				struct logical_volume *slv;
				s = str * data_copies + dc;
				slv = seg_lv(seg, s);
				idx[s] = ((slv->status & PARTIAL_LV) || idx1 != idx1_sav) ? idx2++ : idx1++;
			}

			if (idx1 == idx1_sav) {
				log_error("Failed to find a valid mirror in stripe %u!", str);
				return 0;
			}
		}

		break;

	default:
		return 0;
	}

	/* Sort areas */
	do {
		xchg = seg->area_count;

		for (s = 0; s < seg->area_count ; s++)
			if (idx[s] == s)
				xchg--;

			else {
				_swap_areas(seg->areas + s, seg->areas + idx[s]);
				_swap_areas(seg->meta_areas + s, seg->meta_areas + idx[s]);
				ss = idx[idx[s]];
				idx[idx[s]] = idx[s];
				idx[s] = ss;
			}
		i++;
	} while (xchg);

	return 1;
}

/*
 * _shift_and_rename_image_components
 * @seg: Top-level RAID segment
 *
 * Shift all higher indexed segment areas down to fill in gaps where
 * there are 'AREA_UNASSIGNED' areas and rename data/metadata LVs so
 * that their names match their new index.  When finished, set
 * seg->area_count to new reduced total.
 *
 * Returns: 1 on success, 0 on failure
 */
static int _shift_and_rename_image_components(struct lv_segment *seg)
{
	int len;
	char *shift_name;
	uint32_t s, missing;
	struct cmd_context *cmd = seg->lv->vg->cmd;

	/*
	 * All LVs must be properly named for their index before
	 * shifting begins.  (e.g.  Index '0' must contain *_rimage_0 and
	 * *_rmeta_0.  Index 'n' must contain *_rimage_n and *_rmeta_n.)
	 */

	if (!seg_is_raid(seg))
		return_0;

	if (seg->area_count > 10) {
		/*
		 * FIXME: Handling more would mean I'd have
		 * to handle double digits
		 */
		log_error("Unable handle arrays with more than 10 devices.");
		return 0;
	}

	log_very_verbose("Shifting images in %s.", display_lvname(seg->lv));

	for (s = 0, missing = 0; s < seg->area_count; s++) {
		if (seg_type(seg, s) == AREA_UNASSIGNED) {
			if (seg_metatype(seg, s) != AREA_UNASSIGNED) {
				log_error(INTERNAL_ERROR "Metadata segment area"
					  " #%d should be AREA_UNASSIGNED.", s);
				return 0;
			}
			missing++;
			continue;
		}
		if (!missing)
			continue;

		log_very_verbose("Shifting %s and %s by %u.",
				 display_lvname(seg_metalv(seg, s)),
				 display_lvname(seg_lv(seg, s)), missing);

		/* Alter rmeta name */
		shift_name = dm_pool_strdup(cmd->mem, seg_metalv(seg, s)->name);
		if (!shift_name) {
			log_error("Memory allocation failed.");
			return 0;
		}
		len = strlen(shift_name) - 1;
		shift_name[len] -= missing;
		seg_metalv(seg, s)->name = shift_name;

		/* Alter rimage name */
		shift_name = dm_pool_strdup(cmd->mem, seg_lv(seg, s)->name);
		if (!shift_name) {
			log_error("Memory allocation failed.");
			return 0;
		}
		len = strlen(shift_name) - 1;
		shift_name[len] -= missing;
		seg_lv(seg, s)->name = shift_name;

		seg->areas[s - missing] = seg->areas[s];
		seg->meta_areas[s - missing] = seg->meta_areas[s];
	}

	seg->area_count -= missing;
	return 1;
}

/* Generate raid subvolume name and validate it */
static char *_generate_raid_name(struct logical_volume *lv,
				 const char *suffix, int count)
{
	const char *format = (count >= 0) ? "%s_%s_%u" : "%s_%s";
	char name[NAME_LEN], *lvname;
	int historical;

	if (dm_snprintf(name, sizeof(name), format, lv->name, suffix, count) < 0) {
		log_error("Failed to new raid name for %s.",
			  display_lvname(lv));
		return NULL;
	}

	if (!validate_name(name)) {
		log_error("New logical volume name \"%s\" is not valid.", name);
		return NULL;
	}

	if (lv_name_is_used_in_vg(lv->vg, name, &historical)) {
		log_error("%sLogical Volume %s already exists in volume group %s.",
			  historical ? "historical " : "", name, lv->vg->name);
		return NULL;
	}

	if (!(lvname = dm_pool_strdup(lv->vg->vgmem, name))) {
		log_error("Failed to allocate new name.");
		return NULL;
	}

	return lvname;
}
/*
 * Create an LV of specified type.  Set visible after creation.
 * This function does not make metadata changes.
 */
static struct logical_volume *_alloc_image_component(struct logical_volume *lv,
						     const char *alt_base_name,
						     struct alloc_handle *ah, uint32_t first_area,
						     uint64_t type)
{
	uint64_t status;
	char img_name[NAME_LEN];
	const char *type_suffix;
	struct logical_volume *tmp_lv;
	const struct segment_type *segtype;

	switch (type) {
	case RAID_META:
		type_suffix = "rmeta";
		break;
	case RAID_IMAGE:
		type_suffix = "rimage";
		break;
	default:
		log_error(INTERNAL_ERROR
			  "Bad type provided to _alloc_raid_component.");
		return 0;
	}

	if (dm_snprintf(img_name, sizeof(img_name), "%s_%s_%%d",
			(alt_base_name) ? : lv->name, type_suffix) < 0) {
		log_error("Component name for raid %s is too long.", display_lvname(lv));
		return 0;
	}

	status = LVM_READ | LVM_WRITE | LV_REBUILD | type;
	if (!(tmp_lv = lv_create_empty(img_name, NULL, status, ALLOC_INHERIT, lv->vg))) {
		log_error("Failed to allocate new raid component, %s.", img_name);
		return 0;
	}

	if (ah) {
		if (!(segtype = get_segtype_from_string(lv->vg->cmd, SEG_TYPE_NAME_STRIPED)))
			return_0;

		if (!lv_add_segment(ah, first_area, 1, tmp_lv, segtype, 0, status, 0)) {
			log_error("Failed to add segment to LV, %s.", img_name);
			return 0;
		}
	}

	lv_set_visible(tmp_lv);

	return tmp_lv;
}

static int _alloc_image_components(struct logical_volume *lv,
				   struct dm_list *pvs, uint32_t count,
				   struct dm_list *new_meta_lvs,
				   struct dm_list *new_data_lvs, int use_existing_area_len)
{
	uint32_t s;
	uint32_t region_size;
	uint32_t extents;
	struct lv_segment *seg = first_seg(lv);
	const struct segment_type *segtype;
	struct alloc_handle *ah = NULL;
	struct dm_list *parallel_areas;
	struct lv_list *lvl_array;

	if (!(lvl_array = dm_pool_alloc(lv->vg->vgmem,
					sizeof(*lvl_array) * count * 2)))
		return_0;

	if (!(parallel_areas = build_parallel_areas_from_lv(lv, 0, 1)))
		return_0;

	if (seg_is_linear(seg))
		region_size = seg->region_size ? : get_default_region_size(lv->vg->cmd);
	else
		region_size = seg->region_size;

	if (seg_is_raid(seg))
		segtype = seg->segtype;
	else if (!(segtype = get_segtype_from_string(lv->vg->cmd, SEG_TYPE_NAME_RAID1)))
		return_0;

	/*
	 * The number of extents is based on the RAID type.  For RAID1,
	 * each of the rimages is the same size - 'le_count'.  However
	 * for RAID 4/5/6, the stripes add together (NOT including the parity
	 * devices) to equal 'le_count'.  Thus, when we are allocating
	 * individual devies, we must specify how large the individual device
	 * is along with the number we want ('count').
	 */
	if (use_existing_area_len)
		/* FIXME Workaround for segment type changes where new segtype is unknown here */
		/* Only for raid0* to raid4 */
		extents = (lv->le_count / seg->area_count) * count;
	else if (segtype_is_raid10(segtype)) {
		if (seg->area_count < 2) {
			log_error(INTERNAL_ERROR "LV %s needs at least 2 areas.",
				  display_lvname(lv));
			return 0;
		}
		extents = lv->le_count / (seg->area_count / 2); /* we enforce 2 mirrors right now */
	} else
		extents = (segtype->parity_devs) ?
			   (lv->le_count / (seg->area_count - segtype->parity_devs)) :
			   lv->le_count;

	/* Do we need to allocate any extents? */
	if (pvs && !dm_list_empty(pvs) &&
	    !(ah = allocate_extents(lv->vg, NULL, segtype, 0, count, count,
				    region_size, extents, pvs,
				    lv->alloc, 0, parallel_areas)))
		return_0;

	for (s = 0; s < count; ++s) {
		/*
		 * The allocation areas are grouped together.  First
		 * come the rimage allocated areas, then come the metadata
		 * allocated areas.  Thus, the metadata areas are pulled
		 * from 's + count'.
		 */

		/* new_meta_lvs are optional for raid0 */
		if (new_meta_lvs) {
			if (!(lvl_array[s + count].lv =
			      _alloc_image_component(lv, NULL, ah, s + count, RAID_META))) {
				alloc_destroy(ah);
				return_0;
			}
			dm_list_add(new_meta_lvs, &(lvl_array[s + count].list));
		}

		if (new_data_lvs) {
			if (!(lvl_array[s].lv =
			      _alloc_image_component(lv, NULL, ah, s, RAID_IMAGE))) {
				alloc_destroy(ah);
				return_0;
			}
			dm_list_add(new_data_lvs, &(lvl_array[s].list));
		}
	}

	alloc_destroy(ah);

	return 1;
}

/*
 * HM Helper:
 *
 * Calculate absolute amount of metadata device extents based
 * on @rimage_extents, @region_size and @extent_size.
 */
static uint32_t _raid_rmeta_extents(struct cmd_context *cmd, uint32_t rimage_extents,
				    uint32_t region_size, uint32_t extent_size)
{
	uint64_t bytes, regions, sectors;

	region_size = region_size ?: get_default_region_size(cmd);
	regions = ((uint64_t) rimage_extents) * extent_size / region_size;

	/* raid and bitmap superblocks + region bytes */
	bytes = 2 * 4096 + dm_div_up(regions, 8);
	sectors = dm_div_up(bytes, 512);

	return dm_div_up(sectors, extent_size);
}

/*
 * Returns raid metadata device size _change_ in extents, algorithm from dm-raid ("raid" target) kernel code.
 */
uint32_t raid_rmeta_extents_delta(struct cmd_context *cmd,
				  uint32_t rimage_extents_cur, uint32_t rimage_extents_new,
				  uint32_t region_size, uint32_t extent_size)
{
	uint32_t rmeta_extents_cur = _raid_rmeta_extents(cmd, rimage_extents_cur, region_size, extent_size);
	uint32_t rmeta_extents_new = _raid_rmeta_extents(cmd, rimage_extents_new, region_size, extent_size);

	/* Need minimum size on LV creation */
	if (!rimage_extents_cur)
		return rmeta_extents_new;

	/* Need current size on LV deletion */
	if (!rimage_extents_new)
		return rmeta_extents_cur;

	if (rmeta_extents_new == rmeta_extents_cur)
		return 0;

	/* Extending/reducing... */
	return rmeta_extents_new > rmeta_extents_cur ?
		rmeta_extents_new - rmeta_extents_cur :
		rmeta_extents_cur - rmeta_extents_new;
}

/* Calculate raid rimage extents required based on total @extents for @segtype, @stripes and @data_copies */
uint32_t raid_rimage_extents(const struct segment_type *segtype,
			     uint32_t extents, uint32_t stripes, uint32_t data_copies)
{
	uint64_t r;

	if (!extents ||
	    segtype_is_mirror(segtype) ||
	    segtype_is_raid1(segtype))
		return extents;

	r = extents;
	if (segtype_is_any_raid10(segtype))
		r *= (data_copies ?: 1); /* Caller should ensure data_copies > 0 */

	r = dm_div_up(r, stripes ?: 1); /* Caller should ensure stripes > 0 */

	return r > UINT_MAX ? 0 : (uint32_t) r;
}

/*
 * _alloc_rmeta_for_lv
 * @lv
 *
 * Allocate a RAID metadata device for the given LV (which is or will
 * be the associated RAID data device).  The new metadata device must
 * be allocated from the same PV(s) as the data device.
 */
static int _alloc_rmeta_for_lv(struct logical_volume *data_lv,
			       struct logical_volume **meta_lv,
			       struct dm_list *allocate_pvs)
{
	struct dm_list allocatable_pvs;
	struct alloc_handle *ah;
	struct lv_segment *seg = first_seg(data_lv);
	char *base_name;

	dm_list_init(&allocatable_pvs);

	if (!allocate_pvs) {
		allocate_pvs = &allocatable_pvs;
		if (!get_pv_list_for_lv(data_lv->vg->cmd->mem,
					data_lv, &allocatable_pvs)) {
			log_error("Failed to build list of PVs for %s.",
				  display_lvname(data_lv));
			return 0;
		}
	}

	if (!seg_is_linear(seg)) {
		log_error(INTERNAL_ERROR "Unable to allocate RAID metadata "
			  "area for non-linear LV %s.", display_lvname(data_lv));
		return 0;
	}

	if (!(base_name = top_level_lv_name(data_lv->vg, data_lv->name)))
		return_0;

	if (!(ah = allocate_extents(data_lv->vg, NULL, seg->segtype, 0, 1, 0,
				    seg->region_size,
				    raid_rmeta_extents_delta(data_lv->vg->cmd, 0, data_lv->le_count,
							     seg->region_size, data_lv->vg->extent_size),
				    allocate_pvs, data_lv->alloc, 0, NULL)))
		return_0;

	if (!(*meta_lv = _alloc_image_component(data_lv, base_name, ah, 0, RAID_META))) {
		alloc_destroy(ah);
		return_0;
	}

	alloc_destroy(ah);

	return 1;
}

static int _raid_add_images_without_commit(struct logical_volume *lv,
					   uint32_t new_count, struct dm_list *pvs,
					   int use_existing_area_len)
{
	uint32_t s;
	uint32_t old_count = lv_raid_image_count(lv);
	uint32_t count = new_count - old_count;
	uint64_t status_mask = -1;
	struct lv_segment *seg = first_seg(lv);
	struct dm_list meta_lvs, data_lvs;
	struct lv_list *lvl;
	struct lv_segment_area *new_areas;

	if (lv_is_not_synced(lv)) {
		log_error("Can't add image to out-of-sync RAID LV:"
			  " use 'lvchange --resync' first.");
		return 0;
	}

	if (!_raid_in_sync(lv)) {
		log_error("Can't add image to RAID LV that is still initializing.");
		return 0;
	}

	if (lv_is_active(lv_lock_holder(lv)) &&
	    (old_count == 1) &&
	    (lv_is_thin_pool_data(lv) || lv_is_thin_pool_metadata(lv))) {
		log_error("Can't add image to active thin pool LV %s yet. Deactivate first.",
			  display_lvname(lv));
		return 0;
	}

	if (!archive(lv->vg))
		return_0;

	dm_list_init(&meta_lvs); /* For image addition */
	dm_list_init(&data_lvs); /* For image addition */

	/*
	 * If the segtype is linear, then we must allocate a metadata
	 * LV to accompany it.
	 */
	if (seg_is_linear(seg)) {
		/* A complete resync will be done, no need to mark each sub-lv */
		status_mask = ~(LV_REBUILD);

		/* FIXME: allow setting region size on upconvert from linear */
		seg->region_size = get_default_region_size(lv->vg->cmd);
		/* MD's bitmap is limited to tracking 2^21 regions */
		seg->region_size = raid_ensure_min_region_size(lv, lv->size, seg->region_size);

		if (!(lvl = dm_pool_alloc(lv->vg->vgmem, sizeof(*lvl)))) {
			log_error("Memory allocation failed.");
			return 0;
		}

		if (!_alloc_rmeta_for_lv(lv, &lvl->lv, NULL))
			return_0;

		dm_list_add(&meta_lvs, &lvl->list);
	} else if (!seg_is_raid(seg)) {
		log_error("Unable to add RAID images to %s of segment type %s.",
			  display_lvname(lv), lvseg_name(seg));
		return 0;
	}

	if (!_alloc_image_components(lv, pvs, count, &meta_lvs, &data_lvs, use_existing_area_len))
		return_0;

	/*
	 * If linear, we must correct data LV names.  They are off-by-one
	 * because the linear volume hasn't taken its proper name of "_rimage_0"
	 * yet.  This action must be done before '_clear_lvs' because it
	 * commits the LVM metadata before clearing the LVs.
	 */
	if (seg_is_linear(seg)) {
		struct dm_list *l;
		struct lv_list *lvl_tmp;

		dm_list_iterate(l, &data_lvs) {
			if (l == dm_list_last(&data_lvs)) {
				lvl = dm_list_item(l, struct lv_list);
				if (!(lvl->lv->name = _generate_raid_name(lv, "rimage", count)))
					return_0;
				continue;
			}
			lvl = dm_list_item(l, struct lv_list);
			lvl_tmp = dm_list_item(l->n, struct lv_list);
			lvl->lv->name = lvl_tmp->lv->name;
		}
	}

	/* Metadata LVs must be cleared before being added to the array */
	if (!_clear_lvs(&meta_lvs))
		goto fail;

	if (seg_is_linear(seg)) {
		uint32_t region_size = seg->region_size;

		seg->status |= RAID_IMAGE;
		if (!insert_layer_for_lv(lv->vg->cmd, lv,
					 RAID | LVM_READ | LVM_WRITE,
					 "_rimage_0"))
			return_0;

		lv->status |= RAID;
		seg = first_seg(lv);
		seg->region_size = region_size;
		seg_lv(seg, 0)->status |= RAID_IMAGE | LVM_READ | LVM_WRITE;
		if (!(seg->segtype = get_segtype_from_string(lv->vg->cmd, SEG_TYPE_NAME_RAID1)))
			return_0;
	}
/*
FIXME: It would be proper to activate the new LVs here, instead of having
them activated by the suspend.  However, this causes residual device nodes
to be left for these sub-lvs.
	dm_list_iterate_items(lvl, &meta_lvs)
		if (!do_correct_activate(lv, lvl->lv))
			return_0;
	dm_list_iterate_items(lvl, &data_lvs)
		if (!do_correct_activate(lv, lvl->lv))
			return_0;
*/
	/* Expand areas array */
	if (!(new_areas = dm_pool_zalloc(lv->vg->cmd->mem,
					 new_count * sizeof(*new_areas)))) {
		log_error("Allocation of new areas failed.");
		goto fail;
	}
	memcpy(new_areas, seg->areas, seg->area_count * sizeof(*seg->areas));
	seg->areas = new_areas;

	/* Expand meta_areas array */
	if (!(new_areas = dm_pool_zalloc(lv->vg->cmd->mem,
					 new_count * sizeof(*new_areas)))) {
		log_error("Allocation of new meta areas failed.");
		goto fail;
	}
	if (seg->meta_areas)
		memcpy(new_areas, seg->meta_areas,
		       seg->area_count * sizeof(*seg->meta_areas));
	seg->meta_areas = new_areas;
	seg->area_count = new_count;

	/* Add extra meta area when converting from linear */
	s = (old_count == 1) ? 0 : old_count;

	/* Set segment areas for metadata sub_lvs */
	dm_list_iterate_items(lvl, &meta_lvs) {
		log_debug_metadata("Adding %s to %s.",
				   display_lvname(lvl->lv),
				   display_lvname(lv));
		lvl->lv->status &= status_mask;
		first_seg(lvl->lv)->status &= status_mask;
		if (!set_lv_segment_area_lv(seg, s, lvl->lv, 0,
					    lvl->lv->status)) {
			log_error("Failed to add %s to %s.",
				  display_lvname(lvl->lv),
				  display_lvname(lv));
			goto fail;
		}
		s++;
	}

	s = old_count;

	/* Set segment areas for data sub_lvs */
	dm_list_iterate_items(lvl, &data_lvs) {
		log_debug_metadata("Adding %s to %s.",
				   display_lvname(lvl->lv),
				   display_lvname(lv));
		lvl->lv->status &= status_mask;
		first_seg(lvl->lv)->status &= status_mask;
		if (!set_lv_segment_area_lv(seg, s, lvl->lv, 0,
					    lvl->lv->status)) {
			log_error("Failed to add %s to %s.",
				  display_lvname(lvl->lv),
				  display_lvname(lv));
			goto fail;
		}
		s++;
	}

	/*
	 * FIXME: Failure handling during these points is harder.
	 */
	dm_list_iterate_items(lvl, &meta_lvs)
		lv_set_hidden(lvl->lv);
	dm_list_iterate_items(lvl, &data_lvs)
		lv_set_hidden(lvl->lv);

	return 1;

fail:
	/* Cleanly remove newly-allocated LVs that failed insertion attempt */
	dm_list_iterate_items(lvl, &meta_lvs)
		if (!lv_remove(lvl->lv))
			return_0;

	dm_list_iterate_items(lvl, &data_lvs)
		if (!lv_remove(lvl->lv))
			return_0;

	return 0;
}

static int _raid_add_images(struct logical_volume *lv,
			    uint32_t new_count, struct dm_list *pvs,
			    int commit, int use_existing_area_len)
{
	int rebuild_flag_cleared = 0;
	struct lv_segment *seg;
	uint32_t s;

	if (!_raid_add_images_without_commit(lv, new_count, pvs, use_existing_area_len))
		return_0;

	if (!commit)
		return 1;

	if (!lv_update_and_reload_origin(lv))
		return_0;

	/*
	 * Now that the 'REBUILD' has made its way to the kernel, we must
	 * remove the flag so that the individual devices are not rebuilt
	 * upon every activation.
	 */
	seg = first_seg(lv);
	for (s = 0; s < seg->area_count; s++) {
		if ((seg_lv(seg, s)->status & LV_REBUILD) ||
		    (seg_metalv(seg, s)->status & LV_REBUILD)) {
			seg_metalv(seg, s)->status &= ~LV_REBUILD;
			seg_lv(seg, s)->status &= ~LV_REBUILD;
			rebuild_flag_cleared = 1;
		}
	}
	if (rebuild_flag_cleared) {
		if (!vg_write(lv->vg) || !vg_commit(lv->vg)) {
			log_error("Failed to clear REBUILD flag for %s components.",
				  display_lvname(lv));
			return 0;
		}
		backup(lv->vg);
	}

	return 1;
}

/*
 * _extract_image_components
 * @seg
 * @idx:  The index in the areas array to remove
 * @extracted_rmeta:  The displaced metadata LV
 * @extracted_rimage:  The displaced data LV
 *
 * This function extracts the image components - setting the respective
 * 'extracted' pointers.  It appends '_extracted' to the LVs' names, so that
 * there are not future conflicts.  It does /not/ commit the results.
 * (IOW, erroring-out requires no unwinding of operations.)
 *
 * This function does /not/ attempt to:
 *    1) shift the 'areas' or 'meta_areas' arrays.
 *       The '[meta_]areas' are left as AREA_UNASSIGNED.
 *    2) Adjust the seg->area_count
 *    3) Name the extracted LVs appropriately (appends '_extracted' to names)
 * These actions must be performed by the caller.
 *
 * Returns: 1 on success, 0 on failure
 */
static int _extract_image_components(struct lv_segment *seg, uint32_t idx,
				     struct logical_volume **extracted_rmeta,
				     struct logical_volume **extracted_rimage)
{
	struct logical_volume *data_lv = seg_lv(seg, idx);
	struct logical_volume *meta_lv = seg_metalv(seg, idx);

	log_very_verbose("Extracting image components %s and %s from %s.",
			 display_lvname(data_lv),
			 display_lvname(meta_lv),
			 display_lvname(seg->lv));

	data_lv->status &= ~RAID_IMAGE;
	meta_lv->status &= ~RAID_META;
	lv_set_visible(data_lv);
	lv_set_visible(meta_lv);

	/* release removes data and meta areas */
	if (!remove_seg_from_segs_using_this_lv(data_lv, seg) ||
	    !remove_seg_from_segs_using_this_lv(meta_lv, seg))
		return_0;

	seg_type(seg, idx) = AREA_UNASSIGNED;
	seg_metatype(seg, idx) = AREA_UNASSIGNED;

	if (!(data_lv->name = _generate_raid_name(data_lv, "extracted", -1)))
		return_0;

	if (!(meta_lv->name = _generate_raid_name(meta_lv, "extracted", -1)))
		return_0;

	*extracted_rmeta = meta_lv;
	*extracted_rimage = data_lv;

	return 1;
}

/*
 * _raid_extract_images
 * @lv
 * @force: force a replacement in case of primary mirror leg
 * @new_count:  The absolute count of images (e.g. '2' for a 2-way mirror)
 * @target_pvs:  The list of PVs that are candidates for removal
 * @shift:  If set, use _shift_and_rename_image_components().
 *	  Otherwise, leave the [meta_]areas as AREA_UNASSIGNED and
 *	  seg->area_count unchanged.
 * @extracted_[meta|data]_lvs:  The LVs removed from the array.  If 'shift'
 *			      is set, then there will likely be name conflicts.
 *
 * This function extracts _both_ portions of the indexed image.  It
 * does /not/ commit the results.  (IOW, erroring-out requires no unwinding
 * of operations.)
 *
 * Returns: 1 on success, 0 on failure
 */
static int _raid_extract_images(struct logical_volume *lv,
				int force, uint32_t new_count,
				struct dm_list *target_pvs, int shift,
				struct dm_list *extracted_meta_lvs,
				struct dm_list *extracted_data_lvs)
{
	int ss, s, extract, lvl_idx = 0;
	struct lv_list *lvl_array;
	struct lv_segment *seg = first_seg(lv);
	struct logical_volume *rmeta_lv, *rimage_lv;
	struct segment_type *error_segtype;

	extract = seg->area_count - new_count;
	log_verbose("Extracting %u %s from %s.", extract,
		    (extract > 1) ? "images" : "image",
		    display_lvname(lv));
	if ((int) dm_list_size(target_pvs) < extract) {
		log_error("Unable to remove %d images:  Only %d device%s given.",
			  extract, dm_list_size(target_pvs),
			  (dm_list_size(target_pvs) == 1) ? "" : "s");
		return 0;
	}

	if (!(lvl_array = dm_pool_alloc(lv->vg->vgmem,
					sizeof(*lvl_array) * extract * 2)))
		return_0;

	if (!(error_segtype = get_segtype_from_string(lv->vg->cmd, SEG_TYPE_NAME_ERROR)))
		return_0;

	/*
	 * We make two passes over the devices.
	 * - The first pass we look for error LVs
	 * - The second pass we look for PVs that match target_pvs
	 */
	for (ss = (seg->area_count * 2) - 1; (ss >= 0) && extract; ss--) {
		s = ss % seg->area_count;

		if (ss / seg->area_count) {
			/* Conditions for first pass */
			if ((first_seg(seg_lv(seg, s))->segtype != error_segtype) &&
			    (first_seg(seg_metalv(seg, s))->segtype != error_segtype))
				continue;

			if (!dm_list_empty(target_pvs) &&
			    (target_pvs != &lv->vg->pvs)) {
				/*
				 * User has supplied a list of PVs, but we
				 * cannot honor that list because error LVs
				 * must come first.
				 */
				log_error("%s has components with error targets"
					  " that must be removed first: %s.",
					  display_lvname(lv),
					  display_lvname(seg_lv(seg, s)));

				log_error("Try removing the PV list and rerun"
					  " the command.");
				return 0;
			}
			log_debug("LVs with error segments to be removed: %s %s.",
				  display_lvname(seg_metalv(seg, s)),
				  display_lvname(seg_lv(seg, s)));
		} else {
			/* Conditions for second pass */
			if (!lv_is_on_pvs(seg_lv(seg, s), target_pvs) &&
			    !lv_is_on_pvs(seg_metalv(seg, s), target_pvs))
				continue;

			/*
			 * Kernel may report raid LV in-sync but still
			 * image devices may not be in-sync or faulty.
			 */
			if (!_raid_devs_sync_healthy(lv) &&
			    (!seg_is_mirrored(seg) || (s == 0 && !force))) {
				log_error("Unable to extract %sRAID image"
					  " while RAID array is not in-sync%s.",
					  seg_is_mirrored(seg) ? "primary " : "",
					  seg_is_mirrored(seg) ? " (use --force option to replace)" : "");
				return 0;
			}
		}
		if (!_extract_image_components(seg, s, &rmeta_lv, &rimage_lv)) {
			log_error("Failed to extract %s from %s.",
				  display_lvname(seg_lv(seg, s)),
				  display_lvname(lv));
			return 0;
		}

		if (shift && !_shift_and_rename_image_components(seg)) {
			log_error("Failed to shift and rename image components.");
			return 0;
		}

		lvl_array[lvl_idx].lv = rmeta_lv;
		lvl_array[lvl_idx + 1].lv = rimage_lv;
		dm_list_add(extracted_meta_lvs, &(lvl_array[lvl_idx++].list));
		dm_list_add(extracted_data_lvs, &(lvl_array[lvl_idx++].list));

		extract--;
	}
	if (extract) {
		log_error("Unable to extract enough images to satisfy request.");
		return 0;
	}

	return 1;
}

static int _raid_remove_images(struct logical_volume *lv,
			       uint32_t new_count, struct dm_list *allocate_pvs,
			       struct dm_list *removal_lvs, int commit)
{
	struct dm_list removed_lvs;

	if (!archive(lv->vg))
		return_0;

	if (!removal_lvs) {
		dm_list_init(&removed_lvs);
		removal_lvs = &removed_lvs;
	}

	if (!_raid_extract_images(lv, 0, new_count, allocate_pvs, 1,
				 removal_lvs, removal_lvs)) {
		log_error("Failed to extract images from %s.",
			  display_lvname(lv));
		return 0;
	}

	/* Convert to linear? */
	if (new_count == 1) {
		if (!_raid_remove_top_layer(lv, removal_lvs)) {
			log_error("Failed to remove RAID layer "
				  "after linear conversion.");
			return 0;
		}
		lv->status &= ~(LV_NOTSYNCED | LV_WRITEMOSTLY);
		first_seg(lv)->writebehind = 0;
	}

	if (!commit)
		return 1;

	if (!_lv_update_and_reload_list(lv, 0, removal_lvs))
		return_0;

	/*
	 * Eliminate the extracted LVs
	 */
	if (!dm_list_empty(removal_lvs)) {
		if (!_deactivate_and_remove_lvs(lv->vg, removal_lvs))
			return_0;

		if (!vg_write(lv->vg) || !vg_commit(lv->vg))
			return_0;
	}

	backup(lv->vg);

	return 1;
}

/*
 * _lv_raid_change_image_count
 * new_count: The absolute count of images (e.g. '2' for a 2-way mirror)
 * allocate_pvs: The list of PVs that are candidates for removal (or empty list)
 *
 * RAID arrays have 'images' which are composed of two parts, they are:
 *    - 'rimage': The data/parity holding portion
 *    - 'rmeta' : The metadata holding portion (i.e. superblock/bitmap area)
 * This function adds or removes _both_ portions of the image and commits
 * the results.
 */
static int _lv_raid_change_image_count(struct logical_volume *lv, uint32_t new_count,
				       struct dm_list *allocate_pvs, struct dm_list *removal_lvs,
				       int commit, int use_existing_area_len)
{
	uint32_t old_count = lv_raid_image_count(lv);

	if (old_count == new_count) {
		log_warn("WARGNING: %s already has image count of %d.",
			 display_lvname(lv), new_count);
		return 1;
	}

	/*
	 * LV must be either in-active or exclusively active
	 */
	if (lv_is_active(lv_lock_holder(lv)) && vg_is_clustered(lv->vg) &&
	    !lv_is_active_exclusive_locally(lv_lock_holder(lv))) {
		log_error("%s must be active exclusive locally to "
			  "perform this operation.", display_lvname(lv));
		return 0;
	}

	if (old_count > new_count)
		return _raid_remove_images(lv, new_count, allocate_pvs, removal_lvs, commit);

	return _raid_add_images(lv, new_count, allocate_pvs, commit, use_existing_area_len);
}

int lv_raid_change_image_count(struct logical_volume *lv, uint32_t new_count,
			       struct dm_list *allocate_pvs)
{
	return _lv_raid_change_image_count(lv, new_count, allocate_pvs, NULL, 1, 0);
}

int lv_raid_split(struct logical_volume *lv, const char *split_name,
		  uint32_t new_count, struct dm_list *splittable_pvs)
{
	struct lv_list *lvl;
	struct dm_list removal_lvs, data_list;
	struct cmd_context *cmd = lv->vg->cmd;
	uint32_t old_count = lv_raid_image_count(lv);
	struct logical_volume *tracking;
	struct dm_list tracking_pvs;
	int historical;

	dm_list_init(&removal_lvs);
	dm_list_init(&data_list);

	if (is_lockd_type(lv->vg->lock_type)) {
		log_error("Splitting raid image is not allowed with lock_type %s.",
			  lv->vg->lock_type);
		return 0;
	}

	if ((old_count - new_count) != 1) {
		log_error("Unable to split more than one image from %s.",
			  display_lvname(lv));
		return 0;
	}

	if (!seg_is_mirrored(first_seg(lv)) ||
	    seg_is_raid10(first_seg(lv))) {
		log_error("Unable to split logical volume of segment type, %s.",
			  lvseg_name(first_seg(lv)));
		return 0;
	}

	if (lv_name_is_used_in_vg(lv->vg, split_name, &historical)) {
		log_error("%sLogical Volume \"%s\" already exists in %s.",
			  historical ? "historical " : "", split_name, lv->vg->name);
		return 0;
	}

	if (!_raid_in_sync(lv)) {
		log_error("Unable to split %s while it is not in-sync.",
			  display_lvname(lv));
		return 0;
	}

	/*
	 * We only allow a split while there is tracking if it is to
	 * complete the split of the tracking sub-LV
	 */
	if (_lv_is_raid_with_tracking(lv, &tracking)) {
		if (!lv_is_on_pvs(tracking, splittable_pvs)) {
			log_error("Unable to split additional image from %s "
				  "while tracking changes for %s.",
				  display_lvname(lv), display_lvname(tracking));
			return 0;
		}

		/* Ensure we only split the tracking image */
		dm_list_init(&tracking_pvs);
		splittable_pvs = &tracking_pvs;
		if (!get_pv_list_for_lv(tracking->vg->cmd->mem,
					tracking, splittable_pvs))
			return_0;
	}

	if (!_raid_extract_images(lv, 0, new_count, splittable_pvs, 1,
				 &removal_lvs, &data_list)) {
		log_error("Failed to extract images from %s.",
			  display_lvname(lv));
		return 0;
	}

	/* Convert to linear? */
	if ((new_count == 1) && !_raid_remove_top_layer(lv, &removal_lvs)) {
		log_error("Failed to remove RAID layer after linear conversion.");
		return 0;
	}

	/* Get first item */
	dm_list_iterate_items(lvl, &data_list)
		break;

	lvl->lv->name = split_name;

	if (!vg_write(lv->vg)) {
		log_error("Failed to write changes for %s.",
			  display_lvname(lv));
		return 0;
	}

	if (!suspend_lv(cmd, lv_lock_holder(lv))) {
		log_error("Failed to suspend %s before committing changes.",
			  display_lvname(lv_lock_holder(lv)));
		vg_revert(lv->vg);
		return 0;
	}

	if (!vg_commit(lv->vg)) {
		log_error("Failed to commit changes for %s.",
			  display_lvname(lv));
		return 0;
	}

	/*
	 * First activate the newly split LV and LVs on the removal list.
	 * This is necessary so that there are no name collisions due to
	 * the original RAID LV having possibly had sub-LVs that have been
	 * shifted and renamed.
	 */
	if (!activate_lv_excl_local(cmd, lvl->lv))
		return_0;

	dm_list_iterate_items(lvl, &removal_lvs)
		if (!activate_lv_excl_local(cmd, lvl->lv))
			return_0;

	if (!resume_lv(cmd, lv_lock_holder(lv))) {
		log_error("Failed to resume %s after committing changes.",
			  display_lvname(lv));
		return 0;
	}

	/*
	 * Since newly split LV is typically already active - we need to call
	 * suspend() and resume() to also rename it.
	 *
	 * TODO: activate should recognize it and avoid these 2 calls
	 */

	/*
	 * Eliminate the residual LVs
	 */
	if (!_deactivate_and_remove_lvs(lv->vg, &removal_lvs))
                return_0;

	if (!vg_write(lv->vg) || !vg_commit(lv->vg))
		return_0;

	backup(lv->vg);

	return 1;
}

/*
 * lv_raid_split_and_track
 * @lv
 * @splittable_pvs
 *
 * Only allows a single image to be split while tracking.  The image
 * never actually leaves the mirror.  It is simply made visible.  This
 * action triggers two things: 1) users are able to access the (data) image
 * and 2) lower layers replace images marked with a visible flag with
 * error targets.
 *
 * Returns: 1 on success, 0 on error
 */
int lv_raid_split_and_track(struct logical_volume *lv,
			    struct dm_list *splittable_pvs)
{
	int s;
	struct lv_segment *seg = first_seg(lv);

	if (!seg_is_mirrored(seg)) {
		log_error("Unable to split images from non-mirrored RAID.");
		return 0;
	}

	if (!_raid_in_sync(lv)) {
		log_error("Unable to split image from %s while not in-sync.",
			  display_lvname(lv));
		return 0;
	}

	/* Cannot track two split images at once */
	if (lv_is_raid_with_tracking(lv)) {
		log_error("Cannot track more than one split image at a time.");
		return 0;
	}

	for (s = seg->area_count - 1; s >= 0; --s) {
		if (!lv_is_on_pvs(seg_lv(seg, s), splittable_pvs))
			continue;
		lv_set_visible(seg_lv(seg, s));
		seg_lv(seg, s)->status &= ~LVM_WRITE;
		break;
	}

	if (s < 0) {
		log_error("Unable to find image to satisfy request.");
		return 0;
	}

	if (!lv_update_and_reload(lv))
		return_0;

	log_print_unless_silent("%s split from %s for read-only purposes.",
				display_lvname(seg_lv(seg, s)),
				display_lvname(lv));

	/* Activate the split (and tracking) LV */
	/* Preserving exclusive local activation also for tracked LV */
	if (!activate_lv_excl_local(lv->vg->cmd, seg_lv(seg, s)))
		return_0;

	log_print_unless_silent("Use 'lvconvert --merge %s' to merge back into %s.",
				display_lvname(seg_lv(seg, s)),
				display_lvname(lv));
	return 1;
}

int lv_raid_merge(struct logical_volume *image_lv)
{
	uint32_t s;
	char *p, *lv_name;
	struct lv_list *lvl;
	struct logical_volume *lv;
	struct logical_volume *meta_lv = NULL;
	struct lv_segment *seg;
	struct volume_group *vg = image_lv->vg;

	if (image_lv->status & LVM_WRITE) {
		log_error("%s is not read-only - refusing to merge.",
			  display_lvname(image_lv));
		return 0;
	}

	if (!(lv_name = dm_pool_strdup(vg->vgmem, image_lv->name)))
		return_0;

	if (!(p = strstr(lv_name, "_rimage_"))) {
		log_error("Unable to merge non-mirror image %s.",
			  display_lvname(image_lv));
		return 0;
	}
	*p = '\0'; /* lv_name is now that of top-level RAID */

	if (!(lvl = find_lv_in_vg(vg, lv_name))) {
		log_error("Unable to find containing RAID array for %s.",
			  display_lvname(image_lv));
		return 0;
	}

	lv = lvl->lv;
	seg = first_seg(lv);
	for (s = 0; s < seg->area_count; ++s)
		if (seg_lv(seg, s) == image_lv)
			meta_lv = seg_metalv(seg, s);

	if (!meta_lv) {
		log_error("Failed to find meta for %s in RAID array %s.",
			  display_lvname(image_lv),
			  display_lvname(lv));
		return 0;
	}

	if (!deactivate_lv(vg->cmd, meta_lv)) {
		log_error("Failed to deactivate %s before merging.",
			  display_lvname(meta_lv));
		return 0;
	}

	if (!deactivate_lv(vg->cmd, image_lv)) {
		log_error("Failed to deactivate %s before merging.",
			  display_lvname(image_lv));
		return 0;
	}
	lv_set_hidden(image_lv);
	image_lv->status |= (lv->status & LVM_WRITE);
	image_lv->status |= RAID_IMAGE;

	if (!lv_update_and_reload(lv))
		return_0;

	log_print_unless_silent("%s successfully merged back into %s.",
				display_lvname(image_lv),
				display_lvname(lv));
	return 1;
}

/*
 * Allocate metadata devs for all @new_data_devs and link them to list @new_meta_lvs
 */
static int _alloc_rmeta_devs_for_rimage_devs(struct logical_volume *lv,
					     struct dm_list *new_data_lvs,
					     struct dm_list *new_meta_lvs,
					     struct dm_list *allocate_pvs)
{
	uint32_t a = 0, raid_devs = dm_list_size(new_data_lvs);
	struct lv_list *lvl, *lvl1, *lvl_array;

	if (!raid_devs)
		return_0;

	if (!(lvl_array = dm_pool_zalloc(lv->vg->vgmem, raid_devs * sizeof(*lvl_array))))
		return_0;

	dm_list_iterate_items(lvl, new_data_lvs) {
		log_debug_metadata("Allocating new metadata LV for %s.",
				   display_lvname(lvl->lv));

		/*
		 * Try to collocate with DataLV first and
		 * if that fails allocate on different PV.
		 */
		if (!_alloc_rmeta_for_lv(lvl->lv, &lvl_array[a].lv,
					 allocate_pvs != &lv->vg->pvs ? allocate_pvs : NULL)) {
			dm_list_iterate_items(lvl1, new_meta_lvs)
				if (!_avoid_pvs_with_other_images_of_lv(lvl1->lv, allocate_pvs))
					return_0;

			if (!_alloc_rmeta_for_lv(lvl->lv, &lvl_array[a].lv, allocate_pvs)) {
				log_error("Failed to allocate metadata LV for %s.",
					  display_lvname(lvl->lv));
				return 0;
			}
		}

		dm_list_add(new_meta_lvs, &lvl_array[a++].list);

		dm_list_iterate_items(lvl1, new_meta_lvs)
			if (!_avoid_pvs_with_other_images_of_lv(lvl1->lv, allocate_pvs))
				return_0;
	}

	_clear_allocation_prohibited(allocate_pvs);

	return 1;
}

/* Add new @lvs to @lv at @area_offset */
static int _add_image_component_list(struct lv_segment *seg, int delete_from_list,
				     uint64_t lv_flags, struct dm_list *lvs, uint32_t area_offset)
{
	uint32_t s = area_offset;
	struct lv_list *lvl, *tmp;

	dm_list_iterate_items_safe(lvl, tmp, lvs) {
		if (delete_from_list)
			dm_list_del(&lvl->list);

		if (lv_flags & VISIBLE_LV)
			lv_set_visible(lvl->lv);
		else
			lv_set_hidden(lvl->lv);

		if (lv_flags & LV_REBUILD)
			lvl->lv->status |= LV_REBUILD;
		else
			lvl->lv->status &= ~LV_REBUILD;

		if (!set_lv_segment_area_lv(seg, s++, lvl->lv, 0 /* le */, lvl->lv->status)) {
			log_error("Failed to add sublv %s.",
				  display_lvname(lvl->lv));
			return 0;
		}
	}

	return 1;
}

/*
 * Split segments in segment LVs in all areas of seg at offset area_le
 */
static int _split_area_lvs_segments(struct lv_segment *seg, uint32_t area_le)
{
	uint32_t s;

	/* Make sure that there's a segment starting at area_le in all data LVs */
	for (s = 0; s < seg->area_count; s++)
		if (area_le < seg_lv(seg, s)->le_count &&
		    !lv_split_segment(seg_lv(seg, s), area_le))
			return_0;

	return 1;
}

static int _alloc_and_add_new_striped_segment(struct logical_volume *lv,
					      uint32_t le, uint32_t area_len,
					      struct dm_list *new_segments)
{
	struct lv_segment *seg, *new_seg;
	struct segment_type *striped_segtype;

	seg = first_seg(lv);

	if (!(striped_segtype = get_segtype_from_string(lv->vg->cmd, SEG_TYPE_NAME_STRIPED)))
		return_0;

	/* Allocate a segment with seg->area_count areas */
	if (!(new_seg = alloc_lv_segment(striped_segtype, lv, le, area_len * seg->area_count,
					 0,
					 seg->stripe_size, NULL, seg->area_count,
					 area_len, seg->chunk_size, 0, 0, NULL)))
		return_0;

	dm_list_add(new_segments, &new_seg->list);

	return 1;
}

static int _extract_image_component_error_seg(struct lv_segment *seg,
					      uint64_t type, uint32_t idx,
					      struct logical_volume **extracted_lv,
					      int set_error_seg)
{
	struct logical_volume *lv;

	switch (type) {
		case RAID_META:
			lv = seg_metalv(seg, idx);
			seg_metalv(seg, idx) = NULL;
			seg_metatype(seg, idx) = AREA_UNASSIGNED;
			break;
		case RAID_IMAGE:
			lv = seg_lv(seg, idx);
			seg_lv(seg, idx) = NULL;
			seg_type(seg, idx) = AREA_UNASSIGNED;
			break;
		default:
			log_error(INTERNAL_ERROR "Bad type provided to %s.", __func__);
			return 0;
	}

	log_very_verbose("Extracting image component %s from %s.",
			 display_lvname(lv), lvseg_name(seg));
	lv->status &= ~(type | RAID);
	lv_set_visible(lv);

	/* remove reference from seg to lv */
	if (!remove_seg_from_segs_using_this_lv(lv, seg))
		return_0;

	if (!(lv->name = _generate_raid_name(lv, "extracted", -1)))
		return_0;

	if (set_error_seg && !replace_lv_with_error_segment(lv))
		return_0;

	*extracted_lv = lv;

	return 1;
}

/*
 * Extract all sub LVs of type from seg starting at idx excluding end and
 * put them on removal_lvs setting mappings to "error" if error_seg.
 */
static int _extract_image_component_sublist(struct lv_segment *seg,
					    uint64_t type, uint32_t idx, uint32_t end,
					    struct dm_list *removal_lvs,
					    int error_seg)
{
	uint32_t s;
	struct lv_list *lvl;

	if (!(lvl = dm_pool_alloc(seg_lv(seg, idx)->vg->vgmem, sizeof(*lvl) * (end - idx))))
		return_0;

	for (s = idx; s < end; s++) {
		if (!_extract_image_component_error_seg(seg, type, s, &lvl->lv, error_seg))
			return 0;

		dm_list_add(removal_lvs, &lvl->list);
		lvl++;
	}

	if (!idx && end == seg->area_count) {
		if (type == RAID_IMAGE)
			seg->areas = NULL;
		else
			seg->meta_areas = NULL;
	}

	return 1;
}

/* Extract all sub LVs of type from seg starting with idx and put them on removal_Lvs */
static int _extract_image_component_list(struct lv_segment *seg,
					 uint64_t type, uint32_t idx,
					 struct dm_list *removal_lvs)
{
	return _extract_image_component_sublist(seg, type, idx, seg->area_count, removal_lvs, 1);
}

/*
 * Allocate metadata devs for all data devs of an LV
 */
static int _alloc_rmeta_devs_for_lv(struct logical_volume *lv,
				    struct dm_list *meta_lvs,
				    struct dm_list *allocate_pvs,
				    struct lv_segment_area **seg_meta_areas)
{
	uint32_t s;
	struct lv_list *lvl_array;
	struct dm_list data_lvs;
	struct lv_segment *seg = first_seg(lv);

	dm_list_init(&data_lvs);

	if (!(*seg_meta_areas = dm_pool_zalloc(lv->vg->vgmem, seg->area_count * sizeof(*seg->meta_areas))))
		return 0;

	if (!(lvl_array = dm_pool_alloc(lv->vg->vgmem, seg->area_count * sizeof(*lvl_array))))
		return_0;

	for (s = 0; s < seg->area_count; s++) {
		lvl_array[s].lv = seg_lv(seg, s);
		dm_list_add(&data_lvs, &lvl_array[s].list);
	}

	if (!_alloc_rmeta_devs_for_rimage_devs(lv, &data_lvs, meta_lvs, allocate_pvs)) {
		log_error("Failed to allocate metadata LVs for %s.",
			  display_lvname(lv));
		return 0;
	}

	return 1;
}

/*
 * Add metadata areas to raid0
 */
static int _alloc_and_add_rmeta_devs_for_lv(struct logical_volume *lv, struct dm_list *allocate_pvs)
{
	struct lv_segment *seg = first_seg(lv);
	struct dm_list meta_lvs;
	struct lv_segment_area *seg_meta_areas;

	dm_list_init(&meta_lvs);

	log_debug_metadata("Allocating metadata LVs for %s.",
			   display_lvname(lv));
	if (!_alloc_rmeta_devs_for_lv(lv, &meta_lvs, allocate_pvs, &seg_meta_areas)) {
		log_error("Failed to allocate metadata LVs for %s.",
			  display_lvname(lv));
		return 0;
	}

	/* Metadata LVs must be cleared before being added to the array */
	log_debug_metadata("Clearing newly allocated metadata LVs for %s.",
			   display_lvname(lv));
	if (!_clear_lvs(&meta_lvs)) {
		log_error("Failed to initialize metadata LVs for %s.",
			  display_lvname(lv));
		return 0;
	}

	/* Set segment areas for metadata sub_lvs */
	seg->meta_areas = seg_meta_areas;
	log_debug_metadata("Adding newly allocated metadata LVs to %s.",
			   display_lvname(lv));
	if (!_add_image_component_list(seg, 1, 0, &meta_lvs, 0)) {
		log_error("Failed to add newly allocated metadata LVs to %s.",
			  display_lvname(lv));
		return 0;
	}

	return 1;
}

/*
 * Eliminate the extracted LVs on @removal_lvs from @vg incl. vg write, commit and backup 
 */
static int _eliminate_extracted_lvs_optional_write_vg(struct volume_group *vg,
						      struct dm_list *removal_lvs,
						      int vg_write_requested)
{
	if (!removal_lvs || dm_list_empty(removal_lvs))
		return 1;

	if (!_deactivate_and_remove_lvs(vg, removal_lvs))
		return_0;

	/* Wait for events following any deactivation. */
	if (!sync_local_dev_names(vg->cmd)) {
		log_error("Failed to sync local devices after removing %u LVs in VG %s.",
			  dm_list_size(removal_lvs), vg->name);
		return 0;
	}

	dm_list_init(removal_lvs);

	if (vg_write_requested) {
		if (!vg_write(vg) || !vg_commit(vg))
			return_0;

		backup(vg);
	}

	return 1;
}

static int _eliminate_extracted_lvs(struct volume_group *vg, struct dm_list *removal_lvs)
{
	return _eliminate_extracted_lvs_optional_write_vg(vg, removal_lvs, 1);
}

/*
 * Add/remove metadata areas to/from raid0
 */
static int _raid0_add_or_remove_metadata_lvs(struct logical_volume *lv,
					     int update_and_reload,
					     struct dm_list *allocate_pvs,
					     struct dm_list *removal_lvs)
{
	uint64_t new_raid_type_flag;
	struct lv_segment *seg = first_seg(lv);

	if (removal_lvs) {
		if (seg->meta_areas) {
			if (!_extract_image_component_list(seg, RAID_META, 0, removal_lvs))
				return_0;
			seg->meta_areas = NULL;
		}
		new_raid_type_flag = SEG_RAID0;
	} else {
		if (!_alloc_and_add_rmeta_devs_for_lv(lv, allocate_pvs))
			return 0;

		new_raid_type_flag = SEG_RAID0_META;
	}

	if (!(seg->segtype = get_segtype_from_flag(lv->vg->cmd, new_raid_type_flag)))
		return_0;

	if (update_and_reload) {
		if (!_lv_update_and_reload_list(lv, 1, removal_lvs))
			return_0;

		/* If any residual LVs, eliminate them, write VG, commit it and take a backup */
		return _eliminate_extracted_lvs(lv->vg, removal_lvs);
	}

	return 1;
}

/*
 * Clear any rebuild disk flags on lv.
 * If any flags were cleared, *flags_were_cleared is set to 1.
 */
/* FIXME Generalise into foreach_underlying_lv_segment_area. */
static void _clear_rebuild_flags(struct logical_volume *lv, int *flags_were_cleared)
{
	struct lv_segment *seg = first_seg(lv);
	struct logical_volume *sub_lv;
	uint32_t s;
	uint64_t flags_to_clear = LV_REBUILD;

	for (s = 0; s < seg->area_count; s++) {
		if (seg_type(seg, s) == AREA_PV)
			continue;

		sub_lv = seg_lv(seg, s);

		/* Recurse into sub LVs */
		_clear_rebuild_flags(sub_lv, flags_were_cleared);

		if (sub_lv->status & flags_to_clear) {
			sub_lv->status &= ~flags_to_clear;
			*flags_were_cleared = 1;
		}
	}
}

/*
 * Updates and reloads metadata, clears any flags passed to the kernel,
 * eliminates any residual LVs and updates and reloads metadata again.
 *
 * lv removal_lvs
 *
 * This minimally involves 2 metadata commits.
 */
static int _lv_update_reload_fns_reset_eliminate_lvs(struct logical_volume *lv, struct dm_list *removal_lvs)
{
	int flags_were_cleared = 0, r = 0;

	if (!_lv_update_and_reload_list(lv, 1, removal_lvs))
		return_0;

	/* Eliminate any residual LV and don't commit the metadata */
	if (!_eliminate_extracted_lvs_optional_write_vg(lv->vg, removal_lvs, 0))
		return_0;

	/*
	 * Now that any 'REBUILD' or 'RESHAPE_DELTA_DISKS' etc.
	 * has/have made its/their way to the kernel, we must
	 * remove the flag(s) so that the individual devices are
	 * not rebuilt/reshaped/taken over upon every activation.
	 *
	 * Writes and commits metadata if any flags have been reset
	 * and if successful, performs metadata backup.
	 */
	/* FIXME This needs to be done through hooks in the metadata */
	log_debug_metadata("Clearing any flags for %s passed to the kernel.",
			   display_lvname(lv));
	_clear_rebuild_flags(lv, &flags_were_cleared);

	log_debug_metadata("Updating metadata and reloading mappings for %s.",
			   display_lvname(lv));
	if ((r != 2 || flags_were_cleared) && !lv_update_and_reload(lv)) {
		log_error("Update and reload of LV %s failed.",
			  display_lvname(lv));
		return 0;
	}

	return 1;
}

/*
 * Adjust all data sub LVs of lv to mirror
 * or raid name depending on direction
 * adjusting their LV status
 */
enum mirror_raid_conv { MIRROR_TO_RAID1 = 0, RAID1_TO_MIRROR };
static int _adjust_data_lvs(struct logical_volume *lv, enum mirror_raid_conv direction)
{
	uint32_t s;
	char *sublv_name_suffix;
	struct lv_segment *seg = first_seg(lv);
	static struct {
		char type_char;
		uint64_t set_flag;
		uint64_t reset_flag;
	} conv[] = {
		{ 'r', RAID_IMAGE, MIRROR_IMAGE },
		{ 'm', MIRROR_IMAGE, RAID_IMAGE }
	};
	struct logical_volume *dlv;

	for (s = 0; s < seg->area_count; ++s) {
		dlv = seg_lv(seg, s);

		if (!(sublv_name_suffix = first_substring(dlv->name, "_mimage_", "_rimage_", NULL))) {
			log_error(INTERNAL_ERROR "Name %s lags image part.", dlv->name);
			return 0;
		}

		*(sublv_name_suffix + 1) = conv[direction].type_char;
		log_debug_metadata("Data LV renamed to %s.", display_lvname(dlv));

		dlv->status &= ~conv[direction].reset_flag;
		dlv->status |= conv[direction].set_flag;
	}

	return 1;
}

/*
 * General conversion functions
 */

static int _convert_mirror_to_raid1(struct logical_volume *lv,
				    const struct segment_type *new_segtype)
{
	uint32_t s;
	struct lv_segment *seg = first_seg(lv);
	struct lv_list lvl_array[seg->area_count], *lvl;
	struct dm_list meta_lvs;
	struct lv_segment_area *meta_areas;
	char *new_name;

	dm_list_init(&meta_lvs);

	if (!_raid_in_sync(lv)) {
		log_error("Unable to convert %s while it is not in-sync.",
			  display_lvname(lv));
		return 0;
	}

	if (!(meta_areas = dm_pool_zalloc(lv->vg->vgmem,
					  lv_mirror_count(lv) * sizeof(*meta_areas)))) {
		log_error("Failed to allocate meta areas memory.");
		return 0;
	}

	if (!archive(lv->vg))
		return_0;

	for (s = 0; s < seg->area_count; s++) {
		log_debug_metadata("Allocating new metadata LV for %s.",
				   display_lvname(seg_lv(seg, s)));
		if (!_alloc_rmeta_for_lv(seg_lv(seg, s), &(lvl_array[s].lv), NULL)) {
			log_error("Failed to allocate metadata LV for %s in %s.",
				  display_lvname(seg_lv(seg, s)),
				  display_lvname(lv));
			return 0;
		}
		dm_list_add(&meta_lvs, &(lvl_array[s].list));
	}

	log_debug_metadata("Clearing newly allocated metadata LVs.");
	if (!_clear_lvs(&meta_lvs)) {
		log_error("Failed to initialize metadata LVs.");
		return 0;
	}

	if (seg->log_lv) {
		log_debug_metadata("Removing mirror log %s.",
				   display_lvname(seg->log_lv));
		if (!remove_mirror_log(lv->vg->cmd, lv, NULL, 0)) {
			log_error("Failed to remove mirror log.");
			return 0;
		}
	}

	seg->meta_areas = meta_areas;
	s = 0;

	dm_list_iterate_items(lvl, &meta_lvs) {
		log_debug_metadata("Adding %s to %s.",
				   display_lvname(lvl->lv),
				   display_lvname(lv));

		/* Images are known to be in-sync */
		lvl->lv->status &= ~LV_REBUILD;
		first_seg(lvl->lv)->status &= ~LV_REBUILD;
		lv_set_hidden(lvl->lv);

		if (!set_lv_segment_area_lv(seg, s, lvl->lv, 0,
					    lvl->lv->status)) {
			log_error("Failed to add %s to %s.",
				  display_lvname(lvl->lv),
				  display_lvname(lv));
			return 0;
		}
		s++;
	}

	for (s = 0; s < seg->area_count; ++s) {
		if (!(new_name = _generate_raid_name(lv, "rimage", s)))
			return_0;
		log_debug_metadata("Renaming %s to %s.", seg_lv(seg, s)->name, new_name);
		seg_lv(seg, s)->name = new_name;
		seg_lv(seg, s)->status &= ~MIRROR_IMAGE;
		seg_lv(seg, s)->status |= RAID_IMAGE;
	}
	init_mirror_in_sync(1);

	log_debug_metadata("Setting new segtype for %s.", display_lvname(lv));
	seg->segtype = new_segtype;
	lv->status &= ~MIRROR;
	lv->status &= ~MIRRORED;
	lv->status |= RAID;

	if (!lv_update_and_reload(lv))
		return_0;

	return 1;
}

/*
 * Convert lv with "raid1" mapping to "mirror"
 * optionally changing number of data_copies
 * defined by @new_image_count.
 */
static int _convert_raid1_to_mirror(struct logical_volume *lv,
				    const struct segment_type *new_segtype,
				    uint32_t new_image_count,
				    uint32_t new_region_size,
				    struct dm_list *allocate_pvs,
				    int update_and_reload,
				    struct dm_list *removal_lvs)
{
	struct logical_volume *log_lv;
	struct lv_segment *seg = first_seg(lv);

	if (!seg_is_raid1(seg)) {
		log_error(INTERNAL_ERROR "raid1 conversion supported only.");
		return 0;
	}

	if ((new_image_count = new_image_count ?: seg->area_count) < 2) {
		log_error("can't convert %s to fewer than 2 data_copies.", display_lvname(lv));
		return 0;
	}

	if (!_check_max_mirror_devices(new_image_count)) {
		log_error("Unable to convert %s LV %s with %u images to %s.",
			  SEG_TYPE_NAME_RAID1, display_lvname(lv), new_image_count, SEG_TYPE_NAME_MIRROR);
		log_error("At least reduce to the maximum of %u images with \"lvconvert -m%u %s\".",
			  DEFAULT_MIRROR_MAX_IMAGES, DEFAULT_MIRROR_MAX_IMAGES - 1, display_lvname(lv));
		return 0;
	}

	if (!(log_lv = prepare_mirror_log(lv, (new_image_count <= seg->area_count) /* in sync */,
					  new_region_size,
					  allocate_pvs, lv->vg->alloc)))
		return_0; /* TODO remove log_lv on error path */

	/* Change image pair count to requested # of images */
	if (new_image_count != seg->area_count) {
		log_debug_metadata("Changing image count to %u on %s.",
				   new_image_count, display_lvname(lv));
		if (!_lv_raid_change_image_count(lv, new_image_count, allocate_pvs, removal_lvs, 0, 0))
			return_0;
	}

	/* Remove rmeta LVs */
	log_debug_metadata("Extracting and renaming metadata LVs.");
	if (!_extract_image_component_list(seg, RAID_META, 0, removal_lvs))
		return 0;

	seg->meta_areas = NULL;

	/* Rename all data sub LVs from "*_rimage_*" to "*_mimage_*" and set their status */
	log_debug_metadata("Adjust data LVs of %s.", display_lvname(lv));
	if (!_adjust_data_lvs(lv, RAID1_TO_MIRROR))
		return 0;

	seg->segtype = new_segtype;
	seg->region_size = new_region_size;
	lv->status &= ~RAID;
	lv->status |= (MIRROR | MIRRORED);

	if (!attach_mirror_log(first_seg(lv), log_lv))
		return_0;

	return update_and_reload ? _lv_update_reload_fns_reset_eliminate_lvs(lv, removal_lvs) : 1;
}

/*
 * All areas from LV segments are moved to new
 * segments allocated with area_count=1 for data_lvs.
 */
static int _striped_to_raid0_move_segs_to_raid0_lvs(struct logical_volume *lv,
						    struct dm_list *data_lvs)
{
	uint32_t s = 0, le;
	struct logical_volume *dlv;
	struct lv_segment *seg_from, *seg_new;
	struct lv_list *lvl;
	struct segment_type *segtype;
	uint64_t status;

	if (!(segtype = get_segtype_from_string(lv->vg->cmd, SEG_TYPE_NAME_STRIPED)))
		return_0;

	/* Move segment areas across to the N data LVs of the new raid0 LV */
	dm_list_iterate_items(lvl, data_lvs)  {
		dlv = lvl->lv;
		le = 0;
		dm_list_iterate_items(seg_from, &lv->segments) {
			status = RAID | SEG_RAID | (seg_from->status & (LVM_READ | LVM_WRITE));

			/* Allocate a data LV segment with one area for each segment in the striped LV */
			if (!(seg_new = alloc_lv_segment(segtype, dlv,
							 le, seg_from->area_len,
							 status,
							 0 /* stripe_size */, NULL, 1 /* area_count */,
							 seg_from->area_len,
							 0 /* chunk_size */, 0 /* region_size */, 0, NULL)))
				return_0;

			seg_type(seg_new, 0) = AREA_UNASSIGNED;
			dm_list_add(&dlv->segments, &seg_new->list);
			le += seg_from->area_len;

			/* Move the respective area across to our new segment */
			if (!move_lv_segment_area(seg_new, 0, seg_from, s))
				return_0;
		}

		/* Adjust le count and LV size */
		dlv->le_count = le;
		dlv->size = (uint64_t) le * lv->vg->extent_size;
		s++;
	}

	/* Remove the empty segments from the striped LV */
	dm_list_init(&lv->segments);

	return 1;
}

/*
 * Find the smallest area across all the subLV segments at area_le.
 */
static uint32_t _min_sublv_area_at_le(struct lv_segment *seg, uint32_t area_le)
{
	uint32_t s, area_len = ~0U;
	struct lv_segment *seg1;

	/* Find smallest segment of each of the data image LVs at offset area_le */
	for (s = 0; s < seg->area_count; s++) {
		if (!(seg1 = find_seg_by_le(seg_lv(seg, s), area_le))) {
			log_error("Failed to find segment for %s extent " FMTu32 ".",
				  display_lvname(seg_lv(seg, s)), area_le);
			return 0;
		}

		area_len = min(area_len, seg1->len);
	}

	return area_len;
}

/*
 * All areas from lv image component LV's segments are
 * being split at "striped" compatible boundaries and
 * moved to allocated new_segments.
 *
 * The data component LVs are mapped to an
 * error target and linked to removal_lvs for disposal
 * by the caller.
 */
static int _raid0_to_striped_retrieve_segments_and_lvs(struct logical_volume *lv,
						       struct dm_list *removal_lvs)
{
	uint32_t s, area_le, area_len, le;
	struct lv_segment *data_seg = NULL, *seg, *seg_to;
	struct dm_list new_segments;

	seg = first_seg(lv);

	dm_list_init(&new_segments);

	/*
	 * Walk all segments of all data LVs splitting them up at proper boundaries
	 * and create the number of new striped segments we need to move them across
	 */
	area_le = le = 0;
	while (le < lv->le_count) {
		if (!(area_len = _min_sublv_area_at_le(seg, area_le)))
			return_0;
		area_le += area_len;

		if (!_split_area_lvs_segments(seg, area_le) ||
		    !_alloc_and_add_new_striped_segment(lv, le, area_len, &new_segments))
			return_0;

		le = area_le * seg->area_count;
	}

	/* Now move the prepared split areas across to the new segments */
	area_le = 0;
	dm_list_iterate_items(seg_to, &new_segments) {
		for (s = 0; s < seg->area_count; s++) {
			if (!(data_seg = find_seg_by_le(seg_lv(seg, s), area_le))) {
				log_error("Failed to find segment for %s extent " FMTu32 ".",
					  display_lvname(seg_lv(seg, s)), area_le);
				return 0;
			}

			/* Move the respective area across to our new segments area */
			if (!move_lv_segment_area(seg_to, s, data_seg, 0))
				return_0;
		}

		/* Presumes all data LVs have equal size */
		area_le += data_seg->len;
	}

	/* Extract any metadata LVs and the empty data LVs for disposal by the caller */
	if (!_extract_image_component_list(seg, RAID_IMAGE, 0, removal_lvs))
		return_0;

	/*
	 * Remove the one segment holding the image component areas
	 * from the top-level LV, then add the new segments to it
	 */
	dm_list_del(&seg->list);
	dm_list_splice(&lv->segments, &new_segments);

	return 1;
}

/*
 * Convert a RAID0 set to striped
 */
static int _convert_raid0_to_striped(struct logical_volume *lv,
				     int update_and_reload,
				     struct dm_list *removal_lvs)
{
	struct lv_segment *seg = first_seg(lv);

	/* Remove metadata devices */
	if (seg_is_raid0_meta(seg) &&
	    !_raid0_add_or_remove_metadata_lvs(lv, 0 /* update_and_reload */, NULL, removal_lvs))
		return_0;

	/* Move the AREA_PV areas across to new top-level segments of type "striped" */
	if (!_raid0_to_striped_retrieve_segments_and_lvs(lv, removal_lvs)) {
		log_error("Failed to retrieve raid0 segments from %s.",
			  display_lvname(lv));
		return 0;
	}

	lv->status &= ~RAID;

	if (!(seg->segtype = get_segtype_from_string(lv->vg->cmd, SEG_TYPE_NAME_STRIPED)))
		return_0;

	if (update_and_reload) {
		if (!lv_update_and_reload(lv))
			return_0;

		/* Eliminate the residual LVs, write VG, commit it and take a backup */
		return _eliminate_extracted_lvs(lv->vg, removal_lvs);
	} 

	return 1;
}

/*
 * Inserts hidden LVs for all segments and the parallel areas in lv and moves 
 * given segments and areas across.
 *
 * Optionally updates metadata and reloads mappings.
 */
static struct lv_segment *_convert_striped_to_raid0(struct logical_volume *lv,
						    int alloc_metadata_devs,
						    int update_and_reload,
						    struct dm_list *allocate_pvs)
{
	uint32_t area_count, area_len = 0, stripe_size;
	struct lv_segment *seg, *raid0_seg;
	struct segment_type *segtype;
	struct dm_list data_lvs;

	dm_list_iterate_items(seg, &lv->segments)
		area_len += seg->area_len;

	seg = first_seg(lv);
	stripe_size = seg->stripe_size;
	area_count = seg->area_count;

	/* Check for not (yet) supported varying area_count on multi-segment striped LVs */
	if (!lv_has_constant_stripes(lv)) {
		log_error("Cannot convert striped LV %s with varying stripe count to raid0.",
			  display_lvname(lv));
		return NULL;
	}

	if (!is_power_of_2(seg->stripe_size)) {
		log_error("Cannot convert striped LV %s with non-power of 2 stripe size %u.",
			  display_lvname(lv), seg->stripe_size);
		return NULL;
	}

	if (!(segtype = get_segtype_from_flag(lv->vg->cmd, SEG_RAID0)))
		return_NULL;

	/* Allocate empty rimage components */
	dm_list_init(&data_lvs);
	if (!_alloc_image_components(lv, NULL, area_count, NULL, &data_lvs, 0)) {
		log_error("Failed to allocate empty image components for raid0 LV %s.",
			  display_lvname(lv));
		return NULL;
	}

	/* Move the AREA_PV areas across to the new rimage components; empties lv->segments */
	if (!_striped_to_raid0_move_segs_to_raid0_lvs(lv, &data_lvs)) {
		log_error("Failed to insert linear LVs underneath %s.", display_lvname(lv));
		return NULL;
	}

	/*
	 * Allocate single segment to hold the image component
	 * areas based on the first data LVs properties derived
	 * from the first new raid0 LVs first segment
	 */
	seg = first_seg(dm_list_item(dm_list_first(&data_lvs), struct lv_list)->lv);
	if (!(raid0_seg = alloc_lv_segment(segtype, lv,
					   0 /* le */, lv->le_count /* len */,
					   0,
					   stripe_size, NULL /* log_lv */,
					   area_count, area_len,
					   0 /* chunk_size */,
					   0 /* seg->region_size */, 0u /* extents_copied */ ,
					   NULL /* pvmove_source_seg */))) {
		log_error("Failed to allocate new raid0 segment for LV %s.", display_lvname(lv));
		return NULL;
	}

	/* Add new single raid0 segment to emptied LV segments list */
	dm_list_add(&lv->segments, &raid0_seg->list);

	/* Add data LVs to the top-level LVs segment; resets LV_REBUILD flag on them */
	if (!_add_image_component_list(raid0_seg, 1, 0, &data_lvs, 0))
		return NULL;

	lv->status |= RAID;

	/* Allocate metadata LVs if requested */
	if (alloc_metadata_devs && !_raid0_add_or_remove_metadata_lvs(lv, 0, allocate_pvs, NULL))
		return NULL;

	if (update_and_reload && !lv_update_and_reload(lv))
		return NULL;

	return raid0_seg;
}

/***********************************************/

/*
 * Takeover.
 *
 * Change the user's requested segment type to 
 * the appropriate more-refined one for takeover.
 *
 *  raid can takeover striped,raid0 if there is only one stripe zone
 */
#define	ALLOW_NONE		0x0
#define	ALLOW_STRIPES		0x2
#define	ALLOW_STRIPE_SIZE	0x4
#define	ALLOW_REGION_SIZE	0x8

struct possible_takeover_reshape_type {
	/* First 2 have to stay... */
	const uint64_t possible_types;
	const uint32_t options;
	const uint64_t current_types;
	const uint32_t current_areas;
};

struct possible_type {
	/* ..to be handed back via this struct */
	const uint64_t possible_types;
	const uint32_t options;
};

static struct possible_takeover_reshape_type _possible_takeover_reshape_types[] = {
	/* striped -> raid1 */
	{ .current_types  = SEG_STRIPED_TARGET, /* linear, i.e. seg->area_count = 1 */
	  .possible_types = SEG_RAID1,
	  .current_areas = 1,
	  .options = ALLOW_REGION_SIZE },

	{ .current_types  = SEG_STRIPED_TARGET, /* linear, i.e. seg->area_count = 1 */
	  .possible_types = SEG_RAID0|SEG_RAID0_META,
	  .current_areas = 1,
	  .options = ALLOW_STRIPE_SIZE },

	/* raid0* -> raid1 */
	{ .current_types  = SEG_RAID0|SEG_RAID0_META, /* seg->area_count = 1 */
	  .possible_types = SEG_RAID1,
	  .current_areas = 1,
	  .options = ALLOW_REGION_SIZE },

	/* striped,raid0* <-> striped,raid0* */
	{ .current_types  = SEG_STRIPED_TARGET|SEG_RAID0|SEG_RAID0_META,
	  .possible_types = SEG_STRIPED_TARGET|SEG_RAID0|SEG_RAID0_META,
	  .current_areas = ~0U,
	  .options = ALLOW_NONE },

	/* striped,raid0* -> raid4,raid5_n,raid6_n_6,raid10_near */
	{ .current_types  = SEG_STRIPED_TARGET|SEG_RAID0|SEG_RAID0_META,
	  .possible_types = SEG_RAID4|SEG_RAID5_N|SEG_RAID6_N_6|SEG_RAID10_NEAR,
	  .current_areas = ~0U,
	  .options = ALLOW_REGION_SIZE },

	/* raid4,raid5_n,raid6_n_6,raid10_near -> striped/raid0* */
	{ .current_types  = SEG_RAID4|SEG_RAID5_N|SEG_RAID6_N_6|SEG_RAID10_NEAR,
	  .possible_types = SEG_STRIPED_TARGET|SEG_RAID0|SEG_RAID0_META,
	  .current_areas = ~0U,
	  .options = ALLOW_NONE },

	/* raid4,raid5_n,raid6_n_6 <-> raid4,raid5_n,raid6_n_6 */
	{ .current_types  = SEG_RAID4|SEG_RAID5_N|SEG_RAID6_N_6,
	  .possible_types = SEG_RAID4|SEG_RAID5_N|SEG_RAID6_N_6,
	  .current_areas = ~0U,
	  .options = ALLOW_REGION_SIZE },


	/* raid5_ls <-> raid6_ls_6 */
	{ .current_types  = SEG_RAID5_LS|SEG_RAID6_LS_6,
	  .possible_types = SEG_RAID5_LS|SEG_RAID6_LS_6,
	  .current_areas = ~0U,
	  .options = ALLOW_REGION_SIZE },

	/* raid5_rs -> raid6_rs_6 */
	{ .current_types  = SEG_RAID5_RS|SEG_RAID6_RS_6,
	  .possible_types = SEG_RAID5_RS|SEG_RAID6_RS_6,
	  .current_areas = ~0U,
	  .options = ALLOW_REGION_SIZE },

	/* raid5_ls -> raid6_la_6 */
	{ .current_types  = SEG_RAID5_LA|SEG_RAID6_LA_6,
	  .possible_types = SEG_RAID5_LA|SEG_RAID6_LA_6,
	  .current_areas = ~0U,
	  .options = ALLOW_REGION_SIZE },

	/* raid5_ls -> raid6_ra_6 */
	{ .current_types  = SEG_RAID5_RA|SEG_RAID6_RA_6,
	  .possible_types = SEG_RAID5_RA|SEG_RAID6_RA_6,
	  .current_areas = ~0U,
	  .options = ALLOW_REGION_SIZE },

	/* mirror <-> raid1 with arbitrary number of legs */
	{ .current_types  = SEG_MIRROR|SEG_RAID1,
	  .possible_types = SEG_MIRROR|SEG_RAID1,
	  .current_areas = ~0U,
	  .options = ALLOW_REGION_SIZE },

	/* END */
	{ .current_types  = 0 }
};

/*
 * Return possible_type struct for current segment type.
 */
static struct possible_takeover_reshape_type *_get_possible_takeover_reshape_type(const struct lv_segment *seg_from,
										   const struct segment_type *segtype_to,
										   struct possible_type *last_pt)
{
	struct possible_takeover_reshape_type *lpt = (struct possible_takeover_reshape_type *) last_pt;
	struct possible_takeover_reshape_type *pt = lpt ? lpt + 1 : _possible_takeover_reshape_types;

	for ( ; pt->current_types; pt++)
		if ((seg_from->segtype->flags & pt->current_types) &&
		    (segtype_to ? (segtype_to->flags & pt->possible_types) : 1))
			if (seg_from->area_count <= pt->current_areas)
				return pt;

	return NULL;
}

static struct possible_type *_get_possible_type(const struct lv_segment *seg_from,
						const struct segment_type *segtype_to,
						uint32_t new_image_count,
						struct possible_type *last_pt)
{
	return (struct possible_type *) _get_possible_takeover_reshape_type(seg_from, segtype_to, last_pt);
}

/*
 * Return allowed options (--stripes, ...) for conversion from @seg_from -> @seg_to
 */
static int _get_allowed_conversion_options(const struct lv_segment *seg_from,
					   const struct segment_type *segtype_to,
					   uint32_t new_image_count, uint32_t *options)
{
	struct possible_type *pt;

	if ((pt = _get_possible_type(seg_from, segtype_to, new_image_count, NULL))) {
		*options = pt->options;
		return 1;
	}

	return 0;
}

/*
 * Log any possible conversions for @lv
 */
typedef int (*type_flag_fn_t)(uint64_t *processed_segtypes, void *data);

/* Loop through pt->flags calling tfn with argument @data */
static int _process_type_flags(const struct logical_volume *lv, struct possible_type *pt, uint64_t *processed_segtypes, type_flag_fn_t tfn, void *data)
{
	unsigned i;
	uint64_t t;
	const struct lv_segment *seg = first_seg(lv);
	const struct segment_type *segtype;

	for (i = 0; i < 64; i++) {
		t = 1ULL << i;
		if ((t & pt->possible_types) &&
		    !(t & seg->segtype->flags) &&
		     ((segtype = get_segtype_from_flag(lv->vg->cmd, t))))
			if (!tfn(processed_segtypes, data ? : (void *) segtype))
				return 0;
	}

	return 1;
}

/* Callback to increment unsigned  possible conversion types in *data */
static int _count_possible_conversions(uint64_t *processed_segtypes, void *data)
{
	unsigned *possible_conversions = data;

	(*possible_conversions)++;

	return 1;
}

/* Callback to log possible conversion to segment type in *data */
static int _log_possible_conversion(uint64_t *processed_segtypes, void *data)
{
	struct segment_type *segtype = data;

	/* Already processed? */
	if (!(~*processed_segtypes & segtype->flags))
		return 1;

	log_error("  %s", segtype->name);

	*processed_segtypes |= segtype->flags;

	return 1;
}

static const char *_get_segtype_alias(const struct segment_type *segtype)
{
	if (!strcmp(segtype->name, SEG_TYPE_NAME_RAID5))
		return SEG_TYPE_NAME_RAID5_LS;

	if (!strcmp(segtype->name, SEG_TYPE_NAME_RAID6))
		return SEG_TYPE_NAME_RAID6_ZR;

	if (!strcmp(segtype->name, SEG_TYPE_NAME_RAID5_LS))
		return SEG_TYPE_NAME_RAID5;

	if (!strcmp(segtype->name, SEG_TYPE_NAME_RAID6_ZR))
		return SEG_TYPE_NAME_RAID6;

	return "";
}

static int _log_possible_conversion_types(const struct logical_volume *lv, const struct segment_type *new_segtype)
{
	unsigned possible_conversions = 0;
	const struct lv_segment *seg = first_seg(lv);
	struct possible_type *pt = NULL;
	const char *alias;
	uint64_t processed_segtypes = UINT64_C(0);

	/* Count any possible segment types @seg an be directly converted to */
	while ((pt = _get_possible_type(seg, NULL, 0, pt)))
		if (!_process_type_flags(lv, pt, &processed_segtypes, _count_possible_conversions, &possible_conversions))
			return_0;

	if (!possible_conversions)
		log_error("Direct conversion of %s LV %s is not possible.", lvseg_name(seg), display_lvname(lv));
	else {
			alias = _get_segtype_alias(seg->segtype);

			log_error("Converting %s from %s%s%s%s is "
				  "directly possible to the following layout%s:",
				  display_lvname(lv), lvseg_name(seg),
				  *alias ? " (same as " : "", alias, *alias ? ")" : "",
				  possible_conversions > 1 ? "s" : "");

			pt = NULL;

			/* Print any possible segment types @seg can be directly converted to */
			while ((pt = _get_possible_type(seg, NULL, 0, pt)))
				if (!_process_type_flags(lv, pt, &processed_segtypes, _log_possible_conversion, NULL))
					return_0;
	}

	return 0;
}

/***********************************************/

#define TAKEOVER_FN_ARGS			\
	struct logical_volume *lv,		\
	const struct segment_type *new_segtype,	\
	int yes,				\
	int force,				\
	unsigned new_image_count,		\
	unsigned new_data_copies,		\
	const unsigned new_stripes,		\
	uint32_t new_stripe_size,		\
	const uint32_t new_region_size,		\
	struct dm_list *allocate_pvs

typedef int (*takeover_fn_t)(TAKEOVER_FN_ARGS);

/***********************************************/

/*
 * Unsupported takeover functions.
 */
static int _takeover_noop(TAKEOVER_FN_ARGS)
{
	log_error("Logical volume %s is already of requested type %s.",
		  display_lvname(lv), lvseg_name(first_seg(lv)));

	return 0;
}

static int _takeover_unsupported(TAKEOVER_FN_ARGS)
{
	log_error("Converting the segment type for %s from %s to %s is not supported.",
		  display_lvname(lv), lvseg_name(first_seg(lv)),
		  (segtype_is_striped_target(new_segtype) &&
		   (new_stripes == 1)) ? SEG_TYPE_NAME_LINEAR : new_segtype->name);

	if (!_log_possible_conversion_types(lv, new_segtype))
		stack;

	return 0;
}

static int _takeover_unsupported_yet(const struct logical_volume *lv, const unsigned new_stripes, const struct segment_type *new_segtype)
{
	log_error("Converting the segment type for %s from %s to %s is not supported yet.",
		  display_lvname(lv), lvseg_name(first_seg(lv)),
		  (segtype_is_striped_target(new_segtype) &&
		   (new_stripes == 1)) ? SEG_TYPE_NAME_LINEAR : new_segtype->name);

	if (!_log_possible_conversion_types(lv, new_segtype))
		stack;

	return 0;
}

/*
 * Will this particular takeover combination be possible?
 */
static int _takeover_not_possible(takeover_fn_t takeover_fn)
{
	if (takeover_fn == _takeover_noop || takeover_fn == _takeover_unsupported)
		return 1;

	return 0;
}

/***********************************************/

/*
 * Wrapper functions that share conversion code.
 */
static int _raid0_meta_change_wrapper(struct logical_volume *lv,
				     const struct segment_type *new_segtype,
				     uint32_t new_stripes,
				     int yes, int force, int alloc_metadata_devs,
				     struct dm_list *allocate_pvs)
{
	struct dm_list removal_lvs;

	dm_list_init(&removal_lvs);

	if (!_check_restriping(new_stripes, lv))
		return_0;

	if (!archive(lv->vg))
		return_0;

	if (alloc_metadata_devs)
		return _raid0_add_or_remove_metadata_lvs(lv, 1, allocate_pvs, NULL);
	else
		return _raid0_add_or_remove_metadata_lvs(lv, 1, allocate_pvs, &removal_lvs);
}

static int _raid0_to_striped_wrapper(struct logical_volume *lv,
				     const struct segment_type *new_segtype,
				     uint32_t new_stripes,
				     int yes, int force,
				     struct dm_list *allocate_pvs)
{
	struct dm_list removal_lvs;

	dm_list_init(&removal_lvs);

	if (!_check_restriping(new_stripes, lv))
		return_0;

	/* Archive metadata */
	if (!archive(lv->vg))
		return_0;

	/* FIXME update_and_reload is only needed if the LV is already active */
	/* FIXME Some of the validation in here needs moving before the archiving */
	if (!_convert_raid0_to_striped(lv, 1 /* update_and_reload */, &removal_lvs))
		return_0;

	return 1;
}

/* raid1 -> mirror */
static int _raid1_to_mirrored_wrapper(TAKEOVER_FN_ARGS)
{
	struct dm_list removal_lvs;

	dm_list_init(&removal_lvs);

	if (!_raid_in_sync(lv))
		return_0;

	if (!yes && yes_no_prompt("Are you sure you want to convert %s back to the older \"%s\" type? [y/n]: ",
				  display_lvname(lv), SEG_TYPE_NAME_MIRROR) == 'n') {
		log_error("Logical volume %s NOT converted to \"%s\".",
			  display_lvname(lv), SEG_TYPE_NAME_MIRROR);
		return 0;
	}

	/* Archive metadata */
	if (!archive(lv->vg))
		return_0;

	return _convert_raid1_to_mirror(lv, new_segtype, new_image_count, new_region_size,
					allocate_pvs, 1, &removal_lvs);
}

/*
 * HM Helper: (raid0_meta -> raid4)
 *
 * To convert raid0_meta to raid4, which involves shifting the
 * parity device to lv segment area 0 and thus changing MD
 * array roles, detach the MetaLVs and reload as raid0 in
 * order to wipe them then reattach and set back to raid0_meta.
 *
 * Same applies to raid4 <-> raid5.
 */
static int _clear_meta_lvs(struct logical_volume *lv)
{
	uint32_t s;
	struct lv_segment *seg = first_seg(lv);
	struct lv_segment_area *tmp_areas;
	const struct segment_type *tmp_segtype;
	struct dm_list meta_lvs;
	struct lv_list *lvl_array, *lvl;
	int is_raid4_or_5N = seg_is_raid4(seg) || seg_is_raid5_n(seg);

	/* Reject non-raid0_meta/raid4/raid5_n segment types cautiously */
	if (!seg->meta_areas ||
	    (!seg_is_raid0_meta(seg) && !is_raid4_or_5N))
		return_0;

	if (!(lvl_array = dm_pool_alloc(lv->vg->vgmem, seg->area_count * sizeof(*lvl_array))))
		return_0;

	dm_list_init(&meta_lvs);
	tmp_segtype = seg->segtype;
	tmp_areas = seg->meta_areas;

	/* Extract all MetaLVs listing them on @meta_lvs */
	log_debug_metadata("Extracting all MetaLVs of %s to activate as raid0.",
			   display_lvname(lv));
	if (!_extract_image_component_sublist(seg, RAID_META, 0, seg->area_count, &meta_lvs, 0))
		return_0;

	/* Memorize meta areas and segtype to set again after initializing. */
	seg->meta_areas = NULL;

	if (seg_is_raid0_meta(seg) &&
	    !(seg->segtype = get_segtype_from_flag(lv->vg->cmd, SEG_RAID0)))
		return_0;

	if (!lv_update_and_reload(lv))
		return_0;

	/* Note: detached rmeta are NOT renamed */
	/* Grab locks first in case of clustered VG */
	if (vg_is_clustered(lv->vg))
		dm_list_iterate_items(lvl, &meta_lvs)
			if (!activate_lv_excl_local(lv->vg->cmd, lvl->lv))
				return_0;
	/*
	 * Now deactivate the MetaLVs before clearing, so
	 * that _clear_lvs() will activate them visible.
	 */
	log_debug_metadata("Deactivating pulled out MetaLVs of %s before initializing.",
			   display_lvname(lv));
	dm_list_iterate_items(lvl, &meta_lvs)
		if (!deactivate_lv(lv->vg->cmd, lvl->lv))
			return_0;

	log_debug_metadata("Clearing allocated raid0_meta metadata LVs for conversion to raid4.");
	if (!_clear_lvs(&meta_lvs)) {
		log_error("Failed to initialize metadata LVs.");
		return 0;
	}

	/* Set memorized meta areas and raid0_meta segtype */
	seg->meta_areas = tmp_areas;
	seg->segtype = tmp_segtype;

	log_debug_metadata("Adding metadata LVs back into %s.", display_lvname(lv));
	s = 0;
	dm_list_iterate_items(lvl, &meta_lvs) {
		lv_set_hidden(lvl->lv);
		if (!set_lv_segment_area_lv(seg, s++, lvl->lv, 0, RAID_META))
			return 0;
	}

	return 1;
}

/*
 * HM Helper: (raid0* <-> raid4)
 *
 * Rename SubLVs (pairs) allowing to shift names w/o collisions with active ones.
 */
#define	SLV_COUNT	2
static int _rename_area_lvs(struct logical_volume *lv, const char *suffix)
{
	uint32_t s;
	size_t sz = strlen("rimage") + (suffix ? strlen(suffix) : 0) + 1;
	char *sfx[SLV_COUNT] = { NULL, NULL };
	struct lv_segment *seg = first_seg(lv);

	/* Create _generate_raid_name() suffixes w/ or w/o passed in @suffix */
	for (s = 0; s < SLV_COUNT; s++)
		if (!(sfx[s] = dm_pool_alloc(lv->vg->cmd->mem, sz)) ||
		    dm_snprintf(sfx[s], sz, suffix ? "%s%s" : "%s", s ? "rmeta" : "rimage", suffix) < 0)
			return_0;

	/* Change names (temporarily) to be able to shift numerical name suffixes */
	for (s = 0; s < seg->area_count; s++) {
		if (!(seg_lv(seg, s)->name = _generate_raid_name(lv, sfx[0], s)))
			return_0;
		if (seg->meta_areas &&
		    !(seg_metalv(seg, s)->name = _generate_raid_name(lv, sfx[1], s)))
			return_0;
	}

	for (s = 0; s < SLV_COUNT; s++)
		dm_pool_free(lv->vg->cmd->mem, sfx[s]);

	return 1;
}

/*
 * HM Helper: (raid0* <-> raid4)
 *
 * Switch area LVs in lv segment @seg indexed by @s1 and @s2
 */
static void _switch_area_lvs(struct lv_segment *seg, uint32_t s1, uint32_t s2)
{
	struct logical_volume *lvt;

	lvt = seg_lv(seg, s1);
	seg_lv(seg, s1) = seg_lv(seg, s2);
	seg_lv(seg, s2) = lvt;

	/* Be cautious */
	if (seg->meta_areas) {
		lvt = seg_metalv(seg, s1);
		seg_metalv(seg, s1) = seg_metalv(seg, s2);
		seg_metalv(seg, s2) = lvt;
	}
}

/*
 * HM Helper:
 *
 * shift range of area LVs in @seg in range [ @s1, @s2 ] up if @s1 < @s2,
 * else down  bubbling the parity SubLVs up/down whilst shifting.
 */
static void _shift_area_lvs(struct lv_segment *seg, uint32_t s1, uint32_t s2)
{
	uint32_t s;

	if (s1 < s2)
		/* Forward shift n+1 -> n */
		for (s = s1; s < s2; s++)
			_switch_area_lvs(seg, s, s + 1);
	else
		/* Reverse shift n-1 -> n */
		for (s = s1; s > s2; s--)
			_switch_area_lvs(seg, s, s - 1);
}

/*
 * Switch position of first and last area lv within
 * @lv to move parity SubLVs from end to end.
 *
 * Direction depends on segment type raid4 / raid0_meta.
 */
static int _shift_parity_dev(struct lv_segment *seg)
{
	if (seg_is_raid0_meta(seg) || seg_is_raid5_n(seg))
		_shift_area_lvs(seg, seg->area_count - 1, 0);
	else if (seg_is_raid4(seg))
		_shift_area_lvs(seg, 0, seg->area_count - 1);
	else
		return 0;

	return 1;
}

/* raid456 -> raid0* / striped */
static int _raid45_to_raid54_wrapper(TAKEOVER_FN_ARGS);
static int _raid45610_to_raid0_or_striped_wrapper(TAKEOVER_FN_ARGS)
{
	int rename_sublvs = 0;
	struct lv_segment *seg = first_seg(lv);
	struct dm_list removal_lvs;
	uint32_t region_size = seg->region_size;

	dm_list_init(&removal_lvs);

	/* Necessary when converting to raid0/striped w/o redundancy. */
	if (!_raid_in_sync(lv)) {
		log_error("Unable to convert %s while it is not in-sync.",
			  display_lvname(lv));
		return 0;
	}

	if (!yes && yes_no_prompt("Are you sure you want to convert \"%s\" LV %s to \"%s\" "
				  "type losing %s resilience? [y/n]: ",
				  lvseg_name(seg), display_lvname(lv), new_segtype->name,
				  segtype_is_striped(new_segtype) ? "all" : "some") == 'n') {
		log_error("Logical volume %s NOT converted to \"%s\"",
			  display_lvname(lv), new_segtype->name);
		return 0;
	}

	/* Archive metadata */
	if (!archive(lv->vg))
		return_0;

	/*
	 * raid4 (which actually gets mapped to raid5/dedicated first parity disk)
	 * needs shifting of SubLVs to move the parity SubLV pair in the first area
	 * to the last one before conversion to raid0[_meta]/striped to allow for
	 * SubLV removal from the end of the areas arrays.
	 */
	if (seg_is_raid4(seg)) {
		/* Shift parity SubLV pair "PDD..." -> "DD...P" to be able to remove it off the end */
		if (!_shift_parity_dev(seg))
			return 0;

		if (segtype_is_any_raid0(new_segtype) &&
		    !(rename_sublvs = _rename_area_lvs(lv, "_"))) {
			log_error("Failed to rename %s LV %s MetaLVs.", lvseg_name(seg), display_lvname(lv));
			return 0;
		}
	} else if (seg_is_raid10_near(seg)) {
		log_debug_metadata("Reordering areas for raid10 -> raid0 takeover");
		if (!_reorder_raid10_near_seg_areas(seg, reorder_from_raid10_near))
			return 0;
	}

	/* Remove meta and data LVs requested */
	if (!_lv_raid_change_image_count(lv, new_image_count, allocate_pvs, &removal_lvs, 0, 0))
		return 0;

	/* FIXME Hard-coded raid4/5/6 to striped/raid0 */
	if (segtype_is_striped_target(new_segtype) || segtype_is_any_raid0(new_segtype)) {
		seg->area_len = seg->extents_copied = seg->area_len / seg->area_count;
		if (!(seg->segtype = get_segtype_from_flag(lv->vg->cmd, SEG_RAID0_META)))
			return_0;

		region_size = 0;
	}

	if (segtype_is_striped_target(new_segtype)) {
		if (!_convert_raid0_to_striped(lv, 0, &removal_lvs))
			return_0;
	} else if (segtype_is_raid0(new_segtype) &&
		   !_raid0_add_or_remove_metadata_lvs(lv, 0 /* update_and_reload */, allocate_pvs, &removal_lvs))
		return_0;

	if (segtype_is_raid4(new_segtype)) {
		if (!(seg->segtype = get_segtype_from_flag(lv->vg->cmd, SEG_RAID5_N)))
			return_0;
	} else
		seg->segtype = new_segtype;

	seg->region_size = new_region_size ?: region_size;

	if (!_lv_update_reload_fns_reset_eliminate_lvs(lv, &removal_lvs))
		return_0;

	if (rename_sublvs) {
		if (!_rename_area_lvs(lv, NULL)) {
			log_error("Failed to rename %s LV %s MetaLVs.", lvseg_name(seg), display_lvname(lv));
			return 0;
		}
		if (!lv_update_and_reload(lv))
			return_0;
	}

	if (segtype_is_raid4(new_segtype))
		return _raid45_to_raid54_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count,
						 1 /* data_copies */, 0, 0, 0, allocate_pvs);

	return 1;
}

/*
 * raid4 <-> raid5_n helper
 *
 * On conversions between raid4 and raid5_n, the parity SubLVs need
 * to be switched between beginning and end of the segment areas.
 *
 * The metadata devices reflect the previous positions within the RaidLV,
 * thus need to be cleared in order to allow the kernel to start the new
 * mapping and recreate metadata with the proper new position stored.
 */
static int _raid45_to_raid54_wrapper(TAKEOVER_FN_ARGS)
{
	struct lv_segment *seg = first_seg(lv);
	struct dm_list removal_lvs;
	uint32_t region_size = seg->region_size;

	dm_list_init(&removal_lvs);

	if (!(seg_is_raid4(seg) && segtype_is_raid5_n(new_segtype)) &&
	    !(seg_is_raid5_n(seg) && segtype_is_raid4(new_segtype))) {
		log_error("LV %s has to be of type raid4 or raid5_n to allow for this conversion.",
			  display_lvname(lv));
		return 0;
	}


	/* Necessary when convering to raid0/striped w/o redundancy. */
	if (!_raid_in_sync(lv)) {
		log_error("Unable to convert %s while it is not in-sync.",
			  display_lvname(lv));
		return 0;
	}

	log_debug_metadata("Converting LV %s from %s to %s.", display_lvname(lv),
			   (seg_is_raid4(seg) ? SEG_TYPE_NAME_RAID4 : SEG_TYPE_NAME_RAID5_N),
			   (seg_is_raid4(seg) ? SEG_TYPE_NAME_RAID5_N : SEG_TYPE_NAME_RAID4));

	/* Archive metadata */
	if (!archive(lv->vg))
		return_0;

	if (!_rename_area_lvs(lv, "_")) {
		log_error("Failed to rename %s LV %s MetaLVs.", lvseg_name(seg), display_lvname(lv));
		return 0;
	}

	if (!_clear_meta_lvs(lv))
		return_0;

	/* Shift parity SubLV pair "PDD..." <-> "DD...P" on raid4 <-> raid5_n conversion */
	if( !_shift_parity_dev(seg))
		return 0;

	/* Don't resync */
	init_mirror_in_sync(1);
	seg->region_size = new_region_size ?: region_size;
	seg->segtype = new_segtype;

	if (!_lv_update_reload_fns_reset_eliminate_lvs(lv, &removal_lvs))
		return_0;

	init_mirror_in_sync(0);

	if (!_rename_area_lvs(lv, NULL)) {
		log_error("Failed to rename %s LV %s MetaLVs.", lvseg_name(seg), display_lvname(lv));
		return 0;
	}
	if (!lv_update_and_reload(lv))
		return_0;

	return 1;
}

static int _striped_to_raid0_wrapper(struct logical_volume *lv,
				     const struct segment_type *new_segtype,
				     uint32_t new_stripes,
				     int yes, int force, int alloc_metadata_devs,
				     struct dm_list *allocate_pvs)
{
	if (!_check_restriping(new_stripes, lv))
		return_0;

	/* Archive metadata */
	if (!archive(lv->vg))
		return_0;

	/* FIXME update_and_reload is only needed if the LV is already active */
	/* FIXME Some of the validation in here needs moving before the archiving */
	if (!_convert_striped_to_raid0(lv, alloc_metadata_devs, 1 /* update_and_reload */, allocate_pvs))
		return_0;

	return 1;
}

/* Helper: striped/raid0* -> raid4/5/6/10, raid45 -> raid6 wrapper */
static int _striped_or_raid0_to_raid45610_wrapper(TAKEOVER_FN_ARGS)
{
	uint32_t extents_copied, region_size, seg_len, stripe_size;
	struct lv_segment *seg = first_seg(lv);
	struct dm_list removal_lvs;

	dm_list_init(&removal_lvs);

	if (new_data_copies > new_image_count) {
		log_error("N number of data_copies \"--mirrors N-1\" may not be larger than number of stripes.");
		return 0;
	}

	if (new_stripes && new_stripes != seg->area_count) {
		log_error("Can't restripe LV %s during conversion.", display_lvname(lv));
		return 0;
	}

	/* Archive metadata */
	if (!archive(lv->vg))
		return_0;

	/* This helper can be used to convert from striped/raid0* -> raid10 too */
	if (seg_is_striped_target(seg)) {
		log_debug_metadata("Converting LV %s from %s to %s.",
				   display_lvname(lv), SEG_TYPE_NAME_STRIPED, SEG_TYPE_NAME_RAID0);
		if (!(seg = _convert_striped_to_raid0(lv, 1 /* alloc_metadata_devs */, 0 /* update_and_reload */, allocate_pvs)))
			return_0;
	}

	/* Add metadata LVs */
	if (seg_is_raid0(seg)) {
		log_debug_metadata("Adding metadata LVs to %s.", display_lvname(lv));
		if (!_raid0_add_or_remove_metadata_lvs(lv, 1 /* update_and_reload */, allocate_pvs, NULL))
			return 0;
	/* raid0_meta -> raid4 needs clearing of MetaLVs in order to avoid raid disk role change issues in the kernel */
	} else if (segtype_is_raid4(new_segtype) &&
		   !_clear_meta_lvs(lv))
		return_0;


	/* Add the additional component LV pairs */
	log_debug_metadata("Adding %" PRIu32 " component LV pair(s) to %s.",
			   new_image_count - lv_raid_image_count(lv),
			   display_lvname(lv));
	extents_copied = seg->extents_copied;
	region_size = seg->region_size;
	seg_len = seg->len;
	stripe_size = seg->stripe_size;

	if (seg_is_raid4(seg) || seg_is_any_raid5(seg)) {
		if (!(seg->segtype = get_segtype_from_flag(lv->vg->cmd, SEG_RAID0_META)))
			return_0;
		seg->area_len = seg_lv(seg, 0)->le_count;
		lv->le_count = seg->len = seg->area_len * seg->area_count;
		seg->extents_copied = seg->region_size = 0;
	}

	if (!_lv_raid_change_image_count(lv, new_image_count, allocate_pvs, NULL, 0, 1))
		return 0;

	if (segtype_is_raid4(new_segtype) &&
	    (!_shift_parity_dev(seg) ||
	     !_rename_area_lvs(lv, "_"))) {
		log_error("Can't convert %s to %s.", display_lvname(lv), new_segtype->name);
		return 0;
	} else if (segtype_is_raid10_near(new_segtype)) {
		log_debug_metadata("Reordering areas for raid0 -> raid10 takeover");
		if (!_reorder_raid10_near_seg_areas(seg, reorder_to_raid10_near))
			return 0;
	}

	seg->segtype = new_segtype;
	seg->region_size = new_region_size ?: region_size;

	/* FIXME Hard-coded raid0 to raid4/5/6 */
	seg->stripe_size = stripe_size;
	lv->le_count = seg->len = seg->area_len = seg_len;
	seg->extents_copied = extents_copied;

	_check_and_adjust_region_size(lv);

	log_debug_metadata("Updating VG metadata and reloading %s LV %s.",
			   lvseg_name(seg), display_lvname(lv));
	if (!_lv_update_reload_fns_reset_eliminate_lvs(lv, NULL))
		return_0;

	if (segtype_is_raid4(new_segtype)) {
		/* We had to rename SubLVs because of collision free shifting, rename back... */
		if (!_rename_area_lvs(lv, NULL))
			return_0;
		if (!lv_update_and_reload(lv))
			return_0;
	}

	return 1;
}

/************************************************/

/*
 * Customised takeover functions
 */
static int _takeover_from_linear_to_raid0(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_linear_to_raid1(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_linear_to_raid10(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_linear_to_raid45(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_mirrored_to_raid0(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_mirrored_to_raid0_meta(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_mirrored_to_raid1(TAKEOVER_FN_ARGS)
{
	first_seg(lv)->region_size = new_region_size;

	return _convert_mirror_to_raid1(lv, new_segtype);
}

static int _takeover_from_mirrored_to_raid10(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_mirrored_to_raid45(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid0_to_linear(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid0_to_mirrored(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid0_to_raid0_meta(TAKEOVER_FN_ARGS)
{
	if (!_raid0_meta_change_wrapper(lv, new_segtype, new_stripes, yes, force, 1, allocate_pvs))
		return_0;

	return 1;
}

static int _takeover_from_raid0_to_raid1(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid0_to_raid10(TAKEOVER_FN_ARGS)
{
	return _striped_or_raid0_to_raid45610_wrapper(lv, new_segtype, yes, force,
						      first_seg(lv)->area_count * 2 /* new_image_count */,
						      2 /* data_copies */, 0, 0, new_region_size, allocate_pvs);
}

static int _takeover_from_raid0_to_raid45(TAKEOVER_FN_ARGS)
{
	return _striped_or_raid0_to_raid45610_wrapper(lv, new_segtype, yes, force,
						      first_seg(lv)->area_count + 1 /* new_image_count */,
						      2 /* data_copies */, 0, 0, new_region_size, allocate_pvs);
}

static int _takeover_from_raid0_to_raid6(TAKEOVER_FN_ARGS)
{
	return _striped_or_raid0_to_raid45610_wrapper(lv, new_segtype, yes, force,
						      first_seg(lv)->area_count + 2 /* new_image_count */,
						      3 /* data_copies */, 0, 0, new_region_size, allocate_pvs);
}

static int _takeover_from_raid0_to_striped(TAKEOVER_FN_ARGS)
{
	if (!_raid0_to_striped_wrapper(lv, new_segtype, new_stripes, yes, force, allocate_pvs))
		return_0;

	return 1;
}

static int _takeover_from_raid0_meta_to_linear(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid0_meta_to_mirrored(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid0_meta_to_raid0(TAKEOVER_FN_ARGS)
{
	if (!_raid0_meta_change_wrapper(lv, new_segtype, new_stripes, yes, force, 0, allocate_pvs))
		return_0;

	return 1;
}

static int _takeover_from_raid0_meta_to_raid1(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid0_meta_to_raid10(TAKEOVER_FN_ARGS)
{
	return _striped_or_raid0_to_raid45610_wrapper(lv, new_segtype, yes, force,
						      first_seg(lv)->area_count * 2 /* new_image_count */,
						      2 /* data_copies */, 0, 0, new_region_size, allocate_pvs);
}

static int _takeover_from_raid0_meta_to_raid45(TAKEOVER_FN_ARGS)
{
	return _striped_or_raid0_to_raid45610_wrapper(lv, new_segtype, yes, force,
						      first_seg(lv)->area_count + 1 /* new_image_count */,
						      2 /* data_copies */, 0, 0, new_region_size, allocate_pvs);
}

static int _takeover_from_raid0_meta_to_raid6(TAKEOVER_FN_ARGS)
{
	return _striped_or_raid0_to_raid45610_wrapper(lv, new_segtype, yes, force,
						      first_seg(lv)->area_count + 2 /* new_image_count */,
						      3 /* data_copies */, 0, 0, new_region_size, allocate_pvs);
}

static int _takeover_from_raid0_meta_to_striped(TAKEOVER_FN_ARGS)
{
	if (!_raid0_to_striped_wrapper(lv, new_segtype, new_stripes, yes, force, allocate_pvs))
		return_0;

	return 1;
}

static int _takeover_from_raid1_to_linear(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid1_to_mirrored(TAKEOVER_FN_ARGS)
{
	return _raid1_to_mirrored_wrapper(lv, new_segtype, yes, force, new_image_count, new_data_copies, new_stripes, new_stripe_size, new_region_size, allocate_pvs);
}

static int _takeover_from_raid1_to_raid0(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid1_to_raid0_meta(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid1_to_raid1(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid1_to_raid10(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid1_to_raid45(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid1_to_striped(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid45_to_linear(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid45_to_mirrored(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid45_to_raid0(TAKEOVER_FN_ARGS)
{
	return _raid45610_to_raid0_or_striped_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count - 1, 1 /* data_copies */, 0, 0, 0, allocate_pvs);
}

static int _takeover_from_raid45_to_raid0_meta(TAKEOVER_FN_ARGS)
{
	return _raid45610_to_raid0_or_striped_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count - 1, 1 /* data_copies */, 0, 0, 0, allocate_pvs);
}

static int _takeover_from_raid45_to_raid1(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid45_to_raid54(TAKEOVER_FN_ARGS)
{
	return _raid45_to_raid54_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count,
					 2 /* data_copies */, 0, 0, new_region_size, allocate_pvs);
}

static int _takeover_from_raid45_to_raid6(TAKEOVER_FN_ARGS)
{
	if (seg_is_raid4(first_seg(lv))) {
		struct segment_type *segtype = get_segtype_from_flag(lv->vg->cmd, SEG_RAID5_N);

		if (!segtype ||
		    !_raid45_to_raid54_wrapper(lv, segtype, yes, force, first_seg(lv)->area_count,
					       1 /* data_copies */, 0, 0, 0, allocate_pvs))
			return 0;
	}
	return _striped_or_raid0_to_raid45610_wrapper(lv, new_segtype, yes, force,
						      first_seg(lv)->area_count + 1 /* new_image_count */,
						      3 /* data_copies */, 0, 0, new_region_size, allocate_pvs);
}

static int _takeover_from_raid45_to_striped(TAKEOVER_FN_ARGS)
{
	return _raid45610_to_raid0_or_striped_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count - 1, 1 /* data_copies */, 0, 0, 0, allocate_pvs);
}

static int _takeover_from_raid6_to_raid0(TAKEOVER_FN_ARGS)
{
	return _raid45610_to_raid0_or_striped_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count - 2,
						    1 /* data_copies */, 0, 0, 0, allocate_pvs);
}

static int _takeover_from_raid6_to_raid0_meta(TAKEOVER_FN_ARGS)
{
	return _raid45610_to_raid0_or_striped_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count - 2,
						    1 /* data_copies */, 0, 0, 0, allocate_pvs);
}

static int _takeover_from_raid6_to_raid45(TAKEOVER_FN_ARGS)
{
	return _raid45610_to_raid0_or_striped_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count - 1,
						    2 /* data_copies */, 0, 0, 0, allocate_pvs);
}

static int _takeover_from_raid6_to_striped(TAKEOVER_FN_ARGS)
{
	return _raid45610_to_raid0_or_striped_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count - 2,
						    2 /* data_copies */, 0, 0, 0, allocate_pvs);
}

static int _takeover_from_striped_to_raid0(TAKEOVER_FN_ARGS)
{
	if (!_striped_to_raid0_wrapper(lv, new_segtype, new_stripes, yes, force, 0, allocate_pvs))
		return_0;

	return 1;
}

static int _takeover_from_striped_to_raid01(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_striped_to_raid0_meta(TAKEOVER_FN_ARGS)
{
	if (!_striped_to_raid0_wrapper(lv, new_segtype, new_stripes, yes, force, 1, allocate_pvs))
		return_0;

	return 1;
}

static int _takeover_from_striped_to_raid10(TAKEOVER_FN_ARGS)
{
	return _striped_or_raid0_to_raid45610_wrapper(lv, new_segtype, yes, force,
						      first_seg(lv)->area_count * 2 /* new_image_count */,
						      2 /* data_copies */, 0, 0, new_region_size, allocate_pvs);
}

static int _takeover_from_striped_to_raid45(TAKEOVER_FN_ARGS)
{
	return _striped_or_raid0_to_raid45610_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count + 1,
						      2 /* data_copies*/, 0, 0, new_region_size, allocate_pvs);
}

static int _takeover_from_striped_to_raid6(TAKEOVER_FN_ARGS)
{
	return _striped_or_raid0_to_raid45610_wrapper(lv, new_segtype, yes, force,
						      first_seg(lv)->area_count + 2 /* new_image_count */,
						      3 /* data_copies */, 0, 0, new_region_size, allocate_pvs);
}

/*
 * Only if we decide to support raid01 at all.
 
static int _takeover_from_raid01_to_raid01(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid01_to_raid10(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid01_to_striped(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}
*/

static int _takeover_from_raid10_to_linear(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid10_to_mirrored(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

static int _takeover_from_raid10_to_raid0(TAKEOVER_FN_ARGS)
{
	return _raid45610_to_raid0_or_striped_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count / 2,
						      1 /* data_copies */, 0, 0, 0, allocate_pvs);
}

/*
 * Only if we decide to support raid01 at all.
static int _takeover_from_raid10_to_raid01(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}
*/

static int _takeover_from_raid10_to_raid0_meta(TAKEOVER_FN_ARGS)
{
	return _raid45610_to_raid0_or_striped_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count / 2,
						      1 /* data_copies */, 0, 0, 0, allocate_pvs);
}

static int _takeover_from_raid10_to_raid1(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}

/*
 * This'd be a reshape, not a takeover.
 *
static int _takeover_from_raid10_to_raid10(TAKEOVER_FN_ARGS)
{
	return _takeover_unsupported_yet(lv, new_stripes, new_segtype);
}
*/

static int _takeover_from_raid10_to_striped(TAKEOVER_FN_ARGS)
{
	return _raid45610_to_raid0_or_striped_wrapper(lv, new_segtype, yes, force, first_seg(lv)->area_count / 2,
						      1 /* data_copies */, 0, 0, 0, allocate_pvs);
}

/*
 * Import takeover matrix.
 */
#include "takeover_matrix.h"

static unsigned _segtype_ix(const struct segment_type *segtype, uint32_t area_count)
{
	int i = 2, j;

	/* Linear special case */
	if (segtype_is_striped_target(segtype)) {
		if (area_count == 1)
			return 0;	/* linear */
		return 1;	/* striped */
	}

	while ((j = _segtype_index[i++]))
		if (segtype->flags & j)
			break;

	return (i - 1);
}

/* Call appropriate takeover function */
static takeover_fn_t _get_takeover_fn(const struct lv_segment *seg, const struct segment_type *new_segtype, unsigned new_image_count)
{
	return _takeover_fns[_segtype_ix(seg->segtype, seg->area_count)][_segtype_ix(new_segtype, new_image_count)];
}

/* Number of data (not parity) rimages */
static uint32_t _data_rimages_count(const struct lv_segment *seg, const uint32_t total_rimages)
{
	return total_rimages - seg->segtype->parity_devs;
}

/*
 * Determine whether data_copies, stripes, stripe_size are
 * possible for conversion from seg_from to new_segtype.
 */
static int _log_prohibited_option(const struct lv_segment *seg_from,
				  const struct segment_type *new_segtype,
				  const char *opt_str)
{
	if (seg_from->segtype == new_segtype)
		log_error("%s not allowed when converting %s LV %s.",
			  opt_str, lvseg_name(seg_from), display_lvname(seg_from->lv));
	else
		log_error("%s not allowed for LV %s when converting from %s to %s.",
			  opt_str, display_lvname(seg_from->lv), lvseg_name(seg_from), new_segtype->name);

	return 1;
}

/* Change segtype for raid4 <-> raid5 <-> raid6 takeover where necessary. */
static int _set_convenient_raid456_segtype_to(const struct lv_segment *seg_from,
					      const struct segment_type **segtype)
{
	size_t len = min(strlen((*segtype)->name), strlen(lvseg_name(seg_from)));
	const struct segment_type *segtype_sav = *segtype;

	/* Bail out if same RAID level is requested. */
	if (!strncmp((*segtype)->name, lvseg_name(seg_from), len))
		return 1;

	/* Striped/raid0 -> raid5/6 */
	if (seg_is_striped(seg_from) || seg_is_any_raid0(seg_from)) {
		/* If this is any raid5 conversion request -> enforce raid5_n, because we convert from striped */
		if (segtype_is_any_raid5(*segtype) &&
		    !segtype_is_raid5_n(*segtype)) {
			if (!(*segtype = get_segtype_from_flag(seg_from->lv->vg->cmd, SEG_RAID5_N)))
				return_0;
			goto replaced;

		/* If this is any raid6 conversion request -> enforce raid6_n_6, because we convert from striped */
		} else if (segtype_is_any_raid6(*segtype) &&
			   !segtype_is_raid6_n_6(*segtype)) {
			if (!(*segtype = get_segtype_from_flag(seg_from->lv->vg->cmd, SEG_RAID6_N_6)))
				return_0;
			goto replaced;
		}

	/* raid4 -> raid5_n */
	} else if (seg_is_raid4(seg_from) &&
		   segtype_is_any_raid5(*segtype)) {
		if (!(*segtype = get_segtype_from_flag(seg_from->lv->vg->cmd, SEG_RAID5_N)))
			return_0;
		goto replaced;

	/* raid4/raid5_n -> striped/raid0/raid6 */
	} else if ((seg_is_raid4(seg_from) || seg_is_raid5_n(seg_from)) &&
		   !segtype_is_striped(*segtype) &&
		   !segtype_is_any_raid0(*segtype) &&
		   !segtype_is_raid4(*segtype) &&
		   !segtype_is_raid5_n(*segtype) &&
		   !segtype_is_raid6_n_6(*segtype)) {
		if (!(*segtype = get_segtype_from_flag(seg_from->lv->vg->cmd, SEG_RAID6_N_6)))
			return_0;
		goto replaced;

	/* ... and raid6 -> striped/raid0/raid4/raid5_n */
	} else if (seg_is_raid6_n_6(seg_from) &&
		   !segtype_is_striped(*segtype) &&
		   !segtype_is_any_raid0(*segtype) &&
		   !segtype_is_raid4(*segtype) &&
		   !segtype_is_raid5_n(*segtype)) {
		if (!(*segtype = get_segtype_from_flag(seg_from->lv->vg->cmd, SEG_RAID5_N)))
			return_0;
		goto replaced;
	}

	return 1;

replaced:
	log_warn("Replaced LV type %s with possible type %s.",
		 segtype_sav->name, (*segtype)->name);
	return 1;
}

/*
 * HM Helper:
 *
 * Change region size on raid @lv to @region_size if
 * different from current region_size and adjusted region size
 */
static int _region_size_change_requested(struct logical_volume *lv, int yes, const uint32_t region_size)
{
	uint32_t old_region_size;
	const char *seg_region_size_str;
	struct lv_segment *seg = first_seg(lv);

	/* Caller should ensure this */
	if (!region_size)
		return_0;

	/* CLI validation provides the check but be caucious... */
	if (seg_is_any_raid0(seg))
		return_0;

	if (region_size == seg->region_size) {
		log_print_unless_silent("Region size wouldn't change on %s LV %s.",
					lvseg_name(seg), display_lvname(lv));
		return 1;
	}

	if (region_size * 8 > lv->size) {
		log_error("Requested region size too large for LV %s size %s.",
			  display_lvname(lv), display_size(lv->vg->cmd, lv->size));
		return 0;
	}

	if (region_size < seg->stripe_size) {
		log_error("Requested region size for LV %s is smaller than stripe size.",
			  display_lvname(lv));
		return 0;
	}

	if (!_raid_in_sync(lv)) {
		log_error("Unable to change region size on %s LV %s while it is not in-sync.",
			  lvseg_name(seg), display_lvname(lv));
		return 0;
	}

	old_region_size = seg->region_size;
	seg_region_size_str = display_size(lv->vg->cmd, region_size);

	if (!yes && yes_no_prompt("Do you really want to change the region_size %s of LV %s to %s? [y/n]: ",
				  display_size(lv->vg->cmd, old_region_size),
				  display_lvname(lv), seg_region_size_str) == 'n') {
		log_error("Logical volume %s NOT converted", display_lvname(lv));
		return 0;
	}

	seg->region_size = region_size;
	_check_and_adjust_region_size(lv);

	if (seg->region_size == old_region_size) {
		log_warn("Region size on %s did not change due to adjustment.",
			 display_lvname(lv));
		return 1;
	}

	/* Check for new region size causing bitmap to still fit metadata image LV */
	if (seg->meta_areas && seg_metatype(seg, 0) == AREA_LV && seg_metalv(seg, 0)->le_count <
	    _raid_rmeta_extents(lv->vg->cmd, lv->le_count, seg->region_size, lv->vg->extent_size)) {
		log_error("Region size %s on %s is too small for metadata LV size.",
			  seg_region_size_str, display_lvname(lv));
		return 0;
	}

	if (!lv_update_and_reload_origin(lv))
		return_0;

	log_warn("Changed region size on RAID LV %s to %s.",
		 display_lvname(lv), seg_region_size_str);
	return 1;
}

/* Check allowed conversion from seg_from to *segtype_to */
static int _conversion_options_allowed(const struct lv_segment *seg_from,
				       const struct segment_type **segtype_to,
				       uint32_t new_image_count,
				       int new_data_copies, int new_region_size,
				       int stripes, unsigned new_stripe_size_supplied)
{
	int r = 1;
	uint32_t opts;

	if (!new_image_count && !_set_convenient_raid456_segtype_to(seg_from, segtype_to))
		return_0;

	if (!_get_allowed_conversion_options(seg_from, *segtype_to, new_image_count, &opts)) {
		log_error("Unable to convert LV %s from %s to %s.",
			  display_lvname(seg_from->lv), lvseg_name(seg_from), (*segtype_to)->name);
		return 0;
	}

	if (stripes > 1 && !(opts & ALLOW_STRIPES)) {
		if (!_log_prohibited_option(seg_from, *segtype_to, "--stripes"))
			stack;
		r = 0;
	}

	if (new_stripe_size_supplied && !(opts & ALLOW_STRIPE_SIZE)) {
		if (!_log_prohibited_option(seg_from, *segtype_to, "-I/--stripesize"))
			stack;
		r = 0;
	}

	if (new_region_size && !(opts & ALLOW_REGION_SIZE)) {
		if (!_log_prohibited_option(seg_from, *segtype_to, "-R/--regionsize"))
			stack;
		r = 0;
	}

	return r;
}

/*
 * lv_raid_convert
 *
 * Convert lv from one RAID type (or striped/mirror segtype) to new_segtype,
 * or add/remove LVs to/from a RAID LV.
 *
 * Non dm-raid changes e.g. mirror/striped functions are also called from here.
 *
 * Takeover is defined as a switch from one raid level to another, potentially
 * involving the addition of one or more image component pairs and rebuild.
 */
int lv_raid_convert(struct logical_volume *lv,
		    const struct segment_type *new_segtype,
		    int yes, int force,
		    const unsigned new_stripes,
		    const unsigned new_stripe_size_supplied,
		    const unsigned new_stripe_size,
		    const uint32_t new_region_size,
		    struct dm_list *allocate_pvs)
{
	struct lv_segment *seg = first_seg(lv);
	uint32_t stripes, stripe_size;
	uint32_t new_image_count = seg->area_count;
	uint32_t region_size = new_region_size;
	takeover_fn_t takeover_fn;

	if (!new_segtype) {
		log_error(INTERNAL_ERROR "New segtype not specified.");
		return 0;
	}

	stripes = new_stripes ? : _data_rimages_count(seg, seg->area_count);

	/* FIXME Ensure caller does *not* set wrong default value! */
	/* Define new stripe size if not passed in */
	stripe_size = new_stripe_size ? : seg->stripe_size;

	if (segtype_is_striped(new_segtype))
		new_image_count = stripes;

	if (segtype_is_raid(new_segtype) && !_check_max_raid_devices(new_image_count))
		return_0;

	/* Change RAID region size */
	/*
	 * FIXME: workaround with new_region_size until the
	 *	  cli validation patches got merged when we'll change
	 *	  the API to have new_region_size_supplied to check for.
	 */
	if (new_region_size) {
	       if (new_segtype == seg->segtype &&
	           new_region_size != seg->region_size &&
		   seg_is_raid(seg) && !seg_is_any_raid0(seg))
			return _region_size_change_requested(lv, yes, new_region_size);
	} else
		region_size = seg->region_size ? : get_default_region_size(lv->vg->cmd);

	/*
	 * Check acceptible options mirrors, region_size,
	 * stripes and/or stripe_size have been provided.
	 */
	if (!_conversion_options_allowed(seg, &new_segtype, 0 /* Takeover */, 0 /*new_data_copies*/, new_region_size,
					 new_stripes, new_stripe_size_supplied))
		return _log_possible_conversion_types(lv, new_segtype);
	
	takeover_fn = _get_takeover_fn(first_seg(lv), new_segtype, new_image_count);

	/* Exit without doing activation checks if the combination isn't possible */
	if (_takeover_not_possible(takeover_fn))
		return takeover_fn(lv, new_segtype, yes, force, new_image_count, 0, new_stripes, stripe_size,
				   region_size, allocate_pvs);

	log_verbose("Converting %s from %s to %s.",
		    display_lvname(lv), lvseg_name(first_seg(lv)),
		    (segtype_is_striped_target(new_segtype) &&
		    (new_stripes == 1)) ? SEG_TYPE_NAME_LINEAR : new_segtype->name);

	/* FIXME If not active, prompt and activate */
	/* FIXME Some operations do not require the LV to be active */
	/* LV must be active to perform raid conversion operations */
	if (!lv_is_active(lv)) {
		log_error("%s must be active to perform this operation.",
			  display_lvname(lv));
		return 0;
	}

	/* In clustered VGs, the LV must be active on this node exclusively. */
	if (vg_is_clustered(lv->vg) && !lv_is_active_exclusive_locally(lv)) {
		log_error("%s must be active exclusive locally to "
			  "perform this operation.", display_lvname(lv));
		return 0;
	}

	/* LV must be in sync. */
	if (!_raid_in_sync(lv)) {
		log_error("Unable to convert %s while it is not in-sync.",
			  display_lvname(lv));
		return 0;
	}

	return takeover_fn(lv, new_segtype, yes, force, new_image_count, 0, new_stripes, stripe_size,
			   region_size, allocate_pvs);
}

int lv_raid_change_region_size(struct logical_volume *lv,
		    int yes, int force, uint32_t new_region_size)
{
	return _region_size_change_requested(lv, yes, new_region_size);
}

static int _remove_partial_multi_segment_image(struct logical_volume *lv,
					       struct dm_list *remove_pvs)
{
	uint32_t s, extents_needed;
	struct lv_segment *rm_seg, *raid_seg = first_seg(lv);
	struct logical_volume *rm_image = NULL;
	struct physical_volume *pv;

	if (!lv_is_partial(lv))
		return_0;

	for (s = 0; s < raid_seg->area_count; s++) {
		extents_needed = 0;
		if (lv_is_partial(seg_lv(raid_seg, s)) &&
		    lv_is_on_pvs(seg_lv(raid_seg, s), remove_pvs) &&
		    (dm_list_size(&(seg_lv(raid_seg, s)->segments)) > 1)) {
			rm_image = seg_lv(raid_seg, s);

			/* First, how many damaged extents are there */
			if (lv_is_partial(seg_metalv(raid_seg, s)))
				extents_needed += seg_metalv(raid_seg, s)->le_count;
			dm_list_iterate_items(rm_seg, &rm_image->segments) {
				/*
				 * segment areas are for stripe, mirror, raid,
				 * etc.  We only need to check the first area
				 * if we are dealing with RAID image LVs.
				 */
				if (seg_type(rm_seg, 0) != AREA_PV)
					continue;
				pv = seg_pv(rm_seg, 0);
				if (pv->status & MISSING_PV)
					extents_needed += rm_seg->len;
			}
			log_debug_metadata("%u extents needed to repair %s.",
				  extents_needed, display_lvname(rm_image));

			/* Second, do the other PVs have the space */
			dm_list_iterate_items(rm_seg, &rm_image->segments) {
				if (seg_type(rm_seg, 0) != AREA_PV)
					continue;
				pv = seg_pv(rm_seg, 0);
				if (pv->status & MISSING_PV)
					continue;

				if ((pv->pe_count - pv->pe_alloc_count) >
				    extents_needed) {
					log_debug_metadata("%s has enough space for %s.",
							   pv_dev_name(pv),
							   display_lvname(rm_image));
					goto has_enough_space;
				}
				log_debug_metadata("Not enough space on %s for %s.",
						   pv_dev_name(pv), display_lvname(rm_image));
			}
		}
	}

	/*
	 * This is likely to be the normal case - single
	 * segment images.
	 */
	return_0;

has_enough_space:
	/*
	 * Now we have a multi-segment, partial image that has enough
	 * space on just one of its PVs for the entire image to be
	 * replaced.  So, we replace the image's space with an error
	 * target so that the allocator can find that space (along with
	 * the remaining free space) in order to allocate the image
	 * anew.
	 */
	if (!replace_lv_with_error_segment(rm_image))
		return_0;

	return 1;
}

/*
 * Helper:
 *
 * _lv_raid_rebuild_or_replace
 * @lv
 * @remove_pvs
 * @allocate_pvs
 * @rebuild
 *
 * Rebuild the specified PVs on @remove_pvs if rebuild != 0;
 * @allocate_pvs not accessed for rebuild.
 *
 * Replace the specified PVs on @remove_pvs if rebuild == 0;
 * new SubLVS are allocated on PVs on list @allocate_pvs.
 */
static int _lv_raid_rebuild_or_replace(struct logical_volume *lv,
				       int force,
				       struct dm_list *remove_pvs,
				       struct dm_list *allocate_pvs,
				       int rebuild)
{
	int partial_segment_removed = 0;
	uint32_t s, sd, match_count = 0;
	struct dm_list old_lvs;
	struct dm_list new_meta_lvs, new_data_lvs;
	struct lv_segment *raid_seg = first_seg(lv);
	struct lv_list *lvl;
	char *tmp_names[raid_seg->area_count * 2];
	const char *action_str = rebuild ? "rebuild" : "replace";

	if (seg_is_any_raid0(raid_seg)) {
		log_error("Can't replace any devices in %s LV %s.",
			  lvseg_name(raid_seg), display_lvname(lv));
		return 0;
	}

	dm_list_init(&old_lvs);
	dm_list_init(&new_meta_lvs);
	dm_list_init(&new_data_lvs);

	if (lv_is_partial(lv))
		lv->vg->cmd->partial_activation = 1;

	if (!lv_is_active_exclusive_locally(lv_lock_holder(lv))) {
		log_error("%s must be active %sto perform this operation.",
			  display_lvname(lv),
			  vg_is_clustered(lv->vg) ? "exclusive locally " : "");
		return 0;
	}

	if (!_raid_in_sync(lv)) {
		log_error("Unable to replace devices in %s while it is "
			  "not in-sync.", display_lvname(lv));
		return 0;
	}

	/*
	 * How many sub-LVs are being removed?
	 */
	for (s = 0; s < raid_seg->area_count; s++) {
		if ((seg_type(raid_seg, s) == AREA_UNASSIGNED) ||
		    (seg_metatype(raid_seg, s) == AREA_UNASSIGNED)) {
			log_error("Unable to replace RAID images while the "
				  "array has unassigned areas.");
			return 0;
		}

		if (lv_is_virtual(seg_lv(raid_seg, s)) ||
		    lv_is_virtual(seg_metalv(raid_seg, s)) ||
		    lv_is_on_pvs(seg_lv(raid_seg, s), remove_pvs) ||
		    lv_is_on_pvs(seg_metalv(raid_seg, s), remove_pvs)) {
			match_count++;
			if (rebuild) {
				if ((match_count == 1) &&
				    !archive(lv->vg))
					return_0;
				seg_lv(raid_seg, s)->status |= LV_REBUILD;
				seg_metalv(raid_seg, s)->status |= LV_REBUILD;
			}
		}
	}

	if (!match_count) {
		log_print_unless_silent("%s does not contain devices specified to %s.",
					display_lvname(lv), action_str);
		return 1;
	} else if (match_count == raid_seg->area_count) {
		log_error("Unable to %s all PVs from %s at once.",
			  action_str, display_lvname(lv));
		return 0;
	} else if (raid_seg->segtype->parity_devs &&
		   (match_count > raid_seg->segtype->parity_devs)) {
		log_error("Unable to %s more than %u PVs from (%s) %s.",
			  action_str, raid_seg->segtype->parity_devs,
			  lvseg_name(raid_seg), display_lvname(lv));
		return 0;
	} else if (seg_is_raid10(raid_seg)) {
		uint32_t i, rebuilds_per_group = 0;
		/* FIXME: We only support 2-way mirrors (i.e. 2 data copies) in RAID10 currently */
		uint32_t copies = 2;

		for (i = 0; i < raid_seg->area_count * copies; i++) {
			s = i % raid_seg->area_count;
			if (!(i % copies))
				rebuilds_per_group = 0;
			if (lv_is_on_pvs(seg_lv(raid_seg, s), remove_pvs) ||
			    lv_is_on_pvs(seg_metalv(raid_seg, s), remove_pvs) ||
			    lv_is_virtual(seg_lv(raid_seg, s)) ||
			    lv_is_virtual(seg_metalv(raid_seg, s)))
				rebuilds_per_group++;
			if (rebuilds_per_group >= copies) {
				log_error("Unable to %s all the devices "
					  "in a RAID10 mirror group.", action_str);
				return 0;
			}
		}
	}

	if (rebuild)
		goto skip_alloc;

	if (!archive(lv->vg))
		return_0;

	/* Prevent any PVs holding image components from being used for allocation */
	if (!_avoid_pvs_with_other_images_of_lv(lv, allocate_pvs)) {
		log_error("Failed to prevent PVs holding image components "
			  "from being used for allocation.");
		return 0;
	}

	/*
	 * Allocate the new image components first
	 * - This makes it easy to avoid all currently used devs
	 * - We can immediately tell if there is enough space
	 *
	 * - We need to change the LV names when we insert them.
	 */
try_again:
	if (!_alloc_image_components(lv, allocate_pvs, match_count,
				     &new_meta_lvs, &new_data_lvs, 0)) {
		if (!lv_is_partial(lv)) {
			log_error("LV %s in not partial.", display_lvname(lv));
			return 0;
		}

		/* This is a repair, so try to do better than all-or-nothing */
		match_count--;
		if (match_count > 0) {
			log_error("Failed to replace %u devices."
				  "  Attempting to replace %u instead.",
				  match_count, match_count+1);
			/*
			 * Since we are replacing some but not all of the bad
			 * devices, we must set partial_activation
			 */
			lv->vg->cmd->partial_activation = 1;
			goto try_again;
		} else if (!match_count && !partial_segment_removed) {
			/*
			 * We are down to the last straw.  We can only hope
			 * that a failed PV is just one of several PVs in
			 * the image; and if we extract the image, there may
			 * be enough room on the image's other PVs for a
			 * reallocation of the image.
			 */
			if (!_remove_partial_multi_segment_image(lv, remove_pvs))
				return_0;

			match_count = 1;
			partial_segment_removed = 1;
			lv->vg->cmd->partial_activation = 1;
			goto try_again;
		}
		log_error("Failed to allocate replacement images for %s.",
			  display_lvname(lv));

		return 0;
	}

	/*
	 * Remove the old images
	 * - If we did this before the allocate, we wouldn't have to rename
	 *   the allocated images, but it'd be much harder to avoid the right
	 *   PVs during allocation.
	 *
	 * - If this is a repair and we were forced to call
	 *   _remove_partial_multi_segment_image, then the remove_pvs list
	 *   is no longer relevant - _raid_extract_images is forced to replace
	 *   the image with the error target.  Thus, the full set of PVs is
	 *   supplied - knowing that only the image with the error target
	 *   will be affected.
	 */
	if (!_raid_extract_images(lv, force,
				  raid_seg->area_count - match_count,
				  partial_segment_removed ?
				  &lv->vg->pvs : remove_pvs, 0,
				  &old_lvs, &old_lvs)) {
		log_error("Failed to remove the specified images from %s.",
			  display_lvname(lv));
		return 0;
	}

	/*
	 * Now that they are extracted and visible, make the system aware
	 * of their new names.
	 */
	dm_list_iterate_items(lvl, &old_lvs)
		if (!activate_lv_excl_local(lv->vg->cmd, lvl->lv))
			return_0;

	/*
	 * Skip metadata operation normally done to clear the metadata sub-LVs.
	 *
	 * The LV_REBUILD flag is set on the new sub-LVs,
	 * so they will be rebuilt and we don't need to clear the metadata dev.
	 */

	for (s = 0; s < raid_seg->area_count; s++) {
		sd = s + raid_seg->area_count;

		if ((seg_type(raid_seg, s) == AREA_UNASSIGNED) &&
		    (seg_metatype(raid_seg, s) == AREA_UNASSIGNED)) {
			/* Adjust the new metadata LV name */
			lvl = dm_list_item(dm_list_first(&new_meta_lvs),
					   struct lv_list);
			dm_list_del(&lvl->list);
			if (!(tmp_names[s] = _generate_raid_name(lv, "rmeta", s)))
				return_0;
			if (!set_lv_segment_area_lv(raid_seg, s, lvl->lv, 0,
						    lvl->lv->status)) {
				log_error("Failed to add %s to %s.",
					  display_lvname(lvl->lv),
					  display_lvname(lv));
				return 0;
			}
			lv_set_hidden(lvl->lv);

			/* Adjust the new data LV name */
			lvl = dm_list_item(dm_list_first(&new_data_lvs),
					   struct lv_list);
			dm_list_del(&lvl->list);
			/* coverity[copy_paste_error] intentional */
			if (!(tmp_names[sd] = _generate_raid_name(lv, "rimage", s)))
				return_0;
			if (!set_lv_segment_area_lv(raid_seg, s, lvl->lv, 0,
						    lvl->lv->status)) {
				log_error("Failed to add %s to %s.",
					  display_lvname(lvl->lv),
					  display_lvname(lv));
				return 0;
			}
			lv_set_hidden(lvl->lv);
		} else
			tmp_names[s] = tmp_names[sd] = NULL;
	}

skip_alloc:
	if (!lv_update_and_reload_origin(lv))
		return_0;

	/* @old_lvs is empty in case of a rebuild */
	dm_list_iterate_items(lvl, &old_lvs) {
		if (!deactivate_lv(lv->vg->cmd, lvl->lv))
			return_0;
		if (!lv_remove(lvl->lv))
			return_0;
	}

	/* Clear REBUILD flag */
	for (s = 0; s < raid_seg->area_count; s++) {
		seg_lv(raid_seg, s)->status &= ~LV_REBUILD;
		seg_metalv(raid_seg, s)->status &= ~LV_REBUILD;
	}

	/* If replace, correct name(s) */
	if (!rebuild)
		for (s = 0; s < raid_seg->area_count; s++) {
			sd = s + raid_seg->area_count;
			if (tmp_names[s] && tmp_names[sd]) {
				seg_metalv(raid_seg, s)->name = tmp_names[s];
				seg_lv(raid_seg, s)->name = tmp_names[sd];
			}
		}

	if (!lv_update_and_reload_origin(lv))
		return_0;

	return 1;
}

/*
 * lv_raid_rebuild
 * @lv
 * @remove_pvs
 *
 * Rebuild the specified PVs of @lv on @remove_pvs.
 */
int lv_raid_rebuild(struct logical_volume *lv,
		    struct dm_list *rebuild_pvs)
{
	return _lv_raid_rebuild_or_replace(lv, 0, rebuild_pvs, NULL, 1);
}

/*
 * lv_raid_replace
 * @lv
 * @remove_pvs
 * @allocate_pvs
 *
 * Replace the specified PVs on @remove_pvs of @lv
 * allocating new SubLVs from PVs on list @allocate_pvs.
 */
int lv_raid_replace(struct logical_volume *lv,
		    int force,
		    struct dm_list *remove_pvs,
		    struct dm_list *allocate_pvs)
{
	return _lv_raid_rebuild_or_replace(lv, force, remove_pvs, allocate_pvs, 0);
}

int lv_raid_remove_missing(struct logical_volume *lv)
{
	uint32_t s;
	struct lv_segment *seg = first_seg(lv);

	if (!lv_is_partial(lv)) {
		log_error(INTERNAL_ERROR "%s is not a partial LV.",
			  display_lvname(lv));
		return 0;
	}

	if (!archive(lv->vg))
		return_0;

	log_debug("Attempting to remove missing devices from %s LV, %s.",
		  lvseg_name(seg), display_lvname(lv));

	/*
	 * FIXME: Make sure # of compromised components will not affect RAID
	 */

	for (s = 0; s < seg->area_count; s++) {
		if (!lv_is_partial(seg_lv(seg, s)) &&
		    (!seg->meta_areas || !seg_metalv(seg, s) || !lv_is_partial(seg_metalv(seg, s))))
			continue;

		log_debug("Replacing %s segments with error target.",
			  display_lvname(seg_lv(seg, s)));
		if (seg->meta_areas && seg_metalv(seg, s))
			log_debug("Replacing %s segments with error target.",
				  display_lvname(seg_metalv(seg, s)));
		if (!replace_lv_with_error_segment(seg_lv(seg, s))) {
			log_error("Failed to replace %s's extents with error target.",
				  display_lvname(seg_lv(seg, s)));
			return 0;
		}
		if (seg->meta_areas && !replace_lv_with_error_segment(seg_metalv(seg, s))) {
			log_error("Failed to replace %s's extents with error target.",
				  display_lvname(seg_metalv(seg, s)));
			return 0;
		}
	}

	if (!lv_update_and_reload(lv))
		return_0;

	return 1;
}

/* Return 1 if a partial raid LV can be activated redundantly */
static int _partial_raid_lv_is_redundant(const struct logical_volume *lv)
{
	struct lv_segment *raid_seg = first_seg(lv);
	uint32_t copies;
	uint32_t i, s, rebuilds_per_group = 0;
	uint32_t failed_components = 0;

	if (seg_is_raid10(raid_seg)) {
		/* FIXME: We only support 2-way mirrors in RAID10 currently */
		copies = 2;
		for (i = 0; i < raid_seg->area_count * copies; i++) {
			s = i % raid_seg->area_count;

			if (!(i % copies))
				rebuilds_per_group = 0;

			if (lv_is_partial(seg_lv(raid_seg, s)) ||
			    lv_is_partial(seg_metalv(raid_seg, s)) ||
			    lv_is_virtual(seg_lv(raid_seg, s)) ||
			    lv_is_virtual(seg_metalv(raid_seg, s)))
				rebuilds_per_group++;

			if (rebuilds_per_group >= copies) {
				log_verbose("An entire mirror group has failed in %s.",
					    display_lvname(lv));
				return 0;	/* Insufficient redundancy to activate */
			}
		}

		return 1; /* Redundant */
	}

	for (s = 0; s < raid_seg->area_count; s++) {
		if (lv_is_partial(seg_lv(raid_seg, s)) ||
		    lv_is_partial(seg_metalv(raid_seg, s)) ||
		    lv_is_virtual(seg_lv(raid_seg, s)) ||
		    lv_is_virtual(seg_metalv(raid_seg, s)))
			failed_components++;
	}

	if (failed_components == raid_seg->area_count) {
		log_verbose("All components of raid LV %s have failed.",
			    display_lvname(lv));
		return 0;	/* Insufficient redundancy to activate */
	} else if (raid_seg->segtype->parity_devs &&
		   (failed_components > raid_seg->segtype->parity_devs)) {
		log_verbose("More than %u components from %s %s have failed.",
			    raid_seg->segtype->parity_devs,
			    lvseg_name(raid_seg),
			    display_lvname(lv));
		return 0;	/* Insufficient redundancy to activate */
	}

	return 1;
}

/* Sets *data to 1 if the LV cannot be activated without data loss */
static int _lv_may_be_activated_in_degraded_mode(struct logical_volume *lv, void *data)
{
	int *not_capable = (int *)data;
	uint32_t s;
	struct lv_segment *seg;

	if (*not_capable)
		return 1;	/* No further checks needed */

	if (!lv_is_partial(lv))
		return 1;

	if (lv_is_raid(lv)) {
		*not_capable = !_partial_raid_lv_is_redundant(lv);
		return 1;
	}

	/* Ignore RAID sub-LVs. */
	if (lv_is_raid_type(lv))
		return 1;

	dm_list_iterate_items(seg, &lv->segments)
		for (s = 0; s < seg->area_count; s++)
			if (seg_type(seg, s) != AREA_LV) {
				log_verbose("%s contains a segment incapable of degraded activation.",
					    display_lvname(lv));
				*not_capable = 1;
			}

	return 1;
}

int partial_raid_lv_supports_degraded_activation(const struct logical_volume *clv)
{
	int not_capable = 0;
	struct logical_volume * lv = (struct logical_volume *)clv; /* drop const */

	if (!_lv_may_be_activated_in_degraded_mode(lv, &not_capable) || not_capable)
		return_0;

	if (!for_each_sub_lv(lv, _lv_may_be_activated_in_degraded_mode, &not_capable)) {
		log_error(INTERNAL_ERROR "for_each_sub_lv failure.");
		return 0;
	}

	return !not_capable;
}