1 /* vi: set sw=4 ts=4: */
3 * mdev - Mini udev for busybox
5 * Copyright 2005 Rob Landley <rob@landley.net>
6 * Copyright 2005 Frank Sorenson <frank@tuxrocks.com>
8 * Licensed under GPL version 2, see file LICENSE in this tarball for details.
13 /* "mdev -s" scans /sys/class/xxx, looking for directories which have dev
14 * file (it is of the form "M:m\n"). Example: /sys/class/tty/tty0/dev
15 * contains "4:0\n". Directory name is taken as device name, path component
16 * directly after /sys/class/ as subsystem. In this example, "tty0" and "tty".
17 * Then mdev creates the /dev/device_name node.
19 * mdev w/o parameters is called as hotplug helper. It takes device
20 * and subsystem names from $DEVPATH and $SUBSYSTEM, extracts
21 * maj,min from "/sys/$DEVPATH/dev" and also examines
22 * $ACTION ("add"/"delete") and $FIRMWARE.
24 * If action is "add", mdev creates /dev/device_name similarly to mdev -s.
25 * (todo: explain "delete" and $FIRMWARE)
27 * If /etc/mdev.conf exists, it may modify /dev/device_name's properties.
28 * /etc/mdev.conf file format:
30 * [-][subsystem/]device user:grp mode [>|=path] [@|$|*command args...]
31 * [-]@maj,min[-min2] user:grp mode [>|=path] [@|$|*command args...]
33 * The device name or "subsystem/device" combo is matched against 1st field
34 * (which is a regex), or maj,min is matched against 1st field.
36 * Leading minus in 1st field means "don't stop on this line", otherwise
37 * search is stopped after the matching line is encountered.
39 * When line matches, the device node is created, chmod'ed and chown'ed.
40 * Then it moved to path, and if >path, a symlink to moved node is created
42 * =loop/ - moves to /dev/loop
43 * >disk/sda%1 - moves to /dev/disk/sdaN, makes /dev/sdaN a symlink
44 * Then "command args" is executed (via sh -c 'command args').
45 * @:execute on creation, $:on deletion, *:on both.
49 int root_major, root_minor;
52 #define G (*(struct globals*)&bb_common_bufsiz1)
53 #define root_major (G.root_major)
54 #define root_minor (G.root_minor)
55 #define subsystem (G.subsystem)
57 /* Prevent infinite loops in /sys symlinks */
58 #define MAX_SYSFS_DEPTH 3
60 /* We use additional 64+ bytes in make_device() */
61 #define SCRATCH_SIZE 80
63 #if ENABLE_FEATURE_MDEV_RENAME
64 /* Builds an alias path.
65 * This function potentionally reallocates the alias parameter.
67 static char *build_alias(char *alias, const char *device_name)
71 /* ">bar/": rename to bar/device_name */
72 /* ">bar[/]baz": rename to bar[/]baz */
73 dest = strrchr(alias, '/');
74 if (dest) { /* ">bar/[baz]" ? */
75 *dest = '\0'; /* mkdir bar */
76 bb_make_directory(alias, 0755, FILEUTILS_RECUR);
78 if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
80 alias = concat_path_file(alias, device_name);
89 /* mknod in /dev based on a path like "/sys/block/hda/hda1" */
90 /* NB: "mdev -s" may call us many times, do not leak memory/fds! */
91 static void make_device(char *path, int delete)
93 #if ENABLE_FEATURE_MDEV_CONF
96 const char *device_name;
97 int major, minor, type, len;
99 char *dev_maj_min = path + strlen(path);
101 /* Force the configuration file settings exactly. */
104 /* Try to read major/minor string. Note that the kernel puts \n after
105 * the data, so we don't need to worry about null terminating the string
106 * because sscanf() will stop at the first nondigit, which \n is.
107 * We also depend on path having writeable space after it.
111 strcpy(dev_maj_min, "/dev");
112 len = open_read_close(path, dev_maj_min + 1, 64);
113 *dev_maj_min++ = '\0';
115 if (!ENABLE_FEATURE_MDEV_EXEC)
117 /* no "dev" file, so just try to run script */
119 } else if (sscanf(dev_maj_min, "%u:%u", &major, &minor) != 2) {
124 /* Determine device name, type, major and minor */
125 device_name = bb_basename(path);
126 /* http://kernel.org/doc/pending/hotplug.txt says that only
127 * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
128 * But since 2.6.25 block devices are also in /sys/class/block,
129 * we use strstr("/block/") to forestall future surprises. */
131 if (strstr(path, "/block/"))
134 /* Make path point to "subsystem/device_name" */
135 if (path[5] == 'b') /* legacy /sys/block? */
136 path += sizeof("/sys/") - 1;
138 path += sizeof("/sys/class/") - 1;
140 #if !ENABLE_FEATURE_MDEV_CONF
143 /* If we have config file, look up user settings */
144 parser = config_open2("/etc/mdev.conf", fopen_for_read);
146 regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
149 struct bb_uidgid_t ugid;
151 # if ENABLE_FEATURE_MDEV_EXEC
152 char *command = NULL;
154 # if ENABLE_FEATURE_MDEV_RENAME
156 char aliaslink = aliaslink; /* for compiler */
158 /* Defaults in case we won't match any line */
159 ugid.uid = ugid.gid = 0;
163 if (!config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL)) {
164 /* End of file, create dev node with default params */
169 keep_matching = ('-' == val[0]);
170 val += keep_matching; /* swallow leading dash */
172 /* Match against either "subsystem/device_name"
173 * or "device_name" alone */
174 name = strchr(val, '/') ? path : (char *) device_name;
176 /* Fields: regex uid:gid mode [alias] [cmd] */
178 /* 1st field: @<numeric maj,min>... */
180 /* @major,minor[-last] */
181 /* (useful when name is ambiguous:
182 * "/sys/class/usb/lp0" and
183 * "/sys/class/printer/lp0") */
184 int cmaj, cmin0, cmin1, sc;
186 continue; /* no dev, no match */
187 sc = sscanf(val, "@%u,%u-%u", &cmaj, &cmin0, &cmin1);
188 if (sc < 1 || major != cmaj
189 || (sc == 2 && minor != cmin0)
190 || (sc == 3 && (minor < cmin0 || minor > cmin1))
192 continue; /* this line doesn't match */
194 } else { /* ... or regex to match device name */
199 xregcomp(&match, val, REG_EXTENDED);
200 result = regexec(&match, name, ARRAY_SIZE(off), off, 0);
203 //bb_error_msg("matches:");
204 //for (int i = 0; i < ARRAY_SIZE(off); i++) {
205 // if (off[i].rm_so < 0) continue;
206 // bb_error_msg("match %d: '%.*s'\n", i,
207 // (int)(off[i].rm_eo - off[i].rm_so),
208 // device_name + off[i].rm_so);
211 /* If not this device, skip rest of line */
212 /* (regexec returns whole pattern as "range" 0) */
213 if (result || off[0].rm_so
214 || ((int)off[0].rm_eo != (int)strlen(name))
216 continue; /* this line doesn't match */
220 /* This line matches: stop parsing the file after parsing
221 * the rest of fields unless keep_matching == 1 */
223 /* 2nd field: uid:gid - device ownership */
224 parse_chown_usergroup_or_die(&ugid, tokens[1]);
226 /* 3rd field: mode - device permissions */
227 mode = strtoul(tokens[2], NULL, 8);
230 /* 4th field (opt): >|=alias */
231 # if ENABLE_FEATURE_MDEV_RENAME
235 if (aliaslink == '>' || aliaslink == '=') {
237 # if ENABLE_FEATURE_MDEV_RENAME_REGEXP
242 s = strchrnul(val, ' ');
243 st = strchrnul(val, '\t');
246 val = (s[0] && s[1]) ? s+1 : NULL;
249 # if ENABLE_FEATURE_MDEV_RENAME_REGEXP
250 /* substitute %1..9 with off[1..9], if any */
257 p = alias = xzalloc(strlen(a) + n * strlen(name));
263 if (i <= 9 && off[i].rm_so >= 0) {
264 n = off[i].rm_eo - off[i].rm_so;
265 strncpy(p, name + off[i].rm_so, n);
274 alias = xstrdup(a + 1);
277 # endif /* ENABLE_FEATURE_MDEV_RENAME */
279 # if ENABLE_FEATURE_MDEV_EXEC
280 /* The rest (opt): @|$|*command */
284 const char *s = "@$*";
285 const char *s2 = strchr(s, val[0]);
288 bb_error_msg_and_die("bad line %u", parser->lineno);
290 /* Correlate the position in the "@$*" with the delete
291 * step so that we get the proper behavior:
292 * @cmd: run on create
293 * $cmd: run on delete
296 if ((s2 - s + 1) /*1/2/3*/ & /*1/2*/ (1 + delete)) {
297 command = xstrdup(val + 1);
301 /* End of field parsing */
303 #endif /* ENABLE_FEATURE_MDEV_CONF */
305 /* "Execute" the line we found */
307 if (!delete && major >= 0) {
308 if (ENABLE_FEATURE_MDEV_RENAME)
310 if (mknod(device_name, mode | type, makedev(major, minor)) && errno != EEXIST)
311 bb_perror_msg_and_die("mknod %s", device_name);
312 if (major == root_major && minor == root_minor)
313 symlink(device_name, "root");
314 #if ENABLE_FEATURE_MDEV_CONF
315 chmod(device_name, mode);
316 chown(device_name, ugid.uid, ugid.gid);
317 # if ENABLE_FEATURE_MDEV_RENAME
319 alias = build_alias(alias, device_name);
320 /* move the device, and optionally
321 * make a symlink to moved device node */
322 if (rename(device_name, alias) == 0 && aliaslink == '>')
323 symlink(alias, device_name);
329 #if ENABLE_FEATURE_MDEV_EXEC
331 /* setenv will leak memory, use putenv/unsetenv/free */
332 char *s = xasprintf("%s=%s", "MDEV", device_name);
333 char *s1 = xasprintf("%s=%s", "SUBSYSTEM", subsystem);
336 if (system(command) == -1)
337 bb_perror_msg_and_die("can't run '%s'", command);
338 unsetenv("SUBSYSTEM");
347 /* At creation time, device might have been moved
348 * and a symlink might have been created. Undo that. */
349 #if ENABLE_FEATURE_MDEV_RENAME
351 alias = build_alias(alias, device_name);
358 #if ENABLE_FEATURE_MDEV_CONF
359 /* We found matching line.
360 * Stop unless it was prefixed with '-' */
363 } /* end of "while line is read from /etc/mdev.conf" */
365 config_close(parser);
366 #endif /* ENABLE_FEATURE_MDEV_CONF */
369 /* File callback for /sys/ traversal */
370 static int FAST_FUNC fileAction(const char *fileName,
371 struct stat *statbuf UNUSED_PARAM,
373 int depth UNUSED_PARAM)
375 size_t len = strlen(fileName) - 4; /* can't underflow */
376 char *scratch = userData;
378 /* len check is for paranoid reasons */
379 if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
382 strcpy(scratch, fileName);
384 make_device(scratch, 0);
389 /* Directory callback for /sys/ traversal */
390 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
391 struct stat *statbuf UNUSED_PARAM,
392 void *userData UNUSED_PARAM,
395 /* Extract device subsystem -- the name of the directory
396 * under /sys/class/ */
399 subsystem = strrchr(fileName, '/');
401 subsystem = xstrdup(subsystem + 1);
404 return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
407 /* For the full gory details, see linux/Documentation/firmware_class/README
409 * Firmware loading works like this:
410 * - kernel sets FIRMWARE env var
411 * - userspace checks /lib/firmware/$FIRMWARE
412 * - userspace waits for /sys/$DEVPATH/loading to appear
413 * - userspace writes "1" to /sys/$DEVPATH/loading
414 * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
415 * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
416 * - kernel loads firmware into device
418 static void load_firmware(const char *const firmware, const char *const sysfs_path)
421 int firmware_fd, loading_fd, data_fd;
423 /* check for /lib/firmware/$FIRMWARE */
424 xchdir("/lib/firmware");
425 firmware_fd = xopen(firmware, O_RDONLY);
427 /* in case we goto out ... */
430 /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
432 for (cnt = 0; cnt < 30; ++cnt) {
433 loading_fd = open("loading", O_WRONLY);
434 if (loading_fd != -1)
441 /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
442 if (full_write(loading_fd, "1", 1) != 1)
445 /* load firmware into /sys/$DEVPATH/data */
446 data_fd = open("data", O_WRONLY);
449 cnt = bb_copyfd_eof(firmware_fd, data_fd);
451 /* tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading" */
453 full_write(loading_fd, "0", 1);
455 full_write(loading_fd, "-1", 2);
458 if (ENABLE_FEATURE_CLEAN_UP) {
465 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
466 int mdev_main(int argc UNUSED_PARAM, char **argv)
468 RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
470 /* We can be called as hotplug helper */
471 /* Kernel cannot provide suitable stdio fds for us, do it ourself */
476 /* Replace LOGFILE by other file or device name if you need */
477 #define LOGFILE "/dev/console"
478 /* Just making sure fd 0 is not closed,
479 * we don't really intend to read from it */
480 xmove_fd(xopen("/", O_RDONLY), STDIN_FILENO);
481 xmove_fd(xopen(LOGFILE, O_WRONLY|O_APPEND), STDOUT_FILENO);
482 xmove_fd(xopen(LOGFILE, O_WRONLY|O_APPEND), STDERR_FILENO);
487 if (argv[1] && strcmp(argv[1], "-s") == 0) {
494 root_major = major(st.st_dev);
495 root_minor = minor(st.st_dev);
497 /* ACTION_FOLLOWLINKS is needed since in newer kernels
498 * /sys/block/loop* (for example) are symlinks to dirs,
499 * not real directories.
500 * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
501 * but we can't enforce that on users)
503 if (access("/sys/class/block", F_OK) != 0) {
504 /* Scan obsolete /sys/block only if /sys/class/block
505 * doesn't exist. Otherwise we'll have dupes.
506 * Also, do not complain if it doesn't exist.
507 * Some people configure kernel to have no blockdevs.
509 recursive_action("/sys/block",
510 ACTION_RECURSE | ACTION_FOLLOWLINKS | ACTION_QUIET,
511 fileAction, dirAction, temp, 0);
513 recursive_action("/sys/class",
514 ACTION_RECURSE | ACTION_FOLLOWLINKS,
515 fileAction, dirAction, temp, 0);
523 * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
524 * ACTION can be "add" or "remove"
525 * DEVPATH is like "/block/sda" or "/class/input/mice"
527 action = getenv("ACTION");
528 env_path = getenv("DEVPATH");
529 subsystem = getenv("SUBSYSTEM");
530 if (!action || !env_path /*|| !subsystem*/)
532 fw = getenv("FIRMWARE");
534 /* If it exists, does /dev/mdev.seq match $SEQNUM?
535 * If it does not match, earlier mdev is running
536 * in parallel, and we need to wait */
537 seq = getenv("SEQNUM");
539 int timeout = 2000 / 32; /* 2000 msec */
542 char seqbuf[sizeof(int)*3 + 2];
544 seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf-1));
549 seqbuf[seqlen] = '\0';
550 if (seqbuf[0] == '\n' /* seed file? */
551 || strcmp(seq, seqbuf) == 0 /* correct idx? */
559 snprintf(temp, PATH_MAX, "/sys%s", env_path);
560 if (strcmp(action, "remove") == 0) {
561 /* Ignoring "remove firmware". It was reported
562 * to happen and to cause erroneous deletion
563 * of device nodes. */
565 make_device(temp, 1);
567 else if (strcmp(action, "add") == 0) {
568 make_device(temp, 0);
569 if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
571 load_firmware(fw, temp);
576 xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
580 if (ENABLE_FEATURE_CLEAN_UP)
581 RELEASE_CONFIG_BUFFER(temp);