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 /* Builds an alias path.
64 * This function potentionally reallocates the alias parameter.
65 * Only used for ENABLE_FEATURE_MDEV_RENAME
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);
88 /* mknod in /dev based on a path like "/sys/block/hda/hda1" */
89 /* NB: "mdev -s" may call us many times, do not leak memory/fds! */
90 static void make_device(char *path, int delete)
93 int major, minor, type, len;
97 /* Try to read major/minor string. Note that the kernel puts \n after
98 * the data, so we don't need to worry about null terminating the string
99 * because sscanf() will stop at the first nondigit, which \n is.
100 * We also depend on path having writeable space after it.
104 char *dev_maj_min = path + strlen(path);
106 strcpy(dev_maj_min, "/dev");
107 len = open_read_close(path, dev_maj_min + 1, 64);
110 if (!ENABLE_FEATURE_MDEV_EXEC)
112 /* no "dev" file, but we can still run scripts
113 * based on device name */
114 } else if (sscanf(++dev_maj_min, "%u:%u", &major, &minor) != 2) {
119 /* Determine device name, type, major and minor */
120 device_name = (char*) bb_basename(path);
121 /* http://kernel.org/doc/pending/hotplug.txt says that only
122 * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
123 * But since 2.6.25 block devices are also in /sys/class/block,
124 * we use strstr("/block/") to forestall future surprises. */
126 if (strstr(path, "/block/"))
129 /* Make path point to "subsystem/device_name" */
130 if (path[5] == 'b') /* legacy /sys/block? */
131 path += sizeof("/sys/") - 1;
133 path += sizeof("/sys/class/") - 1;
135 /* If we have config file, look up user settings */
136 if (ENABLE_FEATURE_MDEV_CONF)
137 parser = config_open2("/etc/mdev.conf", fopen_for_read);
141 struct bb_uidgid_t ugid;
143 char *command = NULL;
145 char aliaslink = aliaslink; /* for compiler */
147 /* Defaults in case we won't match any line */
148 ugid.uid = ugid.gid = 0;
152 if (ENABLE_FEATURE_MDEV_CONF
153 && config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL)
157 regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
160 keep_matching = ('-' == val[0]);
161 val += keep_matching; /* swallow leading dash */
163 /* Match against either "subsystem/device_name"
164 * or "device_name" alone */
165 str_to_match = strchr(val, '/') ? path : device_name;
167 /* Fields: regex uid:gid mode [alias] [cmd] */
170 /* @major,minor[-minor2] */
171 /* (useful when name is ambiguous:
172 * "/sys/class/usb/lp0" and
173 * "/sys/class/printer/lp0") */
174 int cmaj, cmin0, cmin1, sc;
176 continue; /* no dev, no match */
177 sc = sscanf(val, "@%u,%u-%u", &cmaj, &cmin0, &cmin1);
178 if (sc < 1 || major != cmaj
179 || (sc == 2 && minor != cmin0)
180 || (sc == 3 && (minor < cmin0 || minor > cmin1))
182 continue; /* this line doesn't match */
187 /* regex to match an environment variable */
188 char *eq = strchr(++val, '=');
192 str_to_match = getenv(val);
195 str_to_match -= strlen(val) + 1;
198 /* else: regex to match [subsystem/]device_name */
204 xregcomp(&match, val, REG_EXTENDED);
205 result = regexec(&match, str_to_match, ARRAY_SIZE(off), off, 0);
207 //bb_error_msg("matches:");
208 //for (int i = 0; i < ARRAY_SIZE(off); i++) {
209 // if (off[i].rm_so < 0) continue;
210 // bb_error_msg("match %d: '%.*s'\n", i,
211 // (int)(off[i].rm_eo - off[i].rm_so),
212 // device_name + off[i].rm_so);
215 /* If no match, skip rest of line */
216 /* (regexec returns whole pattern as "range" 0) */
217 if (result || off[0].rm_so
218 || ((int)off[0].rm_eo != (int)strlen(str_to_match))
220 continue; /* this line doesn't match */
224 /* This line matches. Stop parsing after parsing
225 * the rest the line unless keep_matching == 1 */
227 /* 2nd field: uid:gid - device ownership */
228 parse_chown_usergroup_or_die(&ugid, tokens[1]);
230 /* 3rd field: mode - device permissions */
231 mode = strtoul(tokens[2], NULL, 8);
234 /* 4th field (opt): >|=alias */
236 if (ENABLE_FEATURE_MDEV_RENAME && val) {
238 if (aliaslink == '>' || aliaslink == '=') {
244 s = strchrnul(val, ' ');
245 st = strchrnul(val, '\t');
248 val = (s[0] && s[1]) ? s+1 : NULL;
251 if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
252 /* substitute %1..9 with off[1..9], if any */
259 p = alias = xzalloc(strlen(a) + n * strlen(str_to_match));
265 if (i <= 9 && off[i].rm_so >= 0) {
266 n = off[i].rm_eo - off[i].rm_so;
267 strncpy(p, str_to_match + off[i].rm_so, n);
276 alias = xstrdup(a + 1);
281 if (ENABLE_FEATURE_MDEV_EXEC && val) {
282 const char *s = "$@*";
283 const char *s2 = strchr(s, val[0]);
286 bb_error_msg_and_die("bad line %u", parser->lineno);
288 /* Are we running this command now?
289 * Run $cmd on delete, @cmd on create, *cmd on both
292 command = xstrdup(val + 1);
296 /* End of field parsing */
298 /* "Execute" the line we found */
300 if (!delete && major >= 0) {
301 if (ENABLE_FEATURE_MDEV_RENAME)
303 if (mknod(device_name, mode | type, makedev(major, minor)) && errno != EEXIST)
304 bb_perror_msg_and_die("mknod %s", device_name);
305 if (major == root_major && minor == root_minor)
306 symlink(device_name, "root");
307 if (ENABLE_FEATURE_MDEV_CONF) {
308 chmod(device_name, mode);
309 chown(device_name, ugid.uid, ugid.gid);
311 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
312 alias = build_alias(alias, device_name);
313 /* move the device, and optionally
314 * make a symlink to moved device node */
315 if (rename(device_name, alias) == 0 && aliaslink == '>')
316 symlink(alias, device_name);
321 if (ENABLE_FEATURE_MDEV_EXEC && command) {
322 /* setenv will leak memory, use putenv/unsetenv/free */
323 char *s = xasprintf("%s=%s", "MDEV", device_name);
324 char *s1 = xasprintf("%s=%s", "SUBSYSTEM", subsystem);
327 if (system(command) == -1)
328 bb_perror_msg_and_die("can't run '%s'", command);
329 unsetenv("SUBSYSTEM");
338 /* At creation time, device might have been moved
339 * and a symlink might have been created. Undo that. */
341 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
342 alias = build_alias(alias, device_name);
348 /* We found matching line.
349 * Stop unless it was prefixed with '-' */
350 if (ENABLE_FEATURE_MDEV_CONF && !keep_matching)
353 /* end of "while line is read from /etc/mdev.conf" */
354 } while (ENABLE_FEATURE_MDEV_CONF);
356 if (ENABLE_FEATURE_MDEV_CONF)
357 config_close(parser);
360 /* File callback for /sys/ traversal */
361 static int FAST_FUNC fileAction(const char *fileName,
362 struct stat *statbuf UNUSED_PARAM,
364 int depth UNUSED_PARAM)
366 size_t len = strlen(fileName) - 4; /* can't underflow */
367 char *scratch = userData;
369 /* len check is for paranoid reasons */
370 if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
373 strcpy(scratch, fileName);
375 make_device(scratch, 0);
380 /* Directory callback for /sys/ traversal */
381 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
382 struct stat *statbuf UNUSED_PARAM,
383 void *userData UNUSED_PARAM,
386 /* Extract device subsystem -- the name of the directory
387 * under /sys/class/ */
390 subsystem = strrchr(fileName, '/');
392 subsystem = xstrdup(subsystem + 1);
395 return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
398 /* For the full gory details, see linux/Documentation/firmware_class/README
400 * Firmware loading works like this:
401 * - kernel sets FIRMWARE env var
402 * - userspace checks /lib/firmware/$FIRMWARE
403 * - userspace waits for /sys/$DEVPATH/loading to appear
404 * - userspace writes "1" to /sys/$DEVPATH/loading
405 * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
406 * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
407 * - kernel loads firmware into device
409 static void load_firmware(const char *firmware, const char *sysfs_path)
412 int firmware_fd, loading_fd, data_fd;
414 /* check for /lib/firmware/$FIRMWARE */
415 xchdir("/lib/firmware");
416 firmware_fd = xopen(firmware, O_RDONLY);
418 /* in case we goto out ... */
421 /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
423 for (cnt = 0; cnt < 30; ++cnt) {
424 loading_fd = open("loading", O_WRONLY);
425 if (loading_fd != -1)
432 /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
433 if (full_write(loading_fd, "1", 1) != 1)
436 /* load firmware into /sys/$DEVPATH/data */
437 data_fd = open("data", O_WRONLY);
440 cnt = bb_copyfd_eof(firmware_fd, data_fd);
442 /* tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading" */
444 full_write(loading_fd, "0", 1);
446 full_write(loading_fd, "-1", 2);
449 if (ENABLE_FEATURE_CLEAN_UP) {
456 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
457 int mdev_main(int argc UNUSED_PARAM, char **argv)
459 RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
461 /* We can be called as hotplug helper */
462 /* Kernel cannot provide suitable stdio fds for us, do it ourself */
465 /* Force the configuration file settings exactly */
470 if (argv[1] && strcmp(argv[1], "-s") == 0) {
477 root_major = major(st.st_dev);
478 root_minor = minor(st.st_dev);
480 /* ACTION_FOLLOWLINKS is needed since in newer kernels
481 * /sys/block/loop* (for example) are symlinks to dirs,
482 * not real directories.
483 * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
484 * but we can't enforce that on users)
486 if (access("/sys/class/block", F_OK) != 0) {
487 /* Scan obsolete /sys/block only if /sys/class/block
488 * doesn't exist. Otherwise we'll have dupes.
489 * Also, do not complain if it doesn't exist.
490 * Some people configure kernel to have no blockdevs.
492 recursive_action("/sys/block",
493 ACTION_RECURSE | ACTION_FOLLOWLINKS | ACTION_QUIET,
494 fileAction, dirAction, temp, 0);
496 recursive_action("/sys/class",
497 ACTION_RECURSE | ACTION_FOLLOWLINKS,
498 fileAction, dirAction, temp, 0);
506 * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
507 * ACTION can be "add" or "remove"
508 * DEVPATH is like "/block/sda" or "/class/input/mice"
510 action = getenv("ACTION");
511 env_path = getenv("DEVPATH");
512 subsystem = getenv("SUBSYSTEM");
513 if (!action || !env_path /*|| !subsystem*/)
515 fw = getenv("FIRMWARE");
517 /* If it exists, does /dev/mdev.seq match $SEQNUM?
518 * If it does not match, earlier mdev is running
519 * in parallel, and we need to wait */
520 seq = getenv("SEQNUM");
522 int timeout = 2000 / 32; /* 2000 msec */
525 char seqbuf[sizeof(int)*3 + 2];
527 seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf-1));
532 seqbuf[seqlen] = '\0';
533 if (seqbuf[0] == '\n' /* seed file? */
534 || strcmp(seq, seqbuf) == 0 /* correct idx? */
542 snprintf(temp, PATH_MAX, "/sys%s", env_path);
543 if (strcmp(action, "remove") == 0) {
544 /* Ignoring "remove firmware". It was reported
545 * to happen and to cause erroneous deletion
546 * of device nodes. */
548 make_device(temp, 1);
550 else if (strcmp(action, "add") == 0) {
551 make_device(temp, 0);
552 if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
554 load_firmware(fw, temp);
559 xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
563 if (ENABLE_FEATURE_CLEAN_UP)
564 RELEASE_CONFIG_BUFFER(temp);