summaryrefslogtreecommitdiff
path: root/tools/lvmcmdline.c
blob: 6bbf1af26e44132ca52861e6ff11d8cda44d2305 (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
/*
 * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved.
 * Copyright (C) 2004-2012 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 "tools.h"

#include "lvm2cmdline.h"
#include "lib/label/label.h"
#include "lib/device/device_id.h"
#include "lvm-version.h"
#include "lib/locking/lvmlockd.h"
#include "lib/datastruct/str_list.h"

/* coverity[unnecessary_header] */
#include "stub.h"
#include "lib/misc/last-path-component.h"

#include <sys/stat.h>
#include <time.h>
#include <sys/resource.h>
#include <dirent.h>
#include <paths.h>
#include <locale.h>
#include <langinfo.h>

#ifdef HAVE_VALGRIND
#include <valgrind.h>
#endif

#ifdef HAVE_GETOPTLONG
#  include <getopt.h>
#  define GETOPTLONG_FN(a, b, c, d, e) getopt_long((a), (b), (c), (d), (e))
#  define OPTIND_INIT 0
#else
struct option {
};
extern int optind;
extern char *optarg;
#  define GETOPTLONG_FN(a, b, c, d, e) getopt((a), (b), (c))
#  define OPTIND_INIT 1
#endif


/*
 * Table of valid --option values.
 */
extern struct val_name val_names[VAL_COUNT + 1];

/*
 * Table of valid --option's
 */
extern struct opt_name opt_names[ARG_COUNT + 1];

/*
 * Table of LV properties
 */
extern struct lv_prop lv_props[LVP_COUNT + 1];

/*
 * Table of LV types
 */
extern struct lv_type lv_types[LVT_COUNT + 1];

/*
 * Table of command names
 */
extern struct command_name command_names[];

/*
 * Table of commands (as defined in command-lines.in)
 */
struct command commands[COMMAND_COUNT];
struct command *commands_idx[COMMAND_COUNT];

static struct cmdline_context _cmdline;

/*
 * Table of command line functions
 *
 * This table could be auto-generated once all commands have been converted
 * to use these functions instead of the old per-command-name function.
 * For now, any command id not included here uses the old command fn.
 */
static const struct command_function _command_functions[CMD_COUNT] = {
	{ lvmconfig_general_CMD, lvmconfig },
	{ lvchange_properties_CMD, lvchange_properties_cmd },
	{ lvchange_resync_CMD, lvchange_resync_cmd },
	{ lvchange_syncaction_CMD, lvchange_syncaction_cmd },
	{ lvchange_rebuild_CMD, lvchange_rebuild_cmd },
	{ lvchange_activate_CMD, lvchange_activate_cmd },
	{ lvchange_refresh_CMD, lvchange_refresh_cmd },
	{ lvchange_monitor_CMD, lvchange_monitor_poll_cmd },
	{ lvchange_poll_CMD, lvchange_monitor_poll_cmd },
	{ lvchange_persistent_CMD, lvchange_persistent_cmd },

	{ vgchange_locktype_CMD, vgchange_locktype_cmd },
	{ vgchange_lockstart_CMD, vgchange_lock_start_stop_cmd },
	{ vgchange_lockstop_CMD, vgchange_lock_start_stop_cmd },
	{ vgchange_systemid_CMD, vgchange_systemid_cmd },

	/* lvconvert utilities related to repair. */
	{ lvconvert_repair_CMD,	lvconvert_repair_cmd },
	{ lvconvert_replace_pv_CMD, lvconvert_replace_pv_cmd },

	/* lvconvert utilities related to snapshots. */
	{ lvconvert_split_cow_snapshot_CMD, lvconvert_split_snapshot_cmd },
	{ lvconvert_merge_snapshot_CMD, lvconvert_merge_snapshot_cmd },
	{ lvconvert_combine_split_snapshot_CMD, lvconvert_combine_split_snapshot_cmd },

	/* lvconvert utility to trigger polling on an LV. */
	{ lvconvert_start_poll_CMD, lvconvert_start_poll_cmd },
	{ lvconvert_plain_CMD, lvconvert_start_poll_cmd },

	/* lvconvert utilities for creating/maintaining thin and cache objects. */
	{ lvconvert_to_thinpool_CMD,			lvconvert_to_pool_cmd },
	{ lvconvert_to_cachepool_CMD,			lvconvert_to_pool_cmd },
	{ lvconvert_to_thin_with_external_CMD,		lvconvert_to_thin_with_external_cmd },
	{ lvconvert_to_cache_with_cachevol_CMD,		lvconvert_to_cache_with_cachevol_cmd },
	{ lvconvert_to_cache_with_device_CMD,		lvconvert_to_cache_with_cachevol_cmd },
	{ lvconvert_to_cache_with_cachepool_CMD,	lvconvert_to_cache_with_cachepool_cmd },
	{ lvconvert_to_writecache_CMD,			lvconvert_to_writecache_cmd },
	{ lvconvert_to_writecache_with_device_CMD,	lvconvert_to_writecache_cmd },
	{ lvconvert_swap_pool_metadata_CMD,		lvconvert_swap_pool_metadata_cmd },
	{ lvconvert_to_thinpool_or_swap_metadata_CMD,   lvconvert_to_pool_or_swap_metadata_cmd },
	{ lvconvert_to_cachepool_or_swap_metadata_CMD,  lvconvert_to_pool_or_swap_metadata_cmd },
	{ lvconvert_merge_thin_CMD,			lvconvert_merge_thin_cmd },
	{ lvconvert_split_and_keep_cache_CMD,		lvconvert_split_cache_cmd },
	{ lvconvert_split_and_remove_cache_CMD,		lvconvert_split_cache_cmd },

	/* lvconvert raid-related type conversions */
	{ lvconvert_raid_types_CMD,			lvconvert_raid_types_cmd },

	/* lvconvert utilities for raid/mirror */
	{ lvconvert_split_mirror_images_CMD,		lvconvert_split_mirror_images_cmd},
	{ lvconvert_change_mirrorlog_CMD,		lvconvert_change_mirrorlog_cmd },
	{ lvconvert_merge_mirror_images_CMD,		lvconvert_merge_mirror_images_cmd },
	{ lvconvert_change_region_size_CMD,		lvconvert_change_region_size_cmd },

	/* redirected to merge_snapshot/merge_thin/merge_mirrors */
	{ lvconvert_merge_CMD, lvconvert_merge_cmd },

	/* lvconvert VDO pool */
	{ lvconvert_to_vdopool_CMD, lvconvert_to_vdopool_cmd },
	{ lvconvert_to_vdopool_param_CMD, lvconvert_to_vdopool_param_cmd },

	/* lvconvert for integrity */
	{ lvconvert_integrity_CMD, lvconvert_integrity_cmd },

	/* lvcreate */
	{ lvcreate_and_attach_cachevol_for_cache_CMD,		lvcreate_and_attach_cache_cmd },
	{ lvcreate_and_attach_cachedevice_for_cache_CMD,	lvcreate_and_attach_cache_cmd },
	{ lvcreate_and_attach_cachevol_for_writecache_CMD,	lvcreate_and_attach_writecache_cmd },
	{ lvcreate_and_attach_cachedevice_for_writecache_CMD,	lvcreate_and_attach_writecache_cmd },

	{ pvscan_display_CMD, pvscan_display_cmd },
	{ pvscan_cache_CMD, pvscan_cache_cmd },

	/* lvextend/lvreduce/lvresize */
	{ lvextend_policy_CMD,		lvextend_policy_cmd },
	{ lvextend_pool_metadata_CMD,	lvresize_cmd },
	{ lvresize_pool_metadata_CMD,	lvresize_cmd },
	{ lvextend_pv_CMD,		lvresize_cmd },
	{ lvresize_pv_CMD,		lvresize_cmd },
	{ lvextend_size_CMD,		lvresize_cmd },
	{ lvreduce_size_CMD,		lvresize_cmd },
	{ lvresize_size_CMD,		lvresize_cmd },
};


/* Command line args */
int arg_is_valid_for_command(const struct cmd_context *cmd, int a)
{
	int i;

	for (i = 0; i < cmd->cname->num_args; i++) {
		if (cmd->cname->valid_args[i] == a)
			return 1;
	}

	return 0;
}

unsigned arg_count(const struct cmd_context *cmd, int a)
{
	return cmd->opt_arg_values ? cmd->opt_arg_values[a].count : 0;
}

unsigned grouped_arg_count(const struct arg_values *av, int a)
{
	return av ? av[a].count : 0;
}

unsigned arg_is_set(const struct cmd_context *cmd, int a)
{
	return arg_count(cmd, a) ? 1 : 0;
}

int arg_from_list_is_set(const struct cmd_context *cmd, const char *err_found, ...)
{
	int arg;
	va_list ap;

	va_start(ap, err_found);
	while ((arg = va_arg(ap, int)) != -1 && !arg_is_set(cmd, arg))
		/* empty */;
	va_end(ap);

	if (arg == -1)
		return 0;

	if (err_found)
		log_error("%s %s.", arg_long_option_name(arg), err_found);

	return 1;
}

int arg_outside_list_is_set(const struct cmd_context *cmd, const char *err_found, ...)
{
	int i, arg;
	va_list ap;

	for (i = 0; i < ARG_COUNT; ++i) {
		switch (i) {
		/* skip common options */
		case commandprofile_ARG:
		case config_ARG:
		case debug_ARG:
		case driverloaded_ARG:
		case help2_ARG:
		case help_ARG:
		case profile_ARG:
		case quiet_ARG:
		case verbose_ARG:
		case version_ARG:
		case yes_ARG:
			continue;
		}
		if (!arg_is_set(cmd, i))
			continue; /* unset */
		va_start(ap, err_found);
		while (((arg = va_arg(ap, int)) != -1) && (arg != i))
			/* empty */;
		va_end(ap);

		if (arg == i)
			continue; /* set and in list */

		if (err_found)
			log_error("Option %s %s.", arg_long_option_name(i), err_found);

		return 1;
	}

	return 0;
}

int arg_from_list_is_negative(const struct cmd_context *cmd, const char *err_found, ...)
{
	int arg, ret = 0;
	va_list ap;

	va_start(ap, err_found);
	while ((arg = va_arg(ap, int)) != -1)
		if (arg_sign_value(cmd, arg, SIGN_NONE) == SIGN_MINUS) {
			if (err_found)
				log_error("%s %s.", arg_long_option_name(arg), err_found);
			ret = 1;
		}
	va_end(ap);

	return ret;
}

int arg_from_list_is_zero(const struct cmd_context *cmd, const char *err_found, ...)
{
	int arg, ret = 0;
	va_list ap;

	va_start(ap, err_found);
	while ((arg = va_arg(ap, int)) != -1)
		if (arg_is_set(cmd, arg) &&
		    !arg_int_value(cmd, arg, 0)) {
			if (err_found)
				log_error("%s %s.", arg_long_option_name(arg), err_found);
			ret = 1;
		}
	va_end(ap);

	return ret;
}

unsigned grouped_arg_is_set(const struct arg_values *av, int a)
{
	return grouped_arg_count(av, a) ? 1 : 0;
}

const char *arg_long_option_name(int a)
{
	return _cmdline.opt_names[a].long_opt;
}

const char *arg_value(const struct cmd_context *cmd, int a)
{
	return cmd->opt_arg_values ? cmd->opt_arg_values[a].value : NULL;
}

const char *arg_str_value(const struct cmd_context *cmd, int a, const char *def)
{
	return arg_is_set(cmd, a) ? cmd->opt_arg_values[a].value : def;
}

const char *grouped_arg_str_value(const struct arg_values *av, int a, const char *def)
{
	return grouped_arg_count(av, a) ? av[a].value : def;
}

int32_t grouped_arg_int_value(const struct arg_values *av, int a, const int32_t def)
{
	return grouped_arg_count(av, a) ? av[a].i_value : def;
}

int32_t first_grouped_arg_int_value(const struct cmd_context *cmd, int a, const int32_t def)
{
	struct arg_value_group_list *current_group;
	struct arg_values *av;

	dm_list_iterate_items(current_group, &cmd->arg_value_groups) {
		av = current_group->arg_values;
		if (grouped_arg_count(av, a))
			return grouped_arg_int_value(av, a, def);
	}

	return def;
}

int32_t arg_int_value(const struct cmd_context *cmd, int a, const int32_t def)
{
	return (_cmdline.opt_names[a].flags & ARG_GROUPABLE) ?
		first_grouped_arg_int_value(cmd, a, def) : (arg_is_set(cmd, a) ? cmd->opt_arg_values[a].i_value : def);
}

uint32_t arg_uint_value(const struct cmd_context *cmd, int a, const uint32_t def)
{
	return arg_is_set(cmd, a) ? cmd->opt_arg_values[a].ui_value : def;
}

int64_t arg_int64_value(const struct cmd_context *cmd, int a, const int64_t def)
{
	return arg_is_set(cmd, a) ? cmd->opt_arg_values[a].i64_value : def;
}

uint64_t arg_uint64_value(const struct cmd_context *cmd, int a, const uint64_t def)
{
	return arg_is_set(cmd, a) ? cmd->opt_arg_values[a].ui64_value : def;
}

/* No longer used.
const void *arg_ptr_value(struct cmd_context *cmd, int a, const void *def)
{
	return arg_is_set(cmd, a) ? cmd->opt_arg_values[a].ptr : def;
}
*/

sign_t arg_sign_value(const struct cmd_context *cmd, int a, const sign_t def)
{
	return arg_is_set(cmd, a) ? cmd->opt_arg_values[a].sign : def;
}

percent_type_t arg_percent_value(const struct cmd_context *cmd, int a, const percent_type_t def)
{
	return arg_is_set(cmd, a) ? cmd->opt_arg_values[a].percent : def;
}

int arg_count_increment(struct cmd_context *cmd, int a)
{
	return cmd->opt_arg_values[a].count++;
}

int yes_no_arg(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	av->sign = SIGN_NONE;
	av->percent = PERCENT_NONE;

	if (!strcmp(av->value, "y")) {
		av->i_value = 1;
		av->ui_value = 1;
	}

	else if (!strcmp(av->value, "n")) {
		av->i_value = 0;
		av->ui_value = 0;
	}

	else
		return 0;

	return 1;
}

int activation_arg(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	av->sign = SIGN_NONE;
	av->percent = PERCENT_NONE;

	if (!strcmp(av->value, "e") || !strcmp(av->value, "ey") ||
	    !strcmp(av->value, "ye")) {
		av->i_value = CHANGE_AEY;
		av->ui_value = CHANGE_AEY;
	}

	else if (!strcmp(av->value, "s") || !strcmp(av->value, "sy") ||
		 !strcmp(av->value, "ys")) {
		av->i_value = CHANGE_ASY;
		av->ui_value = CHANGE_ASY;
	}

	else if (!strcmp(av->value, "y")) {
		av->i_value = CHANGE_AY;
		av->ui_value = CHANGE_AY;
	}

	else if (!strcmp(av->value, "a") || !strcmp(av->value, "ay") ||
		 !strcmp(av->value, "ya")) {
		av->i_value = CHANGE_AAY;
		av->ui_value = CHANGE_AAY;
	}

	else if (!strcmp(av->value, "n") || !strcmp(av->value, "en") ||
		 !strcmp(av->value, "ne")) {
		av->i_value = CHANGE_AN;
		av->ui_value = CHANGE_AN;
	}

	else if (!strcmp(av->value, "ln") || !strcmp(av->value, "nl")) {
		av->i_value = CHANGE_ALN;
		av->ui_value = CHANGE_ALN;
	}

	else if (!strcmp(av->value, "ly") || !strcmp(av->value, "yl")) {
		av->i_value = CHANGE_ALY;
		av->ui_value = CHANGE_ALY;
	}

	else
		return 0;

	return 1;
}

int cachemode_arg(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	cache_mode_t mode;

	if (!set_cache_mode(&mode, av->value))
		return_0;

	av->i_value = mode;
	av->ui_value = mode;

	return 1;
}

int cachemetadataformat_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!strcmp(av->value, "auto")) {
		av->i_value = CACHE_METADATA_FORMAT_UNSELECTED;
		av->ui_value = CACHE_METADATA_FORMAT_UNSELECTED;
	} else if (!int_arg(cmd, av))
		return_0;

	switch (av->i_value) {
	case CACHE_METADATA_FORMAT_UNSELECTED:
	case CACHE_METADATA_FORMAT_1:
	case CACHE_METADATA_FORMAT_2:
		return 1;
	}

	log_error("Selected cache metadata format %d is not supported.", av->i_value);
	return 0;
}

int discards_arg(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	thin_discards_t discards;

	if (!set_pool_discards(&discards, av->value))
		return_0;

	av->i_value = discards;
	av->ui_value = discards;

	return 1;
}

int mirrorlog_arg(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	int log_count;

	if (!set_mirror_log_count(&log_count, av->value))
		return_0;

	av->i_value = log_count;
	av->ui_value = log_count;

	return 1;
}

int metadatatype_arg(struct cmd_context *cmd, struct arg_values *av)
{
	return get_format_by_name(cmd, av->value) ? 1 : 0;
}

static int _get_int_arg(struct arg_values *av, char **ptr)
{
	char *val;
	unsigned long long v;

	av->percent = PERCENT_NONE;

	val = av->value;
	switch (*val) {
	case '+':
		av->sign = SIGN_PLUS;
		val++;
		break;
	case '-':
		av->sign = SIGN_MINUS;
		val++;
		break;
	default:
		av->sign = SIGN_NONE;
	}

	if (!isdigit(*val))
		return 0;

	errno = 0;
	v = strtoull(val, ptr, 10);

	if (*ptr == val || errno)
		return 0;

	av->i_value = (v < INT32_MAX) ? (int32_t) v : INT32_MAX;
	av->ui_value = (v < UINT32_MAX) ? (uint32_t) v : UINT32_MAX;
	av->i64_value = (v < INT64_MAX) ? (int64_t) v : INT64_MAX;
	av->ui64_value = (v < UINT64_MAX) ? (uint64_t) v : UINT64_MAX;

	return 1;
}

static int _get_percent_arg(struct arg_values *av, const char *ptr)
{
	if (!strcasecmp(ptr, "V") || !strcasecmp(ptr, "VG"))
		av->percent = PERCENT_VG;
	else if (!strcasecmp(ptr, "L") || !strcasecmp(ptr, "LV"))
		av->percent = PERCENT_LV;
	else if (!strcasecmp(ptr, "P") || !strcasecmp(ptr, "PV") ||
		 !strcasecmp(ptr, "PVS"))
		av->percent = PERCENT_PVS;
	else if (!strcasecmp(ptr, "F") || !strcasecmp(ptr, "FR") ||
		 !strcasecmp(ptr, "FREE"))
		av->percent = PERCENT_FREE;
	else if (!strcasecmp(ptr, "O") || !strcasecmp(ptr, "OR") ||
		 !strcasecmp(ptr, "ORIGIN"))
		av->percent = PERCENT_ORIGIN;
	else {
		log_error("Specified %%%s is unknown.", ptr);
		return 0;
	}

	return 1;
}

/* Size stored in sectors */
static int _size_arg(struct cmd_context *cmd __attribute__((unused)),
		     struct arg_values *av, int factor, int percent)
{
	char *ptr;
	int i;
	static const char *suffixes = "kmgtpebs";
	char *val;
	double v;
	uint64_t v_tmp, adjustment;
	const char *radixchar = nl_langinfo(RADIXCHAR) ? : ".";

	av->percent = PERCENT_NONE;

	val = av->value;
	switch (*val) {
	case '+':
		av->sign = SIGN_PLUS;
		val++;
		break;
	case '-':
		av->sign = SIGN_MINUS;
		val++;
		break;
	default:
		av->sign = SIGN_NONE;
	}

	if (*val == '+' || *val == '-') {
		log_error("Multiple sign symbols detected.");
		return 0;
	}

	if (!isdigit(*val) && (*val != '.') && (*val != radixchar[0])) {
		log_error("Size requires number argument.");
		return 0;
	}

	errno = 0;
	v = strtod(val, &ptr);

	if (*ptr == '.' && radixchar[0] != '.') {
		/*
		 * Maybe user has non-C locale with different decimal point ?
		 * Lets be tolerant and retry with standard C locales
		 */
		if (setlocale(LC_ALL, "C")) {
			errno = 0;
			v = strtod(val, &ptr);
			setlocale(LC_ALL, "");
		}
	}

	if (ptr == val || errno) {
		log_error("Can't parse size argument at '%c'.%s%s", ptr[0], (errno) ? " " :"", (errno) ? strerror(errno) : "");
		return 0;
	}

	if (percent && *ptr == '%') {
		if (!_get_percent_arg(av, ++ptr))
			return_0;
		if ((uint64_t) v >= UINT32_MAX) {
			log_error("Percentage is too big (>=%d%%).", UINT32_MAX);
			return 0;
		}
	} else if (*ptr) {
		for (i = strlen(suffixes) - 1; i >= 0; i--)
			if (suffixes[i] == tolower((int) *ptr))
				break;

		if (i < 0) {
			log_error("Can't parse size argument.");
			return 0;
		} else if (i == 7) {
			/* v is already in sectors */
			;
		} else if (i == 6) {
			/* bytes */
			v_tmp = (uint64_t) v;
			adjustment = v_tmp % 512;
			if (adjustment) {
				v_tmp += (512 - adjustment);
				log_error("Size is not a multiple of 512. "
					  "Try using %"PRIu64" or %"PRIu64".",
					  v_tmp - 512, v_tmp);
				return 0;
			}
			v /= 512;
		} else {
			/* all other units: kmgtpe */
			while (i-- > 0)
				v *= 1024;
			v *= 2;
		}
	} else
		v *= factor;

	/* Compare (double) */
	if (v >= (double) (UINT64_MAX >> SECTOR_SHIFT)) {
		log_error("Size is too big (>=16EiB).");
		return 0;
	}

	av->i_value = (v < INT32_MAX) ? (int32_t) v : INT32_MAX;
	av->ui_value = (v < UINT32_MAX) ? (uint32_t) v : UINT32_MAX;
	av->i64_value = (v < INT64_MAX) ? (int64_t) v : INT64_MAX;
	av->ui64_value = (v < UINT64_MAX) ? (uint64_t) v : UINT64_MAX;

	return 1;
}

/* negative not accepted */
int size_kb_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!_size_arg(cmd, av, 2, 0))
		return 0;

	if (av->sign == SIGN_MINUS) {
		log_error("Size may not be negative.");
		return 0;
	}

	return 1;
}

int ssize_kb_arg(struct cmd_context *cmd, struct arg_values *av)
{
	return _size_arg(cmd, av, 2, 0);
}

int size_mb_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!_size_arg(cmd, av, 2048, 0))
		return 0;

	if ((av->sign == SIGN_MINUS) || (av->sign == SIGN_PLUS)) {
		log_error("Size may not be relative/signed.");
		return 0;
	}

	return 1;
}

int ssize_mb_arg(struct cmd_context *cmd, struct arg_values *av)
{
	return _size_arg(cmd, av, 2048, 0);
}

int psize_mb_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!_size_arg(cmd, av, 2048, 0))
		return 0;

	if (av->sign == SIGN_MINUS) {
		log_error("Size may not be negative.");
		return 0;
	}

	return 1;
}

int nsize_mb_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!_size_arg(cmd, av, 2048, 0))
		return 0;

	if (av->sign == SIGN_PLUS) {
		log_error("Size may not be positive.");
		return 0;
	}

	return 1;
}

int int_arg(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	char *ptr;

	if (!_get_int_arg(av, &ptr) || (*ptr) || (av->sign == SIGN_MINUS))
		return 0;

	return 1;
}

int uint32_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!int_arg(cmd, av) || (av->ui64_value > UINT32_MAX))
		return 0;

	return 1;
}

int int_arg_with_sign(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	char *ptr;

	if (!_get_int_arg(av, &ptr) || (*ptr))
		return 0;

	return 1;
}

int int_arg_with_plus(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	char *ptr;

	if (!_get_int_arg(av, &ptr) || (*ptr))
		return 0;

	if (av->sign == SIGN_MINUS) {
		log_error("Number may not be negative.");
		return 0;
	}

	return 1;
}

static int _extents_arg(struct cmd_context *cmd __attribute__((unused)),
			struct arg_values *av)
{
	char *ptr;

	if (!_get_int_arg(av, &ptr))
		return 0;

	if (!*ptr)
		return 1;

	if (*ptr++ != '%')
		return 0;

	if (!_get_percent_arg(av, ptr))
		return_0;

	if (av->ui64_value >= UINT32_MAX) {
		log_error("Percentage is too big (>=%d%%).", UINT32_MAX);
		return 0;
	}

	return 1;
}

int extents_arg(struct cmd_context *cmd __attribute__((unused)),
		struct arg_values *av)
{
	if (!_extents_arg(cmd, av))
		return 0;

	if ((av->sign == SIGN_MINUS) || (av->sign == SIGN_PLUS)) {
		log_error("Extents may not be relative/signed.");
		return 0;
	}

	return 1;
}

int sextents_arg(struct cmd_context *cmd __attribute__((unused)),
		 struct arg_values *av)
{
	return _extents_arg(cmd, av);
}

int pextents_arg(struct cmd_context *cmd __attribute__((unused)),
		 struct arg_values *av)
{
	if (!_extents_arg(cmd, av))
		return 0;

	if (av->sign == SIGN_MINUS) {
		log_error("Extents may not be negative.");
		return 0;
	}

	return 1;
}

int nextents_arg(struct cmd_context *cmd __attribute__((unused)),
		 struct arg_values *av)
{
	if (!_extents_arg(cmd, av))
		return 0;

	if (av->sign == SIGN_PLUS) {
		log_error("Extents may not be positive.");
		return 0;
	}

	return 1;
}

int string_arg(struct cmd_context *cmd __attribute__((unused)),
	       struct arg_values *av __attribute__((unused)))
{
	return 1;
}

int tag_arg(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	char *pos = av->value;

	if (*pos == '@')
		pos++;

	if (!validate_tag(pos))
		return 0;

	av->value = pos;

	return 1;
}

int permission_arg(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	av->sign = SIGN_NONE;

	if ((!strcmp(av->value, "rw")) || (!strcmp(av->value, "wr")))
		av->ui_value = LVM_READ | LVM_WRITE;

	else if (!strcmp(av->value, "r"))
		av->ui_value = LVM_READ;

	else
		return 0;

	return 1;
}

int alloc_arg(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	alloc_policy_t alloc;

	av->sign = SIGN_NONE;

	alloc = get_alloc_from_string(av->value);
	if (alloc == ALLOC_INVALID)
		return 0;

	av->ui_value = (uint32_t) alloc;

	return 1;
}

int locktype_arg(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	lock_type_t lock_type;

	av->sign = SIGN_NONE;

	lock_type = get_lock_type_from_string(av->value);
	if (lock_type == LOCK_TYPE_INVALID)
		return 0;

	return 1;
}

int segtype_arg(struct cmd_context *cmd, struct arg_values *av)
{
	struct segment_type *segtype;
	const char *str = (!strcmp(av->value, SEG_TYPE_NAME_LINEAR)) ? SEG_TYPE_NAME_STRIPED : av->value;

	if (!(segtype = get_segtype_from_string(cmd, str)))
		return_0;

	return (!segtype_is_unknown(segtype)) ? 1 : 0;
}

/*
 * Positive integer, zero or "auto".
 */
int readahead_arg(struct cmd_context *cmd __attribute__((unused)), struct arg_values *av)
{
	if (!strcasecmp(av->value, "auto")) {
		av->ui_value = DM_READ_AHEAD_AUTO;
		return 1;
	}

	if (!strcasecmp(av->value, "none")) {
		av->ui_value = DM_READ_AHEAD_NONE;
		return 1;
	}

	if (!_size_arg(cmd, av, 1, 0))
		return 0;

	if (av->sign == SIGN_MINUS)
		return 0;

	return 1;
}

int regionsize_mb_arg(struct cmd_context *cmd, struct arg_values *av)
{
	int pagesize = lvm_getpagesize();
	uint32_t num;

	if (!_size_arg(cmd, av, 2048, 0))
		return 0;

	if (av->sign == SIGN_MINUS) {
		log_error("Region size may not be negative.");
		return 0;
	}

	if (av->ui64_value > UINT32_MAX) {
		log_error("Region size is too big (max %u).", UINT32_MAX);
		return 0;
	}

	num = av->ui_value;

	if (!num) {
		log_error("Region size may not be zero.");
		return 0;
	}

	if (num % (pagesize >> SECTOR_SHIFT)) {
		log_error("Region size must be a multiple of machine memory page size (%d bytes).",
			  pagesize);
		return 0;
	}

	if (!is_power_of_2(num)) {
		log_error("Region size must be a power of 2.");
		return 0;
	}

	return 1;
}

/*
 * Non-zero, positive integer, "all", or "unmanaged"
 */
int vgmetadatacopies_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!strcasecmp(av->value, "all")) {
		av->ui_value = VGMETADATACOPIES_ALL;
		return 1;
	}

	if (!strcasecmp(av->value, "unmanaged")) {
		av->ui_value = VGMETADATACOPIES_UNMANAGED;
		return 1;
	}

	return int_arg(cmd, av);
}

int pvmetadatacopies_arg(struct cmd_context *cmd, struct arg_values *av)
{
	int num;

	if (!int_arg(cmd, av))
		return 0;

	num = av->i_value;

	if ((num != 0) && (num != 1) && (num != 2))
		return 0;

	return 1;
}

int metadatacopies_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!strncmp(cmd->name, "pv", 2))
		return pvmetadatacopies_arg(cmd, av);
	if (!strncmp(cmd->name, "vg", 2))
		return vgmetadatacopies_arg(cmd, av);
	return 0;
}

int polloperation_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!strcmp(av->value, "pvmove") ||
	    !strcmp(av->value, "convert") ||
	    !strcmp(av->value, "merge") ||
	    !strcmp(av->value, "merge_thin"))
		return 1;
	return 0;
}

int writemostly_arg(struct cmd_context *cmd, struct arg_values *av)
{
	/* Could we verify that a PV arg looks like /dev/foo ? */
	return 1;
}

int syncaction_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!strcmp(av->value, "check") ||
	    !strcmp(av->value, "repair"))
		return 1;
	return 0;
}

int reportformat_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!strcmp(av->value, "basic") ||
	    !strcmp(av->value, "json") ||
	    !strcmp(av->value, "json_std"))
		return 1;
	return 0;
}

int configreport_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!strcmp(av->value, "log") ||
	    !strcmp(av->value, "vg") ||
	    !strcmp(av->value, "lv") ||
	    !strcmp(av->value, "pv") ||
	    !strcmp(av->value, "pvseg") ||
	    !strcmp(av->value, "seg"))
		return 1;
	return 0;
}

int configtype_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!strcmp(av->value, "current") ||
	    !strcmp(av->value, "default") ||
	    !strcmp(av->value, "diff") ||
	    !strcmp(av->value, "full") ||
	    !strcmp(av->value, "list") ||
	    !strcmp(av->value, "missing") ||
	    !strcmp(av->value, "new") ||
	    !strcmp(av->value, "profilable") ||
	    !strcmp(av->value, "profilable-command") ||
	    !strcmp(av->value, "profilable-metadata"))
		return 1;
	return 0;
}

int repairtype_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!strcmp(av->value, "pv_header") ||
	    !strcmp(av->value, "metadata") ||
	    !strcmp(av->value, "label_header"))
		return 1;
	return 0;
}

int dumptype_arg(struct cmd_context *cmd, struct arg_values *av)
{
	if (!strcmp(av->value, "headers") ||
	    !strcmp(av->value, "metadata") ||
	    !strcmp(av->value, "metadata_all") ||
	    !strcmp(av->value, "metadata_search") ||
	    !strcmp(av->value, "metadata_area") ||
	    !strcmp(av->value, "backup_to_raw"))
		return 1;
	return 0;
}

/*
 * FIXME: there's been a confusing mixup among:
 * resizeable, resizable, allocatable, allocation.
 *
 * resizeable and allocatable are the preferred,
 * standard option names.
 *
 * The dispreferred "resizable" is always translated
 * to the preferred resizeable.
 *
 * But, the dispreferred "allocation" name seems
 * to translate to either or both resizeable
 * and allocatable, it's not clear which.
 */

static int _opt_standard_to_synonym(const char *cmd_name, int opt)
{
	switch (opt) {
	case mirrorlog_ARG:
		return corelog_ARG;
	case resizeable_ARG:
		return resizable_ARG;
	case allocatable_ARG:
		return allocation_ARG;
	case activate_ARG:
		return available_ARG;
	case rebuild_ARG:
		return raidrebuild_ARG;
	case syncaction_ARG:
		return raidsyncaction_ARG;
	case writemostly_ARG:
		return raidwritemostly_ARG;
	case minrecoveryrate_ARG:
		return raidminrecoveryrate_ARG;
	case maxrecoveryrate_ARG:
		return raidmaxrecoveryrate_ARG;
	case writebehind_ARG:
		return raidwritebehind_ARG;
	case virtualsize_ARG:
		return virtualoriginsize_ARG;
	case splitcache_ARG:
		return split_ARG;
	case pvmetadatacopies_ARG:
		if (!strncmp(cmd_name, "pv", 2))
			return metadatacopies_ARG;
		return 0;
	case vgmetadatacopies_ARG:
		if (!strncmp(cmd_name, "vg", 2))
			return metadatacopies_ARG;
		return 0;
	}
	return 0;
}

static int _opt_synonym_to_standard(const char *cmd_name, int opt)
{
	switch (opt) {
	case corelog_ARG:
		return mirrorlog_ARG;
	case resizable_ARG:
		return resizeable_ARG;
	case allocation_ARG:
		return allocatable_ARG;
	case available_ARG:
		return activate_ARG;
	case raidrebuild_ARG:
		return rebuild_ARG;
	case raidsyncaction_ARG:
		return syncaction_ARG;
	case raidwritemostly_ARG:
		return writemostly_ARG;
	case raidminrecoveryrate_ARG:
		return minrecoveryrate_ARG;
	case raidmaxrecoveryrate_ARG:
		return maxrecoveryrate_ARG;
	case raidwritebehind_ARG:
		return writebehind_ARG;
	case virtualoriginsize_ARG:
		return virtualsize_ARG;
	case split_ARG:
		return splitcache_ARG;
	case metadatacopies_ARG:
		if (!strncmp(cmd_name, "pv", 2))
			return pvmetadatacopies_ARG;
		if (!strncmp(cmd_name, "vg", 2))
			return vgmetadatacopies_ARG;
		return 0;
	}
	return 0;
}

static void _add_getopt_arg(int arg_enum, char **optstrp, struct option **longoptsp);

/*
 * The valid args for a command name in general is a union of
 * required_opt_args and optional_opt_args for all commands[]
 * with the given name.
 */

static void _set_valid_args_for_command_name(int ci)
{
	int all_args[ARG_COUNT] = { 0 };
	int num_args = 0;
	int opt_enum; /* foo_ARG from args.h */
	int opt_syn;
	int i, ro, oo, io;
	int first = 0, last = COMMAND_COUNT - 1, middle;
	const char *name = command_names[ci].name;

	/* all_args is indexed by the foo_ARG enum vals */
	/* Binary search in sorted array of long options (with duplicates) */
	while (first <= last) {
		middle = first + (last - first) / 2;
		if ((i = strcmp(commands_idx[middle]->name, name)) < 0)
			first = middle + 1;
		else if (i > 0)
			last = middle - 1;
		else {
			/* Matching command found.
			 * As sorted array contains duplicates, found 1st. and last such cmd. */
			i = middle;
			while (middle > first && !strcmp(commands_idx[middle - 1]->name, name))
				middle--;
			while (i < last && !strcmp(commands_idx[i + 1]->name, name))
				i++;
			last = i;
			break;
		}
	}

	while (middle <= last) {
		i = commands_idx[middle++]->command_index;
		for (ro = 0; ro < (commands[i].ro_count + commands[i].any_ro_count); ro++) {
			opt_enum = commands[i].required_opt_args[ro].opt;
			all_args[opt_enum] = 1;
		}
		for (oo = 0; oo < commands[i].oo_count; oo++) {
			opt_enum = commands[i].optional_opt_args[oo].opt;
			all_args[opt_enum] = 1;
		}
		for (io = 0; io < commands[i].io_count; io++) {
			opt_enum = commands[i].ignore_opt_args[io].opt;
			all_args[opt_enum] = 1;
		}
	}

	for (i = 0; i < ARG_COUNT; i++) {
		if (all_args[i]) {
			opt_enum = _cmdline.opt_names[i].opt_enum;

			command_names[ci].valid_args[num_args] = opt_enum;
			num_args++;

			/* Automatically recognize --extents in addition to --size. */
			if (opt_enum == size_ARG) {
				command_names[ci].valid_args[num_args] = extents_ARG;
				num_args++;
			}

			/* Recognize synonyms */
			if ((opt_syn = _opt_standard_to_synonym(command_names[ci].name, opt_enum))) {
				command_names[ci].valid_args[num_args] = opt_syn;
				num_args++;
			}

			/*
			 * "--allocation" is a weird option that seems to be
			 * a synonym for either allocatable or resizeable,
			 * each which already have their own other synonyms,
			 * so just add allocation whenever either is seen.
			 */
			if ((opt_enum == allocatable_ARG) || (opt_enum == resizeable_ARG)) {
				command_names[ci].valid_args[num_args] = allocation_ARG;
				num_args++;
			}
		}
	}

	command_names[ci].num_args = num_args;
}

static const struct command_function *_find_command_id_function(int command_enum)
{
	int i;

	if (!command_enum)
		return NULL;

	for (i = 0; i < CMD_COUNT; i++) {
		if (_command_functions[i].command_enum == command_enum)
			return &_command_functions[i];
	}
	return NULL;
}

static void _unregister_commands(void)
{
	_cmdline.commands = NULL;
	_cmdline.num_commands = 0;
	_cmdline.command_names = NULL;
	_cmdline.num_command_names = 0;
	memset(&commands, 0, sizeof(commands));
}

static int _command_name_compare(const void *on1, const void *on2)
{
	const struct command * const *optname1 = on1;
	const struct command * const *optname2 = on2;

	return strcmp((*optname1)->name, (*optname2)->name);
}

int lvm_register_commands(struct cmd_context *cmd, const char *run_name)
{
	int i;

	/* already initialized */
	if (_cmdline.commands)
		return 1;

	memset(&commands, 0, sizeof(commands));

	/*
	 * populate commands[] array with command definitions
	 * by parsing command-lines.in/command-lines-input.h
	 */
	if (!define_commands(cmd, run_name)) {
		log_error(INTERNAL_ERROR "Failed to parse command definitions.");
		return 0;
	}

	_cmdline.commands = commands;
	_cmdline.num_commands = COMMAND_COUNT;

	for (i = 0; i < COMMAND_COUNT; i++) {
		commands_idx[i] = &commands[i];
		commands[i].command_index = i;
		commands[i].command_enum = command_id_to_enum(commands[i].command_id);

		if (!commands[i].command_enum) {
			log_error(INTERNAL_ERROR "Failed to find command id %s.", commands[i].command_id);
			_cmdline.commands = NULL;
			_cmdline.num_commands = 0;
			return 0;
		}

		/* new style */
		commands[i].functions = _find_command_id_function(commands[i].command_enum);

		/* old style */
		if (!commands[i].functions) {
			struct command_name *cname = find_command_name(commands[i].name);
			if (cname)
				commands[i].fn = cname->fn;
		}
	}

	/* Sort all commands by its name for quick binary search */
	qsort(commands_idx, COMMAND_COUNT, sizeof(long), _command_name_compare);

	for (i = 0; command_names[i].name; i++)
		_set_valid_args_for_command_name(i);

	_cmdline.num_command_names = i; /* Also counted how many command entries we have */
	_cmdline.command_names = command_names;

	return 1;
}

struct lv_prop *get_lv_prop(int lvp_enum)
{
	if (!lvp_enum)
		return NULL;
	return &lv_props[lvp_enum];
}

struct lv_type *get_lv_type(int lvt_enum)
{
	if (!lvt_enum)
		return NULL;
	return &lv_types[lvt_enum];
}

struct command *get_command(int cmd_enum)
{
	int i;

	for (i = 0; i < COMMAND_COUNT; i++) {
		if (commands[i].command_enum == cmd_enum)
			return &commands[i];
	}

	return NULL;
}

/*
 * Also see merge_synonym().  The command definitions
 * are written using just one variation of the option
 * name (opt below).  This function checks if the user
 * entered a synonym (arg_is_set).
 */

static int _opt_synonym_is_set(struct cmd_context *cmd, int opt_std)
{
	int opt_syn = _opt_standard_to_synonym(cmd->name, opt_std);

	return opt_syn && arg_is_set(cmd, opt_syn);
}

static int _command_optional_opt_matches(struct cmd_context *cmd, int ci, int oo)
{
	int opt_enum = commands[ci].optional_opt_args[oo].opt;

	if (val_bit_is_set(commands[ci].optional_opt_args[oo].def.val_bits, conststr_VAL)) {
		if (!strcmp(commands[ci].optional_opt_args[oo].def.str, arg_str_value(cmd, opt_enum, "")))
			return 1;
		return 0;
	}

	if (val_bit_is_set(commands[ci].optional_opt_args[oo].def.val_bits, constnum_VAL)) {
		if (commands[ci].optional_opt_args[oo].def.num == arg_int_value(cmd, opt_enum, 0))
			return 1;
		return 0;
	}

	return 1;
}

static int _command_ignore_opt_matches(struct cmd_context *cmd, int ci, int io)
{
	int opt_enum = commands[ci].ignore_opt_args[io].opt;

	if (val_bit_is_set(commands[ci].ignore_opt_args[io].def.val_bits, conststr_VAL)) {
		if (!strcmp(commands[ci].ignore_opt_args[io].def.str, arg_str_value(cmd, opt_enum, "")))
			return 1;
		return 0;
	}

	if (val_bit_is_set(commands[ci].ignore_opt_args[io].def.val_bits, constnum_VAL)) {
		if (commands[ci].ignore_opt_args[io].def.num == arg_int_value(cmd, opt_enum, 0))
			return 1;
		return 0;
	}

	return 1;
}

static int _command_required_opt_matches(struct cmd_context *cmd, int ci, int ro)
{
	int opt_enum = commands[ci].required_opt_args[ro].opt;

	if (arg_is_set(cmd, opt_enum) || _opt_synonym_is_set(cmd, opt_enum))
		goto check_val;

	/*
	 * For some commands, --size and --extents are interchangable,
	 * but command[] definitions use only --size.
	 */
	if ((opt_enum == size_ARG) && arg_is_set(cmd, extents_ARG) &&
	    command_has_alternate_extents(commands[ci].name))
		goto check_val;

	return 0;

	/*
	 * If the definition requires a literal string or number, check
	 * that the arg value matches.
	 */

check_val:
	if (val_bit_is_set(commands[ci].required_opt_args[ro].def.val_bits, conststr_VAL)) {
		if (!strcmp(commands[ci].required_opt_args[ro].def.str, arg_str_value(cmd, opt_enum, "")))
			return 1;

		/* Special case: "raid0" (any raid<N>), matches command def "raid" */
		if (!strcmp(commands[ci].required_opt_args[ro].def.str, "raid") &&
		    !strncmp(arg_str_value(cmd, opt_enum, ""), "raid", 4))
			return 1;

		return 0;
	}

	if (val_bit_is_set(commands[ci].required_opt_args[ro].def.val_bits, constnum_VAL)) {
		if (commands[ci].required_opt_args[ro].def.num == arg_int_value(cmd, opt_enum, 0))
			return 1;
		return 0;
	}

	return 1;
}

static int _command_required_pos_matches(struct cmd_context *cmd, int ci, int rp, char **argv)
{
	const char *name;

	/*
	 * rp is the index in required_pos_args[] of the required positional arg.
	 * The pos values begin with 1, so the first positional arg has
	 * pos 1, rp 0.
	 */
	if (argv[rp]) {
		/* FIXME: can we match object type better than just checking something exists? */
		/* Some cases could be validated by looking at defs.types and at the value. */
		return 1;
	}

	/*
	 * If Select is specified as a pos arg, then that pos arg can be
	 * empty if --select is used.
	 */
	if ((val_bit_is_set(commands[ci].required_pos_args[rp].def.val_bits, select_VAL)) &&
	    arg_is_set(cmd, select_ARG))
		return 1;

	/*
	 * For an lvcreate command with VG as the first required positional arg,
	 * the VG position is allowed to be empty if --name VG/LV is used, or if the
	 * LVM_VG_NAME env var is set.
	 *
	 * --thinpool|--cachepool|--vdopool VG/LV can also function like --name
	 * to provide the VG name in place of the positional arg.
	 */
	if (!strcmp(cmd->name, "lvcreate") &&
	    (rp == 0) &&
	    val_bit_is_set(commands[ci].required_pos_args[rp].def.val_bits, vg_VAL) &&
	    (arg_is_set(cmd, name_ARG) ||
	     arg_is_set(cmd, thinpool_ARG) ||
	     arg_is_set(cmd, cachepool_ARG) ||
	     arg_is_set(cmd, vdopool_ARG) ||
	     getenv("LVM_VG_NAME"))) {

		if (getenv("LVM_VG_NAME"))
			return 1;

		if ((name = arg_str_value(cmd, name_ARG, NULL))) {
			if (strstr(name, "/"))
				return 1;
		}

		if ((name = arg_str_value(cmd, thinpool_ARG, NULL))) {
			if (strstr(name, "/"))
				return 1;
		}

		if ((name = arg_str_value(cmd, cachepool_ARG, NULL))) {
			if (strstr(name, "/"))
				return 1;
		}

		if ((name = arg_str_value(cmd, vdopool_ARG, NULL)) && strstr(name, "/"))
			return 1;
	}

	return 0;
}

/*
 * Return 1 if we should skip this command from consideration.
 * This would happen if the command does not include a --type
 * option that does not match type_arg.
 */

static int _command_skip_for_type_arg(struct cmd_context *cmd, int ci, const char *type_arg)
{
	int ro, oo, opt_enum;

	for (ro = 0; ro < (commands[ci].ro_count + commands[ci].any_ro_count); ro++) {
		opt_enum = commands[ci].required_opt_args[ro].opt;

		if (opt_enum != type_ARG)
			continue;

		/* SegType keyword in command def matches any type_arg */
		if (val_bit_is_set(commands[ci].required_opt_args[ro].def.val_bits, segtype_VAL))
			return 0;

		if (!commands[ci].required_opt_args[ro].def.str)
			return 0;

		if (!strcmp(commands[ci].required_opt_args[ro].def.str, type_arg))
			return 0;

		if (!strncmp(commands[ci].required_opt_args[ro].def.str, "raid", 4) &&
		    !strncmp(type_arg, "raid", 4))
			return 0;

		return 1;
	}

	for (oo = 0; oo < commands[ci].oo_count; oo++) {
		opt_enum = commands[ci].optional_opt_args[oo].opt;

		if (opt_enum != type_ARG)
			continue;

		/* SegType keyword in command def matches any type_arg */
		if (val_bit_is_set(commands[ci].optional_opt_args[oo].def.val_bits, segtype_VAL))
			return 0;

		if (!commands[ci].optional_opt_args[oo].def.str)
			return 0;

		if (!strcmp(commands[ci].optional_opt_args[oo].def.str, type_arg))
			return 0;

		if (!strncmp(commands[ci].optional_opt_args[oo].def.str, "raid", 4) &&
		    !strncmp(type_arg, "raid", 4))
			return 0;

		return 1;
	}

	return 1;
}

/*
 * Match what the user typed with a one specific command definition/prototype
 * from commands[].  If nothing matches, it's not a valid command.  The match
 * is based on command name, required opt args and required pos args.
 *
 * Find an entry in the commands array that matches based the arg values.
 *
 * If the cmd has opt or pos args set that are not accepted by command,
 * we can: silently ignore them, warn they are not being used, or fail.
 * Default should probably be to warn and continue.
 *
 * For each command[i], check how many required opt/pos args cmd matches.
 * Save the command[i] that matches the most.
 *
 * commands[i].cmd_flags & CMD_FLAG_ANY_REQUIRED_OPT means
 * any one item from commands[i].required_opt_args needs to be
 * set to match.
 *
 * required_pos_args[0].types & select_VAL means
 * argv[] in that pos can be NULL if arg_is_set(select_ARG)
 */

/* The max number of unused options we keep track of to warn about */
#define MAX_UNUSED_COUNT 8

#define MAX_OPTS_MSG 64

static struct command *_find_command(struct cmd_context *cmd, const char *path, int *argc, char **argv)
{
	const char *name;
	const char *type_arg = NULL;
	char opts_msg[MAX_OPTS_MSG];
	char check_opts_msg[MAX_OPTS_MSG];
	int match_required, match_ro, match_rp, match_any_ro, match_type, match_unused, mismatch_required;
	int best_i = 0, best_required = 0, best_type = 0, best_unused = 0;
	int close_i = 0, close_ro = 0, close_type = 0;
	int only_i = 0;
	int temp_unused_options[MAX_UNUSED_COUNT];
	int temp_unused_count;
	int best_unused_options[MAX_UNUSED_COUNT] = { 0 };
	int best_unused_count = 0;
	int opts_match_count, opts_unmatch_count;
	int ro, rp;
	int i, j;
	int opt_enum, opt_i;
	int accepted, count;
	int variants = 0;

	name = last_path_component(path);

	/* factor_common_options() is only for usage, so cname->variants is not set. */
	for (i = 0; i < COMMAND_COUNT; i++) {
		if (strcmp(name, commands[i].name))
			continue;
		variants++;
	}

	if (arg_is_set(cmd, type_ARG))
		type_arg = arg_str_value(cmd, type_ARG, "");

	for (i = 0; i < COMMAND_COUNT; i++) {
		if (strcmp(name, commands[i].name))
			continue;

		if (variants == 1)
			only_i = i;

		/* For help and version just return the first entry with matching name. */
		if (arg_is_set(cmd, help_ARG) || arg_is_set(cmd, help2_ARG) || arg_is_set(cmd, longhelp_ARG) || arg_is_set(cmd, version_ARG))
			return &commands[i];

		/*
		 * The 'lvconvert LV' cmd def matches any lvconvert cmd which throws off
		 * nearest-command partial-match suggestions.  Make it a special case so
		 * that it won't be used as a close match.  If the command has any option
		 * set (other than -v), don't attempt to match it to 'lvconvert LV'.
		 */
		if (commands[i].command_enum == lvconvert_plain_CMD) {
			if (cmd->opt_count - cmd->opt_arg_values[verbose_ARG].count)
				continue;
		}

		/*
		 * If the cmd def has an implied type, specified in AUTOTYPE,
		 * then if the user command has --type, it must match.
		 */
		if (type_arg && commands[i].autotype && strcmp(type_arg, commands[i].autotype))
			continue;
		if (type_arg && commands[i].autotype2 && strcmp(type_arg, commands[i].autotype2))
			continue;

		/*
		 * '--type foo' is special.  If the user has set --type foo, then
		 * we will only look at command defs that include the same --type foo
		 * (as required or optional).  We'll never match some command based
		 * on *other* (non-type) options, and then at the end complain that
		 * the user's --type is not accepted.
		 */
		if (type_arg && _command_skip_for_type_arg(cmd, i, type_arg))
			continue;

		match_required = 0;	/* required parameters that match */
		match_ro = 0;		/* required opt_args that match */
		match_rp = 0;		/* required pos_args that match */
		match_any_ro = 0;
		match_type = 0;		/* type arg matches */
		match_unused = 0;	/* options set that are not accepted by command */
		mismatch_required = 0;	/* required parameters that do not match */
		temp_unused_count = 0;
		memset(&temp_unused_options, 0, sizeof(temp_unused_options));

		/* if the command name alone is enough, then that's a match */

		if (!commands[i].ro_count && !commands[i].rp_count)
			match_required = 1;

		/* match required_opt_args */

		for (ro = 0; ro < commands[i].ro_count; ro++) {
			if (_command_required_opt_matches(cmd, i, ro)) {
				/* log_warn("match %d ro opt %d", i, commands[i].required_opt_args[ro].opt); */
				match_required++;
				match_ro++;

				if (commands[i].required_opt_args[ro].opt == type_ARG)
					match_type = 1;
			} else {
				/* cmd is missing a required opt arg */
				/* log_warn("mismatch %d ro opt %d", i, commands[i].required_opt_args[ro].opt); */
				mismatch_required++;
			}
		}

		for (ro = commands[i].ro_count; ro < commands[i].ro_count + commands[i].any_ro_count; ro++) {
			if (_command_required_opt_matches(cmd, i, ro)) {
				/* log_warn("match %d any ro opt %d", i, commands[i].required_opt_args[ro].opt); */
				match_any_ro++;
			}
		}

		if ((commands[i].cmd_flags & CMD_FLAG_ANY_REQUIRED_OPT) && !match_any_ro) {
			/* not even one of the any ro is used */
			/* log_warn("match %d not one from any", i); */
			mismatch_required = 1;
		}

		/* match required_pos_args */

		for (rp = 0; rp < commands[i].rp_count; rp++) {
			if (_command_required_pos_matches(cmd, i, rp, argv)) {
				/* log_warn("match %d rp %d", i, commands[i].required_pos_args[rp].pos); */
				match_required++;
				match_rp++;
			} else {
				/* cmd is missing a required pos arg */
				/* log_warn("mismatch %d rp %d", i, commands[i].required_pos_args[rp].pos); */
				mismatch_required++;
			}
		}

		/* if cmd is missing any required opt/pos args, it can't be this command. */

		if (mismatch_required) {
			/* save "closest" command that doesn't match */
			if ((match_type && !close_type) ||
			    ((match_type == close_type) && (match_ro > close_ro))) {
				close_i = i;
				close_ro = match_ro;
				close_type = match_type;
			}
			continue;
		}

		if (!match_required)
			continue;

		/* Count the command name as a match if all the required opt/pos args match. */

		if ((commands[i].ro_count || commands[i].rp_count) && (match_ro || match_rp))
			match_required++;

		/* log_warn("command %d has match_required %d match_ro %d match_rp %d",
			 i, match_required, match_ro, match_rp); */

		/* Count how many options cmd has set that are not accepted by commands[i]. */
		/* FIXME: also count unused positional args? */

		for (opt_i = 0; opt_i < ARG_COUNT; opt_i++) {
			if (!arg_is_set(cmd, opt_i))
				continue;

			if (!(opt_enum = _opt_synonym_to_standard(cmd->name, opt_i)))
				opt_enum = opt_i;

			/* extents are not used in command definitions */
			if (opt_enum == extents_ARG)
				continue;

			accepted = 0;

			/* NB in some cases required_opt_args are optional */
			for (j = 0; j < commands[i].ro_count + commands[i].any_ro_count; j++) {
				if (commands[i].required_opt_args[j].opt == opt_enum) {
					accepted = 1;
					break;
				}
			}

			if (accepted)
				continue;

			for (j = 0; j < commands[i].oo_count; j++) {
				if ((commands[i].optional_opt_args[j].opt == opt_enum) &&
				    _command_optional_opt_matches(cmd, i, j)) {
					accepted = 1;
					break;
				}
			}

			for (j = 0; j < commands[i].io_count; j++) {
				if ((commands[i].ignore_opt_args[j].opt == opt_enum) &&
				    _command_ignore_opt_matches(cmd, i, j)) {
					accepted = 1;
					break;
				}
			}

			if (!accepted) {
				match_unused++;
				if (temp_unused_count < MAX_UNUSED_COUNT)
					temp_unused_options[temp_unused_count++] = opt_enum;
			}
		}

		/*
		 * Choose the best match, which in general is the command with
		 * the most matching required_{opt,pos}, but it could be a
		 * command with fewer required_{opt,pos} matches in the case
		 * where cmddef1 has more required matches, but a match_unused
		 * and cmddef2 has fewer required matches, but zero match_unused.
		 *
		 * A match is better if:
		 * . more required opt/pos args match
		 * . type arg matches when other doesn't
		 * . less unused options
		 */

		if (!best_required ||
		    ((match_required > best_required) && !match_unused) ||
		    (match_unused < best_unused) ||
		    (match_type > best_type) ||
		    ((match_required == best_required) && (match_type == best_type) && (match_unused < best_unused))) {
			/* log_warn("best %d has match_required %d match_ro %d match_rp %d",
				 i, match_required, match_ro, match_rp); */
			best_i = i;
			best_required = match_required;
			best_type = match_type;
			best_unused = match_unused;
			best_unused_count = temp_unused_count;
			memcpy(&best_unused_options, &temp_unused_options, sizeof(best_unused_options));
		}
	}

	if (!best_required) {
		/* cmd did not have all the required opt/pos args of any command */
		log_error("No command with matching syntax recognised.  Run '%s --help' for more information.", name);

		if (only_i) {
			log_warn("Correct command syntax is:");
			print_usage(&_cmdline.commands[only_i], 0, 0);
		} else if (close_ro) {
			log_warn("Nearest similar command has syntax:");
			print_usage(&_cmdline.commands[close_i], 0, 0);
		}
		return NULL;
	}

	/*
	 * If the user passed an option that is not accepted by the matched
	 * command, then fail.
	 *
	 * FIXME: it might be nice to have a config setting that would turn
	 * these into warnings, and just ignore the unused options.
	 */

	if (best_unused_count) {
		for (i = 0; i < best_unused_count; i++) {
			const char *opt_val = NULL;
			opt_enum = best_unused_options[i];
			opt_val = arg_value(cmd, opt_enum);

			log_error("Command does not accept option: %s%s%s.",
				  arg_long_option_name(opt_enum),
				  opt_val ? " " : "", opt_val ?: "");
		}
		return NULL;
	}

	/*
	 * If the user provided a positional arg that is not accepted by
	 * the mached command, then fail.
	 *
	 * If the last required_pos_arg or the last optional_pos_arg may repeat,
	 * then there won't be unused positional args.
	 *
	 * FIXME: same question as above, should there be a config setting
	 * to just warn/ignore about unused positional args?
	 */

	count = commands[best_i].rp_count;
	if (count && (commands[best_i].required_pos_args[count - 1].def.flags & ARG_DEF_FLAG_MAY_REPEAT))
		goto out;

	count = commands[best_i].op_count;
	if (count && (commands[best_i].optional_pos_args[count - 1].def.flags & ARG_DEF_FLAG_MAY_REPEAT))
		goto out;

	for (count = 0; ; count++) {
		if (!argv[count])
			break;

		if (count >= (commands[best_i].rp_count + commands[best_i].op_count)) {
			log_error("Command does not accept argument: %s.", argv[count]);

			/* FIXME: to warn/ignore, clear so it can't be used when processing. */
			/*
			argv[count] = NULL;
			(*argc)--;
			*/
			return NULL;
		}
	}

out:
	/*
	 * Check any rules related to option combinations.
	 * Other rules are checked after VG is read.
	 */

	for (i = 0; i < commands[best_i].rule_count; i++) {
		struct cmd_rule *rule;
		rule = &commands[best_i].rules[i];

		/*
		 * The rule wants to validate options (check_opts). That can be
		 * done here if the only qualification for the validation is
		 * other options (and not specific LV type or LV property which
		 * are not known here.)
		 */

		if (rule->check_opts_count && !rule->lvt_bits && !rule->lvp_bits) {
			/*
			 * When no opt is specified for applying the rule, then
			 * the rule is always applied, otherwise the rule is
			 * applied when the specific option is set.
			 */
			if (rule->opts_count &&
			    !opt_in_list_is_set(cmd, rule->opts, rule->opts_count, NULL, NULL))
				continue;

			opt_in_list_is_set(cmd, rule->check_opts, rule->check_opts_count,
					   &opts_match_count, &opts_unmatch_count);

			if (opts_match_count && (rule->rule == RULE_INVALID)) {
				memset(opts_msg, 0, sizeof(opts_msg));
				memset(check_opts_msg, 0, sizeof(check_opts_msg));

				if (rule->opts_count)
					opt_array_to_str(cmd, rule->opts, rule->opts_count, opts_msg, sizeof(opts_msg));
				opt_array_to_str(cmd, rule->check_opts, rule->check_opts_count, check_opts_msg, sizeof(check_opts_msg));

				if (rule->opts_count)
					log_error("Command does not accept option combination: %s with %s", opts_msg, check_opts_msg);
				else
					log_error("Command does not accept options: %s", check_opts_msg);
				return NULL;
			}

			if (opts_unmatch_count && (rule->rule == RULE_REQUIRE)) {
				memset(check_opts_msg, 0, sizeof(check_opts_msg));
				opt_array_to_str(cmd, rule->check_opts, rule->check_opts_count, check_opts_msg, sizeof(check_opts_msg));
				log_error("Command requires options: %s", check_opts_msg);
				return NULL;
			}
		}
	}

	log_debug("Recognised command %s (id %d / enum %d).",
		  commands[best_i].command_id, best_i, commands[best_i].command_enum);

	log_command(cmd->cmd_line, commands[best_i].name, commands[best_i].command_id);

	return &commands[best_i];
}

static void _short_usage(const char *name)
{
	log_error("Run `%s --help' for more information.", name);
}

static int _usage(const char *name, int longhelp, int skip_notes)
{
	struct command_name *cname = find_command_name(name);
	struct command *cmd = NULL;
	int show_full = longhelp;
	int i;

	if (!cname) {
		log_print("%s: no such command.", name);
		return 0;
	}

	configure_command_option_values(name);

	/*
	 * Looks at all variants of each command name and figures out
	 * which options are common to all variants (for compact output)
	 */
	factor_common_options();

	log_print("%s - %s\n", name, cname->desc);

	/* Reduce the default output when there are several variants. */

	if (cname->variants < 3)
		show_full = 1;

	for (i = 0; i < COMMAND_COUNT; i++) {
		if (strcmp(_cmdline.commands[i].name, name))
			continue;

		if (_cmdline.commands[i].cmd_flags & CMD_FLAG_PREVIOUS_SYNTAX)
			continue;

		if ((_cmdline.commands[i].cmd_flags & CMD_FLAG_SECONDARY_SYNTAX) && !show_full)
			continue;

		log_very_verbose("Command definition index %d enum %d id %s",
			         _cmdline.commands[i].command_index,
			         _cmdline.commands[i].command_enum,
			         _cmdline.commands[i].command_id);

		print_usage(&_cmdline.commands[i], 1, 1);
		cmd = &_cmdline.commands[i];
	}

	/* Common options are printed once for all variants of a command name. */
	if (!cmd) {
		log_error(INTERNAL_ERROR "Command %s not found.", name);
		return 0;
	}

	print_usage_common_cmd(cname, cmd);
	print_usage_common_lvm(cname, cmd);

	if (skip_notes)
		return 1;

	if (longhelp)
		print_usage_notes(cname);
	else
		log_print("Use --longhelp to show all options and advanced commands.");

	return 1;
}

static void _usage_all(void)
{
	int i;

	for (i = 0; command_names[i].name; i++)
		_usage(command_names[i].name, 1, 1);

	print_usage_notes(NULL);
}

/*
 * Sets up the arguments to pass to getopt_long().
 *
 * getopt_long() takes a string of short option characters
 * where the char is followed by ":" if the option takes an arg,
 * e.g. "abc:d:"  This string is created in optstrp.
 *
 * getopt_long() also takes an array of struct option which
 * has the name of the long option, if it takes an arg, etc,
 * e.g.
 *
 * option long_options[] = {
 * 	{ "foo", required_argument, 0,  0  },
 * 	{ "bar", no_argument,       0, 'b' }
 * };
 *
 * this array is created in longoptsp.
 *
 * Original comment:
 * Sets up the short and long argument.  If there
 * is no short argument then the index of the
 * argument in the the_args array is set as the
 * long opt value.  Yuck.  Of course this means we
 * can't have more than 'a' long arguments.
 */

static void _add_getopt_arg(int opt_enum, char **optstrp, struct option **longoptsp)
{
	struct opt_name *a = _cmdline.opt_names + opt_enum;

	if (a->short_opt) {
		*(*optstrp)++ = a->short_opt;

		if (a->val_enum)
			*(*optstrp)++ = ':';
	}
#ifdef HAVE_GETOPTLONG
	/* long_arg is "--foo", so +2 is the offset of the name after "--" */

	if (*(a->long_opt + 2)) {
		(*longoptsp)->name = a->long_opt + 2;
		(*longoptsp)->has_arg = a->val_enum ? 1 : 0;
		(*longoptsp)->flag = NULL;

		/*
		 * When getopt_long() sees an option that has an associated
		 * single letter, it returns the ascii value of that letter.
		 * e.g. getopt_long() returns 100 for '-d' or '--debug'
		 * (100 is the ascii value of 'd').
		 *
		 * When getopt_long() sees an option that does not have an
		 * associated single letter, it returns the value of the
		 * the enum for that long option name plus 128.
		 * e.g. getopt_long() returns 139 for --cachepool
		 * (11 is the enum value for --cachepool, so 11+128)
		 */

		if (a->short_opt)
			(*longoptsp)->val = a->short_opt;
		else
			(*longoptsp)->val = opt_enum + 128;
		(*longoptsp)++;
	}
#endif
}

/*
 * getopt_long() has returned goval which indicates which option it's found.
 * We need to translate that goval to an enum value from the args array.
 * 
 * For options with both long and short forms, goval is the character value
 * of the short option.  For options with only a long form, goval is the
 * corresponding enum value plus 128.
 *
 * The trick with character values is that different long options share the
 * same single-letter short form.  So, we have to translate goval to an
 * enum using only the set of valid options for the given command.  And,
 * a command name is not allowed to use two different long options that
 * have the same single-letter short form.
 */

static int _find_arg(const char *cmd_name, int goval)
{
	struct command_name *cname;
	int arg_enum;
	int i;

	if (!(cname = find_command_name(cmd_name)))
		return -1;

	for (i = 0; i < cname->num_args; i++) {
		arg_enum = cname->valid_args[i];

		/* assert arg_enum == _cmdline.opt_names[arg_enum].arg_enum */

		/* the value returned by getopt matches the ascii value of single letter option */
		if (_cmdline.opt_names[arg_enum].short_opt && (goval == _cmdline.opt_names[arg_enum].short_opt))
			return arg_enum;

		/* the value returned by getopt matches the enum value plus 128 */
		if (!_cmdline.opt_names[arg_enum].short_opt && (goval == (arg_enum + 128)))
			return arg_enum;
	}

	return -1;
}

static int _process_command_line(struct cmd_context *cmd, int *argc, char ***argv)
{
	char str[((ARG_COUNT + 1) * 2) + 1], *ptr = str;
	struct option opts[ARG_COUNT + 1], *o = opts;
	struct opt_name *a;
	struct arg_values *av;
	struct arg_value_group_list *current_group = NULL;
	int arg_enum; /* e.g. foo_ARG */
	int goval;    /* the number returned from getopt_long identifying what it found */
	int i;

	if (!(cmd->opt_arg_values = dm_pool_zalloc(cmd->mem, sizeof(*cmd->opt_arg_values) * ARG_COUNT))) {
		log_fatal("Unable to allocate memory for command line arguments.");
		return 0;
	}

	/*
	 * create the short-form character array (str) and the long-form option
	 * array (opts) to pass to the getopt_long() function.  IOW we generate
	 * the arguments to pass to getopt_long() from the opt_names data.
	 */
	if (cmd->cname)
		for (i = 0; i < cmd->cname->num_args; i++)
			_add_getopt_arg(cmd->cname->valid_args[i], &ptr, &o);

	*ptr = '\0';
	memset(o, 0, sizeof(*o));

	optarg = (char*) "";
	optind = OPTIND_INIT;
	while ((goval = GETOPTLONG_FN(*argc, *argv, str, opts, NULL)) >= 0) {

		if (goval == '?')
			return 0;

		cmd->opt_count++;

		/*
		 * translate the option value used by getopt into the enum
		 * value (e.g. foo_ARG) from the args array.
		 */
		if ((arg_enum = _find_arg(cmd->name, goval)) < 0) {
			log_fatal("Unrecognised option %d (%c).", goval, goval);
			return 0;
		}

		a = _cmdline.opt_names + arg_enum;

		av = &cmd->opt_arg_values[arg_enum];

		if (a->flags & ARG_NONINTERACTIVE && cmd->is_interactive) {
			log_error("Argument%s%c%s%s cannot be used in interactive mode.",
				  a->short_opt ? " -" : "",
				  a->short_opt ? : ' ',
				  (a->short_opt && a->long_opt) ?
				  "/" : "", a->long_opt ? : "");
			return 0;
		}

		if (a->flags & ARG_GROUPABLE) {
			/*
			 * Start a new group of arguments:
			 *   - the first time,
			 *   - or if a non-countable argument is repeated,
			 *   - or if argument has higher priority than current group.
			 */
			if (!current_group ||
			    (current_group->arg_values[arg_enum].count && !(a->flags & ARG_COUNTABLE)) ||
			    (current_group->prio < a->prio)) {
				/* FIXME Reduce size including only groupable args */
				if (!(current_group = dm_pool_zalloc(cmd->mem, sizeof(struct arg_value_group_list) + sizeof(*cmd->opt_arg_values) * ARG_COUNT))) {
					log_fatal("Unable to allocate memory for command line arguments.");
					return 0;
				}

				current_group->prio = a->prio;
				dm_list_add(&cmd->arg_value_groups, &current_group->list);
			}
			/* Maintain total argument count as well as count within each group */
			av->count++;
			av = &current_group->arg_values[arg_enum];
		}

		if (av->count && !(a->flags & ARG_COUNTABLE)) {
			log_error("Option%s%c%s%s may not be repeated.",
				  a->short_opt ? " -" : "",
				  a->short_opt ? : ' ',
				  (a->short_opt && a->long_opt) ?
				  "/" : "", a->long_opt ? : "");
			return 0;
		}

		if (a->val_enum) {
			if (!optarg) {
				log_error("Option requires argument.");
				return 0;
			}

			av->value = optarg;

			if (!val_names[a->val_enum].fn(cmd, av)) {
				log_error("Invalid argument for %s: %s", a->long_opt, optarg);
				return 0;
			}
		}

		av->count++;
	}

	*argc -= optind;
	*argv += optind;
	return 1;
}

static void _copy_arg_values(struct arg_values *av, int oldarg, int newarg)
{
	const struct arg_values *old = av + oldarg;
	struct arg_values *new = av + newarg;

	new->count = old->count;
	new->value = old->value;
	new->i_value = old->i_value;
	new->ui_value = old->ui_value;
	new->i64_value = old->i64_value;
	new->ui64_value = old->ui64_value;
	new->sign = old->sign;
}

static int _merge_synonym(struct cmd_context *cmd, int oldarg, int newarg)
{
	struct arg_values *av;
	struct arg_value_group_list *current_group;

	if (arg_is_set(cmd, oldarg) && arg_is_set(cmd, newarg)) {
		log_error("%s and %s are synonyms.  Please only supply one.",
			  _cmdline.opt_names[oldarg].long_opt, _cmdline.opt_names[newarg].long_opt);
		return 0;
	}

	/* Not groupable? */
	if (!(_cmdline.opt_names[oldarg].flags & ARG_GROUPABLE)) {
		if (arg_is_set(cmd, oldarg))
			_copy_arg_values(cmd->opt_arg_values, oldarg, newarg);
		return 1;
	}

	if (arg_is_set(cmd, oldarg))
		cmd->opt_arg_values[newarg].count = cmd->opt_arg_values[oldarg].count;

	/* Groupable */
	dm_list_iterate_items(current_group, &cmd->arg_value_groups) {
		av = current_group->arg_values;
		if (!grouped_arg_count(av, oldarg))
			continue;
		_copy_arg_values(av, oldarg, newarg);
	}

	return 1;
}

int systemid(struct cmd_context *cmd __attribute__((unused)),
	     int argc __attribute__((unused)),
	     char **argv __attribute__((unused)))
{
	log_print("system ID: %s", cmd->system_id ? : "");

	return ECMD_PROCESSED;
}

int version(struct cmd_context *cmd __attribute__((unused)),
	    int argc __attribute__((unused)),
	    char **argv __attribute__((unused)))
{
	char vsn[80];

	log_print("LVM version:     %s", LVM_VERSION);
	if (library_version(vsn, sizeof(vsn)))
		log_print("Library version: %s", vsn);
	if (driver_version(vsn, sizeof(vsn)))
		log_print("Driver version:  %s", vsn);
	log_print("Configuration:   %s", LVM_CONFIGURE_LINE);

	return ECMD_PROCESSED;
}

static void _reset_current_settings_to_default(struct cmd_context *cmd)
{
	cmd->current_settings = cmd->default_settings;
}

static void _get_current_output_settings_from_args(struct cmd_context *cmd)
{
	if (arg_is_set(cmd, udevoutput_ARG)) {
		cmd->current_settings.suppress = 1;
		cmd->udevoutput = 1;
	}

	if (arg_is_set(cmd, debug_ARG))
		cmd->current_settings.debug = _LOG_FATAL + (arg_count(cmd, debug_ARG) - 1);

	if (arg_is_set(cmd, verbose_ARG))
		cmd->current_settings.verbose = arg_count(cmd, verbose_ARG);

	if (arg_is_set(cmd, quiet_ARG)) {
		cmd->current_settings.debug = 0;
		cmd->current_settings.verbose = 0;
		cmd->current_settings.silent = (arg_count(cmd, quiet_ARG) > 1) ? 1 : 0;
	}

	/*
	 * default_settings.journal is already set from config and has already been
	 * applied using init_log_journal().
	 * current_settings have been set to default_settings.
	 * now --journal value adds to current_settings.
	 */
	if (arg_is_set(cmd, journal_ARG))
		cmd->current_settings.journal |= log_journal_str_to_val(arg_str_value(cmd, journal_ARG, ""));
}

static void _apply_current_output_settings(struct cmd_context *cmd)
{
	log_suppress(cmd->current_settings.suppress);
	init_debug(cmd->current_settings.debug);
	init_debug_classes_logged(cmd->default_settings.debug_classes);
	init_verbose(cmd->current_settings.verbose + VERBOSE_BASE_LEVEL);
	init_silent(cmd->current_settings.silent);
	init_log_journal(cmd->current_settings.journal);
}

static int _read_devices_list(struct cmd_context *cmd)
{
	struct arg_value_group_list *group;
	const char *names;
	struct dm_list *names_list;

	dm_list_iterate_items(group, &cmd->arg_value_groups) {
		if (!grouped_arg_is_set(group->arg_values, devices_ARG))
			continue;

		if (!(names = (char *)grouped_arg_str_value(group->arg_values, devices_ARG, NULL)))
			continue;

		if (!strchr(names, ',')) {
			if (!str_list_add(cmd->mem, &cmd->deviceslist, names))
				return 0;
		} else {
			if ((names_list = str_to_str_list(cmd->mem, names, ",", 1)))
				dm_list_splice(&cmd->deviceslist, names_list);
		}
	}
	return 1;
}

static int _get_current_settings(struct cmd_context *cmd)
{
	const char *activation_mode;
	const char *hint_mode;
	const char *search_mode;

	_get_current_output_settings_from_args(cmd);

	if (arg_is_set(cmd, test_ARG))
		cmd->current_settings.test = arg_is_set(cmd, test_ARG);

	cmd->current_settings.yes = arg_count(cmd, yes_ARG);

	if (arg_is_set(cmd, driverloaded_ARG)) {
		cmd->current_settings.activation =
		    arg_int_value(cmd, driverloaded_ARG,
				  cmd->default_settings.activation);
	}

	cmd->current_settings.archive = arg_int_value(cmd, autobackup_ARG, cmd->current_settings.archive);
	cmd->current_settings.backup = arg_int_value(cmd, autobackup_ARG, cmd->current_settings.backup);

	if (arg_is_set(cmd, readonly_ARG)) {
		cmd->current_settings.activation = 0;
		cmd->current_settings.archive = 0;
		cmd->current_settings.backup = 0;
	}

	if (cmd->cname->flags & LOCKD_VG_SH)
		cmd->lockd_vg_default_sh = 1;

	if (cmd->cname->flags & CAN_USE_ONE_SCAN)
		cmd->can_use_one_scan = 1;

	cmd->include_exported_vgs = (cmd->cname->flags & ALLOW_EXPORTED) ? 1 : 0;

	cmd->scan_lvs = find_config_tree_bool(cmd, devices_scan_lvs_CFG, NULL);

	cmd->allow_mixed_block_sizes = find_config_tree_bool(cmd, devices_allow_mixed_block_sizes_CFG, NULL);

	cmd->check_devs_used = (cmd->cname->flags & CHECK_DEVS_USED) ? 1 : 0;

	cmd->print_device_id_not_found = (cmd->cname->flags & DEVICE_ID_NOT_FOUND) ? 1 : 0;

	/*
	 * enable_hints is set to 1 if any commands are using hints.
	 * use_hints is set to 1 if this command should use the hints.
	 * enable_hints=1 and use_hints=0 means that this command won't
	 * use the hints, but it may invalidate the hints that are used
	 * by other commands.
	 *
	 * enable_hints=0 means no commands are using hints, so this
	 * command would not need to invalidate hints for other cmds.
	 *
	 * Code should check !enable_hints before checking use_hints.
	 */
	cmd->enable_hints = 1;

	/* Only certain commands need to be optimized by using hints. */
	if (cmd->cname->flags & ALLOW_HINTS)
		cmd->use_hints = 1;
	else
		cmd->use_hints = 0;

	/* The hints file is associated with the default/system devices file. */
	if (arg_is_set(cmd, devicesfile_ARG) || arg_is_set(cmd, devices_ARG))
		cmd->use_hints = 0;

	/*
	 * During system init, hints are repeatedly invalidated due to PVs
	 * appearing, so it's wasted effort to try to maintain hints.
	 * Hints are only effective when devices are in a steady-state.
	 */
	if (arg_is_set(cmd, sysinit_ARG))
		cmd->use_hints = 0;

	/*
	 * Don't use hints from this command, but enable_hints will
	 * remain set unless hints=none in the config.  See above re
	 * the meaning of use_hints=0 && enable_hints=1.
	 */
	if (arg_is_set(cmd, nohints_ARG))
		cmd->use_hints = 0;

	if ((hint_mode = find_config_tree_str(cmd, devices_hints_CFG, NULL))) {
		if (!strcmp(hint_mode, "none")) {
			cmd->enable_hints = 0;
			cmd->use_hints = 0;
		}
	}

	cmd->partial_activation = 0;
	cmd->degraded_activation = 0;
	activation_mode = find_config_tree_str(cmd, activation_mode_CFG, NULL);
	if (!activation_mode)
		activation_mode = DEFAULT_ACTIVATION_MODE;

	if (arg_is_set(cmd, activationmode_ARG)) {
		activation_mode = arg_str_value(cmd, activationmode_ARG,
						activation_mode);

		/* complain only if the two arguments conflict */
		if (arg_is_set(cmd, partial_ARG) &&
		    strcmp(activation_mode, "partial")) {
			log_error("--partial and --activationmode are mutually"
				  " exclusive arguments");
			return EINVALID_CMD_LINE;
		}
	} else if (arg_is_set(cmd, partial_ARG))
		activation_mode = "partial";

	if (!strcmp(activation_mode, "partial")) {
		cmd->partial_activation = 1;
		log_warn("PARTIAL MODE. Incomplete logical volumes will be processed.");
	} else if (!strcmp(activation_mode, "degraded"))
		cmd->degraded_activation = 1;
	else if (strcmp(activation_mode, "complete")) {
		log_error("Invalid activation mode given.");
		return EINVALID_CMD_LINE;
	}

	cmd->include_foreign_vgs = arg_is_set(cmd, foreign_ARG) ? 1 : 0;
	cmd->include_shared_vgs = arg_is_set(cmd, shared_ARG) ? 1 : 0;
	cmd->include_historical_lvs = arg_is_set(cmd, history_ARG) ? 1 : 0;
	cmd->record_historical_lvs = find_config_tree_bool(cmd, metadata_record_lvs_history_CFG, NULL) ?
							  (arg_is_set(cmd, nohistory_ARG) ? 0 : 1) : 0;

	if (!(search_mode = find_config_tree_str(cmd, devices_search_for_devnames_CFG, NULL)))
		cmd->search_for_devnames = DEFAULT_SEARCH_FOR_DEVNAMES;
	else {
		if (!strcmp(search_mode, "none") || !strcmp(search_mode, "auto") || !strcmp(search_mode, "all"))
			cmd->search_for_devnames = search_mode;
		else {
			log_warn("Ignoring unknown search_for_devnames setting, using %s.", DEFAULT_SEARCH_FOR_DEVNAMES);
			cmd->search_for_devnames = DEFAULT_SEARCH_FOR_DEVNAMES;
		}
	}

	if (arg_is_set(cmd, devicesfile_ARG)) {
		const char *devices_file = arg_str_value(cmd, devicesfile_ARG, NULL);
		if (devices_file && !strlen(devices_file)) {
			cmd->devicesfile = "";
		} else if (!devices_file || !validate_name(devices_file)) {
			log_error("Invalid devices file name.");
			return EINVALID_CMD_LINE;
		} else if (!(cmd->devicesfile = dm_pool_strdup(cmd->libmem, devices_file))) {
			log_error("Failed to copy devices file name.");
			return EINVALID_CMD_LINE;
		}
	}

	dm_list_init(&cmd->deviceslist);

	if (arg_is_set(cmd, devices_ARG)) {
		if (cmd->devicesfile && strlen(cmd->devicesfile)) {
			log_error("A --devices list cannot be used with --devicesfile.");
			return EINVALID_CMD_LINE;
		}
		cmd->enable_devices_list = 1;
		if (!_read_devices_list(cmd)) {
			log_error("Failed to read --devices args.");
			return EINVALID_CMD_LINE;
		}
	}

	/*
	 * This is set to zero by process_each which wants to print errors
	 * itself rather than having them printed in vg_read.
	 */
	cmd->vg_read_print_access_error = 1;
		
	if (arg_is_set(cmd, nosuffix_ARG))
		cmd->current_settings.suffix = 0;

	if (arg_is_set(cmd, units_ARG))
		if (!(cmd->current_settings.unit_factor =
		      dm_units_to_factor(arg_str_value(cmd, units_ARG, ""),
					 &cmd->current_settings.unit_type, 1, NULL))) {
			log_error("Invalid units specification");
			return EINVALID_CMD_LINE;
		}

	if (arg_is_set(cmd, binary_ARG))
		cmd->report_binary_values_as_numeric = 1;

	if (arg_is_set(cmd, noudevsync_ARG))
		cmd->current_settings.udev_sync = 0;

	/* Handle synonyms */
	if (!_merge_synonym(cmd, resizable_ARG, resizeable_ARG) ||
	    !_merge_synonym(cmd, allocation_ARG, allocatable_ARG) ||
	    !_merge_synonym(cmd, allocation_ARG, resizeable_ARG) ||
	    !_merge_synonym(cmd, virtualoriginsize_ARG, virtualsize_ARG) ||
	    !_merge_synonym(cmd, available_ARG, activate_ARG) ||
	    !_merge_synonym(cmd, raidrebuild_ARG, rebuild_ARG) ||
	    !_merge_synonym(cmd, raidsyncaction_ARG, syncaction_ARG) ||
	    !_merge_synonym(cmd, raidwritemostly_ARG, writemostly_ARG) ||
	    !_merge_synonym(cmd, raidminrecoveryrate_ARG, minrecoveryrate_ARG) ||
	    !_merge_synonym(cmd, raidmaxrecoveryrate_ARG, maxrecoveryrate_ARG) ||
	    !_merge_synonym(cmd, raidwritebehind_ARG, writebehind_ARG))
		return EINVALID_CMD_LINE;

	if ((!strncmp(cmd->name, "pv", 2) &&
	    !_merge_synonym(cmd, metadatacopies_ARG, pvmetadatacopies_ARG)) ||
	    (!strncmp(cmd->name, "vg", 2) &&
	     !_merge_synonym(cmd, metadatacopies_ARG, vgmetadatacopies_ARG)))
		return EINVALID_CMD_LINE;

	/* Zero indicates success */
	return 0;
}

static int _process_common_commands(struct cmd_context *cmd)
{
	if (arg_is_set(cmd, help_ARG) ||
	    arg_is_set(cmd, longhelp_ARG) ||
	    arg_is_set(cmd, help2_ARG)) {
		_usage(cmd->name, arg_is_set(cmd, longhelp_ARG), 0);
		return ECMD_PROCESSED;
	}

	if (arg_is_set(cmd, version_ARG)) {
		return version(cmd, 0, (char **) NULL);
	}

	/* Zero indicates it's OK to continue processing this command */
	return 0;
}

static void _display_help(void)
{
	int i;

	log_error("Available lvm commands:");
	log_error("Use 'lvm help <command>' for more information");
	log_error(" ");

	for (i = 0; i < _cmdline.num_command_names; i++) {
		struct command_name *cname = _cmdline.command_names + i;

		log_error("%-16.16s%s", cname->name, cname->desc);
	}
}

int help(struct cmd_context *cmd __attribute__((unused)), int argc, char **argv)
{
	int ret = ECMD_PROCESSED;

	if (!argc)
		_display_help();
	else if (argc == 1 && !strcmp(argv[0], "all"))
		_usage_all();
	else {
		int i;
		for (i = 0; i < argc; i++)
			if (!_usage(argv[i], 0, 0))
				ret = EINVALID_CMD_LINE;
	}

	return ret;
}

static void _apply_current_settings(struct cmd_context *cmd)
{
	_apply_current_output_settings(cmd);

	init_test(cmd->current_settings.test);
	init_mirror_in_sync(0);
	init_dmeventd_monitor(DEFAULT_DMEVENTD_MONITOR);

	init_msg_prefix(cmd->default_settings.msg_prefix);

	archive_enable(cmd, cmd->current_settings.archive);
	backup_enable(cmd, cmd->current_settings.backup);

	set_activation(cmd->current_settings.activation, cmd->metadata_read_only);

	cmd->fmt = get_format_by_name(cmd, arg_str_value(cmd, metadatatype_ARG,
				      cmd->current_settings.fmt_name));

	cmd->handles_missing_pvs = 0;
}

static const char *_copy_command_line(struct cmd_context *cmd, int argc, char **argv)
{
	int i, space;

	/*
	 * Build up the complete command line, used as a
	 * description for backups.
	 */
	if (!dm_pool_begin_object(cmd->mem, 128))
		goto_bad;

	for (i = 0; i < argc; i++) {
		space = strchr(argv[i], ' ') ? 1 : 0;

		if (space && !dm_pool_grow_object(cmd->mem, "'", 1))
			goto_bad;

		if (!dm_pool_grow_object(cmd->mem, argv[i], strlen(argv[i])))
			goto_bad;

		if (space && !dm_pool_grow_object(cmd->mem, "'", 1))
			goto_bad;

		if (i < (argc - 1))
			if (!dm_pool_grow_object(cmd->mem, " ", 1))
				goto_bad;
	}

	/*
	 * Terminate.
	 */
	if (!dm_pool_grow_object(cmd->mem, "\0", 1))
		goto_bad;

	return dm_pool_end_object(cmd->mem);

      bad:
	log_error("Couldn't copy command line.");
	dm_pool_abandon_object(cmd->mem);
	return NULL;
}

static int _prepare_profiles(struct cmd_context *cmd)
{
	static const char COMMAND_PROFILE_ENV_VAR_NAME[] = "LVM_COMMAND_PROFILE";
	static const char _cmd_profile_arg_preferred_over_env_var_msg[] = "Giving "
				"preference to command profile specified on command "
				"line over the one specified via environment variable.";
	static const char _failed_to_add_profile_msg[] = "Failed to add %s %s.";
	static const char _failed_to_apply_profile_msg[] = "Failed to apply %s %s.";
	static const char _command_profile_source_name[] = "command profile";
	static const char _metadata_profile_source_name[] = "metadata profile";
	static const char _setting_global_profile_msg[] = "Setting global %s \"%s\".";

	const char *env_cmd_profile_name = NULL;
	const char *name;
	struct profile *profile;
	config_source_t source;
	const char *source_name;

	/* Check whether default global command profile is set via env. var. */
	if ((env_cmd_profile_name = getenv(COMMAND_PROFILE_ENV_VAR_NAME))) {
		if (!*env_cmd_profile_name)
			env_cmd_profile_name = NULL;
		else
			log_debug("Command profile '%s' requested via "
				  "environment variable.",
				   env_cmd_profile_name);
	}

	if (!arg_is_set(cmd, profile_ARG) &&
	    !arg_is_set(cmd, commandprofile_ARG) &&
	    !arg_is_set(cmd, metadataprofile_ARG) &&
	    !env_cmd_profile_name)
		/* nothing to do */
		return 1;

	if (arg_is_set(cmd, profile_ARG)) {
		/*
		 * If --profile is used with dumpconfig, it's used
		 * to dump the profile without the profile being applied.
		 */
		if (!strcmp(cmd->command->name, "dumpconfig") ||
		    !strcmp(cmd->command->name, "lvmconfig") ||
		    !strcmp(cmd->command->name, "config"))
			return 1;

		/*
		 * If --profile is used with lvcreate/lvchange/vgchange,
		 * it's recognized as shortcut to --metadataprofile.
		 * The --commandprofile is assumed otherwise.
		 */
		if (!strcmp(cmd->command->name, "lvcreate") ||
		    !strcmp(cmd->command->name, "lvconvert") ||
		    !strcmp(cmd->command->name, "vgcreate") ||
		    !strcmp(cmd->command->name, "lvchange") ||
		    !strcmp(cmd->command->name, "vgchange")) {
			if (arg_is_set(cmd, metadataprofile_ARG)) {
				log_error("Only one of --profile or "
					  " --metadataprofile allowed.");
				return 0;
			}
			source = CONFIG_PROFILE_METADATA;
			source_name = _metadata_profile_source_name;
		}
		else {
			if (arg_is_set(cmd, commandprofile_ARG)) {
				log_error("Only one of --profile or "
					  "--commandprofile allowed.");
				return 0;
			}
			/*
			 * Prefer command profile specified on command
			 * line over the profile specified via
			 * COMMAND_PROFILE_ENV_VAR_NAME env. var.
			 */
			if (env_cmd_profile_name) {
				log_debug(_cmd_profile_arg_preferred_over_env_var_msg);
				env_cmd_profile_name = NULL;
			}
			source = CONFIG_PROFILE_COMMAND;
			source_name = _command_profile_source_name;
		}

		name = arg_str_value(cmd, profile_ARG, NULL);

		if (!(profile = add_profile(cmd, name, source))) {
			log_error(_failed_to_add_profile_msg, source_name, name);
			return 0;
		}

		if (source == CONFIG_PROFILE_COMMAND) {
			log_debug(_setting_global_profile_msg, _command_profile_source_name, profile->name);
			cmd->profile_params->global_command_profile = profile;
		} else if (source == CONFIG_PROFILE_METADATA) {
			log_debug(_setting_global_profile_msg, _metadata_profile_source_name, profile->name);
			/* This profile will override any VG/LV-based profile if present */
			cmd->profile_params->global_metadata_profile = profile;
		}

		remove_config_tree_by_source(cmd, source);
		if (!override_config_tree_from_profile(cmd, profile)) {
			log_error(_failed_to_apply_profile_msg, source_name, name);
			return 0;
		}

	}

	if (arg_is_set(cmd, commandprofile_ARG) || env_cmd_profile_name) {
		if (arg_is_set(cmd, commandprofile_ARG)) {
			/*
			 * Prefer command profile specified on command
			 * line over the profile specified via
			 * COMMAND_PROFILE_ENV_VAR_NAME env. var.
			 */
			if (env_cmd_profile_name)
				log_debug(_cmd_profile_arg_preferred_over_env_var_msg);
			name = arg_str_value(cmd, commandprofile_ARG, NULL);
		} else
			name = env_cmd_profile_name;
		source_name = _command_profile_source_name;

		if (!(profile = add_profile(cmd, name, CONFIG_PROFILE_COMMAND))) {
			log_error(_failed_to_add_profile_msg, source_name, name);
			return 0;
		}

		remove_config_tree_by_source(cmd, CONFIG_PROFILE_COMMAND);
		if (!override_config_tree_from_profile(cmd, profile)) {
			log_error(_failed_to_apply_profile_msg, source_name, name);
			return 0;
		}

		log_debug(_setting_global_profile_msg, _command_profile_source_name, profile->name);
		cmd->profile_params->global_command_profile = profile;

		if (!cmd->opt_arg_values)
			cmd->profile_params->shell_profile = profile;
	}


	if (arg_is_set(cmd, metadataprofile_ARG)) {
		name = arg_str_value(cmd, metadataprofile_ARG, NULL);
		source_name = _metadata_profile_source_name;

		if (!(profile = add_profile(cmd, name, CONFIG_PROFILE_METADATA))) {
			log_error(_failed_to_add_profile_msg, source_name, name);
			return 0;
		}
		remove_config_tree_by_source(cmd, CONFIG_PROFILE_METADATA);
		if (!override_config_tree_from_profile(cmd, profile)) {
			log_error(_failed_to_apply_profile_msg, source_name, name);
			return 0;
		}

		log_debug(_setting_global_profile_msg, _metadata_profile_source_name, profile->name);
		cmd->profile_params->global_metadata_profile = profile;
	}

	if (!process_profilable_config(cmd))
		return_0;

	return 1;
}

static int _init_lvmlockd(struct cmd_context *cmd)
{
	const char *lvmlockd_socket;
	int use_lvmlockd = find_config_tree_bool(cmd, global_use_lvmlockd_CFG, NULL);

	if (cmd->command->command_enum == pvscan_cache_CMD) {
		/* pvscan cache ignores shared vgs, it only activates local vgs. */
		if (use_lvmlockd)
			log_debug("Ignore lvmlockd for pvscan cache.");
		return 1;
	}

	/*
	 * Think about when/how to enable hints with lvmlockd.
	 */
	if (use_lvmlockd)
		cmd->enable_hints = 0;

	if (use_lvmlockd && arg_is_set(cmd, nolocking_ARG)) {
		/* --nolocking is only allowed with vgs/lvs/pvs commands */
		cmd->lockd_gl_disable = 1;
		cmd->lockd_vg_disable = 1;
		cmd->lockd_lv_disable = 1;
		return 1;
	}

	if (use_lvmlockd && arg_is_set(cmd, lockopt_ARG)) {
		const char *opts = arg_str_value(cmd, lockopt_ARG, "");
		if (strstr(opts, "skiplv")) {
			log_warn("WARNING: skipping LV lock in lvmlockd.");
			cmd->lockd_lv_disable = 1;
		}
		if (strstr(opts, "skipvg")) {
			log_warn("WARNING: skipping VG lock in lvmlockd.");
			cmd->lockd_vg_disable = 1;
		}
		if (strstr(opts, "skipgl")) {
			log_warn("WARNING: skipping global lock in lvmlockd.");
			cmd->lockd_gl_disable = 1;
		}
	}

	lvmlockd_disconnect(); /* start over when tool context is refreshed */
	lvmlockd_socket = getenv("LVM_LVMLOCKD_SOCKET");
	if (!lvmlockd_socket)
		lvmlockd_socket = DEFAULT_RUN_DIR "/lvmlockd.socket";

	lvmlockd_set_socket(lvmlockd_socket);
	lvmlockd_set_use(use_lvmlockd);
	if (use_lvmlockd) {
		lvmlockd_init(cmd);
		lvmlockd_connect();
	}

	return 1;
}

/*
 * md_component_check full: always set use_full_md_check
 * which causes filter-md to read the start+end of every
 * device on the system (this could be optimized to only
 * read the end of PVs.)
 *
 * md_component_check start: the end of devices will
 * not generally be read to check for an md superblock
 * (lvm may still scan for end-of-device md superblocks
 * if it knows that some exists.)
 *
 * md_component_check auto: lvm will use some built-in
 * heuristics to decide when it should scan the end of
 * devices to look for md superblocks, e.g. commands
 * like pvcreate that could clobber a component, or if
 * udev info is not available and hints are not available.
 */
static void _init_md_checks(struct cmd_context *cmd)
{
	const char *md_check;

	cmd->md_component_detection = find_config_tree_bool(cmd, devices_md_component_detection_CFG, NULL);

	md_check = find_config_tree_str(cmd, devices_md_component_checks_CFG, NULL);
	if (!md_check)
		cmd->md_component_checks = "auto";
	else if (!strcmp(md_check, "auto") ||
	         !strcmp(md_check, "start") ||
	         !strcmp(md_check, "full"))
		cmd->md_component_checks = md_check;
	else {
		log_warn("Ignoring unknown md_component_checks setting, using auto.");
		cmd->md_component_checks = "auto";
	}

	if (!strcmp(cmd->md_component_checks, "full"))
		cmd->use_full_md_check = 1;

	/* use_full_md_check can also be set later */

	log_debug("Using md_component_checks %s use_full_md_check %d",
		  cmd->md_component_checks, cmd->use_full_md_check);
}

static int _cmd_no_meta_proc(struct cmd_context *cmd)
{
	return cmd->cname->flags & NO_METADATA_PROCESSING;
}

int lvm_run_command(struct cmd_context *cmd, int argc, char **argv)
{
	struct dm_config_tree *config_string_cft, *config_profile_command_cft, *config_profile_metadata_cft;
	int ret = 0;
	int locking_type;
	int readonly = 0;
	int sysinit = 0;
	int monitoring;
	char *arg_new, *arg;
	int i;
	int skip_hyphens;
	int refresh_done = 0;
	int io;

	/* Avoid excessive access to /etc/localtime and set TZ variable for glibc
	 * so it does not need to check /etc/localtime everytime that needs that info */
	if (!getenv("TZ"))
		setenv("TZ", ":/etc/localtime", 0);

	init_error_message_produced(0);

	/* each command should start out with sigint flag cleared */
	sigint_clear();

	if (!(cmd->name = dm_pool_strdup(cmd->mem, dm_basename(argv[0])))) {
		log_error("Failed to strdup command basename.");
		return ECMD_FAILED;
	}

	set_cmd_name(cmd->name);

	init_log_command(find_config_tree_bool(cmd, log_command_names_CFG, NULL), 0);

	configure_command_option_values(cmd->name);

	/* eliminate '-' from all options starting with -- */
	for (i = 1; i < argc; i++) {

		arg = argv[i];

		if (*arg++ != '-' || *arg++ != '-')
			continue;

		/* If we reach "--" then stop. */
		if (!*arg)
			break;

		arg_new = arg;
		skip_hyphens = 1;
		while (*arg) {
			/* If we encounter '=', stop any further hyphen removal. */
			if (*arg == '=')
				skip_hyphens = 0;

			/* Do we need to keep the next character? */
			if (*arg != '-' || !skip_hyphens) {
				if (arg_new != arg)
					*arg_new = *arg;
				++arg_new;
			}
			arg++;
		}

		/* Terminate a shortened arg */
		if (arg_new != arg)
			*arg_new = '\0';
	}

	/* The cmd_line string is only used for logging, not processing. */
	if (!(cmd->cmd_line = _copy_command_line(cmd, argc, argv)))
		return_ECMD_FAILED;

	/* Look up command - will be NULL if not recognised */
	if (!(cmd->cname = find_command_name(cmd->name)))
		return ENO_SUCH_CMD;

	if (!_process_command_line(cmd, &argc, &argv)) {
		log_error("Error during parsing of command line.");
		return EINVALID_CMD_LINE;
	}

	/*
	 * Now we have the command line args, set up any known output logging
	 * options immediately.
	 */
	_reset_current_settings_to_default(cmd);
	_get_current_output_settings_from_args(cmd);
	_apply_current_output_settings(cmd);

	log_debug("Version: %s", LVM_VERSION);
	log_debug("Parsing: %s", cmd->cmd_line);

	if (!(cmd->command = _find_command(cmd, cmd->name, &argc, argv)))
		return EINVALID_CMD_LINE;

	/* avoid this by letting lib code use cmd->command */
	cmd->command_enum = cmd->command->command_enum;

	/*
	 * If option --foo is set which is listed in IO (ignore option) in
	 * command-lines.in, then unset foo.  Commands won't usually use an
	 * ignored option, but there can be shared code that checks for --foo,
	 * and should not find it to be set.
	 */
	for (io = 0; io < cmd->command->io_count; io++) {
		int opt = cmd->command->ignore_opt_args[io].opt;
		if (arg_is_set(cmd, opt)) {
			log_debug("Ignore opt %d", opt);
			cmd->opt_arg_values[opt].count = 0;
		}
	}

	/*
	 * Remaining position args after command name and --options are removed.
	 */
	cmd->position_argc = argc;
	cmd->position_argv = argv;

	if (arg_is_set(cmd, config_ARG))
		if (!override_config_tree_from_string(cmd, arg_str_value(cmd, config_ARG, ""))) {
			ret = EINVALID_CMD_LINE;
			goto_out;
		}

	if (arg_is_set(cmd, config_ARG) || !cmd->initialized.config || config_files_changed(cmd)) {
		/* Reinitialise various settings inc. logging, filters */
		if (!refresh_toolcontext(cmd)) {
			if ((config_string_cft = remove_config_tree_by_source(cmd, CONFIG_STRING)))
				dm_config_destroy(config_string_cft);
			log_error("Updated config file invalid. Aborting.");
			return ECMD_FAILED;
		}
		refresh_done = 1;
	}

	if (!_prepare_profiles(cmd))
		return_ECMD_FAILED;

	if (!cmd->initialized.connections && !_cmd_no_meta_proc(cmd) && !init_connections(cmd))
		return_ECMD_FAILED;

	if (!cmd->initialized.filters && !_cmd_no_meta_proc(cmd) &&
	    !init_filters(cmd, !refresh_done))
		return_ECMD_FAILED;

	cmd->metadata_read_only = arg_is_set(cmd, readonly_ARG);

	cmd->is_activating = (cmd->command->command_enum == vgchange_activate_CMD) ||
			     (cmd->command->command_enum == lvchange_activate_CMD);

	cmd->wipe_outdated_pvs = 0;

	/*
	 * Now that all configs, profiles and command lines args are available,
	 * freshly calculate and apply all settings.  Specific command line
	 * options take precedence over config files (which include --config as
	 * that is treated like a config file).
	 */
	_reset_current_settings_to_default(cmd);
	if ((ret = _get_current_settings(cmd)))
		goto_out;
	_apply_current_settings(cmd);

	if (cmd->degraded_activation)
		log_debug("DEGRADED MODE. Incomplete RAID LVs will be processed.");

	if (!get_activation_monitoring_mode(cmd, &monitoring))
		goto_out;
	init_dmeventd_monitor(monitoring);

	log_debug("Processing command: %s", cmd->cmd_line);
	log_debug("Command pid: %d", getpid());
	log_debug("System ID: %s", cmd->system_id ? : "");

#ifdef O_DIRECT_SUPPORT
	log_debug("O_DIRECT will be used");
#endif

	if ((ret = _process_common_commands(cmd))) {
		if (ret != ECMD_PROCESSED)
			stack;
		goto out;
	}

	if (cmd->metadata_read_only &&
	    !(cmd->cname->flags & PERMITTED_READ_ONLY)) {
		log_error("%s: Command not permitted while global/metadata_read_only "
			  "is set.", cmd->cmd_line);
		goto out;
	}

	cmd->ignorelockingfailure = arg_is_set(cmd, ignorelockingfailure_ARG);
	cmd->nolocking = arg_is_set(cmd, nolocking_ARG);

	if (_cmd_no_meta_proc(cmd))
		cmd->nolocking = 1;

	/* Defaults to 1 if not set. */
	locking_type = find_config_tree_int(cmd, global_locking_type_CFG, NULL);

	if (locking_type == 3)
		log_warn("WARNING: see lvmlockd(8) for information on using cluster/clvm VGs.");

	if ((locking_type == 0) || (locking_type == 5)) {
		log_warn("WARNING: locking_type (%d) is deprecated, using --nolocking.", locking_type);
		cmd->nolocking = 1;

	} else if (locking_type == 4) {
		log_warn("WARNING: locking_type (%d) is deprecated, using --sysinit --readonly.", locking_type);
		sysinit = 1;
		readonly = 1;

	} else if (locking_type != 1) {
		log_warn("WARNING: locking_type (%d) is deprecated, using file locking.", locking_type);
	}

	if ((cmd->sysinit = arg_is_set(cmd, sysinit_ARG)))
		sysinit = 1;

	if (arg_is_set(cmd, readonly_ARG))
		readonly = 1;

	if (!cmd->nolocking) {
		if (!init_locking(cmd, sysinit, readonly, cmd->ignorelockingfailure)) {
			ret = ECMD_FAILED;
			goto_out;
		}
	}

	_init_md_checks(cmd);

	if (!dev_mpath_init(find_config_tree_str_allow_empty(cmd, devices_multipath_wwids_file_CFG, NULL))) {
		ret = ECMD_FAILED;
		goto_out;
	}

	if (!_cmd_no_meta_proc(cmd) && !_init_lvmlockd(cmd)) {
		ret = ECMD_FAILED;
		goto_out;
	}

	if (cmd->command->functions)
		/* A command-line-specific function is used */
		ret = cmd->command->functions->fn(cmd, argc, argv);
	else
		/* The old style command-name function is used */
		ret = cmd->command->fn(cmd, argc, argv);

	lvmlockd_disconnect();
	fin_locking(cmd);

	if (!_cmd_no_meta_proc(cmd) && find_config_tree_bool(cmd, global_notify_dbus_CFG, NULL))
		lvmnotify_send(cmd);

      out:

	dev_mpath_exit();
	hints_exit(cmd);
	lvmcache_destroy(cmd, 1, 1);
	label_scan_destroy(cmd);
	devices_file_exit(cmd);

	if ((config_string_cft = remove_config_tree_by_source(cmd, CONFIG_STRING)))
		dm_config_destroy(config_string_cft);

	config_profile_command_cft = remove_config_tree_by_source(cmd, CONFIG_PROFILE_COMMAND);
	config_profile_metadata_cft = remove_config_tree_by_source(cmd, CONFIG_PROFILE_METADATA);
	cmd->profile_params->global_metadata_profile = NULL;

	if (config_string_cft) {
		/* Move this? */
		if (!refresh_toolcontext(cmd))
			stack;
	} else if (config_profile_command_cft || config_profile_metadata_cft) {
		if (!process_profilable_config(cmd))
			stack;
	}

	if (ret == EINVALID_CMD_LINE && !cmd->is_interactive)
		_short_usage(cmd->command->name);

	log_debug("Completed: %s", cmd->cmd_line);

	/*
	 * Reset all settings back to the persistent defaults that
	 * ignore everything supplied on the command line of the
	 * completed command.
	 */
	//_reset_current_settings_to_default(cmd);
	//_apply_current_settings(cmd);

	/*
	 * free off any memory the command used.
	 */
	dm_list_init(&cmd->arg_value_groups);
	dm_pool_empty(cmd->mem);

	reset_lvm_errno(1);
	reset_log_duplicated();

	return ret;
}

int lvm_return_code(int ret)
{
	unlink_log_file(ret);

	return (ret == ECMD_PROCESSED ? 0 : ret);
}

int lvm_split(char *str, int *argc, char **argv, int max)
{
	char *b = str, *e;
	char quote = 0;
	*argc = 0;

	while (*b) {
		while (*b && isspace(*b))
			b++;

		if ((!*b) || (*b == '#'))
			break;

		if (*b == '\'' || *b == '"') {
			quote = *b;
			b++;
		}

		e = b;
		while (*e && (quote ? *e != quote : !isspace(*e)))
			e++;

		argv[(*argc)++] = b;
		if (!*e)
			break;
		*e++ = '\0';
		quote = 0;
		b = e;
		if (*argc == max)
			break;
	}

	if (*argc < max)
		argv[*argc] = NULL;

	return *argc;
}

/* Make sure we have always valid filedescriptors 0,1,2 */
static int _check_standard_fds(void)
{
	int err = is_valid_fd(STDERR_FILENO);

	if (!is_valid_fd(STDIN_FILENO) &&
	    !(stdin = fopen(_PATH_DEVNULL, "r"))) {
		if (err)
			perror("stdin stream open");
		else
			printf("stdin stream open: %s\n",
			       strerror(errno));
		return 0;
	}

	if (!is_valid_fd(STDOUT_FILENO) &&
	    !(stdout = fopen(_PATH_DEVNULL, "w"))) {
		if (err)
			perror("stdout stream open");
		/* else no stdout */
		return 0;
	}

	if (!is_valid_fd(STDERR_FILENO) &&
	    !(stderr = fopen(_PATH_DEVNULL, "w"))) {
		printf("stderr stream open: %s\n",
		       strerror(errno));
		return 0;
	}

	return 1;
}

#define LVM_OUT_FD_ENV_VAR_NAME    "LVM_OUT_FD"
#define LVM_ERR_FD_ENV_VAR_NAME    "LVM_ERR_FD"
#define LVM_REPORT_FD_ENV_VAR_NAME "LVM_REPORT_FD"

static int _do_get_custom_fd(const char *env_var_name, int *fd)
{
	const char *str;
	char *endptr;
	long int tmp_fd;

	*fd = -1;

	if (!(str = getenv(env_var_name)))
		return 1;

	errno = 0;
	tmp_fd = strtol(str, &endptr, 10);
	if (errno || *endptr || (tmp_fd < 0) || (tmp_fd > INT_MAX)) {
		log_error("%s: invalid file descriptor.", env_var_name);
		return 0;
	}

	*fd = tmp_fd;
	return 1;
}

static int _get_custom_fds(struct custom_fds *custom_fds)
{
	return _do_get_custom_fd(LVM_OUT_FD_ENV_VAR_NAME, &custom_fds->out) &&
	       _do_get_custom_fd(LVM_ERR_FD_ENV_VAR_NAME, &custom_fds->err) &&
	       _do_get_custom_fd(LVM_REPORT_FD_ENV_VAR_NAME, &custom_fds->report);
}

static const char *_get_cmdline(pid_t pid)
{
	static char _proc_cmdline[32];
	char buf[256];
	int fd, n = 0;

	snprintf(buf, sizeof(buf), DEFAULT_PROC_DIR "/%u/cmdline", pid);
	/* FIXME Use generic read code. */
	if ((fd = open(buf, O_RDONLY)) >= 0) {
		if ((n = read(fd, _proc_cmdline, sizeof(_proc_cmdline) - 1)) < 0) {
			log_sys_error("read", buf);
			n = 0;
		}
		if (close(fd))
			log_sys_error("close", buf);
	}
	_proc_cmdline[n] = '\0';

	return _proc_cmdline;
}

static const char *_get_filename(int fd)
{
	static char filename[PATH_MAX];
	char buf[32];	/* Assumes short DEFAULT_PROC_DIR */
	int size;

	snprintf(buf, sizeof(buf), DEFAULT_PROC_DIR "/self/fd/%u", fd);

	if ((size = readlink(buf, filename, sizeof(filename) - 1)) == -1)
		filename[0] = '\0';
	else
		filename[size] = '\0';

	return filename;
}

static void _close_descriptor(int fd, unsigned suppress_warnings,
			      const char *command, pid_t ppid,
			      const char *parent_cmdline)
{
	int r;
	const char *filename;

	/* Ignore bad file descriptors */
	if (!is_valid_fd(fd))
		return;

	if (!suppress_warnings)
		filename = _get_filename(fd);

	r = close(fd);
	if (suppress_warnings)
		return;

	if (!r)
		fprintf(stderr, "File descriptor %d (%s) leaked on "
			"%s invocation.", fd, filename, command);
	else if (errno == EBADF)
		return;
	else
		fprintf(stderr, "Close failed on stray file descriptor "
			"%d (%s): %s", fd, filename, strerror(errno));

	fprintf(stderr, " Parent PID %" PRIpid_t ": %s\n", ppid, parent_cmdline);
}

static int _close_stray_fds(const char *command, struct custom_fds *custom_fds)
{
#ifndef VALGRIND_POOL
	struct rlimit rlim;
	int fd;
	unsigned suppress_warnings = 0;
	pid_t ppid = getppid();
	const char *parent_cmdline = _get_cmdline(ppid);
	static const char _fd_dir[] = DEFAULT_PROC_DIR "/self/fd";
	struct dirent *dirent;
	DIR *d;

#ifdef HAVE_VALGRIND
	if (RUNNING_ON_VALGRIND) {
		log_debug("Skipping close of descriptors within valgrind execution.");
		return 1;
	}
#endif

	if (getenv("LVM_SUPPRESS_FD_WARNINGS"))
		suppress_warnings = 1;

	if (!(d = opendir(_fd_dir))) {
		if (errno != ENOENT) {
			log_sys_error("opendir", _fd_dir);
			return 0; /* broken system */
		}

		/* Path does not exist, use the old way */
		if (getrlimit(RLIMIT_NOFILE, &rlim) < 0) {
			log_sys_error("getrlimit", "RLIMIT_NOFILE");
			return 1;
		}

		for (fd = 3; fd < (int)rlim.rlim_cur; fd++) {
			if ((fd != custom_fds->out) &&
			    (fd != custom_fds->err) &&
			    (fd != custom_fds->report)) {
				_close_descriptor(fd, suppress_warnings, command, ppid,
						  parent_cmdline);
			}
		}
		return 1;
	}

	while ((dirent = readdir(d))) {
		fd = atoi(dirent->d_name);
		if ((fd > 2) &&
		    (fd != dirfd(d)) &&
		    (fd != custom_fds->out) &&
		    (fd != custom_fds->err) &&
		    (fd != custom_fds->report)) {
			_close_descriptor(fd, suppress_warnings,
					  command, ppid, parent_cmdline);
		}
	}

	if (closedir(d))
		log_sys_debug("closedir", _fd_dir);
#endif

	return 1;
}

struct cmd_context *init_lvm(unsigned set_connections,
			     unsigned set_filters,
			     unsigned threaded)
{
	struct cmd_context *cmd;

	/*
	 * It's not necessary to use name mangling for LVM:
	 *   - the character set used for LV names is subset of udev character set
	 *   - when we check other devices (e.g. device_is_usable fn), we use major:minor, not dm names
	 */
	dm_set_name_mangling_mode(DM_STRING_MANGLING_NONE);

	if (!(cmd = create_toolcontext(0, NULL, 1, threaded, set_connections, set_filters))) {
		return_NULL;
	}

	_cmdline.opt_names = &opt_names[0];

	if (stored_errno()) {
		destroy_toolcontext(cmd);
		return_NULL;
	}

	return cmd;
}

void lvm_fin(struct cmd_context *cmd)
{
	_unregister_commands();
	destroy_toolcontext(cmd);
	udev_fin_library_context();
}

static int _run_script(struct cmd_context *cmd, int argc, char **argv)
{
	FILE *script;
	char buffer[CMD_LEN];
	int ret = ENO_SUCH_CMD;
	int magic_number = 0;
	char *script_file = argv[0];
	int largc;
	char *largv[MAX_ARGS];

	if ((script = fopen(script_file, "r")) == NULL)
		return ENO_SUCH_CMD;

	while (fgets(buffer, sizeof(buffer), script) != NULL) {
		if (!magic_number) {
			if (buffer[0] == '#' && buffer[1] == '!')
				magic_number = 1;
			else {
				ret = ENO_SUCH_CMD;
				break;
			}
		}
		if ((strlen(buffer) == sizeof(buffer) - 1)
		    && (buffer[sizeof(buffer) - 1] - 2 != '\n')) {
			buffer[50] = '\0';
			log_error("Line too long (max 255) beginning: %s",
				  buffer);
			ret = EINVALID_CMD_LINE;
			break;
		}
		if (lvm_split(buffer, &largc, largv, MAX_ARGS) == MAX_ARGS) {
			buffer[50] = '\0';
			log_error("Too many arguments: %s", buffer);
			ret = EINVALID_CMD_LINE;
			break;
		}
		if (!largc)
			continue;
		if (!strcmp(largv[0], "quit") || !strcmp(largv[0], "exit"))
			break;
		ret = lvm_run_command(cmd, largc, largv);
		/*
		 * FIXME: handling scripts with invalid or failing commands
		 * could use some cleaning up, e.g. error_message_produced
		 * check and error are repeated again in the caller.
		 */
		if (ret == ENO_SUCH_CMD)
			break;
		if (ret != ECMD_PROCESSED) {
			if (!error_message_produced()) {
				log_debug(INTERNAL_ERROR "Failed command did not use log_error");
				log_error("Command failed with status code %d.", ret);
			}
			break;
		}
	}

	if (fclose(script))
		log_sys_error("fclose", script_file);

	return ret;
}

static void _nonroot_warning(void)
{
	if (getuid() || geteuid())
		log_warn("WARNING: Running as a non-root user. Functionality may be unavailable.");
}

int lvm2_main(int argc, char **argv)
{
	const char *base;
	int ret, alias = 0;
	struct custom_fds custom_fds;
	struct cmd_context *cmd;
	int run_shell = 0;
	int run_script = 0;
	const char *run_name;
	const char *run_command_name = NULL;

	if (!argv)
		return EINIT_FAILED;

	base = last_path_component(argv[0]);
	if (strcmp(base, "lvm") && strcmp(base, "lvm.static") &&
	    strcmp(base, "initrd-lvm"))
		alias = 1;

	if (!_check_standard_fds())
		return EINIT_FAILED;

	if (!_get_custom_fds(&custom_fds))
		return EINIT_FAILED;

	if (!_close_stray_fds(base, &custom_fds))
		return EINIT_FAILED;

	if (!init_custom_log_streams(&custom_fds))
		return EINIT_FAILED;

	if (is_static() && strcmp(base, "lvm.static") &&
	    path_exists(LVM_PATH) &&
	    !getenv("LVM_DID_EXEC")) {
		if (setenv("LVM_DID_EXEC", base, 1))
			log_sys_error("setenv", "LVM_DID_EXEC");
		if (execvp(LVM_PATH, argv) == -1)
			log_sys_error("execvp", LVM_PATH);
		if (unsetenv("LVM_DID_EXEC"))
			log_sys_error("unsetenv", "LVM_DID_EXEC");
	}

	if (!alias && argc > 1) {
		/* "version" command is simple enough so it doesn't need any complex init */
		if (!strcmp(argv[1], "version"))
			return lvm_return_code(version(NULL, argc, argv));

		/* turn 'lvm -h', 'lvm --help', 'lvm -?' into 'lvm help' */
		if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help") || !strcmp(argv[1], "-?"))
			argv[1] = (char *)"help";

		if (*argv[1] == '-') {
			log_error("Specify options after a command: lvm [command] [options].");
			return EINVALID_CMD_LINE;
		}
	}

	/* turn command -? into command -h and lvm command -? into lvm command -h */
	if (alias && (argc > 1) && !strcmp(argv[1], "-?"))
		argv[1] = (char *)"-h";
	if (!alias && (argc > 2) && !strcmp(argv[2], "-?"))
		argv[2] = (char *)"-h";

	if (!(cmd = init_lvm(0, 0, 0)))
		return EINIT_FAILED;

	/* Store original argv location so we may customise it if we become a daemon */
	cmd->argv = argv;

	/*
	 * If the invocation command name wasn't itself an alias, shift to the
	 * first arg.  After this point, run_name holds one of:
	 *   the LVM command name we want to run;
	 *   the LVM script name (handled through ENO_SUCH_CMD below);
	 *   NULL for a shell (if readline is enabled).
	 */
	if (!alias) {
		argc--;
		argv++;
		run_name = argv[0];
	} else
		run_name = dm_basename(argv[0]);

	/*
	 * Decide if we are running a shell or a command or a script.  When
	 * there is no run_name, it's a shell, when run_name is a recognized
	 * lvm command it's that command, when run_name is not a recognized
	 * command name, try it as an lvm script.
	 */
	if (!run_name)
		run_shell = 1;
	else if (!find_command_name(run_name))
		run_script = 1;
	else
		run_command_name = run_name;

	/*
	 * NULL run_command_name means register all command defs because
	 * a script or shell needs to access any command name, while a
	 * single command needs to access only defs for the named command.
	 */
	if (!lvm_register_commands(cmd, run_command_name)) {
		ret = ECMD_FAILED;
		goto out;
	}

	if (run_shell) {
#if defined(READLINE_SUPPORT) || defined(EDITLINE_SUPPORT)
		_nonroot_warning();
		if (!_prepare_profiles(cmd)) {
			ret = ECMD_FAILED;
			goto out;
		}
		ret = lvm_shell(cmd, &_cmdline);
		goto out;
#else
		log_fatal("Please supply an LVM command.");
		_display_help();
		ret = EINVALID_CMD_LINE;
		goto out;
#endif
	}

	_nonroot_warning();

	if (run_script)
		ret = _run_script(cmd, argc, argv);
	else
		ret = lvm_run_command(cmd, argc, argv);

	if (ret == ENO_SUCH_CMD) {
		log_error("No such command.  Try 'lvm help'.");
		goto out;
	}

	if ((ret != ECMD_PROCESSED) && !error_message_produced()) {
		log_debug(INTERNAL_ERROR "Failed command did not use log_error");
		log_error("Command failed with status code %d.", ret);
	}

      out:
	lvm_fin(cmd);

	return lvm_return_code(ret);
}