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)
92 const char *device_name;
93 int major, minor, type, len;
95 char *dev_maj_min = path + strlen(path);
98 /* Force the configuration file settings exactly. */
101 /* Try to read major/minor string. Note that the kernel puts \n after
102 * the data, so we don't need to worry about null terminating the string
103 * because sscanf() will stop at the first nondigit, which \n is.
104 * We also depend on path having writeable space after it.
108 strcpy(dev_maj_min, "/dev");
109 len = open_read_close(path, dev_maj_min + 1, 64);
110 *dev_maj_min++ = '\0';
112 if (!ENABLE_FEATURE_MDEV_EXEC)
114 /* no "dev" file, so just try to run script */
116 } else if (sscanf(dev_maj_min, "%u:%u", &major, &minor) != 2) {
121 /* Determine device name, type, major and minor */
122 device_name = bb_basename(path);
123 /* http://kernel.org/doc/pending/hotplug.txt says that only
124 * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
125 * But since 2.6.25 block devices are also in /sys/class/block,
126 * we use strstr("/block/") to forestall future surprises. */
128 if (strstr(path, "/block/"))
131 /* Make path point to "subsystem/device_name" */
132 if (path[5] == 'b') /* legacy /sys/block? */
133 path += sizeof("/sys/") - 1;
135 path += sizeof("/sys/class/") - 1;
137 /* If we have config file, look up user settings */
138 if (ENABLE_FEATURE_MDEV_CONF)
139 parser = config_open2("/etc/mdev.conf", fopen_for_read);
142 regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
145 struct bb_uidgid_t ugid;
147 char *command = NULL;
149 char aliaslink = aliaslink; /* for compiler */
151 /* Defaults in case we won't match any line */
152 ugid.uid = ugid.gid = 0;
156 if (ENABLE_FEATURE_MDEV_CONF
157 && config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL)
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 name = strchr(val, '/') ? path : (char *) device_name;
167 /* Fields: regex uid:gid mode [alias] [cmd] */
169 /* 1st field: @<numeric maj,min>... */
171 /* @major,minor[-last] */
172 /* (useful when name is ambiguous:
173 * "/sys/class/usb/lp0" and
174 * "/sys/class/printer/lp0") */
175 int cmaj, cmin0, cmin1, sc;
177 continue; /* no dev, no match */
178 sc = sscanf(val, "@%u,%u-%u", &cmaj, &cmin0, &cmin1);
179 if (sc < 1 || major != cmaj
180 || (sc == 2 && minor != cmin0)
181 || (sc == 3 && (minor < cmin0 || minor > cmin1))
183 continue; /* this line doesn't match */
185 } else { /* ... or regex to match device name */
190 xregcomp(&match, val, REG_EXTENDED);
191 result = regexec(&match, name, ARRAY_SIZE(off), off, 0);
194 //bb_error_msg("matches:");
195 //for (int i = 0; i < ARRAY_SIZE(off); i++) {
196 // if (off[i].rm_so < 0) continue;
197 // bb_error_msg("match %d: '%.*s'\n", i,
198 // (int)(off[i].rm_eo - off[i].rm_so),
199 // device_name + off[i].rm_so);
202 /* If not this device, skip rest of line */
203 /* (regexec returns whole pattern as "range" 0) */
204 if (result || off[0].rm_so
205 || ((int)off[0].rm_eo != (int)strlen(name))
207 continue; /* this line doesn't match */
211 /* This line matches: stop parsing the file after parsing
212 * the rest of fields unless keep_matching == 1 */
214 /* 2nd field: uid:gid - device ownership */
215 parse_chown_usergroup_or_die(&ugid, tokens[1]);
217 /* 3rd field: mode - device permissions */
218 mode = strtoul(tokens[2], NULL, 8);
221 /* 4th field (opt): >|=alias */
223 if (ENABLE_FEATURE_MDEV_RENAME && val) {
225 if (aliaslink == '>' || aliaslink == '=') {
231 s = strchrnul(val, ' ');
232 st = strchrnul(val, '\t');
235 val = (s[0] && s[1]) ? s+1 : NULL;
238 if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
239 /* substitute %1..9 with off[1..9], if any */
246 p = alias = xzalloc(strlen(a) + n * strlen(name));
252 if (i <= 9 && off[i].rm_so >= 0) {
253 n = off[i].rm_eo - off[i].rm_so;
254 strncpy(p, name + off[i].rm_so, n);
263 alias = xstrdup(a + 1);
268 if (ENABLE_FEATURE_MDEV_EXEC && val) {
269 const char *s = "$@*";
270 const char *s2 = strchr(s, val[0]);
273 bb_error_msg_and_die("bad line %u", parser->lineno);
275 /* Are we running this command now?
276 * Run $cmd on delete, @cmd on create, *cmd on both
279 command = xstrdup(val + 1);
283 /* End of field parsing */
285 /* "Execute" the line we found */
287 if (!delete && major >= 0) {
288 if (ENABLE_FEATURE_MDEV_RENAME)
290 if (mknod(device_name, mode | type, makedev(major, minor)) && errno != EEXIST)
291 bb_perror_msg_and_die("mknod %s", device_name);
292 if (major == root_major && minor == root_minor)
293 symlink(device_name, "root");
294 if (ENABLE_FEATURE_MDEV_CONF) {
295 chmod(device_name, mode);
296 chown(device_name, ugid.uid, ugid.gid);
298 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
299 alias = build_alias(alias, device_name);
300 /* move the device, and optionally
301 * make a symlink to moved device node */
302 if (rename(device_name, alias) == 0 && aliaslink == '>')
303 symlink(alias, device_name);
308 if (ENABLE_FEATURE_MDEV_EXEC && command) {
309 /* setenv will leak memory, use putenv/unsetenv/free */
310 char *s = xasprintf("%s=%s", "MDEV", device_name);
311 char *s1 = xasprintf("%s=%s", "SUBSYSTEM", subsystem);
314 if (system(command) == -1)
315 bb_perror_msg_and_die("can't run '%s'", command);
316 unsetenv("SUBSYSTEM");
325 /* At creation time, device might have been moved
326 * and a symlink might have been created. Undo that. */
328 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
329 alias = build_alias(alias, device_name);
335 /* We found matching line.
336 * Stop unless it was prefixed with '-' */
337 if (ENABLE_FEATURE_MDEV_CONF && !keep_matching)
340 /* end of "while line is read from /etc/mdev.conf" */
341 } while (ENABLE_FEATURE_MDEV_CONF);
343 if (ENABLE_FEATURE_MDEV_CONF)
344 config_close(parser);
347 /* File callback for /sys/ traversal */
348 static int FAST_FUNC fileAction(const char *fileName,
349 struct stat *statbuf UNUSED_PARAM,
351 int depth UNUSED_PARAM)
353 size_t len = strlen(fileName) - 4; /* can't underflow */
354 char *scratch = userData;
356 /* len check is for paranoid reasons */
357 if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
360 strcpy(scratch, fileName);
362 make_device(scratch, 0);
367 /* Directory callback for /sys/ traversal */
368 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
369 struct stat *statbuf UNUSED_PARAM,
370 void *userData UNUSED_PARAM,
373 /* Extract device subsystem -- the name of the directory
374 * under /sys/class/ */
377 subsystem = strrchr(fileName, '/');
379 subsystem = xstrdup(subsystem + 1);
382 return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
385 /* For the full gory details, see linux/Documentation/firmware_class/README
387 * Firmware loading works like this:
388 * - kernel sets FIRMWARE env var
389 * - userspace checks /lib/firmware/$FIRMWARE
390 * - userspace waits for /sys/$DEVPATH/loading to appear
391 * - userspace writes "1" to /sys/$DEVPATH/loading
392 * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
393 * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
394 * - kernel loads firmware into device
396 static void load_firmware(const char *firmware, const char *sysfs_path)
399 int firmware_fd, loading_fd, data_fd;
401 /* check for /lib/firmware/$FIRMWARE */
402 xchdir("/lib/firmware");
403 firmware_fd = xopen(firmware, O_RDONLY);
405 /* in case we goto out ... */
408 /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
410 for (cnt = 0; cnt < 30; ++cnt) {
411 loading_fd = open("loading", O_WRONLY);
412 if (loading_fd != -1)
419 /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
420 if (full_write(loading_fd, "1", 1) != 1)
423 /* load firmware into /sys/$DEVPATH/data */
424 data_fd = open("data", O_WRONLY);
427 cnt = bb_copyfd_eof(firmware_fd, data_fd);
429 /* tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading" */
431 full_write(loading_fd, "0", 1);
433 full_write(loading_fd, "-1", 2);
436 if (ENABLE_FEATURE_CLEAN_UP) {
443 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
444 int mdev_main(int argc UNUSED_PARAM, char **argv)
446 RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
448 /* We can be called as hotplug helper */
449 /* Kernel cannot provide suitable stdio fds for us, do it ourself */
455 if (argv[1] && strcmp(argv[1], "-s") == 0) {
462 root_major = major(st.st_dev);
463 root_minor = minor(st.st_dev);
465 /* ACTION_FOLLOWLINKS is needed since in newer kernels
466 * /sys/block/loop* (for example) are symlinks to dirs,
467 * not real directories.
468 * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
469 * but we can't enforce that on users)
471 if (access("/sys/class/block", F_OK) != 0) {
472 /* Scan obsolete /sys/block only if /sys/class/block
473 * doesn't exist. Otherwise we'll have dupes.
474 * Also, do not complain if it doesn't exist.
475 * Some people configure kernel to have no blockdevs.
477 recursive_action("/sys/block",
478 ACTION_RECURSE | ACTION_FOLLOWLINKS | ACTION_QUIET,
479 fileAction, dirAction, temp, 0);
481 recursive_action("/sys/class",
482 ACTION_RECURSE | ACTION_FOLLOWLINKS,
483 fileAction, dirAction, temp, 0);
491 * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
492 * ACTION can be "add" or "remove"
493 * DEVPATH is like "/block/sda" or "/class/input/mice"
495 action = getenv("ACTION");
496 env_path = getenv("DEVPATH");
497 subsystem = getenv("SUBSYSTEM");
498 if (!action || !env_path /*|| !subsystem*/)
500 fw = getenv("FIRMWARE");
502 /* If it exists, does /dev/mdev.seq match $SEQNUM?
503 * If it does not match, earlier mdev is running
504 * in parallel, and we need to wait */
505 seq = getenv("SEQNUM");
507 int timeout = 2000 / 32; /* 2000 msec */
510 char seqbuf[sizeof(int)*3 + 2];
512 seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf-1));
517 seqbuf[seqlen] = '\0';
518 if (seqbuf[0] == '\n' /* seed file? */
519 || strcmp(seq, seqbuf) == 0 /* correct idx? */
527 snprintf(temp, PATH_MAX, "/sys%s", env_path);
528 if (strcmp(action, "remove") == 0) {
529 /* Ignoring "remove firmware". It was reported
530 * to happen and to cause erroneous deletion
531 * of device nodes. */
533 make_device(temp, 1);
535 else if (strcmp(action, "add") == 0) {
536 make_device(temp, 0);
537 if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
539 load_firmware(fw, temp);
544 xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
548 if (ENABLE_FEATURE_CLEAN_UP)
549 RELEASE_CONFIG_BUFFER(temp);