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.
18 * If /sys/class/.../dev file does not exist, mdev still may act
19 * on this device: see "@|$|*command args..." parameter in config file.
21 * mdev w/o parameters is called as hotplug helper. It takes device
22 * and subsystem names from $DEVPATH and $SUBSYSTEM, extracts
23 * maj,min from "/sys/$DEVPATH/dev" and also examines
24 * $ACTION ("add"/"delete") and $FIRMWARE.
26 * If action is "add", mdev creates /dev/device_name similarly to mdev -s.
27 * (todo: explain "delete" and $FIRMWARE)
29 * If /etc/mdev.conf exists, it may modify /dev/device_name's properties.
30 * /etc/mdev.conf file format:
32 * [-][subsystem/]device user:grp mode [>|=path] [@|$|*command args...]
33 * [-]@maj,min[-min2] user:grp mode [>|=path] [@|$|*command args...]
34 * [-]$envvar=val user:grp mode [>|=path] [@|$|*command args...]
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 * The device name or "subsystem/device" combo is matched against 1st field
40 * (which is a regex), or maj,min is matched against 1st field,
41 * or specified environment variable (as regex) is matched against 1st field.
43 * $envvar=val format is useful for loading modules for hot-plugged devices
44 * which do not have driver loaded yet. In this case /sys/class/.../dev
45 * does not exist, but $MODALIAS is set to needed module's name
46 * (actually, an alias to it) by kernel. This rule instructs mdev
47 * to load the module and exit:
48 * $MODALIAS=.* 0:0 660 @modprobe "$MODALIAS"
49 * The kernel will generate another hotplug event when /sys/class/.../dev
52 * When line matches, the device node is created, chmod'ed and chown'ed,
53 * moved to path, and if >path, a symlink to moved node is created,
54 * all this if /sys/class/.../dev exists.
56 * =loop/ - moves to /dev/loop
57 * >disk/sda%1 - moves to /dev/disk/sdaN, makes /dev/sdaN a symlink
59 * Then "command args..." is executed (via sh -c 'command args...').
60 * @:execute on creation, $:on deletion, *:on both.
61 * This happens regardless of /sys/class/.../dev existence.
65 int root_major, root_minor;
68 #define G (*(struct globals*)&bb_common_bufsiz1)
70 /* Prevent infinite loops in /sys symlinks */
71 #define MAX_SYSFS_DEPTH 3
73 /* We use additional 64+ bytes in make_device() */
74 #define SCRATCH_SIZE 80
76 /* Builds an alias path.
77 * This function potentionally reallocates the alias parameter.
78 * Only used for ENABLE_FEATURE_MDEV_RENAME
80 static char *build_alias(char *alias, const char *device_name)
84 /* ">bar/": rename to bar/device_name */
85 /* ">bar[/]baz": rename to bar[/]baz */
86 dest = strrchr(alias, '/');
87 if (dest) { /* ">bar/[baz]" ? */
88 *dest = '\0'; /* mkdir bar */
89 bb_make_directory(alias, 0755, FILEUTILS_RECUR);
91 if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
93 alias = concat_path_file(alias, device_name);
101 /* mknod in /dev based on a path like "/sys/block/hda/hda1"
102 * NB1: path parameter needs to have SCRATCH_SIZE scratch bytes
103 * after NUL, but we promise to not mangle (IOW: to restore if needed)
105 * NB2: "mdev -s" may call us many times, do not leak memory/fds!
107 static void make_device(char *path, int delete)
109 char *device_name, *subsystem_slash_devname;
110 int major, minor, type, len;
114 /* Try to read major/minor string. Note that the kernel puts \n after
115 * the data, so we don't need to worry about null terminating the string
116 * because sscanf() will stop at the first nondigit, which \n is.
117 * We also depend on path having writeable space after it.
121 char *dev_maj_min = path + strlen(path);
123 strcpy(dev_maj_min, "/dev");
124 len = open_read_close(path, dev_maj_min + 1, 64);
127 if (!ENABLE_FEATURE_MDEV_EXEC)
129 /* no "dev" file, but we can still run scripts
130 * based on device name */
131 } else if (sscanf(++dev_maj_min, "%u:%u", &major, &minor) != 2) {
136 /* Determine device name, type, major and minor */
137 device_name = (char*) bb_basename(path);
138 /* http://kernel.org/doc/pending/hotplug.txt says that only
139 * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
140 * But since 2.6.25 block devices are also in /sys/class/block.
141 * We use strstr("/block/") to forestall future surprises. */
143 if (strstr(path, "/block/") || (G.subsystem && strncmp(G.subsystem, "block", 5) == 0))
146 /* Make path point to "subsystem/device_name" */
147 subsystem_slash_devname = NULL;
148 /* Check for coldplug invocations first */
149 if (strncmp(path, "/sys/block/", 11) == 0) /* legacy case */
150 path += sizeof("/sys/") - 1;
151 else if (strncmp(path, "/sys/class/", 11) == 0)
152 path += sizeof("/sys/class/") - 1;
154 /* Example of a hotplug invocation:
156 * DEVPATH="/sys" + "/devices/virtual/mtd/mtd3/mtdblock3"
157 * ("/sys" is added by mdev_main)
158 * - path does not contain subsystem
160 subsystem_slash_devname = concat_path_file(G.subsystem, device_name);
161 path = subsystem_slash_devname;
164 /* If we have config file, look up user settings */
165 if (ENABLE_FEATURE_MDEV_CONF)
166 parser = config_open2("/etc/mdev.conf", fopen_for_read);
170 struct bb_uidgid_t ugid;
172 char *command = NULL;
174 char aliaslink = aliaslink; /* for compiler */
176 /* Defaults in case we won't match any line */
177 ugid.uid = ugid.gid = 0;
181 if (ENABLE_FEATURE_MDEV_CONF
182 && config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL)
186 regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
189 keep_matching = ('-' == val[0]);
190 val += keep_matching; /* swallow leading dash */
192 /* Match against either "subsystem/device_name"
193 * or "device_name" alone */
194 str_to_match = strchr(val, '/') ? path : device_name;
196 /* Fields: regex uid:gid mode [alias] [cmd] */
199 /* @major,minor[-minor2] */
200 /* (useful when name is ambiguous:
201 * "/sys/class/usb/lp0" and
202 * "/sys/class/printer/lp0") */
203 int cmaj, cmin0, cmin1, sc;
205 continue; /* no dev, no match */
206 sc = sscanf(val, "@%u,%u-%u", &cmaj, &cmin0, &cmin1);
207 if (sc < 1 || major != cmaj
208 || (sc == 2 && minor != cmin0)
209 || (sc == 3 && (minor < cmin0 || minor > cmin1))
211 continue; /* this line doesn't match */
216 /* regex to match an environment variable */
217 char *eq = strchr(++val, '=');
221 str_to_match = getenv(val);
224 str_to_match -= strlen(val) + 1;
227 /* else: regex to match [subsystem/]device_name */
233 xregcomp(&match, val, REG_EXTENDED);
234 result = regexec(&match, str_to_match, ARRAY_SIZE(off), off, 0);
236 //bb_error_msg("matches:");
237 //for (int i = 0; i < ARRAY_SIZE(off); i++) {
238 // if (off[i].rm_so < 0) continue;
239 // bb_error_msg("match %d: '%.*s'\n", i,
240 // (int)(off[i].rm_eo - off[i].rm_so),
241 // device_name + off[i].rm_so);
244 /* If no match, skip rest of line */
245 /* (regexec returns whole pattern as "range" 0) */
246 if (result || off[0].rm_so
247 || ((int)off[0].rm_eo != (int)strlen(str_to_match))
249 continue; /* this line doesn't match */
253 /* This line matches. Stop parsing after parsing
254 * the rest the line unless keep_matching == 1 */
256 /* 2nd field: uid:gid - device ownership */
257 if (get_uidgid(&ugid, tokens[1], 1) == 0)
258 bb_error_msg("unknown user/group %s on line %d", tokens[1], parser->lineno);
260 /* 3rd field: mode - device permissions */
261 /* mode = strtoul(tokens[2], NULL, 8); */
262 bb_parse_mode(tokens[2], &mode);
265 /* 4th field (opt): >|=alias */
267 if (ENABLE_FEATURE_MDEV_RENAME && val) {
269 if (aliaslink == '>' || aliaslink == '=') {
275 s = strchrnul(val, ' ');
276 st = strchrnul(val, '\t');
279 val = (s[0] && s[1]) ? s+1 : NULL;
282 if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
283 /* substitute %1..9 with off[1..9], if any */
290 p = alias = xzalloc(strlen(a) + n * strlen(str_to_match));
296 if (i <= 9 && off[i].rm_so >= 0) {
297 n = off[i].rm_eo - off[i].rm_so;
298 strncpy(p, str_to_match + off[i].rm_so, n);
307 alias = xstrdup(a + 1);
312 if (ENABLE_FEATURE_MDEV_EXEC && val) {
313 const char *s = "$@*";
314 const char *s2 = strchr(s, val[0]);
317 bb_error_msg("bad line %u", parser->lineno);
318 if (ENABLE_FEATURE_MDEV_RENAME)
323 /* Are we running this command now?
324 * Run $cmd on delete, @cmd on create, *cmd on both
327 command = xstrdup(val + 1);
331 /* End of field parsing */
333 /* "Execute" the line we found */
335 const char *node_name;
337 node_name = device_name;
338 if (ENABLE_FEATURE_MDEV_RENAME && alias)
339 node_name = alias = build_alias(alias, device_name);
341 if (!delete && major >= 0) {
342 if (mknod(node_name, mode | type, makedev(major, minor)) && errno != EEXIST)
343 bb_perror_msg("can't create %s", node_name);
344 if (major == G.root_major && minor == G.root_minor)
345 symlink(node_name, "root");
346 if (ENABLE_FEATURE_MDEV_CONF) {
347 chmod(node_name, mode);
348 chown(node_name, ugid.uid, ugid.gid);
350 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
351 if (aliaslink == '>')
352 symlink(node_name, device_name);
356 if (ENABLE_FEATURE_MDEV_EXEC && command) {
357 /* setenv will leak memory, use putenv/unsetenv/free */
358 char *s = xasprintf("%s=%s", "MDEV", node_name);
359 char *s1 = xasprintf("%s=%s", "SUBSYSTEM", G.subsystem);
362 if (system(command) == -1)
363 bb_perror_msg("can't run '%s'", command);
364 unsetenv("SUBSYSTEM");
372 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
373 if (aliaslink == '>')
379 if (ENABLE_FEATURE_MDEV_RENAME)
383 /* We found matching line.
384 * Stop unless it was prefixed with '-' */
385 if (ENABLE_FEATURE_MDEV_CONF && !keep_matching)
388 /* end of "while line is read from /etc/mdev.conf" */
389 } while (ENABLE_FEATURE_MDEV_CONF);
391 if (ENABLE_FEATURE_MDEV_CONF)
392 config_close(parser);
393 free(subsystem_slash_devname);
396 /* File callback for /sys/ traversal */
397 static int FAST_FUNC fileAction(const char *fileName,
398 struct stat *statbuf UNUSED_PARAM,
400 int depth UNUSED_PARAM)
402 size_t len = strlen(fileName) - 4; /* can't underflow */
403 char *scratch = userData;
405 /* len check is for paranoid reasons */
406 if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
409 strcpy(scratch, fileName);
411 make_device(scratch, /*delete:*/ 0);
416 /* Directory callback for /sys/ traversal */
417 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
418 struct stat *statbuf UNUSED_PARAM,
419 void *userData UNUSED_PARAM,
422 /* Extract device subsystem -- the name of the directory
423 * under /sys/class/ */
426 G.subsystem = strrchr(fileName, '/');
428 G.subsystem = xstrdup(G.subsystem + 1);
431 return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
434 /* For the full gory details, see linux/Documentation/firmware_class/README
436 * Firmware loading works like this:
437 * - kernel sets FIRMWARE env var
438 * - userspace checks /lib/firmware/$FIRMWARE
439 * - userspace waits for /sys/$DEVPATH/loading to appear
440 * - userspace writes "1" to /sys/$DEVPATH/loading
441 * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
442 * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
443 * - kernel loads firmware into device
445 static void load_firmware(const char *firmware, const char *sysfs_path)
448 int firmware_fd, loading_fd, data_fd;
450 /* check for /lib/firmware/$FIRMWARE */
451 xchdir("/lib/firmware");
452 firmware_fd = xopen(firmware, O_RDONLY);
454 /* in case we goto out ... */
457 /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
459 for (cnt = 0; cnt < 30; ++cnt) {
460 loading_fd = open("loading", O_WRONLY);
461 if (loading_fd != -1)
468 /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
469 if (full_write(loading_fd, "1", 1) != 1)
472 /* load firmware into /sys/$DEVPATH/data */
473 data_fd = open("data", O_WRONLY);
476 cnt = bb_copyfd_eof(firmware_fd, data_fd);
478 /* tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading" */
480 full_write(loading_fd, "0", 1);
482 full_write(loading_fd, "-1", 2);
485 if (ENABLE_FEATURE_CLEAN_UP) {
492 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
493 int mdev_main(int argc UNUSED_PARAM, char **argv)
495 RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
497 /* We can be called as hotplug helper */
498 /* Kernel cannot provide suitable stdio fds for us, do it ourself */
501 /* Force the configuration file settings exactly */
506 if (argv[1] && strcmp(argv[1], "-s") == 0) {
513 G.root_major = major(st.st_dev);
514 G.root_minor = minor(st.st_dev);
516 /* ACTION_FOLLOWLINKS is needed since in newer kernels
517 * /sys/block/loop* (for example) are symlinks to dirs,
518 * not real directories.
519 * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
520 * but we can't enforce that on users)
522 if (access("/sys/class/block", F_OK) != 0) {
523 /* Scan obsolete /sys/block only if /sys/class/block
524 * doesn't exist. Otherwise we'll have dupes.
525 * Also, do not complain if it doesn't exist.
526 * Some people configure kernel to have no blockdevs.
528 recursive_action("/sys/block",
529 ACTION_RECURSE | ACTION_FOLLOWLINKS | ACTION_QUIET,
530 fileAction, dirAction, temp, 0);
532 recursive_action("/sys/class",
533 ACTION_RECURSE | ACTION_FOLLOWLINKS,
534 fileAction, dirAction, temp, 0);
540 static const char keywords[] ALIGN1 = "remove\0add\0";
541 enum { OP_remove = 0, OP_add };
545 * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
546 * ACTION can be "add" or "remove"
547 * DEVPATH is like "/block/sda" or "/class/input/mice"
549 action = getenv("ACTION");
550 env_path = getenv("DEVPATH");
551 G.subsystem = getenv("SUBSYSTEM");
552 if (!action || !env_path /*|| !G.subsystem*/)
554 fw = getenv("FIRMWARE");
555 op = index_in_strings(keywords, action);
556 /* If it exists, does /dev/mdev.seq match $SEQNUM?
557 * If it does not match, earlier mdev is running
558 * in parallel, and we need to wait */
559 seq = getenv("SEQNUM");
561 int timeout = 2000 / 32; /* 2000 msec */
564 char seqbuf[sizeof(int)*3 + 2];
566 seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf-1));
571 seqbuf[seqlen] = '\0';
572 if (seqbuf[0] == '\n' /* seed file? */
573 || strcmp(seq, seqbuf) == 0 /* correct idx? */
581 snprintf(temp, PATH_MAX, "/sys%s", env_path);
582 if (op == OP_remove) {
583 /* Ignoring "remove firmware". It was reported
584 * to happen and to cause erroneous deletion
585 * of device nodes. */
587 make_device(temp, /*delete:*/ 1);
589 else if (op == OP_add) {
590 make_device(temp, /*delete:*/ 0);
591 if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
593 load_firmware(fw, temp);
598 xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
602 if (ENABLE_FEATURE_CLEAN_UP)
603 RELEASE_CONFIG_BUFFER(temp);