summaryrefslogtreecommitdiffstats
path: root/tools/lvconvert.c
blob: 76cc9b362a1de184aef7969a646bc7233c35049a (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
/*
 * Copyright (C) 2005-2007 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "tools.h"
#include "polldaemon.h"
#include "lv_alloc.h"
#include "metadata.h"

struct lvconvert_params {
	int snapshot;
	int merge;
	int merge_mirror;
	int zero;

	const char *origin;
	const char *lv_name;
	const char *lv_split_name;
	const char *lv_name_full;
	const char *vg_name;
	int wait_completion;
	int need_polling;

	uint32_t chunk_size;
	uint32_t region_size;

	uint32_t mirrors;
	sign_t mirrors_sign;
	uint32_t keep_mimages;
	uint32_t stripes;
	uint32_t stripe_size;

	const struct segment_type *segtype;

	alloc_policy_t alloc;

	int pv_count;
	char **pvs;
	struct dm_list *pvh;

	int replace_pv_count;
	char **replace_pvs;
	struct dm_list *replace_pvh;

	struct logical_volume *lv_to_poll;

	uint64_t poolmetadata_size; /* thin pool */
	const char *pool_data_lv_name;
	/* pool_metadata_lv_name is lv_name */
};

static int _lvconvert_name_params(struct lvconvert_params *lp,
				  struct cmd_context *cmd,
				  int *pargc, char ***pargv)
{
	char *ptr;
	const char *vg_name = NULL;

	if (lp->merge)
		return 1;

	if (lp->snapshot) {
		if (!*pargc) {
			log_error("Please specify a logical volume to act as "
				  "the snapshot origin.");
			return 0;
		}

		lp->origin = *pargv[0];
		(*pargv)++, (*pargc)--;
		if (!(lp->vg_name = extract_vgname(cmd, lp->origin))) {
			log_error("The origin name should include the "
				  "volume group.");
			return 0;
		}

		/* Strip the volume group from the origin */
		if ((ptr = strrchr(lp->origin, (int) '/')))
			lp->origin = ptr + 1;
	}

	if (!*pargc && lp->pool_data_lv_name) {
		if (!lp->vg_name || !validate_name(lp->vg_name)) {
			log_error("Please provide a valid volume group name.");
			return 0;
		}
		lp->lv_name = lp->pool_data_lv_name;
		return 1; /* Create metadata LV on it's own */
	}

	if (!*pargc) {
		log_error("Please provide logical volume path");
		return 0;
	}

	lp->lv_name = lp->lv_name_full = (*pargv)[0];
	(*pargv)++, (*pargc)--;

	if (strchr(lp->lv_name_full, '/') &&
	    (vg_name = extract_vgname(cmd, lp->lv_name_full)) &&
	    lp->vg_name && strcmp(vg_name, lp->vg_name)) {
		log_error("Please use a single volume group name "
			  "(\"%s\" or \"%s\")", vg_name, lp->vg_name);
		return 0;
	}

	if (!lp->vg_name)
		lp->vg_name = vg_name;

	if (!validate_name(lp->vg_name)) {
		log_error("Please provide a valid volume group name");
		return 0;
	}

	if ((ptr = strrchr(lp->lv_name_full, '/')))
		lp->lv_name = ptr + 1;

	if (!lp->merge_mirror && !apply_lvname_restrictions(lp->lv_name))
		return_0;

	if (*pargc && lp->snapshot) {
		log_error("Too many arguments provided for snapshots");
		return 0;
	}

	if (lp->pool_data_lv_name && lp->lv_name && lp->poolmetadata_size) {
		log_error("Please specify either metadata logical volume or its size.");
		return 0;
	}

	return 1;
}

static int _read_params(struct lvconvert_params *lp, struct cmd_context *cmd,
			int argc, char **argv)
{
	int i;
	const char *tmp_str;
	struct arg_value_group_list *group;
	int region_size;
	int pagesize = lvm_getpagesize();

	memset(lp, 0, sizeof(*lp));

	if ((arg_count(cmd, snapshot_ARG) || arg_count(cmd, merge_ARG)) &&
	    (arg_count(cmd, mirrorlog_ARG) || arg_count(cmd, mirrors_ARG) ||
	     arg_count(cmd, repair_ARG))) {
		log_error("--snapshot or --merge argument cannot be mixed "
			  "with --mirrors, --repair or --mirrorlog");
		return 0;
	}

	if (!arg_count(cmd, background_ARG))
		lp->wait_completion = 1;

	if (arg_count(cmd, snapshot_ARG))
		lp->snapshot = 1;

	if (arg_count(cmd, snapshot_ARG) && arg_count(cmd, merge_ARG)) {
		log_error("--snapshot and --merge are mutually exclusive");
		return 0;
	}

	if (arg_count(cmd, splitmirrors_ARG) && arg_count(cmd, mirrors_ARG)) {
		log_error("--mirrors and --splitmirrors are "
			  "mutually exclusive");
		return 0;
	}

	if (arg_count(cmd, thinpool_ARG)) {
		if (arg_count(cmd, merge_ARG)) {
			log_error("--thinpool and --merge are mutually exlusive.");
			return 0;
		}
		if (arg_count(cmd, mirrors_ARG)) {
			log_error("--thinpool and --mirrors are mutually exlusive.");
			return 0;
		}
		if (arg_count(cmd, repair_ARG)) {
			log_error("--thinpool and --repair are mutually exlusive.");
			return 0;
		}
		if (arg_count(cmd, snapshot_ARG)) {
			log_error("--thinpool and --snapshot are mutually exlusive.");
			return 0;
		}
		if (arg_count(cmd, splitmirrors_ARG)) {
			log_error("--thinpool and --splitmirrors are mutually exlusive.");
			return 0;
		}
	}

	/*
	 * The '--splitmirrors n' argument is equivalent to '--mirrors -n'
	 * (note the minus sign), except that it signifies the additional
	 * intent to keep the mimage that is detached, rather than
	 * discarding it.
	 */
	if (arg_count(cmd, splitmirrors_ARG)) {
		if (!arg_count(cmd, name_ARG) &&
		    !arg_count(cmd, trackchanges_ARG)) {
			log_error("Please name the new logical volume using '--name'");
			return 0;
		}

		lp->lv_split_name = arg_value(cmd, name_ARG);
		if (lp->lv_split_name) {
			if (strchr(lp->lv_split_name, '/')) {
				if (!(lp->vg_name = extract_vgname(cmd, lp->lv_split_name)))
					return_0;

				/* Strip VG from lv_split_name */
				if ((tmp_str = strrchr(lp->lv_split_name, '/')))
					lp->lv_split_name = tmp_str + 1;
			}

			if (!apply_lvname_restrictions(lp->lv_split_name))
				return_0;
		}

		lp->keep_mimages = 1;
		lp->mirrors = arg_uint_value(cmd, splitmirrors_ARG, 0);
		lp->mirrors_sign = SIGN_MINUS;
	} else if (arg_count(cmd, name_ARG)) {
		log_error("The 'name' argument is only valid"
			  " with --splitmirrors");
		return 0;
	}

	if (arg_count(cmd, merge_ARG)) {
		if ((argc == 1) && strstr(argv[0], "_rimage_"))
			lp->merge_mirror = 1;
		else
			lp->merge = 1;
	}

	if (arg_count(cmd, mirrors_ARG)) {
		/*
		 * --splitmirrors has been chosen as the mechanism for
		 * specifying the intent of detaching and keeping a mimage
		 * versus an additional qualifying argument being added here.
		 */
		lp->mirrors = arg_uint_value(cmd, mirrors_ARG, 0);
		lp->mirrors_sign = arg_sign_value(cmd, mirrors_ARG, SIGN_NONE);
	}

	lp->alloc = (alloc_policy_t) arg_uint_value(cmd, alloc_ARG, ALLOC_INHERIT);

	/* There are three types of lvconvert. */
	if (lp->merge) {	/* Snapshot merge */
		if (arg_count(cmd, regionsize_ARG) || arg_count(cmd, chunksize_ARG) ||
		    arg_count(cmd, zero_ARG) || arg_count(cmd, regionsize_ARG) ||
		    arg_count(cmd, stripes_long_ARG) || arg_count(cmd, stripesize_ARG)) {
			log_error("Only --background and --interval are valid "
				  "arguments for snapshot merge");
			return 0;
		}

		if (!(lp->segtype = get_segtype_from_string(cmd, "snapshot")))
			return_0;

	} else if (lp->snapshot) {	/* Snapshot creation from pre-existing cow */
		if (arg_count(cmd, regionsize_ARG)) {
			log_error("--regionsize is only available with mirrors");
			return 0;
		}

		if (arg_count(cmd, stripesize_ARG) || arg_count(cmd, stripes_long_ARG)) {
			log_error("--stripes and --stripesize are only available with striped mirrors");
			return 0;
		}

		if (arg_sign_value(cmd, chunksize_ARG, SIGN_NONE) == SIGN_MINUS) {
			log_error("Negative chunk size is invalid");
			return 0;
		}
		lp->chunk_size = arg_uint_value(cmd, chunksize_ARG, 8);
		if (lp->chunk_size < 8 || lp->chunk_size > 1024 ||
		    (lp->chunk_size & (lp->chunk_size - 1))) {
			log_error("Chunk size must be a power of 2 in the "
				  "range 4K to 512K");
			return 0;
		}
		log_verbose("Setting chunksize to %d sectors.", lp->chunk_size);

		if (!(lp->segtype = get_segtype_from_string(cmd, "snapshot")))
			return_0;

		lp->zero = strcmp(arg_str_value(cmd, zero_ARG,
						(lp->segtype->flags &
						 SEG_CANNOT_BE_ZEROED) ?
						"n" : "y"), "n");

	} else if (arg_count(cmd, replace_ARG)) { /* RAID device replacement */
		lp->replace_pv_count = arg_count(cmd, replace_ARG);
		lp->replace_pvs = dm_pool_alloc(cmd->mem, sizeof(char *) * lp->replace_pv_count);
		if (!lp->replace_pvs)
			return_0;

		i = 0;
		dm_list_iterate_items(group, &cmd->arg_value_groups) {
			if (!grouped_arg_is_set(group->arg_values, replace_ARG))
				continue;
			if (!(tmp_str = grouped_arg_str_value(group->arg_values,
							      replace_ARG,
							      NULL))) {
				log_error("Failed to get '--replace' argument");
				return 0;
			}
			if (!(lp->replace_pvs[i++] = dm_pool_strdup(cmd->mem,
								    tmp_str)))
				return_0;
		}
	} else if (arg_count(cmd, thinpool_ARG)) {
		if (!(lp->pool_data_lv_name = arg_str_value(cmd, thinpool_ARG, NULL))) {
			log_error("Missing pool logical volume name.");
			return 0;
		}

		if (arg_count(cmd, poolmetadatasize_ARG)) {
			if (arg_sign_value(cmd, poolmetadatasize_ARG, SIGN_NONE) == SIGN_MINUS) {
				log_error("Negative pool metadata size is invalid.");
				return 0;
			}
			lp->poolmetadata_size = arg_uint64_value(cmd, poolmetadatasize_ARG, UINT64_C(0));

			if (lp->poolmetadata_size > (2 * DEFAULT_THIN_POOL_MAX_METADATA_SIZE)) {
				if (arg_count(cmd, poolmetadatasize_ARG))
					log_warn("WARNING: Maximum supported pool metadata size is 16GB.");
				lp->poolmetadata_size = 2 * DEFAULT_THIN_POOL_MAX_METADATA_SIZE;
			} else if (lp->poolmetadata_size < (2 * DEFAULT_THIN_POOL_MIN_METADATA_SIZE)) {
				if (arg_count(cmd, poolmetadatasize_ARG))
					log_warn("WARNING: Minimum supported pool metadata size is 2M.");
				lp->poolmetadata_size = 2 * DEFAULT_THIN_POOL_MIN_METADATA_SIZE;
			}

			log_verbose("Setting pool metadata size to %" PRIu64 " sectors.",
				    lp->poolmetadata_size);
		}

		if (arg_count(cmd, chunksize_ARG)) {
			if (arg_sign_value(cmd, chunksize_ARG, SIGN_NONE) == SIGN_MINUS) {
				log_error("Negative chunk size is invalid.");
				return 0;
			}
			lp->chunk_size = arg_uint_value(cmd, chunksize_ARG,
							DM_THIN_MIN_DATA_BLOCK_SIZE);

			if ((lp->chunk_size < DM_THIN_MIN_DATA_BLOCK_SIZE) ||
			    (lp->chunk_size > DM_THIN_MAX_DATA_BLOCK_SIZE)) {
				log_error("Chunk size must be in the range %uK to %uK.",
					  (DM_THIN_MIN_DATA_BLOCK_SIZE / 2),
					  (DM_THIN_MAX_DATA_BLOCK_SIZE / 2));
				return 0;
			}
		} else
			lp->chunk_size = DM_THIN_MIN_DATA_BLOCK_SIZE;
		log_verbose("Setting pool metadata chunk size to %u sectors.",
			    lp->chunk_size);

		if (arg_count(cmd, zero_ARG))
			lp->zero = strcmp(arg_str_value(cmd, zero_ARG, "y"), "n");

		/* If --thinpool contains VG name, extract it. */
		if ((tmp_str = strchr(lp->pool_data_lv_name, (int) '/'))) {
			if (!(lp->vg_name = extract_vgname(cmd, lp->pool_data_lv_name)))
				return 0;
			/* Strip VG from pool */
			lp->pool_data_lv_name = tmp_str + 1;
		}

		lp->segtype = get_segtype_from_string(cmd, arg_str_value(cmd, type_ARG, "thin-pool"));
		if (!lp->segtype)
			return_0;
	} else { /* Mirrors (and some RAID functions) */
		if (arg_count(cmd, chunksize_ARG)) {
			log_error("--chunksize is only available with "
				  "snapshots");
			return 0;
		}

		if (arg_count(cmd, zero_ARG)) {
			log_error("--zero is only available with snapshots");
			return 0;
		}

		/*
	 	 * --regionsize is only valid if converting an LV into a mirror.
	 	 * Checked when we know the state of the LV being converted.
	 	 */

		if (arg_count(cmd, regionsize_ARG)) {
			if (arg_sign_value(cmd, regionsize_ARG, SIGN_NONE) ==
				    SIGN_MINUS) {
				log_error("Negative regionsize is invalid");
				return 0;
			}
			lp->region_size = arg_uint_value(cmd, regionsize_ARG, 0);
		} else {
			region_size = 2 * find_config_tree_int(cmd,
						"activation/mirror_region_size",
						DEFAULT_MIRROR_REGION_SIZE);
			if (region_size < 0) {
				log_error("Negative regionsize in "
					  "configuration file is invalid");
				return 0;
			}
			lp->region_size = region_size;
		}

		if (lp->region_size % (pagesize >> SECTOR_SHIFT)) {
			log_error("Region size (%" PRIu32 ") must be "
				  "a multiple of machine memory "
				  "page size (%d)",
				  lp->region_size, pagesize >> SECTOR_SHIFT);
			return 0;
		}

		if (lp->region_size & (lp->region_size - 1)) {
			log_error("Region size (%" PRIu32
				  ") must be a power of 2", lp->region_size);
			return 0;
		}

		if (!lp->region_size) {
			log_error("Non-zero region size must be supplied.");
			return 0;
		}

		/* Default is never striped, regardless of existing LV configuration. */
		if (!get_stripe_params(cmd, &lp->stripes, &lp->stripe_size)) {
			stack;
			return 0;
		}

		lp->segtype = get_segtype_from_string(cmd, arg_str_value(cmd, type_ARG, "mirror"));
		if (!lp->segtype)
			return_0;
	}

	if (activation() && lp->segtype && lp->segtype->ops->target_present &&
	    !lp->segtype->ops->target_present(cmd, NULL, NULL)) {
		log_error("%s: Required device-mapper target(s) not "
			  "detected in your kernel", lp->segtype->name);
		return 0;
	}

	if (!_lvconvert_name_params(lp, cmd, &argc, &argv))
		return_0;

	lp->pv_count = argc;
	lp->pvs = argv;

	return 1;
}

static struct volume_group *_get_lvconvert_vg(struct cmd_context *cmd,
					      const char *name,
					      const char *uuid __attribute__((unused)))
{
	dev_close_all();

	if (name && !strchr(name, '/'))
		return vg_read_for_update(cmd, name, NULL, 0);

	/* 'name' is the full LV name; must extract_vgname() */
	return vg_read_for_update(cmd, extract_vgname(cmd, name),
				  NULL, 0);
}

static struct logical_volume *_get_lvconvert_lv(struct cmd_context *cmd __attribute__((unused)),
						struct volume_group *vg,
						const char *name,
						const char *uuid,
						uint64_t lv_type __attribute__((unused)))
{
	struct logical_volume *lv = find_lv(vg, name);

	if (!lv || (uuid && strcmp(uuid, (char *)&lv->lvid)))
		return NULL;

	return lv;
}

static int _finish_lvconvert_mirror(struct cmd_context *cmd,
				    struct volume_group *vg,
				    struct logical_volume *lv,
				    struct dm_list *lvs_changed __attribute__((unused)))
{
	int r = 0;

	if (!(lv->status & CONVERTING))
		return 1;

	if (!collapse_mirrored_lv(lv)) {
		log_error("Failed to remove temporary sync layer.");
		return 0;
	}

	lv->status &= ~CONVERTING;

	log_very_verbose("Updating logical volume \"%s\" on disk(s)", lv->name);

	if (!vg_write(vg))
		return_0;

	if (!suspend_lv(cmd, lv)) {
		log_error("Failed to lock %s", lv->name);
		vg_revert(vg);
		goto out;
	}

	if (!vg_commit(vg)) {
		resume_lv(cmd, lv);
		goto_out;
	}

	log_very_verbose("Updating \"%s\" in kernel", lv->name);

	if (!resume_lv(cmd, lv)) {
		log_error("Problem reactivating %s", lv->name);
		goto out;
	}

	r = 1;
	log_print("Logical volume %s converted.", lv->name);
out:
	backup(vg);
	return r;
}

static int _finish_lvconvert_merge(struct cmd_context *cmd,
				   struct volume_group *vg,
				   struct logical_volume *lv,
				   struct dm_list *lvs_changed __attribute__((unused)))
{
	struct lv_segment *snap_seg = find_merging_cow(lv);
	if (!snap_seg) {
		log_error("Logical volume %s has no merging snapshot.", lv->name);
		return 0;
	}

	log_print("Merge of snapshot into logical volume %s has finished.", lv->name);
	if (!lv_remove_single(cmd, snap_seg->cow, DONT_PROMPT)) {
		log_error("Could not remove snapshot %s merged into %s.",
			  snap_seg->cow->name, lv->name);
		return 0;
	}

	return 1;
}

static progress_t _poll_merge_progress(struct cmd_context *cmd,
				       struct logical_volume *lv,
				       const char *name __attribute__((unused)),
				       struct daemon_parms *parms)
{
	percent_t percent = PERCENT_0;

	if (!lv_snapshot_percent(lv, &percent)) {
		log_error("%s: Failed query for merging percentage. Aborting merge.", lv->name);
		return PROGRESS_CHECK_FAILED;
	} else if (percent == PERCENT_INVALID) {
		log_error("%s: Merging snapshot invalidated. Aborting merge.", lv->name);
		return PROGRESS_CHECK_FAILED;
	} else if (percent == PERCENT_MERGE_FAILED) {
		log_error("%s: Merge failed. Retry merge or inspect manually.", lv->name);
		return PROGRESS_CHECK_FAILED;
	}

	if (parms->progress_display)
		log_print("%s: %s: %.1f%%", lv->name, parms->progress_title,
			  100.0 - percent_to_float(percent));
	else
		log_verbose("%s: %s: %.1f%%", lv->name, parms->progress_title,
			    100.0 - percent_to_float(percent));

	if (percent == PERCENT_0)
		return PROGRESS_FINISHED_ALL;

	return PROGRESS_UNFINISHED;
}

static struct poll_functions _lvconvert_mirror_fns = {
	.get_copy_vg = _get_lvconvert_vg,
	.get_copy_lv = _get_lvconvert_lv,
	.poll_progress = poll_mirror_progress,
	.finish_copy = _finish_lvconvert_mirror,
};

static struct poll_functions _lvconvert_merge_fns = {
	.get_copy_vg = _get_lvconvert_vg,
	.get_copy_lv = _get_lvconvert_lv,
	.poll_progress = _poll_merge_progress,
	.finish_copy = _finish_lvconvert_merge,
};

int lvconvert_poll(struct cmd_context *cmd, struct logical_volume *lv,
		   unsigned background)
{
	/*
	 * FIXME allocate an "object key" structure with split
	 * out members (vg_name, lv_name, uuid, etc) and pass that
	 * around the lvconvert and polldaemon code
	 * - will avoid needless work, e.g. extract_vgname()
	 * - unfortunately there are enough overloaded "name" dragons in
	 *   the polldaemon, lvconvert, pvmove code that a comprehensive
	 *   audit/rework is needed
	 */
	int len = strlen(lv->vg->name) + strlen(lv->name) + 2;
	char *uuid = alloca(sizeof(lv->lvid));
	char *lv_full_name = alloca(len);

	if (!uuid || !lv_full_name)
		return_0;

	if (dm_snprintf(lv_full_name, len, "%s/%s", lv->vg->name, lv->name) < 0)
		return_0;

	memcpy(uuid, &lv->lvid, sizeof(lv->lvid));

	if (!lv_is_merging_origin(lv))
		return poll_daemon(cmd, lv_full_name, uuid, background, 0,
				   &_lvconvert_mirror_fns, "Converted");
	else
		return poll_daemon(cmd, lv_full_name, uuid, background, 0,
				   &_lvconvert_merge_fns, "Merged");
}

static int _insert_lvconvert_layer(struct cmd_context *cmd,
				   struct logical_volume *lv)
{
	char *format, *layer_name;
	size_t len;
	int i;

	/*
 	 * We would like to give the same number for this layer
 	 * and the newly added mimage.
 	 * However, LV name of newly added mimage is determined *after*
	 * the LV name of this layer is determined.
	 *
	 * So, use generate_lv_name() to generate mimage name first
	 * and take the number from it.
	 */

	len = strlen(lv->name) + 32;
	if (!(format = alloca(len)) ||
	    !(layer_name = alloca(len)) ||
	    dm_snprintf(format, len, "%s_mimage_%%d", lv->name) < 0) {
		log_error("lvconvert: layer name allocation failed.");
		return 0;
	}

	if (!generate_lv_name(lv->vg, format, layer_name, len) ||
	    sscanf(layer_name, format, &i) != 1) {
		log_error("lvconvert: layer name generation failed.");
		return 0;
	}

	if (dm_snprintf(layer_name, len, MIRROR_SYNC_LAYER "_%d", i) < 0) {
		log_error("layer name allocation failed.");
		return 0;
	}

	if (!insert_layer_for_lv(cmd, lv, 0, layer_name)) {
		log_error("Failed to insert resync layer");
		return 0;
	}

	return 1;
}

static int _failed_mirrors_count(struct logical_volume *lv)
{
	struct lv_segment *lvseg;
	int ret = 0;
	unsigned s;

	dm_list_iterate_items(lvseg, &lv->segments) {
		if (!seg_is_mirrored(lvseg))
			return -1;
		for (s = 0; s < lvseg->area_count; s++) {
			if (seg_type(lvseg, s) == AREA_LV) {
				if (is_temporary_mirror_layer(seg_lv(lvseg, s)))
					ret += _failed_mirrors_count(seg_lv(lvseg, s));
				else if (seg_lv(lvseg, s)->status & PARTIAL_LV)
					++ ret;
				else if (seg_type(lvseg, s) == AREA_PV &&
					 is_missing_pv(seg_pv(lvseg, s)))
					++ret;
			}
		}
	}

	return ret;
}

static int _failed_logs_count(struct logical_volume *lv)
{
	int ret = 0;
	unsigned s;
	struct logical_volume *log_lv = first_seg(lv)->log_lv;
	if (log_lv && (log_lv->status & PARTIAL_LV)) {
		if (log_lv->status & MIRRORED)
			ret += _failed_mirrors_count(log_lv);
		else
			ret += 1;
	}
	for (s = 0; s < first_seg(lv)->area_count; s++) {
		if (seg_type(first_seg(lv), s) == AREA_LV &&
		    is_temporary_mirror_layer(seg_lv(first_seg(lv), s)))
			ret += _failed_logs_count(seg_lv(first_seg(lv), s));
	}
	return ret;
}


static struct dm_list *_failed_pv_list(struct volume_group *vg)
{
	struct dm_list *failed_pvs;
	struct pv_list *pvl, *new_pvl;

	if (!(failed_pvs = dm_pool_alloc(vg->vgmem, sizeof(*failed_pvs)))) {
		log_error("Allocation of list of failed_pvs failed.");
		return_NULL;
	}

	dm_list_init(failed_pvs);

	dm_list_iterate_items(pvl, &vg->pvs) {
		if (!is_missing_pv(pvl->pv))
			continue;

		/* 
		 * Finally, --repair will remove empty PVs.
		 * But we only want remove these which are output of repair,
		 * Do not count these which are already empty here.
		 * FIXME: code should traverse PV in LV not in whole VG.
		 * FIXME: layer violation? should it depend on vgreduce --removemising?
		 */
		if (pvl->pv->pe_alloc_count == 0)
			continue;

		if (!(new_pvl = dm_pool_alloc(vg->vgmem, sizeof(*new_pvl)))) {
			log_error("Allocation of failed_pvs list entry failed.");
			return_NULL;
		}
		new_pvl->pv = pvl->pv;
		dm_list_add(failed_pvs, &new_pvl->list);
	}

	return failed_pvs;
}

static int _is_partial_lv(struct logical_volume *lv,
			  void *baton __attribute__((unused)))
{
	return lv->status & PARTIAL_LV;
}

/*
 * Walk down the stacked mirror LV to the original mirror LV.
 */
static struct logical_volume *_original_lv(struct logical_volume *lv)
{
	struct logical_volume *next_lv = lv, *tmp_lv;

	while ((tmp_lv = find_temporary_mirror(next_lv)))
		next_lv = tmp_lv;

	return next_lv;
}

static void _lvconvert_mirrors_repair_ask(struct cmd_context *cmd,
					  int failed_log, int failed_mirrors,
					  int *replace_log, int *replace_mirrors)
{
	const char *leg_policy = NULL, *log_policy = NULL;

	int force = arg_count(cmd, force_ARG);
	int yes = arg_count(cmd, yes_ARG);

	*replace_log = *replace_mirrors = 1;

	if (arg_count(cmd, use_policies_ARG)) {
		leg_policy = find_config_tree_str(cmd,
					"activation/mirror_image_fault_policy", NULL);
		if (!leg_policy)
			leg_policy = find_config_tree_str(cmd,
					"activation/mirror_device_fault_policy",
					DEFAULT_MIRROR_DEVICE_FAULT_POLICY);
		log_policy = find_config_tree_str(cmd,
					"activation/mirror_log_fault_policy",
					DEFAULT_MIRROR_LOG_FAULT_POLICY);
		*replace_mirrors = strcmp(leg_policy, "remove");
		*replace_log = strcmp(log_policy, "remove");
		return;
	}

	if (yes)
		return;

	if (force != PROMPT) {
		*replace_log = *replace_mirrors = 0;
		return;
	}

	if (failed_log &&
	    yes_no_prompt("Attempt to replace failed mirror log? [y/n]: ") == 'n') {
		*replace_log = 0;
	}

	if (failed_mirrors &&
	    yes_no_prompt("Attempt to replace failed mirror images "
			  "(requires full device resync)? [y/n]: ") == 'n') {
		*replace_mirrors = 0;
	}
}

/*
 * _get_log_count
 * @lv: the mirror LV
 *
 * Get the number of on-disk copies of the log.
 *  0  = 'core'
 *  1  = 'disk'
 *  2+ = 'mirrored'
 */
static int _get_log_count(struct logical_volume *lv)
{
	struct logical_volume *log_lv;

	log_lv = first_seg(_original_lv(lv))->log_lv;
	if (log_lv)
		return lv_mirror_count(log_lv);

	return 0;
}

static int _lv_update_mirrored_log(struct logical_volume *lv,
				   struct dm_list *operable_pvs,
				   int log_count)
{
	int old_log_count;
	struct logical_volume *log_lv;

	/*
	 * When log_count is 0, mirrored log doesn't need to be
	 * updated here but it will be removed later.
	 */
	if (!log_count)
		return 1;

	log_lv = first_seg(_original_lv(lv))->log_lv;
	if (!log_lv || !(log_lv->status & MIRRORED))
		return 1;

	old_log_count = _get_log_count(lv);
	if (old_log_count == log_count)
		return 1;

	/* Reducing redundancy of the log */
	return remove_mirror_images(log_lv, log_count,
				    is_mirror_image_removable,
				    operable_pvs, 0U);
}

static int _reload_lv(struct cmd_context *cmd, struct logical_volume *lv);
static int _lv_update_log_type(struct cmd_context *cmd,
			       struct lvconvert_params *lp,
			       struct logical_volume *lv,
			       struct dm_list *operable_pvs,
			       int log_count)
{
	int old_log_count;
	uint32_t region_size = (lp) ? lp->region_size :
		first_seg(lv)->region_size;
	alloc_policy_t alloc = (lp) ? lp->alloc : lv->alloc;
	struct logical_volume *original_lv;
	struct logical_volume *log_lv;

	old_log_count = _get_log_count(lv);
	if (old_log_count == log_count)
		return 1;

	original_lv = _original_lv(lv);
	/* Remove an existing log completely */
	if (!log_count) {
		if (!remove_mirror_log(cmd, original_lv, operable_pvs,
				       arg_count(cmd, yes_ARG) ||
				       arg_count(cmd, force_ARG)))
			return_0;
		return 1;
	}

	log_lv = first_seg(original_lv)->log_lv;

	/* Adding redundancy to the log */
	if (old_log_count < log_count) {
		region_size = adjusted_mirror_region_size(lv->vg->extent_size,
							  lv->le_count,
							  region_size);

		if (!add_mirror_log(cmd, original_lv, log_count,
				    region_size, operable_pvs, alloc))
			return_0;
		/*
		 * FIXME: This simple approach won't work in cluster mirrors,
		 *        but it doesn't matter because we don't support
		 *        mirrored logs in cluster mirrors.
		 */
		if (old_log_count)
			return _reload_lv(cmd, log_lv);
		return 1;
	}

	/* Reducing redundancy of the log */
	return remove_mirror_images(log_lv, log_count,
				    is_mirror_image_removable, operable_pvs, 1U);
}

/*
 * Reomove missing and empty PVs from VG, if are also in provided list
 */
static void _remove_missing_empty_pv(struct volume_group *vg, struct dm_list *remove_pvs)
{
	struct pv_list *pvl, *pvl_vg, *pvlt;
	int removed = 0;

	if (!remove_pvs)
		return;

	dm_list_iterate_items(pvl, remove_pvs) {
		dm_list_iterate_items_safe(pvl_vg, pvlt, &vg->pvs) {
			if (!id_equal(&pvl->pv->id, &pvl_vg->pv->id) ||
			    !is_missing_pv(pvl_vg->pv) ||
			    pvl_vg->pv->pe_alloc_count != 0)
				continue;

			/* FIXME: duplication of vgreduce code, move this to library */
			vg->free_count -= pvl_vg->pv->pe_count;
			vg->extent_count -= pvl_vg->pv->pe_count;
			del_pvl_from_vgs(vg, pvl_vg);
			free_pv_fid(pvl_vg->pv);

			removed++;
		}
	}

	if (removed) {
		if (!vg_write(vg) || !vg_commit(vg)) {
			stack;
			return;
		}
		log_warn("%d missing and now unallocated Physical Volumes removed from VG.", removed);
	}
}

/*
 * _lvconvert_mirrors_parse_params
 *
 * This function performs the following:
 *  1) Gets the old values of mimage and log counts
 *  2) Parses the CLI args to find the new desired values
 *  3) Adjusts 'lp->mirrors' to the appropriate absolute value.
 *     (Remember, 'lp->mirrors' is specified in terms of the number of "copies"
 *      vs. the number of mimages.  It can also be a relative value.)
 *  4) Sets 'lp->need_polling' if collapsing
 *  5) Validates other mirror params
 *
 * Returns: 1 on success, 0 on error
 */
static int _lvconvert_mirrors_parse_params(struct cmd_context *cmd,
					   struct logical_volume *lv,
					   struct lvconvert_params *lp,
					   uint32_t *old_mimage_count,
					   uint32_t *old_log_count,
					   uint32_t *new_mimage_count,
					   uint32_t *new_log_count)
{
	int repair = arg_count(cmd, repair_ARG);
	const char *mirrorlog;
	*old_mimage_count = lv_mirror_count(lv);
	*old_log_count = _get_log_count(lv);

	/*
	 * Collapsing a stack of mirrors:
	 *
	 * If called with no argument, try collapsing the resync layers
	 */
	if (!arg_count(cmd, mirrors_ARG) && !arg_count(cmd, mirrorlog_ARG) &&
	    !arg_count(cmd, corelog_ARG) && !arg_count(cmd, regionsize_ARG) &&
	    !arg_count(cmd, splitmirrors_ARG) && !repair) {
		*new_mimage_count = *old_mimage_count;
		*new_log_count = *old_log_count;

		if (find_temporary_mirror(lv) || (lv->status & CONVERTING))
			lp->need_polling = 1;
		return 1;
	}

	if ((arg_count(cmd, mirrors_ARG) && repair) ||
	    (arg_count(cmd, mirrorlog_ARG) && repair) ||
	    (arg_count(cmd, corelog_ARG) && repair)) {
		log_error("--repair cannot be used with --mirrors, --mirrorlog,"
			  " or --corelog");
		return 0;
	}

	if (arg_count(cmd, mirrorlog_ARG) && arg_count(cmd, corelog_ARG)) {
		log_error("--mirrorlog and --corelog are incompatible");
		return 0;
	}

	/*
	 * Adjusting mimage count?
	 */
	if (!arg_count(cmd, mirrors_ARG) && !arg_count(cmd, splitmirrors_ARG))
		lp->mirrors = *old_mimage_count;
	else if (lp->mirrors_sign == SIGN_PLUS)
		lp->mirrors = *old_mimage_count + lp->mirrors;
	else if (lp->mirrors_sign == SIGN_MINUS)
		lp->mirrors = (*old_mimage_count > lp->mirrors) ?
			*old_mimage_count - lp->mirrors: 0;
	else
		lp->mirrors += 1;

	*new_mimage_count = lp->mirrors;

	/* Too many mimages? */
	if (lp->mirrors > DEFAULT_MIRROR_MAX_IMAGES) {
		log_error("Only up to %d images in mirror supported currently.",
			  DEFAULT_MIRROR_MAX_IMAGES);
		return 0;
	}

	/* Did the user try to subtract more legs than available? */
	if (lp->mirrors < 1) {
		log_error("Unable to reduce images by specified amount - only %d in %s",
			  *old_mimage_count, lv->name);
		return 0;
	}

	/*
	 * FIXME: It would be nice to say what we are adjusting to, but
	 * I really don't know whether to specify the # of copies or mimages.
	 */
	if (*old_mimage_count != *new_mimage_count)
		log_verbose("Adjusting mirror image count of %s", lv->name);

	/*
	 * Adjust log type
	 *
	 * If we are converting from a mirror to another mirror or simply
	 * changing the log type, we start by assuming they want the log
	 * type the same and then parse the given args.  OTOH, If we are
	 * converting from linear to mirror, then we start from the default
	 * position that the user would like a 'disk' log.
	 */
	*new_log_count = (*old_mimage_count > 1) ? *old_log_count : 1;
	if (!arg_count(cmd, corelog_ARG) && !arg_count(cmd, mirrorlog_ARG))
		return 1;

	if (arg_count(cmd, corelog_ARG))
		*new_log_count = 0;

	mirrorlog = arg_str_value(cmd, mirrorlog_ARG,
				  !*new_log_count ? "core" : DEFAULT_MIRRORLOG);

	if (!strcmp("mirrored", mirrorlog))
		*new_log_count = 2;
	else if (!strcmp("disk", mirrorlog))
		*new_log_count = 1;
	else if (!strcmp("core", mirrorlog))
		*new_log_count = 0;
	else {
		log_error("Unknown mirrorlog type: %s", mirrorlog);
		return 0;
	}

	/*
	 * No mirrored logs for cluster mirrors until
	 * log daemon is multi-threaded.
	 */
	if ((*new_log_count == 2) && vg_is_clustered(lv->vg)) {
		log_error("Log type, \"mirrored\", is unavailable to cluster mirrors");
		return 0;
	}

	log_verbose("Setting logging type to %s", mirrorlog);

	/*
	 * Region size must not change on existing mirrors
	 */
	if (arg_count(cmd, regionsize_ARG) && (lv->status & MIRRORED) &&
	    (lp->region_size != first_seg(lv)->region_size)) {
		log_error("Mirror log region size cannot be changed on "
			  "an existing mirror.");
		return 0;
	}

	/*
	 * For the most part, we cannot handle multi-segment mirrors. Bail out
	 * early if we have encountered one.
	 */
	if ((lv->status & MIRRORED) && dm_list_size(&lv->segments) != 1) {
		log_error("Logical volume %s has multiple "
			  "mirror segments.", lv->name);
		return 0;
	}

	return 1;
}

static int _reload_lv(struct cmd_context *cmd, struct logical_volume *lv)
{
	log_very_verbose("Updating logical volume \"%s\" on disk(s)", lv->name);

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

	if (!suspend_lv(cmd, lv)) {
		log_error("Failed to lock %s", lv->name);
		vg_revert(lv->vg);
		return 0;
	}

	if (!vg_commit(lv->vg)) {
		if (!resume_lv(cmd, lv))
			stack;
		return_0;
	}

	log_very_verbose("Updating \"%s\" in kernel", lv->name);

	if (!resume_lv(cmd, lv)) {
		log_error("Problem reactivating %s", lv->name);
		return 0;
	}
	return 1;
}

/*
 * _lvconvert_mirrors_aux
 *
 * Add/remove mirror images and adjust log type.  'operable_pvs'
 * are the set of PVs open to removal or allocation - depending
 * on the operation being performed.
 */
static int _lvconvert_mirrors_aux(struct cmd_context *cmd,
				  struct logical_volume *lv,
				  struct lvconvert_params *lp,
				  struct dm_list *operable_pvs,
				  uint32_t new_mimage_count,
				  uint32_t new_log_count)
{
	uint32_t region_size;
	struct lv_segment *seg;
	struct logical_volume *layer_lv;
	uint32_t old_mimage_count = lv_mirror_count(lv);
	uint32_t old_log_count = _get_log_count(lv);

	if ((lp->mirrors == 1) && !(lv->status & MIRRORED)) {
		log_error("Logical volume %s is already not mirrored.",
			  lv->name);
		return 1;
	}

	region_size = adjusted_mirror_region_size(lv->vg->extent_size,
						  lv->le_count,
						  lp->region_size);

	if (!operable_pvs)
		operable_pvs = lp->pvh;

	seg = first_seg(lv);

	/*
	 * Up-convert from linear to mirror
	 */
	if (!(lv->status & MIRRORED)) {
		/* FIXME Share code with lvcreate */

		/*
		 * FIXME should we give not only lp->pvh, but also all PVs
		 * currently taken by the mirror? Would make more sense from
		 * user perspective.
		 */
		if (!lv_add_mirrors(cmd, lv, new_mimage_count - 1, lp->stripes,
				    lp->stripe_size, region_size, new_log_count, operable_pvs,
				    lp->alloc, MIRROR_BY_LV))
			return_0;

		if (lp->wait_completion)
			lp->need_polling = 1;

		goto out;
	}

	/*
	 * Up-convert m-way mirror to n-way mirror
	 */
	if (new_mimage_count > old_mimage_count) {
		if (lv->status & LV_NOTSYNCED) {
			log_error("Can't add mirror to out-of-sync mirrored "
				  "LV: use lvchange --resync first.");
			return 0;
		}

		/*
		 * We allow snapshots of mirrors, but for now, we
		 * do not allow up converting mirrors that are under
		 * snapshots.  The layering logic is somewhat complex,
		 * and preliminary test show that the conversion can't
		 * seem to get the correct %'age of completion.
		 */
		if (lv_is_origin(lv)) {
			log_error("Can't add additional mirror images to "
				  "mirrors that are under snapshots");
			return 0;
		}

		/*
		 * Is there already a convert in progress?  We do not
		 * currently allow more than one.
		 */
		if (find_temporary_mirror(lv) || (lv->status & CONVERTING)) {
			log_error("%s is already being converted.  Unable to start another conversion.",
				  lv->name);
			return 0;
		}

		/*
		 * Log addition/removal should be done before the layer
		 * insertion to make the end result consistent with
		 * linear-to-mirror conversion.
		 */
		if (!_lv_update_log_type(cmd, lp, lv,
					 operable_pvs, new_log_count)) {
			stack;
			return 0;
		}

		/* Insert a temporary layer for syncing,
		 * only if the original lv is using disk log. */
		if (seg->log_lv && !_insert_lvconvert_layer(cmd, lv)) {
			log_error("Failed to insert resync layer");
			return 0;
		}

		/* FIXME: can't have multiple mlogs. force corelog. */
		if (!lv_add_mirrors(cmd, lv,
				    new_mimage_count - old_mimage_count,
				    lp->stripes, lp->stripe_size,
				    region_size, 0U, operable_pvs, lp->alloc,
				    MIRROR_BY_LV)) {
			layer_lv = seg_lv(first_seg(lv), 0);
			if (!remove_layer_from_lv(lv, layer_lv) ||
			    !deactivate_lv(cmd, layer_lv) ||
			    !lv_remove(layer_lv) || !vg_write(lv->vg) ||
			    !vg_commit(lv->vg)) {
				log_error("ABORTING: Failed to remove "
					  "temporary mirror layer %s.",
					  layer_lv->name);
				log_error("Manual cleanup with vgcfgrestore "
					  "and dmsetup may be required.");
				return 0;
			}
			stack;
			return 0;
		}
		if (seg->log_lv)
			lv->status |= CONVERTING;
		lp->need_polling = 1;

		goto out_skip_log_convert;
	}

	/*
	 * Down-convert (reduce # of mimages).
	 */
	if (new_mimage_count < old_mimage_count) {
		uint32_t nmc = old_mimage_count - new_mimage_count;
		uint32_t nlc = (!new_log_count || lp->mirrors == 1) ? 1U : 0U;

		/* FIXME: Why did nlc used to be calculated that way? */

		/* Reduce number of mirrors */
		if (lp->keep_mimages) {
			if (arg_count(cmd, trackchanges_ARG)) {
				log_error("--trackchanges is not available "
					  "to 'mirror' segment type");
				return 0;
			}
			if (!lv_split_mirror_images(lv, lp->lv_split_name,
						    nmc, operable_pvs))
				return 0;
		} else if (!lv_remove_mirrors(cmd, lv, nmc, nlc,
					      is_mirror_image_removable, operable_pvs, 0))
			return_0;

		goto out; /* Just in case someone puts code between */
	}

out:
	/*
	 * Converting the log type
	 */
	if ((lv->status & MIRRORED) && (old_log_count != new_log_count)) {
		if (!_lv_update_log_type(cmd, lp, lv,
					 operable_pvs, new_log_count)) {
			stack;
			return 0;
		}
	}

out_skip_log_convert:

	if (!_reload_lv(cmd, lv))
		return 0;

	return 1;
}

int mirror_remove_missing(struct cmd_context *cmd,
			  struct logical_volume *lv, int force)
{
	struct dm_list *failed_pvs;
	int log_count = _get_log_count(lv) - _failed_logs_count(lv);

	if (!(failed_pvs = _failed_pv_list(lv->vg)))
		return_0;

	/* No point in keeping a log if the result is not a mirror */
	if (_failed_mirrors_count(lv) + 1 >= lv_mirror_count(lv))
		log_count = 0;

        if (force && _failed_mirrors_count(lv) == lv_mirror_count(lv)) {
		log_error("No usable images left in %s.", lv->name);
		return lv_remove_with_dependencies(cmd, lv, DONT_PROMPT, 0);
        }

	/*
	 * We must adjust the log first, or the entire mirror
	 * will get stuck during a suspend.
	 */
	if (!_lv_update_mirrored_log(lv, failed_pvs, log_count))
		return 0;

	if (_failed_mirrors_count(lv) > 0 &&
	    !lv_remove_mirrors(cmd, lv, _failed_mirrors_count(lv),
			       log_count ? 0U : 1U,
			       _is_partial_lv, NULL, 0))
		return 0;

	if (!_lv_update_log_type(cmd, NULL, lv, failed_pvs,
				 log_count))
		return 0;

	if (!_reload_lv(cmd, lv))
		return 0;

	return 1;
}

/*
 * _lvconvert_mirrors_repair
 *
 * This function operates in two phases.  First, all of the bad
 * devices are removed from the mirror.  Then, if desired by the
 * user, the devices are replaced.
 *
 * 'old_mimage_count' and 'old_log_count' are there so we know
 * what to convert to after the removal of devices.
 */
static int _lvconvert_mirrors_repair(struct cmd_context *cmd,
				     struct logical_volume *lv,
				     struct lvconvert_params *lp)
{
	int failed_logs = 0;
	int failed_mimages = 0;
	int replace_logs = 0;
	int replace_mimages = 0;
	uint32_t log_count;

	uint32_t original_mimages = lv_mirror_count(lv);
	uint32_t original_logs = _get_log_count(lv);

	cmd->handles_missing_pvs = 1;
	cmd->partial_activation = 1;
	lp->need_polling = 0;

	lv_check_transient(lv); /* TODO check this in lib for all commands? */

	if (!(lv->status & PARTIAL_LV)) {
		log_error("%s is consistent. Nothing to repair.", lv->name);
		return 1;
	}

	failed_mimages = _failed_mirrors_count(lv);
	failed_logs = _failed_logs_count(lv);

	mirror_remove_missing(cmd, lv, 0);

	if (failed_mimages)
		log_error("Mirror status: %d of %d images failed.",
			  failed_mimages, original_mimages);

	/*
	 * Count the failed log devices
	 */
	if (failed_logs)
		log_error("Mirror log status: %d of %d images failed.",
			  failed_logs, original_logs);

	/*
	 * Find out our policies
	 */
	_lvconvert_mirrors_repair_ask(cmd, failed_logs, failed_mimages,
				      &replace_logs, &replace_mimages);

	/*
	 * Second phase - replace faulty devices
	 */
	lp->mirrors = replace_mimages ? original_mimages : (original_mimages - failed_mimages);

	/*
	 * It does not make sense to replace the log if the volume is no longer
	 * a mirror.
	 */
	if (lp->mirrors == 1)
		replace_logs = 0;

	log_count = replace_logs ? original_logs : (original_logs - failed_logs);

	while (replace_mimages || replace_logs) {
		log_warn("Trying to up-convert to %d images, %d logs.", lp->mirrors, log_count);
		if (_lvconvert_mirrors_aux(cmd, lv, lp, NULL,
					   lp->mirrors, log_count))
			break;
		else {
			if (lp->mirrors > 2)
				-- lp->mirrors;
			else if (log_count > 0)
				-- log_count;
			else
				break; /* nowhere to go, anymore... */
		}
	}

	if (replace_mimages && lv_mirror_count(lv) != original_mimages)
		log_warn("WARNING: Failed to replace %d of %d images in volume %s",
			 original_mimages - lv_mirror_count(lv), original_mimages, lv->name);
	if (replace_logs && _get_log_count(lv) != original_logs)
		log_warn("WARNING: Failed to replace %d of %d logs in volume %s",
			 original_logs - _get_log_count(lv), original_logs, lv->name);

	/* if (!arg_count(cmd, use_policies_ARG) && (lp->mirrors != old_mimage_count
						  || log_count != old_log_count))
						  return 0; */

	return 1;
}

/*
 * _lvconvert_mirrors
 *
 * Determine what is being done.  Are we doing a conversion, repair, or
 * collapsing a stack?  Once determined, call helper functions.
 */
static int _lvconvert_mirrors(struct cmd_context *cmd,
			      struct logical_volume *lv,
			      struct lvconvert_params *lp)
{
	int repair = arg_count(cmd, repair_ARG);
	uint32_t old_mimage_count;
	uint32_t old_log_count;
	uint32_t new_mimage_count;
	uint32_t new_log_count;

	if (lp->merge_mirror) {
		log_error("Unable to merge mirror images"
			  "of segment type 'mirror'");
		return 0;
	}

	/* Adjust mimage and/or log count */
	if (!_lvconvert_mirrors_parse_params(cmd, lv, lp,
					     &old_mimage_count, &old_log_count,
					     &new_mimage_count, &new_log_count))
		return 0;

        if (((old_mimage_count < new_mimage_count && old_log_count > new_log_count) ||
             (old_mimage_count > new_mimage_count && old_log_count < new_log_count)) &&
            lp->pv_count) {
		log_error("Cannot both allocate and free extents when "
			  "specifying physical volumes to use.");
		log_error("Please specify the operation in two steps.");
		return 0;
        }

	/* Nothing to do?  (Probably finishing collapse.) */
	if ((old_mimage_count == new_mimage_count) &&
	    (old_log_count == new_log_count) && !repair)
		return 1;

	if (repair)
		return _lvconvert_mirrors_repair(cmd, lv, lp);

	if (!_lvconvert_mirrors_aux(cmd, lv, lp, NULL,
				    new_mimage_count, new_log_count))
		return 0;

	if (!lp->need_polling)
		log_print("Logical volume %s converted.", lv->name);

	backup(lv->vg);
	return 1;
}

static int is_valid_raid_conversion(const struct segment_type *from_segtype,
				    const struct segment_type *to_segtype)
{
	if (from_segtype == to_segtype)
		return 1;

	if (!segtype_is_raid(from_segtype) && !segtype_is_raid(to_segtype))
		return_0;  /* Not converting to or from RAID? */

	return 1;
}

static void _lvconvert_raid_repair_ask(struct cmd_context *cmd, int *replace_dev)
{
	const char *dev_policy = NULL;

	int force = arg_count(cmd, force_ARG);
	int yes = arg_count(cmd, yes_ARG);

	*replace_dev = 0;

	if (arg_count(cmd, use_policies_ARG)) {
		dev_policy = find_config_tree_str(cmd, "activation/raid_fault_policy", DEFAULT_RAID_FAULT_POLICY);

		if (!strcmp(dev_policy, "allocate") ||
		    !strcmp(dev_policy, "replace"))
			*replace_dev = 1;
		/* else if (!strcmp(dev_policy, "anything_else")) -- ignore */
		return;
	}

	if (yes) {
		*replace_dev = 1;
		return;
	}

	if (force != PROMPT)
		return;

	if (yes_no_prompt("Attempt to replace failed RAID images "
			  "(requires full device resync)? [y/n]: ") == 'y') {
		*replace_dev = 1;
	}
}

static int lvconvert_raid(struct logical_volume *lv, struct lvconvert_params *lp)
{
	int replace = 0;
	int uninitialized_var(image_count);
	struct dm_list *failed_pvs;
	struct cmd_context *cmd = lv->vg->cmd;
	struct lv_segment *seg = first_seg(lv);

	if (!arg_count(cmd, type_ARG))
		lp->segtype = seg->segtype;

	/* Can only change image count for raid1 and linear */
	if (arg_count(cmd, mirrors_ARG) &&
	    !seg_is_mirrored(seg) && !seg_is_linear(seg)) {
		log_error("'--mirrors/-m' is not compatible with %s",
			  seg->segtype->name);
		return 0;
	}

	if (!is_valid_raid_conversion(seg->segtype, lp->segtype)) {
		log_error("Unable to convert %s/%s from %s to %s",
			  lv->vg->name, lv->name,
			  seg->segtype->name, lp->segtype->name);
		return 0;
	}

	/* Change number of RAID1 images */
	if (arg_count(cmd, mirrors_ARG) || arg_count(cmd, splitmirrors_ARG)) {
		image_count = lv_raid_image_count(lv);
		if (lp->mirrors_sign == SIGN_PLUS)
			image_count += lp->mirrors;
		else if (lp->mirrors_sign == SIGN_MINUS)
			image_count -= lp->mirrors;
		else
			image_count = lp->mirrors + 1;

		if (image_count < 1) {
			log_error("Unable to %s images by specified amount",
				  arg_count(cmd, splitmirrors_ARG) ?
				  "split" : "reduce");
			return 0;
		}
	}

	if (lp->merge_mirror)
		return lv_raid_merge(lv);

	if (arg_count(cmd, trackchanges_ARG))
		return lv_raid_split_and_track(lv, lp->pvh);

	if (arg_count(cmd, splitmirrors_ARG))
		return lv_raid_split(lv, lp->lv_split_name,
				     image_count, lp->pvh);

	if (arg_count(cmd, mirrors_ARG))
		return lv_raid_change_image_count(lv, image_count, lp->pvh);

	if (arg_count(cmd, type_ARG))
		return lv_raid_reshape(lv, lp->segtype);

	if (arg_count(cmd, replace_ARG))
		return lv_raid_replace(lv, lp->replace_pvh, lp->pvh);

	if (arg_count(cmd, repair_ARG)) {
		_lvconvert_raid_repair_ask(cmd, &replace);

		if (replace) {
			if (!(failed_pvs = _failed_pv_list(lv->vg)))
				return_0;

			if (!lv_raid_replace(lv, failed_pvs, lp->pvh)) {
				log_error("Failed to replace faulty devices in"
					  " %s/%s.", lv->vg->name, lv->name);
				return 0;
			}

			log_print("Faulty devices in %s/%s successfully"
				  " replaced.", lv->vg->name, lv->name);
			return 1;
		}

		/* "warn" if policy not set to replace */
		if (arg_count(cmd, use_policies_ARG))
			log_error("Use 'lvconvert --repair %s/%s' to "
				  "replace failed device",
				  lv->vg->name, lv->name);
		return 1;
	}

	log_error("Conversion operation not yet supported.");
	return 0;
}

static int lvconvert_snapshot(struct cmd_context *cmd,
			      struct logical_volume *lv,
			      struct lvconvert_params *lp)
{
	struct logical_volume *org;
	int r = 0;

	if (!(org = find_lv(lv->vg, lp->origin))) {
		log_error("Couldn't find origin volume '%s'.", lp->origin);
		return 0;
	}

	if (org == lv) {
		log_error("Unable to use \"%s\" as both snapshot and origin.",
			  lv->name);
		return 0;
	}

	if (org->status & (LOCKED|PVMOVE|MIRRORED) || lv_is_cow(org)) {
		log_error("Unable to convert an LV into a snapshot of a %s LV.",
			  org->status & LOCKED ? "locked" :
			  org->status & PVMOVE ? "pvmove" :
			  org->status & MIRRORED ? "mirrored" :
			  "snapshot");
		return 0;
	}

	if (!lp->zero || !(lv->status & LVM_WRITE))
		log_warn("WARNING: \"%s\" not zeroed", lv->name);
	else if (!set_lv(cmd, lv, UINT64_C(0), 0)) {
		log_error("Aborting. Failed to wipe snapshot "
			  "exception store.");
		return 0;
	}

	if (!deactivate_lv(cmd, lv)) {
		log_error("Couldn't deactivate LV %s.", lv->name);
		return 0;
	}

	if (!vg_add_snapshot(org, lv, NULL, org->le_count, lp->chunk_size)) {
		log_error("Couldn't create snapshot.");
		return 0;
	}

	/* store vg on disk(s) */
	if (!vg_write(lv->vg))
		return_0;

	if (!suspend_lv(cmd, org)) {
		log_error("Failed to suspend origin %s", org->name);
		vg_revert(lv->vg);
		goto out;
	}

	if (!vg_commit(lv->vg))
		goto_out;

	if (!resume_lv(cmd, org)) {
		log_error("Problem reactivating origin %s", org->name);
		goto out;
	}

	log_print("Logical volume %s converted to snapshot.", lv->name);
	r = 1;
out:
	backup(lv->vg);
	return r;
}

static int lvconvert_merge(struct cmd_context *cmd,
			   struct logical_volume *lv,
			   struct lvconvert_params *lp)
{
	int r = 0;
	int merge_on_activate = 0;
	struct logical_volume *origin = origin_from_cow(lv);
	struct lv_segment *cow_seg = find_cow(lv);
	struct lvinfo info;

	/* Check if merge is possible */
	if (lv_is_merging_cow(lv)) {
		log_error("Snapshot %s is already merging", lv->name);
		return 0;
	}
	if (lv_is_merging_origin(origin)) {
		log_error("Snapshot %s is already merging into the origin",
			  find_merging_cow(origin)->cow->name);
		return 0;
	}

	/*
	 * Prevent merge with open device(s) as it would likely lead
	 * to application/filesystem failure.  Merge on origin's next
	 * activation if either the origin or snapshot LV are currently
	 * open.
	 *
	 * FIXME testing open_count is racey; snapshot-merge target's
	 * constructor and DM should prevent appropriate devices from
	 * being open.
	 */
	if (lv_info(cmd, origin, 0, &info, 1, 0)) {
		if (info.open_count) {
			log_error("Can't merge over open origin volume");
			merge_on_activate = 1;
		}
	}
	if (lv_info(cmd, lv, 0, &info, 1, 0)) {
		if (info.open_count) {
			log_print("Can't merge when snapshot is open");
			merge_on_activate = 1;
		}
	}

	init_snapshot_merge(cow_seg, origin);

	/* store vg on disk(s) */
	if (!vg_write(lv->vg))
		return_0;

	if (merge_on_activate) {
		/* commit vg but skip starting the merge */
		if (!vg_commit(lv->vg))
			return_0;
		r = 1;
		log_print("Merging of snapshot %s will start "
			  "next activation.", lv->name);
		goto out;
	}

	/* Perform merge */
	if (!suspend_lv(cmd, origin)) {
		log_error("Failed to suspend origin %s", origin->name);
		vg_revert(lv->vg);
		goto out;
	}

	if (!vg_commit(lv->vg)) {
		if (!resume_lv(cmd, origin))
			stack;
		goto_out;
	}

	if (!resume_lv(cmd, origin)) {
		log_error("Failed to reactivate origin %s", origin->name);
		goto out;
	}

	lp->need_polling = 1;
	lp->lv_to_poll = origin;

	r = 1;
	log_print("Merging of volume %s started.", lv->name);
out:
	backup(lv->vg);
	return r;
}

static int _lvconvert_thinpool(struct cmd_context *cmd,
			       struct logical_volume *metadata_lv,
			       struct lvconvert_params *lp)
{
	int r = 0;
	char *name;
	int len;
	int was_active;
	struct lv_segment *seg;
	struct logical_volume *data_lv;
	struct logical_volume *pool_lv =
		(lp->pool_data_lv_name == lp->lv_name) ?
		metadata_lv : find_lv(metadata_lv->vg,
				      lp->pool_data_lv_name);

	if (!pool_lv) {
		log_error("Can't find pool logical volume %s.", lp->lv_name);
		return 0;
	}

	if ((pool_lv != metadata_lv)) {
		if (!lv_is_visible(metadata_lv)) {
			log_error("Can't use hidden logical volume %s/%s for thin pool metadata.",
				  metadata_lv->vg->name, metadata_lv->name);
			goto out;
		}
		if (lv_is_thin_pool(metadata_lv)) {
			log_error("Can't use thin pool logical volume %s/%s for thin pool metadata.",
				  metadata_lv->vg->name, metadata_lv->name);
			goto out;
		}
		/* FIXME: any more types prohibited here ? */
		if (!deactivate_lv(cmd, metadata_lv)) {
			log_error("Can't deactivate logical volume %s/%s.",
				  metadata_lv->vg->name, metadata_lv->name);
			goto out;
		}
		/* FIXME: initialize metadata LV! */
	} else {
		/* FIXME: add creation of metadata LV */
	}

	if (!lv_is_visible(pool_lv)) {
		log_error("Can't use hidden logical volume %s/%s for thin pool data.",
			  metadata_lv->vg->name, metadata_lv->name);
		goto out;
	}
	if (lv_is_thin_pool(pool_lv)) {
		log_error("Can't use thin pool logical volume %s/%s for thin pool data.",
			  metadata_lv->vg->name, metadata_lv->name);
		goto out;
	}
	/* FIXME: any more types prohibited here ? */
	if ((was_active = lv_is_active(pool_lv))) {
		if (!deactivate_lv(cmd, pool_lv)) {
			log_error("Can't deactivate logical volume %s/%s.",
				  pool_lv->vg->name, pool_lv->name);
			goto out;
		}
	}

	/* FIXME: common code with metadata/thin_manip.c  extend_pool() */
	if (!(data_lv = insert_layer_for_lv(pool_lv->vg->cmd, pool_lv,
					    pool_lv->status, "_tdata")))
		return_0;

	seg = first_seg(pool_lv);
	seg->segtype = lp->segtype;
	seg->lv->status |= THIN_POOL;

	seg->chunk_size = lp->chunk_size;
	seg->zero_new_blocks = lp->zero ? 1 : 0;
	seg->low_water_mark = 0;

	len = strlen(pool_lv->name) + 16;
	if (!(name = dm_pool_alloc(pool_lv->vg->vgmem, len))) {
		log_error("Cannot allocate new name.");
		return 0;
	}

	if (dm_snprintf(name, len, "%s_tmeta", pool_lv->name) < 0)
		return_0;
	metadata_lv->name = name;

	if (!attach_pool_metadata_lv(seg, metadata_lv))
		return_0;

	/* Drop reference as attach_pool_data_lv() takes it again */
	remove_seg_from_segs_using_this_lv(data_lv, seg);
	if (!attach_pool_data_lv(seg, data_lv))
		return_0;

	/* store vg on disk(s) */
	if (!vg_write(pool_lv->vg) || !vg_commit(pool_lv->vg))
		return_0;

	log_print("Converted %s/%s to thin pool.",
		  pool_lv->vg->name, pool_lv->name);
	if (was_active && !activate_lv(cmd, pool_lv)) {
		log_error("Failed to activate pool logical volume %s/%s.",
			  pool_lv->vg->name, pool_lv->name);
		goto out;
	}

	r = 1;
out:
	backup(pool_lv->vg);
	return r;
}

static int _lvconvert_single(struct cmd_context *cmd, struct logical_volume *lv,
			     void *handle)
{
	struct lvconvert_params *lp = handle;
	struct dm_list *failed_pvs;
	struct lvinfo info;
	percent_t snap_percent;

	if (lv->status & LOCKED) {
		log_error("Cannot convert locked LV %s", lv->name);
		return ECMD_FAILED;
	}

	if (lv_is_cow(lv) && !lp->merge) {
		log_error("Can't convert snapshot logical volume \"%s\"",
			  lv->name);
		return ECMD_FAILED;
	}

	if (lv->status & PVMOVE) {
		log_error("Unable to convert pvmove LV %s", lv->name);
		return ECMD_FAILED;
	}

	if (arg_count(cmd, repair_ARG) &&
	    !(lv->status & MIRRORED) && !(lv->status & RAID)) {
		if (arg_count(cmd, use_policies_ARG))
			return ECMD_PROCESSED; /* nothing to be done here */
		log_error("Can't repair non-mirrored LV \"%s\".", lv->name);
		return ECMD_FAILED;
	}

	if (!lp->segtype)
		lp->segtype = first_seg(lv)->segtype;

	if (lp->merge) {
		if (!lv_is_cow(lv)) {
			log_error("\"%s\" is not a mergeable logical volume",
				  lv->name);
			return ECMD_FAILED;
		}
	        if (lv_info(lv->vg->cmd, lv, 0, &info, 1, 0)
		    && info.exists && info.live_table &&
		    (!lv_snapshot_percent(lv, &snap_percent) ||
		     snap_percent == PERCENT_INVALID)) {
			log_error("Unable to merge invalidated snapshot LV \"%s\"", lv->name);
			return ECMD_FAILED;
		}
		if (!archive(lv->vg)) {
			stack;
			return ECMD_FAILED;
		}
		if (!lvconvert_merge(cmd, lv, lp)) {
			log_error("Unable to merge LV \"%s\" into its origin.", lv->name);
			return ECMD_FAILED;
		}
	} else if (lp->snapshot) {
		if (lv->status & MIRRORED) {
			log_error("Unable to convert mirrored LV \"%s\" into a snapshot.", lv->name);
			return ECMD_FAILED;
		}
		if (!archive(lv->vg)) {
			stack;
			return ECMD_FAILED;
		}
		if (!lvconvert_snapshot(cmd, lv, lp)) {
			stack;
			return ECMD_FAILED;
		}
	} else if (segtype_is_raid(lp->segtype) ||
		   (lv->status & RAID) || lp->merge_mirror) {
		if (!archive(lv->vg)) {
			stack;
			return ECMD_FAILED;
		}
		if (!lvconvert_raid(lv, lp)) {
			stack;
			return ECMD_FAILED;
		}

		if (!(failed_pvs = _failed_pv_list(lv->vg))) {
			stack;
			return ECMD_FAILED;
		}

		/* If repairing and using policies, remove missing PVs from VG */
		if (arg_count(cmd, repair_ARG) && arg_count(cmd, use_policies_ARG))
			_remove_missing_empty_pv(lv->vg, failed_pvs);
	} else if (arg_count(cmd, mirrors_ARG) ||
		   arg_count(cmd, splitmirrors_ARG) ||
		   (lv->status & MIRRORED)) {
		if (!archive(lv->vg)) {
			stack;
			return ECMD_FAILED;
		}
		if (!_lvconvert_mirrors(cmd, lv, lp)) {
			stack;
			return ECMD_FAILED;
		}

		if (!(failed_pvs = _failed_pv_list(lv->vg))) {
			stack;
			return ECMD_FAILED;
		}

		/* If repairing and using policies, remove missing PVs from VG */
		if (arg_count(cmd, repair_ARG) && arg_count(cmd, use_policies_ARG))
			_remove_missing_empty_pv(lv->vg, failed_pvs);
	} else if (arg_count(cmd, thinpool_ARG)) {
		if (!archive(lv->vg)) {
			stack;
			return ECMD_FAILED;
		}
		if (!_lvconvert_thinpool(cmd, lv, lp)) {
			stack;
			return ECMD_FAILED;
		}
	}

	return ECMD_PROCESSED;
}

/*
 * FIXME move to toollib along with the rest of the drop/reacquire
 * VG locking that is used by lvconvert_merge_single()
 */
static struct logical_volume *get_vg_lock_and_logical_volume(struct cmd_context *cmd,
							     const char *vg_name,
							     const char *lv_name)
{
	/*
	 * Returns NULL if the requested LV doesn't exist;
	 * otherwise the caller must release_vg(lv->vg)
	 * - it is also up to the caller to unlock_vg() as needed
	 */
	struct volume_group *vg;
	struct logical_volume* lv = NULL;

	vg = _get_lvconvert_vg(cmd, vg_name, NULL);
	if (vg_read_error(vg)) {
		release_vg(vg);
		return_NULL;
	}

	if (!(lv = _get_lvconvert_lv(cmd, vg, lv_name, NULL, 0))) {
		log_error("Can't find LV %s in VG %s", lv_name, vg_name);
		unlock_and_release_vg(cmd, vg, vg_name);
		return NULL;
	}

	return lv;
}

static int poll_logical_volume(struct cmd_context *cmd, struct logical_volume *lv,
			       int wait_completion)
{
	struct lvinfo info;

	if (!lv_info(cmd, lv, 0, &info, 0, 0) || !info.exists) {
		log_print("Conversion starts after activation.");
		return ECMD_PROCESSED;
	}
	return lvconvert_poll(cmd, lv, wait_completion ? 0 : 1U);
}

static int lvconvert_single(struct cmd_context *cmd, struct lvconvert_params *lp)
{
	struct logical_volume *lv = NULL;
	int ret = ECMD_FAILED;
	int saved_ignore_suspended_devices = ignore_suspended_devices();

	if (arg_count(cmd, repair_ARG)) {
		init_ignore_suspended_devices(1);
		cmd->handles_missing_pvs = 1;
	}

	lv = get_vg_lock_and_logical_volume(cmd, lp->vg_name, lp->lv_name);
	if (!lv)
		goto_out;

	/*
	 * lp->pvh holds the list of PVs available for allocation or removal
	 */
	if (lp->pv_count) {
		if (!(lp->pvh = create_pv_list(cmd->mem, lv->vg, lp->pv_count,
					      lp->pvs, 0)))
			goto_bad;
	} else
		lp->pvh = &lv->vg->pvs;

	if (lp->replace_pv_count &&
	    !(lp->replace_pvh = create_pv_list(cmd->mem, lv->vg,
					       lp->replace_pv_count,
					       lp->replace_pvs, 0)))
			goto_bad;

	lp->lv_to_poll = lv;
	ret = _lvconvert_single(cmd, lv, lp);
bad:
	unlock_vg(cmd, lp->vg_name);

	if (ret == ECMD_PROCESSED && lp->need_polling)
		ret = poll_logical_volume(cmd, lp->lv_to_poll,
					  lp->wait_completion);

	release_vg(lv->vg);
out:
	init_ignore_suspended_devices(saved_ignore_suspended_devices);
	return ret;
}

static int lvconvert_merge_single(struct cmd_context *cmd, struct logical_volume *lv,
				  void *handle)
{
	struct lvconvert_params *lp = handle;
	const char *vg_name = NULL;
	struct logical_volume *refreshed_lv = NULL;
	int ret;

	/*
	 * FIXME can't trust lv's VG to be current given that caller
	 * is process_each_lv() -- poll_logical_volume() may have
	 * already updated the VG's metadata in an earlier iteration.
	 * - preemptively drop the VG lock, as is needed for
	 *   poll_logical_volume(), refresh LV (and VG in the process).
	 */
	vg_name = lv->vg->name;
	unlock_vg(cmd, vg_name);
	refreshed_lv = get_vg_lock_and_logical_volume(cmd, vg_name, lv->name);
	if (!refreshed_lv) {
		log_error("ABORTING: Can't reread LV %s/%s", vg_name, lv->name);
		return ECMD_FAILED;
	}

	lp->lv_to_poll = refreshed_lv;
	ret = _lvconvert_single(cmd, refreshed_lv, lp);

	if (ret == ECMD_PROCESSED && lp->need_polling) {
		/*
		 * Must drop VG lock, because lvconvert_poll() needs it,
		 * then reacquire it after polling completes
		 */
		unlock_vg(cmd, vg_name);

		ret = poll_logical_volume(cmd, lp->lv_to_poll,
					  lp->wait_completion);

		/* use LCK_VG_WRITE to match lvconvert()'s READ_FOR_UPDATE */
		if (!lock_vol(cmd, vg_name, LCK_VG_WRITE)) {
			log_error("ABORTING: Can't relock VG for %s "
				  "after polling finished", vg_name);
			ret = ECMD_FAILED;
		}
	}

	release_vg(refreshed_lv->vg);

	return ret;
}

int lvconvert(struct cmd_context * cmd, int argc, char **argv)
{
	struct lvconvert_params lp;

	if (!_read_params(&lp, cmd, argc, argv)) {
		stack;
		return EINVALID_CMD_LINE;
	}

	if (lp.merge) {
		if (!argc) {
			log_error("Please provide logical volume path");
			return EINVALID_CMD_LINE;
		}
		return process_each_lv(cmd, argc, argv, READ_FOR_UPDATE, &lp,
				       &lvconvert_merge_single);
	}

	return lvconvert_single(cmd, &lp);
}