]> sourceware.org Git - lvm2.git/blob - tools/toollib.c
f854d17c54d24cf16206b8e76001c535af9f31d0
[lvm2.git] / tools / toollib.c
1 /*
2 * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved.
3 * Copyright (C) 2004-2017 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
14 */
15
16 #include "tools.h"
17 #include "lib/format_text/format-text.h"
18 #include "lib/label/hints.h"
19 #include "lib/device/device_id.h"
20 #include "lib/device/online.h"
21 #include "libdm/misc/dm-ioctl.h"
22
23 #include <sys/stat.h>
24 #include <signal.h>
25 #include <sys/wait.h>
26 #include <sys/utsname.h>
27 #include <mntent.h>
28
29 #define report_log_ret_code(ret_code) report_current_object_cmdlog(REPORT_OBJECT_CMDLOG_NAME, \
30 ((ret_code) == ECMD_PROCESSED) ? REPORT_OBJECT_CMDLOG_SUCCESS \
31 : REPORT_OBJECT_CMDLOG_FAILURE, (ret_code))
32
33 const char *command_name(struct cmd_context *cmd)
34 {
35 return cmd->command->name;
36 }
37
38 static void _sigchld_handler(int sig __attribute__((unused)))
39 {
40 while (wait4(-1, NULL, WNOHANG | WUNTRACED, NULL) > 0) ;
41 }
42
43 /*
44 * returns:
45 * -1 if the fork failed
46 * 0 if the parent
47 * 1 if the child
48 */
49 int become_daemon(struct cmd_context *cmd, int skip_lvm)
50 {
51 static const char _devnull[] = "/dev/null";
52 int null_fd;
53 pid_t pid;
54 struct sigaction act = {
55 .sa_handler = _sigchld_handler,
56 .sa_flags = SA_NOCLDSTOP,
57 };
58
59 log_verbose("Forking background process from command: %s", cmd->cmd_line);
60
61 if (sigaction(SIGCHLD, &act, NULL))
62 log_warn("WARNING: Failed to set SIGCHLD action.");
63
64 if (!skip_lvm)
65 if (!sync_local_dev_names(cmd)) { /* Flush ops and reset dm cookie */
66 log_error("Failed to sync local devices before forking.");
67 return -1;
68 }
69
70 if ((pid = fork()) == -1) {
71 log_error("fork failed: %s", strerror(errno));
72 return -1;
73 }
74
75 /* Parent */
76 if (pid > 0)
77 return 0;
78
79 /* Child */
80 if (setsid() == -1)
81 log_error("Background process failed to setsid: %s",
82 strerror(errno));
83
84 /* Set this to avoid discarding output from background process */
85 // #define DEBUG_CHILD
86
87 #ifndef DEBUG_CHILD
88 if ((null_fd = open(_devnull, O_RDWR)) == -1) {
89 log_sys_error("open", _devnull);
90 _exit(ECMD_FAILED);
91 }
92
93 /* coverity[leaked_handle] don't care */
94 if ((dup2(null_fd, STDIN_FILENO) < 0) || /* reopen stdin */
95 (dup2(null_fd, STDOUT_FILENO) < 0) || /* reopen stdout */
96 (dup2(null_fd, STDERR_FILENO) < 0)) { /* reopen stderr */
97 log_sys_error("dup2", "redirect");
98 (void) close(null_fd);
99 _exit(ECMD_FAILED);
100 }
101
102 if (null_fd > STDERR_FILENO)
103 (void) close(null_fd);
104
105 init_verbose(VERBOSE_BASE_LEVEL);
106 #endif /* DEBUG_CHILD */
107
108 strncpy(*cmd->argv, "(lvm2)", strlen(*cmd->argv));
109
110 if (!skip_lvm) {
111 reset_locking();
112 lvmcache_destroy(cmd, 1, 1);
113 if (!lvmcache_init(cmd))
114 /* FIXME Clean up properly here */
115 _exit(ECMD_FAILED);
116 }
117
118 /* coverity[leaked_handle] null_fd does not leak here */
119 return 1;
120 }
121
122 /*
123 * Strip dev_dir if present
124 */
125 const char *skip_dev_dir(struct cmd_context *cmd, const char *vg_name,
126 unsigned *dev_dir_found)
127 {
128 size_t devdir_len = strlen(cmd->dev_dir);
129 const char *dmdir = dm_dir() + devdir_len;
130 size_t dmdir_len = strlen(dmdir), vglv_sz;
131 char *vgname = NULL, *lvname, *layer, *vglv;
132
133 /* FIXME Do this properly */
134 if (*vg_name == '/')
135 while (vg_name[1] == '/')
136 vg_name++;
137
138 if (strncmp(vg_name, cmd->dev_dir, devdir_len)) {
139 if (dev_dir_found)
140 *dev_dir_found = 0;
141 } else {
142 if (dev_dir_found)
143 *dev_dir_found = 1;
144
145 vg_name += devdir_len;
146 while (*vg_name == '/')
147 vg_name++;
148
149 /* Reformat string if /dev/mapper found */
150 if (!strncmp(vg_name, dmdir, dmdir_len) && vg_name[dmdir_len] == '/') {
151 vg_name += dmdir_len + 1;
152 while (*vg_name == '/')
153 vg_name++;
154
155 if (!dm_split_lvm_name(cmd->mem, vg_name, &vgname, &lvname, &layer) ||
156 *layer) {
157 log_error("skip_dev_dir: Couldn't split up device name %s.",
158 vg_name);
159 return vg_name;
160 }
161 vglv_sz = strlen(vgname) + strlen(lvname) + 2;
162 if (!(vglv = dm_pool_alloc(cmd->mem, vglv_sz)) ||
163 dm_snprintf(vglv, vglv_sz, "%s%s%s", vgname,
164 *lvname ? "/" : "",
165 lvname) < 0) {
166 log_error("vg/lv string alloc failed.");
167 return vg_name;
168 }
169 return vglv;
170 }
171 }
172
173 return vg_name;
174 }
175
176 static int _printed_clustered_vg_advice = 0;
177
178 /*
179 * Three possible results:
180 * a) return 0, skip 0: take the VG, and cmd will end in success
181 * b) return 0, skip 1: skip the VG, and cmd will end in success
182 * c) return 1, skip *: skip the VG, and cmd will end in failure
183 *
184 * Case b is the special case, and includes the following:
185 * . The VG is inconsistent, and the command allows for inconsistent VGs.
186 * . The VG is clustered, the host cannot access clustered VG's,
187 * and the command option has been used to ignore clustered vgs.
188 *
189 * Case c covers the other errors returned when reading the VG.
190 * If *skip is 1, it's OK for the caller to read the list of PVs in the VG.
191 */
192 static int _ignore_vg(struct cmd_context *cmd,
193 uint32_t error_flags, struct volume_group *error_vg,
194 const char *vg_name, struct dm_list *arg_vgnames,
195 uint32_t read_flags, int *skip, int *notfound)
196 {
197 uint32_t read_error = error_flags;
198
199 *skip = 0;
200 *notfound = 0;
201
202 if ((read_error & FAILED_NOTFOUND) && (read_flags & READ_OK_NOTFOUND)) {
203 *notfound = 1;
204 return 0;
205 }
206
207 if (read_error & FAILED_CLUSTERED) {
208 if (arg_vgnames && str_list_match_item(arg_vgnames, vg_name)) {
209 log_error("Cannot access clustered VG %s.", vg_name);
210 if (!_printed_clustered_vg_advice) {
211 _printed_clustered_vg_advice = 1;
212 log_error("See lvmlockd(8) for changing a clvm/clustered VG to a shared VG.");
213 }
214 return 1;
215 } else {
216 log_warn("WARNING: Skipping clustered VG %s.", vg_name);
217 if (!_printed_clustered_vg_advice) {
218 _printed_clustered_vg_advice = 1;
219 log_error("See lvmlockd(8) for changing a clvm/clustered VG to a shared VG.");
220 }
221 *skip = 1;
222 return 0;
223 }
224 }
225
226 if (read_error & FAILED_EXPORTED) {
227 if (arg_vgnames && str_list_match_item(arg_vgnames, vg_name)) {
228 log_error("Volume group %s is exported", vg_name);
229 return 1;
230 } else {
231 read_error &= ~FAILED_EXPORTED; /* Check for other errors */
232 log_verbose("Skipping exported volume group %s", vg_name);
233 *skip = 1;
234 }
235 }
236
237 /*
238 * Commands that operate on "all vgs" shouldn't be bothered by
239 * skipping a foreign VG, and the command shouldn't fail when
240 * one is skipped. But, if the command explicitly asked to
241 * operate on a foreign VG and it's skipped, then the command
242 * would expect to fail.
243 */
244 if (read_error & FAILED_SYSTEMID) {
245 if (arg_vgnames && str_list_match_item(arg_vgnames, vg_name)) {
246 log_error("Cannot access VG %s with system ID %s with %slocal system ID%s%s.",
247 vg_name,
248 error_vg ? error_vg->system_id : "unknown ",
249 cmd->system_id ? "" : "unknown ",
250 cmd->system_id ? " " : "",
251 cmd->system_id ? cmd->system_id : "");
252 return 1;
253 } else {
254 read_error &= ~FAILED_SYSTEMID; /* Check for other errors */
255 log_verbose("Skipping foreign volume group %s", vg_name);
256 *skip = 1;
257 }
258 }
259
260 /*
261 * Accessing a lockd VG when lvmlockd is not used is similar
262 * to accessing a foreign VG.
263 * This is also the point where a command fails if it failed
264 * to acquire the necessary lock from lvmlockd.
265 * The two cases are distinguished by FAILED_LOCK_TYPE (the
266 * VG lock_type requires lvmlockd), and FAILED_LOCK_MODE (the
267 * command failed to acquire the necessary lock.)
268 */
269 if (read_error & (FAILED_LOCK_TYPE | FAILED_LOCK_MODE)) {
270 if (arg_vgnames && str_list_match_item(arg_vgnames, vg_name)) {
271 if (read_error & FAILED_LOCK_TYPE)
272 log_error("Cannot access VG %s with lock type %s that requires lvmlockd.",
273 vg_name,
274 error_vg ? error_vg->lock_type : "unknown");
275 /* For FAILED_LOCK_MODE, the error is printed in vg_read. */
276 return 1;
277 } else {
278 read_error &= ~FAILED_LOCK_TYPE; /* Check for other errors */
279 read_error &= ~FAILED_LOCK_MODE;
280 log_verbose("Skipping volume group %s", vg_name);
281 *skip = 1;
282 }
283 }
284
285 if (read_error != SUCCESS) {
286 *skip = 0;
287 if (is_orphan_vg(vg_name))
288 log_error("Cannot process standalone physical volumes");
289 else
290 log_error("Cannot process volume group %s", vg_name);
291 return 1;
292 }
293
294 return 0;
295 }
296
297 /*
298 * This function updates the "selected" arg only if last item processed
299 * is selected so this implements the "whole structure is selected if
300 * at least one of its items is selected".
301 */
302 static void _update_selection_result(struct processing_handle *handle, int *selected)
303 {
304 if (!handle || !handle->selection_handle)
305 return;
306
307 if (handle->selection_handle->selected)
308 *selected = 1;
309 }
310
311 static void _set_final_selection_result(struct processing_handle *handle, int selected)
312 {
313 if (!handle || !handle->selection_handle)
314 return;
315
316 handle->selection_handle->selected = selected;
317 }
318
319 /*
320 * Metadata iteration functions
321 */
322 int process_each_segment_in_pv(struct cmd_context *cmd,
323 struct volume_group *vg,
324 struct physical_volume *pv,
325 struct processing_handle *handle,
326 process_single_pvseg_fn_t process_single_pvseg)
327 {
328 struct pv_segment *pvseg;
329 int whole_selected = 0;
330 int ret_max = ECMD_PROCESSED;
331 int ret;
332 struct pv_segment _free_pv_segment = { .pv = pv };
333
334 if (dm_list_empty(&pv->segments)) {
335 ret = process_single_pvseg(cmd, NULL, &_free_pv_segment, handle);
336 if (ret != ECMD_PROCESSED)
337 stack;
338 if (ret > ret_max)
339 ret_max = ret;
340 } else {
341 dm_list_iterate_items(pvseg, &pv->segments) {
342 if (sigint_caught())
343 return_ECMD_FAILED;
344
345 ret = process_single_pvseg(cmd, vg, pvseg, handle);
346 _update_selection_result(handle, &whole_selected);
347 if (ret != ECMD_PROCESSED)
348 stack;
349 if (ret > ret_max)
350 ret_max = ret;
351 }
352 }
353
354 /* the PV is selected if at least one PV segment is selected */
355 _set_final_selection_result(handle, whole_selected);
356 return ret_max;
357 }
358
359 int process_each_segment_in_lv(struct cmd_context *cmd,
360 struct logical_volume *lv,
361 struct processing_handle *handle,
362 process_single_seg_fn_t process_single_seg)
363 {
364 struct lv_segment *seg;
365 int whole_selected = 0;
366 int ret_max = ECMD_PROCESSED;
367 int ret;
368
369 dm_list_iterate_items(seg, &lv->segments) {
370 if (sigint_caught())
371 return_ECMD_FAILED;
372
373 ret = process_single_seg(cmd, seg, handle);
374 _update_selection_result(handle, &whole_selected);
375 if (ret != ECMD_PROCESSED)
376 stack;
377 if (ret > ret_max)
378 ret_max = ret;
379 }
380
381 /* the LV is selected if at least one LV segment is selected */
382 _set_final_selection_result(handle, whole_selected);
383 return ret_max;
384 }
385
386 static const char *_extract_vgname(struct cmd_context *cmd, const char *lv_name,
387 const char **after)
388 {
389 const char *vg_name = lv_name;
390 char *st, *pos;
391
392 /* Strip dev_dir (optional) */
393 if (!(vg_name = skip_dev_dir(cmd, vg_name, NULL)))
394 return_0;
395
396 /* Require exactly one set of consecutive slashes */
397 if ((st = pos = strchr(vg_name, '/')))
398 while (*st == '/')
399 st++;
400
401 if (!st || strchr(st, '/')) {
402 log_error("\"%s\": Invalid path for Logical Volume.",
403 lv_name);
404 return 0;
405 }
406
407 if (!(vg_name = dm_pool_strndup(cmd->mem, vg_name, pos - vg_name))) {
408 log_error("Allocation of vg_name failed.");
409 return 0;
410 }
411
412 if (after)
413 *after = st;
414
415 return vg_name;
416 }
417
418 /*
419 * Extract default volume group name from environment
420 */
421 static const char *_default_vgname(struct cmd_context *cmd)
422 {
423 const char *vg_path;
424
425 /* Take default VG from environment? */
426 vg_path = getenv("LVM_VG_NAME");
427 if (!vg_path)
428 return 0;
429
430 vg_path = skip_dev_dir(cmd, vg_path, NULL);
431
432 if (strchr(vg_path, '/')) {
433 log_error("\"%s\": Invalid environment var LVM_VG_NAME set for Volume Group.",
434 vg_path);
435 return 0;
436 }
437
438 return dm_pool_strdup(cmd->mem, vg_path);
439 }
440
441 /*
442 * Determine volume group name from a logical volume name
443 */
444 const char *extract_vgname(struct cmd_context *cmd, const char *lv_name)
445 {
446 const char *vg_name = lv_name;
447
448 /* Path supplied? */
449 if (vg_name && strchr(vg_name, '/')) {
450 if (!(vg_name = _extract_vgname(cmd, lv_name, NULL)))
451 return_NULL;
452
453 return vg_name;
454 }
455
456 if (!(vg_name = _default_vgname(cmd))) {
457 if (lv_name)
458 log_error("Path required for Logical Volume \"%s\".",
459 lv_name);
460 return NULL;
461 }
462
463 return vg_name;
464 }
465
466 static const char _pe_size_may_not_be_negative_msg[] = "Physical extent size may not be negative.";
467
468 int vgcreate_params_set_defaults(struct cmd_context *cmd,
469 struct vgcreate_params *vp_def,
470 struct volume_group *vg)
471 {
472 int64_t extent_size;
473
474 /* Only vgsplit sets vg */
475 if (vg) {
476 vp_def->vg_name = NULL;
477 vp_def->extent_size = vg->extent_size;
478 vp_def->max_pv = vg->max_pv;
479 vp_def->max_lv = vg->max_lv;
480 vp_def->alloc = vg->alloc;
481 vp_def->vgmetadatacopies = vg->mda_copies;
482 vp_def->system_id = vg->system_id; /* No need to clone this */
483 } else {
484 vp_def->vg_name = NULL;
485 extent_size = find_config_tree_int64(cmd,
486 allocation_physical_extent_size_CFG, NULL) * 2;
487 if (extent_size < 0) {
488 log_error(_pe_size_may_not_be_negative_msg);
489 return 0;
490 }
491 vp_def->extent_size = (uint32_t) extent_size;
492 vp_def->max_pv = DEFAULT_MAX_PV;
493 vp_def->max_lv = DEFAULT_MAX_LV;
494 vp_def->alloc = DEFAULT_ALLOC_POLICY;
495 vp_def->vgmetadatacopies = DEFAULT_VGMETADATACOPIES;
496 vp_def->system_id = cmd->system_id;
497 }
498
499 return 1;
500 }
501
502 /*
503 * Set members of struct vgcreate_params from cmdline arguments.
504 * Do preliminary validation with arg_*() interface.
505 * Further, more generic validation is done in validate_vgcreate_params().
506 * This function is to remain in tools directory.
507 */
508 int vgcreate_params_set_from_args(struct cmd_context *cmd,
509 struct vgcreate_params *vp_new,
510 struct vgcreate_params *vp_def)
511 {
512 const char *system_id_arg_str;
513 const char *lock_type = NULL;
514 int use_lvmlockd;
515 lock_type_t lock_type_num;
516
517 if (arg_is_set(cmd, clustered_ARG)) {
518 log_error("The clustered option is deprecated, see --shared.");
519 return 0;
520 }
521
522 vp_new->vg_name = skip_dev_dir(cmd, vp_def->vg_name, NULL);
523 vp_new->max_lv = arg_uint_value(cmd, maxlogicalvolumes_ARG,
524 vp_def->max_lv);
525 vp_new->max_pv = arg_uint_value(cmd, maxphysicalvolumes_ARG,
526 vp_def->max_pv);
527 vp_new->alloc = (alloc_policy_t) arg_uint_value(cmd, alloc_ARG, vp_def->alloc);
528
529 /* Units of 512-byte sectors */
530 vp_new->extent_size =
531 arg_uint_value(cmd, physicalextentsize_ARG, vp_def->extent_size);
532
533 if (arg_sign_value(cmd, physicalextentsize_ARG, SIGN_NONE) == SIGN_MINUS) {
534 log_error(_pe_size_may_not_be_negative_msg);
535 return 0;
536 }
537
538 if (arg_uint64_value(cmd, physicalextentsize_ARG, 0) > MAX_EXTENT_SIZE) {
539 log_error("Physical extent size must be smaller than %s.",
540 display_size(cmd, (uint64_t) MAX_EXTENT_SIZE));
541 return 0;
542 }
543
544 if (arg_sign_value(cmd, maxlogicalvolumes_ARG, SIGN_NONE) == SIGN_MINUS) {
545 log_error("Max Logical Volumes may not be negative.");
546 return 0;
547 }
548
549 if (arg_sign_value(cmd, maxphysicalvolumes_ARG, SIGN_NONE) == SIGN_MINUS) {
550 log_error("Max Physical Volumes may not be negative.");
551 return 0;
552 }
553
554 if (arg_is_set(cmd, vgmetadatacopies_ARG))
555 vp_new->vgmetadatacopies = arg_int_value(cmd, vgmetadatacopies_ARG,
556 DEFAULT_VGMETADATACOPIES);
557 else
558 vp_new->vgmetadatacopies = find_config_tree_int(cmd, metadata_vgmetadatacopies_CFG, NULL);
559
560 if (!(system_id_arg_str = arg_str_value(cmd, systemid_ARG, NULL))) {
561 vp_new->system_id = vp_def->system_id;
562 } else {
563 if (!(vp_new->system_id = system_id_from_string(cmd, system_id_arg_str)))
564 return_0;
565
566 /* FIXME Take local/extra_system_ids into account */
567 if (vp_new->system_id && cmd->system_id &&
568 strcmp(vp_new->system_id, cmd->system_id)) {
569 if (*vp_new->system_id)
570 log_warn("WARNING: VG with system ID %s might become inaccessible as local system ID is %s",
571 vp_new->system_id, cmd->system_id);
572 else
573 log_warn("WARNING: A VG without a system ID allows unsafe access from other hosts.");
574 }
575 }
576
577 if ((system_id_arg_str = arg_str_value(cmd, systemid_ARG, NULL))) {
578 vp_new->system_id = system_id_from_string(cmd, system_id_arg_str);
579 } else {
580 vp_new->system_id = vp_def->system_id;
581 }
582
583 if (system_id_arg_str) {
584 if (!vp_new->system_id || !vp_new->system_id[0])
585 log_warn("WARNING: A VG without a system ID allows unsafe access from other hosts.");
586
587 if (vp_new->system_id && cmd->system_id &&
588 strcmp(vp_new->system_id, cmd->system_id)) {
589 log_warn("WARNING: VG with system ID %s might become inaccessible as local system ID is %s",
590 vp_new->system_id, cmd->system_id);
591 }
592 }
593
594 /*
595 * Locking: what kind of locking should be used for the
596 * new VG, and is it compatible with current lvm.conf settings.
597 *
598 * The end result is to set vp_new->lock_type to:
599 * none | clvm | dlm | sanlock | idm.
600 *
601 * If 'vgcreate --lock-type <arg>' is set, the answer is given
602 * directly by <arg> which is one of none|clvm|dlm|sanlock|idm.
603 *
604 * 'vgcreate --clustered y' is the way to create clvm VGs.
605 *
606 * 'vgcreate --shared' is the way to create lockd VGs.
607 * lock_type of sanlock, dlm or idm is selected based on
608 * which lock manager is running.
609 *
610 *
611 * 1. Using neither clvmd nor lvmlockd.
612 * ------------------------------------------------
613 * lvm.conf:
614 * global/use_lvmlockd = 0
615 * global/locking_type = 1
616 *
617 * - no locking is enabled
618 * - clvmd is not used
619 * - lvmlockd is not used
620 * - VGs with CLUSTERED set are ignored (requires clvmd)
621 * - VGs with lockd type are ignored (requires lvmlockd)
622 * - vgcreate can create new VGs with lock_type none
623 * - 'vgcreate --clustered y' fails
624 * - 'vgcreate --shared' fails
625 * - 'vgcreate' (neither option) creates a local VG
626 *
627 * 2. Using clvmd.
628 * ------------------------------------------------
629 * lvm.conf:
630 * global/use_lvmlockd = 0
631 * global/locking_type = 3
632 *
633 * - locking through clvmd is enabled (traditional clvm config)
634 * - clvmd is used
635 * - lvmlockd is not used
636 * - VGs with CLUSTERED set can be used
637 * - VGs with lockd type are ignored (requires lvmlockd)
638 * - vgcreate can create new VGs with CLUSTERED status flag
639 * - 'vgcreate --clustered y' works
640 * - 'vgcreate --shared' fails
641 * - 'vgcreate' (neither option) creates a clvm VG
642 *
643 * 3. Using lvmlockd.
644 * ------------------------------------------------
645 * lvm.conf:
646 * global/use_lvmlockd = 1
647 * global/locking_type = 1
648 *
649 * - locking through lvmlockd is enabled
650 * - clvmd is not used
651 * - lvmlockd is used
652 * - VGs with CLUSTERED set are ignored (requires clvmd)
653 * - VGs with lockd type can be used
654 * - vgcreate can create new VGs with lock_type sanlock, dlm or idm
655 * - 'vgcreate --clustered y' fails
656 * - 'vgcreate --shared' works
657 * - 'vgcreate' (neither option) creates a local VG
658 */
659
660 use_lvmlockd = find_config_tree_bool(cmd, global_use_lvmlockd_CFG, NULL);
661
662 if (arg_is_set(cmd, locktype_ARG)) {
663 lock_type = arg_str_value(cmd, locktype_ARG, "");
664
665 if (arg_is_set(cmd, shared_ARG) && !is_lockd_type(lock_type)) {
666 log_error("The --shared option requires lock type sanlock, dlm or idm.");
667 return 0;
668 }
669
670 } else if (arg_is_set(cmd, shared_ARG)) {
671 int found_multiple = 0;
672
673 if (use_lvmlockd) {
674 if (!(lock_type = lockd_running_lock_type(cmd, &found_multiple))) {
675 if (found_multiple)
676 log_error("Found multiple lock managers, select one with --lock-type.");
677 else
678 log_error("Failed to detect a running lock manager to select lock type.");
679 return 0;
680 }
681
682 } else {
683 log_error("Using a shared lock type requires lvmlockd (lvm.conf use_lvmlockd.)");
684 return 0;
685 }
686
687 } else {
688 lock_type = "none";
689 }
690
691 /*
692 * Check that the lock_type is recognized, and is being
693 * used with the correct lvm.conf settings.
694 */
695 lock_type_num = get_lock_type_from_string(lock_type);
696
697 switch (lock_type_num) {
698 case LOCK_TYPE_INVALID:
699 case LOCK_TYPE_CLVM:
700 log_error("lock_type %s is invalid", lock_type);
701 return 0;
702
703 case LOCK_TYPE_SANLOCK:
704 case LOCK_TYPE_DLM:
705 case LOCK_TYPE_IDM:
706 if (!use_lvmlockd) {
707 log_error("Using a shared lock type requires lvmlockd.");
708 return 0;
709 }
710 break;
711 case LOCK_TYPE_NONE:
712 break;
713 };
714
715 /*
716 * The vg is not owned by one host/system_id.
717 * Locking coordinates access from multiple hosts.
718 */
719 if (lock_type_num == LOCK_TYPE_DLM || lock_type_num == LOCK_TYPE_SANLOCK)
720 vp_new->system_id = NULL;
721
722 vp_new->lock_type = lock_type;
723
724 log_debug("Setting lock_type to %s", vp_new->lock_type);
725 return 1;
726 }
727
728 /* Shared code for changing activation state for vgchange/lvchange */
729 int lv_change_activate(struct cmd_context *cmd, struct logical_volume *lv,
730 activation_change_t activate)
731 {
732 int r = 1;
733 int integrity_recalculate;
734 struct logical_volume *snapshot_lv;
735
736 if (lv_is_cache_pool(lv)) {
737 if (is_change_activating(activate)) {
738 log_verbose("Skipping activation of cache pool %s.",
739 display_lvname(lv));
740 return 1;
741 }
742 if (!dm_list_empty(&lv->segs_using_this_lv)) {
743 log_verbose("Skipping deactivation of used cache pool %s.",
744 display_lvname(lv));
745 return 1;
746 }
747 /*
748 * Allow to pass only deactivation of unused cache pool.
749 * Useful only for recovery of failed zeroing of metadata LV.
750 */
751 }
752
753 if (lv_is_merging_origin(lv)) {
754 /*
755 * For merging origin, its snapshot must be inactive.
756 * If it's still active and cannot be deactivated
757 * activation or deactivation of origin fails!
758 *
759 * When origin is deactivated and merging snapshot is thin
760 * it allows to deactivate origin, but still report error,
761 * since the thin snapshot remains active.
762 *
763 * User could retry to deactivate it with another
764 * deactivation of origin, which is the only visible LV
765 */
766 snapshot_lv = find_snapshot(lv)->lv;
767 if (lv_is_thin_type(snapshot_lv) && !deactivate_lv(cmd, snapshot_lv)) {
768 if (is_change_activating(activate)) {
769 log_error("Refusing to activate merging volume %s while "
770 "snapshot volume %s is still active.",
771 display_lvname(lv), display_lvname(snapshot_lv));
772 return 0;
773 }
774
775 log_error("Cannot fully deactivate merging origin volume %s while "
776 "snapshot volume %s is still active.",
777 display_lvname(lv), display_lvname(snapshot_lv));
778 r = 0; /* and continue to deactivate origin... */
779 }
780 }
781
782 if (is_change_activating(activate) &&
783 lvmcache_has_duplicate_devs() &&
784 vg_has_duplicate_pvs(lv->vg) &&
785 !find_config_tree_bool(cmd, devices_allow_changes_with_duplicate_pvs_CFG, NULL)) {
786 log_error("Cannot activate LVs in VG %s while PVs appear on duplicate devices.",
787 lv->vg->name);
788 return 0;
789 }
790
791 if ((integrity_recalculate = lv_has_integrity_recalculate_metadata(lv))) {
792 /* Don't want pvscan to write VG while running from systemd service. */
793 if (!strcmp(cmd->name, "pvscan")) {
794 log_error("Cannot activate uninitialized integrity LV %s from pvscan.",
795 display_lvname(lv));
796 return 0;
797 }
798
799 if (vg_is_shared(lv->vg)) {
800 uint32_t lockd_state = 0;
801 if (!lockd_vg(cmd, lv->vg->name, "ex", 0, &lockd_state)) {
802 log_error("Cannot activate uninitialized integrity LV %s without lock.",
803 display_lvname(lv));
804 return 0;
805 }
806 }
807 }
808
809 if (!lv_active_change(cmd, lv, activate))
810 return_0;
811
812 /* Write VG metadata to clear the integrity recalculate flag. */
813 if (integrity_recalculate && lv_is_active(lv)) {
814 log_print_unless_silent("Updating VG to complete initialization of integrity LV %s.",
815 display_lvname(lv));
816 lv_clear_integrity_recalculate_metadata(lv);
817 }
818
819 /*
820 * When LVs are deactivated, then autoactivation of the VG is
821 * "re-armed" by removing the vg online file. So, after deactivation
822 * of LVs, if PVs are disconnected and reconnected again, event
823 * activation will trigger autoactivation again. This secondary
824 * autoactivation is somewhat different from, and not as important as
825 * the initial autoactivation during system startup. The secondary
826 * autoactivation will happen to a VG on a running system and may be
827 * mixing with user commands, so the end result is unpredictable.
828 *
829 * It's possible that we might want a config setting for users to
830 * disable secondary autoactivations. Once a system is up, the
831 * user may want to take charge of activation changes to the VG
832 * and not have the system autoactivation interfere.
833 */
834 if (!is_change_activating(activate) && cmd->event_activation &&
835 !cmd->online_vg_file_removed) {
836 cmd->online_vg_file_removed = 1;
837 online_vg_file_remove(lv->vg->name);
838 }
839
840 set_lv_notify(lv->vg->cmd);
841
842 return r;
843 }
844
845 int lv_refresh(struct cmd_context *cmd, struct logical_volume *lv)
846 {
847 struct logical_volume *snapshot_lv;
848
849 if (lv_is_merging_origin(lv)) {
850 snapshot_lv = find_snapshot(lv)->lv;
851 if (lv_is_thin_type(snapshot_lv) && !deactivate_lv(cmd, snapshot_lv))
852 log_print_unless_silent("Delaying merge for origin volume %s since "
853 "snapshot volume %s is still active.",
854 display_lvname(lv), display_lvname(snapshot_lv));
855 }
856
857 if (!lv_refresh_suspend_resume(lv))
858 return_0;
859
860 /*
861 * check if snapshot merge should be polled
862 * - unfortunately: even though the dev_manager will clear
863 * the lv's merge attributes if a merge is not possible;
864 * it is clearing a different instance of the lv (as
865 * retrieved with lv_from_lvid)
866 * - fortunately: polldaemon will immediately shutdown if the
867 * origin doesn't have a status with a snapshot percentage
868 */
869 if (background_polling() && lv_is_merging_origin(lv) && lv_is_active(lv))
870 lv_spawn_background_polling(cmd, lv);
871
872 return 1;
873 }
874
875 int vg_refresh_visible(struct cmd_context *cmd, struct volume_group *vg)
876 {
877 struct lv_list *lvl;
878 int r = 1;
879
880 sigint_allow();
881 dm_list_iterate_items(lvl, &vg->lvs) {
882 if (sigint_caught()) {
883 r = 0;
884 stack;
885 break;
886 }
887
888 if (lv_is_visible(lvl->lv) &&
889 !(lv_is_cow(lvl->lv) && !lv_is_virtual_origin(origin_from_cow(lvl->lv))) &&
890 !lv_refresh(cmd, lvl->lv)) {
891 r = 0;
892 stack;
893 }
894 }
895
896 sigint_restore();
897
898 return r;
899 }
900
901 void lv_spawn_background_polling(struct cmd_context *cmd,
902 struct logical_volume *lv)
903 {
904 const char *pvname;
905 const struct logical_volume *lv_mirr = NULL;
906
907 /* Ensure there is nothing waiting on cookie */
908 if (!sync_local_dev_names(cmd))
909 log_warn("WARNING: Failed to sync local dev names.");
910
911 if (lv_is_pvmove(lv))
912 lv_mirr = lv;
913 else if (lv_is_locked(lv))
914 lv_mirr = find_pvmove_lv_in_lv(lv);
915
916 if (lv_mirr &&
917 (pvname = get_pvmove_pvname_from_lv_mirr(lv_mirr))) {
918 log_verbose("Spawning background pvmove process for %s.",
919 pvname);
920 pvmove_poll(cmd, pvname, lv_mirr->lvid.s, lv_mirr->vg->name, lv_mirr->name, 1);
921 }
922
923 if (lv_is_converting(lv) || lv_is_merging(lv)) {
924 log_verbose("Spawning background lvconvert process for %s.",
925 lv->name);
926 lvconvert_poll(cmd, lv, 1);
927 }
928 }
929
930 int get_activation_monitoring_mode(struct cmd_context *cmd,
931 int *monitoring_mode)
932 {
933 *monitoring_mode = DEFAULT_DMEVENTD_MONITOR;
934
935 if (arg_is_set(cmd, monitor_ARG) &&
936 (arg_is_set(cmd, ignoremonitoring_ARG) ||
937 arg_is_set(cmd, sysinit_ARG))) {
938 log_error("--ignoremonitoring or --sysinit option not allowed with --monitor option.");
939 return 0;
940 }
941
942 if (arg_is_set(cmd, monitor_ARG))
943 *monitoring_mode = arg_int_value(cmd, monitor_ARG,
944 DEFAULT_DMEVENTD_MONITOR);
945 else if (is_static() || arg_is_set(cmd, ignoremonitoring_ARG) ||
946 arg_is_set(cmd, sysinit_ARG) ||
947 !find_config_tree_bool(cmd, activation_monitoring_CFG, NULL))
948 *monitoring_mode = DMEVENTD_MONITOR_IGNORE;
949
950 return 1;
951 }
952
953 /*
954 * Read pool options from cmdline
955 */
956 int get_pool_params(struct cmd_context *cmd,
957 const struct segment_type *segtype,
958 int *pool_data_vdo,
959 uint64_t *pool_metadata_size,
960 int *pool_metadata_spare,
961 uint32_t *chunk_size,
962 thin_discards_t *discards,
963 thin_zero_t *zero_new_blocks)
964 {
965 if ((*pool_data_vdo = arg_int_value(cmd, pooldatavdo_ARG, 0))) {
966 if (!(segtype = get_segtype_from_string(cmd, SEG_TYPE_NAME_VDO)))
967 return_0;
968
969 if (activation() && segtype->ops->target_present) {
970 if (!segtype->ops->target_present(cmd, NULL, NULL)) {
971 log_error("%s: Required device-mapper target(s) not detected in your kernel.",
972 segtype->name);
973 return_0;
974 }
975 }
976 }
977
978 if (segtype_is_thin_pool(segtype) || segtype_is_thin(segtype) || *pool_data_vdo) {
979 if (arg_is_set(cmd, zero_ARG)) {
980 *zero_new_blocks = arg_int_value(cmd, zero_ARG, 0) ? THIN_ZERO_YES : THIN_ZERO_NO;
981 log_very_verbose("%s pool zeroing.",
982 (*zero_new_blocks == THIN_ZERO_YES) ? "Enabling" : "Disabling");
983 } else
984 *zero_new_blocks = THIN_ZERO_UNSELECTED;
985
986 if (arg_is_set(cmd, discards_ARG)) {
987 *discards = (thin_discards_t) arg_uint_value(cmd, discards_ARG, 0);
988 log_very_verbose("Setting pool discards to %s.",
989 get_pool_discards_name(*discards));
990 } else
991 *discards = THIN_DISCARDS_UNSELECTED;
992 }
993
994 if (arg_from_list_is_negative(cmd, "may not be negative",
995 chunksize_ARG,
996 pooldatasize_ARG,
997 poolmetadatasize_ARG,
998 -1))
999 return_0;
1000
1001 if (arg_from_list_is_zero(cmd, "may not be zero",
1002 chunksize_ARG,
1003 pooldatasize_ARG,
1004 poolmetadatasize_ARG,
1005 -1))
1006 return_0;
1007
1008 if (arg_is_set(cmd, chunksize_ARG)) {
1009 *chunk_size = arg_uint_value(cmd, chunksize_ARG, 0);
1010
1011 if (!validate_pool_chunk_size(cmd, segtype, *chunk_size))
1012 return_0;
1013
1014 log_very_verbose("Setting pool chunk size to %s.",
1015 display_size(cmd, *chunk_size));
1016 } else
1017 *chunk_size = 0;
1018
1019 if (arg_is_set(cmd, poolmetadatasize_ARG)) {
1020 if (arg_is_set(cmd, poolmetadata_ARG)) {
1021 log_error("Please specify either metadata logical volume or its size.");
1022 return 0;
1023 }
1024
1025 *pool_metadata_size = arg_uint64_value(cmd, poolmetadatasize_ARG,
1026 UINT64_C(0));
1027 } else
1028 *pool_metadata_size = 0;
1029
1030 /* TODO: default in lvm.conf and metadata profile ? */
1031 *pool_metadata_spare = arg_int_value(cmd, poolmetadataspare_ARG,
1032 DEFAULT_POOL_METADATA_SPARE);
1033
1034 return 1;
1035 }
1036
1037 /*
1038 * Generic stripe parameter checks.
1039 */
1040 static int _validate_stripe_params(struct cmd_context *cmd, const struct segment_type *segtype,
1041 uint32_t *stripes, uint32_t *stripe_size)
1042 {
1043 if (*stripes < 1 || *stripes > MAX_STRIPES) {
1044 log_error("Number of stripes (%d) must be between %d and %d.",
1045 *stripes, 1, MAX_STRIPES);
1046 return 0;
1047 }
1048
1049 if (!segtype_supports_stripe_size(segtype)) {
1050 if (*stripe_size) {
1051 log_print_unless_silent("Ignoring stripesize argument for %s devices.",
1052 segtype->name);
1053 *stripe_size = 0;
1054 }
1055 } else if (*stripes == 1) {
1056 if (*stripe_size) {
1057 log_print_unless_silent("Ignoring stripesize argument with single stripe.");
1058 *stripe_size = 0;
1059 }
1060 } else {
1061 if (!*stripe_size) {
1062 *stripe_size = find_config_tree_int(cmd, metadata_stripesize_CFG, NULL) * 2;
1063 log_print_unless_silent("Using default stripesize %s.",
1064 display_size(cmd, (uint64_t) *stripe_size));
1065 }
1066
1067 if (*stripe_size > STRIPE_SIZE_LIMIT * 2) {
1068 log_error("Stripe size cannot be larger than %s.",
1069 display_size(cmd, (uint64_t) STRIPE_SIZE_LIMIT));
1070 return 0;
1071 } else if (*stripe_size < STRIPE_SIZE_MIN || !is_power_of_2(*stripe_size)) {
1072 log_error("Invalid stripe size %s.",
1073 display_size(cmd, (uint64_t) *stripe_size));
1074 return 0;
1075 }
1076 }
1077
1078 return 1;
1079 }
1080
1081 /*
1082 * The stripe size is limited by the size of a uint32_t, but since the
1083 * value given by the user is doubled, and the final result must be a
1084 * power of 2, we must divide UINT_MAX by four and add 1 (to round it
1085 * up to the power of 2)
1086 */
1087 int get_stripe_params(struct cmd_context *cmd, const struct segment_type *segtype,
1088 uint32_t *stripes, uint32_t *stripe_size,
1089 unsigned *stripes_supplied, unsigned *stripe_size_supplied)
1090 {
1091 /* stripes_long_ARG takes precedence (for lvconvert) */
1092 /* FIXME Cope with relative +/- changes for lvconvert. */
1093 if (arg_is_set(cmd, stripes_long_ARG)) {
1094 *stripes = arg_uint_value(cmd, stripes_long_ARG, 0);
1095 *stripes_supplied = 1;
1096 } else if (arg_is_set(cmd, stripes_ARG)) {
1097 *stripes = arg_uint_value(cmd, stripes_ARG, 0);
1098 *stripes_supplied = 1;
1099 } else {
1100 /*
1101 * FIXME add segtype parameter for min_stripes and remove logic for this
1102 * from all other places
1103 */
1104 if (segtype_is_any_raid6(segtype))
1105 *stripes = 3;
1106 else if (segtype_is_striped_raid(segtype))
1107 *stripes = 2;
1108 else
1109 *stripes = 1;
1110 *stripes_supplied = 0;
1111 }
1112
1113 if ((*stripe_size = arg_uint_value(cmd, stripesize_ARG, 0))) {
1114 if (arg_sign_value(cmd, stripesize_ARG, SIGN_NONE) == SIGN_MINUS) {
1115 log_error("Negative stripesize is invalid.");
1116 return 0;
1117 }
1118 }
1119 *stripe_size_supplied = arg_is_set(cmd, stripesize_ARG);
1120
1121 return _validate_stripe_params(cmd, segtype, stripes, stripe_size);
1122 }
1123
1124 static int _validate_cachepool_params(const char *policy_name, cache_mode_t cache_mode)
1125 {
1126 /*
1127 * FIXME: it might be nice if cmd def rules could check option values,
1128 * then a rule could do this.
1129 */
1130 if ((cache_mode == CACHE_MODE_WRITEBACK) && policy_name && !strcmp(policy_name, "cleaner")) {
1131 log_error("Cache mode \"writeback\" is not compatible with cache policy \"cleaner\".");
1132 return 0;
1133 }
1134
1135 return 1;
1136 }
1137
1138 int get_cache_params(struct cmd_context *cmd,
1139 uint32_t *chunk_size,
1140 cache_metadata_format_t *cache_metadata_format,
1141 cache_mode_t *cache_mode,
1142 const char **name,
1143 struct dm_config_tree **settings)
1144 {
1145 const char *str;
1146 struct arg_value_group_list *group;
1147 struct dm_config_tree *result = NULL, *prev = NULL, *current = NULL;
1148 struct dm_config_node *cn;
1149 int ok = 0;
1150
1151 if (arg_is_set(cmd, chunksize_ARG)) {
1152 *chunk_size = arg_uint_value(cmd, chunksize_ARG, 0);
1153
1154 if (!validate_cache_chunk_size(cmd, *chunk_size))
1155 return_0;
1156
1157 log_very_verbose("Setting pool chunk size to %s.",
1158 display_size(cmd, *chunk_size));
1159 }
1160
1161 *cache_metadata_format = (cache_metadata_format_t)
1162 arg_uint_value(cmd, cachemetadataformat_ARG, CACHE_METADATA_FORMAT_UNSELECTED);
1163
1164 *cache_mode = (cache_mode_t) arg_uint_value(cmd, cachemode_ARG, CACHE_MODE_UNSELECTED);
1165
1166 *name = arg_str_value(cmd, cachepolicy_ARG, NULL);
1167
1168 if (!_validate_cachepool_params(*name, *cache_mode))
1169 goto_out;
1170
1171 dm_list_iterate_items(group, &cmd->arg_value_groups) {
1172 if (!grouped_arg_is_set(group->arg_values, cachesettings_ARG))
1173 continue;
1174
1175 if (!(current = dm_config_create()))
1176 goto_out;
1177 if (prev)
1178 current->cascade = prev;
1179 prev = current;
1180
1181 if (!(str = grouped_arg_str_value(group->arg_values,
1182 cachesettings_ARG,
1183 NULL)))
1184 goto_out;
1185
1186 if (!dm_config_parse_without_dup_node_check(current, str, str + strlen(str)))
1187 goto_out;
1188 }
1189
1190 if (current) {
1191 if (!(result = dm_config_flatten(current)))
1192 goto_out;
1193
1194 if (result->root) {
1195 if (!(cn = dm_config_create_node(result, "policy_settings")))
1196 goto_out;
1197
1198 cn->child = result->root;
1199 result->root = cn;
1200 }
1201 }
1202
1203 ok = 1;
1204 out:
1205 if (!ok && result) {
1206 dm_config_destroy(result);
1207 result = NULL;
1208 }
1209 while (prev) {
1210 current = prev->cascade;
1211 dm_config_destroy(prev);
1212 prev = current;
1213 }
1214
1215 *settings = result;
1216
1217 return ok;
1218 }
1219
1220 /*
1221 * Compare VDO option name, skip any '_' in name
1222 * and also allow to use it without vdo_[use_] prefix
1223 */
1224 static int _compare_vdo_option(const char *b1, const char *b2)
1225 {
1226 int use_skipped = 0;
1227
1228 if (strncasecmp(b1, "vdo", 3) == 0) // skip vdo prefix
1229 b1 += 3;
1230
1231 while (*b1 && *b2) {
1232 if (tolower(*b1) == tolower(*b2)) {
1233 ++b1;
1234 ++b2;
1235 continue; // matching char
1236 }
1237
1238 if (*b1 == '_')
1239 ++b1; // skip to next char
1240 else if (*b2 == '_')
1241 ++b2; // skip to next char
1242 else {
1243 if (!use_skipped++ && (strncmp(b2, "use_", 4) == 0)) {
1244 b2 += 4; // try again with skipped prefix 'use_'
1245 continue;
1246 }
1247
1248 break; // mismatch
1249 }
1250 }
1251
1252 return (*b1 || *b2) ? 0 : 1;
1253 }
1254
1255 #define CHECK_AND_SET(var, onoff) \
1256 option = #var;\
1257 if (_compare_vdo_option(cn->key, option)) {\
1258 if (is_lvchange || !cn->v || (cn->v->type != DM_CFG_INT))\
1259 goto err;\
1260 if (vtp->var != cn->v->v.i) {\
1261 vtp->var = cn->v->v.i;\
1262 u |= onoff;\
1263 }\
1264 continue;\
1265 }
1266
1267 #define DO_OFFLINE(var) \
1268 CHECK_AND_SET(var, VDO_CHANGE_OFFLINE)
1269
1270 #define DO_ONLINE(var) \
1271 CHECK_AND_SET(var, VDO_CHANGE_ONLINE)
1272
1273 int get_vdo_settings(struct cmd_context *cmd,
1274 struct dm_vdo_target_params *vtp,
1275 int *updated)
1276 {
1277 const char *str, *option = NULL;
1278 struct arg_value_group_list *group;
1279 struct dm_config_tree *result = NULL, *prev = NULL, *current = NULL;
1280 struct dm_config_node *cn;
1281 int r = 0, u = 0, is_lvchange;
1282 int use_compression = vtp->use_compression;
1283 int use_deduplication = vtp->use_deduplication;
1284 int checked_lvchange;
1285
1286 if (updated)
1287 *updated = 0;
1288
1289 // Group all --vdosettings
1290 dm_list_iterate_items(group, &cmd->arg_value_groups) {
1291 if (!grouped_arg_is_set(group->arg_values, vdosettings_ARG))
1292 continue;
1293
1294 if (!(current = dm_config_create()))
1295 goto_out;
1296 if (prev)
1297 current->cascade = prev;
1298 prev = current;
1299
1300 if (!(str = grouped_arg_str_value(group->arg_values,
1301 vdosettings_ARG,
1302 NULL)))
1303 goto_out;
1304
1305 if (!dm_config_parse_without_dup_node_check(current, str, str + strlen(str)))
1306 goto_out;
1307 }
1308
1309 if (current) {
1310 if (!(result = dm_config_flatten(current)))
1311 goto_out;
1312
1313 checked_lvchange = !strcmp(cmd->name, "lvchange");
1314
1315 /* Use all acceptable VDO options */
1316 for (cn = result->root; cn; cn = cn->sib) {
1317 is_lvchange = 0;
1318 DO_OFFLINE(ack_threads);
1319 DO_OFFLINE(bio_rotation);
1320 DO_OFFLINE(bio_threads);
1321 DO_OFFLINE(block_map_cache_size_mb);
1322 DO_OFFLINE(block_map_era_length);
1323 DO_OFFLINE(block_map_period); // alias for block_map_era_length
1324 DO_OFFLINE(cpu_threads);
1325 DO_OFFLINE(hash_zone_threads);
1326 DO_OFFLINE(logical_threads);
1327 DO_OFFLINE(max_discard);
1328 DO_OFFLINE(physical_threads);
1329
1330 // Support also these - even when we have regular opts for them
1331 DO_ONLINE(use_compression);
1332 DO_ONLINE(use_deduplication);
1333
1334 // Settings below cannot be changed with lvchange command
1335 is_lvchange = checked_lvchange;
1336
1337 DO_OFFLINE(index_memory_size_mb);
1338 DO_OFFLINE(minimum_io_size);
1339 DO_OFFLINE(slab_size_mb);
1340 DO_OFFLINE(use_metadata_hints);
1341 DO_OFFLINE(use_sparse_index);
1342
1343 option = "write_policy";
1344 if (_compare_vdo_option(cn->key, option)) {
1345 if (is_lvchange || !cn->v || (cn->v->type != DM_CFG_STRING))
1346 goto err;
1347 if (!set_vdo_write_policy(&vtp->write_policy, cn->v->v.str))
1348 goto_out;
1349 u |= VDO_CHANGE_OFFLINE;
1350 continue;
1351 }
1352
1353 if (_compare_vdo_option(cn->key, "check_point_frequency")) {
1354 log_verbose("Ignoring deprecated --vdosettings option \"%s\" and its value.", cn->key);
1355 continue; /* Accept & ignore deprecated option */
1356 }
1357
1358 log_error("Unknown VDO setting \"%s\".", cn->key);
1359 goto out;
1360 }
1361 }
1362
1363 if (arg_is_set(cmd, compression_ARG)) {
1364 vtp->use_compression = arg_int_value(cmd, compression_ARG, 0);
1365 if (vtp->use_compression != use_compression)
1366 u |= VDO_CHANGE_ONLINE;
1367 }
1368
1369 if (arg_is_set(cmd, deduplication_ARG)) {
1370 vtp->use_deduplication = arg_int_value(cmd, deduplication_ARG, 0);
1371 if (vtp->use_deduplication != use_deduplication)
1372 u |= VDO_CHANGE_ONLINE;
1373 }
1374
1375 /* store size in sector units */
1376 if (vtp->minimum_io_size >= 512)
1377 vtp->minimum_io_size >>= SECTOR_SHIFT;
1378
1379 // validation of updated VDO option
1380 if (!dm_vdo_validate_target_params(vtp, 0 /* vdo_size */))
1381 goto_out;
1382
1383 if (updated)
1384 *updated = u;
1385
1386 r = 1; // success
1387 goto out;
1388 err:
1389 if (is_lvchange)
1390 log_error("Cannot change VDO setting \"vdo_%s\" in existing VDO pool.",
1391 option);
1392 else
1393 log_error("Invalid argument for VDO setting \"vdo_%s\".",
1394 option);
1395
1396 out:
1397 if (result)
1398 dm_config_destroy(result);
1399
1400 while (prev) {
1401 current = prev->cascade;
1402 dm_config_destroy(prev);
1403 prev = current;
1404 }
1405
1406 return r;
1407 }
1408
1409 static int _get_one_writecache_setting(struct cmd_context *cmd, struct writecache_settings *settings,
1410 char *key, char *val, uint32_t *block_size_sectors)
1411 {
1412 /* special case: block_size is not a setting but is set with the --cachesettings option */
1413 if (!strncmp(key, "block_size", sizeof("block_size") - 1)) {
1414 uint32_t block_size = 0;
1415 if (sscanf(val, "%u", &block_size) != 1)
1416 goto_bad;
1417 if (block_size == 512)
1418 *block_size_sectors = 1;
1419 else if (block_size == 4096)
1420 *block_size_sectors = 8;
1421 else
1422 goto_bad;
1423 return 1;
1424 }
1425
1426 if (!strncmp(key, "high_watermark", sizeof("high_watermark") - 1)) {
1427 if (sscanf(val, "%llu", (unsigned long long *)&settings->high_watermark) != 1)
1428 goto_bad;
1429 if (settings->high_watermark > 100)
1430 goto_bad;
1431 settings->high_watermark_set = 1;
1432 return 1;
1433 }
1434
1435 if (!strncmp(key, "low_watermark", sizeof("low_watermark") - 1)) {
1436 if (sscanf(val, "%llu", (unsigned long long *)&settings->low_watermark) != 1)
1437 goto_bad;
1438 if (settings->low_watermark > 100)
1439 goto_bad;
1440 settings->low_watermark_set = 1;
1441 return 1;
1442 }
1443
1444 if (!strncmp(key, "writeback_jobs", sizeof("writeback_jobs") - 1)) {
1445 if (sscanf(val, "%llu", (unsigned long long *)&settings->writeback_jobs) != 1)
1446 goto_bad;
1447 settings->writeback_jobs_set = 1;
1448 return 1;
1449 }
1450
1451 if (!strncmp(key, "autocommit_blocks", sizeof("autocommit_blocks") - 1)) {
1452 if (sscanf(val, "%llu", (unsigned long long *)&settings->autocommit_blocks) != 1)
1453 goto_bad;
1454 settings->autocommit_blocks_set = 1;
1455 return 1;
1456 }
1457
1458 if (!strncmp(key, "autocommit_time", sizeof("autocommit_time") - 1)) {
1459 if (sscanf(val, "%llu", (unsigned long long *)&settings->autocommit_time) != 1)
1460 goto_bad;
1461 settings->autocommit_time_set = 1;
1462 return 1;
1463 }
1464
1465 if (!strncmp(key, "fua", sizeof("fua") - 1)) {
1466 if (settings->nofua_set) {
1467 log_error("Setting fua and nofua cannot both be set.");
1468 return 0;
1469 }
1470 if (sscanf(val, "%u", &settings->fua) != 1)
1471 goto_bad;
1472 settings->fua_set = 1;
1473 return 1;
1474 }
1475
1476 if (!strncmp(key, "nofua", sizeof("nofua") - 1)) {
1477 if (settings->fua_set) {
1478 log_error("Setting fua and nofua cannot both be set.");
1479 return 0;
1480 }
1481 if (sscanf(val, "%u", &settings->nofua) != 1)
1482 goto_bad;
1483 settings->nofua_set = 1;
1484 return 1;
1485 }
1486
1487 if (!strncmp(key, "cleaner", sizeof("cleaner") - 1)) {
1488 if (sscanf(val, "%u", &settings->cleaner) != 1)
1489 goto_bad;
1490 settings->cleaner_set = 1;
1491 return 1;
1492 }
1493
1494 if (!strncmp(key, "max_age", sizeof("max_age") - 1)) {
1495 if (sscanf(val, "%u", &settings->max_age) != 1)
1496 goto_bad;
1497 settings->max_age_set = 1;
1498 return 1;
1499 }
1500
1501 if (!strncmp(key, "metadata_only", sizeof("metadata_only") - 1)) {
1502 if (sscanf(val, "%u", &settings->metadata_only) != 1)
1503 goto_bad;
1504 settings->metadata_only_set = 1;
1505 return 1;
1506 }
1507
1508 if (!strncmp(key, "pause_writeback", sizeof("pause_writeback") - 1)) {
1509 if (sscanf(val, "%u", &settings->pause_writeback) != 1)
1510 goto_bad;
1511 settings->pause_writeback_set = 1;
1512 return 1;
1513 }
1514
1515 if (settings->new_key) {
1516 log_error("Setting %s is not recognized. Only one unrecognized setting is allowed.", key);
1517 return 0;
1518 }
1519
1520 log_warn("WARNING: Unrecognized writecache setting \"%s\" may cause activation failure.", key);
1521 if (yes_no_prompt("Use unrecognized writecache setting? [y/n]: ") == 'n') {
1522 log_error("Aborting writecache conversion.");
1523 return 0;
1524 }
1525
1526 log_warn("WARNING: Using unrecognized writecache setting: %s = %s.", key, val);
1527
1528 settings->new_key = dm_pool_strdup(cmd->mem, key);
1529 settings->new_val = dm_pool_strdup(cmd->mem, val);
1530 return 1;
1531
1532 bad:
1533 log_error("Invalid setting: %s", key);
1534 return 0;
1535 }
1536
1537 int get_writecache_settings(struct cmd_context *cmd, struct writecache_settings *settings,
1538 uint32_t *block_size_sectors)
1539 {
1540 const struct dm_config_node *cns, *cn1, *cn2;
1541 struct arg_value_group_list *group;
1542 const char *str;
1543 char key[64];
1544 char val[64];
1545 int num;
1546 unsigned pos;
1547 int rn;
1548 int found = 0;
1549
1550 /*
1551 * "grouped" means that multiple --cachesettings options can be used.
1552 * Each option is also allowed to contain multiple key = val pairs.
1553 */
1554
1555 dm_list_iterate_items(group, &cmd->arg_value_groups) {
1556 if (!grouped_arg_is_set(group->arg_values, cachesettings_ARG))
1557 continue;
1558
1559 if (!(str = grouped_arg_str_value(group->arg_values, cachesettings_ARG, NULL)))
1560 break;
1561
1562 pos = 0;
1563
1564 while (pos < strlen(str)) {
1565 /* scan for "key1=val1 key2 = val2 key3= val3" */
1566
1567 memset(key, 0, sizeof(key));
1568 memset(val, 0, sizeof(val));
1569
1570 if (sscanf(str + pos, " %63[^=]=%63s %n", key, val, &num) != 2) {
1571 log_error("Invalid setting at: %s", str+pos);
1572 return 0;
1573 }
1574
1575 pos += num;
1576
1577 if (!_get_one_writecache_setting(cmd, settings, key, val, block_size_sectors))
1578 return_0;
1579 }
1580 found = 1;
1581 }
1582
1583 if (found)
1584 goto out;
1585
1586 /*
1587 * If there were no settings on the command line, look for settings in
1588 * lvm.conf
1589 *
1590 * TODO: support profiles
1591 */
1592
1593 if (!(cns = find_config_tree_node(cmd, allocation_cache_settings_CFG_SECTION, NULL)))
1594 goto out;
1595
1596 for (cn1 = cns->child; cn1; cn1 = cn1->sib) {
1597 if (!cn1->child)
1598 continue; /* Ignore section without settings */
1599
1600 if (cn1->v || strcmp(cn1->key, "writecache") != 0)
1601 continue; /* Ignore non-matching settings */
1602
1603 cn2 = cn1->child;
1604
1605 for (; cn2; cn2 = cn2->sib) {
1606 memset(val, 0, sizeof(val));
1607
1608 if (cn2->v->type == DM_CFG_INT)
1609 rn = dm_snprintf(val, sizeof(val), FMTd64, cn2->v->v.i);
1610 else if (cn2->v->type == DM_CFG_STRING)
1611 rn = dm_snprintf(val, sizeof(val), "%s", cn2->v->v.str);
1612 else
1613 rn = -1;
1614 if (rn < 0) {
1615 log_error("Invalid lvm.conf writecache setting value for %s.", cn2->key);
1616 return 0;
1617 }
1618
1619 if (!_get_one_writecache_setting(cmd, settings, (char *)cn2->key, val, block_size_sectors))
1620 return_0;
1621 }
1622 }
1623
1624 out:
1625 if (settings->high_watermark_set && settings->low_watermark_set &&
1626 (settings->high_watermark <= settings->low_watermark)) {
1627 log_error("High watermark must be greater than low watermark.");
1628 return 0;
1629 }
1630
1631 return 1;
1632 }
1633
1634 static int _get_one_integrity_setting(struct cmd_context *cmd, struct integrity_settings *settings,
1635 char *key, char *val)
1636 {
1637 /*
1638 * Some settings handled by other options:
1639 * settings->mode from --raidintegritymode
1640 * settings->block_size from --raidintegrityblocksize
1641 */
1642
1643 /* always set in metadata and on table line */
1644
1645 if (!strncmp(key, "journal_sectors", sizeof("journal_sectors") - 1)) {
1646 uint32_t size_mb;
1647
1648 if (sscanf(val, "%u", &settings->journal_sectors) != 1)
1649 goto_bad;
1650
1651 size_mb = settings->journal_sectors / 2048;
1652 if (size_mb < 4 || size_mb > 1024) {
1653 log_error("Invalid raid integrity journal size %d MiB (use 4-1024 MiB).", size_mb);
1654 goto_bad;
1655 }
1656 settings->journal_sectors_set = 1;
1657 return 1;
1658 }
1659
1660
1661 /* optional, not included in metadata or table line unless set */
1662
1663 if (!strncmp(key, "journal_watermark", sizeof("journal_watermark") - 1)) {
1664 if (sscanf(val, "%u", &settings->journal_watermark) != 1)
1665 goto_bad;
1666 if (settings->journal_watermark > 100)
1667 goto_bad;
1668 settings->journal_watermark_set = 1;
1669 return 1;
1670 }
1671
1672 if (!strncmp(key, "commit_time", sizeof("commit_time") - 1)) {
1673 if (sscanf(val, "%u", &settings->commit_time) != 1)
1674 goto_bad;
1675 settings->commit_time_set = 1;
1676 return 1;
1677 }
1678
1679 if (!strncmp(key, "bitmap_flush_interval", sizeof("bitmap_flush_interval") - 1)) {
1680 if (sscanf(val, "%u", &settings->bitmap_flush_interval) != 1)
1681 goto_bad;
1682 settings->bitmap_flush_interval_set = 1;
1683 return 1;
1684 }
1685
1686 if (!strncmp(key, "allow_discards", sizeof("allow_discards") - 1)) {
1687 if (sscanf(val, "%u", &settings->allow_discards) != 1)
1688 goto_bad;
1689 if (settings->allow_discards != 0 && settings->allow_discards != 1)
1690 goto_bad;
1691 settings->allow_discards_set = 1;
1692 return 1;
1693 }
1694
1695 return 1;
1696
1697 bad:
1698 log_error("Invalid setting: %s", key);
1699 return 0;
1700 }
1701
1702 int get_integrity_settings(struct cmd_context *cmd, struct integrity_settings *settings)
1703 {
1704 struct arg_value_group_list *group;
1705 const char *str;
1706 char key[64];
1707 char val[64];
1708 int num;
1709 unsigned pos;
1710
1711 /*
1712 * "grouped" means that multiple --integritysettings options can be used.
1713 * Each option is also allowed to contain multiple key = val pairs.
1714 */
1715
1716 dm_list_iterate_items(group, &cmd->arg_value_groups) {
1717 if (!grouped_arg_is_set(group->arg_values, integritysettings_ARG))
1718 continue;
1719
1720 if (!(str = grouped_arg_str_value(group->arg_values, integritysettings_ARG, NULL)))
1721 break;
1722
1723 pos = 0;
1724
1725 while (pos < strlen(str)) {
1726 /* scan for "key1=val1 key2 = val2 key3= val3" */
1727
1728 memset(key, 0, sizeof(key));
1729 memset(val, 0, sizeof(val));
1730
1731 if (sscanf(str + pos, " %63[^=]=%63s %n", key, val, &num) != 2) {
1732 log_error("Invalid setting at: %s", str+pos);
1733 return 0;
1734 }
1735
1736 pos += num;
1737
1738 if (!_get_one_integrity_setting(cmd, settings, key, val))
1739 return_0;
1740 }
1741 }
1742
1743 return 1;
1744 }
1745
1746 /* FIXME move to lib */
1747 static int _pv_change_tag(struct physical_volume *pv, const char *tag, int addtag)
1748 {
1749 if (addtag) {
1750 if (!str_list_add(pv->fmt->cmd->mem, &pv->tags, tag)) {
1751 log_error("Failed to add tag %s to physical volume %s.",
1752 tag, pv_dev_name(pv));
1753 return 0;
1754 }
1755 } else
1756 str_list_del(&pv->tags, tag);
1757
1758 return 1;
1759 }
1760
1761 /* Set exactly one of VG, LV or PV */
1762 int change_tag(struct cmd_context *cmd, struct volume_group *vg,
1763 struct logical_volume *lv, struct physical_volume *pv, int arg)
1764 {
1765 const char *tag;
1766 struct arg_value_group_list *current_group;
1767
1768 dm_list_iterate_items(current_group, &cmd->arg_value_groups) {
1769 if (!grouped_arg_is_set(current_group->arg_values, arg))
1770 continue;
1771
1772 if (!(tag = grouped_arg_str_value(current_group->arg_values, arg, NULL))) {
1773 log_error("Failed to get tag.");
1774 return 0;
1775 }
1776
1777 if (vg && !vg_change_tag(vg, tag, arg == addtag_ARG))
1778 return_0;
1779 else if (lv && !lv_change_tag(lv, tag, arg == addtag_ARG))
1780 return_0;
1781 else if (pv && !_pv_change_tag(pv, tag, arg == addtag_ARG))
1782 return_0;
1783 }
1784
1785 return 1;
1786 }
1787
1788 /*
1789 * FIXME: replace process_each_label() with process_each_vg() which is
1790 * based on performing vg_read(), which provides a correct representation
1791 * of VGs/PVs, that is not provided by lvmcache_label_scan().
1792 */
1793
1794 int process_each_label(struct cmd_context *cmd, int argc, char **argv,
1795 struct processing_handle *handle,
1796 process_single_label_fn_t process_single_label)
1797 {
1798 log_report_t saved_log_report_state = log_get_report_state();
1799 struct label *label;
1800 struct dev_iter *iter;
1801 struct device *dev;
1802 struct lvmcache_info *info;
1803 struct dm_list process_duplicates;
1804 struct device_list *devl;
1805 int ret_max = ECMD_PROCESSED;
1806 int ret;
1807 int opt = 0;
1808
1809 dm_list_init(&process_duplicates);
1810
1811 log_set_report_object_type(LOG_REPORT_OBJECT_TYPE_LABEL);
1812
1813 if (!lvmcache_label_scan(cmd)) {
1814 ret_max = ECMD_FAILED;
1815 goto_out;
1816 }
1817
1818 if (argc) {
1819 for (; opt < argc; opt++) {
1820 if (sigint_caught()) {
1821 log_error("Interrupted.");
1822 ret_max = ECMD_FAILED;
1823 goto out;
1824 }
1825
1826 if (!(dev = dev_cache_get_existing(cmd, argv[opt], cmd->filter))) {
1827 log_error("Failed to find device "
1828 "\"%s\".", argv[opt]);
1829 ret_max = ECMD_FAILED;
1830 continue;
1831 }
1832
1833 if (!(label = lvmcache_get_dev_label(dev))) {
1834 if (!lvmcache_dev_is_unused_duplicate(dev)) {
1835 log_error("No physical volume label read from %s.", argv[opt]);
1836 ret_max = ECMD_FAILED;
1837 } else {
1838 if (!(devl = malloc(sizeof(*devl))))
1839 return_0;
1840 devl->dev = dev;
1841 dm_list_add(&process_duplicates, &devl->list);
1842 }
1843 continue;
1844 }
1845
1846 log_set_report_object_name_and_id(dev_name(dev), NULL);
1847
1848 ret = process_single_label(cmd, label, handle);
1849 report_log_ret_code(ret);
1850
1851 if (ret > ret_max)
1852 ret_max = ret;
1853
1854 log_set_report_object_name_and_id(NULL, NULL);
1855 }
1856
1857 dm_list_iterate_items(devl, &process_duplicates) {
1858 if (sigint_caught()) {
1859 log_error("Interrupted.");
1860 ret_max = ECMD_FAILED;
1861 goto out;
1862 }
1863 /*
1864 * remove the existing dev for this pvid from lvmcache
1865 * so that the duplicate dev can replace it.
1866 */
1867 if ((info = lvmcache_info_from_pvid(devl->dev->pvid, NULL, 0)))
1868 lvmcache_del(info);
1869
1870 /*
1871 * add info to lvmcache from the duplicate dev.
1872 */
1873 label_scan_dev(cmd, devl->dev);
1874
1875 /*
1876 * the info/label should now be found because
1877 * the label_read should have added it.
1878 */
1879 if (!(label = lvmcache_get_dev_label(devl->dev)))
1880 continue;
1881
1882 log_set_report_object_name_and_id(dev_name(devl->dev), NULL);
1883
1884 ret = process_single_label(cmd, label, handle);
1885 report_log_ret_code(ret);
1886
1887 if (ret > ret_max)
1888 ret_max = ret;
1889
1890 log_set_report_object_name_and_id(NULL, NULL);
1891 }
1892
1893 goto out;
1894 }
1895
1896 if (!(iter = dev_iter_create(cmd->filter, 1))) {
1897 log_error("dev_iter creation failed.");
1898 ret_max = ECMD_FAILED;
1899 goto out;
1900 }
1901
1902 while ((dev = dev_iter_get(cmd, iter))) {
1903 if (sigint_caught()) {
1904 log_error("Interrupted.");
1905 ret_max = ECMD_FAILED;
1906 break;
1907 }
1908
1909 if (!(label = lvmcache_get_dev_label(dev)))
1910 continue;
1911
1912 log_set_report_object_name_and_id(dev_name(label->dev), NULL);
1913
1914 ret = process_single_label(cmd, label, handle);
1915 report_log_ret_code(ret);
1916
1917 if (ret > ret_max)
1918 ret_max = ret;
1919
1920 log_set_report_object_name_and_id(NULL, NULL);
1921 }
1922
1923 dev_iter_destroy(iter);
1924 out:
1925 log_restore_report_state(saved_log_report_state);
1926 return ret_max;
1927 }
1928
1929 /*
1930 * Parse persistent major minor parameters.
1931 *
1932 * --persistent is unspecified => state is deduced
1933 * from presence of options --minor or --major.
1934 *
1935 * -Mn => --minor or --major not allowed.
1936 *
1937 * -My => --minor is required (and also --major on <=2.4)
1938 */
1939 int get_and_validate_major_minor(const struct cmd_context *cmd,
1940 const struct format_type *fmt,
1941 int32_t *major, int32_t *minor)
1942 {
1943 if (arg_count(cmd, minor_ARG) > 1) {
1944 log_error("Option --minor may not be repeated.");
1945 return 0;
1946 }
1947
1948 if (arg_count(cmd, major_ARG) > 1) {
1949 log_error("Option -j|--major may not be repeated.");
1950 return 0;
1951 }
1952
1953 /* Check with default 'y' */
1954 if (!arg_int_value(cmd, persistent_ARG, 1)) { /* -Mn */
1955 if (arg_is_set(cmd, minor_ARG) || arg_is_set(cmd, major_ARG)) {
1956 log_error("Options --major and --minor are incompatible with -Mn.");
1957 return 0;
1958 }
1959 *major = *minor = -1;
1960 return 1;
1961 }
1962
1963 /* -1 cannot be entered as an argument for --major, --minor */
1964 *major = arg_int_value(cmd, major_ARG, -1);
1965 *minor = arg_int_value(cmd, minor_ARG, -1);
1966
1967 if (arg_is_set(cmd, persistent_ARG)) { /* -My */
1968 if (*minor == -1) {
1969 log_error("Please specify minor number with --minor when using -My.");
1970 return 0;
1971 }
1972 }
1973
1974 if (!strncmp(cmd->kernel_vsn, "2.4.", 4)) {
1975 /* Major is required for 2.4 */
1976 if (arg_is_set(cmd, persistent_ARG) && *major < 0) {
1977 log_error("Please specify major number with --major when using -My.");
1978 return 0;
1979 }
1980 } else {
1981 if (*major != -1) {
1982 log_warn("WARNING: Ignoring supplied major number %d - "
1983 "kernel assigns major numbers dynamically. "
1984 "Using major number %d instead.",
1985 *major, cmd->dev_types->device_mapper_major);
1986 }
1987 /* Stay with dynamic major:minor if minor is not specified. */
1988 *major = (*minor == -1) ? -1 : (int)cmd->dev_types->device_mapper_major;
1989 }
1990
1991 if ((*minor != -1) && !validate_major_minor(cmd, fmt, *major, *minor))
1992 return_0;
1993
1994 return 1;
1995 }
1996
1997 /*
1998 * Validate lvname parameter
1999 *
2000 * If it contains vgname, it is extracted from lvname.
2001 * If there is passed vgname, it is compared whether its the same name.
2002 */
2003 int validate_lvname_param(struct cmd_context *cmd, const char **vg_name,
2004 const char **lv_name)
2005 {
2006 const char *vgname;
2007 const char *lvname;
2008
2009 if (!lv_name || !*lv_name)
2010 return 1; /* NULL lvname is ok */
2011
2012 /* If contains VG name, extract it. */
2013 if (strchr(*lv_name, (int) '/')) {
2014 if (!(vgname = _extract_vgname(cmd, *lv_name, &lvname)))
2015 return_0;
2016
2017 if (!*vg_name)
2018 *vg_name = vgname;
2019 else if (strcmp(vgname, *vg_name)) {
2020 log_error("Please use a single volume group name "
2021 "(\"%s\" or \"%s\").", vgname, *vg_name);
2022 return 0;
2023 }
2024
2025 *lv_name = lvname;
2026 }
2027
2028 if (!validate_name(*lv_name)) {
2029 log_error("Logical volume name \"%s\" is invalid.",
2030 *lv_name);
2031 return 0;
2032 }
2033
2034 return 1;
2035 }
2036
2037 /*
2038 * Validate lvname parameter
2039 * This name must follow restriction rules on prefixes and suffixes.
2040 *
2041 * If it contains vgname, it is extracted from lvname.
2042 * If there is passed vgname, it is compared whether its the same name.
2043 */
2044 int validate_restricted_lvname_param(struct cmd_context *cmd, const char **vg_name,
2045 const char **lv_name)
2046 {
2047 if (!validate_lvname_param(cmd, vg_name, lv_name))
2048 return_0;
2049
2050 if (lv_name && *lv_name && !apply_lvname_restrictions(*lv_name))
2051 return_0;
2052
2053 return 1;
2054 }
2055
2056 /*
2057 * Extract list of VG names and list of tags from command line arguments.
2058 */
2059 static int _get_arg_vgnames(struct cmd_context *cmd,
2060 int argc, char **argv,
2061 const char *one_vgname,
2062 struct dm_list *use_vgnames,
2063 struct dm_list *arg_vgnames,
2064 struct dm_list *arg_tags)
2065 {
2066 int opt = 0;
2067 int ret_max = ECMD_PROCESSED;
2068 const char *vg_name;
2069
2070 if (one_vgname) {
2071 if (!str_list_add(cmd->mem, arg_vgnames,
2072 dm_pool_strdup(cmd->mem, one_vgname))) {
2073 log_error("strlist allocation failed.");
2074 return ECMD_FAILED;
2075 }
2076 return ret_max;
2077 }
2078
2079 if (use_vgnames && !dm_list_empty(use_vgnames)) {
2080 dm_list_splice(arg_vgnames, use_vgnames);
2081 return ret_max;
2082 }
2083
2084 for (; opt < argc; opt++) {
2085 vg_name = argv[opt];
2086
2087 if (*vg_name == '@') {
2088 if (!validate_tag(vg_name + 1)) {
2089 log_error("Skipping invalid tag: %s", vg_name);
2090 if (ret_max < EINVALID_CMD_LINE)
2091 ret_max = EINVALID_CMD_LINE;
2092 continue;
2093 }
2094
2095 if (!str_list_add(cmd->mem, arg_tags,
2096 dm_pool_strdup(cmd->mem, vg_name + 1))) {
2097 log_error("strlist allocation failed.");
2098 return ECMD_FAILED;
2099 }
2100
2101 continue;
2102 }
2103
2104 vg_name = skip_dev_dir(cmd, vg_name, NULL);
2105 if (strchr(vg_name, '/')) {
2106 log_error("Invalid volume group name %s.", vg_name);
2107 if (ret_max < EINVALID_CMD_LINE)
2108 ret_max = EINVALID_CMD_LINE;
2109 continue;
2110 }
2111
2112 if (!str_list_add(cmd->mem, arg_vgnames,
2113 dm_pool_strdup(cmd->mem, vg_name))) {
2114 log_error("strlist allocation failed.");
2115 return ECMD_FAILED;
2116 }
2117 }
2118
2119 return ret_max;
2120 }
2121
2122 struct processing_handle *init_processing_handle(struct cmd_context *cmd, struct processing_handle *parent_handle)
2123 {
2124 struct processing_handle *handle;
2125
2126 if (!(handle = dm_pool_zalloc(cmd->mem, sizeof(struct processing_handle)))) {
2127 log_error("_init_processing_handle: failed to allocate memory for processing handle");
2128 return NULL;
2129 }
2130
2131 handle->parent = parent_handle;
2132
2133 /*
2134 * For any reporting tool, the internal_report_for_select is reset to 0
2135 * automatically because the internal reporting/selection is simply not
2136 * needed - the reporting/selection is already a part of the code path
2137 * used there.
2138 *
2139 * *The internal report for select is only needed for non-reporting tools!*
2140 */
2141 handle->internal_report_for_select = arg_is_set(cmd, select_ARG);
2142 handle->include_historical_lvs = cmd->include_historical_lvs;
2143
2144 if (!parent_handle && !cmd->cmd_report.report_group) {
2145 if (!report_format_init(cmd)) {
2146 dm_pool_free(cmd->mem, handle);
2147 return NULL;
2148 }
2149 } else
2150 cmd->cmd_report.saved_log_report_state = log_get_report_state();
2151
2152 log_set_report_context(LOG_REPORT_CONTEXT_PROCESSING);
2153 return handle;
2154 }
2155
2156 int init_selection_handle(struct cmd_context *cmd, struct processing_handle *handle,
2157 unsigned initial_report_type)
2158 {
2159 struct selection_handle *sh;
2160 const char *selection;
2161
2162 if (!(sh = dm_pool_zalloc(cmd->mem, sizeof(struct selection_handle)))) {
2163 log_error("_init_selection_handle: failed to allocate memory for selection handle");
2164 return 0;
2165 }
2166
2167 if (!report_get_single_selection(cmd, initial_report_type, &selection))
2168 return_0;
2169
2170 sh->report_type = initial_report_type;
2171 if (!(sh->selection_rh = report_init_for_selection(cmd, &sh->report_type, selection))) {
2172 dm_pool_free(cmd->mem, sh);
2173 return_0;
2174 }
2175
2176 handle->selection_handle = sh;
2177 return 1;
2178 }
2179
2180 void destroy_processing_handle(struct cmd_context *cmd, struct processing_handle *handle)
2181 {
2182 if (handle) {
2183 if (handle->selection_handle && handle->selection_handle->selection_rh)
2184 dm_report_free(handle->selection_handle->selection_rh);
2185
2186 log_restore_report_state(cmd->cmd_report.saved_log_report_state);
2187
2188 /*
2189 * Do not destroy current cmd->report_group and cmd->log_rh
2190 * (the log report) yet if we're running interactively
2191 * (== running in lvm shell) or if there's a parent handle
2192 * (== we're executing nested processing, like it is when
2193 * doing selection for parent's process_each_* processing).
2194 *
2195 * In both cases, there's still possible further processing
2196 * to do outside the processing covered by the handle we are
2197 * destroying here and for which we may still need to access
2198 * the log report to cover the rest of the processing.
2199 *
2200 */
2201 if (!cmd->is_interactive && !handle->parent) {
2202 if (!dm_report_group_destroy(cmd->cmd_report.report_group))
2203 stack;
2204 cmd->cmd_report.report_group = NULL;
2205
2206 if (cmd->cmd_report.log_rh) {
2207 dm_report_free(cmd->cmd_report.log_rh);
2208 cmd->cmd_report.log_rh = NULL;
2209 }
2210 }
2211 /*
2212 * TODO: think about better alternatives:
2213 * handle mempool, dm_alloc for handle memory...
2214 */
2215 memset(handle, 0, sizeof(*handle));
2216 }
2217 }
2218
2219
2220 int select_match_vg(struct cmd_context *cmd, struct processing_handle *handle,
2221 struct volume_group *vg)
2222 {
2223 int r;
2224
2225 if (!handle->internal_report_for_select)
2226 return 1;
2227
2228 handle->selection_handle->orig_report_type = VGS;
2229 if (!(r = report_for_selection(cmd, handle, NULL, vg, NULL)))
2230 log_error("Selection failed for VG %s.", vg->name);
2231 handle->selection_handle->orig_report_type = 0;
2232
2233 return r;
2234 }
2235
2236 int select_match_lv(struct cmd_context *cmd, struct processing_handle *handle,
2237 struct volume_group *vg, struct logical_volume *lv)
2238 {
2239 int r;
2240
2241 if (!handle->internal_report_for_select)
2242 return 1;
2243
2244 handle->selection_handle->orig_report_type = LVS;
2245 if (!(r = report_for_selection(cmd, handle, NULL, vg, lv)))
2246 log_error("Selection failed for LV %s.", lv->name);
2247 handle->selection_handle->orig_report_type = 0;
2248
2249 return r;
2250 }
2251
2252 int select_match_pv(struct cmd_context *cmd, struct processing_handle *handle,
2253 struct volume_group *vg, struct physical_volume *pv)
2254 {
2255 int r;
2256
2257 if (!handle->internal_report_for_select)
2258 return 1;
2259
2260 handle->selection_handle->orig_report_type = PVS;
2261 if (!(r = report_for_selection(cmd, handle, pv, vg, NULL)))
2262 log_error("Selection failed for PV %s.", dev_name(pv->dev));
2263 handle->selection_handle->orig_report_type = 0;
2264
2265 return r;
2266 }
2267
2268 static int _select_matches(struct processing_handle *handle)
2269 {
2270 if (!handle->internal_report_for_select)
2271 return 1;
2272
2273 return handle->selection_handle->selected;
2274 }
2275
2276 static int _process_vgnameid_list(struct cmd_context *cmd, uint32_t read_flags,
2277 struct dm_list *vgnameids_to_process,
2278 struct dm_list *arg_vgnames,
2279 struct dm_list *arg_tags,
2280 struct processing_handle *handle,
2281 process_single_vg_fn_t process_single_vg)
2282 {
2283 log_report_t saved_log_report_state = log_get_report_state();
2284 char uuid[64] __attribute__((aligned(8)));
2285 struct volume_group *vg;
2286 struct volume_group *error_vg = NULL;
2287 struct vgnameid_list *vgnl;
2288 const char *vg_name;
2289 const char *vg_uuid;
2290 uint32_t lockd_state = 0;
2291 uint32_t error_flags = 0;
2292 int whole_selected = 0;
2293 int ret_max = ECMD_PROCESSED;
2294 int ret;
2295 int skip;
2296 int notfound;
2297 int is_lockd;
2298 int process_all = 0;
2299 int do_report_ret_code = 1;
2300
2301 log_set_report_object_type(LOG_REPORT_OBJECT_TYPE_VG);
2302
2303 /*
2304 * If no VG names or tags were supplied, then process all VGs.
2305 */
2306 if (dm_list_empty(arg_vgnames) && dm_list_empty(arg_tags))
2307 process_all = 1;
2308
2309 /*
2310 * FIXME If one_vgname, only proceed if exactly one VG matches tags or selection.
2311 */
2312 dm_list_iterate_items(vgnl, vgnameids_to_process) {
2313 if (sigint_caught()) {
2314 ret_max = ECMD_FAILED;
2315 goto_out;
2316 }
2317
2318 vg_name = vgnl->vg_name;
2319 vg_uuid = vgnl->vgid;
2320 skip = 0;
2321 notfound = 0;
2322 is_lockd = lvmcache_vg_is_lockd_type(cmd, vg_name, vg_uuid);
2323
2324 uuid[0] = '\0';
2325 if (is_orphan_vg(vg_name)) {
2326 log_set_report_object_type(LOG_REPORT_OBJECT_TYPE_ORPHAN);
2327 log_set_report_object_name_and_id(vg_name + sizeof(VG_ORPHANS), NULL);
2328 } else {
2329 if (vg_uuid && !id_write_format((const struct id*)vg_uuid, uuid, sizeof(uuid)))
2330 stack;
2331 log_set_report_object_name_and_id(vg_name, (const struct id*)vg_uuid);
2332 }
2333
2334 log_very_verbose("Processing VG %s %s", vg_name, uuid);
2335 do_lockd:
2336 if (is_lockd && !lockd_vg(cmd, vg_name, NULL, 0, &lockd_state)) {
2337 stack;
2338 ret_max = ECMD_FAILED;
2339 report_log_ret_code(ret_max);
2340 continue;
2341 }
2342
2343 vg = vg_read(cmd, vg_name, vg_uuid, read_flags, lockd_state, &error_flags, &error_vg);
2344 if (_ignore_vg(cmd, error_flags, error_vg, vg_name, arg_vgnames, read_flags, &skip, &notfound)) {
2345 stack;
2346 ret_max = ECMD_FAILED;
2347 report_log_ret_code(ret_max);
2348 if (error_vg)
2349 unlock_and_release_vg(cmd, error_vg, vg_name);
2350 goto endvg;
2351 }
2352 if (error_vg)
2353 unlock_and_release_vg(cmd, error_vg, vg_name);
2354
2355 if (skip || notfound)
2356 goto endvg;
2357
2358 if (!is_lockd && vg_is_shared(vg)) {
2359 /* The lock_type changed since label_scan, won't really occur in practice. */
2360 log_debug("Repeat lock and read for local to shared vg");
2361 unlock_and_release_vg(cmd, vg, vg_name);
2362 is_lockd = 1;
2363 goto do_lockd;
2364 }
2365
2366 /* Process this VG? */
2367 if ((process_all ||
2368 (!dm_list_empty(arg_vgnames) && str_list_match_item(arg_vgnames, vg_name)) ||
2369 (!dm_list_empty(arg_tags) && str_list_match_list(arg_tags, &vg->tags, NULL))) &&
2370 select_match_vg(cmd, handle, vg) && _select_matches(handle)) {
2371
2372 log_very_verbose("Running command for VG %s %s", vg_name, vg_uuid ? uuid : "");
2373
2374 ret = process_single_vg(cmd, vg_name, vg, handle);
2375 _update_selection_result(handle, &whole_selected);
2376 if (ret != ECMD_PROCESSED)
2377 stack;
2378 report_log_ret_code(ret);
2379 if (ret > ret_max)
2380 ret_max = ret;
2381 }
2382
2383 unlock_vg(cmd, vg, vg_name);
2384 endvg:
2385 release_vg(vg);
2386 if (is_lockd && !lockd_vg(cmd, vg_name, "un", 0, &lockd_state))
2387 stack;
2388
2389 log_set_report_object_name_and_id(NULL, NULL);
2390 }
2391 /* the VG is selected if at least one LV is selected */
2392 _set_final_selection_result(handle, whole_selected);
2393 do_report_ret_code = 0;
2394 out:
2395 if (do_report_ret_code)
2396 report_log_ret_code(ret_max);
2397 log_restore_report_state(saved_log_report_state);
2398 return ret_max;
2399 }
2400
2401 /*
2402 * Check if a command line VG name is ambiguous, i.e. there are multiple VGs on
2403 * the system that have the given name. If *one* VG with the given name is
2404 * local and the rest are foreign, then use the local VG (removing foreign VGs
2405 * with the same name from the vgnameids_on_system list). If multiple VGs with
2406 * the given name are local, we don't know which VG is intended, so remove the
2407 * ambiguous name from the list of args.
2408 */
2409 static int _resolve_duplicate_vgnames(struct cmd_context *cmd,
2410 struct dm_list *arg_vgnames,
2411 struct dm_list *vgnameids_on_system)
2412 {
2413 struct dm_str_list *sl, *sl2;
2414 struct vgnameid_list *vgnl, *vgnl2;
2415 char uuid[64] __attribute__((aligned(8)));
2416 int found;
2417 int ret = ECMD_PROCESSED;
2418
2419 dm_list_iterate_items_safe(sl, sl2, arg_vgnames) {
2420 found = 0;
2421 dm_list_iterate_items(vgnl, vgnameids_on_system) {
2422 if (strcmp(sl->str, vgnl->vg_name))
2423 continue;
2424 found++;
2425 }
2426
2427 if (found < 2)
2428 continue;
2429
2430 /*
2431 * More than one VG match the given name.
2432 * If only one is local, use that one.
2433 */
2434
2435 found = 0;
2436 dm_list_iterate_items_safe(vgnl, vgnl2, vgnameids_on_system) {
2437 if (strcmp(sl->str, vgnl->vg_name))
2438 continue;
2439
2440 /*
2441 * label scan has already populated lvmcache vginfo with
2442 * this information.
2443 */
2444 if (lvmcache_vg_is_foreign(cmd, vgnl->vg_name, vgnl->vgid)) {
2445 if (!id_write_format((const struct id*)vgnl->vgid, uuid, sizeof(uuid)))
2446 stack;
2447 dm_list_del(&vgnl->list);
2448 } else {
2449 found++;
2450 }
2451 }
2452
2453 if (found < 2)
2454 continue;
2455
2456 /*
2457 * More than one VG with this name is local so the intended VG
2458 * is unknown.
2459 */
2460 log_error("Multiple VGs found with the same name: skipping %s", sl->str);
2461
2462 if (arg_is_valid_for_command(cmd, select_ARG))
2463 log_error("Use --select vg_uuid=<uuid> in place of the VG name.");
2464 else
2465 log_error("Use VG uuid in place of the VG name.");
2466
2467 dm_list_del(&sl->list);
2468 ret = ECMD_FAILED;
2469 }
2470
2471 return ret;
2472 }
2473
2474 /*
2475 * For each arg_vgname, move the corresponding entry from
2476 * vgnameids_on_system to vgnameids_to_process. If an
2477 * item in arg_vgnames doesn't exist in vgnameids_on_system,
2478 * then add a new entry for it to vgnameids_to_process.
2479 */
2480 static void _choose_vgs_to_process(struct cmd_context *cmd,
2481 struct dm_list *arg_vgnames,
2482 struct dm_list *vgnameids_on_system,
2483 struct dm_list *vgnameids_to_process)
2484 {
2485 char uuid[64] __attribute__((aligned(8)));
2486 struct dm_str_list *sl, *sl2;
2487 struct vgnameid_list *vgnl, *vgnl2;
2488 struct id id;
2489 int arg_is_uuid = 0;
2490 int found;
2491
2492 dm_list_iterate_items_safe(sl, sl2, arg_vgnames) {
2493 found = 0;
2494 dm_list_iterate_items_safe(vgnl, vgnl2, vgnameids_on_system) {
2495 if (strcmp(sl->str, vgnl->vg_name))
2496 continue;
2497
2498 dm_list_del(&vgnl->list);
2499 dm_list_add(vgnameids_to_process, &vgnl->list);
2500 found = 1;
2501 break;
2502 }
2503
2504 /*
2505 * If the VG name arg looks like a UUID, then check if it
2506 * matches the UUID of a VG. (--select should generally
2507 * be used to select a VG by uuid instead.)
2508 */
2509 if (!found && (cmd->cname->flags & ALLOW_UUID_AS_NAME))
2510 arg_is_uuid = id_read_format_try(&id, sl->str);
2511
2512 if (!found && arg_is_uuid) {
2513 dm_list_iterate_items_safe(vgnl, vgnl2, vgnameids_on_system) {
2514 if (!(id_write_format((const struct id*)vgnl->vgid, uuid, sizeof(uuid))))
2515 continue;
2516
2517 if (strcmp(sl->str, uuid))
2518 continue;
2519
2520 log_print("Processing VG %s because of matching UUID %s",
2521 vgnl->vg_name, uuid);
2522
2523 dm_list_del(&vgnl->list);
2524 dm_list_add(vgnameids_to_process, &vgnl->list);
2525
2526 /* Make the arg_vgnames entry use the actual VG name. */
2527 sl->str = dm_pool_strdup(cmd->mem, vgnl->vg_name);
2528
2529 found = 1;
2530 break;
2531 }
2532 }
2533
2534 /*
2535 * If the name arg was not found in the list of all VGs, then
2536 * it probably doesn't exist, but we want the "VG not found"
2537 * failure to be handled by the existing vg_read() code for
2538 * that error. So, create an entry with just the VG name so
2539 * that the processing loop will attempt to process it and use
2540 * the vg_read() error path.
2541 */
2542 if (!found) {
2543 log_verbose("VG name on command line not found in list of VGs: %s", sl->str);
2544
2545 if (!(vgnl = dm_pool_alloc(cmd->mem, sizeof(*vgnl))))
2546 continue;
2547
2548 vgnl->vgid = NULL;
2549
2550 if (!(vgnl->vg_name = dm_pool_strdup(cmd->mem, sl->str)))
2551 continue;
2552
2553 dm_list_add(vgnameids_to_process, &vgnl->list);
2554 }
2555 }
2556 }
2557
2558 /*
2559 * Call process_single_vg() for each VG selected by the command line arguments.
2560 * If one_vgname is set, process only that VG and ignore argc/argv (which should be 0/NULL).
2561 * If one_vgname is not set, get VG names to process from argc/argv.
2562 */
2563 int process_each_vg(struct cmd_context *cmd,
2564 int argc, char **argv,
2565 const char *one_vgname,
2566 struct dm_list *use_vgnames,
2567 uint32_t read_flags,
2568 int include_internal,
2569 struct processing_handle *handle,
2570 process_single_vg_fn_t process_single_vg)
2571 {
2572 log_report_t saved_log_report_state = log_get_report_state();
2573 int handle_supplied = handle != NULL;
2574 struct dm_list arg_tags; /* str_list */
2575 struct dm_list arg_vgnames; /* str_list */
2576 struct dm_list vgnameids_on_system; /* vgnameid_list */
2577 struct dm_list vgnameids_to_process; /* vgnameid_list */
2578 int enable_all_vgs = (cmd->cname->flags & ALL_VGS_IS_DEFAULT);
2579 int process_all_vgs_on_system = 0;
2580 int ret_max = ECMD_PROCESSED;
2581 int ret;
2582
2583 log_set_report_object_type(LOG_REPORT_OBJECT_TYPE_VG);
2584 log_debug("Processing each VG");
2585
2586 /* Disable error in vg_read so we can print it from ignore_vg. */
2587 cmd->vg_read_print_access_error = 0;
2588
2589 dm_list_init(&arg_tags);
2590 dm_list_init(&arg_vgnames);
2591 dm_list_init(&vgnameids_on_system);
2592 dm_list_init(&vgnameids_to_process);
2593
2594 /*
2595 * Find any VGs or tags explicitly provided on the command line.
2596 */
2597 if ((ret = _get_arg_vgnames(cmd, argc, argv, one_vgname, use_vgnames, &arg_vgnames, &arg_tags)) != ECMD_PROCESSED) {
2598 ret_max = ret;
2599 goto_out;
2600 }
2601
2602 /*
2603 * Process all VGs on the system when:
2604 * . tags are specified and all VGs need to be read to
2605 * look for matching tags.
2606 * . no VG names are specified and the command defaults
2607 * to processing all VGs when none are specified.
2608 */
2609 if ((dm_list_empty(&arg_vgnames) && enable_all_vgs) || !dm_list_empty(&arg_tags))
2610 process_all_vgs_on_system = 1;
2611
2612 /*
2613 * Needed for a current listing of the global VG namespace.
2614 */
2615 if (process_all_vgs_on_system && !lock_global(cmd, "sh")) {
2616 ret_max = ECMD_FAILED;
2617 goto_out;
2618 }
2619
2620 /*
2621 * Scan all devices to populate lvmcache with initial
2622 * list of PVs and VGs.
2623 */
2624 if (!(read_flags & PROCESS_SKIP_SCAN)) {
2625 if (!lvmcache_label_scan(cmd)) {
2626 ret_max = ECMD_FAILED;
2627 goto_out;
2628 }
2629 }
2630
2631
2632 /*
2633 * A list of all VGs on the system is needed when:
2634 * . processing all VGs on the system
2635 * . A VG name is specified which may refer to one
2636 * of multiple VGs on the system with that name.
2637 */
2638 log_very_verbose("Obtaining the complete list of VGs to process");
2639
2640 if (!lvmcache_get_vgnameids(cmd, &vgnameids_on_system, NULL, include_internal)) {
2641 ret_max = ECMD_FAILED;
2642 goto_out;
2643 }
2644
2645 if (!dm_list_empty(&arg_vgnames)) {
2646 /* This may remove entries from arg_vgnames or vgnameids_on_system. */
2647 ret = _resolve_duplicate_vgnames(cmd, &arg_vgnames, &vgnameids_on_system);
2648 if (ret > ret_max)
2649 ret_max = ret;
2650 if (dm_list_empty(&arg_vgnames) && dm_list_empty(&arg_tags)) {
2651 ret_max = ECMD_FAILED;
2652 goto out;
2653 }
2654 }
2655
2656 if (dm_list_empty(&arg_vgnames) && dm_list_empty(&vgnameids_on_system)) {
2657 /* FIXME Should be log_print, but suppressed for reporting cmds */
2658 log_verbose("No volume groups found.");
2659 ret_max = ECMD_PROCESSED;
2660 goto out;
2661 }
2662
2663 if (dm_list_empty(&arg_vgnames))
2664 read_flags |= READ_OK_NOTFOUND;
2665
2666 /*
2667 * When processing all VGs, vgnameids_on_system simply becomes
2668 * vgnameids_to_process.
2669 * When processing only specified VGs, then for each item in
2670 * arg_vgnames, move the corresponding entry from
2671 * vgnameids_on_system to vgnameids_to_process.
2672 */
2673 if (process_all_vgs_on_system)
2674 dm_list_splice(&vgnameids_to_process, &vgnameids_on_system);
2675 else
2676 _choose_vgs_to_process(cmd, &arg_vgnames, &vgnameids_on_system, &vgnameids_to_process);
2677
2678 if (!handle && !(handle = init_processing_handle(cmd, NULL))) {
2679 ret_max = ECMD_FAILED;
2680 goto_out;
2681 }
2682
2683 if (handle->internal_report_for_select && !handle->selection_handle &&
2684 !init_selection_handle(cmd, handle, VGS)) {
2685 ret_max = ECMD_FAILED;
2686 goto_out;
2687 }
2688
2689 ret = _process_vgnameid_list(cmd, read_flags, &vgnameids_to_process,
2690 &arg_vgnames, &arg_tags, handle, process_single_vg);
2691 if (ret > ret_max)
2692 ret_max = ret;
2693 out:
2694 if (!handle_supplied)
2695 destroy_processing_handle(cmd, handle);
2696
2697 log_restore_report_state(saved_log_report_state);
2698 return ret_max;
2699 }
2700
2701 static struct dm_str_list *_str_list_match_item_with_prefix(const struct dm_list *sll, const char *prefix, const char *str)
2702 {
2703 struct dm_str_list *sl;
2704 size_t prefix_len = strlen(prefix);
2705
2706 dm_list_iterate_items(sl, sll) {
2707 if (!strncmp(prefix, sl->str, prefix_len) &&
2708 !strcmp(sl->str + prefix_len, str))
2709 return sl;
2710 }
2711
2712 return NULL;
2713 }
2714
2715 /*
2716 * Dummy LV, segment type and segment to represent all historical LVs.
2717 */
2718 static struct logical_volume _historical_lv = {
2719 .name = "",
2720 .major = -1,
2721 .minor = -1,
2722 .snapshot_segs = DM_LIST_HEAD_INIT(_historical_lv.snapshot_segs),
2723 .segments = DM_LIST_HEAD_INIT(_historical_lv.segments),
2724 .tags = DM_LIST_HEAD_INIT(_historical_lv.tags),
2725 .segs_using_this_lv = DM_LIST_HEAD_INIT(_historical_lv.segs_using_this_lv),
2726 .indirect_glvs = DM_LIST_HEAD_INIT(_historical_lv.indirect_glvs),
2727 .hostname = "",
2728 };
2729
2730 static struct segment_type _historical_segment_type = {
2731 .name = "historical",
2732 .flags = SEG_VIRTUAL | SEG_CANNOT_BE_ZEROED,
2733 };
2734
2735 static struct lv_segment _historical_lv_segment = {
2736 .lv = &_historical_lv,
2737 .segtype = &_historical_segment_type,
2738 .len = 0,
2739 .tags = DM_LIST_HEAD_INIT(_historical_lv_segment.tags),
2740 .origin_list = DM_LIST_HEAD_INIT(_historical_lv_segment.origin_list),
2741 };
2742
2743 int opt_in_list_is_set(struct cmd_context *cmd, const uint16_t *opts, int count,
2744 int *match_count, int *unmatch_count)
2745 {
2746 int match = 0;
2747 int unmatch = 0;
2748 int i;
2749
2750 for (i = 0; i < count; i++) {
2751 if (arg_is_set(cmd, opts[i]))
2752 match++;
2753 else
2754 unmatch++;
2755 }
2756
2757 if (match_count)
2758 *match_count = match;
2759 if (unmatch_count)
2760 *unmatch_count = unmatch;
2761
2762 return match ? 1 : 0;
2763 }
2764
2765 void opt_array_to_str(struct cmd_context *cmd, const uint16_t *opts, int count,
2766 char *buf, int len)
2767 {
2768 int pos = 0;
2769 int ret;
2770 int i;
2771
2772 for (i = 0; i < count; i++) {
2773 ret = snprintf(buf + pos, len - pos, "%s ", arg_long_option_name(opts[i]));
2774 if (ret >= len - pos)
2775 break;
2776 pos += ret;
2777 }
2778
2779 buf[len - 1] = '\0';
2780 }
2781
2782 static void _lvp_bits_to_str(uint64_t bits, char *buf, int len)
2783 {
2784 const struct lv_prop *prop;
2785 int lvp_enum;
2786 int pos = 0;
2787 int ret;
2788
2789 for (lvp_enum = 0; lvp_enum < LVP_COUNT; lvp_enum++) {
2790 if (!(prop = get_lv_prop(lvp_enum)))
2791 continue;
2792
2793 if (lvp_bit_is_set(bits, lvp_enum)) {
2794 ret = snprintf(buf + pos, len - pos, "%s ", prop->name);
2795 if (ret >= len - pos)
2796 break;
2797 pos += ret;
2798 }
2799 }
2800 buf[len - 1] = '\0';
2801 }
2802
2803 static void _lvt_bits_to_str(uint64_t bits, char *buf, int len)
2804 {
2805 const struct lv_type *type;
2806 int lvt_enum;
2807 int pos = 0;
2808 int ret;
2809
2810 for (lvt_enum = 0; lvt_enum < LVT_COUNT; lvt_enum++) {
2811 if (!(type = get_lv_type(lvt_enum)))
2812 continue;
2813
2814 if (lvt_bit_is_set(bits, lvt_enum)) {
2815 ret = snprintf(buf + pos, len - pos, "%s ", type->name);
2816 if (ret >= len - pos)
2817 break;
2818 pos += ret;
2819 }
2820 }
2821 buf[len - 1] = '\0';
2822 }
2823
2824 /*
2825 * This is the lv_prop function pointer used for lv_is_foo() #defines.
2826 * Alternatively, lv_is_foo() could all be turned into functions.
2827 */
2828
2829 static int _lv_is_prop(struct cmd_context *cmd, struct logical_volume *lv, int lvp_enum)
2830 {
2831 switch (lvp_enum) {
2832 case is_locked_LVP:
2833 return lv_is_locked(lv);
2834 case is_partial_LVP:
2835 return lv_is_partial(lv);
2836 case is_virtual_LVP:
2837 return lv_is_virtual(lv);
2838 case is_merging_LVP:
2839 return lv_is_merging(lv);
2840 case is_merging_origin_LVP:
2841 return lv_is_merging_origin(lv);
2842 case is_converting_LVP:
2843 return lv_is_converting(lv);
2844 case is_external_origin_LVP:
2845 return lv_is_external_origin(lv);
2846 case is_virtual_origin_LVP:
2847 return lv_is_virtual_origin(lv);
2848 case is_not_synced_LVP:
2849 return lv_is_not_synced(lv);
2850 case is_pending_delete_LVP:
2851 return lv_is_pending_delete(lv);
2852 case is_error_when_full_LVP:
2853 return lv_is_error_when_full(lv);
2854 case is_pvmove_LVP:
2855 return lv_is_pvmove(lv);
2856 case is_removed_LVP:
2857 return lv_is_removed(lv);
2858 case is_writable_LVP:
2859 return lv_is_writable(lv);
2860 case is_vg_writable_LVP:
2861 return (lv->vg->status & LVM_WRITE) ? 1 : 0;
2862 case is_thinpool_data_LVP:
2863 return lv_is_thin_pool_data(lv);
2864 case is_thinpool_metadata_LVP:
2865 return lv_is_thin_pool_metadata(lv);
2866 case is_cachepool_data_LVP:
2867 return lv_is_cache_pool_data(lv);
2868 case is_cachepool_metadata_LVP:
2869 return lv_is_cache_pool_metadata(lv);
2870 case is_mirror_image_LVP:
2871 return lv_is_mirror_image(lv);
2872 case is_mirror_log_LVP:
2873 return lv_is_mirror_log(lv);
2874 case is_raid_image_LVP:
2875 return lv_is_raid_image(lv);
2876 case is_raid_metadata_LVP:
2877 return lv_is_raid_metadata(lv);
2878 case is_origin_LVP: /* use lv_is_thick_origin */
2879 return lv_is_origin(lv);
2880 case is_thick_origin_LVP:
2881 return lv_is_thick_origin(lv);
2882 case is_thick_snapshot_LVP:
2883 return lv_is_thick_snapshot(lv);
2884 case is_thin_origin_LVP:
2885 return lv_is_thin_origin(lv, NULL);
2886 case is_thin_snapshot_LVP:
2887 return lv_is_thin_snapshot(lv);
2888 case is_cache_origin_LVP:
2889 return lv_is_cache_origin(lv);
2890 case is_merging_cow_LVP:
2891 return lv_is_merging_cow(lv);
2892 case is_cow_LVP:
2893 return lv_is_cow(lv);
2894 case is_cow_covering_origin_LVP:
2895 return lv_is_cow_covering_origin(lv);
2896 case is_visible_LVP:
2897 return lv_is_visible(lv);
2898 case is_error_LVP:
2899 return lv_is_error(lv);
2900 case is_zero_LVP:
2901 return lv_is_zero(lv);
2902 case is_historical_LVP:
2903 return lv_is_historical(lv);
2904 case is_raid_with_tracking_LVP:
2905 return lv_is_raid_with_tracking(lv);
2906 case is_raid_with_integrity_LVP:
2907 return lv_raid_has_integrity(lv);
2908 default:
2909 log_error(INTERNAL_ERROR "unknown lv property value lvp_enum %d", lvp_enum);
2910 }
2911
2912 return 0;
2913 }
2914
2915 /*
2916 * Check if an LV matches a given LV type enum.
2917 */
2918
2919 static int _lv_is_type(struct cmd_context *cmd, struct logical_volume *lv, int lvt_enum)
2920 {
2921 struct lv_segment *seg = first_seg(lv);
2922
2923 switch (lvt_enum) {
2924 case striped_LVT:
2925 return seg_is_striped(seg) && !lv_is_cow(lv);
2926 case linear_LVT:
2927 return seg_is_linear(seg) && !lv_is_cow(lv);
2928 case snapshot_LVT:
2929 return lv_is_cow(lv);
2930 case thin_LVT:
2931 return lv_is_thin_volume(lv);
2932 case thinpool_LVT:
2933 return lv_is_thin_pool(lv);
2934 case cache_LVT:
2935 return lv_is_cache(lv);
2936 case cachepool_LVT:
2937 return lv_is_cache_pool(lv);
2938 case vdo_LVT:
2939 return lv_is_vdo(lv);
2940 case vdopool_LVT:
2941 return lv_is_vdo_pool(lv);
2942 case vdopooldata_LVT:
2943 return lv_is_vdo_pool_data(lv);
2944 case mirror_LVT:
2945 return lv_is_mirror(lv);
2946 case raid_LVT:
2947 return lv_is_raid(lv);
2948 case raid0_LVT:
2949 return seg_is_any_raid0(seg);
2950 case raid1_LVT:
2951 return seg_is_raid1(seg);
2952 case raid4_LVT:
2953 return seg_is_raid4(seg);
2954 case raid5_LVT:
2955 return seg_is_any_raid5(seg);
2956 case raid6_LVT:
2957 return seg_is_any_raid6(seg);
2958 case raid10_LVT:
2959 return seg_is_raid10(seg);
2960 case writecache_LVT:
2961 return seg_is_writecache(seg);
2962 case integrity_LVT:
2963 return seg_is_integrity(seg);
2964 case error_LVT:
2965 return seg_is_error(seg);
2966 case zero_LVT:
2967 return seg_is_zero(seg);
2968 default:
2969 log_error(INTERNAL_ERROR "unknown lv type value lvt_enum %d", lvt_enum);
2970 }
2971
2972 return 0;
2973 }
2974
2975 int get_lvt_enum(struct logical_volume *lv)
2976 {
2977 struct lv_segment *seg = first_seg(lv);
2978
2979 /*
2980 * The order these are checked is important, because a snapshot LV has
2981 * a linear seg type.
2982 */
2983
2984 if (lv_is_cow(lv))
2985 return snapshot_LVT;
2986 if (seg_is_linear(seg))
2987 return linear_LVT;
2988 if (seg_is_striped(seg))
2989 return striped_LVT;
2990 if (lv_is_thin_volume(lv))
2991 return thin_LVT;
2992 if (lv_is_thin_pool(lv))
2993 return thinpool_LVT;
2994 if (lv_is_cache(lv))
2995 return cache_LVT;
2996 if (lv_is_cache_pool(lv))
2997 return cachepool_LVT;
2998 if (lv_is_vdo(lv))
2999 return vdo_LVT;
3000 if (lv_is_vdo_pool(lv))
3001 return vdopool_LVT;
3002 if (lv_is_vdo_pool_data(lv))
3003 return vdopooldata_LVT;
3004 if (lv_is_mirror(lv))
3005 return mirror_LVT;
3006 if (lv_is_raid(lv))
3007 return raid_LVT;
3008 if (seg_is_any_raid0(seg))
3009 return raid0_LVT;
3010 if (seg_is_raid1(seg))
3011 return raid1_LVT;
3012 if (seg_is_raid4(seg))
3013 return raid4_LVT;
3014 if (seg_is_any_raid5(seg))
3015 return raid5_LVT;
3016 if (seg_is_any_raid6(seg))
3017 return raid6_LVT;
3018 if (seg_is_raid10(seg))
3019 return raid10_LVT;
3020 if (seg_is_writecache(seg))
3021 return writecache_LVT;
3022 if (seg_is_integrity(seg))
3023 return integrity_LVT;
3024
3025 if (seg_is_error(seg))
3026 return error_LVT;
3027 if (seg_is_zero(seg))
3028 return zero_LVT;
3029
3030 return 0;
3031 }
3032
3033 /*
3034 * Call lv_is_<type> for each <type>_LVT bit set in lvt_bits.
3035 * If lv matches one of the specified lv types, then return 1.
3036 */
3037
3038 static int _lv_types_match(struct cmd_context *cmd, struct logical_volume *lv, uint64_t lvt_bits,
3039 uint64_t *match_bits, uint64_t *unmatch_bits)
3040 {
3041 const struct lv_type *type;
3042 int lvt_enum;
3043 int found_a_match = 0;
3044 int match;
3045
3046 if (match_bits)
3047 *match_bits = 0;
3048 if (unmatch_bits)
3049 *unmatch_bits = 0;
3050
3051 for (lvt_enum = 1; lvt_enum < LVT_COUNT; lvt_enum++) {
3052 if (!lvt_bit_is_set(lvt_bits, lvt_enum))
3053 continue;
3054
3055 if (!(type = get_lv_type(lvt_enum)))
3056 continue;
3057
3058 /*
3059 * All types are currently handled by _lv_is_type()
3060 * because lv_is_type() are #defines and not exposed
3061 * in tools.h
3062 */
3063
3064 match = _lv_is_type(cmd, lv, lvt_enum);
3065
3066 if (match)
3067 found_a_match = 1;
3068
3069 if (match_bits && match)
3070 *match_bits |= lvt_enum_to_bit(lvt_enum);
3071
3072 if (unmatch_bits && !match)
3073 *unmatch_bits |= lvt_enum_to_bit(lvt_enum);
3074 }
3075
3076 return found_a_match;
3077 }
3078
3079 /*
3080 * Call lv_is_<prop> for each <prop>_LVP bit set in lvp_bits.
3081 * If lv matches all of the specified lv properties, then return 1.
3082 */
3083
3084 static int _lv_props_match(struct cmd_context *cmd, struct logical_volume *lv, uint64_t lvp_bits,
3085 uint64_t *match_bits, uint64_t *unmatch_bits)
3086 {
3087 const struct lv_prop *prop;
3088 int lvp_enum;
3089 int found_a_mismatch = 0;
3090 int match;
3091
3092 if (match_bits)
3093 *match_bits = 0;
3094 if (unmatch_bits)
3095 *unmatch_bits = 0;
3096
3097 for (lvp_enum = 1; lvp_enum < LVP_COUNT; lvp_enum++) {
3098 if (!lvp_bit_is_set(lvp_bits, lvp_enum))
3099 continue;
3100
3101 if (!(prop = get_lv_prop(lvp_enum)))
3102 continue;
3103
3104 match = _lv_is_prop(cmd, lv, lvp_enum);
3105
3106 if (!match)
3107 found_a_mismatch = 1;
3108
3109 if (match_bits && match)
3110 *match_bits |= lvp_enum_to_bit(lvp_enum);
3111
3112 if (unmatch_bits && !match)
3113 *unmatch_bits |= lvp_enum_to_bit(lvp_enum);
3114 }
3115
3116 return !found_a_mismatch;
3117 }
3118
3119 static int _check_lv_types(struct cmd_context *cmd, struct logical_volume *lv, int pos)
3120 {
3121 int ret;
3122
3123 if (!pos)
3124 return 1;
3125
3126 if (!cmd->command->required_pos_args[pos-1].def.lvt_bits)
3127 return 1;
3128
3129 if (!val_bit_is_set(cmd->command->required_pos_args[pos-1].def.val_bits, lv_VAL)) {
3130 log_error(INTERNAL_ERROR "Command %d:%s arg position %d does not permit an LV (%llx)",
3131 cmd->command->command_index, command_enum(cmd->command->command_enum),
3132 pos, (unsigned long long)cmd->command->required_pos_args[pos-1].def.val_bits);
3133 return 0;
3134 }
3135
3136 ret = _lv_types_match(cmd, lv, cmd->command->required_pos_args[pos-1].def.lvt_bits, NULL, NULL);
3137 if (!ret) {
3138 int lvt_enum = get_lvt_enum(lv);
3139 const struct lv_type *type = get_lv_type(lvt_enum);
3140 if (!type) {
3141 log_warn("WARNING: Command on LV %s does not accept LV type unknown (%d).",
3142 display_lvname(lv), lvt_enum);
3143 } else {
3144 log_warn("WARNING: Command on LV %s does not accept LV type %s.",
3145 display_lvname(lv), type->name);
3146 }
3147 }
3148
3149 return ret;
3150 }
3151
3152 /* Check if LV passes each rule specified in command definition. */
3153
3154 static int _check_lv_rules(struct cmd_context *cmd, struct logical_volume *lv)
3155 {
3156 char buf[64];
3157 const struct cmd_rule *rule;
3158 const struct lv_type *lvtype = NULL;
3159 uint64_t lv_props_match_bits = 0, lv_props_unmatch_bits = 0;
3160 uint64_t lv_types_match_bits = 0, lv_types_unmatch_bits = 0;
3161 int opts_match_count = 0, opts_unmatch_count = 0;
3162 int lvt_enum;
3163 int ret = 1;
3164 int i;
3165
3166 lvt_enum = get_lvt_enum(lv);
3167 if (lvt_enum)
3168 lvtype = get_lv_type(lvt_enum);
3169
3170 for (i = 0; i < cmd->command->rule_count; i++) {
3171 rule = &cmd->command->rules[i];
3172
3173 /*
3174 * RULE: <conditions> INVALID|REQUIRE <checks>
3175 *
3176 * If all the conditions apply to the command+LV, then
3177 * the checks are performed. If all conditions are zero
3178 * (!opts_count, !lvt_bits, !lvp_bits), then the check
3179 * is always performed.
3180 *
3181 * Conditions:
3182 *
3183 * 1. options (opts): if any of the specified options are set,
3184 * then the checks may apply.
3185 *
3186 * 2. LV types (lvt_bits): if any of the specified LV types
3187 * match the LV, then the checks may apply.
3188 *
3189 * 3. LV properties (lvp_bits): if all of the specified
3190 * LV properties match the LV, then the checks may apply.
3191 *
3192 * If conditions 1, 2, 3 all pass, then the checks apply.
3193 *
3194 * Checks:
3195 *
3196 * 1. options (check_opts):
3197 * INVALID: if any of the specified options are set,
3198 * then the command fails.
3199 * REQUIRE: if any of the specified options are not set,
3200 * then the command fails.
3201 *
3202 * 2. LV types (check_lvt_bits):
3203 * INVALID: if any of the specified LV types match the LV,
3204 * then the command fails.
3205 * REQUIRE: if none of the specified LV types match the LV,
3206 * then the command fails.
3207 *
3208 * 3. LV properties (check_lvp_bits):
3209 * INVALID: if any of the specified LV properties match
3210 * the LV, then the command fails.
3211 * REQUIRE: if any of the specified LV properties do not match
3212 * the LV, then the command fails.
3213 */
3214
3215 if (rule->opts_count && !opt_in_list_is_set(cmd, rule->opts, rule->opts_count, NULL, NULL))
3216 continue;
3217
3218 /* If LV matches one type in lvt_bits, this returns 1. */
3219 if (rule->lvt_bits && !_lv_types_match(cmd, lv, rule->lvt_bits, NULL, NULL))
3220 continue;
3221
3222 /* If LV matches all properties in lvp_bits, this returns 1. */
3223 if (rule->lvp_bits && !_lv_props_match(cmd, lv, rule->lvp_bits, NULL, NULL))
3224 continue;
3225
3226 /*
3227 * Check the options, LV types, LV properties.
3228 */
3229
3230 if (rule->check_opts_count)
3231 opt_in_list_is_set(cmd, rule->check_opts, rule->check_opts_count,
3232 &opts_match_count, &opts_unmatch_count);
3233
3234 if (rule->check_lvt_bits)
3235 _lv_types_match(cmd, lv, rule->check_lvt_bits,
3236 &lv_types_match_bits, &lv_types_unmatch_bits);
3237
3238 if (rule->check_lvp_bits)
3239 _lv_props_match(cmd, lv, rule->check_lvp_bits,
3240 &lv_props_match_bits, &lv_props_unmatch_bits);
3241
3242 /*
3243 * Evaluate if the check results pass based on the rule.
3244 * The options are checked again here because the previous
3245 * option validation (during command matching) does not cover
3246 * cases where the option is combined with conditions of LV types
3247 * or properties.
3248 */
3249
3250 /* Fail if any invalid options are set. */
3251
3252 if (rule->check_opts_count && (rule->rule == RULE_INVALID) && opts_match_count) {
3253 memset(buf, 0, sizeof(buf));
3254 opt_array_to_str(cmd, rule->check_opts, rule->check_opts_count, buf, sizeof(buf));
3255 log_warn("WARNING: Command on LV %s has invalid use of option %s.",
3256 display_lvname(lv), buf);
3257 ret = 0;
3258 }
3259
3260 /* Fail if any required options are not set. */
3261
3262 if (rule->check_opts_count && (rule->rule == RULE_REQUIRE) && opts_unmatch_count) {
3263 memset(buf, 0, sizeof(buf));
3264 opt_array_to_str(cmd, rule->check_opts, rule->check_opts_count, buf, sizeof(buf));
3265 log_warn("WARNING: Command on LV %s requires option %s.",
3266 display_lvname(lv), buf);
3267 ret = 0;
3268 }
3269
3270 /* Fail if the LV matches any of the invalid LV types. */
3271
3272 if (rule->check_lvt_bits && (rule->rule == RULE_INVALID) && lv_types_match_bits) {
3273 if (rule->opts_count)
3274 log_warn("WARNING: Command on LV %s uses options invalid with LV type %s.",
3275 display_lvname(lv), lvtype ? lvtype->name : "unknown");
3276 else
3277 log_warn("WARNING: Command on LV %s with invalid LV type %s.",
3278 display_lvname(lv), lvtype ? lvtype->name : "unknown");
3279 ret = 0;
3280 }
3281
3282 /* Fail if the LV does not match any of the required LV types. */
3283
3284 if (rule->check_lvt_bits && (rule->rule == RULE_REQUIRE) && !lv_types_match_bits) {
3285 memset(buf, 0, sizeof(buf));
3286 _lvt_bits_to_str(rule->check_lvt_bits, buf, sizeof(buf));
3287 if (rule->opts_count)
3288 log_warn("WARNING: Command on LV %s uses options that require LV types %s.",
3289 display_lvname(lv), buf);
3290 else
3291 log_warn("WARNING: Command on LV %s does not accept LV type %s. Required LV types are %s.",
3292 display_lvname(lv), lvtype ? lvtype->name : "unknown", buf);
3293 ret = 0;
3294 }
3295
3296 /* Fail if the LV matches any of the invalid LV properties. */
3297
3298 if (rule->check_lvp_bits && (rule->rule == RULE_INVALID) && lv_props_match_bits) {
3299 memset(buf, 0, sizeof(buf));
3300 _lvp_bits_to_str(lv_props_match_bits, buf, sizeof(buf));
3301 if (rule->opts_count)
3302 log_warn("WARNING: Command on LV %s uses options that are invalid with LV properties: %s.",
3303 display_lvname(lv), buf);
3304 else
3305 log_warn("WARNING: Command on LV %s is invalid on LV with properties: %s.",
3306 display_lvname(lv), buf);
3307 ret = 0;
3308 }
3309
3310 /* Fail if the LV does not match any of the required LV properties. */
3311
3312 if (rule->check_lvp_bits && (rule->rule == RULE_REQUIRE) && lv_props_unmatch_bits) {
3313 memset(buf, 0, sizeof(buf));
3314 _lvp_bits_to_str(lv_props_unmatch_bits, buf, sizeof(buf));
3315 if (rule->opts_count)
3316 log_warn("WARNING: Command on LV %s uses options that require LV properties: %s.",
3317 display_lvname(lv), buf);
3318 else
3319 log_warn("WARNING: Command on LV %s requires LV with properties: %s.",
3320 display_lvname(lv), buf);
3321 ret = 0;
3322 }
3323 }
3324
3325 return ret;
3326 }
3327
3328 /*
3329 * Return which arg position the given LV is at,
3330 * where 1 represents the first position arg.
3331 * When the first position arg is repeatable,
3332 * return 1 for all.
3333 *
3334 * Return 0 when the command has no required
3335 * position args. (optional position args are
3336 * not considered.)
3337 */
3338
3339 static int _find_lv_arg_position(struct cmd_context *cmd, struct logical_volume *lv)
3340 {
3341 const char *sep, *lvname;
3342 int i;
3343
3344 if (cmd->command->rp_count == 0)
3345 return 0;
3346
3347 if (cmd->command->rp_count == 1)
3348 return 1;
3349
3350 for (i = 0; i < cmd->position_argc; i++) {
3351 if (i == cmd->command->rp_count)
3352 break;
3353
3354 if (!val_bit_is_set(cmd->command->required_pos_args[i].def.val_bits, lv_VAL))
3355 continue;
3356
3357 if ((sep = strstr(cmd->position_argv[i], "/")))
3358 lvname = sep + 1;
3359 else
3360 lvname = cmd->position_argv[i];
3361
3362 if (!strcmp(lvname, lv->name))
3363 return i + 1;
3364 }
3365
3366 /*
3367 * If the last position arg is an LV and this
3368 * arg is beyond that position, then the last
3369 * LV position arg is repeatable, so return
3370 * that position.
3371 */
3372 if (i == cmd->command->rp_count) {
3373 int last_pos = cmd->command->rp_count;
3374 if (val_bit_is_set(cmd->command->required_pos_args[last_pos-1].def.val_bits, lv_VAL))
3375 return last_pos;
3376 }
3377
3378 return 0;
3379 }
3380
3381 int process_each_lv_in_vg(struct cmd_context *cmd, struct volume_group *vg,
3382 struct dm_list *arg_lvnames, const struct dm_list *tags_in,
3383 int stop_on_error,
3384 struct processing_handle *handle,
3385 check_single_lv_fn_t check_single_lv,
3386 process_single_lv_fn_t process_single_lv)
3387 {
3388 log_report_t saved_log_report_state = log_get_report_state();
3389 int ret_max = ECMD_PROCESSED;
3390 int ret = 0;
3391 int whole_selected = 0;
3392 int handle_supplied = handle != NULL;
3393 unsigned process_lv;
3394 unsigned process_all = 0;
3395 unsigned tags_supplied = 0;
3396 unsigned lvargs_supplied = 0;
3397 int lv_is_named_arg;
3398 int lv_arg_pos;
3399 struct lv_list *lvl;
3400 struct dm_str_list *sl;
3401 DM_LIST_INIT(final_lvs);
3402 struct lv_list *final_lvl;
3403 DM_LIST_INIT(found_arg_lvnames);
3404 struct glv_list *glvl, *tglvl;
3405 int do_report_ret_code = 1;
3406
3407 cmd->online_vg_file_removed = 0;
3408
3409 log_set_report_object_type(LOG_REPORT_OBJECT_TYPE_LV);
3410
3411 if (tags_in && !dm_list_empty(tags_in))
3412 tags_supplied = 1;
3413
3414 if (arg_lvnames && !dm_list_empty(arg_lvnames))
3415 lvargs_supplied = 1;
3416
3417 if (!handle && !(handle = init_processing_handle(cmd, NULL))) {
3418 ret_max = ECMD_FAILED;
3419 goto_out;
3420 }
3421
3422 if (handle->internal_report_for_select && !handle->selection_handle &&
3423 !init_selection_handle(cmd, handle, LVS)) {
3424 ret_max = ECMD_FAILED;
3425 goto_out;
3426 }
3427
3428 /* Process all LVs in this VG if no restrictions given
3429 * or if VG tags match. */
3430 if ((!tags_supplied && !lvargs_supplied) ||
3431 (tags_supplied && str_list_match_list(tags_in, &vg->tags, NULL)))
3432 process_all = 1;
3433
3434 log_set_report_object_group_and_group_id(vg->name, &vg->id);
3435
3436 dm_list_iterate_items(lvl, &vg->lvs) {
3437 if (sigint_caught()) {
3438 ret_max = ECMD_FAILED;
3439 goto_out;
3440 }
3441
3442 log_set_report_object_name_and_id(lvl->lv->name, &lvl->lv->lvid.id[1]);
3443
3444 if (lv_is_snapshot(lvl->lv))
3445 continue;
3446
3447 /* Skip availability change for non-virt snaps when processing all LVs */
3448 /* FIXME: pass process_all to process_single_lv() */
3449 if (process_all &&
3450 (arg_is_set(cmd, activate_ARG) ||
3451 arg_is_set(cmd, refresh_ARG)) &&
3452 lv_is_cow(lvl->lv) && !lv_is_virtual_origin(origin_from_cow(lvl->lv)))
3453 continue;
3454
3455 if (lv_is_virtual_origin(lvl->lv) && !arg_is_set(cmd, all_ARG)) {
3456 if (lvargs_supplied &&
3457 str_list_match_item(arg_lvnames, lvl->lv->name))
3458 log_print_unless_silent("Ignoring virtual origin logical volume %s.",
3459 display_lvname(lvl->lv));
3460 continue;
3461 }
3462
3463 /*
3464 * Only let hidden LVs through if --all was used or the LVs
3465 * were specifically named on the command line.
3466 */
3467 if (!lvargs_supplied && !lv_is_visible(lvl->lv) && !arg_is_set(cmd, all_ARG) &&
3468 (!cmd->process_component_lvs || !lv_is_component(lvl->lv)))
3469 continue;
3470
3471 /*
3472 * Only let sanlock LV through if --all was used or if
3473 * it is named on the command line.
3474 */
3475 if (lv_is_lockd_sanlock_lv(lvl->lv)) {
3476 if (arg_is_set(cmd, all_ARG) ||
3477 (lvargs_supplied && str_list_match_item(arg_lvnames, lvl->lv->name))) {
3478 log_very_verbose("Processing lockd_sanlock_lv %s/%s.", vg->name, lvl->lv->name);
3479 } else {
3480 continue;
3481 }
3482 }
3483
3484 /*
3485 * process the LV if one of the following:
3486 * - process_all is set
3487 * - LV name matches a supplied LV name
3488 * - LV tag matches a supplied LV tag
3489 * - LV matches the selection
3490 */
3491
3492 process_lv = process_all;
3493
3494 if (lvargs_supplied && str_list_match_item(arg_lvnames, lvl->lv->name)) {
3495 /* Remove LV from list of unprocessed LV names */
3496 str_list_del(arg_lvnames, lvl->lv->name);
3497 if (!str_list_add(cmd->mem, &found_arg_lvnames, lvl->lv->name)) {
3498 log_error("strlist allocation failed.");
3499 ret_max = ECMD_FAILED;
3500 goto out;
3501 }
3502 process_lv = 1;
3503 }
3504
3505 if (!process_lv && tags_supplied && str_list_match_list(tags_in, &lvl->lv->tags, NULL))
3506 process_lv = 1;
3507
3508 process_lv = process_lv && select_match_lv(cmd, handle, vg, lvl->lv) && _select_matches(handle);
3509
3510 if (!process_lv)
3511 continue;
3512
3513 log_very_verbose("Adding %s to the list of LVs to be processed.", lvl->lv->name);
3514
3515 if (!(final_lvl = dm_pool_zalloc(cmd->mem, sizeof(struct lv_list)))) {
3516 log_error("Failed to allocate final LV list item.");
3517 ret_max = ECMD_FAILED;
3518 goto out;
3519 }
3520 final_lvl->lv = lvl->lv;
3521 if (lv_is_thin_pool(lvl->lv)) {
3522 /* Add to the front of the list */
3523 dm_list_add_h(&final_lvs, &final_lvl->list);
3524 } else
3525 dm_list_add(&final_lvs, &final_lvl->list);
3526 }
3527 log_set_report_object_name_and_id(NULL, NULL);
3528
3529 /*
3530 * If a PV is stacked on an LV, then the LV is kept open
3531 * in bcache, and needs to be closed so the open fd doesn't
3532 * interfere with processing the LV.
3533 */
3534 label_scan_invalidate_lvs(cmd, &final_lvs);
3535
3536 dm_list_iterate_items(lvl, &final_lvs) {
3537 if (sigint_caught()) {
3538 ret_max = ECMD_FAILED;
3539 goto_out;
3540 }
3541
3542 log_set_report_object_name_and_id(lvl->lv->name, &lvl->lv->lvid.id[1]);
3543
3544 /*
3545 * FIXME: Once we have index over vg->removed_lvs, check directly
3546 * LV presence there and remove LV_REMOVE flag/lv_is_removed fn
3547 * as they won't be needed anymore.
3548 */
3549 if (lv_is_removed(lvl->lv))
3550 continue;
3551
3552 lv_is_named_arg = str_list_match_item(&found_arg_lvnames, lvl->lv->name);
3553
3554 lv_arg_pos = _find_lv_arg_position(cmd, lvl->lv);
3555
3556 /*
3557 * The command definition may include restrictions on the
3558 * types and properties of LVs that can be processed.
3559 */
3560
3561 if (!_check_lv_types(cmd, lvl->lv, lv_arg_pos)) {
3562 /* FIXME: include this result in report log? */
3563 if (lv_is_named_arg) {
3564 log_error("Command not permitted on LV %s.", display_lvname(lvl->lv));
3565 ret_max = ECMD_FAILED;
3566 }
3567 continue;
3568 }
3569
3570 if (!_check_lv_rules(cmd, lvl->lv)) {
3571 /* FIXME: include this result in report log? */
3572 if (lv_is_named_arg) {
3573 log_error("Command not permitted on LV %s.", display_lvname(lvl->lv));
3574 ret_max = ECMD_FAILED;
3575 }
3576 continue;
3577 }
3578
3579 if (check_single_lv && !check_single_lv(cmd, lvl->lv, handle, lv_is_named_arg)) {
3580 if (lv_is_named_arg)
3581 ret_max = ECMD_FAILED;
3582 continue;
3583 }
3584
3585 log_very_verbose("Processing LV %s in VG %s.", lvl->lv->name, vg->name);
3586
3587 ret = process_single_lv(cmd, lvl->lv, handle);
3588 if (handle_supplied)
3589 _update_selection_result(handle, &whole_selected);
3590 if (ret != ECMD_PROCESSED)
3591 stack;
3592 report_log_ret_code(ret);
3593 if (ret > ret_max)
3594 ret_max = ret;
3595
3596 if (stop_on_error && ret != ECMD_PROCESSED) {
3597 do_report_ret_code = 0;
3598 goto_out;
3599 }
3600 }
3601 log_set_report_object_name_and_id(NULL, NULL);
3602
3603 if (handle->include_historical_lvs && !tags_supplied) {
3604 if (dm_list_empty(&_historical_lv.segments))
3605 dm_list_add(&_historical_lv.segments, &_historical_lv_segment.list);
3606 _historical_lv.vg = vg;
3607
3608 dm_list_iterate_items_safe(glvl, tglvl, &vg->historical_lvs) {
3609 if (sigint_caught()) {
3610 ret_max = ECMD_FAILED;
3611 goto_out;
3612 }
3613
3614 log_set_report_object_name_and_id(glvl->glv->historical->name,
3615 &glvl->glv->historical->lvid.id[1]);
3616
3617 if (glvl->glv->historical->fresh)
3618 continue;
3619
3620 process_lv = process_all;
3621
3622 if (lvargs_supplied &&
3623 (sl = _str_list_match_item_with_prefix(arg_lvnames, HISTORICAL_LV_PREFIX, glvl->glv->historical->name))) {
3624 str_list_del(arg_lvnames, glvl->glv->historical->name);
3625 dm_list_del(&sl->list);
3626 process_lv = 1;
3627 }
3628
3629 _historical_lv.this_glv = glvl->glv;
3630 _historical_lv.name = glvl->glv->historical->name;
3631
3632 process_lv = process_lv && select_match_lv(cmd, handle, vg, &_historical_lv) && _select_matches(handle);
3633
3634 if (!process_lv)
3635 continue;
3636
3637 log_very_verbose("Processing historical LV %s in VG %s.", glvl->glv->historical->name, vg->name);
3638
3639 /* coverity[format_string_injection] lv name is already validated */
3640 ret = process_single_lv(cmd, &_historical_lv, handle);
3641 if (handle_supplied)
3642 _update_selection_result(handle, &whole_selected);
3643 if (ret != ECMD_PROCESSED)
3644 stack;
3645 report_log_ret_code(ret);
3646 if (ret > ret_max)
3647 ret_max = ret;
3648
3649 if (stop_on_error && ret != ECMD_PROCESSED) {
3650 do_report_ret_code = 0;
3651 goto_out;
3652 }
3653 }
3654 log_set_report_object_name_and_id(NULL, NULL);
3655 }
3656
3657 if (vg->needs_write_and_commit && (ret_max == ECMD_PROCESSED) &&
3658 (!vg_write(vg) || !vg_commit(vg)))
3659 ret_max = ECMD_FAILED;
3660
3661 if (vg->needs_lockd_free_lvs)
3662 lockd_free_removed_lvs(cmd, vg, (ret_max == ECMD_PROCESSED));
3663
3664 if (lvargs_supplied) {
3665 /*
3666 * FIXME: lvm supports removal of LV with all its dependencies
3667 * this leads to miscalculation that depends on the order of args.
3668 */
3669 dm_list_iterate_items(sl, arg_lvnames) {
3670 log_set_report_object_name_and_id(sl->str, NULL);
3671 log_error("Failed to find logical volume \"%s/%s\"",
3672 vg->name, sl->str);
3673 if (ret_max < ECMD_FAILED)
3674 ret_max = ECMD_FAILED;
3675 report_log_ret_code(ret_max);
3676 }
3677 }
3678 do_report_ret_code = 0;
3679 out:
3680 if (do_report_ret_code)
3681 report_log_ret_code(ret_max);
3682 log_set_report_object_name_and_id(NULL, NULL);
3683 log_set_report_object_group_and_group_id(NULL, NULL);
3684 if (!handle_supplied)
3685 destroy_processing_handle(cmd, handle);
3686 else
3687 _set_final_selection_result(handle, whole_selected);
3688 log_restore_report_state(saved_log_report_state);
3689
3690 return ret_max;
3691 }
3692
3693 /*
3694 * If arg is tag, add it to arg_tags
3695 * else the arg is either vgname or vgname/lvname:
3696 * - add the vgname of each arg to arg_vgnames
3697 * - if arg has no lvname, add just vgname arg_lvnames,
3698 * it represents all lvs in the vg
3699 * - if arg has lvname, add vgname/lvname to arg_lvnames
3700 */
3701 static int _get_arg_lvnames(struct cmd_context *cmd,
3702 int argc, char **argv,
3703 const char *one_vgname, const char *one_lvname,
3704 struct dm_list *arg_vgnames,
3705 struct dm_list *arg_lvnames,
3706 struct dm_list *arg_tags)
3707 {
3708 int opt = 0;
3709 int ret_max = ECMD_PROCESSED;
3710 char *vglv;
3711 size_t vglv_sz;
3712 const char *vgname;
3713 const char *lv_name;
3714 const char *tmp_lv_name;
3715 const char *vgname_def;
3716 unsigned dev_dir_found;
3717
3718 if (one_vgname) {
3719 if (!str_list_add(cmd->mem, arg_vgnames,
3720 dm_pool_strdup(cmd->mem, one_vgname))) {
3721 log_error("strlist allocation failed.");
3722 return ECMD_FAILED;
3723 }
3724
3725 if (!one_lvname) {
3726 if (!str_list_add(cmd->mem, arg_lvnames,
3727 dm_pool_strdup(cmd->mem, one_vgname))) {
3728 log_error("strlist allocation failed.");
3729 return ECMD_FAILED;
3730 }
3731 } else {
3732 vglv_sz = strlen(one_vgname) + strlen(one_lvname) + 2;
3733 if (!(vglv = dm_pool_alloc(cmd->mem, vglv_sz)) ||
3734 dm_snprintf(vglv, vglv_sz, "%s/%s", one_vgname, one_lvname) < 0) {
3735 log_error("vg/lv string alloc failed.");
3736 return ECMD_FAILED;
3737 }
3738 if (!str_list_add(cmd->mem, arg_lvnames, vglv)) {
3739 log_error("strlist allocation failed.");
3740 return ECMD_FAILED;
3741 }
3742 }
3743 return ret_max;
3744 }
3745
3746 for (; opt < argc; opt++) {
3747 lv_name = argv[opt];
3748 dev_dir_found = 0;
3749
3750 /* Do we have a tag or vgname or lvname? */
3751 vgname = lv_name;
3752
3753 if (*vgname == '@') {
3754 if (!validate_tag(vgname + 1)) {
3755 log_error("Skipping invalid tag %s.", vgname);
3756 continue;
3757 }
3758 if (!str_list_add(cmd->mem, arg_tags,
3759 dm_pool_strdup(cmd->mem, vgname + 1))) {
3760 log_error("strlist allocation failed.");
3761 return ECMD_FAILED;
3762 }
3763 continue;
3764 }
3765
3766 /* FIXME Jumbled parsing */
3767 vgname = skip_dev_dir(cmd, vgname, &dev_dir_found);
3768
3769 if (*vgname == '/') {
3770 log_error("\"%s\": Invalid path for Logical Volume.",
3771 argv[opt]);
3772 if (ret_max < ECMD_FAILED)
3773 ret_max = ECMD_FAILED;
3774 continue;
3775 }
3776 lv_name = vgname;
3777 if ((tmp_lv_name = strchr(vgname, '/'))) {
3778 /* Must be an LV */
3779 lv_name = tmp_lv_name;
3780 while (*lv_name == '/')
3781 lv_name++;
3782 if (!(vgname = extract_vgname(cmd, vgname))) {
3783 if (ret_max < ECMD_FAILED) {
3784 stack;
3785 ret_max = ECMD_FAILED;
3786 }
3787 continue;
3788 }
3789 } else if (!dev_dir_found &&
3790 (vgname_def = _default_vgname(cmd)))
3791 vgname = vgname_def;
3792 else
3793 lv_name = NULL;
3794
3795 if (!str_list_add(cmd->mem, arg_vgnames,
3796 dm_pool_strdup(cmd->mem, vgname))) {
3797 log_error("strlist allocation failed.");
3798 return ECMD_FAILED;
3799 }
3800
3801 if (!lv_name) {
3802 if (!str_list_add(cmd->mem, arg_lvnames,
3803 dm_pool_strdup(cmd->mem, vgname))) {
3804 log_error("strlist allocation failed.");
3805 return ECMD_FAILED;
3806 }
3807 } else {
3808 vglv_sz = strlen(vgname) + strlen(lv_name) + 2;
3809 if (!(vglv = dm_pool_alloc(cmd->mem, vglv_sz)) ||
3810 dm_snprintf(vglv, vglv_sz, "%s/%s", vgname, lv_name) < 0) {
3811 log_error("vg/lv string alloc failed.");
3812 return ECMD_FAILED;
3813 }
3814 if (!str_list_add(cmd->mem, arg_lvnames, vglv)) {
3815 log_error("strlist allocation failed.");
3816 return ECMD_FAILED;
3817 }
3818 }
3819 }
3820
3821 return ret_max;
3822 }
3823
3824 /*
3825 * Finding vgname/lvname to process.
3826 *
3827 * When the position arg is a single name without any '/'
3828 * it is treated as an LV name (leaving the VG unknown).
3829 * Other option values, or env var, must be searched for a VG name.
3830 * If one of the option values contains a vgname/lvname value,
3831 * then the VG name is extracted and used for the LV position arg.
3832 * Or, if the env var has the VG name, that is used.
3833 *
3834 * Other option values that are searched for a VG name are:
3835 * --thinpool, --cachepool, --poolmetadata.
3836 *
3837 * . command vg/lv1
3838 * . add vg to arg_vgnames
3839 * . add vg/lv1 to arg_lvnames
3840 *
3841 * command lv1
3842 * . error: no vg name (unless LVM_VG_NAME)
3843 *
3844 * command --option=vg/lv1 vg/lv2
3845 * . verify both vg names match
3846 * . add vg to arg_vgnames
3847 * . add vg/lv2 to arg_lvnames
3848 *
3849 * command --option=lv1 lv2
3850 * . error: no vg name (unless LVM_VG_NAME)
3851 *
3852 * command --option=vg/lv1 lv2
3853 * . add vg to arg_vgnames
3854 * . add vg/lv2 to arg_lvnames
3855 *
3856 * command --option=lv1 vg/lv2
3857 * . add vg to arg_vgnames
3858 * . add vg/lv2 to arg_lvnames
3859 */
3860 static int _get_arg_lvnames_using_options(struct cmd_context *cmd,
3861 int argc, char **argv,
3862 struct dm_list *arg_vgnames,
3863 struct dm_list *arg_lvnames,
3864 struct dm_list *arg_tags)
3865 {
3866 /* Array with args which may provide vgname */
3867 static const unsigned _opts_with_vgname[] = {
3868 cachepool_ARG, poolmetadata_ARG, thinpool_ARG
3869 };
3870 unsigned i;
3871 const char *pos_name = NULL;
3872 const char *arg_name = NULL;
3873 const char *pos_vgname = NULL;
3874 const char *opt_vgname = NULL;
3875 const char *pos_lvname = NULL;
3876 const char *use_vgname = NULL;
3877 char *vglv;
3878 size_t vglv_sz;
3879
3880 if (argc != 1) {
3881 log_error("One LV position arg is required.");
3882 return ECMD_FAILED;
3883 }
3884
3885 if (!(pos_name = dm_pool_strdup(cmd->mem, argv[0]))) {
3886 log_error("string alloc failed.");
3887 return ECMD_FAILED;
3888 }
3889
3890 if (*pos_name == '@') {
3891 if (!validate_tag(pos_name + 1)) {
3892 log_error("Skipping invalid tag %s.", pos_name);
3893 return ECMD_FAILED;
3894 }
3895 if (!str_list_add(cmd->mem, arg_tags,
3896 dm_pool_strdup(cmd->mem, pos_name + 1))) {
3897 log_error("strlist allocation failed.");
3898 return ECMD_FAILED;
3899 }
3900 return ECMD_PROCESSED;
3901 }
3902
3903 if (strchr(pos_name, '/')) {
3904 /*
3905 * This splits pos_name 'x/y' into pos_vgname 'x' and pos_lvname 'y'
3906 * It skips repeated '/', e.g. x//y
3907 * It also checks and fails for extra '/', e.g. x/y/z
3908 */
3909 if (!(pos_vgname = _extract_vgname(cmd, pos_name, &pos_lvname)))
3910 return_0;
3911 use_vgname = pos_vgname;
3912 } else
3913 pos_lvname = pos_name;
3914
3915 /* Go through the list of options which can provide vgname */
3916 for (i = 0; i < DM_ARRAY_SIZE(_opts_with_vgname); ++i) {
3917 if ((arg_name = arg_str_value(cmd, _opts_with_vgname[i], NULL)) &&
3918 strchr(arg_name, '/')) {
3919 /* Combined VG/LV */
3920 /* Don't care about opt lvname, only extract vgname. */
3921 if (!(opt_vgname = _extract_vgname(cmd, arg_name, NULL)))
3922 return_0;
3923 /* Compare with already known vgname */
3924 if (use_vgname) {
3925 if (strcmp(use_vgname, opt_vgname)) {
3926 log_error("VG name mismatch from %s arg (%s) and option arg (%s).",
3927 pos_vgname ? "position" : "option",
3928 use_vgname, opt_vgname);
3929 return ECMD_FAILED;
3930 }
3931 } else
3932 use_vgname = opt_vgname;
3933 }
3934 }
3935
3936 /* VG not specified as position nor as optional arg, so check for default VG */
3937 if (!use_vgname && !(use_vgname = _default_vgname(cmd))) {
3938 log_error("Cannot find VG name for LV %s.", pos_lvname);
3939 return ECMD_FAILED;
3940 }
3941
3942 if (!str_list_add(cmd->mem, arg_vgnames, dm_pool_strdup(cmd->mem, use_vgname))) {
3943 log_error("strlist allocation failed.");
3944 return ECMD_FAILED;
3945 }
3946
3947 vglv_sz = strlen(use_vgname) + strlen(pos_lvname) + 2;
3948
3949 if (!(vglv = dm_pool_alloc(cmd->mem, vglv_sz)) ||
3950 dm_snprintf(vglv, vglv_sz, "%s/%s", use_vgname, pos_lvname) < 0) {
3951 log_error("vg/lv string alloc failed.");
3952 return ECMD_FAILED;
3953 }
3954 if (!str_list_add(cmd->mem, arg_lvnames, vglv)) {
3955 log_error("strlist allocation failed.");
3956 return ECMD_FAILED;
3957 }
3958
3959 return ECMD_PROCESSED;
3960 }
3961
3962 static int _process_lv_vgnameid_list(struct cmd_context *cmd, uint32_t read_flags,
3963 struct dm_list *vgnameids_to_process,
3964 struct dm_list *arg_vgnames,
3965 struct dm_list *arg_lvnames,
3966 struct dm_list *arg_tags,
3967 struct processing_handle *handle,
3968 check_single_lv_fn_t check_single_lv,
3969 process_single_lv_fn_t process_single_lv)
3970 {
3971 log_report_t saved_log_report_state = log_get_report_state();
3972 char uuid[64] __attribute__((aligned(8)));
3973 struct volume_group *vg;
3974 struct volume_group *error_vg = NULL;
3975 struct vgnameid_list *vgnl;
3976 struct dm_str_list *sl;
3977 struct dm_list *tags_arg;
3978 struct dm_list lvnames;
3979 uint32_t lockd_state = 0;
3980 uint32_t error_flags = 0;
3981 const char *vg_name;
3982 const char *vg_uuid;
3983 const char *vgn;
3984 const char *lvn;
3985 int ret_max = ECMD_PROCESSED;
3986 int ret;
3987 int skip;
3988 int notfound;
3989 int is_lockd;
3990 int do_report_ret_code = 1;
3991
3992 log_set_report_object_type(LOG_REPORT_OBJECT_TYPE_VG);
3993
3994 dm_list_iterate_items(vgnl, vgnameids_to_process) {
3995 if (sigint_caught()) {
3996 ret_max = ECMD_FAILED;
3997 goto_out;
3998 }
3999
4000 vg_name = vgnl->vg_name;
4001 vg_uuid = vgnl->vgid;
4002 skip = 0;
4003 notfound = 0;
4004 is_lockd = lvmcache_vg_is_lockd_type(cmd, vg_name, vg_uuid);
4005
4006 uuid[0] = '\0';
4007 if (vg_uuid && !id_write_format((const struct id*)vg_uuid, uuid, sizeof(uuid)))
4008 stack;
4009
4010 log_set_report_object_name_and_id(vg_name, (const struct id*)vg_uuid);
4011
4012 /*
4013 * arg_lvnames contains some elements that are just "vgname"
4014 * which means process all lvs in the vg. Other elements
4015 * are "vgname/lvname" which means process only the select
4016 * lvs in the vg.
4017 */
4018 tags_arg = arg_tags;
4019 dm_list_init(&lvnames); /* LVs to be processed in this VG */
4020
4021 dm_list_iterate_items(sl, arg_lvnames) {
4022 vgn = sl->str;
4023 lvn = strchr(vgn, '/');
4024
4025 if (!lvn && !strcmp(vgn, vg_name)) {
4026 /* Process all LVs in this VG */
4027 tags_arg = NULL;
4028 dm_list_init(&lvnames);
4029 break;
4030 }
4031
4032 if (lvn && !strncmp(vgn, vg_name, strlen(vg_name)) &&
4033 strlen(vg_name) == (size_t) (lvn - vgn)) {
4034 if (!str_list_add(cmd->mem, &lvnames,
4035 dm_pool_strdup(cmd->mem, lvn + 1))) {
4036 log_error("strlist allocation failed.");
4037 ret_max = ECMD_FAILED;
4038 goto out;
4039 }
4040 }
4041 }
4042
4043 log_very_verbose("Processing VG %s %s", vg_name, vg_uuid ? uuid : "");
4044
4045 do_lockd:
4046 if (is_lockd && !lockd_vg(cmd, vg_name, NULL, 0, &lockd_state)) {
4047 ret_max = ECMD_FAILED;
4048 report_log_ret_code(ret_max);
4049 continue;
4050 }
4051
4052 vg = vg_read(cmd, vg_name, vg_uuid, read_flags, lockd_state, &error_flags, &error_vg);
4053 if (_ignore_vg(cmd, error_flags, error_vg, vg_name, arg_vgnames, read_flags, &skip, &notfound)) {
4054 stack;
4055 ret_max = ECMD_FAILED;
4056 report_log_ret_code(ret_max);
4057 if (error_vg)
4058 unlock_and_release_vg(cmd, error_vg, vg_name);
4059 goto endvg;
4060 }
4061 if (error_vg)
4062 unlock_and_release_vg(cmd, error_vg, vg_name);
4063
4064 if (skip || notfound)
4065 goto endvg;
4066
4067 if (!is_lockd && vg_is_shared(vg)) {
4068 /* The lock_type changed since label_scan, won't really occur in practice. */
4069 log_debug("Repeat lock and read for local to shared vg");
4070 unlock_and_release_vg(cmd, vg, vg_name);
4071 is_lockd = 1;
4072 goto do_lockd;
4073 }
4074
4075 ret = process_each_lv_in_vg(cmd, vg, &lvnames, tags_arg, 0,
4076 handle, check_single_lv, process_single_lv);
4077 if (ret != ECMD_PROCESSED)
4078 stack;
4079 report_log_ret_code(ret);
4080 if (ret > ret_max)
4081 ret_max = ret;
4082
4083 unlock_vg(cmd, vg, vg_name);
4084 endvg:
4085 release_vg(vg);
4086 if (is_lockd && !lockd_vg(cmd, vg_name, "un", 0, &lockd_state))
4087 stack;
4088 log_set_report_object_name_and_id(NULL, NULL);
4089 }
4090 do_report_ret_code = 0;
4091 out:
4092 if (do_report_ret_code)
4093 report_log_ret_code(ret_max);
4094 log_restore_report_state(saved_log_report_state);
4095 return ret_max;
4096 }
4097
4098 /*
4099 * Call process_single_lv() for each LV selected by the command line arguments.
4100 */
4101 int process_each_lv(struct cmd_context *cmd,
4102 int argc, char **argv,
4103 const char *one_vgname, const char *one_lvname,
4104 uint32_t read_flags,
4105 struct processing_handle *handle,
4106 check_single_lv_fn_t check_single_lv,
4107 process_single_lv_fn_t process_single_lv)
4108 {
4109 log_report_t saved_log_report_state = log_get_report_state();
4110 int handle_supplied = handle != NULL;
4111 struct dm_list arg_tags; /* str_list */
4112 struct dm_list arg_vgnames; /* str_list */
4113 struct dm_list arg_lvnames; /* str_list */
4114 struct dm_list vgnameids_on_system; /* vgnameid_list */
4115 struct dm_list vgnameids_to_process; /* vgnameid_list */
4116 int enable_all_vgs = (cmd->cname->flags & ALL_VGS_IS_DEFAULT);
4117 int process_all_vgs_on_system = 0;
4118 int ret_max = ECMD_PROCESSED;
4119 int ret;
4120
4121 log_set_report_object_type(LOG_REPORT_OBJECT_TYPE_LV);
4122
4123 /* Disable error in vg_read so we can print it from ignore_vg. */
4124 cmd->vg_read_print_access_error = 0;
4125
4126 dm_list_init(&arg_tags);
4127 dm_list_init(&arg_vgnames);
4128 dm_list_init(&arg_lvnames);
4129 dm_list_init(&vgnameids_on_system);
4130 dm_list_init(&vgnameids_to_process);
4131
4132 /*
4133 * Find any LVs, VGs or tags explicitly provided on the command line.
4134 */
4135 if (cmd->get_vgname_from_options)
4136 ret = _get_arg_lvnames_using_options(cmd, argc, argv, &arg_vgnames, &arg_lvnames, &arg_tags);
4137 else
4138 ret = _get_arg_lvnames(cmd, argc, argv, one_vgname, one_lvname, &arg_vgnames, &arg_lvnames, &arg_tags);
4139
4140 if (ret != ECMD_PROCESSED) {
4141 ret_max = ret;
4142 goto_out;
4143 }
4144
4145 if (!handle && !(handle = init_processing_handle(cmd, NULL))) {
4146 ret_max = ECMD_FAILED;
4147 goto_out;
4148 }
4149
4150 if (handle->internal_report_for_select && !handle->selection_handle &&
4151 !init_selection_handle(cmd, handle, LVS)) {
4152 ret_max = ECMD_FAILED;
4153 goto_out;
4154 }
4155
4156 /*
4157 * Process all VGs on the system when:
4158 * . tags are specified and all VGs need to be read to
4159 * look for matching tags.
4160 * . no VG names are specified and the command defaults
4161 * to processing all VGs when none are specified.
4162 * . no VG names are specified and the select option needs
4163 * resolving.
4164 */
4165 if (!dm_list_empty(&arg_tags))
4166 process_all_vgs_on_system = 1;
4167 else if (dm_list_empty(&arg_vgnames) && enable_all_vgs)
4168 process_all_vgs_on_system = 1;
4169 else if (dm_list_empty(&arg_vgnames) && handle->internal_report_for_select)
4170 process_all_vgs_on_system = 1;
4171
4172 /*
4173 * Needed for a current listing of the global VG namespace.
4174 */
4175 if (process_all_vgs_on_system && !lock_global(cmd, "sh")) {
4176 ret_max = ECMD_FAILED;
4177 goto_out;
4178 }
4179
4180 /*
4181 * Scan all devices to populate lvmcache with initial
4182 * list of PVs and VGs.
4183 */
4184 if (!lvmcache_label_scan(cmd)) {
4185 ret_max = ECMD_FAILED;
4186 goto_out;
4187 }
4188
4189 /*
4190 * A list of all VGs on the system is needed when:
4191 * . processing all VGs on the system
4192 * . A VG name is specified which may refer to one
4193 * of multiple VGs on the system with that name.
4194 */
4195 log_very_verbose("Obtaining the complete list of VGs before processing their LVs");
4196
4197 if (!lvmcache_get_vgnameids(cmd, &vgnameids_on_system, NULL, 0)) {
4198 ret_max = ECMD_FAILED;
4199 goto_out;
4200 }
4201
4202 if (!dm_list_empty(&arg_vgnames)) {
4203 /* This may remove entries from arg_vgnames or vgnameids_on_system. */
4204 ret = _resolve_duplicate_vgnames(cmd, &arg_vgnames, &vgnameids_on_system);
4205 if (ret > ret_max)
4206 ret_max = ret;
4207 if (dm_list_empty(&arg_vgnames) && dm_list_empty(&arg_tags)) {
4208 ret_max = ECMD_FAILED;
4209 goto_out;
4210 }
4211 }
4212
4213 if (dm_list_empty(&arg_vgnames) && dm_list_empty(&vgnameids_on_system)) {
4214 /* FIXME Should be log_print, but suppressed for reporting cmds */
4215 log_verbose("No volume groups found.");
4216 ret_max = ECMD_PROCESSED;
4217 goto out;
4218 }
4219
4220 if (dm_list_empty(&arg_vgnames))
4221 read_flags |= READ_OK_NOTFOUND;
4222
4223 /*
4224 * When processing all VGs, vgnameids_on_system simply becomes
4225 * vgnameids_to_process.
4226 * When processing only specified VGs, then for each item in
4227 * arg_vgnames, move the corresponding entry from
4228 * vgnameids_on_system to vgnameids_to_process.
4229 */
4230 if (process_all_vgs_on_system)
4231 dm_list_splice(&vgnameids_to_process, &vgnameids_on_system);
4232 else
4233 _choose_vgs_to_process(cmd, &arg_vgnames, &vgnameids_on_system, &vgnameids_to_process);
4234
4235 ret = _process_lv_vgnameid_list(cmd, read_flags, &vgnameids_to_process, &arg_vgnames, &arg_lvnames,
4236 &arg_tags, handle, check_single_lv, process_single_lv);
4237
4238 if (ret > ret_max)
4239 ret_max = ret;
4240 out:
4241 if (!handle_supplied)
4242 destroy_processing_handle(cmd, handle);
4243
4244 log_restore_report_state(saved_log_report_state);
4245 return ret_max;
4246 }
4247
4248 static int _get_arg_pvnames(struct cmd_context *cmd,
4249 int argc, char **argv,
4250 struct dm_list *arg_pvnames,
4251 struct dm_list *arg_tags)
4252 {
4253 int opt = 0;
4254 char *at_sign, *tagname;
4255 char *arg_name;
4256 int ret_max = ECMD_PROCESSED;
4257
4258 for (; opt < argc; opt++) {
4259 arg_name = argv[opt];
4260
4261 dm_unescape_colons_and_at_signs(arg_name, NULL, &at_sign);
4262 if (at_sign && (at_sign == arg_name)) {
4263 tagname = at_sign + 1;
4264
4265 if (!validate_tag(tagname)) {
4266 log_error("Skipping invalid tag %s.", tagname);
4267 if (ret_max < EINVALID_CMD_LINE)
4268 ret_max = EINVALID_CMD_LINE;
4269 continue;
4270 }
4271 if (!str_list_add(cmd->mem, arg_tags,
4272 dm_pool_strdup(cmd->mem, tagname))) {
4273 log_error("strlist allocation failed.");
4274 return ECMD_FAILED;
4275 }
4276 continue;
4277 }
4278
4279 if (!str_list_add(cmd->mem, arg_pvnames,
4280 dm_pool_strdup(cmd->mem, arg_name))) {
4281 log_error("strlist allocation failed.");
4282 return ECMD_FAILED;
4283 }
4284 }
4285
4286 return ret_max;
4287 }
4288
4289 static int _get_arg_devices(struct cmd_context *cmd,
4290 struct dm_list *arg_pvnames,
4291 struct dm_list *arg_devices)
4292 {
4293 struct dm_str_list *sl;
4294 struct device_id_list *dil;
4295 int ret_max = ECMD_PROCESSED;
4296
4297 dm_list_iterate_items(sl, arg_pvnames) {
4298 if (!(dil = dm_pool_zalloc(cmd->mem, sizeof(*dil)))) {
4299 log_error("device_id_list alloc failed.");
4300 return ECMD_FAILED;
4301 }
4302
4303 if (!(dil->dev = dev_cache_get_existing(cmd, sl->str, cmd->filter))) {
4304 log_error("Cannot use %s: %s", sl->str, devname_error_reason(sl->str));
4305 ret_max = EINIT_FAILED;
4306 } else {
4307 memcpy(dil->pvid, dil->dev->pvid, ID_LEN);
4308 dm_list_add(arg_devices, &dil->list);
4309 }
4310 }
4311
4312 return ret_max;
4313 }
4314
4315 /* Process devices that are not PVs. */
4316
4317 static int _process_other_devices(struct cmd_context *cmd,
4318 struct processing_handle *handle,
4319 process_single_pv_fn_t process_single_pv)
4320 {
4321 struct dev_iter *iter;
4322 struct physical_volume pv_dummy;
4323 struct physical_volume *pv;
4324 struct device *dev;
4325 int failed = 0;
4326 int ret;
4327
4328 log_debug("Processing devices that are not PVs");
4329
4330 /*
4331 * We want devices here that passed filters during
4332 * label_scan but were found to not be PVs.
4333 *
4334 * No filtering used in iter, DEV_SCAN_FOUND_NOLABEL
4335 * was set by label_scan which did filtering.
4336 */
4337
4338 if (!(iter = dev_iter_create(NULL, 0)))
4339 return_0;
4340
4341 while ((dev = dev_iter_get(cmd, iter))) {
4342 if (sigint_caught()) {
4343 failed = 1;
4344 break;
4345 }
4346
4347 if (!(dev->flags & DEV_SCAN_FOUND_NOLABEL))
4348 continue;
4349
4350 /*
4351 * Pretend that each device is a PV with dummy values.
4352 * FIXME Formalize this extension or find an alternative.
4353 */
4354
4355 memset(&pv_dummy, 0, sizeof(pv_dummy));
4356 dm_list_init(&pv_dummy.tags);
4357 dm_list_init(&pv_dummy.segments);
4358 pv_dummy.dev = dev;
4359 pv = &pv_dummy;
4360
4361 log_very_verbose("Processing device %s.", dev_name(dev));
4362
4363 ret = process_single_pv(cmd, NULL, pv, handle);
4364 if (ret != ECMD_PROCESSED)
4365 failed = 1;
4366 }
4367 dev_iter_destroy(iter);
4368
4369 return failed ? 0 : 1;
4370 }
4371
4372 static int _process_duplicate_pvs(struct cmd_context *cmd,
4373 struct dm_list *arg_devices,
4374 int process_other_devices,
4375 struct processing_handle *handle,
4376 process_single_pv_fn_t process_single_pv)
4377 {
4378 struct device_id_list *dil;
4379 struct device_list *devl;
4380 struct dm_list unused_duplicate_devs;
4381 struct lvmcache_info *info;
4382 const char *vgname;
4383 const char *vgid;
4384 int failed = 0;
4385 int ret;
4386
4387 struct physical_volume dummy_pv = {
4388 .pe_size = 1,
4389 .tags = DM_LIST_HEAD_INIT(dummy_pv.tags),
4390 .segments= DM_LIST_HEAD_INIT(dummy_pv.segments),
4391 };
4392
4393 struct format_instance dummy_fid = {
4394 .metadata_areas_in_use = DM_LIST_HEAD_INIT(dummy_fid.metadata_areas_in_use),
4395 .metadata_areas_ignored = DM_LIST_HEAD_INIT(dummy_fid.metadata_areas_ignored),
4396 };
4397
4398 struct volume_group dummy_vg = {
4399 .cmd = cmd,
4400 .vgmem = cmd->mem,
4401 .extent_size = 1,
4402 .fid = &dummy_fid,
4403 .name = "",
4404 .system_id = (char *) "",
4405 .pvs = DM_LIST_HEAD_INIT(dummy_vg.pvs),
4406 .lvs = DM_LIST_HEAD_INIT(dummy_vg.lvs),
4407 .historical_lvs = DM_LIST_HEAD_INIT(dummy_vg.historical_lvs),
4408 .tags = DM_LIST_HEAD_INIT(dummy_vg.tags),
4409 };
4410
4411 dm_list_init(&unused_duplicate_devs);
4412
4413 if (!lvmcache_get_unused_duplicates(cmd, &unused_duplicate_devs))
4414 return_0;
4415
4416 dm_list_iterate_items(devl, &unused_duplicate_devs) {
4417 /* Duplicates are displayed if -a is used or the dev is named as an arg. */
4418
4419 if ((dil = device_id_list_find_dev(arg_devices, devl->dev)))
4420 device_id_list_remove(arg_devices, devl->dev);
4421
4422 if (!process_other_devices && !dil)
4423 continue;
4424
4425 if (!(cmd->cname->flags & ENABLE_DUPLICATE_DEVS))
4426 continue;
4427
4428 /*
4429 * Use the cached VG from the preferred device for the PV,
4430 * the vg is only used to display the VG name.
4431 *
4432 * This VG from lvmcache was not read from the duplicate
4433 * dev being processed here, but from the preferred dev
4434 * in lvmcache.
4435 *
4436 * When a duplicate PV is displayed, the reporting fields
4437 * that come from the VG metadata are not shown, because
4438 * the dev is not a part of the VG, the dev for the
4439 * preferred PV is (also the VG metadata in lvmcache is
4440 * not from the duplicate dev, but from the preferred dev).
4441 */
4442
4443 log_very_verbose("Processing duplicate device %s.", dev_name(devl->dev));
4444
4445 /*
4446 * Don't pass dev to lvmcache_info_from_pvid because we looking
4447 * for the chosen/preferred dev for this pvid.
4448 */
4449 if (!(info = lvmcache_info_from_pvid(devl->dev->pvid, NULL, 0))) {
4450 log_error(INTERNAL_ERROR "No info for pvid");
4451 return 0;
4452 }
4453
4454 vgname = lvmcache_vgname_from_info(info);
4455 vgid = vgname ? lvmcache_vgid_from_vgname(cmd, vgname) : NULL;
4456
4457 dummy_pv.dev = devl->dev;
4458 dummy_pv.fmt = lvmcache_fmt_from_info(info);
4459 dummy_vg.name = vgname ?: "";
4460
4461 if (vgid)
4462 memcpy(&dummy_vg.id, vgid, ID_LEN);
4463 else
4464 memset(&dummy_vg.id, 0, sizeof(dummy_vg.id));
4465
4466 ret = process_single_pv(cmd, &dummy_vg, &dummy_pv, handle);
4467 if (ret != ECMD_PROCESSED)
4468 failed = 1;
4469
4470 if (sigint_caught())
4471 return_0;
4472 }
4473
4474 return failed ? 0 : 1;
4475 }
4476
4477 static int _process_pvs_in_vg(struct cmd_context *cmd,
4478 struct volume_group *vg,
4479 struct dm_list *arg_devices,
4480 struct dm_list *arg_tags,
4481 int process_all_pvs,
4482 int skip,
4483 uint32_t error_flags,
4484 struct processing_handle *handle,
4485 process_single_pv_fn_t process_single_pv)
4486 {
4487 log_report_t saved_log_report_state = log_get_report_state();
4488 char vg_uuid[64] __attribute__((aligned(8)));
4489 int handle_supplied = handle != NULL;
4490 struct physical_volume *pv;
4491 struct pv_list *pvl;
4492 struct device_id_list *dil;
4493 const char *pv_name;
4494 int process_pv;
4495 int do_report_ret_code = 1;
4496 int ret_max = ECMD_PROCESSED;
4497 int ret = 0;
4498
4499 log_set_report_object_type(LOG_REPORT_OBJECT_TYPE_PV);
4500
4501 vg_uuid[0] = '\0';
4502 if (!id_write_format(&vg->id, vg_uuid, sizeof(vg_uuid)))
4503 stack;
4504
4505 if (!handle && (!(handle = init_processing_handle(cmd, NULL)))) {
4506 ret_max = ECMD_FAILED;
4507 goto_out;
4508 }
4509
4510 if (handle->internal_report_for_select && !handle->selection_handle &&
4511 !init_selection_handle(cmd, handle, PVS)) {
4512 ret_max = ECMD_FAILED;
4513 goto_out;
4514 }
4515
4516 if (!is_orphan_vg(vg->name))
4517 log_set_report_object_group_and_group_id(vg->name, &vg->id);
4518
4519 dm_list_iterate_items(pvl, &vg->pvs) {
4520 if (sigint_caught()) {
4521 ret_max = ECMD_FAILED;
4522 goto_out;
4523 }
4524
4525 pv = pvl->pv;
4526 pv_name = pv_dev_name(pv);
4527
4528 log_set_report_object_name_and_id(pv_name, &pv->id);
4529
4530 process_pv = process_all_pvs;
4531 dil = NULL;
4532
4533 /* Remove each arg_devices entry as it is processed. */
4534
4535 if (arg_devices && !dm_list_empty(arg_devices)) {
4536 if ((dil = device_id_list_find_dev(arg_devices, pv->dev)))
4537 device_id_list_remove(arg_devices, dil->dev);
4538 }
4539
4540 if (!process_pv && dil)
4541 process_pv = 1;
4542
4543 if (!process_pv && !dm_list_empty(arg_tags) &&
4544 str_list_match_list(arg_tags, &pv->tags, NULL))
4545 process_pv = 1;
4546
4547 process_pv = process_pv && select_match_pv(cmd, handle, vg, pv) && _select_matches(handle);
4548
4549 /*
4550 * The command has asked to process a specific PV
4551 * named on the command line, but the VG containing
4552 * that PV cannot be accessed. In this case report
4553 * and return an error. If the inaccessible PV is
4554 * not explicitly named on the command line, it is
4555 * silently skipped.
4556 */
4557 if (process_pv && skip && dil && error_flags) {
4558 if (error_flags & FAILED_EXPORTED)
4559 log_error("Cannot use PV %s in exported VG %s.", pv_name, vg->name);
4560 if (error_flags & FAILED_SYSTEMID)
4561 log_error("Cannot use PV %s in foreign VG %s.", pv_name, vg->name);
4562 if (error_flags & (FAILED_LOCK_TYPE | FAILED_LOCK_MODE))
4563 log_error("Cannot use PV %s in shared VG %s.", pv_name, vg->name);
4564 ret_max = ECMD_FAILED;
4565 }
4566
4567 if (process_pv) {
4568 if (skip)
4569 log_verbose("Skipping PV %s in VG %s.", pv_name, vg->name);
4570 else
4571 log_very_verbose("Processing PV %s in VG %s.", pv_name, vg->name);
4572
4573 if (!skip) {
4574 ret = process_single_pv(cmd, vg, pv, handle);
4575 if (ret != ECMD_PROCESSED)
4576 stack;
4577 report_log_ret_code(ret);
4578 if (ret > ret_max)
4579 ret_max = ret;
4580 }
4581 }
4582
4583 /*
4584 * When processing only specific PVs, we can quit once they've all been found.
4585 */
4586 if (!process_all_pvs && dm_list_empty(arg_tags) &&
4587 (!arg_devices || dm_list_empty(arg_devices)))
4588 break;
4589 log_set_report_object_name_and_id(NULL, NULL);
4590 }
4591
4592 do_report_ret_code = 0;
4593 out:
4594 if (do_report_ret_code)
4595 report_log_ret_code(ret_max);
4596 log_set_report_object_name_and_id(NULL, NULL);
4597 log_set_report_object_group_and_group_id(NULL, NULL);
4598 if (!handle_supplied)
4599 destroy_processing_handle(cmd, handle);
4600 log_restore_report_state(saved_log_report_state);
4601
4602 return ret_max;
4603 }
4604
4605 /*
4606 * Iterate through all PVs in each listed VG. Process a PV if
4607 * its dev or tag matches arg_devices or arg_tags. If both
4608 * arg_devices and arg_tags are empty, then process all PVs.
4609 * No PV should be processed more than once.
4610 *
4611 * Each PV is removed from arg_devices when it is processed.
4612 * Any names remaining in arg_devices were not found, and
4613 * should produce an error.
4614 */
4615 static int _process_pvs_in_vgs(struct cmd_context *cmd, uint32_t read_flags,
4616 struct dm_list *all_vgnameids,
4617 struct dm_list *arg_devices,
4618 struct dm_list *arg_tags,
4619 int process_all_pvs,
4620 struct processing_handle *handle,
4621 process_single_pv_fn_t process_single_pv)
4622 {
4623 log_report_t saved_log_report_state = log_get_report_state();
4624 struct volume_group *vg;
4625 struct volume_group *error_vg;
4626 struct vgnameid_list *vgnl;
4627 const char *vg_name;
4628 const char *vg_uuid;
4629 uint32_t lockd_state = 0;
4630 uint32_t error_flags = 0;
4631 int ret_max = ECMD_PROCESSED;
4632 int ret;
4633 int skip;
4634 int notfound;
4635 int is_lockd;
4636 int do_report_ret_code = 1;
4637
4638 log_set_report_object_type(LOG_REPORT_OBJECT_TYPE_VG);
4639
4640 dm_list_iterate_items(vgnl, all_vgnameids) {
4641 if (sigint_caught()) {
4642 ret_max = ECMD_FAILED;
4643 goto_out;
4644 }
4645
4646 vg_name = vgnl->vg_name;
4647 vg_uuid = vgnl->vgid;
4648 skip = 0;
4649 notfound = 0;
4650 is_lockd = lvmcache_vg_is_lockd_type(cmd, vg_name, vg_uuid);
4651
4652 if (is_orphan_vg(vg_name)) {
4653 log_set_report_object_type(LOG_REPORT_OBJECT_TYPE_ORPHAN);
4654 log_set_report_object_name_and_id(vg_name + sizeof(VG_ORPHANS), NULL);
4655 } else {
4656 log_set_report_object_name_and_id(vg_name, (const struct id*)vg_uuid);
4657 }
4658 do_lockd:
4659 if (is_lockd && !lockd_vg(cmd, vg_name, NULL, 0, &lockd_state)) {
4660 ret_max = ECMD_FAILED;
4661 report_log_ret_code(ret_max);
4662 continue;
4663 }
4664
4665 log_debug("Processing PVs in VG %s", vg_name);
4666
4667 error_flags = 0;
4668
4669 vg = vg_read(cmd, vg_name, vg_uuid, read_flags, lockd_state, &error_flags, &error_vg);
4670 if (_ignore_vg(cmd, error_flags, error_vg, vg_name, NULL, read_flags, &skip, &notfound) ||
4671 (!vg && !error_vg)) {
4672 stack;
4673 ret_max = ECMD_FAILED;
4674 report_log_ret_code(ret_max);
4675 if (!skip || (!vg && !error_vg))
4676 goto endvg;
4677 /* Drop through to eliminate unmpermitted PVs from the devices list */
4678 }
4679 if (notfound)
4680 goto endvg;
4681
4682 if (vg && !is_lockd && vg_is_shared(vg)) {
4683 /* The lock_type changed since label_scan, won't really occur in practice. */
4684 log_debug("Repeat lock and read for local to shared vg");
4685 unlock_and_release_vg(cmd, vg, vg_name);
4686 is_lockd = 1;
4687 goto do_lockd;
4688 }
4689
4690 /*
4691 * Don't call "continue" when skip is set, because we need to remove
4692 * error_vg->pvs entries from devices list.
4693 */
4694
4695 ret = _process_pvs_in_vg(cmd, vg ? vg : error_vg, arg_devices, arg_tags,
4696 process_all_pvs, skip, error_flags,
4697 handle, process_single_pv);
4698 if (ret != ECMD_PROCESSED)
4699 stack;
4700
4701 report_log_ret_code(ret);
4702
4703 if (ret > ret_max)
4704 ret_max = ret;
4705
4706 if (!skip && vg)
4707 unlock_vg(cmd, vg, vg->name);
4708 endvg:
4709 if (error_vg)
4710 unlock_and_release_vg(cmd, error_vg, vg_name);
4711 release_vg(vg);
4712 if (is_lockd && !lockd_vg(cmd, vg_name, "un", 0, &lockd_state))
4713 stack;
4714
4715 /* Quit early when possible. */
4716 if (!process_all_pvs && dm_list_empty(arg_tags) && dm_list_empty(arg_devices)) {
4717 do_report_ret_code = 0;
4718 goto out;
4719 }
4720
4721 log_set_report_object_name_and_id(NULL, NULL);
4722 }
4723 do_report_ret_code = 0;
4724 out:
4725 if (do_report_ret_code)
4726 report_log_ret_code(ret_max);
4727 log_restore_report_state(saved_log_report_state);
4728 return ret_max;
4729 }
4730
4731 int process_each_pv(struct cmd_context *cmd,
4732 int argc, char **argv, const char *only_this_vgname,
4733 int all_is_set, uint32_t read_flags,
4734 struct processing_handle *handle,
4735 process_single_pv_fn_t process_single_pv)
4736 {
4737 log_report_t saved_log_report_state = log_get_report_state();
4738 struct dm_list arg_tags; /* str_list */
4739 struct dm_list arg_pvnames; /* str_list */
4740 struct dm_list arg_devices; /* device_id_list */
4741 struct dm_list all_vgnameids; /* vgnameid_list */
4742 struct device_id_list *dil;
4743 int process_all_pvs;
4744 int process_other_devices;
4745 int ret_max = ECMD_PROCESSED;
4746 int ret;
4747
4748 log_set_report_object_type(LOG_REPORT_OBJECT_TYPE_PV);
4749 log_debug("Processing each PV");
4750
4751 /*
4752 * When processing a specific VG name, warn if it's inconsistent and
4753 * print an error if it's not found. Otherwise we're processing all
4754 * VGs, in which case the command doesn't care if the VG is inconsistent
4755 * or not found; it just wants to skip that VG. (It may be not found
4756 * if it was removed between creating the list of all VGs and then
4757 * processing each VG.
4758 */
4759 if (only_this_vgname)
4760 read_flags |= READ_WARN_INCONSISTENT;
4761 else
4762 read_flags |= READ_OK_NOTFOUND;
4763
4764 /* Disable error in vg_read so we can print it from ignore_vg. */
4765 cmd->vg_read_print_access_error = 0;
4766
4767 dm_list_init(&arg_tags);
4768 dm_list_init(&arg_pvnames);
4769 dm_list_init(&arg_devices);
4770 dm_list_init(&all_vgnameids);
4771
4772 /*
4773 * Create two lists from argv:
4774 * arg_pvnames: pvs explicitly named in argv
4775 * arg_tags: tags explicitly named in argv
4776 *
4777 * Then convert arg_pvnames, which are free-form, user-specified,
4778 * names/paths into arg_devices which can be used to match below.
4779 */
4780 if ((ret = _get_arg_pvnames(cmd, argc, argv, &arg_pvnames, &arg_tags)) != ECMD_PROCESSED) {
4781 ret_max = ret;
4782 goto_out;
4783 }
4784
4785 if ((cmd->cname->flags & DISALLOW_TAG_ARGS) && !dm_list_empty(&arg_tags)) {
4786 log_error("Tags cannot be used with this command.");
4787 return ECMD_FAILED;
4788 }
4789
4790 process_all_pvs = dm_list_empty(&arg_pvnames) && dm_list_empty(&arg_tags);
4791
4792 process_other_devices = process_all_pvs && (cmd->cname->flags & ENABLE_ALL_DEVS) && all_is_set;
4793
4794 /* Needed for a current listing of the global VG namespace. */
4795 if (!only_this_vgname && !lock_global(cmd, "sh")) {
4796 ret_max = ECMD_FAILED;
4797 goto_out;
4798 }
4799
4800 if (!(read_flags & PROCESS_SKIP_SCAN)) {
4801 if (!lvmcache_label_scan(cmd)) {
4802 ret_max = ECMD_FAILED;
4803 goto_out;
4804 }
4805 }
4806
4807 if (!lvmcache_get_vgnameids(cmd, &all_vgnameids, only_this_vgname, 1)) {
4808 ret_max = ret;
4809 goto_out;
4810 }
4811
4812 if ((ret = _get_arg_devices(cmd, &arg_pvnames, &arg_devices)) != ECMD_PROCESSED) {
4813 /* get_arg_devices reports EINIT_FAILED for any PV names not found. */
4814 ret_max = ret;
4815 if (ret_max == ECMD_FAILED)
4816 goto_out;
4817 ret_max = ECMD_FAILED; /* but ATM we've returned FAILED for all cases */
4818 }
4819
4820 ret = _process_pvs_in_vgs(cmd, read_flags, &all_vgnameids,
4821 &arg_devices, &arg_tags, process_all_pvs,
4822 handle, process_single_pv);
4823 if (ret != ECMD_PROCESSED)
4824 stack;
4825 if (ret > ret_max)
4826 ret_max = ret;
4827
4828 /*
4829 * Process the list of unused duplicate devs to display duplicate PVs
4830 * in two cases: 1. pvs -a (which has traditionally included duplicate
4831 * PVs in addition to the expected non-PV devices), 2. pvs <devname>
4832 * (duplicate dev is named on the command line.)
4833 */
4834 if (process_other_devices || !dm_list_empty(&arg_devices)) {
4835 if (!_process_duplicate_pvs(cmd, &arg_devices, process_other_devices, handle, process_single_pv))
4836 ret_max = ECMD_FAILED;
4837 }
4838
4839 dm_list_iterate_items(dil, &arg_devices) {
4840 log_error("Failed to find physical volume \"%s\".", dev_name(dil->dev));
4841 ret_max = ECMD_FAILED;
4842 }
4843
4844 /*
4845 * pvs -a and pvdisplay -a want to show devices that are not PVs.
4846 */
4847 if (process_other_devices) {
4848 if (!_process_other_devices(cmd, handle, process_single_pv))
4849 ret_max = ECMD_FAILED;
4850 }
4851
4852 out:
4853 log_restore_report_state(saved_log_report_state);
4854 return ret_max;
4855 }
4856
4857 int process_each_pv_in_vg(struct cmd_context *cmd, struct volume_group *vg,
4858 struct processing_handle *handle,
4859 process_single_pv_fn_t process_single_pv)
4860 {
4861 log_report_t saved_log_report_state = log_get_report_state();
4862 int whole_selected = 0;
4863 int ret_max = ECMD_PROCESSED;
4864 int ret;
4865 int do_report_ret_code = 1;
4866 struct pv_list *pvl;
4867
4868 log_set_report_object_type(LOG_REPORT_OBJECT_TYPE_PV);
4869
4870 if (!is_orphan_vg(vg->name))
4871 log_set_report_object_group_and_group_id(vg->name, &vg->id);
4872
4873 dm_list_iterate_items(pvl, &vg->pvs) {
4874 if (sigint_caught()) {
4875 ret_max = ECMD_FAILED;
4876 goto_out;
4877 }
4878
4879 log_set_report_object_name_and_id(pv_dev_name(pvl->pv), &pvl->pv->id);
4880
4881 ret = process_single_pv(cmd, vg, pvl->pv, handle);
4882 _update_selection_result(handle, &whole_selected);
4883 if (ret != ECMD_PROCESSED)
4884 stack;
4885 report_log_ret_code(ret);
4886 if (ret > ret_max)
4887 ret_max = ret;
4888
4889 log_set_report_object_name_and_id(NULL, NULL);
4890 }
4891
4892 _set_final_selection_result(handle, whole_selected);
4893 do_report_ret_code = 0;
4894 out:
4895 if (do_report_ret_code)
4896 report_log_ret_code(ret_max);
4897 log_restore_report_state(saved_log_report_state);
4898 return ret_max;
4899 }
4900
4901 int lvremove_single(struct cmd_context *cmd, struct logical_volume *lv,
4902 struct processing_handle *handle)
4903 {
4904 struct lvremove_params *lp = (handle) ? (struct lvremove_params *) handle->custom_handle : NULL;
4905
4906 /*
4907 * Single force is equivalent to single --yes
4908 * Even multiple --yes are equivalent to single --force
4909 * When we require -ff it cannot be replaced with -f -y
4910 */
4911 force_t force = (force_t) arg_count(cmd, force_ARG)
4912 ? : (arg_is_set(cmd, yes_ARG) ? DONT_PROMPT : PROMPT);
4913
4914 if (!lv_remove_with_dependencies(cmd, lv, force, 0))
4915 return_ECMD_FAILED;
4916
4917 if (cmd->scan_lvs && cmd->enable_devices_file && lp)
4918 /* save for removal */
4919 if (!str_list_add(cmd->mem, &lp->removed_uuids,
4920 dm_build_dm_uuid(cmd->mem, UUID_PREFIX, lv->lvid.s, NULL)))
4921 stack;
4922
4923 return ECMD_PROCESSED;
4924 }
4925
4926 int pvcreate_params_from_args(struct cmd_context *cmd, struct pvcreate_params *pp)
4927 {
4928 pp->yes = arg_count(cmd, yes_ARG);
4929 pp->force = (force_t) arg_count(cmd, force_ARG);
4930
4931 if (arg_int_value(cmd, labelsector_ARG, 0) >= LABEL_SCAN_SECTORS) {
4932 log_error("labelsector must be less than %lu.",
4933 LABEL_SCAN_SECTORS);
4934 return 0;
4935 }
4936
4937 pp->pva.label_sector = arg_int64_value(cmd, labelsector_ARG,
4938 DEFAULT_LABELSECTOR);
4939
4940 if (arg_is_set(cmd, metadataignore_ARG))
4941 pp->pva.metadataignore = arg_int_value(cmd, metadataignore_ARG,
4942 DEFAULT_PVMETADATAIGNORE);
4943 else
4944 pp->pva.metadataignore = find_config_tree_bool(cmd, metadata_pvmetadataignore_CFG, NULL);
4945
4946 if (arg_is_set(cmd, pvmetadatacopies_ARG) &&
4947 !arg_int_value(cmd, pvmetadatacopies_ARG, -1) &&
4948 pp->pva.metadataignore) {
4949 log_error("metadataignore only applies to metadatacopies > 0.");
4950 return 0;
4951 }
4952
4953 pp->zero = arg_int_value(cmd, zero_ARG, 1);
4954
4955 if (arg_sign_value(cmd, dataalignment_ARG, SIGN_NONE) == SIGN_MINUS) {
4956 log_error("Physical volume data alignment may not be negative.");
4957 return 0;
4958 }
4959 pp->pva.data_alignment = arg_uint64_value(cmd, dataalignment_ARG, UINT64_C(0));
4960
4961 if (pp->pva.data_alignment > UINT32_MAX) {
4962 log_error("Physical volume data alignment is too big.");
4963 return 0;
4964 }
4965
4966 if (arg_sign_value(cmd, dataalignmentoffset_ARG, SIGN_NONE) == SIGN_MINUS) {
4967 log_error("Physical volume data alignment offset may not be negative.");
4968 return 0;
4969 }
4970 pp->pva.data_alignment_offset = arg_uint64_value(cmd, dataalignmentoffset_ARG, UINT64_C(0));
4971
4972 if (pp->pva.data_alignment_offset > UINT32_MAX) {
4973 log_error("Physical volume data alignment offset is too big.");
4974 return 0;
4975 }
4976
4977 if ((pp->pva.data_alignment + pp->pva.data_alignment_offset) &&
4978 (pp->pva.pe_start != PV_PE_START_CALC)) {
4979 if ((pp->pva.data_alignment ? pp->pva.pe_start % pp->pva.data_alignment : pp->pva.pe_start) != pp->pva.data_alignment_offset) {
4980 log_warn("WARNING: Ignoring data alignment %s"
4981 " incompatible with restored pe_start value %s.",
4982 display_size(cmd, pp->pva.data_alignment + pp->pva.data_alignment_offset),
4983 display_size(cmd, pp->pva.pe_start));
4984 pp->pva.data_alignment = 0;
4985 pp->pva.data_alignment_offset = 0;
4986 }
4987 }
4988
4989 if (arg_sign_value(cmd, metadatasize_ARG, SIGN_NONE) == SIGN_MINUS) {
4990 log_error("Metadata size may not be negative.");
4991 return 0;
4992 }
4993
4994 if (arg_sign_value(cmd, bootloaderareasize_ARG, SIGN_NONE) == SIGN_MINUS) {
4995 log_error("Bootloader area size may not be negative.");
4996 return 0;
4997 }
4998
4999 pp->pva.pvmetadatasize = arg_uint64_value(cmd, metadatasize_ARG, UINT64_C(0));
5000 if (!pp->pva.pvmetadatasize) {
5001 pp->pva.pvmetadatasize = find_config_tree_int(cmd, metadata_pvmetadatasize_CFG, NULL);
5002 if (!pp->pva.pvmetadatasize)
5003 pp->pva.pvmetadatasize = get_default_pvmetadatasize_sectors();
5004 }
5005
5006 pp->pva.pvmetadatacopies = arg_int_value(cmd, pvmetadatacopies_ARG, -1);
5007 if (pp->pva.pvmetadatacopies < 0)
5008 pp->pva.pvmetadatacopies = find_config_tree_int(cmd, metadata_pvmetadatacopies_CFG, NULL);
5009
5010 pp->pva.ba_size = arg_uint64_value(cmd, bootloaderareasize_ARG, pp->pva.ba_size);
5011
5012 return 1;
5013 }
5014
5015 enum {
5016 PROMPT_PVCREATE_PV_IN_VG = 1,
5017 PROMPT_PVREMOVE_PV_IN_VG = 2,
5018 PROMPT_PVCREATE_DEV_SIZE = 4,
5019 };
5020
5021 enum {
5022 PROMPT_ANSWER_NO = 1,
5023 PROMPT_ANSWER_YES = 2
5024 };
5025
5026 /*
5027 * When a prompt entry is created, save any strings or info
5028 * in this struct that are needed for the prompt messages.
5029 * The VG/PV structs are not be available when the prompt
5030 * is run.
5031 */
5032 struct pvcreate_prompt {
5033 struct dm_list list;
5034 uint32_t type;
5035 uint64_t size;
5036 uint64_t new_size;
5037 const char *pv_name;
5038 const char *vg_name;
5039 struct device *dev;
5040 int answer;
5041 unsigned abort_command : 1;
5042 unsigned vg_name_unknown : 1;
5043 };
5044
5045 struct pvcreate_device {
5046 struct dm_list list;
5047 const char *name;
5048 struct device *dev;
5049 char pvid[ID_LEN + 1];
5050 const char *vg_name;
5051 int wiped;
5052 unsigned is_not_pv : 1; /* device is not a PV */
5053 unsigned is_orphan_pv : 1; /* device is an orphan PV */
5054 unsigned is_vg_pv : 1; /* device is a PV used in a VG */
5055 unsigned is_used_unknown_pv : 1; /* device is a PV used in an unknown VG */
5056 };
5057
5058 /*
5059 * If a PV is in a VG, and pvcreate or pvremove is run on it:
5060 *
5061 * pvcreate|pvremove -f : fails
5062 * pvcreate|pvremove -y : fails
5063 * pvcreate|pvremove -f -y : fails
5064 * pvcreate|pvremove -ff : get y/n prompt
5065 * pvcreate|pvremove -ff -y : succeeds
5066 *
5067 * FIXME: there are a lot of various phrasings used depending on the
5068 * command and specific case. Find some similar way to phrase these.
5069 */
5070
5071 static void _check_pvcreate_prompt(struct cmd_context *cmd,
5072 struct pvcreate_params *pp,
5073 struct pvcreate_prompt *prompt,
5074 int ask)
5075 {
5076 const char *vgname = prompt->vg_name ? prompt->vg_name : "<unknown>";
5077 const char *pvname = prompt->pv_name;
5078 int answer_yes = 0;
5079 int answer_no = 0;
5080
5081 /* The VG name can be unknown when the PV is used but metadata is not available */
5082
5083 if (prompt->type & PROMPT_PVCREATE_PV_IN_VG) {
5084 if (pp->force != DONT_PROMPT_OVERRIDE) {
5085 answer_no = 1;
5086
5087 if (prompt->vg_name_unknown) {
5088 log_error("PV %s is used by a VG but its metadata is missing.", pvname);
5089 log_error("Can't initialize PV '%s' without -ff.", pvname);
5090 } else if (!strcmp(command_name(cmd), "pvcreate")) {
5091 log_error("Can't initialize physical volume \"%s\" of volume group \"%s\" without -ff", pvname, vgname);
5092 } else {
5093 log_error("Physical volume '%s' is already in volume group '%s'", pvname, vgname);
5094 log_error("Unable to add physical volume '%s' to volume group '%s'", pvname, vgname);
5095 }
5096 } else if (pp->yes) {
5097 answer_yes = 1;
5098 } else if (ask) {
5099 if (yes_no_prompt("Really INITIALIZE physical volume \"%s\" of volume group \"%s\" [y/n]? ", pvname, vgname) == 'n') {
5100 answer_no = 1;
5101 } else {
5102 answer_yes = 1;
5103 log_warn("WARNING: Forcing physical volume creation on %s of volume group \"%s\"", pvname, vgname);
5104 }
5105 }
5106
5107 }
5108
5109 if (prompt->type & PROMPT_PVCREATE_DEV_SIZE) {
5110 if (pp->yes) {
5111 log_warn("WARNING: Faking size of PV %s. Don't write outside real device.", pvname);
5112 answer_yes = 1;
5113 } else if (ask) {
5114 if (prompt->new_size != prompt->size) {
5115 if (yes_no_prompt("WARNING: %s: device size %s does not match requested size %s. Proceed? [y/n]: ", pvname,
5116 display_size(cmd, prompt->size),
5117 display_size(cmd, prompt->new_size)) == 'n') {
5118 answer_no = 1;
5119 } else {
5120 answer_yes = 1;
5121 log_warn("WARNING: Faking size of PV %s. Don't write outside real device.", pvname);
5122 }
5123 }
5124 }
5125 }
5126
5127 if (prompt->type & PROMPT_PVREMOVE_PV_IN_VG) {
5128 if (pp->force != DONT_PROMPT_OVERRIDE) {
5129 answer_no = 1;
5130
5131 if (prompt->vg_name_unknown)
5132 log_error("PV %s is used by a VG but its metadata is missing.", pvname);
5133 else
5134 log_error("PV %s is used by VG %s so please use vgreduce first.", pvname, vgname);
5135 log_error("(If you are certain you need pvremove, then confirm by using --force twice.)");
5136 } else if (pp->yes) {
5137 log_warn("WARNING: PV %s is used by VG %s.", pvname, vgname);
5138 answer_yes = 1;
5139 } else if (ask) {
5140 log_warn("WARNING: PV %s is used by VG %s.", pvname, vgname);
5141 if (yes_no_prompt("Really WIPE LABELS from physical volume \"%s\" of volume group \"%s\" [y/n]? ", pvname, vgname) == 'n')
5142 answer_no = 1;
5143 else
5144 answer_yes = 1;
5145 }
5146 }
5147
5148 if (answer_yes && answer_no) {
5149 log_warn("WARNING: prompt answer yes is overridden by prompt answer no.");
5150 answer_yes = 0;
5151 }
5152
5153 /*
5154 * no answer is valid when not asking the user.
5155 * the caller uses this to check if all the prompts
5156 * can be answered automatically without prompts.
5157 */
5158 if (!ask && !answer_yes && !answer_no)
5159 return;
5160
5161 if (answer_no)
5162 prompt->answer = PROMPT_ANSWER_NO;
5163 else if (answer_yes)
5164 prompt->answer = PROMPT_ANSWER_YES;
5165
5166 /*
5167 * Mostly historical messages. Other messages above could be moved
5168 * here to separate the answer logic from the messages.
5169 */
5170
5171 if ((prompt->type & (PROMPT_PVCREATE_DEV_SIZE | PROMPT_PVCREATE_PV_IN_VG)) &&
5172 (prompt->answer == PROMPT_ANSWER_NO))
5173 log_error("%s: physical volume not initialized.", pvname);
5174
5175 if ((prompt->type & PROMPT_PVREMOVE_PV_IN_VG) &&
5176 (prompt->answer == PROMPT_ANSWER_NO))
5177 log_error("%s: physical volume label not removed.", pvname);
5178
5179 if ((prompt->type & PROMPT_PVREMOVE_PV_IN_VG) &&
5180 (prompt->answer == PROMPT_ANSWER_YES) &&
5181 (pp->force == DONT_PROMPT_OVERRIDE))
5182 log_warn("WARNING: Wiping physical volume label from %s of volume group \"%s\".", pvname, vgname);
5183 }
5184
5185 static struct pvcreate_device *_pvcreate_list_find_dev(struct dm_list *devices, struct device *dev)
5186 {
5187 struct pvcreate_device *pd;
5188
5189 dm_list_iterate_items(pd, devices) {
5190 if (pd->dev == dev)
5191 return pd;
5192 }
5193
5194 return NULL;
5195 }
5196
5197 static struct pvcreate_device *_pvcreate_list_find_name(struct dm_list *devices, const char *name)
5198 {
5199 struct pvcreate_device *pd;
5200
5201 dm_list_iterate_items(pd, devices) {
5202 if (!strcmp(pd->name, name))
5203 return pd;
5204 }
5205
5206 return NULL;
5207 }
5208
5209 static int _pvcreate_check_used(struct cmd_context *cmd,
5210 struct pvcreate_params *pp,
5211 struct pvcreate_device *pd)
5212 {
5213 struct pvcreate_prompt *prompt;
5214 uint64_t size = 0;
5215 uint64_t new_size = 0;
5216 int need_size_prompt = 0;
5217 int need_vg_prompt = 0;
5218 struct lvmcache_info *info;
5219 const char *vgname;
5220
5221 log_debug("Checking %s for pvcreate %.32s.",
5222 dev_name(pd->dev), pd->dev->pvid[0] ? pd->dev->pvid : "");
5223
5224 if (!pd->dev->pvid[0]) {
5225 log_debug("Check pvcreate arg %s no PVID found", dev_name(pd->dev));
5226 pd->is_not_pv = 1;
5227 return 1;
5228 }
5229
5230 /*
5231 * Don't allow using a device with duplicates.
5232 */
5233 if (lvmcache_pvid_in_unused_duplicates(pd->dev->pvid)) {
5234 log_error("Cannot use device %s with duplicates.", dev_name(pd->dev));
5235 dm_list_move(&pp->arg_fail, &pd->list);
5236 return 0;
5237 }
5238
5239 if (!(info = lvmcache_info_from_pvid(pd->dev->pvid, pd->dev, 0))) {
5240 log_error("Failed to read lvm info for %s PVID %s.", dev_name(pd->dev), pd->dev->pvid);
5241 dm_list_move(&pp->arg_fail, &pd->list);
5242 return 0;
5243 }
5244
5245 vgname = lvmcache_vgname_from_info(info);
5246
5247 /*
5248 * What kind of device is this: an orphan PV, an uninitialized/unused
5249 * device, a PV used in a VG.
5250 */
5251 if (vgname && !is_orphan_vg(vgname)) {
5252 /* Device is a PV used in a VG. */
5253 log_debug("Check pvcreate arg %s found vg %s.", dev_name(pd->dev), vgname);
5254 pd->is_vg_pv = 1;
5255 pd->vg_name = dm_pool_strdup(cmd->mem, vgname);
5256 } else if (!vgname || (vgname && is_orphan_vg(vgname))) {
5257 uint32_t ext_flags = lvmcache_ext_flags(info);
5258 if (ext_flags & PV_EXT_USED) {
5259 /* Device is used in an unknown VG. */
5260 log_debug("Check pvcreate arg %s found EXT_USED flag.", dev_name(pd->dev));
5261 pd->is_used_unknown_pv = 1;
5262 } else {
5263 /* Device is an orphan PV. */
5264 log_debug("Check pvcreate arg %s is orphan.", dev_name(pd->dev));
5265 pd->is_orphan_pv = 1;
5266 }
5267 pp->orphan_vg_name = FMT_TEXT_ORPHAN_VG_NAME;
5268 }
5269
5270 if (arg_is_set(cmd, setphysicalvolumesize_ARG)) {
5271 new_size = arg_uint64_value(cmd, setphysicalvolumesize_ARG, UINT64_C(0));
5272
5273 if (!dev_get_size(pd->dev, &size)) {
5274 log_error("Can't get device size of %s.", dev_name(pd->dev));
5275 dm_list_move(&pp->arg_fail, &pd->list);
5276 return 0;
5277 }
5278
5279 if (new_size != size)
5280 need_size_prompt = 1;
5281 }
5282
5283 /*
5284 * pvcreate is being run on this device, and it's not a PV,
5285 * or is an orphan PV. Neither case requires a prompt.
5286 * Or, pvcreate is being run on this device, but the device
5287 * is already a PV in a VG. A prompt or force option is required
5288 * to use it.
5289 */
5290 if (pd->is_orphan_pv || pd->is_not_pv)
5291 need_vg_prompt = 0;
5292 else
5293 need_vg_prompt = 1;
5294
5295 if (!need_size_prompt && !need_vg_prompt)
5296 return 1;
5297
5298 if (!(prompt = dm_pool_zalloc(cmd->mem, sizeof(*prompt)))) {
5299 dm_list_move(&pp->arg_fail, &pd->list);
5300 return_0;
5301 }
5302 prompt->dev = pd->dev;
5303 prompt->pv_name = dm_pool_strdup(cmd->mem, dev_name(pd->dev));
5304 prompt->size = size;
5305 prompt->new_size = new_size;
5306
5307 if (pd->is_used_unknown_pv)
5308 prompt->vg_name_unknown = 1;
5309 else if (need_vg_prompt)
5310 prompt->vg_name = dm_pool_strdup(cmd->mem, vgname);
5311
5312 if (need_size_prompt)
5313 prompt->type |= PROMPT_PVCREATE_DEV_SIZE;
5314
5315 if (need_vg_prompt)
5316 prompt->type |= PROMPT_PVCREATE_PV_IN_VG;
5317
5318 dm_list_add(&pp->prompts, &prompt->list);
5319
5320 return 1;
5321 }
5322
5323 static int _pvremove_check_used(struct cmd_context *cmd,
5324 struct pvcreate_params *pp,
5325 struct pvcreate_device *pd)
5326 {
5327 struct pvcreate_prompt *prompt;
5328 struct lvmcache_info *info;
5329 const char *vgname = NULL;
5330
5331 log_debug("Checking %s for pvremove %.32s.",
5332 dev_name(pd->dev), pd->dev->pvid[0] ? pd->dev->pvid : "");
5333
5334 /*
5335 * Is there a pv here already?
5336 * If not, this is an error unless you used -f.
5337 */
5338
5339 if (!pd->dev->pvid[0]) {
5340 log_debug("Check pvremove arg %s no PVID found", dev_name(pd->dev));
5341 if (pp->force)
5342 return 1;
5343 pd->is_not_pv = 1;
5344 }
5345
5346 if (!(info = lvmcache_info_from_pvid(pd->dev->pvid, pd->dev, 0))) {
5347 if (pp->force)
5348 return 1;
5349 log_error("No PV found on device %s.", dev_name(pd->dev));
5350 dm_list_move(&pp->arg_fail, &pd->list);
5351 return 0;
5352 }
5353
5354 if (info)
5355 vgname = lvmcache_vgname_from_info(info);
5356
5357 /*
5358 * What kind of device is this: an orphan PV, an uninitialized/unused
5359 * device, a PV used in a VG.
5360 */
5361
5362 if (pd->is_not_pv) {
5363 /* Device is not a PV. */
5364 log_debug("Check pvremove arg %s device is not a PV.", dev_name(pd->dev));
5365
5366 } else if (vgname && !is_orphan_vg(vgname)) {
5367 /* Device is a PV used in a VG. */
5368 log_debug("Check pvremove arg %s found vg %s.", dev_name(pd->dev), vgname);
5369 pd->is_vg_pv = 1;
5370 pd->vg_name = dm_pool_strdup(cmd->mem, vgname);
5371
5372 } else if (info && (!vgname || (vgname && is_orphan_vg(vgname)))) {
5373 uint32_t ext_flags = lvmcache_ext_flags(info);
5374 if (ext_flags & PV_EXT_USED) {
5375 /* Device is used in an unknown VG. */
5376 log_debug("Check pvremove arg %s found EXT_USED flag.", dev_name(pd->dev));
5377 pd->is_used_unknown_pv = 1;
5378 } else {
5379 /* Device is an orphan PV. */
5380 log_debug("Check pvremove arg %s is orphan.", dev_name(pd->dev));
5381 pd->is_orphan_pv = 1;
5382 }
5383 pp->orphan_vg_name = FMT_TEXT_ORPHAN_VG_NAME;
5384 }
5385
5386 if (pd->is_not_pv) {
5387 log_error("No PV found on device %s.", dev_name(pd->dev));
5388 dm_list_move(&pp->arg_fail, &pd->list);
5389 return 0;
5390 }
5391
5392 /*
5393 * pvremove is being run on this device, and it's not a PV,
5394 * or is an orphan PV. Neither case requires a prompt.
5395 */
5396 if (pd->is_orphan_pv)
5397 return 1;
5398
5399 /*
5400 * pvremove is being run on this device, but the device is in a VG.
5401 * A prompt or force option is required to use it.
5402 */
5403
5404 if (!(prompt = dm_pool_zalloc(cmd->mem, sizeof(*prompt)))) {
5405 dm_list_move(&pp->arg_fail, &pd->list);
5406 return_0;
5407 }
5408 prompt->dev = pd->dev;
5409 prompt->pv_name = dm_pool_strdup(cmd->mem, dev_name(pd->dev));
5410 if (pd->is_used_unknown_pv)
5411 prompt->vg_name_unknown = 1;
5412 else
5413 prompt->vg_name = dm_pool_strdup(cmd->mem, vgname);
5414 prompt->type |= PROMPT_PVREMOVE_PV_IN_VG;
5415 dm_list_add(&pp->prompts, &prompt->list);
5416
5417 return 1;
5418 }
5419
5420 static int _confirm_check_used(struct cmd_context *cmd,
5421 struct pvcreate_params *pp,
5422 struct pvcreate_device *pd)
5423 {
5424 struct lvmcache_info *info = NULL;
5425 const char *vgname = NULL;
5426 int is_not_pv = 0;
5427
5428 log_debug("Checking %s to confirm %.32s.",
5429 dev_name(pd->dev), pd->dev->pvid[0] ? pd->dev->pvid : "");
5430
5431 if (!pd->dev->pvid[0]) {
5432 log_debug("Check confirm arg %s no PVID found", dev_name(pd->dev));
5433 is_not_pv = 1;
5434 }
5435
5436 if (!(info = lvmcache_info_from_pvid(pd->dev->pvid, pd->dev, 0))) {
5437 log_debug("Check confirm arg %s no info.", dev_name(pd->dev));
5438 is_not_pv = 1;
5439 }
5440
5441 if (info)
5442 vgname = lvmcache_vgname_from_info(info);
5443
5444
5445 /*
5446 * What kind of device is this: an orphan PV, an uninitialized/unused
5447 * device, a PV used in a VG.
5448 */
5449 if (vgname && !is_orphan_vg(vgname)) {
5450 /* Device is a PV used in a VG. */
5451
5452 if (pd->is_orphan_pv || pd->is_not_pv || pd->is_used_unknown_pv) {
5453 /* In first check it was an orphan or unused. */
5454 goto fail;
5455 }
5456
5457 if (pd->is_vg_pv && pd->vg_name && strcmp(pd->vg_name, vgname)) {
5458 /* In first check it was in a different VG. */
5459 goto fail;
5460 }
5461 } else if (info && (!vgname || is_orphan_vg(vgname))) {
5462 uint32_t ext_flags = lvmcache_ext_flags(info);
5463
5464 /* Device is an orphan PV. */
5465
5466 if (pd->is_not_pv) {
5467 /* In first check it was not a PV. */
5468 goto fail;
5469 }
5470
5471 if (pd->is_vg_pv) {
5472 /* In first check it was in a VG. */
5473 goto fail;
5474 }
5475
5476 if ((ext_flags & PV_EXT_USED) && !pd->is_used_unknown_pv) {
5477 /* In first check it was different. */
5478 goto fail;
5479 }
5480
5481 if (!(ext_flags & PV_EXT_USED) && pd->is_used_unknown_pv) {
5482 /* In first check it was different. */
5483 goto fail;
5484 }
5485 } else if (is_not_pv) {
5486 /* Device is not a PV. */
5487 if (pd->is_orphan_pv || pd->is_used_unknown_pv) {
5488 /* In first check it was an orphan PV. */
5489 goto fail;
5490 }
5491
5492 if (pd->is_vg_pv) {
5493 /* In first check it was in a VG. */
5494 goto fail;
5495 }
5496 }
5497
5498 return 1;
5499
5500 fail:
5501 log_error("Cannot use device %s: it changed during prompt.", dev_name(pd->dev));
5502 dm_list_move(&pp->arg_fail, &pd->list);
5503 return 1;
5504 }
5505
5506 /*
5507 * This can be used by pvcreate, vgcreate and vgextend to create PVs. The
5508 * callers need to set up the pvcreate_each_params structure based on command
5509 * line args. This includes the pv_names field which specifies the devices to
5510 * create PVs on.
5511 *
5512 * This function returns 0 (failed) if the caller requires all specified
5513 * devices to be created, and any of those devices are not found, or any of
5514 * them cannot be created.
5515 *
5516 * This function returns 1 (success) if the caller requires all specified
5517 * devices to be created, and all are created, or if the caller does not
5518 * require all specified devices to be created and one or more were created.
5519 *
5520 * Process of opening, scanning and filtering:
5521 *
5522 * - label scan and filter all devs
5523 * . open ro
5524 * . standard label scan at the start of command
5525 * . done prior to this function
5526 *
5527 * - label scan and filter dev args
5528 * . label_scan_devs(&scan_devs) in this function
5529 * . open ro
5530 * . uses full md component check
5531 * . typically the first scan and filter of pvcreate devs
5532 *
5533 * - close and reopen dev args
5534 * . open rw and excl
5535 * . done by label_scan_devs_excl
5536 *
5537 * - repeat label scan and filter dev args
5538 * . using reopened rw excl fd
5539 * . since something could have used dev
5540 * in the small window between close and reopen
5541 *
5542 * - wipe and write new headers
5543 * . using reopened rw excl fd
5544 */
5545
5546 int pvcreate_each_device(struct cmd_context *cmd,
5547 struct processing_handle *handle,
5548 struct pvcreate_params *pp)
5549 {
5550 struct pvcreate_device *pd, *pd2;
5551 struct pvcreate_prompt *prompt, *prompt2;
5552 struct physical_volume *pv;
5553 struct volume_group *orphan_vg;
5554 struct dm_list remove_duplicates;
5555 struct dm_list arg_sort;
5556 struct dm_list scan_devs;
5557 struct dm_list rescan_devs;
5558 struct pv_list *pvl;
5559 struct pv_list *vgpvl;
5560 struct device_list *devl;
5561 char pvid[ID_LEN + 1] __attribute__((aligned(8))) = { 0 };
5562 const char *pv_name;
5563 unsigned int physical_block_size, logical_block_size;
5564 unsigned int prev_pbs = 0, prev_lbs = 0;
5565 int must_use_all = (cmd->cname->flags & MUST_USE_ALL_ARGS);
5566 int unlocked_for_prompts = 0;
5567 int found;
5568 unsigned i;
5569
5570 set_pv_notify(cmd);
5571
5572 dm_list_init(&remove_duplicates);
5573 dm_list_init(&arg_sort);
5574 dm_list_init(&scan_devs);
5575 dm_list_init(&rescan_devs);
5576
5577 handle->custom_handle = pp;
5578
5579 /*
5580 * Create a list entry for each name arg.
5581 */
5582 for (i = 0; i < pp->pv_count; i++) {
5583 dm_unescape_colons_and_at_signs(pp->pv_names[i], NULL, NULL);
5584
5585 pv_name = pp->pv_names[i];
5586
5587 if (_pvcreate_list_find_name(&pp->arg_devices, pv_name)) {
5588 log_error("Duplicate device name found on input: %s.", pv_name);
5589 return 0;
5590 }
5591
5592 if (!(pd = dm_pool_zalloc(cmd->mem, sizeof(*pd)))) {
5593 log_error("alloc failed.");
5594 return 0;
5595 }
5596
5597 if (!(pd->name = dm_pool_strdup(cmd->mem, pv_name))) {
5598 log_error("strdup failed.");
5599 return 0;
5600 }
5601
5602 dm_list_add(&pp->arg_devices, &pd->list);
5603 }
5604
5605 /*
5606 * Translate arg names into struct device's.
5607 *
5608 * lvmcache_label_scan has already been run by the caller.
5609 * It has likely found and filtered pvremove args, but often
5610 * not pvcreate args, since pvcreate args are not typically PVs
5611 * yet (but may be.)
5612 *
5613 * We call label_scan_devs on the args, using the full
5614 * md filter (the previous scan likely did not use the
5615 * full md filter - we really only need to check the
5616 * command args to ensure they are not md components.)
5617 */
5618
5619 dm_list_iterate_items_safe(pd, pd2, &pp->arg_devices) {
5620 struct device *dev;
5621
5622 /* No filter used here */
5623 if (!(dev = dev_cache_get_existing(cmd, pd->name, NULL))) {
5624 log_error("No device found for %s.", pd->name);
5625 dm_list_del(&pd->list);
5626 dm_list_add(&pp->arg_fail, &pd->list);
5627 continue;
5628 }
5629
5630 if (!(devl = dm_pool_zalloc(cmd->mem, sizeof(*devl))))
5631 goto bad;
5632
5633 devl->dev = dev;
5634 pd->dev = dev;
5635
5636 dm_list_add(&scan_devs, &devl->list);
5637 }
5638
5639 if (dm_list_empty(&pp->arg_devices))
5640 goto_bad;
5641
5642 /*
5643 * Clear the filtering results from lvmcache_label_scan because we are
5644 * going to rerun the filters and don't want to get the results saved
5645 * by the prior filtering. The filtering in label scan will use full
5646 * md filter.
5647 *
5648 * We allow pvcreate to look outside devices file here to find
5649 * the target device, in case the user has not added the device
5650 * being pvcreated to the devices file.
5651 */
5652 dm_list_iterate_items(devl, &scan_devs)
5653 cmd->filter->wipe(cmd, cmd->filter, devl->dev, NULL);
5654
5655 cmd->use_full_md_check = 1;
5656
5657 if (cmd->enable_devices_file && !pp->is_remove)
5658 cmd->filter_deviceid_skip = 1;
5659
5660 log_debug("Scanning and filtering device args (%u).", dm_list_size(&scan_devs));
5661 label_scan_devs(cmd, cmd->filter, &scan_devs);
5662
5663 /*
5664 * Check if the filtering done by label scan excluded any devices.
5665 */
5666 dm_list_iterate_items_safe(pd, pd2, &pp->arg_devices) {
5667 if (!cmd->filter->passes_filter(cmd, cmd->filter, pd->dev, NULL)) {
5668 log_error("Cannot use %s: %s", pd->name, devname_error_reason(pd->name));
5669 dm_list_del(&pd->list);
5670 dm_list_add(&pp->arg_fail, &pd->list);
5671 }
5672 }
5673 cmd->filter_deviceid_skip = 0;
5674
5675 /*
5676 * Can the command continue if some specified devices were not found?
5677 */
5678 if (must_use_all && !dm_list_empty(&pp->arg_fail)) {
5679 log_error("Command requires all devices to be found.");
5680 return 0;
5681 }
5682
5683 /*
5684 * Check for consistent block sizes.
5685 */
5686 if (pp->check_consistent_block_size) {
5687 dm_list_iterate_items(pd, &pp->arg_devices) {
5688 logical_block_size = 0;
5689 physical_block_size = 0;
5690
5691 if (!dev_get_direct_block_sizes(pd->dev, &physical_block_size, &logical_block_size)) {
5692 log_warn("WARNING: Unknown block size for device %s.", dev_name(pd->dev));
5693 continue;
5694 }
5695
5696 if (!logical_block_size) {
5697 log_warn("WARNING: Unknown logical_block_size for device %s.", dev_name(pd->dev));
5698 continue;
5699 }
5700
5701 if (!prev_lbs) {
5702 prev_lbs = logical_block_size;
5703 prev_pbs = physical_block_size;
5704 continue;
5705 }
5706
5707 if (prev_lbs == logical_block_size) {
5708 /* Require lbs to match, just warn about unmatching pbs. */
5709 if (!cmd->allow_mixed_block_sizes && prev_pbs && physical_block_size &&
5710 (prev_pbs != physical_block_size))
5711 log_warn("WARNING: Devices have inconsistent physical block sizes (%u and %u).",
5712 prev_pbs, physical_block_size);
5713 continue;
5714 }
5715
5716 if (!cmd->allow_mixed_block_sizes) {
5717 log_error("Devices have inconsistent logical block sizes (%u and %u).",
5718 prev_lbs, logical_block_size);
5719 log_print("See lvm.conf allow_mixed_block_sizes.");
5720 return 0;
5721 }
5722 }
5723 }
5724
5725 /* check_used moves pd entries into the arg_fail list if pvcreate/pvremove is disallowed */
5726 dm_list_iterate_items_safe(pd, pd2, &pp->arg_devices) {
5727 if (pp->is_remove)
5728 _pvremove_check_used(cmd, pp, pd);
5729 else
5730 _pvcreate_check_used(cmd, pp, pd);
5731 }
5732
5733 /*
5734 * If the user specified a uuid for the new PV, check
5735 * if a PV on another dev is already using that uuid.
5736 */
5737 if (!pp->is_remove && pp->uuid_str) {
5738 struct device *dev;
5739 if ((dev = lvmcache_device_from_pv_id(cmd, &pp->pva.id, NULL))) {
5740 dm_list_iterate_items_safe(pd, pd2, &pp->arg_devices) {
5741 if (pd->dev != dev) {
5742 log_error("UUID %s already in use on \"%s\".", pp->uuid_str, dev_name(dev));
5743 dm_list_move(&pp->arg_fail, &pd->list);
5744 }
5745 }
5746 }
5747 }
5748
5749 /*
5750 * Special case: pvremove -ff is allowed to clear a duplicate device in
5751 * the unchosen duplicates list. We save them here and erase them below.
5752 */
5753 if (pp->is_remove && (pp->force == DONT_PROMPT_OVERRIDE) &&
5754 !dm_list_empty(&pp->arg_devices) && lvmcache_has_duplicate_devs()) {
5755 dm_list_iterate_items_safe(pd, pd2, &pp->arg_devices) {
5756 if (lvmcache_dev_is_unused_duplicate(pd->dev)) {
5757 log_debug("Check pvremove arg %s device is a duplicate.", dev_name(pd->dev));
5758 dm_list_move(&remove_duplicates, &pd->list);
5759 }
5760 }
5761 }
5762
5763 /*
5764 * Any devices not moved to arg_fail can be processed.
5765 */
5766 dm_list_splice(&pp->arg_process, &pp->arg_devices);
5767
5768 /*
5769 * Can the command continue if some specified devices cannot be used?
5770 */
5771 if (!dm_list_empty(&pp->arg_fail) && must_use_all)
5772 goto_bad;
5773
5774 /*
5775 * The command cannot continue if there are no devices to process.
5776 */
5777 if (dm_list_empty(&pp->arg_process) && dm_list_empty(&remove_duplicates)) {
5778 log_debug("No devices to process.");
5779 goto bad;
5780 }
5781
5782 /*
5783 * Clear any prompts that have answers without asking the user.
5784 */
5785 dm_list_iterate_items_safe(prompt, prompt2, &pp->prompts) {
5786 _check_pvcreate_prompt(cmd, pp, prompt, 0);
5787
5788 switch (prompt->answer) {
5789 case PROMPT_ANSWER_YES:
5790 /* The PV can be used, leave it on arg_process. */
5791 dm_list_del(&prompt->list);
5792 break;
5793 case PROMPT_ANSWER_NO:
5794 /* The PV cannot be used, remove it from arg_process. */
5795 if ((pd = _pvcreate_list_find_dev(&pp->arg_process, prompt->dev)))
5796 dm_list_move(&pp->arg_fail, &pd->list);
5797 dm_list_del(&prompt->list);
5798 break;
5799 }
5800 }
5801
5802 if (!dm_list_empty(&pp->arg_fail) && must_use_all)
5803 goto_bad;
5804
5805 /*
5806 * If no remaining prompts need a user response, then keep orphans
5807 * locked and go directly to the create steps.
5808 */
5809 if (dm_list_empty(&pp->prompts))
5810 goto do_command;
5811
5812 /*
5813 * Prompts require asking the user and make take some time, during
5814 * which we don't want to block other commands. So, release the lock
5815 * to prevent blocking other commands while we wait. After a response
5816 * from the user, reacquire the lock, verify that the PVs were not used
5817 * during the wait, then do the create steps.
5818 */
5819
5820 lockf_global(cmd, "un");
5821
5822 unlocked_for_prompts = 1;
5823
5824 /*
5825 * Process prompts that require asking the user. The global lock is
5826 * not held, so there's no harm in waiting for a user to respond.
5827 */
5828 dm_list_iterate_items_safe(prompt, prompt2, &pp->prompts) {
5829 _check_pvcreate_prompt(cmd, pp, prompt, 1);
5830
5831 switch (prompt->answer) {
5832 case PROMPT_ANSWER_YES:
5833 /* The PV can be used, leave it on arg_process. */
5834 dm_list_del(&prompt->list);
5835 break;
5836 case PROMPT_ANSWER_NO:
5837 /* The PV cannot be used, remove it from arg_process. */
5838 if ((pd = _pvcreate_list_find_dev(&pp->arg_process, prompt->dev)))
5839 dm_list_move(&pp->arg_fail, &pd->list);
5840 dm_list_del(&prompt->list);
5841 break;
5842 }
5843
5844 if (!dm_list_empty(&pp->arg_fail) && must_use_all)
5845 goto_bad;
5846
5847 if (sigint_caught())
5848 goto_bad;
5849
5850 if (prompt->abort_command)
5851 goto_bad;
5852 }
5853
5854 /*
5855 * Reacquire the lock that was released above before waiting, then
5856 * check again that the devices can still be used. If the second check
5857 * finds them changed, or can't find them any more, then they aren't
5858 * used. Use a non-blocking request when reacquiring to avoid
5859 * potential deadlock since this is not the normal locking sequence.
5860 */
5861
5862 if (!lockf_global_nonblock(cmd, "ex")) {
5863 log_error("Failed to reacquire global lock after prompt.");
5864 goto bad;
5865 }
5866
5867 do_command:
5868
5869 dm_list_iterate_items(pd, &pp->arg_process) {
5870 if (!(devl = dm_pool_zalloc(cmd->mem, sizeof(*devl))))
5871 goto bad;
5872 devl->dev = pd->dev;
5873 dm_list_add(&rescan_devs, &devl->list);
5874 }
5875
5876 /*
5877 * We want label_scan excl to repeat the filter check in case something
5878 * changed to filter out a dev before we were able to get exclusive.
5879 */
5880 dm_list_iterate_items(devl, &rescan_devs)
5881 cmd->filter->wipe(cmd, cmd->filter, devl->dev, NULL);
5882
5883 if (cmd->enable_devices_file && !pp->is_remove)
5884 cmd->filter_deviceid_skip = 1;
5885
5886 log_debug("Rescanning and filtering device args with exclusive open");
5887 if (!label_scan_devs_excl(cmd, cmd->filter, &rescan_devs)) {
5888 log_debug("Failed to rescan devs excl");
5889 goto bad;
5890 }
5891
5892 dm_list_iterate_items_safe(pd, pd2, &pp->arg_process) {
5893 if (!cmd->filter->passes_filter(cmd, cmd->filter, pd->dev, NULL)) {
5894 log_error("Cannot use %s: %s", pd->name, devname_error_reason(pd->name));
5895 dm_list_del(&pd->list);
5896 dm_list_add(&pp->arg_fail, &pd->list);
5897 }
5898 }
5899 cmd->filter_deviceid_skip = 0;
5900
5901 if (dm_list_empty(&pp->arg_process) && dm_list_empty(&remove_duplicates)) {
5902 log_debug("No devices to process.");
5903 goto bad;
5904 }
5905
5906 if (!dm_list_empty(&pp->arg_fail) && must_use_all)
5907 goto_bad;
5908
5909 /*
5910 * If the global lock was unlocked to wait for prompts, then
5911 * devs could have changed while unlocked, so confirm that
5912 * the devs are unchanged since check_used.
5913 * Changed pd entries are moved to arg_fail.
5914 */
5915 if (unlocked_for_prompts) {
5916 dm_list_iterate_items_safe(pd, pd2, &pp->arg_process)
5917 _confirm_check_used(cmd, pp, pd);
5918
5919 if (!dm_list_empty(&pp->arg_fail) && must_use_all)
5920 goto_bad;
5921 }
5922
5923 if (dm_list_empty(&pp->arg_process)) {
5924 log_debug("No devices to process.");
5925 goto bad;
5926 }
5927
5928 /*
5929 * Reorder arg_process entries to match the original order of args.
5930 */
5931 dm_list_splice(&arg_sort, &pp->arg_process);
5932 for (i = 0; i < pp->pv_count; i++) {
5933 if ((pd = _pvcreate_list_find_name(&arg_sort, pp->pv_names[i])))
5934 dm_list_move(&pp->arg_process, &pd->list);
5935 }
5936
5937 if (pp->is_remove)
5938 dm_list_splice(&pp->arg_remove, &pp->arg_process);
5939 else
5940 dm_list_splice(&pp->arg_create, &pp->arg_process);
5941
5942 /*
5943 * Wipe signatures on devices being created.
5944 */
5945 dm_list_iterate_items_safe(pd, pd2, &pp->arg_create) {
5946 log_verbose("Wiping signatures on new PV %s.", pd->name);
5947
5948 if (!wipe_known_signatures(cmd, pd->dev, pd->name, TYPE_LVM1_MEMBER | TYPE_LVM2_MEMBER,
5949 0, pp->yes, pp->force, &pd->wiped)) {
5950 dm_list_move(&pp->arg_fail, &pd->list);
5951 }
5952
5953 if (sigint_caught())
5954 goto_bad;
5955 }
5956
5957 if (!dm_list_empty(&pp->arg_fail) && must_use_all)
5958 goto_bad;
5959
5960 /*
5961 * Find existing orphan PVs that vgcreate or vgextend want to use.
5962 * "preserve_existing" means that the command wants to use existing PVs
5963 * and not recreate a new PV on top of an existing PV.
5964 */
5965 if (pp->preserve_existing && pp->orphan_vg_name) {
5966 log_debug("Using existing orphan PVs in %s.", pp->orphan_vg_name);
5967
5968 if (!(orphan_vg = vg_read_orphans(cmd, pp->orphan_vg_name))) {
5969 log_error("Cannot read orphans VG %s.", pp->orphan_vg_name);
5970 goto bad;
5971 }
5972
5973 dm_list_iterate_items_safe(pd, pd2, &pp->arg_create) {
5974 if (!pd->is_orphan_pv)
5975 continue;
5976
5977 if (!(pvl = dm_pool_alloc(cmd->mem, sizeof(*pvl)))) {
5978 log_error("alloc pvl failed.");
5979 dm_list_move(&pp->arg_fail, &pd->list);
5980 continue;
5981 }
5982
5983 found = 0;
5984 dm_list_iterate_items(vgpvl, &orphan_vg->pvs) {
5985 if (vgpvl->pv->dev == pd->dev) {
5986 found = 1;
5987 break;
5988 }
5989 }
5990
5991 if (found) {
5992 log_debug("Using existing orphan PV %s.", pv_dev_name(vgpvl->pv));
5993 pvl->pv = vgpvl->pv;
5994 dm_list_add(&pp->pvs, &pvl->list);
5995
5996 /* allow deviceidtype_ARG/deviceid_ARG ? */
5997 memcpy(pvid, &pvl->pv->id.uuid, ID_LEN);
5998 device_id_add(cmd, pd->dev, pvid, NULL, NULL, 0);
5999
6000 } else {
6001 log_error("Failed to find PV %s", pd->name);
6002 dm_list_move(&pp->arg_fail, &pd->list);
6003 }
6004 }
6005 }
6006
6007 /*
6008 * Create PVs on devices. Either create a new PV on top of an existing
6009 * one (e.g. for pvcreate), or create a new PV on a device that is not
6010 * a PV.
6011 */
6012 dm_list_iterate_items_safe(pd, pd2, &pp->arg_create) {
6013 /* Using existing orphan PVs is covered above. */
6014 if (pp->preserve_existing && pd->is_orphan_pv)
6015 continue;
6016
6017 if (!dm_list_empty(&pp->arg_fail) && must_use_all)
6018 break;
6019
6020 if (!(pvl = dm_pool_alloc(cmd->mem, sizeof(*pvl)))) {
6021 log_error("alloc pvl failed.");
6022 dm_list_move(&pp->arg_fail, &pd->list);
6023 continue;
6024 }
6025
6026 pv_name = pd->name;
6027
6028 log_debug("Creating a new PV on %s.", pv_name);
6029
6030 if (!(pv = pv_create(cmd, pd->dev, &pp->pva))) {
6031 log_error("Failed to setup physical volume \"%s\".", pv_name);
6032 dm_list_move(&pp->arg_fail, &pd->list);
6033 continue;
6034 }
6035
6036 /* allow deviceidtype_ARG/deviceid_ARG ? */
6037 memcpy(pvid, &pv->id.uuid, ID_LEN);
6038 device_id_add(cmd, pd->dev, pvid, NULL, NULL, 0);
6039
6040 log_verbose("Set up physical volume for \"%s\" with %" PRIu64
6041 " available sectors.", pv_name, pv_size(pv));
6042
6043 if (!label_remove(pv->dev)) {
6044 log_error("Failed to wipe existing label on %s.", pv_name);
6045 dm_list_move(&pp->arg_fail, &pd->list);
6046 continue;
6047 }
6048
6049 if (pp->zero) {
6050 log_verbose("Zeroing start of device %s.", pv_name);
6051
6052 if (!dev_write_zeros(pv->dev, 0, 2048)) {
6053 log_error("%s not wiped: aborting.", pv_name);
6054 dm_list_move(&pp->arg_fail, &pd->list);
6055 continue;
6056 }
6057 }
6058
6059 log_verbose("Writing physical volume data to disk \"%s\".", pv_name);
6060
6061 if (!pv_write(cmd, pv, 0)) {
6062 log_error("Failed to write physical volume \"%s\".", pv_name);
6063 dm_list_move(&pp->arg_fail, &pd->list);
6064 continue;
6065 }
6066
6067 log_print_unless_silent("Physical volume \"%s\" successfully created.",
6068 pv_name);
6069
6070 pvl->pv = pv;
6071 dm_list_add(&pp->pvs, &pvl->list);
6072 }
6073
6074 /*
6075 * Remove PVs from devices for pvremove.
6076 */
6077 dm_list_iterate_items_safe(pd, pd2, &pp->arg_remove) {
6078 if (!label_remove(pd->dev)) {
6079 log_error("Failed to wipe existing label(s) on %s.", pd->name);
6080 dm_list_move(&pp->arg_fail, &pd->list);
6081 continue;
6082 }
6083
6084 device_id_pvremove(cmd, pd->dev);
6085
6086 log_print_unless_silent("Labels on physical volume \"%s\" successfully wiped.",
6087 pd->name);
6088 }
6089
6090 /*
6091 * Special case: pvremove duplicate PVs (also see above).
6092 */
6093 dm_list_iterate_items_safe(pd, pd2, &remove_duplicates) {
6094 if (!label_remove(pd->dev)) {
6095 log_error("Failed to wipe existing label(s) on %s.", pd->name);
6096 dm_list_move(&pp->arg_fail, &pd->list);
6097 continue;
6098 }
6099
6100 lvmcache_del_dev_from_duplicates(pd->dev);
6101
6102 device_id_pvremove(cmd, pd->dev);
6103
6104 log_print_unless_silent("Labels on physical volume \"%s\" successfully wiped.",
6105 pd->name);
6106 }
6107
6108 /* TODO: when vgcreate uses only existing PVs this doesn't change and can be skipped */
6109 if (!device_ids_write(cmd))
6110 stack;
6111
6112 /*
6113 * Don't keep devs open excl in bcache because the excl will prevent
6114 * using that dev elsewhere.
6115 */
6116 dm_list_iterate_items(devl, &rescan_devs)
6117 label_scan_invalidate(devl->dev);
6118
6119 dm_list_iterate_items(pd, &pp->arg_fail)
6120 log_debug("%s: command failed for %s.",
6121 cmd->command->name, pd->name);
6122
6123 if (!dm_list_empty(&pp->arg_fail))
6124 goto_bad;
6125
6126 return 1;
6127 bad:
6128 return 0;
6129 }
6130
6131 int get_rootvg_dev_uuid(struct cmd_context *cmd, char **dm_uuid_out)
6132 {
6133 char dm_uuid[DM_UUID_LEN];
6134 struct stat info;
6135 FILE *fme = NULL;
6136 struct mntent *me;
6137 int found = 0;
6138
6139 if (!(fme = setmntent("/etc/mtab", "r")))
6140 return_0;
6141
6142 while ((me = getmntent(fme))) {
6143 if ((me->mnt_dir[0] == '/') && (me->mnt_dir[1] == '\0')) {
6144 found = 1;
6145 break;
6146 }
6147 }
6148 endmntent(fme);
6149
6150 if (!found)
6151 return_0;
6152
6153 if (stat(me->mnt_dir, &info) < 0)
6154 return_0;
6155
6156 if (!devno_dm_uuid(cmd, MAJOR(info.st_dev), MINOR(info.st_dev), dm_uuid, sizeof(dm_uuid)))
6157 return_0;
6158
6159 log_debug("Found root dm_uuid %s", dm_uuid);
6160
6161 /* UUID_PREFIX = "LVM-" */
6162 if (strncmp(dm_uuid, UUID_PREFIX, sizeof(UUID_PREFIX) - 1))
6163 return_0;
6164
6165 if (strlen(dm_uuid) < sizeof(UUID_PREFIX) - 1 + ID_LEN)
6166 return_0;
6167
6168 *dm_uuid_out = dm_pool_strdup(cmd->mem, dm_uuid);
6169
6170 return 1;
6171 }
This page took 0.31395 seconds and 6 git commands to generate.