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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
#include "dev-cache.h"
18
#include "lvm-types.h"
21
#include "filter-persistent.h"
22
#include "toolcontext.h"
25
#include <sys/param.h>
29
struct btree_iter *current;
30
struct dev_filter *filter;
40
struct dm_hash_table *names;
41
struct btree *devices;
42
struct dm_regex *preferred_names_matcher;
51
#define _zalloc(x) dm_pool_zalloc(_cache.mem, (x))
52
#define _free(x) dm_pool_free(_cache.mem, (x))
53
#define _strdup(x) dm_pool_strdup(_cache.mem, (x))
55
static int _insert(const char *path, int rec, int check_with_udev_db);
57
/* Setup non-zero members of passed zeroed 'struct device' */
58
static void _dev_init(struct device *dev, int max_error_count)
63
dev->max_error_count = max_error_count;
65
dm_list_init(&dev->aliases);
66
dm_list_init(&dev->open_list);
69
struct device *dev_create_file(const char *filename, struct device *dev,
70
struct str_list *alias, int use_malloc)
76
if (!(dev = dm_zalloc(sizeof(*dev)))) {
77
log_error("struct device allocation failed");
80
if (!(alias = dm_zalloc(sizeof(*alias)))) {
81
log_error("struct str_list allocation failed");
85
if (!(alias->str = dm_strdup(filename))) {
86
log_error("filename strdup failed");
92
if (!(dev = _zalloc(sizeof(*dev)))) {
93
log_error("struct device allocation failed");
96
if (!(alias = _zalloc(sizeof(*alias)))) {
97
log_error("struct str_list allocation failed");
101
if (!(alias->str = _strdup(filename))) {
102
log_error("filename strdup failed");
106
} else if (!(alias->str = dm_strdup(filename))) {
107
log_error("filename strdup failed");
111
_dev_init(dev, NO_DEV_ERROR_COUNT_LIMIT);
112
dev->flags = DEV_REGULAR | ((use_malloc) ? DEV_ALLOCED : 0);
113
dm_list_add(&dev->aliases, &alias->list);
118
static struct device *_dev_create(dev_t d)
122
if (!(dev = _zalloc(sizeof(*dev)))) {
123
log_error("struct device allocation failed");
127
_dev_init(dev, dev_disable_after_error_count());
133
void dev_set_preferred_name(struct str_list *sl, struct device *dev)
136
* Don't interfere with ordering specified in config file.
138
if (_cache.preferred_names_matcher)
141
log_debug("%s: New preferred name", sl->str);
142
dm_list_del(&sl->list);
143
dm_list_add_h(&dev->aliases, &sl->list);
147
* Check whether path0 or path1 contains the subpath. The path that
148
* *does not* contain the subpath wins (return 0 or 1). If both paths
149
* contain the subpath, return -1. If none of them contains the subpath,
152
static int _builtin_preference(const char *path0, const char *path1,
153
size_t skip_prefix_count, const char *subpath)
158
subpath_len = strlen(subpath);
160
r0 = !strncmp(path0 + skip_prefix_count, subpath, subpath_len);
161
r1 = !strncmp(path1 + skip_prefix_count, subpath, subpath_len);
164
/* path0 does not have the subpath - it wins */
167
/* path1 does not have the subpath - it wins */
170
/* both of them have the subpath */
173
/* no path has the subpath */
177
static int _apply_builtin_path_preference_rules(const char *path0, const char *path1)
182
devdir_len = strlen(_cache.dev_dir);
184
if (!strncmp(path0, _cache.dev_dir, devdir_len) &&
185
!strncmp(path1, _cache.dev_dir, devdir_len)) {
187
* We're trying to achieve the ordering:
188
* /dev/block/ < /dev/dm-* < /dev/disk/ < /dev/mapper/ < anything else
191
/* Prefer any other path over /dev/block/ path. */
192
if ((r = _builtin_preference(path0, path1, devdir_len, "block/")) >= -1)
195
/* Prefer any other path over /dev/dm-* path. */
196
if ((r = _builtin_preference(path0, path1, devdir_len, "dm-")) >= -1)
199
/* Prefer any other path over /dev/disk/ path. */
200
if ((r = _builtin_preference(path0, path1, devdir_len, "disk/")) >= -1)
203
/* Prefer any other path over /dev/mapper/ path. */
204
if ((r = _builtin_preference(path0, path1, 0, dm_dir())) >= -1)
211
/* Return 1 if we prefer path1 else return 0 */
212
static int _compare_paths(const char *path0, const char *path1)
214
int slash0 = 0, slash1 = 0;
217
char p0[PATH_MAX], p1[PATH_MAX];
219
struct stat stat0, stat1;
223
* FIXME Better to compare patterns one-at-a-time against all names.
225
if (_cache.preferred_names_matcher) {
226
m0 = dm_regex_match(_cache.preferred_names_matcher, path0);
227
m1 = dm_regex_match(_cache.preferred_names_matcher, path1);
241
/* Apply built-in preference rules first. */
242
if ((r = _apply_builtin_path_preference_rules(path0, path1)) >= 0)
245
/* Return the path with fewer slashes */
246
for (p = path0; p++; p = (const char *) strchr(p, '/'))
249
for (p = path1; p++; p = (const char *) strchr(p, '/'))
257
strncpy(p0, path0, sizeof(p0) - 1);
258
p0[sizeof(p0) - 1] = '\0';
259
strncpy(p1, path1, sizeof(p1) - 1);
260
p1[sizeof(p1) - 1] = '\0';
265
* If we reach here, both paths are the same length.
266
* Now skip past identical path components.
268
while (*s0 && *s0 == *s1)
271
/* We prefer symlinks - they exist for a reason!
272
* So we prefer a shorter path before the first symlink in the name.
273
* FIXME Configuration option to invert this? */
275
s0 = strchr(s0, '/');
276
s1 = strchr(s1, '/');
281
if (lstat(p0, &stat0)) {
282
log_sys_very_verbose("lstat", p0);
285
if (lstat(p1, &stat1)) {
286
log_sys_very_verbose("lstat", p1);
289
if (S_ISLNK(stat0.st_mode) && !S_ISLNK(stat1.st_mode))
291
if (!S_ISLNK(stat0.st_mode) && S_ISLNK(stat1.st_mode))
299
/* ASCII comparison */
300
if (strcmp(path0, path1) < 0)
306
static int _add_alias(struct device *dev, const char *path)
308
struct str_list *sl = _zalloc(sizeof(*sl));
309
struct str_list *strl;
316
/* Is name already there? */
317
dm_list_iterate_items(strl, &dev->aliases) {
318
if (!strcmp(strl->str, path)) {
319
log_debug("%s: Already in device cache", path);
326
if (!dm_list_empty(&dev->aliases)) {
327
oldpath = dm_list_item(dev->aliases.n, struct str_list)->str;
328
prefer_old = _compare_paths(path, oldpath);
329
log_debug("%s: Aliased to %s in device cache%s",
330
path, oldpath, prefer_old ? "" : " (preferred name)");
333
log_debug("%s: Added to device cache", path);
336
dm_list_add(&dev->aliases, &sl->list);
338
dm_list_add_h(&dev->aliases, &sl->list);
344
* Either creates a new dev, or adds an alias to
347
static int _insert_dev(const char *path, dev_t d)
350
static dev_t loopfile_count = 0;
354
/* Generate pretend device numbers for loopfiles */
356
if (dm_hash_lookup(_cache.names, path))
358
d = ++loopfile_count;
362
/* is this device already registered ? */
363
if (!(dev = (struct device *) btree_lookup(_cache.devices,
365
/* create new device */
367
if (!(dev = dev_create_file(path, NULL, NULL, 0)))
369
} else if (!(dev = _dev_create(d)))
372
if (!(btree_insert(_cache.devices, (uint32_t) d, dev))) {
373
log_error("Couldn't insert device into binary tree.");
379
if (!(path_copy = dm_pool_strdup(_cache.mem, path))) {
380
log_error("Failed to duplicate path string.");
384
if (!loopfile && !_add_alias(dev, path_copy)) {
385
log_error("Couldn't add alias to dev cache.");
389
if (!dm_hash_insert(_cache.names, path_copy, dev)) {
390
log_error("Couldn't add name to hash in dev cache.");
397
static char *_join(const char *dir, const char *name)
399
size_t len = strlen(dir) + strlen(name) + 2;
400
char *r = dm_malloc(len);
402
snprintf(r, len, "%s/%s", dir, name);
408
* Get rid of extra slashes in the path string.
410
static void _collapse_slashes(char *str)
415
for (ptr = str; *ptr; ptr++) {
429
static int _insert_dir(const char *dir)
431
int n, dirent_count, r = 1;
432
struct dirent **dirent;
435
dirent_count = scandir(dir, &dirent, NULL, alphasort);
436
if (dirent_count > 0) {
437
for (n = 0; n < dirent_count; n++) {
438
if (dirent[n]->d_name[0] == '.') {
443
if (!(path = _join(dir, dirent[n]->d_name)))
446
_collapse_slashes(path);
447
r &= _insert(path, 1, 0);
458
static int _insert_file(const char *path)
462
if (stat(path, &info) < 0) {
463
log_sys_very_verbose("stat", path);
467
if (!S_ISREG(info.st_mode)) {
468
log_debug("%s: Not a regular file", path);
472
if (!_insert_dev(path, 0))
478
#ifdef UDEV_SYNC_SUPPORT
480
static int _device_in_udev_db(const dev_t d)
483
struct udev_device *udev_device;
485
if (!(udev = udev_get_library_context()))
488
if ((udev_device = udev_device_new_from_devnum(udev, 'b', d))) {
489
udev_device_unref(udev_device);
496
static int _insert_udev_dir(struct udev *udev, const char *dir)
498
struct udev_enumerate *udev_enum = NULL;
499
struct udev_list_entry *device_entry, *symlink_entry;
500
const char *node_name, *symlink_name;
501
struct udev_device *device;
504
if (!(udev_enum = udev_enumerate_new(udev)))
507
if (udev_enumerate_add_match_subsystem(udev_enum, "block") ||
508
udev_enumerate_scan_devices(udev_enum))
511
udev_list_entry_foreach(device_entry, udev_enumerate_get_list_entry(udev_enum)) {
512
if (!(device = udev_device_new_from_syspath(udev, udev_list_entry_get_name(device_entry)))) {
513
log_warn("WARNING: udev failed to return a device entry.");
517
if (!(node_name = udev_device_get_devnode(device)))
518
log_warn("WARNING: udev failed to return a device node.");
520
r &= _insert(node_name, 0, 0);
522
udev_list_entry_foreach(symlink_entry, udev_device_get_devlinks_list_entry(device)) {
523
if (!(symlink_name = udev_list_entry_get_name(symlink_entry)))
524
log_warn("WARNING: udev failed to return a symlink name.");
526
r &= _insert(symlink_name, 0, 0);
529
udev_device_unref(device);
532
udev_enumerate_unref(udev_enum);
536
log_error("Failed to enumerate udev device list.");
537
udev_enumerate_unref(udev_enum);
541
static void _insert_dirs(struct dm_list *dirs)
547
with_udev = obtain_device_list_from_udev() &&
548
(udev = udev_get_library_context());
550
dm_list_iterate_items(dl, &_cache.dirs) {
552
if (!_insert_udev_dir(udev, dl->dir))
553
log_debug("%s: Failed to insert devices from "
554
"udev-managed directory to device "
555
"cache fully", dl->dir);
557
else if (!_insert_dir(dl->dir))
558
log_debug("%s: Failed to insert devices to "
559
"device cache fully", dl->dir);
563
#else /* UDEV_SYNC_SUPPORT */
565
static int _device_in_udev_db(const dev_t d)
570
static void _insert_dirs(struct dm_list *dirs)
574
dm_list_iterate_items(dl, &_cache.dirs)
575
_insert_dir(dl->dir);
578
#endif /* UDEV_SYNC_SUPPORT */
580
static int _insert(const char *path, int rec, int check_with_udev_db)
585
if (stat(path, &info) < 0) {
586
log_sys_very_verbose("stat", path);
590
if (check_with_udev_db && !_device_in_udev_db(info.st_rdev)) {
591
log_very_verbose("%s: Not in udev db", path);
595
if (S_ISDIR(info.st_mode)) { /* add a directory */
596
/* check it's not a symbolic link */
597
if (lstat(path, &info) < 0) {
598
log_sys_very_verbose("lstat", path);
602
if (S_ISLNK(info.st_mode)) {
603
log_debug("%s: Symbolic link to directory", path);
608
r = _insert_dir(path);
610
} else { /* add a device */
611
if (!S_ISBLK(info.st_mode)) {
612
log_debug("%s: Not a block device", path);
616
if (!_insert_dev(path, info.st_rdev))
625
static void _full_scan(int dev_scan)
629
if (_cache.has_scanned && !dev_scan)
632
_insert_dirs(&_cache.dirs);
634
dm_list_iterate_items(dl, &_cache.files)
635
_insert_file(dl->dir);
637
_cache.has_scanned = 1;
638
init_full_scan_done(1);
641
int dev_cache_has_scanned(void)
643
return _cache.has_scanned;
646
void dev_cache_scan(int do_scan)
649
_cache.has_scanned = 1;
654
static int _init_preferred_names(struct cmd_context *cmd)
656
const struct dm_config_node *cn;
657
const struct dm_config_value *v;
658
struct dm_pool *scratch = NULL;
663
_cache.preferred_names_matcher = NULL;
665
if (!(cn = find_config_tree_node(cmd, "devices/preferred_names")) ||
666
cn->v->type == DM_CFG_EMPTY_ARRAY) {
667
log_very_verbose("devices/preferred_names not found in config file: "
668
"using built-in preferences");
672
for (v = cn->v; v; v = v->next) {
673
if (v->type != DM_CFG_STRING) {
674
log_error("preferred_names patterns must be enclosed in quotes");
681
if (!(scratch = dm_pool_create("preferred device name matcher", 1024)))
684
if (!(regex = dm_pool_alloc(scratch, sizeof(*regex) * count))) {
685
log_error("Failed to allocate preferred device name "
690
for (v = cn->v, i = count - 1; v; v = v->next, i--) {
691
if (!(regex[i] = dm_pool_strdup(scratch, v->v.str))) {
692
log_error("Failed to allocate a preferred device name "
698
if (!(_cache.preferred_names_matcher =
699
dm_regex_create(_cache.mem, regex, count))) {
700
log_error("Preferred device name pattern matcher creation failed.");
707
dm_pool_destroy(scratch);
712
int dev_cache_init(struct cmd_context *cmd)
715
_cache.has_scanned = 0;
717
if (!(_cache.mem = dm_pool_create("dev_cache", 10 * 1024)))
720
if (!(_cache.names = dm_hash_create(128))) {
721
dm_pool_destroy(_cache.mem);
726
if (!(_cache.devices = btree_create(_cache.mem))) {
727
log_error("Couldn't create binary tree for dev-cache.");
731
if (!(_cache.dev_dir = _strdup(cmd->dev_dir))) {
732
log_error("strdup dev_dir failed.");
736
dm_list_init(&_cache.dirs);
737
dm_list_init(&_cache.files);
739
if (!_init_preferred_names(cmd))
749
static void _check_closed(struct device *dev)
752
log_error("Device '%s' has been left open.", dev_name(dev));
755
static void _check_for_open_devices(void)
757
dm_hash_iter(_cache.names, (dm_hash_iterate_fn) _check_closed);
760
void dev_cache_exit(void)
763
_check_for_open_devices();
765
if (_cache.preferred_names_matcher)
766
_cache.preferred_names_matcher = NULL;
769
dm_pool_destroy(_cache.mem);
774
dm_hash_destroy(_cache.names);
778
_cache.devices = NULL;
779
_cache.has_scanned = 0;
780
dm_list_init(&_cache.dirs);
781
dm_list_init(&_cache.files);
784
int dev_cache_add_dir(const char *path)
789
if (stat(path, &st)) {
790
log_error("Ignoring %s: %s", path, strerror(errno));
795
if (!S_ISDIR(st.st_mode)) {
796
log_error("Ignoring %s: Not a directory", path);
800
if (!(dl = _zalloc(sizeof(*dl) + strlen(path) + 1))) {
801
log_error("dir_list allocation failed");
805
strcpy(dl->dir, path);
806
dm_list_add(&_cache.dirs, &dl->list);
810
int dev_cache_add_loopfile(const char *path)
815
if (stat(path, &st)) {
816
log_error("Ignoring %s: %s", path, strerror(errno));
821
if (!S_ISREG(st.st_mode)) {
822
log_error("Ignoring %s: Not a regular file", path);
826
if (!(dl = _zalloc(sizeof(*dl) + strlen(path) + 1))) {
827
log_error("dir_list allocation failed for file");
831
strcpy(dl->dir, path);
832
dm_list_add(&_cache.files, &dl->list);
836
/* Check cached device name is still valid before returning it */
837
/* This should be a rare occurrence */
838
/* set quiet if the cache is expected to be out-of-date */
839
/* FIXME Make rest of code pass/cache struct device instead of dev_name */
840
const char *dev_name_confirmed(struct device *dev, int quiet)
846
if ((dev->flags & DEV_REGULAR))
847
return dev_name(dev);
849
while ((r = stat(name = dm_list_item(dev->aliases.n,
850
struct str_list)->str, &buf)) ||
851
(buf.st_rdev != dev->dev)) {
854
log_sys_debug("stat", name);
856
log_sys_error("stat", name);
859
log_debug("Path %s no longer valid for device(%d,%d)",
860
name, (int) MAJOR(dev->dev),
861
(int) MINOR(dev->dev));
863
log_error("Path %s no longer valid for device(%d,%d)",
864
name, (int) MAJOR(dev->dev),
865
(int) MINOR(dev->dev));
867
/* Remove the incorrect hash entry */
868
dm_hash_remove(_cache.names, name);
870
/* Leave list alone if there isn't an alternative name */
871
/* so dev_name will always find something to return. */
872
/* Otherwise add the name to the correct device. */
873
if (dm_list_size(&dev->aliases) > 1) {
874
dm_list_del(dev->aliases.n);
876
_insert(name, 0, obtain_device_list_from_udev());
880
/* Scanning issues this inappropriately sometimes. */
881
log_debug("Aborting - please provide new pathname for what "
882
"used to be %s", name);
886
return dev_name(dev);
889
struct device *dev_cache_get(const char *name, struct dev_filter *f)
892
struct device *d = (struct device *) dm_hash_lookup(_cache.names, name);
894
if (d && (d->flags & DEV_REGULAR))
897
/* If the entry's wrong, remove it */
898
if (d && (stat(name, &buf) || (buf.st_rdev != d->dev))) {
899
dm_hash_remove(_cache.names, name);
904
_insert(name, 0, obtain_device_list_from_udev());
905
d = (struct device *) dm_hash_lookup(_cache.names, name);
908
d = (struct device *) dm_hash_lookup(_cache.names, name);
912
return (d && (!f || (d->flags & DEV_REGULAR) ||
913
f->passes_filter(f, d))) ? d : NULL;
916
static struct device *_dev_cache_seek_devt(dev_t dev)
918
struct device *d = NULL;
919
struct dm_hash_node *n = dm_hash_get_first(_cache.names);
921
d = dm_hash_get_data(_cache.names, n);
924
n = dm_hash_get_next(_cache.names, n);
930
* TODO This is very inefficient. We probably want a hash table indexed by
931
* major:minor for keys to speed up these lookups.
933
struct device *dev_cache_get_by_devt(dev_t dev, struct dev_filter *f)
935
struct device *d = _dev_cache_seek_devt(dev);
937
if (d && (d->flags & DEV_REGULAR))
942
d = _dev_cache_seek_devt(dev);
945
return (d && (!f || (d->flags & DEV_REGULAR) ||
946
f->passes_filter(f, d))) ? d : NULL;
949
struct dev_iter *dev_iter_create(struct dev_filter *f, int dev_scan)
951
struct dev_iter *di = dm_malloc(sizeof(*di));
954
log_error("dev_iter allocation failed");
958
if (dev_scan && !trust_cache()) {
959
/* Flag gets reset between each command */
960
if (!full_scan_done())
961
persistent_filter_wipe(f); /* Calls _full_scan(1) */
965
di->current = btree_first(_cache.devices);
967
di->filter->use_count++;
972
void dev_iter_destroy(struct dev_iter *iter)
974
iter->filter->use_count--;
978
static struct device *_iter_next(struct dev_iter *iter)
980
struct device *d = btree_get_data(iter->current);
981
iter->current = btree_next(iter->current);
985
struct device *dev_iter_get(struct dev_iter *iter)
987
while (iter->current) {
988
struct device *d = _iter_next(iter);
989
if (!iter->filter || (d->flags & DEV_REGULAR) ||
990
iter->filter->passes_filter(iter->filter, d))
997
void dev_reset_error_count(struct cmd_context *cmd)
999
struct dev_iter iter;
1001
if (!_cache.devices)
1004
iter.current = btree_first(_cache.devices);
1005
while (iter.current)
1006
_iter_next(&iter)->error_count = 0;
1009
int dev_fd(struct device *dev)
1014
const char *dev_name(const struct device *dev)
1016
return (dev) ? dm_list_item(dev->aliases.n, struct str_list)->str :