1 /* vi: set sw=4 ts=4: */
3 * finddev.c -- this routine attempts to find a particular device in
6 * Copyright (C) 2000 Theodore Ts'o.
9 * This file may be redistributed under the terms of the GNU Public
21 #ifdef HAVE_SYS_TYPES_H
22 #include <sys/types.h>
24 #ifdef HAVE_SYS_STAT_H
31 #ifdef HAVE_SYS_MKDEV_H
32 #include <sys/mkdev.h>
40 struct dir_list *next;
44 * This function adds an entry to the directory list
46 static void add_to_dirlist(const char *name, struct dir_list **list)
50 dp = xmalloc(sizeof(struct dir_list));
51 dp->name = xmalloc(strlen(name)+1);
52 strcpy(dp->name, name);
58 * This function frees a directory list
60 static void free_dirlist(struct dir_list **list)
62 struct dir_list *dp, *next;
64 for (dp = *list; dp; dp = next) {
72 static int scan_dir(char *dir_name, dev_t device, struct dir_list **list,
81 dirlen = strlen(dir_name);
82 if ((dir = opendir(dir_name)) == NULL)
86 if (dirlen + strlen(dp->d_name) + 2 >= sizeof(path))
88 if (dp->d_name[0] == '.' &&
89 ((dp->d_name[1] == 0) ||
90 ((dp->d_name[1] == '.') && (dp->d_name[2] == 0))))
92 sprintf(path, "%s/%s", dir_name, dp->d_name);
93 if (stat(path, &st) < 0)
95 if (S_ISDIR(st.st_mode))
96 add_to_dirlist(path, list);
97 if (S_ISBLK(st.st_mode) && st.st_rdev == device) {
98 cp = xmalloc(strlen(path)+1);
112 * This function finds the pathname to a block device with a given
113 * device number. It returns a pointer to allocated memory to the
114 * pathname on success, and NULL on failure.
116 char *ext2fs_find_block_device(dev_t device)
118 struct dir_list *list = 0, *new_list = 0;
119 struct dir_list *current;
123 * Add the starting directories to search...
125 add_to_dirlist("/devices", &list);
126 add_to_dirlist("/devfs", &list);
127 add_to_dirlist("/dev", &list);
133 printf("Scanning directory %s\n", current->name);
135 scan_dir(current->name, device, &new_list, &ret_path);
141 * If we're done checking at this level, descend to
142 * the next level of subdirectories. (breadth-first)
150 free_dirlist(&new_list);
156 int main(int argc, char** argv)
161 const char *errmsg = "Cannot parse %s: %s\n";
163 if ((argc != 2) && (argc != 3)) {
164 fprintf(stderr, "Usage: %s device_number\n", argv[0]);
165 fprintf(stderr, "\t: %s major minor\n", argv[0]);
169 device = strtoul(argv[1], &tmp, 0);
171 fprintf(stderr, errmsg, "device number", argv[1]);
175 major = strtoul(argv[1], &tmp, 0);
177 fprintf(stderr, errmsg, "major number", argv[1]);
180 minor = strtoul(argv[2], &tmp, 0);
182 fprintf(stderr, errmsg, "minor number", argv[2]);
185 device = makedev(major, minor);
186 printf("Looking for device 0x%04x (%d:%d)\n", device,
189 devname = ext2fs_find_block_device(device);
191 printf("Found device! %s\n", devname);
194 printf("Cannot find device.\n");