Imported Upstream version 2.02.79
[platform/upstream/device-mapper.git] / tools / lvconvert.c
1 /*
2  * Copyright (C) 2005-2007 Red Hat, Inc. All rights reserved.
3  *
4  * This file is part of LVM2.
5  *
6  * This copyrighted material is made available to anyone wishing to use,
7  * modify, copy, or redistribute it subject to the terms and conditions
8  * of the GNU Lesser General Public License v.2.1.
9  *
10  * You should have received a copy of the GNU Lesser General Public License
11  * along with this program; if not, write to the Free Software Foundation,
12  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
13  */
14
15 #include "tools.h"
16 #include "polldaemon.h"
17 #include "lv_alloc.h"
18 #include "metadata.h"
19
20 struct lvconvert_params {
21         int snapshot;
22         int merge;
23         int zero;
24
25         const char *origin;
26         const char *lv_name;
27         const char *lv_split_name;
28         const char *lv_name_full;
29         const char *vg_name;
30         int wait_completion;
31         int need_polling;
32
33         uint32_t chunk_size;
34         uint32_t region_size;
35
36         uint32_t mirrors;
37         sign_t mirrors_sign;
38         uint32_t keep_mimages;
39         uint32_t stripes;
40         uint32_t stripe_size;
41
42         struct segment_type *segtype;
43
44         alloc_policy_t alloc;
45
46         int pv_count;
47         char **pvs;
48         struct dm_list *pvh;
49         struct dm_list *failed_pvs;
50
51         struct logical_volume *lv_to_poll;
52 };
53
54 static int _lvconvert_name_params(struct lvconvert_params *lp,
55                                   struct cmd_context *cmd,
56                                   int *pargc, char ***pargv)
57 {
58         char *ptr;
59         const char *vg_name = NULL;
60
61         if (lp->merge)
62                 return 1;
63
64         if (lp->snapshot) {
65                 if (!*pargc) {
66                         log_error("Please specify a logical volume to act as "
67                                   "the snapshot origin.");
68                         return 0;
69                 }
70
71                 lp->origin = *pargv[0];
72                 (*pargv)++, (*pargc)--;
73                 if (!(lp->vg_name = extract_vgname(cmd, lp->origin))) {
74                         log_error("The origin name should include the "
75                                   "volume group.");
76                         return 0;
77                 }
78
79                 /* Strip the volume group from the origin */
80                 if ((ptr = strrchr(lp->origin, (int) '/')))
81                         lp->origin = ptr + 1;
82         }
83
84         if (!*pargc) {
85                 log_error("Please provide logical volume path");
86                 return 0;
87         }
88
89         lp->lv_name = lp->lv_name_full = (*pargv)[0];
90         (*pargv)++, (*pargc)--;
91
92         if (strchr(lp->lv_name_full, '/') &&
93             (vg_name = extract_vgname(cmd, lp->lv_name_full)) &&
94             lp->vg_name && strcmp(vg_name, lp->vg_name)) {
95                 log_error("Please use a single volume group name "
96                           "(\"%s\" or \"%s\")", vg_name, lp->vg_name);
97                 return 0;
98         }
99
100         if (!lp->vg_name)
101                 lp->vg_name = vg_name;
102
103         if (!validate_name(lp->vg_name)) {
104                 log_error("Please provide a valid volume group name");
105                 return 0;
106         }
107
108         if ((ptr = strrchr(lp->lv_name_full, '/')))
109                 lp->lv_name = ptr + 1;
110
111         if (!apply_lvname_restrictions(lp->lv_name))
112                 return_0;
113
114         if (*pargc && lp->snapshot) {
115                 log_error("Too many arguments provided for snapshots");
116                 return 0;
117         }
118
119         return 1;
120 }
121
122 static int _read_params(struct lvconvert_params *lp, struct cmd_context *cmd,
123                         int argc, char **argv)
124 {
125         int region_size;
126         int pagesize = lvm_getpagesize();
127
128         memset(lp, 0, sizeof(*lp));
129
130         if ((arg_count(cmd, snapshot_ARG) || arg_count(cmd, merge_ARG)) &&
131             (arg_count(cmd, mirrorlog_ARG) || arg_count(cmd, mirrors_ARG) ||
132              arg_count(cmd, repair_ARG))) {
133                 log_error("--snapshot or --merge argument cannot be mixed "
134                           "with --mirrors, --repair or --log");
135                 return 0;
136         }
137
138         if (!arg_count(cmd, background_ARG))
139                 lp->wait_completion = 1;
140
141         if (arg_count(cmd, snapshot_ARG))
142                 lp->snapshot = 1;
143
144         if (arg_count(cmd, snapshot_ARG) && arg_count(cmd, merge_ARG)) {
145                 log_error("--snapshot and --merge are mutually exclusive");
146                 return 0;
147         }
148
149         if (arg_count(cmd, splitmirrors_ARG) && arg_count(cmd, mirrors_ARG)) {
150                 log_error("--mirrors and --splitmirrors are "
151                           "mutually exclusive");
152                 return 0;
153         }
154
155         /*
156          * The '--splitmirrors n' argument is equivalent to '--mirrors -n'
157          * (note the minus sign), except that it signifies the additional
158          * intent to keep the mimage that is detached, rather than
159          * discarding it.
160          */
161         if (arg_count(cmd, splitmirrors_ARG)) {
162                 if (!arg_count(cmd, name_ARG)) {
163                         log_error("Please name the new logical volume using '--name'");
164                         return 0;
165                 }
166
167                 lp->lv_split_name = arg_value(cmd, name_ARG);
168                 if (!apply_lvname_restrictions(lp->lv_split_name))
169                         return_0;
170
171                 lp->keep_mimages = 1;
172                 if (arg_sign_value(cmd, mirrors_ARG, 0) == SIGN_MINUS) {
173                         log_error("Argument to --splitmirrors"
174                                   " cannot be negative");
175                         return 0;
176                 }
177                 lp->mirrors = arg_uint_value(cmd, splitmirrors_ARG, 0);
178                 lp->mirrors_sign = SIGN_MINUS;
179         } else if (arg_count(cmd, name_ARG)) {
180                 log_error("The 'name' argument is only valid"
181                           " with --splitmirrors");
182                 return 0;
183         }
184
185         if (arg_count(cmd, merge_ARG))
186                 lp->merge = 1;
187
188         if (arg_count(cmd, mirrors_ARG)) {
189                 /*
190                  * --splitmirrors has been chosen as the mechanism for
191                  * specifying the intent of detaching and keeping a mimage
192                  * versus an additional qualifying argument being added here.
193                  */
194                 lp->mirrors = arg_uint_value(cmd, mirrors_ARG, 0);
195                 lp->mirrors_sign = arg_sign_value(cmd, mirrors_ARG, 0);
196         }
197
198         lp->alloc = arg_uint_value(cmd, alloc_ARG, ALLOC_INHERIT);
199
200         /* There are three types of lvconvert. */
201         if (lp->merge) {        /* Snapshot merge */
202                 if (arg_count(cmd, regionsize_ARG) || arg_count(cmd, chunksize_ARG) ||
203                     arg_count(cmd, zero_ARG) || arg_count(cmd, regionsize_ARG) ||
204                     arg_count(cmd, stripes_long_ARG) || arg_count(cmd, stripesize_ARG)) {
205                         log_error("Only --background and --interval are valid "
206                                   "arguments for snapshot merge");
207                         return 0;
208                 }
209
210                 if (!(lp->segtype = get_segtype_from_string(cmd, "snapshot")))
211                         return_0;
212
213         } else if (lp->snapshot) {      /* Snapshot creation from pre-existing cow */
214                 if (arg_count(cmd, regionsize_ARG)) {
215                         log_error("--regionsize is only available with mirrors");
216                         return 0;
217                 }
218
219                 if (arg_count(cmd, stripesize_ARG) || arg_count(cmd, stripes_long_ARG)) {
220                         log_error("--stripes and --stripesize are only available with striped mirrors");
221                         return 0;
222                 }
223
224                 if (arg_sign_value(cmd, chunksize_ARG, 0) == SIGN_MINUS) {
225                         log_error("Negative chunk size is invalid");
226                         return 0;
227                 }
228                 lp->chunk_size = arg_uint_value(cmd, chunksize_ARG, 8);
229                 if (lp->chunk_size < 8 || lp->chunk_size > 1024 ||
230                     (lp->chunk_size & (lp->chunk_size - 1))) {
231                         log_error("Chunk size must be a power of 2 in the "
232                                   "range 4K to 512K");
233                         return 0;
234                 }
235                 log_verbose("Setting chunksize to %d sectors.", lp->chunk_size);
236
237                 if (!(lp->segtype = get_segtype_from_string(cmd, "snapshot")))
238                         return_0;
239
240                 lp->zero = strcmp(arg_str_value(cmd, zero_ARG,
241                                                 (lp->segtype->flags &
242                                                  SEG_CANNOT_BE_ZEROED) ?
243                                                 "n" : "y"), "n");
244
245         } else {        /* Mirrors */
246                 if (arg_count(cmd, chunksize_ARG)) {
247                         log_error("--chunksize is only available with "
248                                   "snapshots");
249                         return 0;
250                 }
251
252                 if (arg_count(cmd, zero_ARG)) {
253                         log_error("--zero is only available with snapshots");
254                         return 0;
255                 }
256
257                 /*
258                  * --regionsize is only valid if converting an LV into a mirror.
259                  * Checked when we know the state of the LV being converted.
260                  */
261
262                 if (arg_count(cmd, regionsize_ARG)) {
263                         if (arg_sign_value(cmd, regionsize_ARG, 0) ==
264                                     SIGN_MINUS) {
265                                 log_error("Negative regionsize is invalid");
266                                 return 0;
267                         }
268                         lp->region_size = arg_uint_value(cmd, regionsize_ARG, 0);
269                 } else {
270                         region_size = 2 * find_config_tree_int(cmd,
271                                                 "activation/mirror_region_size",
272                                                 DEFAULT_MIRROR_REGION_SIZE);
273                         if (region_size < 0) {
274                                 log_error("Negative regionsize in "
275                                           "configuration file is invalid");
276                                 return 0;
277                         }
278                         lp->region_size = region_size;
279                 }
280
281                 if (lp->region_size % (pagesize >> SECTOR_SHIFT)) {
282                         log_error("Region size (%" PRIu32 ") must be "
283                                   "a multiple of machine memory "
284                                   "page size (%d)",
285                                   lp->region_size, pagesize >> SECTOR_SHIFT);
286                         return 0;
287                 }
288
289                 if (lp->region_size & (lp->region_size - 1)) {
290                         log_error("Region size (%" PRIu32
291                                   ") must be a power of 2", lp->region_size);
292                         return 0;
293                 }
294
295                 if (!lp->region_size) {
296                         log_error("Non-zero region size must be supplied.");
297                         return 0;
298                 }
299
300                 /* Default is never striped, regardless of existing LV configuration. */
301                 if (!get_stripe_params(cmd, &lp->stripes, &lp->stripe_size)) {
302                         stack;
303                         return 0;
304                 }
305
306                 if (!(lp->segtype = get_segtype_from_string(cmd, "mirror")))
307                         return_0;
308         }
309
310         if (activation() && lp->segtype->ops->target_present &&
311             !lp->segtype->ops->target_present(cmd, NULL, NULL)) {
312                 log_error("%s: Required device-mapper target(s) not "
313                           "detected in your kernel", lp->segtype->name);
314                 return 0;
315         }
316
317         if (!_lvconvert_name_params(lp, cmd, &argc, &argv))
318                 return_0;
319
320         lp->pv_count = argc;
321         lp->pvs = argv;
322         lp->failed_pvs = NULL;
323
324         return 1;
325 }
326
327 static struct volume_group *_get_lvconvert_vg(struct cmd_context *cmd,
328                                               const char *name,
329                                               const char *uuid __attribute__((unused)))
330 {
331         dev_close_all();
332
333         if (name && !strchr(name, '/'))
334                 return vg_read_for_update(cmd, name, NULL, 0);
335
336         /* 'name' is the full LV name; must extract_vgname() */
337         return vg_read_for_update(cmd, extract_vgname(cmd, name),
338                                   NULL, 0);
339 }
340
341 static struct logical_volume *_get_lvconvert_lv(struct cmd_context *cmd __attribute__((unused)),
342                                                 struct volume_group *vg,
343                                                 const char *name,
344                                                 const char *uuid,
345                                                 uint32_t lv_type __attribute__((unused)))
346 {
347         struct logical_volume *lv = find_lv(vg, name);
348
349         if (!lv || (uuid && strcmp(uuid, (char *)&lv->lvid)))
350                 return NULL;
351
352         return lv;
353 }
354
355 static int _finish_lvconvert_mirror(struct cmd_context *cmd,
356                                     struct volume_group *vg,
357                                     struct logical_volume *lv,
358                                     struct dm_list *lvs_changed __attribute__((unused)))
359 {
360         int r = 0;
361
362         if (!(lv->status & CONVERTING))
363                 return 1;
364
365         if (!collapse_mirrored_lv(lv)) {
366                 log_error("Failed to remove temporary sync layer.");
367                 return 0;
368         }
369
370         lv->status &= ~CONVERTING;
371
372         log_very_verbose("Updating logical volume \"%s\" on disk(s)", lv->name);
373
374         if (!vg_write(vg))
375                 return_0;
376
377         if (!suspend_lv(cmd, lv)) {
378                 log_error("Failed to lock %s", lv->name);
379                 vg_revert(vg);
380                 goto out;
381         }
382
383         if (!vg_commit(vg)) {
384                 resume_lv(cmd, lv);
385                 goto_out;
386         }
387
388         log_very_verbose("Updating \"%s\" in kernel", lv->name);
389
390         if (!resume_lv(cmd, lv)) {
391                 log_error("Problem reactivating %s", lv->name);
392                 goto out;
393         }
394
395         r = 1;
396         log_print("Logical volume %s converted.", lv->name);
397 out:
398         backup(vg);
399         return r;
400 }
401
402 static int _finish_lvconvert_merge(struct cmd_context *cmd,
403                                    struct volume_group *vg,
404                                    struct logical_volume *lv,
405                                    struct dm_list *lvs_changed __attribute__((unused)))
406 {
407         struct lv_segment *snap_seg = find_merging_cow(lv);
408         if (!snap_seg) {
409                 log_error("Logical volume %s has no merging snapshot.", lv->name);
410                 return 0;
411         }
412
413         log_print("Merge of snapshot into logical volume %s has finished.", lv->name);
414         if (!lv_remove_single(cmd, snap_seg->cow, DONT_PROMPT)) {
415                 log_error("Could not remove snapshot %s merged into %s.",
416                           snap_seg->cow->name, lv->name);
417                 return 0;
418         }
419
420         return 1;
421 }
422
423 static progress_t _poll_merge_progress(struct cmd_context *cmd,
424                                        struct logical_volume *lv,
425                                        const char *name __attribute__((unused)),
426                                        struct daemon_parms *parms)
427 {
428         percent_t percent = PERCENT_0;
429
430         if (!lv_snapshot_percent(lv, &percent)) {
431                 log_error("%s: Failed query for merging percentage. Aborting merge.", lv->name);
432                 return PROGRESS_CHECK_FAILED;
433         } else if (percent == PERCENT_INVALID) {
434                 log_error("%s: Merging snapshot invalidated. Aborting merge.", lv->name);
435                 return PROGRESS_CHECK_FAILED;
436         }
437
438         if (parms->progress_display)
439                 log_print("%s: %s: %.1f%%", lv->name, parms->progress_title,
440                           percent_to_float(percent));
441         else
442                 log_verbose("%s: %s: %.1f%%", lv->name, parms->progress_title,
443                             percent_to_float(percent));
444
445         if (percent == PERCENT_0)
446                 return PROGRESS_FINISHED_ALL;
447
448         return PROGRESS_UNFINISHED;
449 }
450
451 static struct poll_functions _lvconvert_mirror_fns = {
452         .get_copy_vg = _get_lvconvert_vg,
453         .get_copy_lv = _get_lvconvert_lv,
454         .poll_progress = poll_mirror_progress,
455         .finish_copy = _finish_lvconvert_mirror,
456 };
457
458 static struct poll_functions _lvconvert_merge_fns = {
459         .get_copy_vg = _get_lvconvert_vg,
460         .get_copy_lv = _get_lvconvert_lv,
461         .poll_progress = _poll_merge_progress,
462         .finish_copy = _finish_lvconvert_merge,
463 };
464
465 int lvconvert_poll(struct cmd_context *cmd, struct logical_volume *lv,
466                    unsigned background)
467 {
468         /*
469          * FIXME allocate an "object key" structure with split
470          * out members (vg_name, lv_name, uuid, etc) and pass that
471          * around the lvconvert and polldaemon code
472          * - will avoid needless work, e.g. extract_vgname()
473          * - unfortunately there are enough overloaded "name" dragons in
474          *   the polldaemon, lvconvert, pvmove code that a comprehensive
475          *   audit/rework is needed
476          */
477         int len = strlen(lv->vg->name) + strlen(lv->name) + 2;
478         char *uuid = alloca(sizeof(lv->lvid));
479         char *lv_full_name = alloca(len);
480
481         if (!uuid || !lv_full_name)
482                 return_0;
483
484         if (!dm_snprintf(lv_full_name, len, "%s/%s", lv->vg->name, lv->name))
485                 return_0;
486
487         memcpy(uuid, &lv->lvid, sizeof(lv->lvid));
488
489         if (!lv_is_merging_origin(lv))
490                 return poll_daemon(cmd, lv_full_name, uuid, background, 0,
491                                    &_lvconvert_mirror_fns, "Converted");
492         else
493                 return poll_daemon(cmd, lv_full_name, uuid, background, 0,
494                                    &_lvconvert_merge_fns, "Merged");
495 }
496
497 static int _insert_lvconvert_layer(struct cmd_context *cmd,
498                                    struct logical_volume *lv)
499 {
500         char *format, *layer_name;
501         size_t len;
502         int i;
503
504         /*
505          * We would like to give the same number for this layer
506          * and the newly added mimage.
507          * However, LV name of newly added mimage is determined *after*
508          * the LV name of this layer is determined.
509          *
510          * So, use generate_lv_name() to generate mimage name first
511          * and take the number from it.
512          */
513
514         len = strlen(lv->name) + 32;
515         if (!(format = alloca(len)) ||
516             !(layer_name = alloca(len)) ||
517             dm_snprintf(format, len, "%s_mimage_%%d", lv->name) < 0) {
518                 log_error("lvconvert: layer name allocation failed.");
519                 return 0;
520         }
521
522         if (!generate_lv_name(lv->vg, format, layer_name, len) ||
523             sscanf(layer_name, format, &i) != 1) {
524                 log_error("lvconvert: layer name generation failed.");
525                 return 0;
526         }
527
528         if (dm_snprintf(layer_name, len, MIRROR_SYNC_LAYER "_%d", i) < 0) {
529                 log_error("layer name allocation failed.");
530                 return 0;
531         }
532
533         if (!insert_layer_for_lv(cmd, lv, 0, layer_name)) {
534                 log_error("Failed to insert resync layer");
535                 return 0;
536         }
537
538         return 1;
539 }
540
541 static int _area_missing(struct lv_segment *lvseg, int s)
542 {
543         if (seg_type(lvseg, s) == AREA_LV) {
544                 if (seg_lv(lvseg, s)->status & PARTIAL_LV)
545                         return 1;
546         } else if ((seg_type(lvseg, s) == AREA_PV) &&
547                    (is_missing_pv(seg_pv(lvseg, s))))
548                 return 1;
549
550         return 0;
551 }
552
553 /* FIXME we want to handle mirror stacks here... */
554 static int _failed_mirrors_count(struct logical_volume *lv)
555 {
556         struct lv_segment *lvseg;
557         int ret = 0;
558         int s;
559
560         dm_list_iterate_items(lvseg, &lv->segments) {
561                 if (!seg_is_mirrored(lvseg))
562                         return -1;
563                 for (s = 0; s < lvseg->area_count; s++)
564                         if (_area_missing(lvseg, s))
565                                 ret++;
566         }
567
568         return ret;
569 }
570
571 static struct dm_list *_failed_pv_list(struct volume_group *vg)
572 {
573         struct dm_list *failed_pvs;
574         struct pv_list *pvl, *new_pvl;
575
576         if (!(failed_pvs = dm_pool_alloc(vg->vgmem, sizeof(*failed_pvs)))) {
577                 log_error("Allocation of list of failed_pvs failed.");
578                 return_NULL;
579         }
580
581         dm_list_init(failed_pvs);
582
583         dm_list_iterate_items(pvl, &vg->pvs) {
584                 if (!is_missing_pv(pvl->pv))
585                         continue;
586
587                 /* 
588                  * Finally, --repair will remove empty PVs.
589                  * But we only want remove these which are output of repair,
590                  * Do not count these which are already empty here.
591                  * FIXME: code should traverse PV in LV not in whole VG.
592                  * FIXME: layer violation? should it depend on vgreduce --removemising?
593                  */
594                 if (pvl->pv->pe_alloc_count == 0)
595                         continue;
596
597                 if (!(new_pvl = dm_pool_alloc(vg->vgmem, sizeof(*new_pvl)))) {
598                         log_error("Allocation of failed_pvs list entry failed.");
599                         return_NULL;
600                 }
601                 new_pvl->pv = pvl->pv;
602                 dm_list_add(failed_pvs, &new_pvl->list);
603         }
604
605         return failed_pvs;
606 }
607
608 static int _is_partial_lv(struct logical_volume *lv,
609                           void *baton __attribute__((unused)))
610 {
611         return lv->status & PARTIAL_LV;
612 }
613
614 /*
615  * Walk down the stacked mirror LV to the original mirror LV.
616  */
617 static struct logical_volume *_original_lv(struct logical_volume *lv)
618 {
619         struct logical_volume *next_lv = lv, *tmp_lv;
620
621         while ((tmp_lv = find_temporary_mirror(next_lv)))
622                 next_lv = tmp_lv;
623
624         return next_lv;
625 }
626
627 static void _lvconvert_mirrors_repair_ask(struct cmd_context *cmd,
628                                           int failed_log, int failed_mirrors,
629                                           int *replace_log, int *replace_mirrors)
630 {
631         const char *leg_policy = NULL, *log_policy = NULL;
632
633         int force = arg_count(cmd, force_ARG);
634         int yes = arg_count(cmd, yes_ARG);
635
636         *replace_log = *replace_mirrors = 1;
637
638         if (arg_count(cmd, use_policies_ARG)) {
639                 leg_policy = find_config_tree_str(cmd,
640                                         "activation/mirror_image_fault_policy", NULL);
641                 if (!leg_policy)
642                         leg_policy = find_config_tree_str(cmd,
643                                         "activation/mirror_device_fault_policy",
644                                         DEFAULT_MIRROR_DEVICE_FAULT_POLICY);
645                 log_policy = find_config_tree_str(cmd,
646                                         "activation/mirror_log_fault_policy",
647                                         DEFAULT_MIRROR_LOG_FAULT_POLICY);
648                 *replace_mirrors = strcmp(leg_policy, "remove");
649                 *replace_log = strcmp(log_policy, "remove");
650                 return;
651         }
652
653         if (yes)
654                 return;
655
656         if (force != PROMPT) {
657                 *replace_log = *replace_mirrors = 0;
658                 return;
659         }
660
661         if (failed_log &&
662             yes_no_prompt("Attempt to replace failed mirror log? [y/n]: ") == 'n') {
663                 *replace_log = 0;
664         }
665
666         if (failed_mirrors &&
667             yes_no_prompt("Attempt to replace failed mirror images "
668                           "(requires full device resync)? [y/n]: ") == 'n') {
669                 *replace_mirrors = 0;
670         }
671 }
672
673 /*
674  * _get_log_count
675  * @lv: the mirror LV
676  *
677  * Get the number of on-disk copies of the log.
678  *  0  = 'core'
679  *  1  = 'disk'
680  *  2+ = 'mirrored'
681  */
682 static int _get_log_count(struct logical_volume *lv)
683 {
684         struct logical_volume *log_lv;
685
686         log_lv = first_seg(_original_lv(lv))->log_lv;
687         if (!log_lv)
688                 return 0;
689
690         return lv_mirror_count(log_lv);
691 }
692
693 static int _lv_update_mirrored_log(struct logical_volume *lv,
694                                    struct dm_list *operable_pvs,
695                                    int log_count)
696 {
697         int old_log_count;
698         struct logical_volume *log_lv;
699
700         /*
701          * When log_count is 0, mirrored log doesn't need to be
702          * updated here but it will be removed later.
703          */
704         if (!log_count)
705                 return 1;
706
707         log_lv = first_seg(_original_lv(lv))->log_lv;
708         if (!log_lv || !(log_lv->status & MIRRORED))
709                 return 1;
710
711         old_log_count = _get_log_count(lv);
712         if (old_log_count == log_count)
713                 return 1;
714
715         /* Reducing redundancy of the log */
716         return remove_mirror_images(log_lv, log_count,
717                                     is_mirror_image_removable,
718                                     operable_pvs, 0U);
719 }
720
721 static int _lv_update_log_type(struct cmd_context *cmd,
722                                struct lvconvert_params *lp,
723                                struct logical_volume *lv,
724                                struct dm_list *operable_pvs,
725                                int log_count)
726 {
727         uint32_t region_size;
728         int old_log_count;
729         struct logical_volume *original_lv;
730         struct logical_volume *log_lv;
731
732         old_log_count = _get_log_count(lv);
733         if (old_log_count == log_count)
734                 return 1;
735
736         original_lv = _original_lv(lv);
737         region_size = adjusted_mirror_region_size(lv->vg->extent_size,
738                                                   lv->le_count,
739                                                   lp->region_size);
740
741         /* Add a log where there is none */
742         if (!old_log_count) {
743                 if (!add_mirror_log(cmd, original_lv, log_count,
744                                     region_size, operable_pvs, lp->alloc))
745                         return_0;
746                 return 1;
747         }
748
749         /* Remove an existing log completely */
750         if (!log_count) {
751                 if (!remove_mirror_log(cmd, original_lv, operable_pvs,
752                                        arg_count(cmd, yes_ARG) ||
753                                        arg_count(cmd, force_ARG)))
754                         return_0;
755                 return 1;
756         }
757
758         log_lv = first_seg(original_lv)->log_lv;
759
760         /* Adding redundancy to the log */
761         if (old_log_count < log_count) {
762                 log_error("Adding log redundancy not supported yet.");
763                 log_error("Try converting the log to 'core' first.");
764                 return_0;
765         }
766
767         /* Reducing redundancy of the log */
768         return remove_mirror_images(log_lv, log_count, is_mirror_image_removable, operable_pvs, 1U);
769 }
770
771 /*
772  * Reomove missing and empty PVs from VG, if are also in provided list
773  */
774 static void _remove_missing_empty_pv(struct volume_group *vg, struct dm_list *remove_pvs)
775 {
776         struct pv_list *pvl, *pvl_vg, *pvlt;
777         int removed = 0;
778
779         if (!remove_pvs)
780                 return;
781
782         dm_list_iterate_items(pvl, remove_pvs) {
783                 dm_list_iterate_items_safe(pvl_vg, pvlt, &vg->pvs) {
784                         if (!id_equal(&pvl->pv->id, &pvl_vg->pv->id) ||
785                             !is_missing_pv(pvl_vg->pv) ||
786                             pvl_vg->pv->pe_alloc_count != 0)
787                                 continue;
788
789                         /* FIXME: duplication of vgreduce code, move this to library */
790                         vg->free_count -= pvl_vg->pv->pe_count;
791                         vg->extent_count -= pvl_vg->pv->pe_count;
792                         del_pvl_from_vgs(vg, pvl_vg);
793
794                         removed++;
795                 }
796         }
797
798         if (removed) {
799                 if (!vg_write(vg) || !vg_commit(vg)) {
800                         stack;
801                         return;
802                 }
803                 log_warn("%d missing and now unallocated Physical Volumes removed from VG.", removed);
804         }
805 }
806
807 /*
808  * _lvconvert_mirrors_parse_params
809  *
810  * This function performs the following:
811  *  1) Gets the old values of mimage and log counts
812  *  2) Parses the CLI args to find the new desired values
813  *  3) Adjusts 'lp->mirrors' to the appropriate absolute value.
814  *     (Remember, 'lp->mirrors' is specified in terms of the number of "copies"
815  *      vs. the number of mimages.  It can also be a relative value.)
816  *  4) Sets 'lp->need_polling' if collapsing
817  *  5) Validates other mirror params
818  *
819  * Returns: 1 on success, 0 on error
820  */
821 static int _lvconvert_mirrors_parse_params(struct cmd_context *cmd,
822                                            struct logical_volume *lv,
823                                            struct lvconvert_params *lp,
824                                            uint32_t *old_mimage_count,
825                                            uint32_t *old_log_count,
826                                            uint32_t *new_mimage_count,
827                                            uint32_t *new_log_count)
828 {
829         int repair = arg_count(cmd, repair_ARG);
830         const char *mirrorlog;
831         *old_mimage_count = lv_mirror_count(lv);
832         *old_log_count = _get_log_count(lv);
833
834         /*
835          * Collapsing a stack of mirrors:
836          *
837          * If called with no argument, try collapsing the resync layers
838          */
839         if (!arg_count(cmd, mirrors_ARG) && !arg_count(cmd, mirrorlog_ARG) &&
840             !arg_count(cmd, corelog_ARG) && !arg_count(cmd, regionsize_ARG) &&
841             !arg_count(cmd, splitmirrors_ARG) && !repair) {
842                 *new_mimage_count = *old_mimage_count;
843                 *new_log_count = *old_log_count;
844
845                 if (find_temporary_mirror(lv) || (lv->status & CONVERTING))
846                         lp->need_polling = 1;
847                 return 1;
848         }
849
850         if ((arg_count(cmd, mirrors_ARG) && repair) ||
851             (arg_count(cmd, mirrorlog_ARG) && repair) ||
852             (arg_count(cmd, corelog_ARG) && repair)) {
853                 log_error("--repair cannot be used with --mirrors, --mirrorlog,"
854                           " or --corelog");
855                 return 0;
856         }
857
858         if (arg_count(cmd, mirrorlog_ARG) && arg_count(cmd, corelog_ARG)) {
859                 log_error("--mirrorlog and --corelog are incompatible");
860                 return 0;
861         }
862
863         /*
864          * Adjusting mimage count?
865          */
866         if (!arg_count(cmd, mirrors_ARG) && !arg_count(cmd, splitmirrors_ARG))
867                 lp->mirrors = *old_mimage_count;
868         else if (lp->mirrors_sign == SIGN_PLUS)
869                 lp->mirrors = *old_mimage_count + lp->mirrors;
870         else if (lp->mirrors_sign == SIGN_MINUS)
871                 lp->mirrors = (*old_mimage_count > lp->mirrors) ?
872                         *old_mimage_count - lp->mirrors: 0;
873         else
874                 lp->mirrors += 1;
875
876         *new_mimage_count = lp->mirrors;
877
878         /* Too many mimages? */
879         if (lp->mirrors > DEFAULT_MIRROR_MAX_IMAGES) {
880                 log_error("Only up to %d images in mirror supported currently.",
881                           DEFAULT_MIRROR_MAX_IMAGES);
882                 return 0;
883         }
884
885         /* Did the user try to subtract more legs than available? */
886         if (lp->mirrors < 1) {
887                 log_error("Unable to reduce images by specified amount - only %d in %s",
888                           *old_mimage_count, lv->name);
889                 return 0;
890         }
891
892         /*
893          * FIXME: It would be nice to say what we are adjusting to, but
894          * I really don't know whether to specify the # of copies or mimages.
895          */
896         if (*old_mimage_count != *new_mimage_count)
897                 log_verbose("Adjusting mirror image count of %s", lv->name);
898
899         /*
900          * Adjust log type
901          *
902          * If we are converting from a mirror to another mirror or simply
903          * changing the log type, we start by assuming they want the log
904          * type the same and then parse the given args.  OTOH, If we are
905          * converting from linear to mirror, then we start from the default
906          * position that the user would like a 'disk' log.
907          */
908         *new_log_count = (*old_mimage_count > 1) ? *old_log_count : 1;
909         if (!arg_count(cmd, corelog_ARG) && !arg_count(cmd, mirrorlog_ARG))
910                 return 1;
911
912         if (arg_count(cmd, corelog_ARG))
913                 *new_log_count = 0;
914
915         mirrorlog = arg_str_value(cmd, mirrorlog_ARG,
916                                   !*new_log_count ? "core" : DEFAULT_MIRRORLOG);
917
918         if (!strcmp("mirrored", mirrorlog))
919                 *new_log_count = 2;
920         else if (!strcmp("disk", mirrorlog))
921                 *new_log_count = 1;
922         else if (!strcmp("core", mirrorlog))
923                 *new_log_count = 0;
924         else {
925                 log_error("Unknown mirrorlog type: %s", mirrorlog);
926                 return 0;
927         }
928
929         /*
930          * No mirrored logs for cluster mirrors until
931          * log daemon is multi-threaded.
932          */
933         if ((*new_log_count == 2) && vg_is_clustered(lv->vg)) {
934                 log_error("Log type, \"mirrored\", is unavailable to cluster mirrors");
935                 return 0;
936         }
937
938         log_verbose("Setting logging type to %s", mirrorlog);
939
940         /*
941          * Region size must not change on existing mirrors
942          */
943         if (arg_count(cmd, regionsize_ARG) && (lv->status & MIRRORED) &&
944             (lp->region_size != first_seg(lv)->region_size)) {
945                 log_error("Mirror log region size cannot be changed on "
946                           "an existing mirror.");
947                 return 0;
948         }
949
950         /*
951          * For the most part, we cannot handle multi-segment mirrors. Bail out
952          * early if we have encountered one.
953          */
954         if ((lv->status & MIRRORED) && dm_list_size(&lv->segments) != 1) {
955                 log_error("Logical volume %s has multiple "
956                           "mirror segments.", lv->name);
957                 return 0;
958         }
959
960         return 1;
961 }
962
963 static int _reload_lv(struct cmd_context *cmd, struct logical_volume *lv)
964 {
965         log_very_verbose("Updating logical volume \"%s\" on disk(s)", lv->name);
966
967         if (!vg_write(lv->vg))
968                 return_0;
969
970         if (!suspend_lv(cmd, lv)) {
971                 log_error("Failed to lock %s", lv->name);
972                 vg_revert(lv->vg);
973                 return 0;
974         }
975
976         if (!vg_commit(lv->vg)) {
977                 if (!resume_lv(cmd, lv))
978                         stack;
979                 return_0;
980         }
981
982         log_very_verbose("Updating \"%s\" in kernel", lv->name);
983
984         if (!resume_lv(cmd, lv)) {
985                 log_error("Problem reactivating %s", lv->name);
986                 return 0;
987         }
988         return 1;
989 }
990
991 /*
992  * _lvconvert_mirrors_aux
993  *
994  * Add/remove mirror images and adjust log type.  'operable_pvs'
995  * are the set of PVs open to removal or allocation - depending
996  * on the operation being performed.
997  */
998 static int _lvconvert_mirrors_aux(struct cmd_context *cmd,
999                                   struct logical_volume *lv,
1000                                   struct lvconvert_params *lp,
1001                                   struct dm_list *operable_pvs,
1002                                   uint32_t new_mimage_count,
1003                                   uint32_t new_log_count)
1004 {
1005         uint32_t region_size;
1006         struct lv_segment *seg;
1007         struct logical_volume *layer_lv;
1008         uint32_t old_mimage_count = lv_mirror_count(lv);
1009         uint32_t old_log_count = _get_log_count(lv);
1010
1011         if ((lp->mirrors == 1) && !(lv->status & MIRRORED)) {
1012                 log_error("Logical volume %s is already not mirrored.",
1013                           lv->name);
1014                 return 1;
1015         }
1016
1017         region_size = adjusted_mirror_region_size(lv->vg->extent_size,
1018                                                   lv->le_count,
1019                                                   lp->region_size);
1020
1021         if (!operable_pvs)
1022                 operable_pvs = lp->pvh;
1023
1024         seg = first_seg(lv);
1025
1026         /*
1027          * Up-convert from linear to mirror
1028          */
1029         if (!(lv->status & MIRRORED)) {
1030                 /* FIXME Share code with lvcreate */
1031
1032                 /*
1033                  * FIXME should we give not only lp->pvh, but also all PVs
1034                  * currently taken by the mirror? Would make more sense from
1035                  * user perspective.
1036                  */
1037                 if (!lv_add_mirrors(cmd, lv, new_mimage_count - 1, lp->stripes,
1038                                     lp->stripe_size, region_size, new_log_count, operable_pvs,
1039                                     lp->alloc, MIRROR_BY_LV)) {
1040                         stack;
1041                         return 0;
1042                 }
1043                 if (lp->wait_completion)
1044                         lp->need_polling = 1;
1045
1046                 goto out;
1047         }
1048
1049         /*
1050          * Up-convert m-way mirror to n-way mirror
1051          */
1052         if (new_mimage_count > old_mimage_count) {
1053                 if (lv->status & MIRROR_NOTSYNCED) {
1054                         log_error("Can't add mirror to out-of-sync mirrored "
1055                                   "LV: use lvchange --resync first.");
1056                         return 0;
1057                 }
1058
1059                 /*
1060                  * We allow snapshots of mirrors, but for now, we
1061                  * do not allow up converting mirrors that are under
1062                  * snapshots.  The layering logic is somewhat complex,
1063                  * and preliminary test show that the conversion can't
1064                  * seem to get the correct %'age of completion.
1065                  */
1066                 if (lv_is_origin(lv)) {
1067                         log_error("Can't add additional mirror images to "
1068                                   "mirrors that are under snapshots");
1069                         return 0;
1070                 }
1071
1072                 /*
1073                  * Is there already a convert in progress?  We do not
1074                  * currently allow more than one.
1075                  */
1076                 if (find_temporary_mirror(lv) || (lv->status & CONVERTING)) {
1077                         log_error("%s is already being converted.  Unable to start another conversion.",
1078                                   lv->name);
1079                         return 0;
1080                 }
1081
1082                 /*
1083                  * Is there already a convert in progress?  We do not
1084                  * currently allow more than one.
1085                  */
1086                 if (find_temporary_mirror(lv) || (lv->status & CONVERTING)) {
1087                         log_error("%s is already being converted.  Unable to start another conversion.",
1088                                   lv->name);
1089                         return 0;
1090                 }
1091
1092                 /*
1093                  * Log addition/removal should be done before the layer
1094                  * insertion to make the end result consistent with
1095                  * linear-to-mirror conversion.
1096                  */
1097                 if (!_lv_update_log_type(cmd, lp, lv,
1098                                          operable_pvs, new_log_count)) {
1099                         stack;
1100                         return 0;
1101                 }
1102
1103                 /* Insert a temporary layer for syncing,
1104                  * only if the original lv is using disk log. */
1105                 if (seg->log_lv && !_insert_lvconvert_layer(cmd, lv)) {
1106                         log_error("Failed to insert resync layer");
1107                         return 0;
1108                 }
1109
1110                 /* FIXME: can't have multiple mlogs. force corelog. */
1111                 if (!lv_add_mirrors(cmd, lv,
1112                                     new_mimage_count - old_mimage_count, lp->stripes, lp->stripe_size,
1113                                     region_size, 0U, operable_pvs, lp->alloc,
1114                                     MIRROR_BY_LV)) {
1115                         layer_lv = seg_lv(first_seg(lv), 0);
1116                         if (!remove_layer_from_lv(lv, layer_lv) ||
1117                             !deactivate_lv(cmd, layer_lv) ||
1118                             !lv_remove(layer_lv) || !vg_write(lv->vg) ||
1119                             !vg_commit(lv->vg)) {
1120                                 log_error("ABORTING: Failed to remove "
1121                                           "temporary mirror layer %s.",
1122                                           layer_lv->name);
1123                                 log_error("Manual cleanup with vgcfgrestore "
1124                                           "and dmsetup may be required.");
1125                                 return 0;
1126                         }
1127                         stack;
1128                         return 0;
1129                 }
1130                 if (seg->log_lv)
1131                         lv->status |= CONVERTING;
1132                 lp->need_polling = 1;
1133
1134                 goto out_skip_log_convert;
1135         }
1136
1137         /*
1138          * Down-convert (reduce # of mimages).
1139          */
1140         if (new_mimage_count < old_mimage_count) {
1141                 uint32_t nmc = old_mimage_count - new_mimage_count;
1142                 uint32_t nlc = (!new_log_count || lp->mirrors == 1) ? 1U : 0U;
1143
1144                 /* FIXME: Why did nlc used to be calculated that way? */
1145
1146                 /* Reduce number of mirrors */
1147                 if (lp->keep_mimages) {
1148                         if (!lv_split_mirror_images(lv, lp->lv_split_name,
1149                                                     nmc, operable_pvs))
1150                                 return 0;
1151                 } else if (!lv_remove_mirrors(cmd, lv, nmc, nlc,
1152                                               is_mirror_image_removable, operable_pvs, 0))
1153                         return_0;
1154
1155                 goto out; /* Just in case someone puts code between */
1156         }
1157
1158 out:
1159         /*
1160          * Converting the log type
1161          */
1162         if ((lv->status & MIRRORED) && (old_log_count != new_log_count)) {
1163                 if (!_lv_update_log_type(cmd, lp, lv,
1164                                          operable_pvs, new_log_count)) {
1165                         stack;
1166                         return 0;
1167                 }
1168         }
1169
1170 out_skip_log_convert:
1171
1172         if (!_reload_lv(cmd, lv))
1173                 return 0;
1174
1175         return 1;
1176 }
1177
1178 /*
1179  * _lvconvert_mirrors_repair
1180  *
1181  * This function operates in two phases.  First, all of the bad
1182  * devices are removed from the mirror.  Then, if desired by the
1183  * user, the devices are replaced.
1184  *
1185  * 'old_mimage_count' and 'old_log_count' are there so we know
1186  * what to convert to after the removal of devices.
1187  */
1188 static int _lvconvert_mirrors_repair(struct cmd_context *cmd,
1189                                      struct logical_volume *lv,
1190                                      struct lvconvert_params *lp,
1191                                      uint32_t old_mimage_count,
1192                                      uint32_t old_log_count)
1193 {
1194         int failed_log = 0;
1195         int failed_mirrors = 0;
1196         int replace_log = 0;
1197         int replace_mirrors = 0;
1198         uint32_t new_log_count, log_count;
1199         struct logical_volume *log_lv;
1200
1201         cmd->handles_missing_pvs = 1;
1202         cmd->partial_activation = 1;
1203         lp->need_polling = 0;
1204
1205         lv_check_transient(lv); /* TODO check this in lib for all commands? */
1206
1207         if (!(lv->status & PARTIAL_LV)) {
1208                 log_error("%s is consistent. Nothing to repair.", lv->name);
1209                 return 1;
1210         }
1211
1212         /*
1213          * Count the failed mimages - negative if 'lv' is not a mirror
1214          */
1215         if ((failed_mirrors = _failed_mirrors_count(lv)) < 0)
1216                 return_0;
1217
1218         lp->mirrors = old_mimage_count - failed_mirrors;
1219
1220         if (lp->mirrors != old_mimage_count)
1221                 log_error("Mirror status: %d of %d images failed.",
1222                           failed_mirrors, old_mimage_count);
1223
1224         /*
1225          * Count the failed log devices
1226          */
1227         new_log_count = old_log_count;
1228         log_lv = first_seg(lv)->log_lv;
1229         if (log_lv) {
1230                 new_log_count = lv_mirror_count(log_lv);
1231                 if (log_lv->status & PARTIAL_LV) {
1232                         failed_log = 1;
1233                         if (log_lv->status & MIRRORED)
1234                                 new_log_count -= _failed_mirrors_count(log_lv);
1235                         else
1236                                 new_log_count = 0;
1237                 }
1238         }
1239         if (old_log_count != new_log_count)
1240                 log_error("Mirror log status: %d of %d images failed%s",
1241                           old_log_count - new_log_count, old_log_count,
1242                           (!new_log_count) ? " - switching to core" : "");
1243
1244         /*
1245          * Find out our policies
1246          */
1247         _lvconvert_mirrors_repair_ask(cmd, failed_log, failed_mirrors,
1248                                       &replace_log, &replace_mirrors);
1249
1250         /*
1251          * First phase - remove faulty devices
1252          */
1253         if (!(lp->failed_pvs = _failed_pv_list(lv->vg)))
1254                 return_0;
1255
1256         log_count = new_log_count;
1257
1258         /*
1259          * We must adjust the log first, or the entire mirror
1260          * will get stuck during a suspend.
1261          */
1262         if (!_lv_update_mirrored_log(lv, lp->failed_pvs, log_count))
1263                 return 0;
1264
1265         if (lp->mirrors == 1)
1266                 log_count = 0;
1267
1268         if (failed_mirrors) {
1269                 if (!lv_remove_mirrors(cmd, lv, failed_mirrors,
1270                                        log_count ? 0U : 1U,
1271                                        _is_partial_lv, NULL, 0))
1272                         return 0;
1273         }
1274
1275         if (!_lv_update_log_type(cmd, lp, lv, lp->failed_pvs,
1276                                  log_count))
1277                 return 0;
1278
1279         if (!_reload_lv(cmd, lv))
1280                 return 0;
1281
1282         /*
1283          * Second phase - replace faulty devices
1284          */
1285
1286         if (replace_mirrors)
1287                 lp->mirrors = old_mimage_count;
1288
1289         /*
1290          * It does not make sense to replace the log if the volume is no longer
1291          * a mirror.
1292          */
1293         if (!replace_mirrors && lp->mirrors == 1)
1294                 replace_log = 0;
1295
1296         log_count = replace_log ? old_log_count : new_log_count;
1297
1298         while (replace_mirrors || replace_log) {
1299                 log_warn("Trying to up-convert to %d images, %d logs.", lp->mirrors, log_count);
1300                 if (_lvconvert_mirrors_aux(cmd, lv, lp, NULL,
1301                                            lp->mirrors, log_count))
1302                         break;
1303                 else {
1304                         if (lp->mirrors > 2)
1305                                 -- lp->mirrors;
1306                         else if (log_count > 0)
1307                                 -- log_count;
1308                         else
1309                                 break; /* nowhere to go, anymore... */
1310                 }
1311         }
1312
1313         if (replace_mirrors && lp->mirrors != old_mimage_count)
1314                 log_warn("WARNING: Failed to replace %d of %d images in volume %s",
1315                          old_mimage_count - lp->mirrors, old_mimage_count, lv->name);
1316         if (replace_log && log_count != old_log_count)
1317                 log_warn("WARNING: Failed to replace %d of %d logs in volume %s",
1318                          old_log_count - log_count, old_log_count, lv->name);
1319
1320         /* if (!arg_count(cmd, use_policies_ARG) && (lp->mirrors != old_mimage_count
1321                                                   || log_count != old_log_count))
1322                                                   return 0; */
1323
1324         return 1;
1325 }
1326
1327 /*
1328  * _lvconvert_mirrors
1329  *
1330  * Determine what is being done.  Are we doing a conversion, repair, or
1331  * collapsing a stack?  Once determined, call helper functions.
1332  */
1333 static int _lvconvert_mirrors(struct cmd_context *cmd,
1334                               struct logical_volume *lv,
1335                               struct lvconvert_params *lp)
1336 {
1337         int repair = arg_count(cmd, repair_ARG);
1338         uint32_t old_mimage_count;
1339         uint32_t old_log_count;
1340         uint32_t new_mimage_count;
1341         uint32_t new_log_count;
1342
1343         /* Adjust mimage and/or log count */
1344         if (!_lvconvert_mirrors_parse_params(cmd, lv, lp,
1345                                              &old_mimage_count, &old_log_count,
1346                                              &new_mimage_count, &new_log_count))
1347                 return 0;
1348
1349         if (((old_mimage_count < new_mimage_count && old_log_count > new_log_count) ||
1350              (old_mimage_count > new_mimage_count && old_log_count < new_log_count)) &&
1351             lp->pv_count) {
1352                 log_error("Cannot both allocate and free extents when specifying physical"
1353                           " volumes to use.");
1354                 log_error("Please specify the operation in two steps.");
1355                 return 0;
1356         }
1357
1358         /* Nothing to do?  (Probably finishing collapse.) */
1359         if ((old_mimage_count == new_mimage_count) &&
1360             (old_log_count == new_log_count) && !repair)
1361                 return 1;
1362
1363         if (repair)
1364                 return _lvconvert_mirrors_repair(cmd, lv, lp,
1365                                                  old_mimage_count,
1366                                                  old_log_count);
1367
1368         if (!_lvconvert_mirrors_aux(cmd, lv, lp, NULL,
1369                                     new_mimage_count, new_log_count))
1370                 return 0;
1371
1372         if (!lp->need_polling)
1373                 log_print("Logical volume %s converted.", lv->name);
1374
1375         backup(lv->vg);
1376         return 1;
1377 }
1378
1379 static int lvconvert_snapshot(struct cmd_context *cmd,
1380                               struct logical_volume *lv,
1381                               struct lvconvert_params *lp)
1382 {
1383         struct logical_volume *org;
1384         int r = 0;
1385
1386         if (!(org = find_lv(lv->vg, lp->origin))) {
1387                 log_error("Couldn't find origin volume '%s'.", lp->origin);
1388                 return 0;
1389         }
1390
1391         if (org == lv) {
1392                 log_error("Unable to use \"%s\" as both snapshot and origin.",
1393                           lv->name);
1394                 return 0;
1395         }
1396
1397         if (org->status & (LOCKED|PVMOVE|MIRRORED) || lv_is_cow(org)) {
1398                 log_error("Unable to create a snapshot of a %s LV.",
1399                           org->status & LOCKED ? "locked" :
1400                           org->status & PVMOVE ? "pvmove" :
1401                           org->status & MIRRORED ? "mirrored" :
1402                           "snapshot");
1403                 return 0;
1404         }
1405
1406         if (!lp->zero || !(lv->status & LVM_WRITE))
1407                 log_warn("WARNING: \"%s\" not zeroed", lv->name);
1408         else if (!set_lv(cmd, lv, UINT64_C(0), 0)) {
1409                 log_error("Aborting. Failed to wipe snapshot "
1410                           "exception store.");
1411                 return 0;
1412         }
1413
1414         if (!deactivate_lv(cmd, lv)) {
1415                 log_error("Couldn't deactivate LV %s.", lv->name);
1416                 return 0;
1417         }
1418
1419         if (!vg_add_snapshot(org, lv, NULL, org->le_count, lp->chunk_size)) {
1420                 log_error("Couldn't create snapshot.");
1421                 return 0;
1422         }
1423
1424         /* store vg on disk(s) */
1425         if (!vg_write(lv->vg))
1426                 return_0;
1427
1428         if (!suspend_lv(cmd, org)) {
1429                 log_error("Failed to suspend origin %s", org->name);
1430                 vg_revert(lv->vg);
1431                 goto out;
1432         }
1433
1434         if (!vg_commit(lv->vg))
1435                 goto_out;
1436
1437         if (!resume_lv(cmd, org)) {
1438                 log_error("Problem reactivating origin %s", org->name);
1439                 goto out;
1440         }
1441
1442         log_print("Logical volume %s converted to snapshot.", lv->name);
1443         r = 1;
1444 out:
1445         backup(lv->vg);
1446         return r;
1447 }
1448
1449 static int lvconvert_merge(struct cmd_context *cmd,
1450                            struct logical_volume *lv,
1451                            struct lvconvert_params *lp)
1452 {
1453         int r = 0;
1454         int merge_on_activate = 0;
1455         struct logical_volume *origin = origin_from_cow(lv);
1456         struct lv_segment *cow_seg = find_cow(lv);
1457         struct lvinfo info;
1458
1459         /* Check if merge is possible */
1460         if (lv_is_merging_cow(lv)) {
1461                 log_error("Snapshot %s is already merging", lv->name);
1462                 return 0;
1463         }
1464         if (lv_is_merging_origin(origin)) {
1465                 log_error("Snapshot %s is already merging into the origin",
1466                           find_merging_cow(origin)->cow->name);
1467                 return 0;
1468         }
1469
1470         /*
1471          * Prevent merge with open device(s) as it would likely lead
1472          * to application/filesystem failure.  Merge on origin's next
1473          * activation if either the origin or snapshot LV are currently
1474          * open.
1475          *
1476          * FIXME testing open_count is racey; snapshot-merge target's
1477          * constructor and DM should prevent appropriate devices from
1478          * being open.
1479          */
1480         if (lv_info(cmd, origin, 0, &info, 1, 0)) {
1481                 if (info.open_count) {
1482                         log_error("Can't merge over open origin volume");
1483                         merge_on_activate = 1;
1484                 }
1485         }
1486         if (lv_info(cmd, lv, 0, &info, 1, 0)) {
1487                 if (info.open_count) {
1488                         log_print("Can't merge when snapshot is open");
1489                         merge_on_activate = 1;
1490                 }
1491         }
1492
1493         init_snapshot_merge(cow_seg, origin);
1494
1495         /* store vg on disk(s) */
1496         if (!vg_write(lv->vg))
1497                 return_0;
1498
1499         if (merge_on_activate) {
1500                 /* commit vg but skip starting the merge */
1501                 if (!vg_commit(lv->vg))
1502                         return_0;
1503                 r = 1;
1504                 log_print("Merging of snapshot %s will start "
1505                           "next activation.", lv->name);
1506                 goto out;
1507         }
1508
1509         /* Perform merge */
1510         if (!suspend_lv(cmd, origin)) {
1511                 log_error("Failed to suspend origin %s", origin->name);
1512                 vg_revert(lv->vg);
1513                 goto out;
1514         }
1515
1516         if (!vg_commit(lv->vg)) {
1517                 if (!resume_lv(cmd, origin))
1518                         stack;
1519                 goto_out;
1520         }
1521
1522         if (!resume_lv(cmd, origin)) {
1523                 log_error("Failed to reactivate origin %s", origin->name);
1524                 goto out;
1525         }
1526
1527         lp->need_polling = 1;
1528         lp->lv_to_poll = origin;
1529
1530         r = 1;
1531         log_print("Merging of volume %s started.", lv->name);
1532 out:
1533         backup(lv->vg);
1534         return r;
1535 }
1536
1537 static int _lvconvert_single(struct cmd_context *cmd, struct logical_volume *lv,
1538                              void *handle)
1539 {
1540         struct lvconvert_params *lp = handle;
1541
1542         if (lv->status & LOCKED) {
1543                 log_error("Cannot convert locked LV %s", lv->name);
1544                 return ECMD_FAILED;
1545         }
1546
1547         if (lv_is_cow(lv) && !lp->merge) {
1548                 log_error("Can't convert snapshot logical volume \"%s\"",
1549                           lv->name);
1550                 return ECMD_FAILED;
1551         }
1552
1553         if (lv->status & PVMOVE) {
1554                 log_error("Unable to convert pvmove LV %s", lv->name);
1555                 return ECMD_FAILED;
1556         }
1557
1558         if (arg_count(cmd, repair_ARG) && !(lv->status & MIRRORED)) {
1559                 if (arg_count(cmd, use_policies_ARG))
1560                         return ECMD_PROCESSED; /* nothing to be done here */
1561                 log_error("Can't repair non-mirrored LV \"%s\".", lv->name);
1562                 return ECMD_FAILED;
1563         }
1564
1565         if (lp->merge) {
1566                 if (!lv_is_cow(lv)) {
1567                         log_error("Logical volume \"%s\" is not a snapshot",
1568                                   lv->name);
1569                         return ECMD_FAILED;
1570                 }
1571                 if (!archive(lv->vg)) {
1572                         stack;
1573                         return ECMD_FAILED;
1574                 }
1575                 if (!lvconvert_merge(cmd, lv, lp)) {
1576                         log_error("Unable to merge LV \"%s\" into its origin.", lv->name);
1577                         return ECMD_FAILED;
1578                 }
1579         } else if (lp->snapshot) {
1580                 if (lv->status & MIRRORED) {
1581                         log_error("Unable to convert mirrored LV \"%s\" into a snapshot.", lv->name);
1582                         return ECMD_FAILED;
1583                 }
1584                 if (!archive(lv->vg)) {
1585                         stack;
1586                         return ECMD_FAILED;
1587                 }
1588                 if (!lvconvert_snapshot(cmd, lv, lp)) {
1589                         stack;
1590                         return ECMD_FAILED;
1591                 }
1592         } else if (arg_count(cmd, mirrors_ARG) ||
1593                    arg_count(cmd, splitmirrors_ARG) ||
1594                    (lv->status & MIRRORED)) {
1595                 if (!archive(lv->vg)) {
1596                         stack;
1597                         return ECMD_FAILED;
1598                 }
1599                 if (!_lvconvert_mirrors(cmd, lv, lp)) {
1600                         stack;
1601                         return ECMD_FAILED;
1602                 }
1603
1604                 /* If repairing and using policies, remove missing PVs from VG */
1605                 if (arg_count(cmd, repair_ARG) && arg_count(cmd, use_policies_ARG))
1606                         _remove_missing_empty_pv(lv->vg, lp->failed_pvs);
1607         }
1608
1609         return ECMD_PROCESSED;
1610 }
1611
1612 /*
1613  * FIXME move to toollib along with the rest of the drop/reacquire
1614  * VG locking that is used by lvconvert_merge_single()
1615  */
1616 static struct logical_volume *get_vg_lock_and_logical_volume(struct cmd_context *cmd,
1617                                                              const char *vg_name,
1618                                                              const char *lv_name)
1619 {
1620         /*
1621          * Returns NULL if the requested LV doesn't exist;
1622          * otherwise the caller must free_vg(lv->vg)
1623          * - it is also up to the caller to unlock_vg() as needed
1624          */
1625         struct volume_group *vg;
1626         struct logical_volume* lv = NULL;
1627
1628         vg = _get_lvconvert_vg(cmd, vg_name, NULL);
1629         if (vg_read_error(vg)) {
1630                 free_vg(vg);
1631                 return_NULL;
1632         }
1633
1634         if (!(lv = _get_lvconvert_lv(cmd, vg, lv_name, NULL, 0))) {
1635                 log_error("Can't find LV %s in VG %s", lv_name, vg_name);
1636                 unlock_and_free_vg(cmd, vg, vg_name);
1637                 return NULL;
1638         }
1639
1640         return lv;
1641 }
1642
1643 static int poll_logical_volume(struct cmd_context *cmd, struct logical_volume *lv,
1644                                int wait_completion)
1645 {
1646         struct lvinfo info;
1647
1648         if (!lv_info(cmd, lv, 0, &info, 1, 0) || !info.exists) {
1649                 log_print("Conversion starts after activation.");
1650                 return ECMD_PROCESSED;
1651         }
1652         return lvconvert_poll(cmd, lv, wait_completion ? 0 : 1U);
1653 }
1654
1655 static int lvconvert_single(struct cmd_context *cmd, struct lvconvert_params *lp)
1656 {
1657         struct logical_volume *lv = NULL;
1658         int ret = ECMD_FAILED;
1659         int saved_ignore_suspended_devices = ignore_suspended_devices();
1660
1661         if (arg_count(cmd, repair_ARG)) {
1662                 init_ignore_suspended_devices(1);
1663                 cmd->handles_missing_pvs = 1;
1664         }
1665
1666         lv = get_vg_lock_and_logical_volume(cmd, lp->vg_name, lp->lv_name);
1667         if (!lv)
1668                 goto_out;
1669
1670         /*
1671          * lp->pvh holds the list of PVs available for allocation or removal
1672          */
1673         if (lp->pv_count) {
1674                 if (!(lp->pvh = create_pv_list(cmd->mem, lv->vg, lp->pv_count,
1675                                               lp->pvs, 0)))
1676                         goto_bad;
1677         } else
1678                 lp->pvh = &lv->vg->pvs;
1679
1680         lp->lv_to_poll = lv;
1681         ret = _lvconvert_single(cmd, lv, lp);
1682 bad:
1683         unlock_vg(cmd, lp->vg_name);
1684
1685         if (ret == ECMD_PROCESSED && lp->need_polling)
1686                 ret = poll_logical_volume(cmd, lp->lv_to_poll,
1687                                           lp->wait_completion);
1688
1689         free_vg(lv->vg);
1690 out:
1691         init_ignore_suspended_devices(saved_ignore_suspended_devices);
1692         return ret;
1693 }
1694
1695 static int lvconvert_merge_single(struct cmd_context *cmd, struct logical_volume *lv,
1696                                   void *handle)
1697 {
1698         struct lvconvert_params *lp = handle;
1699         const char *vg_name = NULL;
1700         struct logical_volume *refreshed_lv = NULL;
1701         int ret;
1702
1703         /*
1704          * FIXME can't trust lv's VG to be current given that caller
1705          * is process_each_lv() -- poll_logical_volume() may have
1706          * already updated the VG's metadata in an earlier iteration.
1707          * - preemptively drop the VG lock, as is needed for
1708          *   poll_logical_volume(), refresh LV (and VG in the process).
1709          */
1710         vg_name = lv->vg->name;
1711         unlock_vg(cmd, vg_name);
1712         refreshed_lv = get_vg_lock_and_logical_volume(cmd, vg_name, lv->name);
1713         if (!refreshed_lv) {
1714                 log_error("ABORTING: Can't reread LV %s/%s", vg_name, lv->name);
1715                 return ECMD_FAILED;
1716         }
1717
1718         lp->lv_to_poll = refreshed_lv;
1719         ret = _lvconvert_single(cmd, refreshed_lv, lp);
1720
1721         if (ret == ECMD_PROCESSED && lp->need_polling) {
1722                 /*
1723                  * Must drop VG lock, because lvconvert_poll() needs it,
1724                  * then reacquire it after polling completes
1725                  */
1726                 unlock_vg(cmd, vg_name);
1727
1728                 ret = poll_logical_volume(cmd, lp->lv_to_poll,
1729                                           lp->wait_completion);
1730
1731                 /* use LCK_VG_WRITE to match lvconvert()'s READ_FOR_UPDATE */
1732                 if (!lock_vol(cmd, vg_name, LCK_VG_WRITE)) {
1733                         log_error("ABORTING: Can't relock VG for %s "
1734                                   "after polling finished", vg_name);
1735                         ret = ECMD_FAILED;
1736                 }
1737         }
1738
1739         free_vg(refreshed_lv->vg);
1740
1741         return ret;
1742 }
1743
1744 int lvconvert(struct cmd_context * cmd, int argc, char **argv)
1745 {
1746         struct lvconvert_params lp;
1747
1748         if (!_read_params(&lp, cmd, argc, argv)) {
1749                 stack;
1750                 return EINVALID_CMD_LINE;
1751         }
1752
1753         if (lp.merge) {
1754                 if (!argc) {
1755                         log_error("Please provide logical volume path");
1756                         return EINVALID_CMD_LINE;
1757                 }
1758                 return process_each_lv(cmd, argc, argv, READ_FOR_UPDATE, &lp,
1759                                        &lvconvert_merge_single);
1760         }
1761
1762         return lvconvert_single(cmd, &lp);
1763 }