2 * finddev.c -- this routine attempts to find a particular device in
5 * Copyright (C) 2000 Theodore Ts'o.
8 * This file may be redistributed under the terms of the GNU Public
21 #include <sys/types.h>
31 #include <sys/mkdev.h>
39 struct dir_list *next;
43 * This function adds an entry to the directory list
45 static void add_to_dirlist(const char *name, struct dir_list **list)
49 dp = malloc(sizeof(struct dir_list));
52 dp->name = malloc(strlen(name)+1);
57 strcpy(dp->name, name);
63 * This function frees a directory list
65 static void free_dirlist(struct dir_list **list)
67 struct dir_list *dp, *next;
69 for (dp = *list; dp; dp = next) {
77 static int scan_dir(char *dirname, dev_t device, struct dir_list **list,
86 dirlen = strlen(dirname);
87 if ((dir = opendir(dirname)) == NULL)
91 if (dirlen + strlen(dp->d_name) + 2 >= sizeof(path))
93 if (dp->d_name[0] == '.' &&
94 ((dp->d_name[1] == 0) ||
95 ((dp->d_name[1] == '.') && (dp->d_name[2] == 0))))
97 sprintf(path, "%s/%s", dirname, dp->d_name);
98 if (stat(path, &st) < 0)
100 if (S_ISDIR(st.st_mode))
101 add_to_dirlist(path, list);
102 if (S_ISBLK(st.st_mode) && st.st_rdev == device) {
103 cp = malloc(strlen(path)+1);
121 * This function finds the pathname to a block device with a given
122 * device number. It returns a pointer to allocated memory to the
123 * pathname on success, and NULL on failure.
125 char *ext2fs_find_block_device(dev_t device)
127 struct dir_list *list = 0, *new_list = 0;
128 struct dir_list *current;
132 * Add the starting directories to search...
134 add_to_dirlist("/devices", &list);
135 add_to_dirlist("/devfs", &list);
136 add_to_dirlist("/dev", &list);
142 printf("Scanning directory %s\n", current->name);
144 scan_dir(current->name, device, &new_list, &ret_path);
150 * If we're done checking at this level, descend to
151 * the next level of subdirectories. (breadth-first)
159 free_dirlist(&new_list);
165 int main(int argc, char** argv)
170 const char *errmsg = "Couldn't parse %s: %s\n";
172 if ((argc != 2) && (argc != 3)) {
173 fprintf(stderr, "Usage: %s device_number\n", argv[0]);
174 fprintf(stderr, "\t: %s major minor\n", argv[0]);
178 device = strtoul(argv[1], &tmp, 0);
180 fprintf(stderr, errmsg, "device number", argv[1]);
184 major = strtoul(argv[1], &tmp, 0);
186 fprintf(stderr, errmsg, "major number", argv[1]);
189 minor = strtoul(argv[2], &tmp, 0);
191 fprintf(stderr, errmsg, "minor number", argv[2]);
194 device = makedev(major, minor);
195 printf("Looking for device 0x%04x (%d:%d)\n", device,
198 devname = ext2fs_find_block_device(device);
200 printf("Found device! %s\n", devname);
203 printf("Couldn't find device.\n");