import source from lvm2 2.02.79
[external/device-mapper.git] / lib / metadata / mirror.c
1 /*
2  * Copyright (C) 2003-2004 Sistina Software, Inc. All rights reserved.
3  * Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
4  *
5  * This file is part of LVM2.
6  *
7  * This copyrighted material is made available to anyone wishing to use,
8  * modify, copy, or redistribute it subject to the terms and conditions
9  * of the GNU Lesser General Public License v.2.1.
10  *
11  * You should have received a copy of the GNU Lesser General Public License
12  * along with this program; if not, write to the Free Software Foundation,
13  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
14  */
15
16 #include "lib.h"
17 #include "metadata.h"
18 #include "toolcontext.h"
19 #include "segtype.h"
20 #include "display.h"
21 #include "archiver.h"
22 #include "activate.h"
23 #include "lv_alloc.h"
24 #include "lvm-string.h"
25 #include "str_list.h"
26 #include "locking.h"    /* FIXME Should not be used in this file */
27 #include "memlock.h"
28
29 #include "defaults.h" /* FIXME: should this be defaults.h? */
30
31 /* These are necessary for _write_log_header() */
32 #include "xlate.h"
33 #define MIRROR_MAGIC 0x4D695272
34 #define MIRROR_DISK_VERSION 2
35
36 /* These are the flags that represent the mirror failure restoration policies */
37 #define MIRROR_REMOVE            0
38 #define MIRROR_ALLOCATE          1
39 #define MIRROR_ALLOCATE_ANYWHERE 2
40
41 /*
42  * Returns true if the lv is temporary mirror layer for resync
43  */
44 int is_temporary_mirror_layer(const struct logical_volume *lv)
45 {
46         if (lv->status & MIRROR_IMAGE
47             && lv->status & MIRRORED
48             && !(lv->status & LOCKED))
49                 return 1;
50
51         return 0;
52 }
53
54 /*
55  * Return a temporary LV for resyncing added mirror image.
56  * Add other mirror legs to lvs list.
57  */
58 struct logical_volume *find_temporary_mirror(const struct logical_volume *lv)
59 {
60         struct lv_segment *seg;
61
62         if (!(lv->status & MIRRORED))
63                 return NULL;
64
65         seg = first_seg(lv);
66
67         /* Temporary mirror is always area_num == 0 */
68         if (seg_type(seg, 0) == AREA_LV &&
69             is_temporary_mirror_layer(seg_lv(seg, 0)))
70                 return seg_lv(seg, 0);
71
72         return NULL;
73 }
74
75 int lv_is_mirrored(const struct logical_volume *lv)
76 {
77         if (lv->status & MIRRORED)
78                 return 1;
79
80         return 0;
81 }
82
83 /*
84  * cluster_mirror_is_available
85  *
86  * Check if the proper kernel module and log daemon are running.
87  * Caller should check for 'vg_is_clustered(lv->vg)' before making
88  * this call.
89  *
90  * Returns: 1 if available, 0 otherwise
91  */
92 static int cluster_mirror_is_available(struct logical_volume *lv)
93 {
94        unsigned attr = 0;
95        struct cmd_context *cmd = lv->vg->cmd;
96        const struct segment_type *segtype;
97
98        if (!(segtype = get_segtype_from_string(cmd, "mirror")))
99                return_0;
100
101        if (!segtype->ops->target_present)
102                return_0;
103
104        if (!segtype->ops->target_present(lv->vg->cmd, NULL, &attr))
105                return_0;
106
107        if (!(attr & MIRROR_LOG_CLUSTERED))
108                return 0;
109
110        return 1;
111 }
112
113 /*
114  * Returns the number of mirrors of the LV
115  */
116 uint32_t lv_mirror_count(const struct logical_volume *lv)
117 {
118         struct lv_segment *seg;
119         uint32_t s, mirrors;
120
121         if (!(lv->status & MIRRORED))
122                 return 1;
123
124         seg = first_seg(lv);
125         mirrors = seg->area_count;
126
127         for (s = 0; s < seg->area_count; s++) {
128                 if (seg_type(seg, s) != AREA_LV)
129                         continue;
130                 if (is_temporary_mirror_layer(seg_lv(seg, s)))
131                         mirrors += lv_mirror_count(seg_lv(seg, s)) - 1;
132         }
133
134         return mirrors;
135 }
136
137 struct lv_segment *find_mirror_seg(struct lv_segment *seg)
138 {
139         struct lv_segment *mirror_seg;
140
141         mirror_seg = get_only_segment_using_this_lv(seg->lv);
142
143         if (!mirror_seg) {
144                 log_error("Failed to find mirror_seg for %s", seg->lv->name);
145                 return NULL;
146         }
147
148         if (!seg_is_mirrored(mirror_seg)) {
149                 log_error("%s on %s is not a mirror segments",
150                           mirror_seg->lv->name, seg->lv->name);
151                 return NULL;
152         }
153
154         return mirror_seg;
155 }
156
157 /*
158  * Reduce the region size if necessary to ensure
159  * the volume size is a multiple of the region size.
160  */
161 uint32_t adjusted_mirror_region_size(uint32_t extent_size, uint32_t extents,
162                                      uint32_t region_size)
163 {
164         uint64_t region_max;
165
166         region_max = (1 << (ffs((int)extents) - 1)) * (uint64_t) extent_size;
167
168         if (region_max < UINT32_MAX && region_size > region_max) {
169                 region_size = (uint32_t) region_max;
170                 log_print("Using reduced mirror region size of %" PRIu32
171                           " sectors", region_size);
172         }
173
174         return region_size;
175 }
176
177 /*
178  * shift_mirror_images
179  * @mirrored_seg
180  * @mimage:  The position (index) of the image to move to the end
181  *
182  * When dealing with removal of legs, we often move a 'removable leg'
183  * to the back of the 'areas' array.  It is critically important not
184  * to simply swap it for the last area in the array.  This would have
185  * the affect of reordering the remaining legs - altering position of
186  * the primary.  So, we must shuffle all of the areas in the array
187  * to maintain their relative position before moving the 'removable
188  * leg' to the end.
189  *
190  * Short illustration of the problem:
191  *   - Mirror consists of legs A, B, C and we want to remove A
192  *   - We swap A and C and then remove A, leaving C, B
193  * This scenario is problematic in failure cases where A dies, because
194  * B becomes the primary.  If the above happens, we effectively throw
195  * away any changes made between the time of failure and the time of
196  * restructuring the mirror.
197  *
198  * So, any time we want to move areas to the end to be removed, use
199  * this function.
200  */
201 int shift_mirror_images(struct lv_segment *mirrored_seg, unsigned mimage)
202 {
203         int i;
204         struct lv_segment_area area;
205
206         if (mimage >= mirrored_seg->area_count) {
207                 log_error("Invalid index (%u) of mirror image supplied "
208                           "to shift_mirror_images()", mimage);
209                 return 0;
210         }
211
212         area = mirrored_seg->areas[mimage];
213
214         /* Shift remaining images down to fill the hole */
215         for (i = mimage + 1; i < mirrored_seg->area_count; i++)
216                 mirrored_seg->areas[i-1] = mirrored_seg->areas[i];
217
218         /* Place this one at the end */
219         mirrored_seg->areas[i-1] = area;
220
221         return 1;
222 }
223
224 /*
225  * This function writes a new header to the mirror log header to the lv
226  *
227  * Returns: 1 on success, 0 on failure
228  */
229 static int _write_log_header(struct cmd_context *cmd, struct logical_volume *lv)
230 {
231         struct device *dev;
232         char *name;
233         struct { /* The mirror log header */
234                 uint32_t magic;
235                 uint32_t version;
236                 uint64_t nr_regions;
237         } log_header;
238
239         log_header.magic = xlate32(MIRROR_MAGIC);
240         log_header.version = xlate32(MIRROR_DISK_VERSION);
241         log_header.nr_regions = xlate64((uint64_t)-1);
242
243         if (!(name = dm_pool_alloc(cmd->mem, PATH_MAX))) {
244                 log_error("Name allocation failed - log header not written (%s)",
245                         lv->name);
246                 return 0;
247         }
248
249         if (dm_snprintf(name, PATH_MAX, "%s%s/%s", cmd->dev_dir,
250                          lv->vg->name, lv->name) < 0) {
251                 log_error("Name too long - log header not written (%s)", lv->name);
252                 return 0;
253         }
254
255         log_verbose("Writing log header to device, %s", lv->name);
256
257         if (!(dev = dev_cache_get(name, NULL))) {
258                 log_error("%s: not found: log header not written", name);
259                 return 0;
260         }
261
262         if (!dev_open_quiet(dev))
263                 return 0;
264
265         if (!dev_write(dev, UINT64_C(0), sizeof(log_header), &log_header)) {
266                 log_error("Failed to write log header to %s", name);
267                 dev_close_immediate(dev);
268                 return 0;
269         }
270
271         dev_close_immediate(dev);
272
273         return 1;
274 }
275
276 /*
277  * Initialize mirror log contents
278  */
279 static int _init_mirror_log(struct cmd_context *cmd,
280                             struct logical_volume *log_lv, int in_sync,
281                             struct dm_list *tags, int remove_on_failure)
282 {
283         struct str_list *sl;
284         struct lvinfo info;
285         uint64_t orig_status = log_lv->status;
286         int was_active = 0;
287
288         if (!activation() && in_sync) {
289                 log_error("Aborting. Unable to create in-sync mirror log "
290                           "while activation is disabled.");
291                 return 0;
292         }
293
294         /* If the LV is active, deactivate it first. */
295         if (lv_info(cmd, log_lv, 0, &info, 0, 0) && info.exists) {
296                 (void)deactivate_lv(cmd, log_lv);
297                 /*
298                  * FIXME: workaround to fail early
299                  * Ensure that log is really deactivated because deactivate_lv
300                  * on cluster do not fail if there is log_lv with different UUID.
301                  */
302                 if (lv_info(cmd, log_lv, 0, &info, 0, 0) && info.exists) {
303                         log_error("Aborting. Unable to deactivate mirror log.");
304                         goto revert_new_lv;
305                 }
306                 was_active = 1;
307         }
308
309         /* Temporary make it visible for set_lv() */
310         lv_set_visible(log_lv);
311
312         /* Temporary tag mirror log for activation */
313         dm_list_iterate_items(sl, tags)
314                 if (!str_list_add(cmd->mem, &log_lv->tags, sl->str)) {
315                         log_error("Aborting. Unable to tag mirror log.");
316                         goto activate_lv;
317                 }
318
319         /* store mirror log on disk(s) */
320         if (!vg_write(log_lv->vg) || !vg_commit(log_lv->vg))
321                 goto activate_lv;
322
323         backup(log_lv->vg);
324
325         if (!activate_lv(cmd, log_lv)) {
326                 log_error("Aborting. Failed to activate mirror log.");
327                 goto revert_new_lv;
328         }
329
330         /* Remove the temporary tags */
331         dm_list_iterate_items(sl, tags)
332                 if (!str_list_del(&log_lv->tags, sl->str))
333                         log_error("Failed to remove tag %s from mirror log.",
334                                   sl->str);
335
336         if (activation() && !set_lv(cmd, log_lv, log_lv->size,
337                                     in_sync ? -1 : 0)) {
338                 log_error("Aborting. Failed to wipe mirror log.");
339                 goto deactivate_and_revert_new_lv;
340         }
341
342         if (activation() && !_write_log_header(cmd, log_lv)) {
343                 log_error("Aborting. Failed to write mirror log header.");
344                 goto deactivate_and_revert_new_lv;
345         }
346
347         if (!deactivate_lv(cmd, log_lv)) {
348                 log_error("Aborting. Failed to deactivate mirror log. "
349                           "Manual intervention required.");
350                 return 0;
351         }
352
353         lv_set_hidden(log_lv);
354
355         if (was_active && !activate_lv(cmd, log_lv))
356                 return_0;
357
358         return 1;
359
360 deactivate_and_revert_new_lv:
361         if (!deactivate_lv(cmd, log_lv)) {
362                 log_error("Unable to deactivate mirror log LV. "
363                           "Manual intervention required.");
364                 return 0;
365         }
366
367 revert_new_lv:
368         log_lv->status = orig_status;
369
370         dm_list_iterate_items(sl, tags)
371                 if (!str_list_del(&log_lv->tags, sl->str))
372                         log_error("Failed to remove tag %s from mirror log.",
373                                   sl->str);
374
375         if (remove_on_failure && !lv_remove(log_lv)) {
376                 log_error("Manual intervention may be required to remove "
377                           "abandoned log LV before retrying.");
378                 return 0;
379         }
380
381         if (!vg_write(log_lv->vg) || !vg_commit(log_lv->vg))
382                 log_error("Manual intervention may be required to "
383                           "remove/restore abandoned log LV before retrying.");
384         else
385                 backup(log_lv->vg);
386
387 activate_lv:
388         if (was_active && !remove_on_failure && !activate_lv(cmd, log_lv))
389                 return_0;
390
391         return 0;
392 }
393
394 /*
395  * Delete independent/orphan LV, it must acquire lock.
396  */
397 static int _delete_lv(struct logical_volume *mirror_lv, struct logical_volume *lv)
398 {
399         struct cmd_context *cmd = mirror_lv->vg->cmd;
400         struct str_list *sl;
401
402         /* Inherit tags - maybe needed for activation */
403         if (!str_list_match_list(&mirror_lv->tags, &lv->tags, NULL)) {
404                 dm_list_iterate_items(sl, &mirror_lv->tags)
405                         if (!str_list_add(cmd->mem, &lv->tags, sl->str)) {
406                                 log_error("Aborting. Unable to tag.");
407                                 return 0;
408                         }
409
410                 if (!vg_write(mirror_lv->vg) ||
411                     !vg_commit(mirror_lv->vg)) {
412                         log_error("Intermediate VG commit for orphan volume failed.");
413                         return 0;
414                 }
415         }
416
417         if (!activate_lv(cmd, lv))
418                 return_0;
419
420         if (!deactivate_lv(cmd, lv))
421                 return_0;
422
423         if (!lv_remove(lv))
424                 return_0;
425
426         return 1;
427 }
428
429 static int _merge_mirror_images(struct logical_volume *lv,
430                                 const struct dm_list *mimages)
431 {
432         uint32_t addition = dm_list_size(mimages);
433         struct logical_volume **img_lvs;
434         struct lv_list *lvl;
435         int i = 0;
436
437         if (!addition)
438                 return 1;
439
440         if (!(img_lvs = alloca(sizeof(*img_lvs) * addition)))
441                 return_0;
442
443         dm_list_iterate_items(lvl, mimages)
444                 img_lvs[i++] = lvl->lv;
445
446         return lv_add_mirror_lvs(lv, img_lvs, addition,
447                                  MIRROR_IMAGE, first_seg(lv)->region_size);
448 }
449
450 /* Unlink the relationship between the segment and its log_lv */
451 struct logical_volume *detach_mirror_log(struct lv_segment *mirrored_seg)
452 {
453         struct logical_volume *log_lv;
454
455         if (!mirrored_seg->log_lv)
456                 return NULL;
457
458         log_lv = mirrored_seg->log_lv;
459         mirrored_seg->log_lv = NULL;
460         lv_set_visible(log_lv);
461         log_lv->status &= ~MIRROR_LOG;
462         remove_seg_from_segs_using_this_lv(log_lv, mirrored_seg);
463
464         return log_lv;
465 }
466
467 /* Check if mirror image LV is removable with regard to given removable_pvs */
468 int is_mirror_image_removable(struct logical_volume *mimage_lv, void *baton)
469 {
470         struct physical_volume *pv;
471         struct lv_segment *seg;
472         int pv_found;
473         struct pv_list *pvl;
474         uint32_t s;
475         struct dm_list *removable_pvs = baton;
476
477         if (!baton || dm_list_empty(removable_pvs))
478                 return 1;
479
480         dm_list_iterate_items(seg, &mimage_lv->segments) {
481                 for (s = 0; s < seg->area_count; s++) {
482                         if (seg_type(seg, s) != AREA_PV) {
483                                 /* FIXME Recurse for AREA_LV? */
484                                 /* Structure of seg_lv is unknown.
485                                  * Not removing this LV for safety. */
486                                 return 0;
487                         }
488
489                         pv = seg_pv(seg, s);
490
491                         pv_found = 0;
492                         dm_list_iterate_items(pvl, removable_pvs) {
493                                 if (id_equal(&pv->id, &pvl->pv->id)) {
494                                         pv_found = 1;
495                                         break;
496                                 }
497                                 if (pvl->pv->dev && pv->dev &&
498                                     pv->dev->dev == pvl->pv->dev->dev) {
499                                         pv_found = 1;
500                                         break;
501                                 }
502                         }
503                         if (!pv_found)
504                                 return 0;
505                 }
506         }
507
508         return 1;
509 }
510
511 /*
512  * _move_removable_mimages_to_end
513  *
514  * We always detach mimage LVs from the end of the areas array.
515  * This function will push 'count' mimages to the end of the array
516  * based on if their PVs are removable.
517  *
518  * This is an all or nothing function.  Either the user specifies
519  * enough removable PVs to satisfy count, or they don't specify
520  * any removable_pvs at all (in which case all PVs in the mirror
521  * are considered removable).
522  */
523 static int _move_removable_mimages_to_end(struct logical_volume *lv,
524                                           uint32_t count,
525                                           struct dm_list *removable_pvs)
526 {
527         int i;
528         struct logical_volume *sub_lv;
529         struct lv_segment *mirrored_seg = first_seg(lv);
530
531         if (!removable_pvs)
532                 return 1;
533
534         for (i = mirrored_seg->area_count - 1; (i >= 0) && count; i--) {
535                 sub_lv = seg_lv(mirrored_seg, i);
536
537                 if (!is_temporary_mirror_layer(sub_lv) &&
538                     is_mirror_image_removable(sub_lv, removable_pvs)) {
539                         if (!shift_mirror_images(mirrored_seg, i))
540                                 return_0;
541                         count--;
542                 }
543         }
544
545         return !count;
546 }
547
548 static int _mirrored_lv_in_sync(struct logical_volume *lv)
549 {
550         percent_t sync_percent;
551
552         if (!lv_mirror_percent(lv->vg->cmd, lv, 0, &sync_percent,
553                                NULL)) {
554                 log_error("Unable to determine mirror sync status of %s/%s.",
555                           lv->vg->name, lv->name);
556                 return 0;
557         }
558
559         return (sync_percent == PERCENT_100) ? 1 : 0;
560 }
561
562 /*
563  * Split off 'split_count' legs from a mirror
564  *
565  * Returns: 0 on error, 1 on success
566  */
567 static int _split_mirror_images(struct logical_volume *lv,
568                                 const char *split_name,
569                                 uint32_t split_count,
570                                 struct dm_list *removable_pvs)
571 {
572         uint32_t i;
573         struct logical_volume *sub_lv = NULL;
574         struct logical_volume *new_lv = NULL;
575         struct logical_volume *detached_log_lv = NULL;
576         struct lv_segment *mirrored_seg = first_seg(lv);
577         struct dm_list split_images;
578         struct lv_list *lvl;
579
580         if (!(lv->status & MIRRORED)) {
581                 log_error("Unable to split non-mirrored LV, %s",
582                           lv->name);
583                 return 0;
584         }
585
586         if (!split_count) {
587                 log_error("split_count is zero!");
588                 return 0;
589         }
590
591         log_verbose("Detaching %d images from mirror, %s",
592                     split_count, lv->name);
593
594         if (!_move_removable_mimages_to_end(lv, split_count, removable_pvs)) {
595                 /*
596                  * FIXME: Allow incomplete specification of removable PVs?
597                  *
598                  * I am forcing the user to either specify no
599                  * removable PVs or all of them.  Should we allow
600                  * them to just specify some - making us pick the rest?
601                  */
602                 log_error("Insufficient removable PVs given"
603                           " to satisfy request");
604                 return 0;
605         }
606
607         dm_list_init(&split_images);
608         for (i = 0; i < split_count; i++) {
609                 mirrored_seg->area_count--;
610                 sub_lv = seg_lv(mirrored_seg, mirrored_seg->area_count);
611
612                 sub_lv->status &= ~MIRROR_IMAGE;
613                 lv_set_visible(sub_lv);
614                 release_lv_segment_area(mirrored_seg, mirrored_seg->area_count,
615                                         mirrored_seg->area_len);
616
617                 log_very_verbose("%s assigned to be split", sub_lv->name);
618
619                 if (!new_lv) {
620                         new_lv = sub_lv;
621                         new_lv->name = dm_pool_strdup(lv->vg->cmd->mem,
622                                                       split_name);
623                         if (!new_lv->name) {
624                                 log_error("Unable to rename newly split LV");
625                                 return 0;
626                         }
627                 } else {
628                         lvl = dm_pool_alloc(lv->vg->cmd->mem, sizeof(*lvl));
629                         if (!lvl) {
630                                 log_error("lv_list alloc failed");
631                                 return 0;
632                         }
633                         lvl->lv = sub_lv;
634                         dm_list_add(&split_images, &lvl->list);
635                 }
636         }
637
638         if (!dm_list_empty(&split_images)) {
639                 size_t len = strlen(new_lv->name) + 32;
640                 char *layer_name, format[len];
641
642                 if (!insert_layer_for_lv(lv->vg->cmd, new_lv,
643                                          0, "_mimage_%d")) {
644                         log_error("Failed to build new mirror, %s",
645                                   new_lv->name);
646                         return 0;
647                 }
648
649                 first_seg(new_lv)->region_size = mirrored_seg->region_size;
650
651                 dm_list_iterate_items(lvl, &split_images) {
652                         sub_lv = lvl->lv;
653
654                         dm_snprintf(format, len, "%s_mimage_%%d",
655                                     new_lv->name);
656
657                         layer_name = dm_pool_alloc(lv->vg->cmd->mem, len);
658                         if (!layer_name) {
659                                 log_error("Unable to allocate memory");
660                                 return 0;
661                         }
662                         if (!generate_lv_name(lv->vg, format, layer_name, len)||
663                             sscanf(layer_name, format, &i) != 1) {
664                                 log_error("Failed to generate new image names");
665                                 return 0;
666                         }
667                         sub_lv->name = layer_name;
668                 }
669
670                 if (!_merge_mirror_images(new_lv, &split_images)) {
671                         log_error("Failed to group split "
672                                   "images into new mirror");
673                         return 0;
674                 }
675
676                 /*
677                  * We don't allow splitting a mirror that is not in-sync,
678                  * so we can bring the newly split mirror up without a
679                  * resync.  (It will be a 'core' log mirror after all.)
680                  */
681                 init_mirror_in_sync(1);
682         }
683
684         sub_lv = NULL;
685
686         /*
687          * If no more mirrors, remove mirror layer.
688          * The sub_lv is removed entirely later - leaving
689          * only the top-level (now linear) LV.
690          */
691         if (mirrored_seg->area_count == 1) {
692                 sub_lv = seg_lv(mirrored_seg, 0);
693                 sub_lv->status &= ~MIRROR_IMAGE;
694                 lv_set_visible(sub_lv);
695                 detached_log_lv = detach_mirror_log(mirrored_seg);
696                 if (!remove_layer_from_lv(lv, sub_lv))
697                         return_0;
698                 lv->status &= ~MIRRORED;
699                 lv->status &= ~MIRROR_NOTSYNCED;
700         }
701
702         if (!vg_write(mirrored_seg->lv->vg)) {
703                 log_error("Intermediate VG metadata write failed.");
704                 return 0;
705         }
706
707         /*
708          * Suspend the original device and all its sub devices
709          */
710         if (!suspend_lv(mirrored_seg->lv->vg->cmd, mirrored_seg->lv)) {
711                 log_error("Failed to lock %s", mirrored_seg->lv->name);
712                 vg_revert(mirrored_seg->lv->vg);
713                 return 0;
714         }
715
716         if (!vg_commit(mirrored_seg->lv->vg)) {
717                 resume_lv(mirrored_seg->lv->vg->cmd, mirrored_seg->lv);
718                 return 0;
719         }
720
721         /* Bring newly split-off LV into existence */
722         if (!activate_lv(lv->vg->cmd, new_lv)) {
723                 log_error("Failed to activate newly split LV, %s",
724                           new_lv->name);
725                 return 0;
726         }
727
728         /* Resume altered original LV */
729         log_very_verbose("Updating \"%s\" in kernel", mirrored_seg->lv->name);
730         if (!resume_lv(mirrored_seg->lv->vg->cmd, mirrored_seg->lv)) {
731                 log_error("Problem reactivating %s", mirrored_seg->lv->name);
732                 return 0;
733         }
734
735         if (sub_lv && !_delete_lv(lv, sub_lv))
736                 return_0;
737
738         if (detached_log_lv && !_delete_lv(lv, detached_log_lv))
739                 return_0;
740
741         log_very_verbose("%" PRIu32 " image(s) detached from %s",
742                          split_count, lv->name);
743
744         return 1;
745 }
746
747 /*
748  * Remove num_removed images from mirrored_seg
749  *
750  * Arguments:
751  *   num_removed:   the requested (maximum) number of mirrors to be removed
752  *   removable_pvs: if not NULL and list not empty, only mirrors using PVs
753  *                  in this list will be removed
754  *   remove_log:    if non-zero, log_lv will be removed
755  *                  (even if it's 0, log_lv will be removed if there is no
756  *                   mirror remaining after the removal)
757  *   collapse:      if non-zero, instead of removing, remove the temporary
758  *                  mirror layer and merge mirrors to the original LV.
759  *                  removable_pvs should be NULL and num_removed should be
760  *                  seg->area_count - 1.
761  *   removed:       if non NULL, the number of removed mirror images is set
762  *                  as a result
763  *
764  * If collapse is non-zero, <removed> is guaranteed to be equal to num_removed.
765  *
766  * Return values:
767  *   Failure (0) means something unexpected has happend and
768  *   the caller should abort.
769  *   Even if no mirror was removed (e.g. no LV matches to 'removable_pvs'),
770  *   returns success (1).
771  */
772 static int _remove_mirror_images(struct logical_volume *lv,
773                                  uint32_t num_removed,
774                                  int (*is_removable)(struct logical_volume *, void *),
775                                  void *removable_baton,
776                                  unsigned remove_log, unsigned collapse,
777                                  uint32_t *removed)
778 {
779         uint32_t m;
780         int32_t s;
781         struct logical_volume *sub_lv;
782         struct logical_volume *detached_log_lv = NULL;
783         struct logical_volume *temp_layer_lv = NULL;
784         struct lv_segment *mirrored_seg = first_seg(lv);
785         uint32_t old_area_count = mirrored_seg->area_count;
786         uint32_t new_area_count = mirrored_seg->area_count;
787         struct lv_list *lvl;
788         struct dm_list tmp_orphan_lvs;
789
790         if (removed)
791                 *removed = 0;
792
793         log_very_verbose("Reducing mirror set from %" PRIu32 " to %"
794                          PRIu32 " image(s)%s.",
795                          old_area_count, old_area_count - num_removed,
796                          remove_log ? " and no log volume" : "");
797
798         if (collapse && (old_area_count - num_removed != 1)) {
799                 log_error("Incompatible parameters to _remove_mirror_images");
800                 return 0;
801         }
802
803         /* Move removable_pvs to end of array */
804         for (s = mirrored_seg->area_count - 1;
805              s >= 0 && old_area_count - new_area_count < num_removed;
806              s--) {
807                 sub_lv = seg_lv(mirrored_seg, s);
808                 if (!is_temporary_mirror_layer(sub_lv) &&
809                     is_removable(sub_lv, removable_baton)) {
810                         /*
811                          * Check if the user is trying to pull the
812                          * primary mirror image when the mirror is
813                          * not in-sync.
814                          */
815                         if ((s == 0) && !_mirrored_lv_in_sync(lv) &&
816                             !(lv->status & PARTIAL_LV)) {
817                                 log_error("Unable to remove primary mirror image while mirror is not in-sync");
818                                 return_0;
819                         }
820                         if (!shift_mirror_images(mirrored_seg, s))
821                                 return_0;
822                         new_area_count--;
823                 }
824         }
825
826         /*
827          * If removable_pvs were specified, then they have been shifted
828          * to the end to ensure they are removed.  The remaining balance
829          * of images left to remove will be taken from the unspecified.
830          */
831         new_area_count = old_area_count - num_removed;
832
833         if (num_removed && old_area_count == new_area_count)
834                 return 1;
835
836         /* Remove mimage LVs from the segment */
837         dm_list_init(&tmp_orphan_lvs);
838         for (m = new_area_count; m < mirrored_seg->area_count; m++) {
839                 seg_lv(mirrored_seg, m)->status &= ~MIRROR_IMAGE;
840                 lv_set_visible(seg_lv(mirrored_seg, m));
841                 if (!(lvl = dm_pool_alloc(lv->vg->cmd->mem, sizeof(*lvl)))) {
842                         log_error("lv_list alloc failed");
843                         return 0;
844                 }
845                 lvl->lv = seg_lv(mirrored_seg, m);
846                 dm_list_add(&tmp_orphan_lvs, &lvl->list);
847                 release_lv_segment_area(mirrored_seg, m, mirrored_seg->area_len);
848         }
849         mirrored_seg->area_count = new_area_count;
850
851         /* If no more mirrors, remove mirror layer */
852         /* As an exceptional case, if the lv is temporary layer,
853          * leave the LV as mirrored and let the lvconvert completion
854          * to remove the layer. */
855         if (new_area_count == 1 && !is_temporary_mirror_layer(lv)) {
856                 temp_layer_lv = seg_lv(mirrored_seg, 0);
857                 temp_layer_lv->status &= ~MIRROR_IMAGE;
858                 lv_set_visible(temp_layer_lv);
859                 detached_log_lv = detach_mirror_log(mirrored_seg);
860                 if (!remove_layer_from_lv(lv, temp_layer_lv))
861                         return_0;
862                 lv->status &= ~MIRRORED;
863                 lv->status &= ~MIRROR_NOTSYNCED;
864                 if (collapse && !_merge_mirror_images(lv, &tmp_orphan_lvs)) {
865                         log_error("Failed to add mirror images");
866                         return 0;
867                 }
868                 mirrored_seg = first_seg(lv);
869                 if (remove_log && !detached_log_lv)
870                         detached_log_lv = detach_mirror_log(mirrored_seg);
871         } else if (new_area_count == 0) {
872                 log_very_verbose("All mimages of %s are gone", lv->name);
873
874                 /* All mirror images are gone.
875                  * It can happen for vgreduce --removemissing. */
876                 detached_log_lv = detach_mirror_log(mirrored_seg);
877                 lv->status &= ~MIRRORED;
878                 lv->status &= ~MIRROR_NOTSYNCED;
879                 if (!replace_lv_with_error_segment(lv))
880                         return_0;
881         } else if (remove_log)
882                 detached_log_lv = detach_mirror_log(mirrored_seg);
883
884         /*
885          * The log may be removed due to repair.  If the log
886          * happens to be a mirrored log, then there is a special
887          * case we need to consider.  One of the images of a
888          * mirrored log can fail followed shortly afterwards by
889          * a failure of the second.  This means that the top-level
890          * mirror is waiting for writes to the log to finish, but
891          * they never will unless the mirrored log can be repaired
892          * or replaced with an error target.  Since both the devices
893          * have failed, we must replace with error target - it is
894          * the only way to release the pending writes.
895          */
896         if (detached_log_lv && lv_is_mirrored(detached_log_lv) &&
897             (detached_log_lv->status & PARTIAL_LV)) {
898                 struct lv_segment *seg = first_seg(detached_log_lv);
899
900                 log_very_verbose("%s being removed due to failures",
901                                  detached_log_lv->name);
902
903                 /*
904                  * We are going to replace the mirror with an
905                  * error segment, but before we do, we must remember
906                  * all of the LVs that must be deleted later (i.e.
907                  * the sub-lv's)
908                  */
909                 for (m = 0; m < seg->area_count; m++) {
910                         seg_lv(seg, m)->status &= ~MIRROR_IMAGE;
911                         lv_set_visible(seg_lv(seg, m));
912                         if (!(lvl = dm_pool_alloc(lv->vg->cmd->mem,
913                                                   sizeof(*lvl)))) {
914                                 log_error("dm_pool_alloc failed");
915                                 return 0;
916                         }
917                         lvl->lv = seg_lv(seg, m);
918                         dm_list_add(&tmp_orphan_lvs, &lvl->list);
919                 }
920
921                 if (!replace_lv_with_error_segment(detached_log_lv)) {
922                         log_error("Failed error target substitution for %s",
923                                   detached_log_lv->name);
924                         return 0;
925                 }
926
927                 if (!vg_write(detached_log_lv->vg)) {
928                         log_error("intermediate VG write failed.");
929                         return 0;
930                 }
931
932                 if (!suspend_lv(detached_log_lv->vg->cmd,
933                                 detached_log_lv)) {
934                         log_error("Failed to suspend %s",
935                                   detached_log_lv->name);
936                         return 0;
937                 }
938
939                 if (!vg_commit(detached_log_lv->vg)) {
940                         if (!resume_lv(detached_log_lv->vg->cmd,
941                                        detached_log_lv))
942                                 stack;
943                         return_0;
944                 }
945
946                 if (!resume_lv(detached_log_lv->vg->cmd, detached_log_lv)) {
947                         log_error("Failed to resume %s",
948                                   detached_log_lv->name);
949                         return_0;
950                 }
951         }
952
953         /*
954          * To successfully remove these unwanted LVs we need to
955          * remove the LVs from the mirror set, commit that metadata
956          * then deactivate and remove them fully.
957          */
958
959         if (!vg_write(mirrored_seg->lv->vg)) {
960                 log_error("intermediate VG write failed.");
961                 return 0;
962         }
963
964         if (!suspend_lv_origin(mirrored_seg->lv->vg->cmd, mirrored_seg->lv)) {
965                 log_error("Failed to lock %s", mirrored_seg->lv->name);
966                 vg_revert(mirrored_seg->lv->vg);
967                 return 0;
968         }
969
970         /* FIXME: second suspend should not be needed
971          * Explicitly suspend temporary LV
972          * This balance memlock_inc() calls with memlock_dec() in resume
973          * (both localy and in cluster) and also properly propagates precommited
974          * metadata into dm table on other nodes.
975          * (visible flag set causes the suspend is not properly propagated?)
976          */
977         if (temp_layer_lv && !suspend_lv(temp_layer_lv->vg->cmd, temp_layer_lv))
978                 log_error("Problem suspending temporary LV %s", temp_layer_lv->name);
979
980         if (!vg_commit(mirrored_seg->lv->vg)) {
981                 if (!resume_lv(mirrored_seg->lv->vg->cmd, mirrored_seg->lv))
982                         stack;
983                 return_0;
984         }
985
986         log_very_verbose("Updating \"%s\" in kernel", mirrored_seg->lv->name);
987
988         /*
989          * Avoid having same mirror target loaded twice simultaneously by first
990          * resuming the removed LV which now contains an error segment.
991          * As it's now detached from mirrored_seg->lv we must resume it
992          * explicitly.
993          */
994         if (temp_layer_lv && !resume_lv(temp_layer_lv->vg->cmd, temp_layer_lv)) {
995                 log_error("Problem resuming temporary LV, %s", temp_layer_lv->name);
996                 return 0;
997         }
998
999         if (!resume_lv_origin(mirrored_seg->lv->vg->cmd, mirrored_seg->lv)) {
1000                 log_error("Problem reactivating %s", mirrored_seg->lv->name);
1001                 return 0;
1002         }
1003
1004         /* Save or delete the 'orphan' LVs */
1005         if (!collapse) {
1006                 dm_list_iterate_items(lvl, &tmp_orphan_lvs)
1007                         if (!_delete_lv(lv, lvl->lv))
1008                                 return_0;
1009         }
1010
1011         if (temp_layer_lv && !_delete_lv(lv, temp_layer_lv))
1012                 return_0;
1013
1014         if (detached_log_lv && !_delete_lv(lv, detached_log_lv))
1015                 return_0;
1016
1017         /* Mirror with only 1 area is 'in sync'. */
1018         if (new_area_count == 1 && is_temporary_mirror_layer(lv)) {
1019                 if (first_seg(lv)->log_lv &&
1020                     !_init_mirror_log(lv->vg->cmd, first_seg(lv)->log_lv,
1021                                       1, &lv->tags, 0)) {
1022                         /* As a result, unnecessary sync may run after
1023                          * collapsing. But safe.*/
1024                         log_error("Failed to initialize log device");
1025                         return_0;
1026                 }
1027         }
1028
1029         if (removed)
1030                 *removed = old_area_count - new_area_count;
1031
1032         log_very_verbose("%" PRIu32 " image(s) removed from %s",
1033                          old_area_count - num_removed, lv->name);
1034
1035         return 1;
1036 }
1037
1038 /*
1039  * Remove the number of mirror images from the LV
1040  */
1041 int remove_mirror_images(struct logical_volume *lv, uint32_t num_mirrors,
1042                          int (*is_removable)(struct logical_volume *, void *),
1043                          void *removable_baton, unsigned remove_log)
1044 {
1045         uint32_t num_removed, removed_once, r;
1046         uint32_t existing_mirrors = lv_mirror_count(lv);
1047         struct logical_volume *next_lv = lv;
1048
1049         num_removed = existing_mirrors - num_mirrors;
1050
1051         /* num_removed can be 0 if the function is called just to remove log */
1052         do {
1053                 if (num_removed < first_seg(next_lv)->area_count)
1054                         removed_once = num_removed;
1055                 else
1056                         removed_once = first_seg(next_lv)->area_count - 1;
1057
1058                 if (!_remove_mirror_images(next_lv, removed_once,
1059                                            is_removable, removable_baton,
1060                                            remove_log, 0, &r))
1061                         return_0;
1062
1063                 if (r < removed_once) {
1064                         /* Some mirrors are removed from the temporary mirror,
1065                          * but the temporary layer still exists.
1066                          * Down the stack and retry for remainder. */
1067                         next_lv = find_temporary_mirror(next_lv);
1068                 }
1069
1070                 num_removed -= r;
1071         } while (next_lv && num_removed);
1072
1073         if (num_removed) {
1074                 if (num_removed == existing_mirrors - num_mirrors)
1075                         log_error("No mirror images found using specified PVs.");
1076                 else {
1077                         log_error("%u images are removed out of requested %u.",
1078                                   existing_mirrors - lv_mirror_count(lv),
1079                                   existing_mirrors - num_mirrors);
1080                 }
1081                 return 0;
1082         }
1083
1084         return 1;
1085 }
1086
1087 static int _no_removable_images(struct logical_volume *lv __attribute__((unused)),
1088                                 void *baton __attribute__((unused))) {
1089         return 0;
1090 }
1091
1092 /*
1093  * Collapsing temporary mirror layers.
1094  *
1095  * When mirrors are added to already-mirrored LV, a temporary mirror layer
1096  * is inserted at the top of the stack to reduce resync work.
1097  * The function will remove the intermediate layer and collapse the stack
1098  * as far as mirrors are in-sync.
1099  *
1100  * The function is destructive: to remove intermediate mirror layers,
1101  * VG metadata commits and suspend/resume are necessary.
1102  */
1103 int collapse_mirrored_lv(struct logical_volume *lv)
1104 {
1105         struct logical_volume *tmp_lv;
1106         struct lv_segment *mirror_seg;
1107
1108         while ((tmp_lv = find_temporary_mirror(lv))) {
1109                 mirror_seg = find_mirror_seg(first_seg(tmp_lv));
1110                 if (!mirror_seg) {
1111                         log_error("Failed to find mirrored LV for %s",
1112                                   tmp_lv->name);
1113                         return 0;
1114                 }
1115
1116                 if (!_mirrored_lv_in_sync(mirror_seg->lv)) {
1117                         log_verbose("Not collapsing %s: out-of-sync",
1118                                     mirror_seg->lv->name);
1119                         return 1;
1120                 }
1121
1122                 if (!_remove_mirror_images(mirror_seg->lv,
1123                                            mirror_seg->area_count - 1,
1124                                            _no_removable_images, NULL, 0, 1, NULL)) {
1125                         log_error("Failed to release mirror images");
1126                         return 0;
1127                 }
1128         }
1129
1130         return 1;
1131 }
1132
1133 static int get_mirror_fault_policy(struct cmd_context *cmd __attribute__((unused)),
1134                                    int log_policy)
1135 {
1136         const char *policy;
1137
1138         if (log_policy)
1139                 policy = find_config_str(NULL, "activation/mirror_log_fault_policy",
1140                                          DEFAULT_MIRROR_LOG_FAULT_POLICY);
1141         else {
1142                 policy = find_config_str(NULL, "activation/mirror_image_fault_policy",
1143                                          NULL);
1144                 if (!policy)
1145                         policy = find_config_str(NULL, "activation/mirror_device_fault_policy",
1146                                                  DEFAULT_MIRROR_IMAGE_FAULT_POLICY);
1147         }
1148
1149         if (!strcmp(policy, "remove"))
1150                 return MIRROR_REMOVE;
1151         else if (!strcmp(policy, "allocate"))
1152                 return MIRROR_ALLOCATE;
1153         else if (!strcmp(policy, "allocate_anywhere"))
1154                 return MIRROR_ALLOCATE_ANYWHERE;
1155
1156         if (log_policy)
1157                 log_error("Bad activation/mirror_log_fault_policy");
1158         else
1159                 log_error("Bad activation/mirror_device_fault_policy");
1160
1161         return MIRROR_REMOVE;
1162 }
1163
1164 static int get_mirror_log_fault_policy(struct cmd_context *cmd)
1165 {
1166         return get_mirror_fault_policy(cmd, 1);
1167 }
1168
1169 static int get_mirror_device_fault_policy(struct cmd_context *cmd)
1170 {
1171         return get_mirror_fault_policy(cmd, 0);
1172 }
1173
1174 /*
1175  * replace_mirror_images
1176  * @mirrored_seg: segment (which may be linear now) to restore
1177  * @num_mirrors: number of copies we should end up with
1178  * @replace_log: replace log if not present
1179  * @in_sync: was the original mirror in-sync?
1180  *
1181  * in_sync will be set to 0 if new mirror devices are being added
1182  * In other words, it is only useful if the log (and only the log)
1183  * is being restored.
1184  *
1185  * Returns: 0 on failure, 1 on reconfig, -1 if no reconfig done
1186  */
1187 static int replace_mirror_images(struct lv_segment *mirrored_seg,
1188                                  uint32_t num_mirrors,
1189                                  int log_policy, int in_sync)
1190 {
1191         int r = -1;
1192         struct logical_volume *lv = mirrored_seg->lv;
1193
1194         /* FIXME: Use lvconvert rather than duplicating its code */
1195
1196         if (mirrored_seg->area_count < num_mirrors) {
1197                 log_warn("WARNING: Failed to replace mirror device in %s/%s",
1198                          mirrored_seg->lv->vg->name, mirrored_seg->lv->name);
1199
1200                 if ((mirrored_seg->area_count > 1) && !mirrored_seg->log_lv)
1201                         log_warn("WARNING: Use 'lvconvert -m %d %s/%s --corelog' to replace failed devices",
1202                                  num_mirrors - 1, lv->vg->name, lv->name);
1203                 else
1204                         log_warn("WARNING: Use 'lvconvert -m %d %s/%s' to replace failed devices",
1205                                  num_mirrors - 1, lv->vg->name, lv->name);
1206                 r = 0;
1207
1208                 /* REMEMBER/FIXME: set in_sync to 0 if a new mirror device was added */
1209                 in_sync = 0;
1210         }
1211
1212         /*
1213          * FIXME: right now, we ignore the allocation policy specified to
1214          * allocate the new log.
1215          */
1216         if ((mirrored_seg->area_count > 1) && !mirrored_seg->log_lv &&
1217             (log_policy != MIRROR_REMOVE)) {
1218                 log_warn("WARNING: Failed to replace mirror log device in %s/%s",
1219                          lv->vg->name, lv->name);
1220
1221                 log_warn("WARNING: Use 'lvconvert -m %d %s/%s' to replace failed devices",
1222                          mirrored_seg->area_count - 1 , lv->vg->name, lv->name);
1223                 r = 0;
1224         }
1225
1226         return r;
1227 }
1228
1229 int reconfigure_mirror_images(struct lv_segment *mirrored_seg, uint32_t num_mirrors,
1230                               struct dm_list *removable_pvs, unsigned remove_log)
1231 {
1232         int r;
1233         int in_sync;
1234         int log_policy, dev_policy;
1235         uint32_t old_num_mirrors = mirrored_seg->area_count;
1236         int had_log = (mirrored_seg->log_lv) ? 1 : 0;
1237
1238         /* was the mirror in-sync before problems? */
1239         in_sync = _mirrored_lv_in_sync(mirrored_seg->lv);
1240
1241         /*
1242          * While we are only removing devices, we can have sync set.
1243          * Setting this is only useful if we are moving to core log
1244          * otherwise the disk log will contain the sync information
1245          */
1246         init_mirror_in_sync(in_sync);
1247
1248         r = _remove_mirror_images(mirrored_seg->lv, old_num_mirrors - num_mirrors,
1249                                   is_mirror_image_removable, removable_pvs,
1250                                   remove_log, 0, NULL);
1251         if (!r)
1252                 /* Unable to remove bad devices */
1253                 return 0;
1254
1255         log_warn("WARNING: Bad device removed from mirror volume, %s/%s",
1256                   mirrored_seg->lv->vg->name, mirrored_seg->lv->name);
1257
1258         log_policy = get_mirror_log_fault_policy(mirrored_seg->lv->vg->cmd);
1259         dev_policy = get_mirror_device_fault_policy(mirrored_seg->lv->vg->cmd);
1260
1261         r = replace_mirror_images(mirrored_seg,
1262                                   (dev_policy != MIRROR_REMOVE) ?
1263                                   old_num_mirrors : num_mirrors,
1264                                   log_policy, in_sync);
1265
1266         if (!r)
1267                 /* Failed to replace device(s) */
1268                 log_warn("WARNING: Unable to find substitute device for mirror volume, %s/%s",
1269                          mirrored_seg->lv->vg->name, mirrored_seg->lv->name);
1270         else if (r > 0)
1271                 /* Success in replacing device(s) */
1272                 log_warn("WARNING: Mirror volume, %s/%s restored - substitute for failed device found.",
1273                           mirrored_seg->lv->vg->name, mirrored_seg->lv->name);
1274         else
1275                 /* Bad device removed, but not replaced because of policy */
1276                 if (mirrored_seg->area_count == 1) {
1277                         log_warn("WARNING: Mirror volume, %s/%s converted to linear due to device failure.",
1278                                   mirrored_seg->lv->vg->name, mirrored_seg->lv->name);
1279                 } else if (had_log && !mirrored_seg->log_lv) {
1280                         log_warn("WARNING: Mirror volume, %s/%s disk log removed due to device failure.",
1281                                   mirrored_seg->lv->vg->name, mirrored_seg->lv->name);
1282                 }
1283         /*
1284          * If we made it here, we at least removed the bad device.
1285          * Consider this success.
1286          */
1287         return 1;
1288 }
1289
1290 static int _create_mimage_lvs(struct alloc_handle *ah,
1291                               uint32_t num_mirrors,
1292                               uint32_t stripes,
1293                               uint32_t stripe_size,
1294                               struct logical_volume *lv,
1295                               struct logical_volume **img_lvs,
1296                               int log)
1297 {
1298         uint32_t m;
1299         char *img_name;
1300         size_t len;
1301         
1302         len = strlen(lv->name) + 32;
1303         if (!(img_name = alloca(len))) {
1304                 log_error("img_name allocation failed. "
1305                           "Remove new LV and retry.");
1306                 return 0;
1307         }
1308
1309         if (dm_snprintf(img_name, len, "%s_mimage_%%d", lv->name) < 0) {
1310                 log_error("img_name allocation failed. "
1311                           "Remove new LV and retry.");
1312                 return 0;
1313         }
1314
1315         for (m = 0; m < num_mirrors; m++) {
1316                 if (!(img_lvs[m] = lv_create_empty(img_name,
1317                                              NULL, LVM_READ | LVM_WRITE,
1318                                              ALLOC_INHERIT, lv->vg))) {
1319                         log_error("Aborting. Failed to create mirror image LV. "
1320                                   "Remove new LV and retry.");
1321                         return 0;
1322                 }
1323
1324                 if (log) {
1325                         if (!lv_add_log_segment(ah, m * stripes + 1, img_lvs[m], 0)) {
1326                                 log_error("Aborting. Failed to add mirror image segment "
1327                                           "to %s. Remove new LV and retry.",
1328                                           img_lvs[m]->name);
1329                                 return 0;
1330                         }
1331                 } else {
1332                         if (!lv_add_segment(ah, m * stripes, stripes, img_lvs[m],
1333                                             get_segtype_from_string(lv->vg->cmd,
1334                                                                     "striped"),
1335                                             stripe_size, 0, 0)) {
1336                                 log_error("Aborting. Failed to add mirror image segment "
1337                                           "to %s. Remove new LV and retry.",
1338                                           img_lvs[m]->name);
1339                                 return 0;
1340                         }
1341                 }
1342         }
1343
1344         return 1;
1345 }
1346
1347 /*
1348  * Remove mirrors from each segment.
1349  * 'new_mirrors' is the number of mirrors after the removal. '0' for linear.
1350  * If 'status_mask' is non-zero, the removal happens only when all segments
1351  * has the status bits on.
1352  */
1353 int remove_mirrors_from_segments(struct logical_volume *lv,
1354                                  uint32_t new_mirrors, uint64_t status_mask)
1355 {
1356         struct lv_segment *seg;
1357         uint32_t s;
1358
1359         /* Check the segment params are compatible */
1360         dm_list_iterate_items(seg, &lv->segments) {
1361                 if (!seg_is_mirrored(seg)) {
1362                         log_error("Segment is not mirrored: %s:%" PRIu32,
1363                                   lv->name, seg->le);
1364                         return 0;
1365                 } if ((seg->status & status_mask) != status_mask) {
1366                         log_error("Segment status does not match: %s:%" PRIu32
1367                                   " status:0x%" PRIx64 "/0x%" PRIx64, lv->name, seg->le,
1368                                   seg->status, status_mask);
1369                         return 0;
1370                 }
1371         }
1372
1373         /* Convert the segments */
1374         dm_list_iterate_items(seg, &lv->segments) {
1375                 if (!new_mirrors && seg->extents_copied == seg->area_len) {
1376                         if (!move_lv_segment_area(seg, 0, seg, 1))
1377                                 return_0;
1378                 }
1379
1380                 for (s = new_mirrors + 1; s < seg->area_count; s++)
1381                         release_lv_segment_area(seg, s, seg->area_len);
1382
1383                 seg->area_count = new_mirrors + 1;
1384
1385                 if (!new_mirrors)
1386                         seg->segtype = get_segtype_from_string(lv->vg->cmd,
1387                                                                "striped");
1388         }
1389
1390         return 1;
1391 }
1392
1393 const char *get_pvmove_pvname_from_lv_mirr(struct logical_volume *lv_mirr)
1394 {
1395         struct lv_segment *seg;
1396
1397         dm_list_iterate_items(seg, &lv_mirr->segments) {
1398                 if (!seg_is_mirrored(seg))
1399                         continue;
1400                 if (seg_type(seg, 0) != AREA_PV)
1401                         continue;
1402                 return dev_name(seg_dev(seg, 0));
1403         }
1404
1405         return NULL;
1406 }
1407
1408 const char *get_pvmove_pvname_from_lv(struct logical_volume *lv)
1409 {
1410         struct lv_segment *seg;
1411         uint32_t s;
1412
1413         dm_list_iterate_items(seg, &lv->segments) {
1414                 for (s = 0; s < seg->area_count; s++) {
1415                         if (seg_type(seg, s) != AREA_LV)
1416                                 continue;
1417                         return get_pvmove_pvname_from_lv_mirr(seg_lv(seg, s));
1418                 }
1419         }
1420
1421         return NULL;
1422 }
1423
1424 struct logical_volume *find_pvmove_lv(struct volume_group *vg,
1425                                       struct device *dev,
1426                                       uint32_t lv_type)
1427 {
1428         struct lv_list *lvl;
1429         struct logical_volume *lv;
1430         struct lv_segment *seg;
1431
1432         /* Loop through all LVs */
1433         dm_list_iterate_items(lvl, &vg->lvs) {
1434                 lv = lvl->lv;
1435
1436                 if (!(lv->status & lv_type))
1437                         continue;
1438
1439                 /* Check segment origins point to pvname */
1440                 dm_list_iterate_items(seg, &lv->segments) {
1441                         if (seg_type(seg, 0) != AREA_PV)
1442                                 continue;
1443                         if (seg_dev(seg, 0) != dev)
1444                                 continue;
1445                         return lv;
1446                 }
1447         }
1448
1449         return NULL;
1450 }
1451
1452 struct logical_volume *find_pvmove_lv_from_pvname(struct cmd_context *cmd,
1453                                                   struct volume_group *vg,
1454                                                   const char *name,
1455                                                   const char *uuid __attribute__((unused)),
1456                                                   uint32_t lv_type)
1457 {
1458         struct physical_volume *pv;
1459
1460         if (!(pv = find_pv_by_name(cmd, name)))
1461                 return_NULL;
1462
1463         return find_pvmove_lv(vg, pv->dev, lv_type);
1464 }
1465
1466 struct dm_list *lvs_using_lv(struct cmd_context *cmd, struct volume_group *vg,
1467                           struct logical_volume *lv)
1468 {
1469         struct dm_list *lvs;
1470         struct logical_volume *lv1;
1471         struct lv_list *lvl, *lvl1;
1472         struct lv_segment *seg;
1473         uint32_t s;
1474
1475         if (!(lvs = dm_pool_alloc(cmd->mem, sizeof(*lvs)))) {
1476                 log_error("lvs list alloc failed");
1477                 return NULL;
1478         }
1479
1480         dm_list_init(lvs);
1481
1482         /* Loop through all LVs except the one supplied */
1483         dm_list_iterate_items(lvl1, &vg->lvs) {
1484                 lv1 = lvl1->lv;
1485                 if (lv1 == lv)
1486                         continue;
1487
1488                 /* Find whether any segment points at the supplied LV */
1489                 dm_list_iterate_items(seg, &lv1->segments) {
1490                         for (s = 0; s < seg->area_count; s++) {
1491                                 if (seg_type(seg, s) != AREA_LV ||
1492                                     seg_lv(seg, s) != lv)
1493                                         continue;
1494                                 if (!(lvl = dm_pool_alloc(cmd->mem, sizeof(*lvl)))) {
1495                                         log_error("lv_list alloc failed");
1496                                         return NULL;
1497                                 }
1498                                 lvl->lv = lv1;
1499                                 dm_list_add(lvs, &lvl->list);
1500                                 goto next_lv;
1501                         }
1502                 }
1503               next_lv:
1504                 ;
1505         }
1506
1507         return lvs;
1508 }
1509
1510 percent_t copy_percent(struct logical_volume *lv_mirr)
1511 {
1512         uint32_t numerator = 0u, denominator = 0u;
1513         struct lv_segment *seg;
1514
1515         dm_list_iterate_items(seg, &lv_mirr->segments) {
1516                 denominator += seg->area_len;
1517
1518                 if (seg_is_mirrored(seg) && seg->area_count > 1)
1519                         numerator += seg->extents_copied;
1520                 else
1521                         numerator += seg->area_len;
1522         }
1523
1524         return denominator ? make_percent( numerator, denominator ) : 100.0;
1525 }
1526
1527 /*
1528  * Fixup mirror pointers after single-pass segment import
1529  */
1530 int fixup_imported_mirrors(struct volume_group *vg)
1531 {
1532         struct lv_list *lvl;
1533         struct lv_segment *seg;
1534
1535         dm_list_iterate_items(lvl, &vg->lvs) {
1536                 dm_list_iterate_items(seg, &lvl->lv->segments) {
1537                         if (seg->segtype !=
1538                             get_segtype_from_string(vg->cmd, "mirror"))
1539                                 continue;
1540
1541                         if (seg->log_lv && !add_seg_to_segs_using_this_lv(seg->log_lv, seg))
1542                                 return_0;
1543                 }
1544         }
1545
1546         return 1;
1547 }
1548
1549 /*
1550  * Add mirrors to "linear" or "mirror" segments
1551  */
1552 int add_mirrors_to_segments(struct cmd_context *cmd, struct logical_volume *lv,
1553                             uint32_t mirrors, uint32_t region_size,
1554                             struct dm_list *allocatable_pvs, alloc_policy_t alloc)
1555 {
1556         struct alloc_handle *ah;
1557         const struct segment_type *segtype;
1558         struct dm_list *parallel_areas;
1559         uint32_t adjusted_region_size;
1560         int r = 1;
1561
1562         if (!(parallel_areas = build_parallel_areas_from_lv(cmd, lv, 1)))
1563                 return_0;
1564
1565         if (!(segtype = get_segtype_from_string(cmd, "mirror")))
1566                 return_0;
1567
1568         adjusted_region_size = adjusted_mirror_region_size(lv->vg->extent_size,
1569                                                            lv->le_count,
1570                                                            region_size);
1571
1572         if (!(ah = allocate_extents(lv->vg, NULL, segtype, 1, mirrors, 0, 0,
1573                                     lv->le_count, allocatable_pvs, alloc,
1574                                     parallel_areas))) {
1575                 log_error("Unable to allocate mirror extents for %s.", lv->name);
1576                 return 0;
1577         }
1578
1579         if (!lv_add_mirror_areas(ah, lv, 0, adjusted_region_size)) {
1580                 log_error("Failed to add mirror areas to %s", lv->name);
1581                 r = 0;
1582         }
1583
1584         alloc_destroy(ah);
1585         return r;
1586 }
1587
1588 /*
1589  * Convert mirror log
1590  *
1591  * FIXME: Can't handle segment-by-segment mirror (like pvmove)
1592  */
1593 int remove_mirror_log(struct cmd_context *cmd,
1594                       struct logical_volume *lv,
1595                       struct dm_list *removable_pvs,
1596                       int force)
1597 {
1598         percent_t sync_percent;
1599         struct lvinfo info;
1600         struct volume_group *vg = lv->vg;
1601
1602         /* Unimplemented features */
1603         if (dm_list_size(&lv->segments) != 1) {
1604                 log_error("Multiple-segment mirror is not supported");
1605                 return 0;
1606         }
1607
1608         /* Had disk log, switch to core. */
1609         if (lv_info(cmd, lv, 0, &info, 0, 0) && info.exists) {
1610                 if (!lv_mirror_percent(cmd, lv, 0, &sync_percent,
1611                                        NULL)) {
1612                         log_error("Unable to determine mirror sync status.");
1613                         return 0;
1614                 }
1615         } else if (vg_is_clustered(vg)) {
1616                 log_error("Unable to convert the log of an inactive "
1617                           "cluster mirror, %s", lv->name);
1618                 return 0;
1619         } else if (force || yes_no_prompt("Full resync required to convert "
1620                                  "inactive mirror %s to core log. "
1621                                  "Proceed? [y/n]: ", lv->name) == 'y')
1622                 sync_percent = 0;
1623         else
1624                 return 0;
1625
1626         if (sync_percent == PERCENT_100)
1627                 init_mirror_in_sync(1);
1628         else {
1629                 /* A full resync will take place */
1630                 lv->status &= ~MIRROR_NOTSYNCED;
1631                 init_mirror_in_sync(0);
1632         }
1633
1634         if (!remove_mirror_images(lv, lv_mirror_count(lv),
1635                                   is_mirror_image_removable, removable_pvs, 1U))
1636                 return_0;
1637
1638         return 1;
1639 }
1640
1641 static struct logical_volume *_create_mirror_log(struct logical_volume *lv,
1642                                                  struct alloc_handle *ah,
1643                                                  alloc_policy_t alloc,
1644                                                  const char *lv_name,
1645                                                  const char *suffix)
1646 {
1647         struct logical_volume *log_lv;
1648         char *log_name;
1649         size_t len;
1650
1651         len = strlen(lv_name) + 32;
1652         if (!(log_name = alloca(len))) {
1653                 log_error("log_name allocation failed.");
1654                 return NULL;
1655         }
1656
1657         if (dm_snprintf(log_name, len, "%s%s", lv_name, suffix) < 0) {
1658                 log_error("log_name allocation failed.");
1659                 return NULL;
1660         }
1661
1662         if (!(log_lv = lv_create_empty(log_name, NULL,
1663                                        VISIBLE_LV | LVM_READ | LVM_WRITE,
1664                                        alloc, lv->vg)))
1665                 return_NULL;
1666
1667         if (!lv_add_log_segment(ah, 0, log_lv, MIRROR_LOG))
1668                 return_NULL;
1669
1670         return log_lv;
1671 }
1672
1673 /*
1674  * Returns: 1 on success, 0 on error
1675  */
1676 static int _form_mirror(struct cmd_context *cmd, struct alloc_handle *ah,
1677                         struct logical_volume *lv,
1678                         uint32_t mirrors, uint32_t stripes,
1679                         uint32_t stripe_size, uint32_t region_size, int log)
1680 {
1681         struct logical_volume **img_lvs;
1682
1683         /*
1684          * insert a mirror layer
1685          */
1686         if (dm_list_size(&lv->segments) != 1 ||
1687             seg_type(first_seg(lv), 0) != AREA_LV)
1688                 if (!insert_layer_for_lv(cmd, lv, 0, "_mimage_%d"))
1689                         return 0;
1690
1691         /*
1692          * create mirror image LVs
1693          */
1694         if (!(img_lvs = alloca(sizeof(*img_lvs) * mirrors))) {
1695                 log_error("img_lvs allocation failed. "
1696                           "Remove new LV and retry.");
1697                 return 0;
1698         }
1699
1700         if (!_create_mimage_lvs(ah, mirrors, stripes, stripe_size, lv, img_lvs, log))
1701                 return 0;
1702
1703         if (!lv_add_mirror_lvs(lv, img_lvs, mirrors,
1704                                MIRROR_IMAGE | (lv->status & LOCKED),
1705                                region_size)) {
1706                 log_error("Aborting. Failed to add mirror segment. "
1707                           "Remove new LV and retry.");
1708                 return 0;
1709         }
1710
1711         return 1;
1712 }
1713
1714 static struct logical_volume *_set_up_mirror_log(struct cmd_context *cmd,
1715                                                  struct alloc_handle *ah,
1716                                                  struct logical_volume *lv,
1717                                                  uint32_t log_count,
1718                                                  uint32_t region_size,
1719                                                  alloc_policy_t alloc,
1720                                                  int in_sync)
1721 {
1722         struct logical_volume *log_lv;
1723         const char *suffix, *c;
1724         char *lv_name;
1725         size_t len;
1726         struct lv_segment *seg;
1727
1728         init_mirror_in_sync(in_sync);
1729
1730         /* Mirror log name is lv_name + suffix, determined as the following:
1731          *   1. suffix is:
1732          *        o "_mlog" for the original mirror LV.
1733          *        o "_mlogtmp_%d" for temporary mirror LV,
1734          *   2. lv_name is:
1735          *        o lv->name, if the log is temporary
1736          *        o otherwise, the top-level LV name
1737          */
1738         seg = first_seg(lv);
1739         if (seg_type(seg, 0) == AREA_LV &&
1740             strstr(seg_lv(seg, 0)->name, MIRROR_SYNC_LAYER)) {
1741                 lv_name = lv->name;
1742                 suffix = "_mlogtmp_%d";
1743         } else if ((c = strstr(lv->name, MIRROR_SYNC_LAYER))) {
1744                 len = c - lv->name + 1;
1745                 if (!(lv_name = alloca(len)) ||
1746                     !dm_snprintf(lv_name, len, "%s", lv->name)) {
1747                         log_error("mirror log name allocation failed");
1748                         return 0;
1749                 }
1750                 suffix = "_mlog";
1751         } else {
1752                 lv_name = lv->name;
1753                 suffix = "_mlog";
1754         }
1755
1756         if (!(log_lv = _create_mirror_log(lv, ah, alloc,
1757                                           (const char *) lv_name, suffix))) {
1758                 log_error("Failed to create mirror log.");
1759                 return NULL;
1760         }
1761
1762         if ((log_count > 1) &&
1763             !_form_mirror(cmd, ah, log_lv, log_count-1, 1, 0, region_size, 1)) {
1764                 log_error("Failed to form mirrored log.");
1765                 return NULL;
1766         }
1767
1768         if (!_init_mirror_log(cmd, log_lv, in_sync, &lv->tags, 1)) {
1769                 log_error("Failed to initialise mirror log.");
1770                 return NULL;
1771         }
1772
1773         return log_lv;
1774 }
1775
1776 int attach_mirror_log(struct lv_segment *seg, struct logical_volume *log_lv)
1777 {
1778         seg->log_lv = log_lv;
1779         log_lv->status |= MIRROR_LOG;
1780         lv_set_hidden(log_lv);
1781         return add_seg_to_segs_using_this_lv(log_lv, seg);
1782 }
1783
1784 int add_mirror_log(struct cmd_context *cmd, struct logical_volume *lv,
1785                    uint32_t log_count, uint32_t region_size,
1786                    struct dm_list *allocatable_pvs, alloc_policy_t alloc)
1787 {
1788         struct alloc_handle *ah;
1789         const struct segment_type *segtype;
1790         struct dm_list *parallel_areas;
1791         percent_t sync_percent;
1792         int in_sync;
1793         struct logical_volume *log_lv;
1794         struct lvinfo info;
1795         int r = 0;
1796
1797         if (dm_list_size(&lv->segments) != 1) {
1798                 log_error("Multiple-segment mirror is not supported");
1799                 return 0;
1800         }
1801
1802         /*
1803          * We are unable to convert the log of inactive cluster mirrors
1804          * due to the inability to detect whether the mirror is active
1805          * on remote nodes (even though it is inactive on this node)
1806          */
1807         if (vg_is_clustered(lv->vg) &&
1808             !(lv_info(cmd, lv, 0, &info, 0, 0) && info.exists)) {
1809                 log_error("Unable to convert the log of inactive "
1810                           "cluster mirror %s", lv->name);
1811                 return 0;
1812         }
1813
1814         if (!(parallel_areas = build_parallel_areas_from_lv(cmd, lv, 0)))
1815                 return_0;
1816
1817         if (!(segtype = get_segtype_from_string(cmd, "mirror")))
1818                 return_0;
1819
1820         if (activation() && segtype->ops->target_present &&
1821             !segtype->ops->target_present(cmd, NULL, NULL)) {
1822                 log_error("%s: Required device-mapper target(s) not "
1823                           "detected in your kernel", segtype->name);
1824                 return 0;
1825         }
1826
1827         /* allocate destination extents */
1828         ah = allocate_extents(lv->vg, NULL, segtype,
1829                               0, 0, log_count, region_size, 0,
1830                               allocatable_pvs, alloc, parallel_areas);
1831         if (!ah) {
1832                 log_error("Unable to allocate extents for mirror log.");
1833                 return 0;
1834         }
1835
1836         /* check sync status */
1837         if (lv_mirror_percent(cmd, lv, 0, &sync_percent, NULL) &&
1838             (sync_percent == PERCENT_100))
1839                 in_sync = 1;
1840         else
1841                 in_sync = 0;
1842
1843         if (!(log_lv = _set_up_mirror_log(cmd, ah, lv, log_count,
1844                                           region_size, alloc, in_sync)))
1845                 goto_out;
1846
1847         if (!attach_mirror_log(first_seg(lv), log_lv))
1848                 goto_out;
1849
1850         r = 1;
1851 out:
1852         alloc_destroy(ah);
1853         return r;
1854 }
1855
1856 /*
1857  * Convert "linear" LV to "mirror".
1858  */
1859 int add_mirror_images(struct cmd_context *cmd, struct logical_volume *lv,
1860                       uint32_t mirrors, uint32_t stripes,
1861                       uint32_t stripe_size, uint32_t region_size,
1862                       struct dm_list *allocatable_pvs, alloc_policy_t alloc,
1863                       uint32_t log_count)
1864 {
1865         struct alloc_handle *ah;
1866         const struct segment_type *segtype;
1867         struct dm_list *parallel_areas;
1868         struct logical_volume *log_lv = NULL;
1869
1870         /*
1871          * allocate destination extents
1872          */
1873
1874         if (!(parallel_areas = build_parallel_areas_from_lv(cmd, lv, 0)))
1875                 return_0;
1876
1877         if (!(segtype = get_segtype_from_string(cmd, "mirror")))
1878                 return_0;
1879
1880         ah = allocate_extents(lv->vg, NULL, segtype,
1881                               stripes, mirrors, log_count, region_size, lv->le_count,
1882                               allocatable_pvs, alloc, parallel_areas);
1883         if (!ah) {
1884                 log_error("Unable to allocate extents for mirror(s).");
1885                 return 0;
1886         }
1887
1888         /*
1889          * create and initialize mirror log
1890          */
1891         if (log_count &&
1892             !(log_lv = _set_up_mirror_log(cmd, ah, lv, log_count,
1893                                           (region_size > lv->vg->extent_size) ?
1894                                           lv->vg->extent_size : region_size,
1895                                           alloc, mirror_in_sync()))) {
1896                 stack;
1897                 goto out_remove_images;
1898         }
1899
1900         /* The log initialization involves vg metadata commit.
1901            So from here on, if failure occurs, the log must be explicitly
1902            removed and the updated vg metadata should be committed. */
1903
1904         if (!_form_mirror(cmd, ah, lv, mirrors, stripes, stripe_size, region_size, 0))
1905                 goto out_remove_log;
1906
1907         if (log_count && !attach_mirror_log(first_seg(lv), log_lv))
1908                 stack;
1909
1910         alloc_destroy(ah);
1911         return 1;
1912
1913   out_remove_log:
1914         if (log_lv) {
1915                 if (!lv_remove(log_lv) ||
1916                     !vg_write(log_lv->vg) ||
1917                     !vg_commit(log_lv->vg))
1918                         log_error("Manual intervention may be required to remove "
1919                                   "abandoned log LV before retrying.");
1920                 else
1921                         backup(log_lv->vg);
1922         }
1923   out_remove_images:
1924         alloc_destroy(ah);
1925         return 0;
1926 }
1927
1928 /*
1929  * Generic interface for adding mirror and/or mirror log.
1930  * 'mirror' is the number of mirrors to be added.
1931  * 'pvs' is either allocatable pvs.
1932  */
1933 int lv_add_mirrors(struct cmd_context *cmd, struct logical_volume *lv,
1934                    uint32_t mirrors, uint32_t stripes, uint32_t stripe_size,
1935                    uint32_t region_size, uint32_t log_count,
1936                    struct dm_list *pvs, alloc_policy_t alloc, uint32_t flags)
1937 {
1938         if (!mirrors && !log_count) {
1939                 log_error("No conversion is requested");
1940                 return 0;
1941         }
1942
1943         if (vg_is_clustered(lv->vg)) {
1944                 if (!(lv->status & ACTIVATE_EXCL) &&
1945                     !cluster_mirror_is_available(lv)) {
1946                         log_error("Shared cluster mirrors are not available.");
1947                         return 0;
1948                 }
1949
1950                 /*
1951                  * No mirrored logs for cluster mirrors until
1952                  * log daemon is multi-threaded.
1953                  */
1954                 if (log_count > 1) {
1955                         log_error("Log type, \"mirrored\", is unavailable to cluster mirrors");
1956                         return 0;
1957                 }
1958         }
1959
1960         /* For corelog mirror, activation code depends on
1961          * the global mirror_in_sync status. As we are adding
1962          * a new mirror, it should be set as 'out-of-sync'
1963          * so that the sync starts. */
1964         /* However, MIRROR_SKIP_INIT_SYNC even overrides it. */
1965         if (flags & MIRROR_SKIP_INIT_SYNC)
1966                 init_mirror_in_sync(1);
1967         else if (!log_count)
1968                 init_mirror_in_sync(0);
1969
1970         if (flags & MIRROR_BY_SEG) {
1971                 if (log_count) {
1972                         log_error("Persistent log is not supported on "
1973                                   "segment-by-segment mirroring");
1974                         return 0;
1975                 }
1976                 if (stripes > 1) {
1977                         log_error("Striped-mirroring is not supported on "
1978                                   "segment-by-segment mirroring");
1979                         return 0;
1980                 }
1981
1982                 return add_mirrors_to_segments(cmd, lv, mirrors,
1983                                                region_size, pvs, alloc);
1984         } else if (flags & MIRROR_BY_LV) {
1985                 if (!mirrors)
1986                         return add_mirror_log(cmd, lv, log_count,
1987                                               region_size, pvs, alloc);
1988                 return add_mirror_images(cmd, lv, mirrors,
1989                                          stripes, stripe_size, region_size,
1990                                          pvs, alloc, log_count);
1991         }
1992
1993         log_error("Unsupported mirror conversion type");
1994         return 0;
1995 }
1996
1997 int lv_split_mirror_images(struct logical_volume *lv, const char *split_name,
1998                            uint32_t split_count, struct dm_list *removable_pvs)
1999 {
2000         int r;
2001
2002         if (find_lv_in_vg(lv->vg, split_name)) {
2003                 log_error("Logical Volume \"%s\" already exists in "
2004                           "volume group \"%s\"", split_name, lv->vg->name);
2005                 return 0;
2006         }
2007
2008         /* Can't split a mirror that is not in-sync... unless force? */
2009         if (!_mirrored_lv_in_sync(lv)) {
2010                 log_error("Unable to split mirror that is not in-sync.");
2011                 return_0;
2012         }
2013
2014         /*
2015          * FIXME: Generate default name when not supplied.
2016          *
2017          * If we were going to generate a default name, we would
2018          * do it here.  Better to wait for a decision on the form
2019          * of the default name when '--track_deltas' (the ability
2020          * to merge a split leg back in and only copy the changes)
2021          * is being implemented.  For now, we force the user to
2022          * come up with a name for their LV.
2023          */
2024         r = _split_mirror_images(lv, split_name, split_count, removable_pvs);
2025         if (!r)
2026                 return 0;
2027
2028         return 1;
2029 }
2030
2031 /*
2032  * Generic interface for removing mirror and/or mirror log.
2033  * 'mirror' is the number of mirrors to be removed.
2034  * 'pvs' is removable pvs.
2035  */
2036 int lv_remove_mirrors(struct cmd_context *cmd __attribute__((unused)),
2037                       struct logical_volume *lv,
2038                       uint32_t mirrors, uint32_t log_count,
2039                       int (*is_removable)(struct logical_volume *, void *),
2040                       void *removable_baton,
2041                       uint64_t status_mask)
2042 {
2043         uint32_t new_mirrors;
2044         struct lv_segment *seg;
2045
2046         if (!mirrors && !log_count) {
2047                 log_error("No conversion is requested");
2048                 return 0;
2049         }
2050
2051         seg = first_seg(lv);
2052         if (!seg_is_mirrored(seg)) {
2053                 log_error("Not a mirror segment");
2054                 return 0;
2055         }
2056
2057         if (lv_mirror_count(lv) <= mirrors) {
2058                 log_error("Removing more than existing: %d <= %d",
2059                           seg->area_count, mirrors);
2060                 return 0;
2061         }
2062         new_mirrors = lv_mirror_count(lv) - mirrors - 1;
2063
2064         /* MIRROR_BY_LV */
2065         if (seg_type(seg, 0) == AREA_LV &&
2066             seg_lv(seg, 0)->status & MIRROR_IMAGE)
2067                 return remove_mirror_images(lv, new_mirrors + 1,
2068                                             is_removable, removable_baton,
2069                                             log_count ? 1U : 0);
2070
2071         /* MIRROR_BY_SEG */
2072         if (log_count) {
2073                 log_error("Persistent log is not supported on "
2074                           "segment-by-segment mirroring");
2075                 return 0;
2076         }
2077         return remove_mirrors_from_segments(lv, new_mirrors, status_mask);
2078 }
2079