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)
69 #define root_major (G.root_major)
70 #define root_minor (G.root_minor)
71 #define subsystem (G.subsystem )
73 /* Prevent infinite loops in /sys symlinks */
74 #define MAX_SYSFS_DEPTH 3
76 /* We use additional 64+ bytes in make_device() */
77 #define SCRATCH_SIZE 80
79 /* Builds an alias path.
80 * This function potentionally reallocates the alias parameter.
81 * Only used for ENABLE_FEATURE_MDEV_RENAME
83 static char *build_alias(char *alias, const char *device_name)
87 /* ">bar/": rename to bar/device_name */
88 /* ">bar[/]baz": rename to bar[/]baz */
89 dest = strrchr(alias, '/');
90 if (dest) { /* ">bar/[baz]" ? */
91 *dest = '\0'; /* mkdir bar */
92 bb_make_directory(alias, 0755, FILEUTILS_RECUR);
94 if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
96 alias = concat_path_file(alias, device_name);
104 /* mknod in /dev based on a path like "/sys/block/hda/hda1" */
105 /* NB: "mdev -s" may call us many times, do not leak memory/fds! */
106 static void make_device(char *path, int delete)
109 int major, minor, type, len;
113 /* Try to read major/minor string. Note that the kernel puts \n after
114 * the data, so we don't need to worry about null terminating the string
115 * because sscanf() will stop at the first nondigit, which \n is.
116 * We also depend on path having writeable space after it.
120 char *dev_maj_min = path + strlen(path);
122 strcpy(dev_maj_min, "/dev");
123 len = open_read_close(path, dev_maj_min + 1, 64);
126 if (!ENABLE_FEATURE_MDEV_EXEC)
128 /* no "dev" file, but we can still run scripts
129 * based on device name */
130 } else if (sscanf(++dev_maj_min, "%u:%u", &major, &minor) != 2) {
135 /* Determine device name, type, major and minor */
136 device_name = (char*) bb_basename(path);
137 /* http://kernel.org/doc/pending/hotplug.txt says that only
138 * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
139 * But since 2.6.25 block devices are also in /sys/class/block,
140 * we use strstr("/block/") to forestall future surprises. */
142 if (strstr(path, "/block/"))
145 /* Make path point to "subsystem/device_name" */
146 if (path[5] == 'b') /* legacy /sys/block? */
147 path += sizeof("/sys/") - 1;
149 path += sizeof("/sys/class/") - 1;
151 /* If we have config file, look up user settings */
152 if (ENABLE_FEATURE_MDEV_CONF)
153 parser = config_open2("/etc/mdev.conf", fopen_for_read);
157 struct bb_uidgid_t ugid;
159 char *command = NULL;
161 char aliaslink = aliaslink; /* for compiler */
163 /* Defaults in case we won't match any line */
164 ugid.uid = ugid.gid = 0;
168 if (ENABLE_FEATURE_MDEV_CONF
169 && config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL)
173 regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
176 keep_matching = ('-' == val[0]);
177 val += keep_matching; /* swallow leading dash */
179 /* Match against either "subsystem/device_name"
180 * or "device_name" alone */
181 str_to_match = strchr(val, '/') ? path : device_name;
183 /* Fields: regex uid:gid mode [alias] [cmd] */
186 /* @major,minor[-minor2] */
187 /* (useful when name is ambiguous:
188 * "/sys/class/usb/lp0" and
189 * "/sys/class/printer/lp0") */
190 int cmaj, cmin0, cmin1, sc;
192 continue; /* no dev, no match */
193 sc = sscanf(val, "@%u,%u-%u", &cmaj, &cmin0, &cmin1);
194 if (sc < 1 || major != cmaj
195 || (sc == 2 && minor != cmin0)
196 || (sc == 3 && (minor < cmin0 || minor > cmin1))
198 continue; /* this line doesn't match */
203 /* regex to match an environment variable */
204 char *eq = strchr(++val, '=');
208 str_to_match = getenv(val);
211 str_to_match -= strlen(val) + 1;
214 /* else: regex to match [subsystem/]device_name */
220 xregcomp(&match, val, REG_EXTENDED);
221 result = regexec(&match, str_to_match, ARRAY_SIZE(off), off, 0);
223 //bb_error_msg("matches:");
224 //for (int i = 0; i < ARRAY_SIZE(off); i++) {
225 // if (off[i].rm_so < 0) continue;
226 // bb_error_msg("match %d: '%.*s'\n", i,
227 // (int)(off[i].rm_eo - off[i].rm_so),
228 // device_name + off[i].rm_so);
231 /* If no match, skip rest of line */
232 /* (regexec returns whole pattern as "range" 0) */
233 if (result || off[0].rm_so
234 || ((int)off[0].rm_eo != (int)strlen(str_to_match))
236 continue; /* this line doesn't match */
240 /* This line matches. Stop parsing after parsing
241 * the rest the line unless keep_matching == 1 */
243 /* 2nd field: uid:gid - device ownership */
244 parse_chown_usergroup_or_die(&ugid, tokens[1]);
246 /* 3rd field: mode - device permissions */
247 mode = strtoul(tokens[2], NULL, 8);
250 /* 4th field (opt): >|=alias */
252 if (ENABLE_FEATURE_MDEV_RENAME && val) {
254 if (aliaslink == '>' || aliaslink == '=') {
260 s = strchrnul(val, ' ');
261 st = strchrnul(val, '\t');
264 val = (s[0] && s[1]) ? s+1 : NULL;
267 if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
268 /* substitute %1..9 with off[1..9], if any */
275 p = alias = xzalloc(strlen(a) + n * strlen(str_to_match));
281 if (i <= 9 && off[i].rm_so >= 0) {
282 n = off[i].rm_eo - off[i].rm_so;
283 strncpy(p, str_to_match + off[i].rm_so, n);
292 alias = xstrdup(a + 1);
297 if (ENABLE_FEATURE_MDEV_EXEC && val) {
298 const char *s = "$@*";
299 const char *s2 = strchr(s, val[0]);
302 bb_error_msg_and_die("bad line %u", parser->lineno);
304 /* Are we running this command now?
305 * Run $cmd on delete, @cmd on create, *cmd on both
308 command = xstrdup(val + 1);
312 /* End of field parsing */
314 /* "Execute" the line we found */
316 if (!delete && major >= 0) {
317 if (ENABLE_FEATURE_MDEV_RENAME)
319 if (mknod(device_name, mode | type, makedev(major, minor)) && errno != EEXIST)
320 bb_perror_msg_and_die("mknod %s", device_name);
321 if (major == root_major && minor == root_minor)
322 symlink(device_name, "root");
323 if (ENABLE_FEATURE_MDEV_CONF) {
324 chmod(device_name, mode);
325 chown(device_name, ugid.uid, ugid.gid);
327 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
328 alias = build_alias(alias, device_name);
329 /* move the device, and optionally
330 * make a symlink to moved device node */
331 if (rename(device_name, alias) == 0 && aliaslink == '>')
332 symlink(alias, device_name);
337 if (ENABLE_FEATURE_MDEV_EXEC && command) {
338 /* setenv will leak memory, use putenv/unsetenv/free */
339 char *s = xasprintf("%s=%s", "MDEV", device_name);
340 char *s1 = xasprintf("%s=%s", "SUBSYSTEM", subsystem);
343 if (system(command) == -1)
344 bb_perror_msg_and_die("can't run '%s'", command);
345 unsetenv("SUBSYSTEM");
354 /* At creation time, device might have been moved
355 * and a symlink might have been created. Undo that. */
357 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
358 alias = build_alias(alias, device_name);
364 /* We found matching line.
365 * Stop unless it was prefixed with '-' */
366 if (ENABLE_FEATURE_MDEV_CONF && !keep_matching)
369 /* end of "while line is read from /etc/mdev.conf" */
370 } while (ENABLE_FEATURE_MDEV_CONF);
372 if (ENABLE_FEATURE_MDEV_CONF)
373 config_close(parser);
376 /* File callback for /sys/ traversal */
377 static int FAST_FUNC fileAction(const char *fileName,
378 struct stat *statbuf UNUSED_PARAM,
380 int depth UNUSED_PARAM)
382 size_t len = strlen(fileName) - 4; /* can't underflow */
383 char *scratch = userData;
385 /* len check is for paranoid reasons */
386 if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
389 strcpy(scratch, fileName);
391 make_device(scratch, 0);
396 /* Directory callback for /sys/ traversal */
397 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
398 struct stat *statbuf UNUSED_PARAM,
399 void *userData UNUSED_PARAM,
402 /* Extract device subsystem -- the name of the directory
403 * under /sys/class/ */
406 subsystem = strrchr(fileName, '/');
408 subsystem = xstrdup(subsystem + 1);
411 return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
414 /* For the full gory details, see linux/Documentation/firmware_class/README
416 * Firmware loading works like this:
417 * - kernel sets FIRMWARE env var
418 * - userspace checks /lib/firmware/$FIRMWARE
419 * - userspace waits for /sys/$DEVPATH/loading to appear
420 * - userspace writes "1" to /sys/$DEVPATH/loading
421 * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
422 * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
423 * - kernel loads firmware into device
425 static void load_firmware(const char *firmware, const char *sysfs_path)
428 int firmware_fd, loading_fd, data_fd;
430 /* check for /lib/firmware/$FIRMWARE */
431 xchdir("/lib/firmware");
432 firmware_fd = xopen(firmware, O_RDONLY);
434 /* in case we goto out ... */
437 /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
439 for (cnt = 0; cnt < 30; ++cnt) {
440 loading_fd = open("loading", O_WRONLY);
441 if (loading_fd != -1)
448 /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
449 if (full_write(loading_fd, "1", 1) != 1)
452 /* load firmware into /sys/$DEVPATH/data */
453 data_fd = open("data", O_WRONLY);
456 cnt = bb_copyfd_eof(firmware_fd, data_fd);
458 /* tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading" */
460 full_write(loading_fd, "0", 1);
462 full_write(loading_fd, "-1", 2);
465 if (ENABLE_FEATURE_CLEAN_UP) {
472 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
473 int mdev_main(int argc UNUSED_PARAM, char **argv)
475 RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
477 /* We can be called as hotplug helper */
478 /* Kernel cannot provide suitable stdio fds for us, do it ourself */
481 /* Force the configuration file settings exactly */
486 if (argv[1] && strcmp(argv[1], "-s") == 0) {
493 root_major = major(st.st_dev);
494 root_minor = minor(st.st_dev);
496 /* ACTION_FOLLOWLINKS is needed since in newer kernels
497 * /sys/block/loop* (for example) are symlinks to dirs,
498 * not real directories.
499 * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
500 * but we can't enforce that on users)
502 if (access("/sys/class/block", F_OK) != 0) {
503 /* Scan obsolete /sys/block only if /sys/class/block
504 * doesn't exist. Otherwise we'll have dupes.
505 * Also, do not complain if it doesn't exist.
506 * Some people configure kernel to have no blockdevs.
508 recursive_action("/sys/block",
509 ACTION_RECURSE | ACTION_FOLLOWLINKS | ACTION_QUIET,
510 fileAction, dirAction, temp, 0);
512 recursive_action("/sys/class",
513 ACTION_RECURSE | ACTION_FOLLOWLINKS,
514 fileAction, dirAction, temp, 0);
522 * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
523 * ACTION can be "add" or "remove"
524 * DEVPATH is like "/block/sda" or "/class/input/mice"
526 action = getenv("ACTION");
527 env_path = getenv("DEVPATH");
528 subsystem = getenv("SUBSYSTEM");
529 if (!action || !env_path /*|| !subsystem*/)
531 fw = getenv("FIRMWARE");
533 /* If it exists, does /dev/mdev.seq match $SEQNUM?
534 * If it does not match, earlier mdev is running
535 * in parallel, and we need to wait */
536 seq = getenv("SEQNUM");
538 int timeout = 2000 / 32; /* 2000 msec */
541 char seqbuf[sizeof(int)*3 + 2];
543 seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf-1));
548 seqbuf[seqlen] = '\0';
549 if (seqbuf[0] == '\n' /* seed file? */
550 || strcmp(seq, seqbuf) == 0 /* correct idx? */
558 snprintf(temp, PATH_MAX, "/sys%s", env_path);
559 if (strcmp(action, "remove") == 0) {
560 /* Ignoring "remove firmware". It was reported
561 * to happen and to cause erroneous deletion
562 * of device nodes. */
564 make_device(temp, 1);
566 else if (strcmp(action, "add") == 0) {
567 make_device(temp, 0);
568 if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
570 load_firmware(fw, temp);
575 xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
579 if (ENABLE_FEATURE_CLEAN_UP)
580 RELEASE_CONFIG_BUFFER(temp);