blkdeactivate.sh: Add PATH environment variable into script
[platform/upstream/device-mapper.git] / lib / device / dev-cache.c
1 /*
2  * Copyright (C) 2001-2004 Sistina Software, Inc. All rights reserved.
3  * Copyright (C) 2004-2007 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 "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"
25
26 #ifdef UDEV_SYNC_SUPPORT
27 #include <libudev.h>
28 #endif
29 #include <unistd.h>
30 #include <dirent.h>
31 #include <locale.h>
32 /* coverity[unnecessary_header] needed for MuslC */
33 #include <sys/file.h>
34
35 struct dev_iter {
36         struct btree_iter *current;
37         struct dev_filter *filter;
38 };
39
40 struct dir_list {
41         struct dm_list list;
42         char dir[0];
43 };
44
45 static struct {
46         struct dm_pool *mem;
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;
53         const char *dev_dir;
54
55         int has_scanned;
56         dev_t st_dev;
57         struct dm_list dirs;
58         struct dm_list files;
59
60 } _cache;
61
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))
65
66 static int _insert(const char *path, const struct stat *info,
67                    int rec, int check_with_udev_db);
68
69 /* Setup non-zero members of passed zeroed 'struct device' */
70 static void _dev_init(struct device *dev)
71 {
72         dev->fd = -1;
73         dev->bcache_fd = -1;
74         dev->bcache_di = -1;
75         dev->read_ahead = -1;
76         dev->part = -1;
77
78         dev->ext.enabled = 0;
79         dev->ext.src = DEV_EXT_NONE;
80
81         dm_list_init(&dev->aliases);
82         dm_list_init(&dev->ids);
83         dm_list_init(&dev->wwids);
84 }
85
86 void dev_destroy_file(struct device *dev)
87 {
88         if (!(dev->flags & DEV_ALLOCED))
89                 return;
90
91         free((void *) dm_list_item(dev->aliases.n, struct dm_str_list)->str);
92         free(dev->aliases.n);
93         free(dev);
94 }
95
96 struct device *dev_create_file(const char *filename, struct device *dev,
97                                struct dm_str_list *alias, int use_malloc)
98 {
99         int allocate = !dev;
100
101         if (allocate) {
102                 if (use_malloc) {
103                         if (!(dev = zalloc(sizeof(*dev)))) {
104                                 log_error("struct device allocation failed");
105                                 return NULL;
106                         }
107                         if (!(alias = zalloc(sizeof(*alias)))) {
108                                 log_error("struct dm_str_list allocation failed");
109                                 free(dev);
110                                 return NULL;
111                         }
112                         if (!(alias->str = strdup(filename))) {
113                                 log_error("filename strdup failed");
114                                 free(dev);
115                                 free(alias);
116                                 return NULL;
117                         }
118                 } else {
119                         if (!(dev = _zalloc(sizeof(*dev)))) {
120                                 log_error("struct device allocation failed");
121                                 return NULL;
122                         }
123                         if (!(alias = _zalloc(sizeof(*alias)))) {
124                                 log_error("struct dm_str_list allocation failed");
125                                 _free(dev);
126                                 return NULL;
127                         }
128                         if (!(alias->str = _strdup(filename))) {
129                                 log_error("filename strdup failed");
130                                 _free(dev);
131                                 return NULL;
132                         }
133                 }
134         } else if (!(alias->str = strdup(filename))) {
135                 log_error("filename strdup failed");
136                 return NULL;
137         }
138
139         _dev_init(dev);
140         dev->flags = DEV_REGULAR | ((use_malloc) ? DEV_ALLOCED : 0);
141         dm_list_add(&dev->aliases, &alias->list);
142
143         return dev;
144 }
145
146 static struct device *_dev_create(dev_t d)
147 {
148         struct device *dev;
149
150         if (!(dev = _zalloc(sizeof(*dev)))) {
151                 log_error("struct device allocation failed");
152                 return NULL;
153         }
154
155         _dev_init(dev);
156         dev->dev = d;
157
158         return dev;
159 }
160
161 void dev_set_preferred_name(struct dm_str_list *sl, struct device *dev)
162 {
163         /*
164          * Don't interfere with ordering specified in config file.
165          */
166         if (_cache.preferred_names_matcher)
167                 return;
168
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);
172 }
173
174 /*
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,
178  * return -2.
179  */
180 static int _builtin_preference(const char *path0, const char *path1,
181                                size_t skip_prefix_count, const char *subpath)
182 {
183         size_t subpath_len;
184         int r0, r1;
185
186         subpath_len = strlen(subpath);
187
188         r0 = !strncmp(path0 + skip_prefix_count, subpath, subpath_len);
189         r1 = !strncmp(path1 + skip_prefix_count, subpath, subpath_len);
190
191         if (!r0 && r1)
192                 /* path0 does not have the subpath - it wins */
193                 return 0;
194         else if (r0 && !r1)
195                 /* path1 does not have the subpath - it wins */
196                 return 1;
197         else if (r0 && r1)
198                 /* both of them have the subpath */
199                 return -1;
200
201         /* no path has the subpath */
202         return -2;
203 }
204
205 static int _apply_builtin_path_preference_rules(const char *path0, const char *path1)
206 {
207         size_t devdir_len;
208         int r;
209
210         devdir_len = strlen(_cache.dev_dir);
211
212         if (!strncmp(path0, _cache.dev_dir, devdir_len) &&
213             !strncmp(path1, _cache.dev_dir, devdir_len)) {
214                 /*
215                  * We're trying to achieve the ordering:
216                  *      /dev/block/ < /dev/dm-* < /dev/disk/ < /dev/mapper/ < anything else
217                  */
218
219                 /* Prefer any other path over /dev/block/ path. */
220                 if ((r = _builtin_preference(path0, path1, devdir_len, "block/")) >= -1)
221                         return r;
222
223                 /* Prefer any other path over /dev/dm-* path. */
224                 if ((r = _builtin_preference(path0, path1, devdir_len, "dm-")) >= -1)
225                         return r;
226
227                 /* Prefer any other path over /dev/disk/ path. */
228                 if ((r = _builtin_preference(path0, path1, devdir_len, "disk/")) >= -1)
229                         return r;
230
231                 /* Prefer any other path over /dev/mapper/ path. */
232                 if ((r = _builtin_preference(path0, path1, 0, dm_dir())) >= -1)
233                         return r;
234         }
235
236         return -1;
237 }
238
239 /* Return 1 if we prefer path1 else return 0 */
240 static int _compare_paths(const char *path0, const char *path1)
241 {
242         int slash0 = 0, slash1 = 0;
243         int m0, m1;
244         const char *p;
245         char p0[PATH_MAX], p1[PATH_MAX];
246         char *s0, *s1;
247         struct stat stat0, stat1;
248         int r;
249
250         /*
251          * FIXME Better to compare patterns one-at-a-time against all names.
252          */
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);
256
257                 if (m0 != m1) {
258                         if (m0 < 0)
259                                 return 1;
260                         if (m1 < 0)
261                                 return 0;
262                         if (m0 < m1)
263                                 return 1;
264                         if (m1 < m0)
265                                 return 0;
266                 }
267         }
268
269         /* Apply built-in preference rules first. */
270         if ((r = _apply_builtin_path_preference_rules(path0, path1)) >= 0)
271                 return r;
272
273         /* Return the path with fewer slashes */
274         for (p = path0; p++; p = (const char *) strchr(p, '/'))
275                 slash0++;
276
277         for (p = path1; p++; p = (const char *) strchr(p, '/'))
278                 slash1++;
279
280         if (slash0 < slash1)
281                 return 0;
282         if (slash1 < slash0)
283                 return 1;
284
285         (void) dm_strncpy(p0, path0, sizeof(p0));
286         (void) dm_strncpy(p1, path1, sizeof(p1));
287         s0 = p0 + 1;
288         s1 = p1 + 1;
289
290         /*
291          * If we reach here, both paths are the same length.
292          * Now skip past identical path components.
293          */
294         while (*s0 && *s0 == *s1)
295                 s0++, s1++;
296
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? */
300         while (s0 && s1) {
301                 if ((s0 = strchr(s0, '/')))
302                         *s0 = '\0';
303
304                 if ((s1 = strchr(s1, '/')))
305                         *s1 = '\0';
306
307                 if (lstat(p0, &stat0)) {
308                         log_sys_very_verbose("lstat", p0);
309                         return 1;
310                 }
311                 if (lstat(p1, &stat1)) {
312                         log_sys_very_verbose("lstat", p1);
313                         return 0;
314                 }
315                 if (S_ISLNK(stat0.st_mode) && !S_ISLNK(stat1.st_mode))
316                         return 0;
317                 if (!S_ISLNK(stat0.st_mode) && S_ISLNK(stat1.st_mode))
318                         return 1;
319                 if (s0)
320                         *s0++ = '/';
321                 if (s1)
322                         *s1++ = '/';
323         }
324
325         /* ASCII comparison */
326         if (strcmp(path0, path1) < 0)
327                 return 0;
328
329         return 1;
330 }
331
332 enum add_hash {
333         NO_HASH,
334         HASH,
335         REHASH
336 };
337
338 static int _add_alias(struct device *dev, const char *path, enum add_hash hash)
339 {
340         struct dm_str_list *sl;
341         struct dm_str_list *strl;
342         const char *oldpath;
343         int prefer_old = 1;
344
345         if (hash == REHASH)
346                 dm_hash_remove(_cache.names, path);
347
348         /* Is name already there? */
349         dm_list_iterate_items(strl, &dev->aliases)
350                 if (!strcmp(strl->str, path)) {
351                         path = strl->str;
352                         goto out;
353                 }
354
355         if (!(path = _strdup(path)) ||
356             !(sl = _zalloc(sizeof(*sl)))) {
357                 log_error("Failed to add allias to dev cache.");
358                 return 0;
359         }
360
361         if (!strncmp(path, "/dev/nvme", 9)) {
362                 log_debug("Found nvme device %s", dev_name(dev));
363                 dev->flags |= DEV_IS_NVME;
364         }
365
366         sl->str = path;
367
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);
371         }
372
373         if (prefer_old)
374                 dm_list_add(&dev->aliases, &sl->list);
375         else
376                 dm_list_add_h(&dev->aliases, &sl->list);
377 out:
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.");
381                 return 0;
382         }
383
384         return 1;
385 }
386
387 int get_sysfs_binary(const char *path, char *buf, size_t buf_size, int *retlen)
388 {
389         int ret;
390         int fd;
391
392         fd = open(path, O_RDONLY);
393         if (fd < 0)
394                 return 0;
395         ret = read(fd, buf, buf_size);
396         close(fd);
397         if (ret <= 0)
398                 return 0;
399         *retlen = ret;
400         return 1;
401 }
402
403 int get_sysfs_value(const char *path, char *buf, size_t buf_size, int error_if_no_value)
404 {
405         FILE *fp;
406         size_t len;
407         int r = 0;
408
409         if (!(fp = fopen(path, "r"))) {
410                 if (error_if_no_value)
411                         log_sys_error("fopen", path);
412                 return 0;
413         }
414
415         if (!fgets(buf, buf_size, fp)) {
416                 if (error_if_no_value)
417                         log_sys_error("fgets", path);
418                 goto out;
419         }
420
421         if ((len = strlen(buf)) && buf[len - 1] == '\n')
422                 buf[--len] = '\0';
423
424         if (!len && error_if_no_value)
425                 log_error("_get_sysfs_value: %s: no value", path);
426         else
427                 r = 1;
428 out:
429         if (fclose(fp))
430                 log_sys_debug("fclose", path);
431
432         return r;
433 }
434
435 int get_dm_uuid_from_sysfs(char *buf, size_t buf_size, int major, int minor)
436 {
437         char path[PATH_MAX];
438
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);
441                 return 0;
442         }
443
444         return get_sysfs_value(path, buf, buf_size, 0);
445 }
446
447 static struct dm_list *_get_or_add_list_by_index_key(struct dm_hash_table *idx, const char *key)
448 {
449         struct dm_list *list;
450
451         if ((list = dm_hash_lookup(idx, key)))
452                 return list;
453
454         if (!(list = _zalloc(sizeof(*list)))) {
455                 log_error("%s: failed to allocate device list for device cache index.", key);
456                 return NULL;
457         }
458
459         dm_list_init(list);
460
461         if (!dm_hash_insert(idx, key, list)) {
462                 log_error("%s: failed to insert device list to device cache index.", key);
463                 return NULL;
464         }
465
466         return list;
467 }
468
469 static struct device *_insert_sysfs_dev(dev_t devno, const char *devname)
470 {
471         static struct device _fake_dev = { .flags = DEV_USED_FOR_LV };
472         struct stat stat0;
473         char path[PATH_MAX];
474         struct device *dev;
475
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);
478                 return NULL;
479         }
480
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);
485                 return &_fake_dev;
486         }
487
488         if (!(dev = _dev_create(devno)))
489                 return_NULL;
490
491         if (!_add_alias(dev, path, NO_HASH)) {
492                 _free(dev);
493                 return_NULL;
494         }
495
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.");
498                 _free(dev);
499                 return NULL;
500         }
501
502         return dev;
503 }
504
505 static struct device *_get_device_for_sysfs_dev_name_using_devno(const char *devname)
506 {
507         char path[PATH_MAX];
508         char buf[PATH_MAX];
509         int major, minor;
510         dev_t devno;
511         struct device *dev;
512
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);
515                 return NULL;
516         }
517
518         if (!get_sysfs_value(path, buf, sizeof(buf), 1))
519                 return_NULL;
520
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);
523                 return NULL;
524         }
525
526         devno = MKDEV(major, minor);
527         if (!(dev = (struct device *) btree_lookup(_cache.devices, (uint32_t) devno))) {
528                 /*
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.
538                  */
539                 if (!(dev = (struct device *) btree_lookup(_cache.sysfs_only_devices, (uint32_t) devno)) &&
540                     !(dev = _insert_sysfs_dev(devno, devname)))
541                         return_NULL;
542         }
543
544         return dev;
545 }
546
547 #define NOT_LVM_UUID "-"
548
549 static int _get_vgid_and_lvid_for_dev(struct device *dev)
550 {
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];
554         size_t uuid_len;
555
556         if (!get_dm_uuid_from_sysfs(uuid, sizeof(uuid), (int) MAJOR(dev->dev), (int) MINOR(dev->dev)))
557                 return_0;
558
559         uuid_len = strlen(uuid);
560
561         /*
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).
565          */
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)))
572                         return_0;
573         } else
574                 dev->vgid = dev->lvid = NOT_LVM_UUID;
575
576         return 1;
577 }
578
579 static int _index_dev_by_vgid_and_lvid(struct device *dev)
580 {
581         const char *devname = dev_name(dev);
582         char devpath[PATH_MAX];
583         char path[PATH_MAX];
584         DIR *d;
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;
589         int r = 0;
590
591         if (dev->flags & DEV_USED_FOR_LV)
592                 /* already indexed */
593                 return 1;
594
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);
598                 return 0;
599         }
600
601         if (!(d = opendir(path))) {
602                 if (errno == ENOENT) {
603                         log_debug("%s: path does not exist, skipping", path);
604                         return 1;
605                 }
606                 log_sys_error("opendir", path);
607                 return 0;
608         }
609
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))
614                         continue;
615
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);
618                         goto out;
619                 }
620
621                 if (!(holder_dev = (struct device *) dm_hash_lookup(_cache.names, devpath))) {
622                         /*
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.
629                          */
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);
632                                 goto out;
633                         }
634                 }
635
636                 /* We're only interested in a holder which is a DM device. */
637                 if (!dm_is_dm_major(MAJOR(holder_dev->dev)))
638                         continue;
639
640                 /*
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.
643                  */
644                 if (!holder_dev->vgid && !_get_vgid_and_lvid_for_dev(holder_dev))
645                         goto_out;
646
647                 if (*holder_dev->vgid == *NOT_LVM_UUID)
648                         continue;
649
650                 /*
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.
653                  */
654                 if (dm_is_dm_major(MAJOR(dev->dev))) {
655                         if (!dev->vgid && !_get_vgid_and_lvid_for_dev(dev))
656                                 goto_out;
657
658                         if (*dev->vgid != *NOT_LVM_UUID && !strcmp(holder_dev->vgid, dev->vgid))
659                                 continue;
660                 }
661
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)))
664                         goto_out;
665
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);
670                         goto out;
671                 }
672
673                 dl_vgid->dev = dl_lvid->dev = dev;
674
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);
678
679                 /* Add dev list item to LVID device list. */
680                 dm_list_add(lvid_list, &dl_lvid->list);
681
682                 /* Mark device as used == also indexed in dev cache by VGID and LVID. */
683                 dev->flags |= DEV_USED_FOR_LV;
684         }
685
686         r = 1;
687 out:
688         if (closedir(d))
689                 log_sys_debug("closedir", path);
690
691         return r;
692 }
693
694 struct dm_list *dev_cache_get_dev_list_for_vgid(const char *vgid)
695 {
696         return dm_hash_lookup(_cache.vgid_index, vgid);
697 }
698
699 struct dm_list *dev_cache_get_dev_list_for_lvid(const char *lvid)
700 {
701         return dm_hash_lookup(_cache.lvid_index, lvid);
702 }
703
704 /*
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
708  * different device.
709  */
710
711 void dev_cache_failed_path(struct device *dev, const char *path)
712 {
713         struct dm_str_list *strl;
714
715         if (dm_hash_lookup(_cache.names, path))
716                 dm_hash_remove(_cache.names, path);
717
718         dm_list_iterate_items(strl, &dev->aliases) {
719                 if (!strcmp(strl->str, path)) {
720                         dm_list_del(&strl->list);
721                         break;
722                 }
723         }
724 }
725
726 /*
727  * Either creates a new dev, or adds an alias to
728  * an existing dev.
729  */
730 static int _insert_dev(const char *path, dev_t d)
731 {
732         struct device *dev;
733         struct device *dev_by_devt;
734         struct device *dev_by_path;
735
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);
738         dev = dev_by_devt;
739
740         /*
741          * Existing device, existing path points to the same device.
742          */
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);
746                 return 1;
747         }
748
749         /*
750          * No device or path found, add devt to cache.devices, add name to cache.names.
751          */
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);
755
756                 if (!(dev = (struct device *) btree_lookup(_cache.sysfs_only_devices, (uint32_t) d))) {
757                         /* create new device */
758                         if (!(dev = _dev_create(d)))
759                                 return_0;
760                 }
761
762                 if (!(btree_insert(_cache.devices, (uint32_t) d, dev))) {
763                         log_error("Couldn't insert device into binary tree.");
764                         _free(dev);
765                         return 0;
766                 }
767
768                 if (!_add_alias(dev, path, HASH))
769                         return_0;
770
771                 return 1;
772         }
773
774         /*
775          * Existing device, path is new, add path as a new alias for the device.
776          */
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);
780
781                 if (!_add_alias(dev, path, HASH))
782                         return_0;
783
784                 return 1;
785         }
786
787         /*
788          * No existing device, but path exists and previously pointed
789          * to a different device.
790          */
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));
795
796                 if (!(dev = (struct device *) btree_lookup(_cache.sysfs_only_devices, (uint32_t) d))) {
797                         /* create new device */
798                         if (!(dev = _dev_create(d)))
799                                 return_0;
800                 }
801
802                 if (!(btree_insert(_cache.devices, (uint32_t) d, dev))) {
803                         log_error("Couldn't insert device into binary tree.");
804                         _free(dev);
805                         return 0;
806                 }
807
808                 if (!_add_alias(dev, path, REHASH))
809                         return_0;
810
811                 return 1;
812         }
813
814         /*
815          * Existing device, and path exists and previously pointed to
816          * a different device.
817          */
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));
822
823                 if (!_add_alias(dev, path, REHASH))
824                         return_0;
825
826                 return 1;
827         }
828
829         log_error("Found dev %d:%d %s - failed to use.", (int)MAJOR(d), (int)MINOR(d), path);
830         return 0;
831 }
832
833 /*
834  * Get rid of extra slashes in the path string.
835  */
836 static void _collapse_slashes(char *str)
837 {
838         char *ptr;
839         int was_slash = 0;
840
841         for (ptr = str; *ptr; ptr++) {
842                 if (*ptr == '/') {
843                         if (was_slash)
844                                 continue;
845
846                         was_slash = 1;
847                 } else
848                         was_slash = 0;
849                 *str++ = *ptr;
850         }
851
852         *str = *ptr;
853 }
854
855 static int _insert_dir(const char *dir)
856 {
857         int n, dirent_count, r = 1;
858         struct dirent **dirent = NULL;
859         char path[PATH_MAX];
860         size_t len;
861
862         if (!dm_strncpy(path, dir, sizeof(path) - 1)) {
863                 log_debug_devs("Dir path %s is too long", path);
864                 return 0;
865         }
866         _collapse_slashes(path);
867         len = strlen(path);
868         if (len && path[len - 1] != '/')
869                 path[len++] = '/';
870
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] == '.')
876                                 continue;
877
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);
880                                 r = 0;
881                                 continue;
882                         }
883
884                         r &= _insert(path, NULL, 1, 0);
885                 }
886
887                 for (n = 0; n < dirent_count; n++)
888                         free(dirent[n]);
889                 free(dirent);
890         }
891         setlocale(LC_COLLATE, "");
892
893         return r;
894 }
895
896 static int _dev_cache_iterate_devs_for_index(void)
897 {
898         struct btree_iter *iter = btree_first(_cache.devices);
899         struct device *dev;
900         int r = 1;
901
902         while (iter) {
903                 dev = btree_get_data(iter);
904
905                 if (!_index_dev_by_vgid_and_lvid(dev))
906                         r = 0;
907
908                 iter = btree_next(iter);
909         }
910
911         return r;
912 }
913
914 static int _dev_cache_iterate_sysfs_for_index(const char *path)
915 {
916         char devname[PATH_MAX];
917         DIR *d;
918         struct dirent *dirent;
919         int major, minor;
920         dev_t devno;
921         struct device *dev;
922         int partial_failure = 0;
923         int r = 0;
924
925         if (!(d = opendir(path))) {
926                 log_sys_error("opendir", path);
927                 return 0;
928         }
929
930         while ((dirent = readdir(d))) {
931                 if (!strcmp(".", dirent->d_name) ||
932                     !strcmp("..", dirent->d_name))
933                         continue;
934
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);
938                         partial_failure = 1;
939                         continue;
940                 }
941
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))) {
947                                 partial_failure = 1;
948                                 continue;
949                         }
950                 }
951
952                 if (!_index_dev_by_vgid_and_lvid(dev))
953                         partial_failure = 1;
954         }
955
956         r = !partial_failure;
957
958         if (closedir(d))
959                 log_sys_debug("closedir", path);
960
961         return r;
962 }
963
964 static int dev_cache_index_devs(void)
965 {
966         static int sysfs_has_dev_block = -1;
967         char path[PATH_MAX];
968
969         if (dm_snprintf(path, sizeof(path), "%sdev/block", dm_sysfs_dir()) < 0) {
970                 log_error("dev_cache_index_devs: dm_snprintf failed.");
971                 return 0;
972         }
973
974         /* Skip indexing if /sys/dev/block is not available.*/
975         if (sysfs_has_dev_block == -1) {
976                 struct stat info;
977                 if (stat(path, &info) == 0)
978                         sysfs_has_dev_block = 1;
979                 else {
980                         if (errno == ENOENT) {
981                                 sysfs_has_dev_block = 0;
982                                 return 1;
983                         }
984
985                         log_sys_debug("stat", path);
986                         return 0;
987                 }
988         } else if (!sysfs_has_dev_block)
989                 return 1;
990
991         if (obtain_device_list_from_udev() &&
992             udev_get_library_context())
993                 return _dev_cache_iterate_devs_for_index();  /* with udev */
994
995         return _dev_cache_iterate_sysfs_for_index(path);
996 }
997
998 #ifdef UDEV_SYNC_SUPPORT
999
1000 static int _device_in_udev_db(const dev_t d)
1001 {
1002         struct udev *udev;
1003         struct udev_device *udev_device;
1004
1005         if (!(udev = udev_get_library_context()))
1006                 return_0;
1007
1008         if ((udev_device = udev_device_new_from_devnum(udev, 'b', d))) {
1009                 udev_device_unref(udev_device);
1010                 return 1;
1011         }
1012
1013         return 0;
1014 }
1015
1016 static int _insert_udev_dir(struct udev *udev, const char *dir)
1017 {
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;
1022         int r = 1;
1023
1024         if (!(udev_enum = udev_enumerate_new(udev))) {
1025                 log_error("Failed to udev_enumerate_new.");
1026                 return 0;
1027         }
1028
1029         if (udev_enumerate_add_match_subsystem(udev_enum, "block")) {
1030                 log_error("Failed to udev_enumerate_add_match_subsystem.");
1031                 goto out;
1032         }
1033
1034         if (udev_enumerate_scan_devices(udev_enum)) {
1035                 log_error("Failed to udev_enumerate_scan_devices.");
1036                 goto out;
1037         }
1038
1039         /*
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.
1047          */
1048         udev_list_entry_foreach(device_entry, udev_enumerate_get_list_entry(udev_enum)) {
1049                 entry_name = udev_list_entry_get_name(device_entry);
1050
1051                 if (!(device = udev_device_new_from_syspath(udev, entry_name))) {
1052                         log_very_verbose("udev failed to return a device for entry %s.",
1053                                          entry_name);
1054                         continue;
1055                 }
1056
1057                 if (!(node_name = udev_device_get_devnode(device)))
1058                         log_very_verbose("udev failed to return a device node for entry %s.",
1059                                          entry_name);
1060                 else
1061                         r &= _insert(node_name, NULL, 0, 0);
1062
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.",
1066                                                  entry_name);
1067                         else
1068                                 r &= _insert(symlink_name, NULL, 0, 0);
1069                 }
1070
1071                 udev_device_unref(device);
1072         }
1073
1074 out:
1075         udev_enumerate_unref(udev_enum);
1076
1077         return r;
1078 }
1079
1080 static void _insert_dirs(struct dm_list *dirs)
1081 {
1082         struct dir_list *dl;
1083         struct udev *udev = NULL;
1084         int with_udev;
1085         struct stat tinfo;
1086
1087         with_udev = obtain_device_list_from_udev() &&
1088                     (udev = udev_get_library_context());
1089
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));
1094                         continue;
1095                 }
1096                 _cache.st_dev = tinfo.st_dev;
1097                 if (with_udev) {
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);
1102                 }
1103                 else if (!_insert_dir(dl->dir))
1104                         log_debug_devs("%s: Failed to insert devices to "
1105                                        "device cache fully", dl->dir);
1106         }
1107 }
1108
1109 #else   /* UDEV_SYNC_SUPPORT */
1110
1111 static int _device_in_udev_db(const dev_t d)
1112 {
1113         return 0;
1114 }
1115
1116 static void _insert_dirs(struct dm_list *dirs)
1117 {
1118         struct dir_list *dl;
1119         struct stat tinfo;
1120
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));
1125                         continue;
1126                 }
1127                 _cache.st_dev = tinfo.st_dev;
1128                 _insert_dir(dl->dir);
1129         }
1130 }
1131
1132 #endif  /* UDEV_SYNC_SUPPORT */
1133
1134 static int _insert(const char *path, const struct stat *info,
1135                    int rec, int check_with_udev_db)
1136 {
1137         struct stat tinfo;
1138
1139         if (!info) {
1140                 if (stat(path, &tinfo) < 0) {
1141                         log_sys_very_verbose("stat", path);
1142                         return 0;
1143                 }
1144                 info = &tinfo;
1145         }
1146
1147         if (check_with_udev_db && !_device_in_udev_db(info->st_rdev)) {
1148                 log_very_verbose("%s: Not in udev db", path);
1149                 return 0;
1150         }
1151
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);
1156                         return 0;
1157                 }
1158
1159                 if (S_ISLNK(tinfo.st_mode)) {
1160                         log_debug_devs("%s: Symbolic link to directory", path);
1161                         return 1;
1162                 }
1163
1164                 if (info->st_dev != _cache.st_dev) {
1165                         log_debug_devs("%s: Different filesystem in directory", path);
1166                         return 1;
1167                 }
1168
1169                 if (rec && !_insert_dir(path))
1170                         return 0;
1171         } else {                /* add a device */
1172                 if (!S_ISBLK(info->st_mode))
1173                         return 1;
1174
1175                 if (!_insert_dev(path, info->st_rdev))
1176                         return 0;
1177         }
1178
1179         return 1;
1180 }
1181
1182 static void _drop_all_aliases(struct device *dev)
1183 {
1184         struct dm_str_list *strl, *strl2;
1185
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);
1190         }
1191 }
1192
1193 void dev_cache_scan(struct cmd_context *cmd)
1194 {
1195         log_debug_devs("Creating list of system devices.");
1196
1197         _cache.has_scanned = 1;
1198
1199         _insert_dirs(&_cache.dirs);
1200
1201         if (cmd->check_devs_used)
1202                 (void) dev_cache_index_devs();
1203 }
1204
1205 int dev_cache_has_scanned(void)
1206 {
1207         return _cache.has_scanned;
1208 }
1209
1210 static int _init_preferred_names(struct cmd_context *cmd)
1211 {
1212         const struct dm_config_node *cn;
1213         const struct dm_config_value *v;
1214         struct dm_pool *scratch = NULL;
1215         const char **regex;
1216         unsigned count = 0;
1217         int i, r = 0;
1218
1219         _cache.preferred_names_matcher = NULL;
1220
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");
1227                 return 1;
1228         }
1229
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");
1233                         return 0;
1234                 }
1235
1236                 count++;
1237         }
1238
1239         if (!(scratch = dm_pool_create("preferred device name matcher", 1024)))
1240                 return_0;
1241
1242         if (!(regex = dm_pool_alloc(scratch, sizeof(*regex) * count))) {
1243                 log_error("Failed to allocate preferred device name "
1244                           "pattern list.");
1245                 goto out;
1246         }
1247
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 "
1251                                   "pattern.");
1252                         goto out;
1253                 }
1254         }
1255
1256         if (!(_cache.preferred_names_matcher =
1257                 dm_regex_create(_cache.mem, regex, count))) {
1258                 log_error("Preferred device name pattern matcher creation failed.");
1259                 goto out;
1260         }
1261
1262         r = 1;
1263
1264 out:
1265         dm_pool_destroy(scratch);
1266
1267         return r;
1268 }
1269
1270 int dev_cache_init(struct cmd_context *cmd)
1271 {
1272         _cache.names = NULL;
1273
1274         if (!(_cache.mem = dm_pool_create("dev_cache", 10 * 1024)))
1275                 return_0;
1276
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);
1281                 _cache.mem = 0;
1282                 return_0;
1283         }
1284
1285         if (!(_cache.devices = btree_create(_cache.mem))) {
1286                 log_error("Couldn't create binary tree for dev-cache.");
1287                 goto bad;
1288         }
1289
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.");
1292                 goto bad;
1293         }
1294
1295         if (!(_cache.dev_dir = _strdup(cmd->dev_dir))) {
1296                 log_error("strdup dev_dir failed.");
1297                 goto bad;
1298         }
1299
1300         dm_list_init(&_cache.dirs);
1301
1302         if (!_init_preferred_names(cmd))
1303                 goto_bad;
1304
1305         return 1;
1306
1307       bad:
1308         dev_cache_exit();
1309         return 0;
1310 }
1311
1312 /*
1313  * Returns number of devices still open.
1314  */
1315 static int _check_for_open_devices(int close_immediate)
1316 {
1317         struct device *dev;
1318         struct dm_hash_node *n;
1319         int num_open = 0;
1320
1321         dm_hash_iterate(n, _cache.names) {
1322                 dev = (struct device *) dm_hash_get_data(_cache.names, n);
1323                 if (dev->fd >= 0) {
1324                         log_error("Device '%s' has been left open (%d remaining references).",
1325                                   dev_name(dev), dev->open_count);
1326                         num_open++;
1327                         if (close_immediate && !dev_close_immediate(dev))
1328                                 stack;
1329                 }
1330         }
1331
1332         return num_open;
1333 }
1334
1335 /*
1336  * Returns number of devices left open.
1337  */
1338 int dev_cache_check_for_open_devices(void)
1339 {
1340         return _check_for_open_devices(0);
1341 }
1342
1343 int dev_cache_exit(void)
1344 {
1345         struct device *dev;
1346         struct dm_hash_node *n;
1347         int num_open = 0;
1348
1349         if (_cache.names) {
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);
1352
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);
1357                 }
1358         }
1359
1360         if (_cache.mem)
1361                 dm_pool_destroy(_cache.mem);
1362
1363         if (_cache.names)
1364                 dm_hash_destroy(_cache.names);
1365
1366         if (_cache.vgid_index)
1367                 dm_hash_destroy(_cache.vgid_index);
1368
1369         if (_cache.lvid_index)
1370                 dm_hash_destroy(_cache.lvid_index);
1371
1372         memset(&_cache, 0, sizeof(_cache));
1373
1374         return (!num_open);
1375 }
1376
1377 int dev_cache_add_dir(const char *path)
1378 {
1379         struct dir_list *dl;
1380         struct stat st;
1381
1382         if (stat(path, &st)) {
1383                 log_warn("Ignoring %s: %s.", path, strerror(errno));
1384                 /* But don't fail */
1385                 return 1;
1386         }
1387
1388         if (!S_ISDIR(st.st_mode)) {
1389                 log_warn("Ignoring %s: Not a directory.", path);
1390                 return 1;
1391         }
1392
1393         if (!(dl = _zalloc(sizeof(*dl) + strlen(path) + 1))) {
1394                 log_error("dir_list allocation failed");
1395                 return 0;
1396         }
1397
1398         strcpy(dl->dir, path);
1399         dm_list_add(&_cache.dirs, &dl->list);
1400         return 1;
1401 }
1402
1403 struct device *dev_hash_get(const char *name)
1404 {
1405         return (struct device *) dm_hash_lookup(_cache.names, name);
1406 }
1407
1408 static void _remove_alias(struct device *dev, const char *name)
1409 {
1410         struct dm_str_list *strl;
1411
1412         dm_list_iterate_items(strl, &dev->aliases) {
1413                 if (!strcmp(strl->str, name)) {
1414                         dm_list_del(&strl->list);
1415                         return;
1416                 }
1417         }
1418 }
1419
1420 /*
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.
1429  */
1430
1431 void dev_cache_verify_aliases(struct device *dev)
1432 {
1433         struct dm_str_list *strl, *strl2;
1434         struct stat st;
1435
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);
1443                 }
1444         }
1445 }
1446
1447 static struct device *_dev_cache_get(struct cmd_context *cmd, const char *name, struct dev_filter *f, int existing)
1448 {
1449         struct device *dev = (struct device *) dm_hash_lookup(_cache.names, name);
1450         struct stat st;
1451         int ret;
1452
1453         /*
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
1456          * can be dropped?
1457          */
1458         if (dev && (dev->flags & DEV_REGULAR))
1459                 return dev;
1460
1461         if (dev && dm_list_empty(&dev->aliases)) {
1462                 /* shouldn't happen */
1463                 log_warn("Ignoring dev with no valid paths for %s.", name);
1464                 return NULL;
1465         }
1466
1467         /*
1468          * The requested path is invalid, remove any dev-cache info for it.
1469          */
1470         if (stat(name, &st)) {
1471                 if (dev) {
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));
1474
1475                         dm_hash_remove(_cache.names, name);
1476
1477                         _remove_alias(dev, name);
1478
1479                         /* Remove any other names in dev->aliases that are incorrect. */
1480                         dev_cache_verify_aliases(dev);
1481                 }
1482                 return NULL;
1483         }
1484
1485         if (dev && dm_list_empty(&dev->aliases)) {
1486                 /* shouldn't happen */
1487                 log_warn("Ignoring dev with no valid paths for %s.", name);
1488                 return NULL;
1489         }
1490
1491         if (!S_ISBLK(st.st_mode)) {
1492                 log_debug("Not a block device %s.", name);
1493                 return NULL;
1494         }
1495
1496         /*
1497          * dev-cache has incorrect info for the requested path.
1498          * Remove incorrect info and then add new dev-cache entry.
1499          */
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);
1502
1503                 /*
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.
1509                  */
1510
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);
1514
1515                 _drop_all_aliases(dev);
1516
1517                 if (dev_by_devt) {
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);
1521
1522                         _drop_all_aliases(dev_by_devt);
1523                 }
1524
1525 #if 0
1526                 /*
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.
1529                  */
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);
1533                 }
1534 #endif
1535
1536                 if (!_insert_dev(name, st.st_rdev))
1537                         return_NULL;
1538
1539                 /* Get the struct dev that was just added. */
1540                 dev = (struct device *) dm_hash_lookup(_cache.names, name);
1541
1542                 if (!dev) {
1543                         log_error("Failed to get device %s", name);
1544                         return NULL;
1545                 }
1546
1547                 goto out;
1548         }
1549
1550         if (dev && dm_list_empty(&dev->aliases)) {
1551                 /* shouldn't happen */
1552                 log_warn("Ignoring dev with no valid paths for %s.", name);
1553                 return NULL;
1554         }
1555
1556         if (!dev && existing)
1557                 return_NULL;
1558
1559         /*
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
1574          * scanned from PVs.
1575          */
1576         if (!dev) {
1577                 /*
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.
1586                  */
1587                 struct device *dev_by_devt = (struct device *) btree_lookup(_cache.devices, (uint32_t) st.st_rdev);
1588                 if (dev_by_devt) {
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);
1592                 }
1593
1594 #if 0
1595                 /*
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.
1598                  */
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);
1602                 }
1603 #endif
1604
1605                 if (!_insert_dev(name, st.st_rdev))
1606                         return_NULL;
1607
1608                 /* Get the struct dev that was just added. */
1609                 dev = (struct device *) dm_hash_lookup(_cache.names, name);
1610
1611                 if (!dev) {
1612                         log_error("Failed to get device %s", name);
1613                         return NULL;
1614                 }
1615         }
1616
1617  out:
1618         /*
1619          * The caller passed a filter if they only want the dev if it
1620          * passes filters.
1621          */
1622
1623         if (!f)
1624                 return dev;
1625
1626         ret = f->passes_filter(cmd, f, dev, NULL);
1627         if (!ret) {
1628                 log_debug_devs("dev_cache_get filter excludes %s", dev_name(dev));
1629                 return NULL;
1630         }
1631
1632         return dev;
1633 }
1634
1635 struct device *dev_cache_get_existing(struct cmd_context *cmd, const char *name, struct dev_filter *f)
1636 {
1637         return _dev_cache_get(cmd, name, f, 1);
1638 }
1639
1640 struct device *dev_cache_get(struct cmd_context *cmd, const char *name, struct dev_filter *f)
1641 {
1642         return _dev_cache_get(cmd, name, f, 0);
1643 }
1644
1645 struct device *dev_cache_get_by_devt(struct cmd_context *cmd, dev_t devt)
1646 {
1647         struct device *dev = (struct device *) btree_lookup(_cache.devices, (uint32_t) devt);
1648
1649         if (dev)
1650                 return dev;
1651         log_debug_devs("No devno %d:%d in dev cache.", (int)MAJOR(devt), (int)MINOR(devt));
1652         return NULL;
1653 }
1654
1655 struct dev_iter *dev_iter_create(struct dev_filter *f, int unused)
1656 {
1657         struct dev_iter *di = malloc(sizeof(*di));
1658
1659         if (!di) {
1660                 log_error("dev_iter allocation failed");
1661                 return NULL;
1662         }
1663
1664         di->current = btree_first(_cache.devices);
1665         di->filter = f;
1666         if (di->filter)
1667                 di->filter->use_count++;
1668
1669         return di;
1670 }
1671
1672 void dev_iter_destroy(struct dev_iter *iter)
1673 {
1674         if (iter->filter)
1675                 iter->filter->use_count--;
1676         free(iter);
1677 }
1678
1679 static struct device *_iter_next(struct dev_iter *iter)
1680 {
1681         struct device *d = btree_get_data(iter->current);
1682         iter->current = btree_next(iter->current);
1683         return d;
1684 }
1685
1686 struct device *dev_iter_get(struct cmd_context *cmd, struct dev_iter *iter)
1687 {
1688         struct dev_filter *f;
1689         int ret;
1690
1691         while (iter->current) {
1692                 struct device *d = _iter_next(iter);
1693                 ret = 1;
1694
1695                 f = iter->filter;
1696
1697                 if (f && !(d->flags & DEV_REGULAR))
1698                         ret = f->passes_filter(cmd, f, d, NULL);
1699
1700                 if (!f || (d->flags & DEV_REGULAR) || ret)
1701                         return d;
1702         }
1703
1704         return NULL;
1705 }
1706
1707 int dev_fd(struct device *dev)
1708 {
1709         return dev->fd;
1710 }
1711
1712 const char *dev_name(const struct device *dev)
1713 {
1714         if (dev && dev->aliases.n && !dm_list_empty(&dev->aliases))
1715                 return dm_list_item(dev->aliases.n, struct dm_str_list)->str;
1716         else
1717                 return unknown_device_name();
1718 }
1719
1720 bool dev_cache_has_md_with_end_superblock(struct dev_types *dt)
1721 {
1722         struct btree_iter *iter = btree_first(_cache.devices);
1723         struct device *dev;
1724
1725         while (iter) {
1726                 dev = btree_get_data(iter);
1727
1728                 if (dev_is_md_with_end_superblock(dt, dev))
1729                         return true;
1730
1731                 iter = btree_next(iter);
1732         }
1733
1734         return false;
1735 }
1736
1737 static int _setup_devices_list(struct cmd_context *cmd)
1738 {
1739         struct dm_str_list *strl;
1740         struct dev_use *du;
1741
1742         /*
1743          * For each --devices arg, add a du to cmd->use_devices.
1744          * The du has devname is the devices arg value.
1745          */
1746
1747         dm_list_iterate_items(strl, &cmd->deviceslist) {
1748                 if (!(du = dm_pool_zalloc(cmd->mem, sizeof(struct dev_use))))
1749                         return_0;
1750
1751                 if (!(du->devname = dm_pool_strdup(cmd->mem, strl->str)))
1752                         return_0;
1753
1754                 dm_list_add(&cmd->use_devices, &du->list);
1755         }
1756
1757         return 1;
1758 }
1759
1760 static int _setup_devices_file_dmeventd(struct cmd_context *cmd)
1761 {
1762         char path[PATH_MAX];
1763         struct stat st;
1764
1765         /*
1766          * When command is run by dmeventd there is no --devicesfile
1767          * option that can enable/disable the use of a devices file.
1768          */
1769         if (!find_config_tree_bool(cmd, devices_use_devicesfile_CFG, NULL)) {
1770                 cmd->enable_devices_file = 0;
1771                 return 1;
1772         }
1773
1774         /*
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
1780          * devices file.)
1781          */
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;
1785                 return 1;
1786         }
1787
1788         if (stat(path, &st)) {
1789                 /* No dmeventd.devices, so do not use a devices file. */
1790                 cmd->enable_devices_file = 0;
1791                 return 1;
1792         }
1793
1794         cmd->enable_devices_file = 1;
1795         (void) dm_strncpy(cmd->devices_file_path, path, sizeof(cmd->devices_file_path));
1796         return 1;
1797 }
1798         
1799 int setup_devices_file(struct cmd_context *cmd)
1800 {
1801         char dirpath[PATH_MAX];
1802         const char *filename = NULL;
1803         struct stat st;
1804         int rv;
1805
1806         if (cmd->run_by_dmeventd)
1807                 return _setup_devices_file_dmeventd(cmd);
1808
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;
1814                 else {
1815                         cmd->enable_devices_file = 1;
1816                         filename = cmd->devicesfile;
1817                 }
1818                 /* TODO: print a warning if --devicesfile system.devices
1819                    while lvm.conf use_devicesfile=0. */
1820         } else {
1821                 if (!find_config_tree_bool(cmd, devices_use_devicesfile_CFG, NULL))
1822                         cmd->enable_devices_file = 0;
1823                 else {
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);
1828                                 return 0;
1829                         }
1830                 }
1831         }
1832
1833         if (!cmd->enable_devices_file)
1834                 return 1;
1835
1836         if (dm_snprintf(dirpath, sizeof(dirpath), "%s/devices", cmd->system_dir) < 0) {
1837                 log_error("Failed to copy devices dir path");
1838                 return 0;
1839         }
1840
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);
1846
1847                 if ((rv < 0) && stat(dirpath, &st)) {
1848                         log_error("Failed to create %s %d", dirpath, errno);
1849                         return 0;
1850                 }
1851         }
1852         
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");
1856                 return 0;
1857         }
1858         return 1;
1859 }
1860
1861 /*
1862  * Add all system devices to dev-cache, and attempt to
1863  * match all devices_file entries to dev-cache entries.
1864  */
1865 int setup_devices(struct cmd_context *cmd)
1866 {
1867         int file_exists;
1868         int lock_mode = 0;
1869
1870         if (cmd->enable_devices_list) {
1871                 if (!_setup_devices_list(cmd))
1872                         return_0;
1873                 goto scan;
1874         }
1875
1876         if (!setup_devices_file(cmd))
1877                 return_0;
1878
1879         if (!cmd->enable_devices_file)
1880                 goto scan;
1881
1882         file_exists = devices_file_exists(cmd);
1883
1884         /*
1885          * Fail if user specifies a file name that doesn't exist and
1886          * the command is not creating a new devices file.
1887          */
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);
1890                 return 0;
1891         }
1892
1893         /*
1894          * Removing the devices file is another way of disabling the use of
1895          * a devices file, unless the command creates the devices file.
1896          */
1897         if (!file_exists && !cmd->create_edit_devices_file) {
1898                 log_debug("Devices file not found, ignoring.");
1899                 cmd->enable_devices_file = 0;
1900                 goto scan;
1901         }
1902
1903         /*
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.)
1918          *
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.
1923          */
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;
1930                 goto scan;
1931         }
1932
1933         if (!file_exists && cmd->sysinit) {
1934                 cmd->enable_devices_file = 0;
1935                 goto scan;
1936         }
1937
1938         if (!file_exists) {
1939                 /*
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.
1944                  */
1945                 lock_mode = LOCK_EX;
1946
1947                 if (!lock_devices_file(cmd, lock_mode)) {
1948                         log_error("Failed to lock the devices file to create.");
1949                         return 0;
1950                 }
1951
1952                 /* The file will be created in device_ids_write() */
1953                 if (!devices_file_exists(cmd))
1954                         goto scan;
1955         } else {
1956                 /*
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.
1962                  */
1963                 lock_mode = (cmd->create_edit_devices_file || cmd->edit_devices_file) ? LOCK_EX : LOCK_SH;
1964
1965                 if (!lock_devices_file(cmd, lock_mode)) {
1966                         log_error("Failed to lock the devices file.");
1967                         return 0;
1968                 }
1969         }
1970
1971         /*
1972          * Read the list of device ids that lvm can use.
1973          * Adds a struct dev_id to cmd->use_devices for each one.
1974          */
1975         if (!device_ids_read(cmd)) {
1976                 log_error("Failed to read the devices file.");
1977                 unlock_devices_file(cmd);
1978                 return 0;
1979         }
1980
1981         /*
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.
1988          */
1989         if (lock_mode == LOCK_SH)
1990                 unlock_devices_file(cmd);
1991
1992  scan:
1993         /*
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.
1997          */
1998         dev_cache_scan(cmd);
1999
2000         /*
2001          * Match entries from cmd->use_devices with device structs in dev-cache.
2002          */
2003         device_ids_match(cmd);
2004
2005         return 1;
2006 }
2007
2008 /*
2009  * The alternative to setup_devices() when the command is interested
2010  * in using only one PV.
2011  *
2012  * Add one system device to dev-cache, and attempt to
2013  * match its dev-cache entry to a devices_file entry.
2014  */
2015 int setup_device(struct cmd_context *cmd, const char *devname)
2016 {
2017         struct stat buf;
2018         struct device *dev;
2019
2020         if (cmd->enable_devices_list) {
2021                 if (!_setup_devices_list(cmd))
2022                         return_0;
2023                 goto scan;
2024         }
2025
2026         if (!setup_devices_file(cmd))
2027                 return_0;
2028
2029         if (!cmd->enable_devices_file)
2030                 goto scan;
2031
2032         if (!devices_file_exists(cmd)) {
2033                 log_debug("Devices file not found, ignoring.");
2034                 cmd->enable_devices_file = 0;
2035                 goto scan;
2036         }
2037
2038         if (!lock_devices_file(cmd, LOCK_SH)) {
2039                 log_error("Failed to lock the devices file to read.");
2040                 return 0;
2041         }
2042
2043         if (!device_ids_read(cmd)) {
2044                 log_error("Failed to read the devices file.");
2045                 unlock_devices_file(cmd);
2046                 return 0;
2047         }
2048
2049         unlock_devices_file(cmd);
2050
2051  scan:
2052         if (stat(devname, &buf) < 0) {
2053                 log_error("Cannot access device %s.", devname);
2054                 return 0;
2055         }
2056
2057         if (!S_ISBLK(buf.st_mode)) {
2058                 log_error("Invaild device type %s.", devname);
2059                 return 0;
2060         }
2061
2062         if (!_insert_dev(devname, buf.st_rdev))
2063                 return_0;
2064
2065         if (!(dev = (struct device *) dm_hash_lookup(_cache.names, devname)))
2066                 return_0;
2067
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);
2072
2073         return 1;
2074 }
2075
2076 /*
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.
2080  */
2081
2082 int setup_devices_for_online_autoactivation(struct cmd_context *cmd)
2083 {
2084         if (cmd->enable_devices_list) {
2085                 if (!_setup_devices_list(cmd))
2086                         return_0;
2087                 return 1;
2088         }
2089
2090         if (!setup_devices_file(cmd))
2091                 return_0;
2092
2093         if (!cmd->enable_devices_file)
2094                 return 1;
2095
2096         if (!devices_file_exists(cmd)) {
2097                 log_debug("Devices file not found, ignoring.");
2098                 cmd->enable_devices_file = 0;
2099                 return 1;
2100         }
2101
2102         if (!lock_devices_file(cmd, LOCK_SH)) {
2103                 log_error("Failed to lock the devices file to read.");
2104                 return 0;
2105         }
2106
2107         if (!device_ids_read(cmd)) {
2108                 log_error("Failed to read the devices file.");
2109                 unlock_devices_file(cmd);
2110                 return 0;
2111         }
2112
2113         unlock_devices_file(cmd);
2114         return 1;
2115 }
2116
2117
2118 /* Get a device name from a devno. */
2119
2120 static char *_get_devname_from_devno(struct cmd_context *cmd, dev_t devno)
2121 {
2122         char path[PATH_MAX];
2123         char devname[PATH_MAX] = { 0 };
2124         char namebuf[NAME_LEN];
2125         char line[1024];
2126         unsigned major = MAJOR(devno);
2127         unsigned minor = MINOR(devno);
2128         unsigned line_major;
2129         unsigned line_minor;
2130         uint64_t line_blocks;
2131         DIR *dir;
2132         struct dirent *dirent;
2133         FILE *fp;
2134
2135         if (!devno)
2136                 return NULL;
2137
2138         /*
2139          * $ ls /sys/dev/block/8:0/device/block/
2140          * sda
2141          */
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) {
2145                         return NULL;
2146                 }
2147
2148                 if (!(dir = opendir(path)))
2149                         goto try_partition;
2150
2151                 while ((dirent = readdir(dir))) {
2152                         if (dirent->d_name[0] == '.')
2153                                 continue;
2154                         if (dm_snprintf(devname, sizeof(devname), "/dev/%s", dirent->d_name) < 0) {
2155                                 devname[0] = '\0';
2156                                 stack;
2157                         }
2158                         break;
2159                 }
2160                 closedir(dir);
2161
2162                 if (devname[0]) {
2163                         log_debug("Found %s for %d:%d from sys", devname, major, minor);
2164                         return _strdup(devname);
2165                 }
2166                 return NULL;
2167         }
2168
2169         /*
2170          * $ cat /sys/dev/block/253:3/dm/name
2171          * mpatha
2172          */
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) {
2176                         return NULL;
2177                 }
2178
2179                 if (!get_sysfs_value(path, namebuf, sizeof(namebuf), 0))
2180                         return NULL;
2181
2182                 if (dm_snprintf(devname, sizeof(devname), "/dev/mapper/%s", namebuf) < 0) {
2183                         devname[0] = '\0';
2184                         stack;
2185                 }
2186
2187                 if (devname[0]) {
2188                         log_debug("Found %s for %d:%d from sys dm", devname, major, minor);
2189                         return _strdup(devname);
2190                 }
2191                 return NULL;
2192         }
2193
2194         /*
2195          * /proc/partitions lists
2196          * major minor #blocks name
2197          */
2198
2199 try_partition:
2200         if (!(fp = fopen("/proc/partitions", "r")))
2201                 return NULL;
2202
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)
2205                         continue;
2206                 if (line_major != major)
2207                         continue;
2208                 if (line_minor != minor)
2209                         continue;
2210
2211                 if (dm_snprintf(devname, sizeof(devname), "/dev/%s", namebuf) < 0) {
2212                         devname[0] = '\0';
2213                         stack;
2214                 }
2215                 break;
2216         }
2217         fclose(fp);
2218
2219         if (devname[0]) {
2220                 log_debug("Found %s for %d:%d from proc", devname, major, minor);
2221                 return _strdup(devname);
2222         }
2223
2224         /*
2225          * If necessary, this could continue searching by stat'ing /dev entries.
2226          */
2227
2228         return NULL;
2229 }
2230
2231 int setup_devname_in_dev_cache(struct cmd_context *cmd, const char *devname)
2232 {
2233         struct stat buf;
2234
2235         if (stat(devname, &buf) < 0) {
2236                 log_error("Cannot access device %s.", devname);
2237                 return 0;
2238         }
2239
2240         if (!S_ISBLK(buf.st_mode)) {
2241                 log_error("Invaild device type %s.", devname);
2242                 return 0;
2243         }
2244
2245         if (!_insert_dev(devname, buf.st_rdev))
2246                 return_0;
2247
2248         if (!dm_hash_lookup(_cache.names, devname))
2249                 return_0;
2250
2251         return 1;
2252 }
2253
2254 int setup_devno_in_dev_cache(struct cmd_context *cmd, dev_t devno)
2255 {
2256         const char *devname;
2257
2258         if (!(devname = _get_devname_from_devno(cmd, devno)))
2259                 return_0;
2260
2261         return setup_devname_in_dev_cache(cmd, devname);
2262 }
2263
2264 struct device *setup_dev_in_dev_cache(struct cmd_context *cmd, dev_t devno, const char *devname)
2265 {
2266         struct device *dev;
2267         struct stat buf;
2268         int major = (int)MAJOR(devno);
2269         int minor = (int)MINOR(devno);
2270
2271         if (devname) {
2272                 if (stat(devname, &buf) < 0) {
2273                         log_error("Cannot access device %s for %d:%d.", devname, major, minor);
2274                         if (!devno)
2275                                 return_NULL;
2276                         if (!(devname = _get_devname_from_devno(cmd, devno))) {
2277                                 log_error("No device name found from %d:%d.", major, minor);
2278                                 return_NULL;
2279                         }
2280                         if (stat(devname, &buf) < 0) {
2281                                 log_error("Cannot access device %s from %d:%d.", devname, major, minor);
2282                                 return_NULL;
2283                         }
2284                 }
2285         } else {
2286                 if (!(devname = _get_devname_from_devno(cmd, devno))) {
2287                         log_error("No device name found from %d:%d.", major, minor);
2288                         return_NULL;
2289                 }
2290                 if (stat(devname, &buf) < 0) {
2291                         log_error("Cannot access device %s from %d:%d.", devname, major, minor);
2292                         return_NULL;
2293                 }
2294         }
2295
2296         if (!S_ISBLK(buf.st_mode)) {
2297                 log_error("Invaild device type %s.", devname);
2298                 return_NULL;
2299         }
2300
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);
2304         }
2305
2306         if (!_insert_dev(devname, buf.st_rdev))
2307                 return_NULL;
2308
2309         if (!(dev = (struct device *) dm_hash_lookup(_cache.names, devname))) {
2310                 log_error("Device lookup failed for %d:%d %s", major, minor, devname);
2311                 return_NULL;
2312         }
2313
2314         return dev;
2315 }