2 * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved.
3 * Copyright (C) 2004-2007 Red Hat, Inc. All rights reserved.
5 * This file is part of LVM2.
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.
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
16 #include "base/memory/zalloc.h"
17 #include "lib/misc/lib.h"
18 #include "lib/device/dev-type.h"
19 #include "lib/device/device_id.h"
20 #include "lib/datastruct/btree.h"
21 #include "lib/config/config.h"
22 #include "lib/commands/toolcontext.h"
23 #include "device_mapper/misc/dm-ioctl.h"
24 #include "lib/misc/lvm-string.h"
26 #ifdef UDEV_SYNC_SUPPORT
32 /* coverity[unnecessary_header] needed for MuslC */
36 struct btree_iter *current;
37 struct dev_filter *filter;
47 struct dm_hash_table *names;
48 struct dm_hash_table *vgid_index;
49 struct dm_hash_table *lvid_index;
50 struct btree *sysfs_only_devices; /* see comments in _get_device_for_sysfs_dev_name_using_devno */
51 struct btree *devices;
52 struct dm_regex *preferred_names_matcher;
62 #define _zalloc(x) dm_pool_zalloc(_cache.mem, (x))
63 #define _free(x) dm_pool_free(_cache.mem, (x))
64 #define _strdup(x) dm_pool_strdup(_cache.mem, (x))
66 static int _insert(const char *path, const struct stat *info,
67 int rec, int check_with_udev_db);
69 /* Setup non-zero members of passed zeroed 'struct device' */
70 static void _dev_init(struct device *dev)
79 dev->ext.src = DEV_EXT_NONE;
81 dm_list_init(&dev->aliases);
82 dm_list_init(&dev->ids);
83 dm_list_init(&dev->wwids);
86 void dev_destroy_file(struct device *dev)
88 if (!(dev->flags & DEV_ALLOCED))
91 free((void *) dm_list_item(dev->aliases.n, struct dm_str_list)->str);
96 struct device *dev_create_file(const char *filename, struct device *dev,
97 struct dm_str_list *alias, int use_malloc)
103 if (!(dev = zalloc(sizeof(*dev)))) {
104 log_error("struct device allocation failed");
107 if (!(alias = zalloc(sizeof(*alias)))) {
108 log_error("struct dm_str_list allocation failed");
112 if (!(alias->str = strdup(filename))) {
113 log_error("filename strdup failed");
119 if (!(dev = _zalloc(sizeof(*dev)))) {
120 log_error("struct device allocation failed");
123 if (!(alias = _zalloc(sizeof(*alias)))) {
124 log_error("struct dm_str_list allocation failed");
128 if (!(alias->str = _strdup(filename))) {
129 log_error("filename strdup failed");
134 } else if (!(alias->str = strdup(filename))) {
135 log_error("filename strdup failed");
140 dev->flags = DEV_REGULAR | ((use_malloc) ? DEV_ALLOCED : 0);
141 dm_list_add(&dev->aliases, &alias->list);
146 static struct device *_dev_create(dev_t d)
150 if (!(dev = _zalloc(sizeof(*dev)))) {
151 log_error("struct device allocation failed");
161 void dev_set_preferred_name(struct dm_str_list *sl, struct device *dev)
164 * Don't interfere with ordering specified in config file.
166 if (_cache.preferred_names_matcher)
169 log_debug_devs("%s: New preferred name", sl->str);
170 dm_list_del(&sl->list);
171 dm_list_add_h(&dev->aliases, &sl->list);
175 * Check whether path0 or path1 contains the subpath. The path that
176 * *does not* contain the subpath wins (return 0 or 1). If both paths
177 * contain the subpath, return -1. If none of them contains the subpath,
180 static int _builtin_preference(const char *path0, const char *path1,
181 size_t skip_prefix_count, const char *subpath)
186 subpath_len = strlen(subpath);
188 r0 = !strncmp(path0 + skip_prefix_count, subpath, subpath_len);
189 r1 = !strncmp(path1 + skip_prefix_count, subpath, subpath_len);
192 /* path0 does not have the subpath - it wins */
195 /* path1 does not have the subpath - it wins */
198 /* both of them have the subpath */
201 /* no path has the subpath */
205 static int _apply_builtin_path_preference_rules(const char *path0, const char *path1)
210 devdir_len = strlen(_cache.dev_dir);
212 if (!strncmp(path0, _cache.dev_dir, devdir_len) &&
213 !strncmp(path1, _cache.dev_dir, devdir_len)) {
215 * We're trying to achieve the ordering:
216 * /dev/block/ < /dev/dm-* < /dev/disk/ < /dev/mapper/ < anything else
219 /* Prefer any other path over /dev/block/ path. */
220 if ((r = _builtin_preference(path0, path1, devdir_len, "block/")) >= -1)
223 /* Prefer any other path over /dev/dm-* path. */
224 if ((r = _builtin_preference(path0, path1, devdir_len, "dm-")) >= -1)
227 /* Prefer any other path over /dev/disk/ path. */
228 if ((r = _builtin_preference(path0, path1, devdir_len, "disk/")) >= -1)
231 /* Prefer any other path over /dev/mapper/ path. */
232 if ((r = _builtin_preference(path0, path1, 0, dm_dir())) >= -1)
239 /* Return 1 if we prefer path1 else return 0 */
240 static int _compare_paths(const char *path0, const char *path1)
242 int slash0 = 0, slash1 = 0;
245 char p0[PATH_MAX], p1[PATH_MAX];
247 struct stat stat0, stat1;
251 * FIXME Better to compare patterns one-at-a-time against all names.
253 if (_cache.preferred_names_matcher) {
254 m0 = dm_regex_match(_cache.preferred_names_matcher, path0);
255 m1 = dm_regex_match(_cache.preferred_names_matcher, path1);
269 /* Apply built-in preference rules first. */
270 if ((r = _apply_builtin_path_preference_rules(path0, path1)) >= 0)
273 /* Return the path with fewer slashes */
274 for (p = path0; p++; p = (const char *) strchr(p, '/'))
277 for (p = path1; p++; p = (const char *) strchr(p, '/'))
285 (void) dm_strncpy(p0, path0, sizeof(p0));
286 (void) dm_strncpy(p1, path1, sizeof(p1));
291 * If we reach here, both paths are the same length.
292 * Now skip past identical path components.
294 while (*s0 && *s0 == *s1)
297 /* We prefer symlinks - they exist for a reason!
298 * So we prefer a shorter path before the first symlink in the name.
299 * FIXME Configuration option to invert this? */
301 if ((s0 = strchr(s0, '/')))
304 if ((s1 = strchr(s1, '/')))
307 if (lstat(p0, &stat0)) {
308 log_sys_very_verbose("lstat", p0);
311 if (lstat(p1, &stat1)) {
312 log_sys_very_verbose("lstat", p1);
315 if (S_ISLNK(stat0.st_mode) && !S_ISLNK(stat1.st_mode))
317 if (!S_ISLNK(stat0.st_mode) && S_ISLNK(stat1.st_mode))
325 /* ASCII comparison */
326 if (strcmp(path0, path1) < 0)
338 static int _add_alias(struct device *dev, const char *path, enum add_hash hash)
340 struct dm_str_list *sl;
341 struct dm_str_list *strl;
346 dm_hash_remove(_cache.names, path);
348 /* Is name already there? */
349 dm_list_iterate_items(strl, &dev->aliases)
350 if (!strcmp(strl->str, path)) {
355 if (!(path = _strdup(path)) ||
356 !(sl = _zalloc(sizeof(*sl)))) {
357 log_error("Failed to add allias to dev cache.");
361 if (!strncmp(path, "/dev/nvme", 9)) {
362 log_debug("Found nvme device %s", dev_name(dev));
363 dev->flags |= DEV_IS_NVME;
368 if (!dm_list_empty(&dev->aliases)) {
369 oldpath = dm_list_item(dev->aliases.n, struct dm_str_list)->str;
370 prefer_old = _compare_paths(path, oldpath);
374 dm_list_add(&dev->aliases, &sl->list);
376 dm_list_add_h(&dev->aliases, &sl->list);
378 if ((hash != NO_HASH) &&
379 !dm_hash_insert(_cache.names, path, dev)) {
380 log_error("Couldn't add name to hash in dev cache.");
387 int get_sysfs_binary(const char *path, char *buf, size_t buf_size, int *retlen)
392 fd = open(path, O_RDONLY);
395 ret = read(fd, buf, buf_size);
403 int get_sysfs_value(const char *path, char *buf, size_t buf_size, int error_if_no_value)
409 if (!(fp = fopen(path, "r"))) {
410 if (error_if_no_value)
411 log_sys_error("fopen", path);
415 if (!fgets(buf, buf_size, fp)) {
416 if (error_if_no_value)
417 log_sys_error("fgets", path);
421 if ((len = strlen(buf)) && buf[len - 1] == '\n')
424 if (!len && error_if_no_value)
425 log_error("_get_sysfs_value: %s: no value", path);
430 log_sys_debug("fclose", path);
435 int get_dm_uuid_from_sysfs(char *buf, size_t buf_size, int major, int minor)
439 if (dm_snprintf(path, sizeof(path), "%sdev/block/%d:%d/dm/uuid", dm_sysfs_dir(), major, minor) < 0) {
440 log_error("%d:%d: dm_snprintf failed for path to sysfs dm directory.", major, minor);
444 return get_sysfs_value(path, buf, buf_size, 0);
447 static struct dm_list *_get_or_add_list_by_index_key(struct dm_hash_table *idx, const char *key)
449 struct dm_list *list;
451 if ((list = dm_hash_lookup(idx, key)))
454 if (!(list = _zalloc(sizeof(*list)))) {
455 log_error("%s: failed to allocate device list for device cache index.", key);
461 if (!dm_hash_insert(idx, key, list)) {
462 log_error("%s: failed to insert device list to device cache index.", key);
469 static struct device *_insert_sysfs_dev(dev_t devno, const char *devname)
471 static struct device _fake_dev = { .flags = DEV_USED_FOR_LV };
476 if (dm_snprintf(path, sizeof(path), "%s%s", _cache.dev_dir, devname) < 0) {
477 log_error("_insert_sysfs_dev: %s: dm_snprintf failed", devname);
481 if (lstat(path, &stat0) < 0) {
482 /* When device node does not exist return fake entry.
483 * This may happen when i.e. lvm2 device dir != /dev */
484 log_debug("%s: Not available device node", path);
488 if (!(dev = _dev_create(devno)))
491 if (!_add_alias(dev, path, NO_HASH)) {
496 if (!btree_insert(_cache.sysfs_only_devices, (uint32_t) devno, dev)) {
497 log_error("Couldn't add device to binary tree of sysfs-only devices in dev cache.");
505 static struct device *_get_device_for_sysfs_dev_name_using_devno(const char *devname)
513 if (dm_snprintf(path, sizeof(path), "%sblock/%s/dev", dm_sysfs_dir(), devname) < 0) {
514 log_error("_get_device_for_sysfs_dev_name_using_devno: %s: dm_snprintf failed", devname);
518 if (!get_sysfs_value(path, buf, sizeof(buf), 1))
521 if (sscanf(buf, "%d:%d", &major, &minor) != 2) {
522 log_error("_get_device_for_sysfs_dev_name_using_devno: %s: failed to get major and minor number", devname);
526 devno = MKDEV(major, minor);
527 if (!(dev = (struct device *) btree_lookup(_cache.devices, (uint32_t) devno))) {
529 * If we get here, it means the device is referenced in sysfs, but it's not yet in /dev.
530 * This may happen in some rare cases right after LVs get created - we sync with udev
531 * (or alternatively we create /dev content ourselves) while VG lock is held. However,
532 * dev scan is done without VG lock so devices may already be in sysfs, but /dev may
533 * not be updated yet if we call LVM command right after LV creation. This is not a
534 * problem with devtmpfs as there's at least kernel name for device in /dev as soon
535 * as the sysfs item exists, but we still support environments without devtmpfs or
536 * where different directory for dev nodes is used (e.g. our test suite). So track
537 * such devices in _cache.sysfs_only_devices hash for the vgid/lvid check to work still.
539 if (!(dev = (struct device *) btree_lookup(_cache.sysfs_only_devices, (uint32_t) devno)) &&
540 !(dev = _insert_sysfs_dev(devno, devname)))
547 #define NOT_LVM_UUID "-"
549 static int _get_vgid_and_lvid_for_dev(struct device *dev)
551 static size_t lvm_prefix_len = sizeof(UUID_PREFIX) - 1;
552 static size_t lvm_uuid_len = sizeof(UUID_PREFIX) - 1 + 2 * ID_LEN;
553 char uuid[DM_UUID_LEN];
556 if (!get_dm_uuid_from_sysfs(uuid, sizeof(uuid), (int) MAJOR(dev->dev), (int) MINOR(dev->dev)))
559 uuid_len = strlen(uuid);
562 * UUID for LV is either "LVM-<vg_uuid><lv_uuid>" or "LVM-<vg_uuid><lv_uuid>-<suffix>",
563 * where vg_uuid and lv_uuid has length of ID_LEN and suffix len is not restricted
564 * (only restricted by whole DM UUID max len).
566 if (((uuid_len == lvm_uuid_len) ||
567 ((uuid_len > lvm_uuid_len) && (uuid[lvm_uuid_len] == '-'))) &&
568 !strncmp(uuid, UUID_PREFIX, lvm_prefix_len)) {
569 /* Separate VGID and LVID part from DM UUID. */
570 if (!(dev->vgid = dm_pool_strndup(_cache.mem, uuid + lvm_prefix_len, ID_LEN)) ||
571 !(dev->lvid = dm_pool_strndup(_cache.mem, uuid + lvm_prefix_len + ID_LEN, ID_LEN)))
574 dev->vgid = dev->lvid = NOT_LVM_UUID;
579 static int _index_dev_by_vgid_and_lvid(struct device *dev)
581 const char *devname = dev_name(dev);
582 char devpath[PATH_MAX];
585 struct dirent *dirent;
586 struct device *holder_dev;
587 struct dm_list *vgid_list, *lvid_list;
588 struct device_list *dl_vgid, *dl_lvid;
591 if (dev->flags & DEV_USED_FOR_LV)
592 /* already indexed */
595 /* Get holders for device. */
596 if (dm_snprintf(path, sizeof(path), "%sdev/block/%d:%d/holders/", dm_sysfs_dir(), (int) MAJOR(dev->dev), (int) MINOR(dev->dev)) < 0) {
597 log_error("%s: dm_snprintf failed for path to holders directory.", devname);
601 if (!(d = opendir(path))) {
602 if (errno == ENOENT) {
603 log_debug("%s: path does not exist, skipping", path);
606 log_sys_error("opendir", path);
610 /* Iterate over device's holders and look for LVs. */
611 while ((dirent = readdir(d))) {
612 if (!strcmp(".", dirent->d_name) ||
613 !strcmp("..", dirent->d_name))
616 if (dm_snprintf(devpath, sizeof(devpath), "%s%s", _cache.dev_dir, dirent->d_name) == -1) {
617 log_error("%s: dm_snprintf failed for holder %s device path.", devname, dirent->d_name);
621 if (!(holder_dev = (struct device *) dm_hash_lookup(_cache.names, devpath))) {
623 * Cope with situation where canonical /<dev_dir>/<dirent->d_name>
624 * does not exist, but some other node name or symlink exists in
625 * non-standard environments - someone renaming the nodes or using
626 * mknod with different dev names than actual kernel names.
627 * This looks up struct device by major:minor pair which we get
628 * by looking at /sys/block/<dirent->d_name>/dev sysfs attribute.
630 if (!(holder_dev = _get_device_for_sysfs_dev_name_using_devno(dirent->d_name))) {
631 log_error("%s: failed to find associated device structure for holder %s.", devname, devpath);
636 /* We're only interested in a holder which is a DM device. */
637 if (!dm_is_dm_major(MAJOR(holder_dev->dev)))
641 * And if it's a DM device, we're only interested in a holder which is an LVM device.
642 * Get the VG UUID and LV UUID if we don't have that already.
644 if (!holder_dev->vgid && !_get_vgid_and_lvid_for_dev(holder_dev))
647 if (*holder_dev->vgid == *NOT_LVM_UUID)
651 * Do not add internal LV devices to index.
652 * If a device is internal, the holder has the same VG UUID as the device.
654 if (dm_is_dm_major(MAJOR(dev->dev))) {
655 if (!dev->vgid && !_get_vgid_and_lvid_for_dev(dev))
658 if (*dev->vgid != *NOT_LVM_UUID && !strcmp(holder_dev->vgid, dev->vgid))
662 if (!(vgid_list = _get_or_add_list_by_index_key(_cache.vgid_index, holder_dev->vgid)) ||
663 !(lvid_list = _get_or_add_list_by_index_key(_cache.lvid_index, holder_dev->lvid)))
666 /* Create dev list items for the holder device. */
667 if (!(dl_vgid = _zalloc(sizeof(*dl_vgid))) ||
668 !(dl_lvid = _zalloc(sizeof(*dl_lvid)))) {
669 log_error("%s: failed to allocate dev list item.", devname);
673 dl_vgid->dev = dl_lvid->dev = dev;
675 /* Add dev list item to VGID device list if it's not there already. */
676 if (!(dev->flags & DEV_USED_FOR_LV))
677 dm_list_add(vgid_list, &dl_vgid->list);
679 /* Add dev list item to LVID device list. */
680 dm_list_add(lvid_list, &dl_lvid->list);
682 /* Mark device as used == also indexed in dev cache by VGID and LVID. */
683 dev->flags |= DEV_USED_FOR_LV;
689 log_sys_debug("closedir", path);
694 struct dm_list *dev_cache_get_dev_list_for_vgid(const char *vgid)
696 return dm_hash_lookup(_cache.vgid_index, vgid);
699 struct dm_list *dev_cache_get_dev_list_for_lvid(const char *lvid)
701 return dm_hash_lookup(_cache.lvid_index, lvid);
705 * Scanning code calls this when it fails to open a device using
706 * this path. The path is dropped from dev-cache. In the next
707 * dev_cache_scan it may be added again, but it could be for a
711 void dev_cache_failed_path(struct device *dev, const char *path)
713 struct dm_str_list *strl;
715 if (dm_hash_lookup(_cache.names, path))
716 dm_hash_remove(_cache.names, path);
718 dm_list_iterate_items(strl, &dev->aliases) {
719 if (!strcmp(strl->str, path)) {
720 dm_list_del(&strl->list);
727 * Either creates a new dev, or adds an alias to
730 static int _insert_dev(const char *path, dev_t d)
733 struct device *dev_by_devt;
734 struct device *dev_by_path;
736 dev_by_devt = (struct device *) btree_lookup(_cache.devices, (uint32_t) d);
737 dev_by_path = (struct device *) dm_hash_lookup(_cache.names, path);
741 * Existing device, existing path points to the same device.
743 if (dev_by_devt && dev_by_path && (dev_by_devt == dev_by_path)) {
744 log_debug_devs("Found dev %d:%d %s - exists. %.8s",
745 (int)MAJOR(d), (int)MINOR(d), path, dev->pvid);
750 * No device or path found, add devt to cache.devices, add name to cache.names.
752 if (!dev_by_devt && !dev_by_path) {
753 log_debug_devs("Found dev %d:%d %s - new.",
754 (int)MAJOR(d), (int)MINOR(d), path);
756 if (!(dev = (struct device *) btree_lookup(_cache.sysfs_only_devices, (uint32_t) d))) {
757 /* create new device */
758 if (!(dev = _dev_create(d)))
762 if (!(btree_insert(_cache.devices, (uint32_t) d, dev))) {
763 log_error("Couldn't insert device into binary tree.");
768 if (!_add_alias(dev, path, HASH))
775 * Existing device, path is new, add path as a new alias for the device.
777 if (dev_by_devt && !dev_by_path) {
778 log_debug_devs("Found dev %d:%d %s - new alias.",
779 (int)MAJOR(d), (int)MINOR(d), path);
781 if (!_add_alias(dev, path, HASH))
788 * No existing device, but path exists and previously pointed
789 * to a different device.
791 if (!dev_by_devt && dev_by_path) {
792 log_debug_devs("Found dev %d:%d %s - new device, path was previously %d:%d.",
793 (int)MAJOR(d), (int)MINOR(d), path,
794 (int)MAJOR(dev_by_path->dev), (int)MINOR(dev_by_path->dev));
796 if (!(dev = (struct device *) btree_lookup(_cache.sysfs_only_devices, (uint32_t) d))) {
797 /* create new device */
798 if (!(dev = _dev_create(d)))
802 if (!(btree_insert(_cache.devices, (uint32_t) d, dev))) {
803 log_error("Couldn't insert device into binary tree.");
808 if (!_add_alias(dev, path, REHASH))
815 * Existing device, and path exists and previously pointed to
816 * a different device.
818 if (dev_by_devt && dev_by_path) {
819 log_debug_devs("Found dev %d:%d %s - existing device, path was previously %d:%d.",
820 (int)MAJOR(d), (int)MINOR(d), path,
821 (int)MAJOR(dev_by_path->dev), (int)MINOR(dev_by_path->dev));
823 if (!_add_alias(dev, path, REHASH))
829 log_error("Found dev %d:%d %s - failed to use.", (int)MAJOR(d), (int)MINOR(d), path);
834 * Get rid of extra slashes in the path string.
836 static void _collapse_slashes(char *str)
841 for (ptr = str; *ptr; ptr++) {
855 static int _insert_dir(const char *dir)
857 int n, dirent_count, r = 1;
858 struct dirent **dirent = NULL;
862 if (!dm_strncpy(path, dir, sizeof(path) - 1)) {
863 log_debug_devs("Dir path %s is too long", path);
866 _collapse_slashes(path);
868 if (len && path[len - 1] != '/')
871 setlocale(LC_COLLATE, "C"); /* Avoid sorting by locales */
872 dirent_count = scandir(dir, &dirent, NULL, alphasort);
873 if (dirent_count > 0) {
874 for (n = 0; n < dirent_count; n++) {
875 if (dirent[n]->d_name[0] == '.')
878 if (!dm_strncpy(path + len, dirent[n]->d_name, sizeof(path) - len)) {
879 log_debug_devs("Path %s/%s is too long.", dir, dirent[n]->d_name);
884 r &= _insert(path, NULL, 1, 0);
887 for (n = 0; n < dirent_count; n++)
891 setlocale(LC_COLLATE, "");
896 static int _dev_cache_iterate_devs_for_index(void)
898 struct btree_iter *iter = btree_first(_cache.devices);
903 dev = btree_get_data(iter);
905 if (!_index_dev_by_vgid_and_lvid(dev))
908 iter = btree_next(iter);
914 static int _dev_cache_iterate_sysfs_for_index(const char *path)
916 char devname[PATH_MAX];
918 struct dirent *dirent;
922 int partial_failure = 0;
925 if (!(d = opendir(path))) {
926 log_sys_error("opendir", path);
930 while ((dirent = readdir(d))) {
931 if (!strcmp(".", dirent->d_name) ||
932 !strcmp("..", dirent->d_name))
935 if (sscanf(dirent->d_name, "%d:%d", &major, &minor) != 2) {
936 log_error("_dev_cache_iterate_sysfs_for_index: %s: failed "
937 "to get major and minor number", dirent->d_name);
942 devno = MKDEV(major, minor);
943 if (!(dev = (struct device *) btree_lookup(_cache.devices, (uint32_t) devno)) &&
944 !(dev = (struct device *) btree_lookup(_cache.sysfs_only_devices, (uint32_t) devno))) {
945 if (!dm_device_get_name(major, minor, 1, devname, sizeof(devname)) ||
946 !(dev = _insert_sysfs_dev(devno, devname))) {
952 if (!_index_dev_by_vgid_and_lvid(dev))
956 r = !partial_failure;
959 log_sys_debug("closedir", path);
964 static int dev_cache_index_devs(void)
966 static int sysfs_has_dev_block = -1;
969 if (dm_snprintf(path, sizeof(path), "%sdev/block", dm_sysfs_dir()) < 0) {
970 log_error("dev_cache_index_devs: dm_snprintf failed.");
974 /* Skip indexing if /sys/dev/block is not available.*/
975 if (sysfs_has_dev_block == -1) {
977 if (stat(path, &info) == 0)
978 sysfs_has_dev_block = 1;
980 if (errno == ENOENT) {
981 sysfs_has_dev_block = 0;
985 log_sys_debug("stat", path);
988 } else if (!sysfs_has_dev_block)
991 if (obtain_device_list_from_udev() &&
992 udev_get_library_context())
993 return _dev_cache_iterate_devs_for_index(); /* with udev */
995 return _dev_cache_iterate_sysfs_for_index(path);
998 #ifdef UDEV_SYNC_SUPPORT
1000 static int _device_in_udev_db(const dev_t d)
1003 struct udev_device *udev_device;
1005 if (!(udev = udev_get_library_context()))
1008 if ((udev_device = udev_device_new_from_devnum(udev, 'b', d))) {
1009 udev_device_unref(udev_device);
1016 static int _insert_udev_dir(struct udev *udev, const char *dir)
1018 struct udev_enumerate *udev_enum = NULL;
1019 struct udev_list_entry *device_entry, *symlink_entry;
1020 const char *entry_name, *node_name, *symlink_name;
1021 struct udev_device *device;
1024 if (!(udev_enum = udev_enumerate_new(udev))) {
1025 log_error("Failed to udev_enumerate_new.");
1029 if (udev_enumerate_add_match_subsystem(udev_enum, "block")) {
1030 log_error("Failed to udev_enumerate_add_match_subsystem.");
1034 if (udev_enumerate_scan_devices(udev_enum)) {
1035 log_error("Failed to udev_enumerate_scan_devices.");
1040 * Report any missing information as "log_very_verbose" only, do not
1041 * report it as a "warning" or "error" - the record could be removed
1042 * by the time we ask for more info (node name, symlink name...).
1043 * Whatever removes *any* block device in the system (even unrelated
1044 * to our operation), we would have a warning/error on output then.
1045 * That could be misleading. If there's really any problem with missing
1046 * information from udev db, we can still have a look at the verbose log.
1048 udev_list_entry_foreach(device_entry, udev_enumerate_get_list_entry(udev_enum)) {
1049 entry_name = udev_list_entry_get_name(device_entry);
1051 if (!(device = udev_device_new_from_syspath(udev, entry_name))) {
1052 log_very_verbose("udev failed to return a device for entry %s.",
1057 if (!(node_name = udev_device_get_devnode(device)))
1058 log_very_verbose("udev failed to return a device node for entry %s.",
1061 r &= _insert(node_name, NULL, 0, 0);
1063 udev_list_entry_foreach(symlink_entry, udev_device_get_devlinks_list_entry(device)) {
1064 if (!(symlink_name = udev_list_entry_get_name(symlink_entry)))
1065 log_very_verbose("udev failed to return a symlink name for entry %s.",
1068 r &= _insert(symlink_name, NULL, 0, 0);
1071 udev_device_unref(device);
1075 udev_enumerate_unref(udev_enum);
1080 static void _insert_dirs(struct dm_list *dirs)
1082 struct dir_list *dl;
1083 struct udev *udev = NULL;
1087 with_udev = obtain_device_list_from_udev() &&
1088 (udev = udev_get_library_context());
1090 dm_list_iterate_items(dl, &_cache.dirs) {
1091 if (stat(dl->dir, &tinfo) < 0) {
1092 log_warn("WARNING: Cannot use dir %s, %s.",
1093 dl->dir, strerror(errno));
1096 _cache.st_dev = tinfo.st_dev;
1098 if (!_insert_udev_dir(udev, dl->dir))
1099 log_debug_devs("%s: Failed to insert devices from "
1100 "udev-managed directory to device "
1101 "cache fully", dl->dir);
1103 else if (!_insert_dir(dl->dir))
1104 log_debug_devs("%s: Failed to insert devices to "
1105 "device cache fully", dl->dir);
1109 #else /* UDEV_SYNC_SUPPORT */
1111 static int _device_in_udev_db(const dev_t d)
1116 static void _insert_dirs(struct dm_list *dirs)
1118 struct dir_list *dl;
1121 dm_list_iterate_items(dl, &_cache.dirs) {
1122 if (stat(dl->dir, &tinfo) < 0) {
1123 log_warn("WARNING: Cannot use dir %s, %s.",
1124 dl->dir, strerror(errno));
1127 _cache.st_dev = tinfo.st_dev;
1128 _insert_dir(dl->dir);
1132 #endif /* UDEV_SYNC_SUPPORT */
1134 static int _insert(const char *path, const struct stat *info,
1135 int rec, int check_with_udev_db)
1140 if (stat(path, &tinfo) < 0) {
1141 log_sys_very_verbose("stat", path);
1147 if (check_with_udev_db && !_device_in_udev_db(info->st_rdev)) {
1148 log_very_verbose("%s: Not in udev db", path);
1152 if (S_ISDIR(info->st_mode)) { /* add a directory */
1153 /* check it's not a symbolic link */
1154 if (lstat(path, &tinfo) < 0) {
1155 log_sys_very_verbose("lstat", path);
1159 if (S_ISLNK(tinfo.st_mode)) {
1160 log_debug_devs("%s: Symbolic link to directory", path);
1164 if (info->st_dev != _cache.st_dev) {
1165 log_debug_devs("%s: Different filesystem in directory", path);
1169 if (rec && !_insert_dir(path))
1171 } else { /* add a device */
1172 if (!S_ISBLK(info->st_mode))
1175 if (!_insert_dev(path, info->st_rdev))
1182 static void _drop_all_aliases(struct device *dev)
1184 struct dm_str_list *strl, *strl2;
1186 dm_list_iterate_items_safe(strl, strl2, &dev->aliases) {
1187 log_debug("Drop alias for %d:%d %s.", (int)MAJOR(dev->dev), (int)MINOR(dev->dev), strl->str);
1188 dm_hash_remove(_cache.names, strl->str);
1189 dm_list_del(&strl->list);
1193 void dev_cache_scan(struct cmd_context *cmd)
1195 log_debug_devs("Creating list of system devices.");
1197 _cache.has_scanned = 1;
1199 _insert_dirs(&_cache.dirs);
1201 if (cmd->check_devs_used)
1202 (void) dev_cache_index_devs();
1205 int dev_cache_has_scanned(void)
1207 return _cache.has_scanned;
1210 static int _init_preferred_names(struct cmd_context *cmd)
1212 const struct dm_config_node *cn;
1213 const struct dm_config_value *v;
1214 struct dm_pool *scratch = NULL;
1219 _cache.preferred_names_matcher = NULL;
1221 if (!(cn = find_config_tree_array(cmd, devices_preferred_names_CFG, NULL)) ||
1222 cn->v->type == DM_CFG_EMPTY_ARRAY) {
1223 log_very_verbose("devices/preferred_names %s: "
1224 "using built-in preferences",
1225 cn && cn->v->type == DM_CFG_EMPTY_ARRAY ? "is empty"
1226 : "not found in config");
1230 for (v = cn->v; v; v = v->next) {
1231 if (v->type != DM_CFG_STRING) {
1232 log_error("preferred_names patterns must be enclosed in quotes");
1239 if (!(scratch = dm_pool_create("preferred device name matcher", 1024)))
1242 if (!(regex = dm_pool_alloc(scratch, sizeof(*regex) * count))) {
1243 log_error("Failed to allocate preferred device name "
1248 for (v = cn->v, i = count - 1; v; v = v->next, i--) {
1249 if (!(regex[i] = dm_pool_strdup(scratch, v->v.str))) {
1250 log_error("Failed to allocate a preferred device name "
1256 if (!(_cache.preferred_names_matcher =
1257 dm_regex_create(_cache.mem, regex, count))) {
1258 log_error("Preferred device name pattern matcher creation failed.");
1265 dm_pool_destroy(scratch);
1270 int dev_cache_init(struct cmd_context *cmd)
1272 _cache.names = NULL;
1274 if (!(_cache.mem = dm_pool_create("dev_cache", 10 * 1024)))
1277 if (!(_cache.names = dm_hash_create(1020)) ||
1278 !(_cache.vgid_index = dm_hash_create(30)) ||
1279 !(_cache.lvid_index = dm_hash_create(29))) {
1280 dm_pool_destroy(_cache.mem);
1285 if (!(_cache.devices = btree_create(_cache.mem))) {
1286 log_error("Couldn't create binary tree for dev-cache.");
1290 if (!(_cache.sysfs_only_devices = btree_create(_cache.mem))) {
1291 log_error("Couldn't create binary tree for sysfs-only devices in dev cache.");
1295 if (!(_cache.dev_dir = _strdup(cmd->dev_dir))) {
1296 log_error("strdup dev_dir failed.");
1300 dm_list_init(&_cache.dirs);
1302 if (!_init_preferred_names(cmd))
1313 * Returns number of devices still open.
1315 static int _check_for_open_devices(int close_immediate)
1318 struct dm_hash_node *n;
1321 dm_hash_iterate(n, _cache.names) {
1322 dev = (struct device *) dm_hash_get_data(_cache.names, n);
1324 log_error("Device '%s' has been left open (%d remaining references).",
1325 dev_name(dev), dev->open_count);
1327 if (close_immediate && !dev_close_immediate(dev))
1336 * Returns number of devices left open.
1338 int dev_cache_check_for_open_devices(void)
1340 return _check_for_open_devices(0);
1343 int dev_cache_exit(void)
1346 struct dm_hash_node *n;
1350 if ((num_open = _check_for_open_devices(1)) > 0)
1351 log_error(INTERNAL_ERROR "%d device(s) were left open and have been closed.", num_open);
1353 dm_hash_iterate(n, _cache.names) {
1354 dev = (struct device *) dm_hash_get_data(_cache.names, n);
1355 free_dids(&dev->ids);
1356 free_wwids(&dev->wwids);
1361 dm_pool_destroy(_cache.mem);
1364 dm_hash_destroy(_cache.names);
1366 if (_cache.vgid_index)
1367 dm_hash_destroy(_cache.vgid_index);
1369 if (_cache.lvid_index)
1370 dm_hash_destroy(_cache.lvid_index);
1372 memset(&_cache, 0, sizeof(_cache));
1377 int dev_cache_add_dir(const char *path)
1379 struct dir_list *dl;
1382 if (stat(path, &st)) {
1383 log_warn("Ignoring %s: %s.", path, strerror(errno));
1384 /* But don't fail */
1388 if (!S_ISDIR(st.st_mode)) {
1389 log_warn("Ignoring %s: Not a directory.", path);
1393 if (!(dl = _zalloc(sizeof(*dl) + strlen(path) + 1))) {
1394 log_error("dir_list allocation failed");
1398 strcpy(dl->dir, path);
1399 dm_list_add(&_cache.dirs, &dl->list);
1403 struct device *dev_hash_get(const char *name)
1405 return (struct device *) dm_hash_lookup(_cache.names, name);
1408 static void _remove_alias(struct device *dev, const char *name)
1410 struct dm_str_list *strl;
1412 dm_list_iterate_items(strl, &dev->aliases) {
1413 if (!strcmp(strl->str, name)) {
1414 dm_list_del(&strl->list);
1421 * Check that paths for this dev still refer to the same dev_t. This is known
1422 * to drop invalid paths in the case where lvm deactivates an LV, which causes
1423 * that LV path to go away, but that LV path is not removed from dev-cache (it
1424 * probably should be). Later a new path to a different LV is added to
1425 * dev-cache, where the new LV has the same major:minor as the previously
1426 * deactivated LV. The new LV will find the existing struct dev, and that
1427 * struct dev will have dev->aliases entries that refer to the name of the old
1428 * deactivated LV. Those old paths are all invalid and are dropped here.
1431 void dev_cache_verify_aliases(struct device *dev)
1433 struct dm_str_list *strl, *strl2;
1436 dm_list_iterate_items_safe(strl, strl2, &dev->aliases) {
1437 if (stat(strl->str, &st) || (st.st_rdev != dev->dev)) {
1438 log_debug("Drop alias for %d:%d invalid path %s %d:%d.",
1439 (int)MAJOR(dev->dev), (int)MINOR(dev->dev), strl->str,
1440 (int)MAJOR(st.st_rdev), (int)MINOR(st.st_rdev));
1441 dm_hash_remove(_cache.names, strl->str);
1442 dm_list_del(&strl->list);
1447 static struct device *_dev_cache_get(struct cmd_context *cmd, const char *name, struct dev_filter *f, int existing)
1449 struct device *dev = (struct device *) dm_hash_lookup(_cache.names, name);
1454 * DEV_REGULAR means that is "dev" is actually a file, not a device.
1455 * FIXME: I don't think dev-cache is used for files any more and this
1458 if (dev && (dev->flags & DEV_REGULAR))
1461 if (dev && dm_list_empty(&dev->aliases)) {
1462 /* shouldn't happen */
1463 log_warn("Ignoring dev with no valid paths for %s.", name);
1468 * The requested path is invalid, remove any dev-cache info for it.
1470 if (stat(name, &st)) {
1472 log_debug("Device path %s is invalid for %d:%d %s.",
1473 name, (int)MAJOR(dev->dev), (int)MINOR(dev->dev), dev_name(dev));
1475 dm_hash_remove(_cache.names, name);
1477 _remove_alias(dev, name);
1479 /* Remove any other names in dev->aliases that are incorrect. */
1480 dev_cache_verify_aliases(dev);
1485 if (dev && dm_list_empty(&dev->aliases)) {
1486 /* shouldn't happen */
1487 log_warn("Ignoring dev with no valid paths for %s.", name);
1491 if (!S_ISBLK(st.st_mode)) {
1492 log_debug("Not a block device %s.", name);
1497 * dev-cache has incorrect info for the requested path.
1498 * Remove incorrect info and then add new dev-cache entry.
1500 if (dev && (st.st_rdev != dev->dev)) {
1501 struct device *dev_by_devt = (struct device *) btree_lookup(_cache.devices, (uint32_t) st.st_rdev);
1504 * lvm commands create this condition when they
1505 * activate/deactivate LVs combined with creating new LVs.
1506 * The command does not purge dev structs when deactivating
1507 * an LV (which it probably should do), but the better
1508 * approach would be not using dev-cache at all for LVs.
1511 log_debug("Dropping aliases for device entry %d:%d %s for new device %d:%d %s.",
1512 (int)MAJOR(dev->dev), (int)MINOR(dev->dev), dev_name(dev),
1513 (int)MAJOR(st.st_rdev), (int)MINOR(st.st_rdev), name);
1515 _drop_all_aliases(dev);
1518 log_debug("Dropping aliases for device entry %d:%d %s for new device %d:%d %s.",
1519 (int)MAJOR(dev_by_devt->dev), (int)MINOR(dev_by_devt->dev), dev_name(dev_by_devt),
1520 (int)MAJOR(st.st_rdev), (int)MINOR(st.st_rdev), name);
1522 _drop_all_aliases(dev_by_devt);
1527 * I think only lvm's own dm devs should be added here, so use
1528 * a warning to look for any other unknown cases.
1530 if (MAJOR(st.st_rdev) != cmd->dev_types->device_mapper_major) {
1531 log_warn("WARNING: new device appeared %d:%d %s",
1532 (int)MAJOR(st.st_rdev), (int)(MINOR(st.st_rdev)), name);
1536 if (!_insert_dev(name, st.st_rdev))
1539 /* Get the struct dev that was just added. */
1540 dev = (struct device *) dm_hash_lookup(_cache.names, name);
1543 log_error("Failed to get device %s", name);
1550 if (dev && dm_list_empty(&dev->aliases)) {
1551 /* shouldn't happen */
1552 log_warn("Ignoring dev with no valid paths for %s.", name);
1556 if (!dev && existing)
1560 * This case should never be hit for a PV. It should only
1561 * happen when the command is opening a new LV it has created.
1562 * Add an arg to all callers indicating when the arg should be
1563 * new (for an LV) and not existing.
1564 * FIXME: fix this further by not using dev-cache struct devs
1565 * at all for new dm devs (LVs) that lvm uses. Make the
1566 * dev-cache contain only devs for PVs.
1567 * Places to fix that use a dev for LVs include:
1568 * . lv_resize opening lv to discard
1569 * . wipe_lv opening lv to zero it
1570 * . _extend_sanlock_lv opening lv to extend it
1571 * . _write_log_header opening lv to write header
1572 * Also, io to LVs should not go through bcache.
1573 * bcache should contain only labels and metadata
1578 * This case should only be used for new devices created by this
1579 * command (opening LVs it's created), so if a dev exists for the
1580 * dev_t referenced by the name, then drop all aliases for before
1581 * _insert_dev adds the new name. lvm commands actually hit this
1582 * fairly often when it uses some LV, deactivates the LV, then
1583 * creates some new LV which ends up with the same major:minor.
1584 * Without dropping the aliases, it's plausible that lvm commands
1585 * could end up using the wrong dm device.
1587 struct device *dev_by_devt = (struct device *) btree_lookup(_cache.devices, (uint32_t) st.st_rdev);
1589 log_debug("Dropping aliases for %d:%d before adding new path %s.",
1590 (int)MAJOR(st.st_rdev), (int)(MINOR(st.st_rdev)), name);
1591 _drop_all_aliases(dev_by_devt);
1596 * I think only lvm's own dm devs should be added here, so use
1597 * a warning to look for any other unknown cases.
1599 if (MAJOR(st.st_rdev) != cmd->dev_types->device_mapper_major) {
1600 log_warn("WARNING: new device appeared %d:%d %s",
1601 (int)MAJOR(st.st_rdev), (int)(MINOR(st.st_rdev)), name);
1605 if (!_insert_dev(name, st.st_rdev))
1608 /* Get the struct dev that was just added. */
1609 dev = (struct device *) dm_hash_lookup(_cache.names, name);
1612 log_error("Failed to get device %s", name);
1619 * The caller passed a filter if they only want the dev if it
1626 ret = f->passes_filter(cmd, f, dev, NULL);
1628 log_debug_devs("dev_cache_get filter excludes %s", dev_name(dev));
1635 struct device *dev_cache_get_existing(struct cmd_context *cmd, const char *name, struct dev_filter *f)
1637 return _dev_cache_get(cmd, name, f, 1);
1640 struct device *dev_cache_get(struct cmd_context *cmd, const char *name, struct dev_filter *f)
1642 return _dev_cache_get(cmd, name, f, 0);
1645 struct device *dev_cache_get_by_devt(struct cmd_context *cmd, dev_t devt)
1647 struct device *dev = (struct device *) btree_lookup(_cache.devices, (uint32_t) devt);
1651 log_debug_devs("No devno %d:%d in dev cache.", (int)MAJOR(devt), (int)MINOR(devt));
1655 struct dev_iter *dev_iter_create(struct dev_filter *f, int unused)
1657 struct dev_iter *di = malloc(sizeof(*di));
1660 log_error("dev_iter allocation failed");
1664 di->current = btree_first(_cache.devices);
1667 di->filter->use_count++;
1672 void dev_iter_destroy(struct dev_iter *iter)
1675 iter->filter->use_count--;
1679 static struct device *_iter_next(struct dev_iter *iter)
1681 struct device *d = btree_get_data(iter->current);
1682 iter->current = btree_next(iter->current);
1686 struct device *dev_iter_get(struct cmd_context *cmd, struct dev_iter *iter)
1688 struct dev_filter *f;
1691 while (iter->current) {
1692 struct device *d = _iter_next(iter);
1697 if (f && !(d->flags & DEV_REGULAR))
1698 ret = f->passes_filter(cmd, f, d, NULL);
1700 if (!f || (d->flags & DEV_REGULAR) || ret)
1707 int dev_fd(struct device *dev)
1712 const char *dev_name(const struct device *dev)
1714 if (dev && dev->aliases.n && !dm_list_empty(&dev->aliases))
1715 return dm_list_item(dev->aliases.n, struct dm_str_list)->str;
1717 return unknown_device_name();
1720 bool dev_cache_has_md_with_end_superblock(struct dev_types *dt)
1722 struct btree_iter *iter = btree_first(_cache.devices);
1726 dev = btree_get_data(iter);
1728 if (dev_is_md_with_end_superblock(dt, dev))
1731 iter = btree_next(iter);
1737 static int _setup_devices_list(struct cmd_context *cmd)
1739 struct dm_str_list *strl;
1743 * For each --devices arg, add a du to cmd->use_devices.
1744 * The du has devname is the devices arg value.
1747 dm_list_iterate_items(strl, &cmd->deviceslist) {
1748 if (!(du = dm_pool_zalloc(cmd->mem, sizeof(struct dev_use))))
1751 if (!(du->devname = dm_pool_strdup(cmd->mem, strl->str)))
1754 dm_list_add(&cmd->use_devices, &du->list);
1760 static int _setup_devices_file_dmeventd(struct cmd_context *cmd)
1762 char path[PATH_MAX];
1766 * When command is run by dmeventd there is no --devicesfile
1767 * option that can enable/disable the use of a devices file.
1769 if (!find_config_tree_bool(cmd, devices_use_devicesfile_CFG, NULL)) {
1770 cmd->enable_devices_file = 0;
1775 * If /etc/lvm/devices/dmeventd.devices exists, then use that.
1776 * The optional dmeventd.devices allows the user to control
1777 * which devices dmeventd will look at and use.
1778 * Otherwise, disable the devices file because dmeventd should
1779 * be able to manage LVs in any VG (i.e. LVs in a non-system
1782 if (dm_snprintf(path, sizeof(path), "%s/devices/dmeventd.devices", cmd->system_dir) < 0) {
1783 log_warn("Failed to copy devices path");
1784 cmd->enable_devices_file = 0;
1788 if (stat(path, &st)) {
1789 /* No dmeventd.devices, so do not use a devices file. */
1790 cmd->enable_devices_file = 0;
1794 cmd->enable_devices_file = 1;
1795 (void) dm_strncpy(cmd->devices_file_path, path, sizeof(cmd->devices_file_path));
1799 int setup_devices_file(struct cmd_context *cmd)
1801 char dirpath[PATH_MAX];
1802 const char *filename = NULL;
1806 if (cmd->run_by_dmeventd)
1807 return _setup_devices_file_dmeventd(cmd);
1809 if (cmd->devicesfile) {
1810 /* --devicesfile <filename> or "" has been set which overrides
1811 lvm.conf settings use_devicesfile and devicesfile. */
1812 if (!strlen(cmd->devicesfile))
1813 cmd->enable_devices_file = 0;
1815 cmd->enable_devices_file = 1;
1816 filename = cmd->devicesfile;
1818 /* TODO: print a warning if --devicesfile system.devices
1819 while lvm.conf use_devicesfile=0. */
1821 if (!find_config_tree_bool(cmd, devices_use_devicesfile_CFG, NULL))
1822 cmd->enable_devices_file = 0;
1824 cmd->enable_devices_file = 1;
1825 filename = find_config_tree_str(cmd, devices_devicesfile_CFG, NULL);
1826 if (!validate_name(filename)) {
1827 log_error("Invalid devices file name from config setting \"%s\".", filename);
1833 if (!cmd->enable_devices_file)
1836 if (dm_snprintf(dirpath, sizeof(dirpath), "%s/devices", cmd->system_dir) < 0) {
1837 log_error("Failed to copy devices dir path");
1841 if (stat(dirpath, &st)) {
1842 log_debug("Creating %s.", dirpath);
1843 dm_prepare_selinux_context(dirpath, S_IFDIR);
1844 rv = mkdir(dirpath, 0755);
1845 dm_prepare_selinux_context(NULL, 0);
1847 if ((rv < 0) && stat(dirpath, &st)) {
1848 log_error("Failed to create %s %d", dirpath, errno);
1853 if (dm_snprintf(cmd->devices_file_path, sizeof(cmd->devices_file_path),
1854 "%s/devices/%s", cmd->system_dir, filename) < 0) {
1855 log_error("Failed to copy devices file path");
1862 * Add all system devices to dev-cache, and attempt to
1863 * match all devices_file entries to dev-cache entries.
1865 int setup_devices(struct cmd_context *cmd)
1870 if (cmd->enable_devices_list) {
1871 if (!_setup_devices_list(cmd))
1876 if (!setup_devices_file(cmd))
1879 if (!cmd->enable_devices_file)
1882 file_exists = devices_file_exists(cmd);
1885 * Fail if user specifies a file name that doesn't exist and
1886 * the command is not creating a new devices file.
1888 if (!file_exists && !cmd->create_edit_devices_file && cmd->devicesfile && strlen(cmd->devicesfile)) {
1889 log_error("Devices file not found: %s", cmd->devices_file_path);
1894 * Removing the devices file is another way of disabling the use of
1895 * a devices file, unless the command creates the devices file.
1897 if (!file_exists && !cmd->create_edit_devices_file) {
1898 log_debug("Devices file not found, ignoring.");
1899 cmd->enable_devices_file = 0;
1904 * Don't let pvcreate or vgcreate create a new system devices file
1905 * unless it's specified explicitly with --devicesfile. This avoids
1906 * a problem where a system is running with existing PVs, and is
1907 * not using a devices file based on the fact that the system
1908 * devices file doesn't exist. If the user simply uses pvcreate
1909 * to create a new PV, they almost certainly do not want that to
1910 * create a new system devices file containing the new PV and none
1911 * of the existing PVs that the system is already using.
1912 * However, if they use the vgimportdevices or lvmdevices command
1913 * then they are clearly intending to use the devices file, so we
1914 * can create it. Or, if they specify a non-system devices file
1915 * with pvcreate/vgcreate, then they clearly want to use a devices
1916 * file and we can create it (and creating a non-system devices file
1917 * would not cause existing PVs to disappear from the main system.)
1919 * An exception is if pvcreate/vgcreate get to device_id_write and
1920 * did not see any existing VGs during label scan. In that case
1921 * they will create a new system devices file, since there will be
1922 * no VGs that the new file would hide.
1924 if (cmd->create_edit_devices_file && !cmd->devicesfile && !file_exists &&
1925 (!strncmp(cmd->name, "pvcreate", 8) || !strncmp(cmd->name, "vgcreate", 8))) {
1926 /* The command will decide in device_ids_write whether to create
1927 a new system devices file. */
1928 cmd->enable_devices_file = 0;
1929 cmd->pending_devices_file = 1;
1933 if (!file_exists && cmd->sysinit) {
1934 cmd->enable_devices_file = 0;
1940 * pvcreate/vgcreate create a new devices file here if it
1941 * doesn't exist. They have create_edit_devices_file=1.
1942 * First create/lock-ex the devices file lockfile.
1943 * Other commands will not use a devices file if none exists.
1945 lock_mode = LOCK_EX;
1947 if (!lock_devices_file(cmd, lock_mode)) {
1948 log_error("Failed to lock the devices file to create.");
1952 /* The file will be created in device_ids_write() */
1953 if (!devices_file_exists(cmd))
1957 * Commands that intend to edit the devices file have
1958 * edit_devices_file or create_edit_devices_file set (create if
1959 * they can also create a new devices file) and lock it ex
1960 * here prior to reading. Other commands that intend to just
1961 * read the devices file lock sh.
1963 lock_mode = (cmd->create_edit_devices_file || cmd->edit_devices_file) ? LOCK_EX : LOCK_SH;
1965 if (!lock_devices_file(cmd, lock_mode)) {
1966 log_error("Failed to lock the devices file.");
1972 * Read the list of device ids that lvm can use.
1973 * Adds a struct dev_id to cmd->use_devices for each one.
1975 if (!device_ids_read(cmd)) {
1976 log_error("Failed to read the devices file.");
1977 unlock_devices_file(cmd);
1982 * When the command is editing the devices file, it acquires
1983 * the ex lock above, will later call device_ids_write(), and
1984 * then unlock the lock after writing the file.
1985 * When the command is just reading the devices file, it's
1986 * locked sh above just before reading the file, and unlocked
1987 * here after reading.
1989 if (lock_mode == LOCK_SH)
1990 unlock_devices_file(cmd);
1994 * Add a 'struct device' to dev-cache for each device available on the system.
1995 * This will not open or read any devices, but may look at sysfs properties.
1996 * This list of devs comes from looking /dev entries, or from asking libudev.
1998 dev_cache_scan(cmd);
2001 * Match entries from cmd->use_devices with device structs in dev-cache.
2003 device_ids_match(cmd);
2009 * The alternative to setup_devices() when the command is interested
2010 * in using only one PV.
2012 * Add one system device to dev-cache, and attempt to
2013 * match its dev-cache entry to a devices_file entry.
2015 int setup_device(struct cmd_context *cmd, const char *devname)
2020 if (cmd->enable_devices_list) {
2021 if (!_setup_devices_list(cmd))
2026 if (!setup_devices_file(cmd))
2029 if (!cmd->enable_devices_file)
2032 if (!devices_file_exists(cmd)) {
2033 log_debug("Devices file not found, ignoring.");
2034 cmd->enable_devices_file = 0;
2038 if (!lock_devices_file(cmd, LOCK_SH)) {
2039 log_error("Failed to lock the devices file to read.");
2043 if (!device_ids_read(cmd)) {
2044 log_error("Failed to read the devices file.");
2045 unlock_devices_file(cmd);
2049 unlock_devices_file(cmd);
2052 if (stat(devname, &buf) < 0) {
2053 log_error("Cannot access device %s.", devname);
2057 if (!S_ISBLK(buf.st_mode)) {
2058 log_error("Invaild device type %s.", devname);
2062 if (!_insert_dev(devname, buf.st_rdev))
2065 if (!(dev = (struct device *) dm_hash_lookup(_cache.names, devname)))
2068 /* Match this device to an entry in devices_file so it will not
2069 be rejected by filter-deviceid. */
2070 if (cmd->enable_devices_file)
2071 device_ids_match_dev(cmd, dev);
2077 * autoactivation is specialized/optimized to look only at command args,
2078 * so this just sets up the devices file, then individual devices are
2079 * added to dev-cache and matched with device_ids.
2082 int setup_devices_for_online_autoactivation(struct cmd_context *cmd)
2084 if (cmd->enable_devices_list) {
2085 if (!_setup_devices_list(cmd))
2090 if (!setup_devices_file(cmd))
2093 if (!cmd->enable_devices_file)
2096 if (!devices_file_exists(cmd)) {
2097 log_debug("Devices file not found, ignoring.");
2098 cmd->enable_devices_file = 0;
2102 if (!lock_devices_file(cmd, LOCK_SH)) {
2103 log_error("Failed to lock the devices file to read.");
2107 if (!device_ids_read(cmd)) {
2108 log_error("Failed to read the devices file.");
2109 unlock_devices_file(cmd);
2113 unlock_devices_file(cmd);
2118 /* Get a device name from a devno. */
2120 static char *_get_devname_from_devno(struct cmd_context *cmd, dev_t devno)
2122 char path[PATH_MAX];
2123 char devname[PATH_MAX] = { 0 };
2124 char namebuf[NAME_LEN];
2126 unsigned major = MAJOR(devno);
2127 unsigned minor = MINOR(devno);
2128 unsigned line_major;
2129 unsigned line_minor;
2130 uint64_t line_blocks;
2132 struct dirent *dirent;
2139 * $ ls /sys/dev/block/8:0/device/block/
2142 if (major_is_scsi_device(cmd->dev_types, major)) {
2143 if (dm_snprintf(path, sizeof(path), "%sdev/block/%d:%d/device/block",
2144 dm_sysfs_dir(), major, minor) < 0) {
2148 if (!(dir = opendir(path)))
2151 while ((dirent = readdir(dir))) {
2152 if (dirent->d_name[0] == '.')
2154 if (dm_snprintf(devname, sizeof(devname), "/dev/%s", dirent->d_name) < 0) {
2163 log_debug("Found %s for %d:%d from sys", devname, major, minor);
2164 return _strdup(devname);
2170 * $ cat /sys/dev/block/253:3/dm/name
2173 if (major == cmd->dev_types->device_mapper_major) {
2174 if (dm_snprintf(path, sizeof(path), "%sdev/block/%d:%d/dm/name",
2175 dm_sysfs_dir(), major, minor) < 0) {
2179 if (!get_sysfs_value(path, namebuf, sizeof(namebuf), 0))
2182 if (dm_snprintf(devname, sizeof(devname), "/dev/mapper/%s", namebuf) < 0) {
2188 log_debug("Found %s for %d:%d from sys dm", devname, major, minor);
2189 return _strdup(devname);
2195 * /proc/partitions lists
2196 * major minor #blocks name
2200 if (!(fp = fopen("/proc/partitions", "r")))
2203 while (fgets(line, sizeof(line), fp)) {
2204 if (sscanf(line, "%u %u %llu %s", &line_major, &line_minor, (unsigned long long *)&line_blocks, namebuf) != 4)
2206 if (line_major != major)
2208 if (line_minor != minor)
2211 if (dm_snprintf(devname, sizeof(devname), "/dev/%s", namebuf) < 0) {
2220 log_debug("Found %s for %d:%d from proc", devname, major, minor);
2221 return _strdup(devname);
2225 * If necessary, this could continue searching by stat'ing /dev entries.
2231 int setup_devname_in_dev_cache(struct cmd_context *cmd, const char *devname)
2235 if (stat(devname, &buf) < 0) {
2236 log_error("Cannot access device %s.", devname);
2240 if (!S_ISBLK(buf.st_mode)) {
2241 log_error("Invaild device type %s.", devname);
2245 if (!_insert_dev(devname, buf.st_rdev))
2248 if (!dm_hash_lookup(_cache.names, devname))
2254 int setup_devno_in_dev_cache(struct cmd_context *cmd, dev_t devno)
2256 const char *devname;
2258 if (!(devname = _get_devname_from_devno(cmd, devno)))
2261 return setup_devname_in_dev_cache(cmd, devname);
2264 struct device *setup_dev_in_dev_cache(struct cmd_context *cmd, dev_t devno, const char *devname)
2268 int major = (int)MAJOR(devno);
2269 int minor = (int)MINOR(devno);
2272 if (stat(devname, &buf) < 0) {
2273 log_error("Cannot access device %s for %d:%d.", devname, major, minor);
2276 if (!(devname = _get_devname_from_devno(cmd, devno))) {
2277 log_error("No device name found from %d:%d.", major, minor);
2280 if (stat(devname, &buf) < 0) {
2281 log_error("Cannot access device %s from %d:%d.", devname, major, minor);
2286 if (!(devname = _get_devname_from_devno(cmd, devno))) {
2287 log_error("No device name found from %d:%d.", major, minor);
2290 if (stat(devname, &buf) < 0) {
2291 log_error("Cannot access device %s from %d:%d.", devname, major, minor);
2296 if (!S_ISBLK(buf.st_mode)) {
2297 log_error("Invaild device type %s.", devname);
2301 if (devno && (buf.st_rdev != devno)) {
2302 log_warn("Found %s devno %d:%d expected %d:%d.", devname,
2303 (int)MAJOR(buf.st_rdev), (int)MINOR(buf.st_rdev), major, minor);
2306 if (!_insert_dev(devname, buf.st_rdev))
2309 if (!(dev = (struct device *) dm_hash_lookup(_cache.names, devname))) {
2310 log_error("Device lookup failed for %d:%d %s", major, minor, devname);