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 GPLv2, see file LICENSE in this source tree.
14 //config: select PLATFORM_LINUX
16 //config: mdev is a mini-udev implementation for dynamically creating device
17 //config: nodes in the /dev directory.
19 //config: For more information, please see docs/mdev.txt
21 //config:config FEATURE_MDEV_CONF
22 //config: bool "Support /etc/mdev.conf"
24 //config: depends on MDEV
26 //config: Add support for the mdev config file to control ownership and
27 //config: permissions of the device nodes.
29 //config: For more information, please see docs/mdev.txt
31 //config:config FEATURE_MDEV_RENAME
32 //config: bool "Support subdirs/symlinks"
34 //config: depends on FEATURE_MDEV_CONF
36 //config: Add support for renaming devices and creating symlinks.
38 //config: For more information, please see docs/mdev.txt
40 //config:config FEATURE_MDEV_RENAME_REGEXP
41 //config: bool "Support regular expressions substitutions when renaming device"
43 //config: depends on FEATURE_MDEV_RENAME
45 //config: Add support for regular expressions substitutions when renaming
48 //config:config FEATURE_MDEV_EXEC
49 //config: bool "Support command execution at device addition/removal"
51 //config: depends on FEATURE_MDEV_CONF
53 //config: This adds support for an optional field to /etc/mdev.conf for
54 //config: executing commands when devices are created/removed.
56 //config: For more information, please see docs/mdev.txt
58 //config:config FEATURE_MDEV_LOAD_FIRMWARE
59 //config: bool "Support loading of firmwares"
61 //config: depends on MDEV
63 //config: Some devices need to load firmware before they can be usable.
65 //config: These devices will request userspace look up the files in
66 //config: /lib/firmware/ and if it exists, send it to the kernel for
67 //config: loading into the hardware.
69 //applet:IF_MDEV(APPLET(mdev, BB_DIR_SBIN, BB_SUID_DROP))
71 //kbuild:lib-$(CONFIG_MDEV) += mdev.o
73 //usage:#define mdev_trivial_usage
75 //usage:#define mdev_full_usage "\n\n"
76 //usage: "mdev -s is to be run during boot to scan /sys and populate /dev.\n"
78 //usage: "Bare mdev is a kernel hotplug helper. To activate it:\n"
79 //usage: " echo /sbin/mdev >/proc/sys/kernel/hotplug\n"
80 //usage: IF_FEATURE_MDEV_CONF(
82 //usage: "It uses /etc/mdev.conf with lines\n"
83 //usage: " [-][ENV=regex;]...DEVNAME UID:GID PERM"
84 //usage: IF_FEATURE_MDEV_RENAME(" [>|=PATH]|[!]")
85 //usage: IF_FEATURE_MDEV_EXEC(" [@|$|*PROG]")
87 //usage: "where DEVNAME is device name regex, @major,minor[-minor2], or\n"
88 //usage: "environment variable regex. A common use of the latter is\n"
89 //usage: "to load modules for hotplugged devices:\n"
90 //usage: " $MODALIAS=.* 0:0 660 @modprobe \"$MODALIAS\"\n"
93 //usage: "If /dev/mdev.seq file exists, mdev will wait for its value\n"
94 //usage: "to match $SEQNUM variable. This prevents plug/unplug races.\n"
95 //usage: "To activate this feature, create empty /dev/mdev.seq at boot.\n"
97 //usage: "If /dev/mdev.log file exists, debug log will be appended to it."
100 #include "common_bufsiz.h"
103 /* "mdev -s" scans /sys/class/xxx, looking for directories which have dev
104 * file (it is of the form "M:m\n"). Example: /sys/class/tty/tty0/dev
105 * contains "4:0\n". Directory name is taken as device name, path component
106 * directly after /sys/class/ as subsystem. In this example, "tty0" and "tty".
107 * Then mdev creates the /dev/device_name node.
108 * If /sys/class/.../dev file does not exist, mdev still may act
109 * on this device: see "@|$|*command args..." parameter in config file.
111 * mdev w/o parameters is called as hotplug helper. It takes device
112 * and subsystem names from $DEVPATH and $SUBSYSTEM, extracts
113 * maj,min from "/sys/$DEVPATH/dev" and also examines
114 * $ACTION ("add"/"delete") and $FIRMWARE.
116 * If action is "add", mdev creates /dev/device_name similarly to mdev -s.
117 * (todo: explain "delete" and $FIRMWARE)
119 * If /etc/mdev.conf exists, it may modify /dev/device_name's properties.
121 * Leading minus in 1st field means "don't stop on this line", otherwise
122 * search is stopped after the matching line is encountered.
124 * $envvar=regex format is useful for loading modules for hot-plugged devices
125 * which do not have driver loaded yet. In this case /sys/class/.../dev
126 * does not exist, but $MODALIAS is set to needed module's name
127 * (actually, an alias to it) by kernel. This rule instructs mdev
128 * to load the module and exit:
129 * $MODALIAS=.* 0:0 660 @modprobe "$MODALIAS"
130 * The kernel will generate another hotplug event when /sys/class/.../dev
133 * When line matches, the device node is created, chmod'ed and chown'ed,
134 * moved to path, and if >path, a symlink to moved node is created,
135 * all this if /sys/class/.../dev exists.
137 * =loop/ - moves to /dev/loop
138 * >disk/sda%1 - moves to /dev/disk/sdaN, makes /dev/sdaN a symlink
140 * Then "command args..." is executed (via sh -c 'command args...').
141 * @:execute on creation, $:on deletion, *:on both.
142 * This happens regardless of /sys/class/.../dev existence.
145 /* Kernel's hotplug environment constantly changes.
146 * Here are new cases I observed on 3.1.0:
148 * Case with $DEVNAME and $DEVICE, not just $DEVPATH:
151 * DEVICE=/proc/bus/usb/001/003
152 * DEVNAME=bus/usb/001/003
154 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5
158 * PRODUCT=18d1/4e12/227
162 * Case with $DEVICE, but no $DEVNAME - apparenty, usb iface notification?
163 * "Please load me a module" thing?
165 * DEVICE=/proc/bus/usb/001/003
166 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0
167 * DEVTYPE=usb_interface
169 * MODALIAS=usb:v18D1p4E12d0227dc00dsc00dp00ic08isc06ip50
170 * PRODUCT=18d1/4e12/227
175 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5
180 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/scsi_host/host5
181 * SUBSYSTEM=scsi_host
184 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0
185 * DEVTYPE=scsi_target
188 * Case with strange $MODALIAS:
190 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0
191 * DEVTYPE=scsi_device
192 * MODALIAS=scsi:t-0x00
196 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0/scsi_disk/5:0:0:0
197 * SUBSYSTEM=scsi_disk
200 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0/scsi_device/5:0:0:0
201 * SUBSYSTEM=scsi_device
203 * Case with explicit $MAJOR/$MINOR (no need to read /sys/$DEVPATH/dev?):
205 * DEVNAME=bsg/5:0:0:0
206 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0/bsg/5:0:0:0
212 * DEVPATH=/devices/virtual/bdi/8:16
223 * Case with ACTION=change:
228 * DISK_MEDIA_CHANGE=1
237 # define dbg1(...) do { if (G.verbose) bb_error_msg(__VA_ARGS__); } while(0)
239 # define dbg1(...) ((void)0)
242 # define dbg2(...) do { if (G.verbose >= 2) bb_error_msg(__VA_ARGS__); } while(0)
244 # define dbg2(...) ((void)0)
247 # define dbg3(...) do { if (G.verbose >= 3) bb_error_msg(__VA_ARGS__); } while(0)
249 # define dbg3(...) ((void)0)
253 static const char keywords[] ALIGN1 = "add\0remove\0"; // "change\0"
254 enum { OP_add, OP_remove };
257 struct envmatch *next;
267 struct bb_uidgid_t ugid;
270 IF_FEATURE_MDEV_EXEC(char *r_cmd;)
272 struct envmatch *envmatch;
276 int root_major, root_minor;
279 char *subsys_env; /* for putenv("SUBSYSTEM=subsystem") */
280 #if ENABLE_FEATURE_MDEV_CONF
281 const char *filename;
283 struct rule **rule_vec;
286 struct rule cur_rule;
287 char timestr[sizeof("HH:MM:SS.123456")];
289 #define G (*(struct globals*)bb_common_bufsiz1)
290 #define INIT_G() do { \
291 setup_common_bufsiz(); \
292 IF_NOT_FEATURE_MDEV_CONF(G.cur_rule.maj = -1;) \
293 IF_NOT_FEATURE_MDEV_CONF(G.cur_rule.mode = 0660;) \
297 /* Prevent infinite loops in /sys symlinks */
298 #define MAX_SYSFS_DEPTH 3
300 /* We use additional bytes in make_device() */
301 #define SCRATCH_SIZE 128
303 #if ENABLE_FEATURE_MDEV_CONF
305 static void make_default_cur_rule(void)
307 memset(&G.cur_rule, 0, sizeof(G.cur_rule));
308 G.cur_rule.maj = -1; /* "not a @major,minor rule" */
309 G.cur_rule.mode = 0660;
312 static void clean_up_cur_rule(void)
316 free(G.cur_rule.envvar);
317 free(G.cur_rule.ren_mov);
318 if (G.cur_rule.regex_compiled)
319 regfree(&G.cur_rule.match);
320 IF_FEATURE_MDEV_EXEC(free(G.cur_rule.r_cmd);)
321 e = G.cur_rule.envmatch;
327 make_default_cur_rule();
330 static char *parse_envmatch_pfx(char *val)
332 struct envmatch **nextp = &G.cur_rule.envmatch;
337 char *eq = strchr(val, '=');
338 if (!eq /* || eq == val? */)
340 if (endofname(val) != eq)
342 semicolon = strchr(eq, ';');
345 /* ENVVAR=regex;... */
346 *nextp = e = xzalloc(sizeof(*e));
348 e->envname = xstrndup(val, eq - val);
350 xregcomp(&e->match, eq + 1, REG_EXTENDED);
356 static void parse_next_rule(void)
358 /* Note: on entry, G.cur_rule is set to default */
363 /* No PARSE_EOL_COMMENTS, because command may contain '#' chars */
364 if (!config_read(G.parser, tokens, 4, 3, "# \t", PARSE_NORMAL & ~PARSE_EOL_COMMENTS))
367 /* Fields: [-]regex uid:gid mode [alias] [cmd] */
368 dbg3("token1:'%s'", tokens[1]);
372 G.cur_rule.keep_matching = ('-' == val[0]);
373 val += G.cur_rule.keep_matching; /* swallow leading dash */
374 val = parse_envmatch_pfx(val);
376 /* @major,minor[-minor2] */
377 /* (useful when name is ambiguous:
378 * "/sys/class/usb/lp0" and
379 * "/sys/class/printer/lp0")
381 int sc = sscanf(val, "@%u,%u-%u", &G.cur_rule.maj, &G.cur_rule.min0, &G.cur_rule.min1);
382 if (sc < 2 || G.cur_rule.maj < 0) {
383 bb_error_msg("bad @maj,min on line %d", G.parser->lineno);
387 G.cur_rule.min1 = G.cur_rule.min0;
389 char *eq = strchr(val, '=');
391 /* $ENVVAR=regex ... */
394 bb_error_msg("bad $envvar=regex on line %d", G.parser->lineno);
397 G.cur_rule.envvar = xstrndup(val, eq - val);
400 xregcomp(&G.cur_rule.match, val, REG_EXTENDED);
401 G.cur_rule.regex_compiled = 1;
404 /* 2nd field: uid:gid - device ownership */
405 if (get_uidgid(&G.cur_rule.ugid, tokens[1]) == 0) {
406 bb_error_msg("unknown user/group '%s' on line %d", tokens[1], G.parser->lineno);
410 /* 3rd field: mode - device permissions */
411 G.cur_rule.mode = bb_parse_mode(tokens[2], G.cur_rule.mode);
413 /* 4th field (opt): ">|=alias" or "!" to not create the node */
415 if (ENABLE_FEATURE_MDEV_RENAME && val && strchr(">=!", val[0])) {
416 char *s = skip_non_whitespace(val);
417 G.cur_rule.ren_mov = xstrndup(val, s - val);
418 val = skip_whitespace(s);
421 if (ENABLE_FEATURE_MDEV_EXEC && val && val[0]) {
422 const char *s = "$@*";
423 const char *s2 = strchr(s, val[0]);
425 bb_error_msg("bad line %u", G.parser->lineno);
428 IF_FEATURE_MDEV_EXEC(G.cur_rule.r_cmd = xstrdup(val);)
434 } /* while (config_read) */
436 dbg3("config_close(G.parser)");
437 config_close(G.parser);
443 /* If mdev -s, we remember rules in G.rule_vec[].
444 * Otherwise, there is no point in doing it, and we just
445 * save only one parsed rule in G.cur_rule.
447 static const struct rule *next_rule(void)
451 /* Open conf file if we didn't do it yet */
452 if (!G.parser && G.filename) {
453 dbg3("config_open('%s')", G.filename);
454 G.parser = config_open2(G.filename, fopen_for_read);
460 /* Do we have rule parsed already? */
461 if (G.rule_vec[G.rule_idx]) {
462 dbg3("< G.rule_vec[G.rule_idx:%d]=%p", G.rule_idx, G.rule_vec[G.rule_idx]);
463 return G.rule_vec[G.rule_idx++];
465 make_default_cur_rule();
471 /* Parse one more rule if file isn't fully read */
475 if (G.rule_vec) { /* mdev -s */
476 rule = xmemdup(&G.cur_rule, sizeof(G.cur_rule));
477 G.rule_vec = xrealloc_vector(G.rule_vec, 4, G.rule_idx);
478 G.rule_vec[G.rule_idx++] = rule;
479 dbg3("> G.rule_vec[G.rule_idx:%d]=%p", G.rule_idx, G.rule_vec[G.rule_idx]);
486 static int env_matches(struct envmatch *e)
490 char *val = getenv(e->envname);
493 r = regexec(&e->match, val, /*size*/ 0, /*range[]*/ NULL, /*eflags*/ 0);
494 if (r != 0) /* no match */
503 # define next_rule() (&G.cur_rule)
507 static void mkdir_recursive(char *name)
509 /* if name has many levels ("dir1/dir2"),
510 * bb_make_directory() will create dir1 according to umask,
511 * not according to its "mode" parameter.
512 * Since we run with umask=0, need to temporarily switch it.
514 umask(022); /* "dir1" (if any) will be 0755 too */
515 bb_make_directory(name, 0755, FILEUTILS_RECUR);
519 /* Builds an alias path.
520 * This function potentionally reallocates the alias parameter.
521 * Only used for ENABLE_FEATURE_MDEV_RENAME
523 static char *build_alias(char *alias, const char *device_name)
527 /* ">bar/": rename to bar/device_name */
528 /* ">bar[/]baz": rename to bar[/]baz */
529 dest = strrchr(alias, '/');
530 if (dest) { /* ">bar/[baz]" ? */
531 *dest = '\0'; /* mkdir bar */
532 mkdir_recursive(alias);
534 if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
536 alias = concat_path_file(alias, device_name);
544 /* mknod in /dev based on a path like "/sys/block/hda/hda1"
545 * NB1: path parameter needs to have SCRATCH_SIZE scratch bytes
546 * after NUL, but we promise to not mangle it (IOW: to restore NUL if needed).
547 * NB2: "mdev -s" may call us many times, do not leak memory/fds!
549 * device_name = $DEVNAME (may be NULL)
550 * path = /sys/$DEVPATH
552 static void make_device(char *device_name, char *path, int operation)
554 int major, minor, type, len;
555 char *path_end = path + strlen(path);
557 /* Try to read major/minor string. Note that the kernel puts \n after
558 * the data, so we don't need to worry about null terminating the string
559 * because sscanf() will stop at the first nondigit, which \n is.
560 * We also depend on path having writeable space after it.
563 if (operation == OP_add) {
564 strcpy(path_end, "/dev");
565 len = open_read_close(path, path_end + 1, SCRATCH_SIZE - 1);
568 if (!ENABLE_FEATURE_MDEV_EXEC)
570 /* no "dev" file, but we can still run scripts
571 * based on device name */
572 } else if (sscanf(path_end + 1, "%u:%u", &major, &minor) == 2) {
573 dbg1("dev %u,%u", major, minor);
578 /* else: for delete, -1 still deletes the node, but < -1 suppresses that */
580 /* Determine device name */
583 * There was no $DEVNAME envvar (for example, mdev -s never has).
584 * But it is very useful: it contains the *path*, not only basename,
585 * Thankfully, uevent file has it.
586 * Example of .../sound/card0/controlC0/uevent file on Linux-3.7.7:
589 * DEVNAME=snd/controlC0
591 strcpy(path_end, "/uevent");
592 len = open_read_close(path, path_end + 1, SCRATCH_SIZE - 1);
596 path_end[1 + len] = '\0';
597 device_name = strstr(path_end + 1, "\nDEVNAME=");
599 device_name += sizeof("\nDEVNAME=")-1;
600 strchrnul(device_name, '\n')[0] = '\0';
602 /* Fall back to just basename */
603 device_name = (char*) bb_basename(path);
606 /* Determine device type */
608 * http://kernel.org/doc/pending/hotplug.txt says that only
609 * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
610 * But since 2.6.25 block devices are also in /sys/class/block.
611 * We use strstr("/block/") to forestall future surprises.
614 if (strstr(path, "/block/") || (G.subsystem && is_prefixed_with(G.subsystem, "block")))
617 #if ENABLE_FEATURE_MDEV_CONF
618 G.rule_idx = 0; /* restart from the beginning (think mdev -s) */
621 const char *str_to_match;
622 regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
625 char aliaslink = aliaslink; /* for compiler */
627 const struct rule *rule;
629 str_to_match = device_name;
633 #if ENABLE_FEATURE_MDEV_CONF
634 if (!env_matches(rule->envmatch))
636 if (rule->maj >= 0) { /* @maj,min rule */
637 if (major != rule->maj)
639 if (minor < rule->min0 || minor > rule->min1)
641 memset(off, 0, sizeof(off));
644 if (rule->envvar) { /* $envvar=regex rule */
645 str_to_match = getenv(rule->envvar);
646 dbg3("getenv('%s'):'%s'", rule->envvar, str_to_match);
650 /* else: str_to_match = device_name */
652 if (rule->regex_compiled) {
653 int regex_match = regexec(&rule->match, str_to_match, ARRAY_SIZE(off), off, 0);
654 dbg3("regex_match for '%s':%d", str_to_match, regex_match);
655 //bb_error_msg("matches:");
656 //for (int i = 0; i < ARRAY_SIZE(off); i++) {
657 // if (off[i].rm_so < 0) continue;
658 // bb_error_msg("match %d: '%.*s'\n", i,
659 // (int)(off[i].rm_eo - off[i].rm_so),
660 // device_name + off[i].rm_so);
664 /* regexec returns whole pattern as "range" 0 */
666 || (int)off[0].rm_eo != (int)strlen(str_to_match)
668 continue; /* this rule doesn't match */
671 /* else: it's final implicit "match-all" rule */
673 dbg2("rule matched, line %d", G.parser ? G.parser->lineno : -1);
675 /* Build alias name */
677 if (ENABLE_FEATURE_MDEV_RENAME && rule->ren_mov) {
678 aliaslink = rule->ren_mov[0];
679 if (aliaslink == '!') {
680 /* "!": suppress node creation/deletion */
683 else if (aliaslink == '>' || aliaslink == '=') {
684 if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
689 /* substitute %1..9 with off[1..9], if any */
696 p = alias = xzalloc(strlen(rule->ren_mov) + n * strlen(str_to_match));
697 s = rule->ren_mov + 1;
701 unsigned i = (s[1] - '0');
702 if (i <= 9 && off[i].rm_so >= 0) {
703 n = off[i].rm_eo - off[i].rm_so;
704 strncpy(p, str_to_match + off[i].rm_so, n);
713 alias = xstrdup(rule->ren_mov + 1);
717 dbg3("alias:'%s'", alias);
720 IF_FEATURE_MDEV_EXEC(command = rule->r_cmd;)
722 /* Are we running this command now?
723 * Run @cmd on create, $cmd on delete, *cmd on any
725 if ((command[0] == '@' && operation == OP_add)
726 || (command[0] == '$' && operation == OP_remove)
727 || (command[0] == '*')
734 dbg3("command:'%s'", command);
736 /* "Execute" the line we found */
737 node_name = device_name;
738 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
739 node_name = alias = build_alias(alias, device_name);
740 dbg3("alias2:'%s'", alias);
743 if (operation == OP_add && major >= 0) {
744 char *slash = strrchr(node_name, '/');
747 mkdir_recursive(node_name);
750 if (ENABLE_FEATURE_MDEV_CONF) {
751 dbg1("mknod %s (%d,%d) %o"
753 node_name, major, minor, rule->mode | type,
754 rule->ugid.uid, rule->ugid.gid
757 dbg1("mknod %s (%d,%d) %o",
758 node_name, major, minor, rule->mode | type
761 if (mknod(node_name, rule->mode | type, makedev(major, minor)) && errno != EEXIST)
762 bb_perror_msg("can't create '%s'", node_name);
763 if (ENABLE_FEATURE_MDEV_CONF) {
764 chmod(node_name, rule->mode);
765 chown(node_name, rule->ugid.uid, rule->ugid.gid);
767 if (major == G.root_major && minor == G.root_minor)
768 symlink(node_name, "root");
769 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
770 if (aliaslink == '>') {
771 //TODO: on devtmpfs, device_name already exists and symlink() fails.
772 //End result is that instead of symlink, we have two nodes.
773 //What should be done?
774 dbg1("symlink: %s", device_name);
775 symlink(node_name, device_name);
780 if (ENABLE_FEATURE_MDEV_EXEC && command) {
781 /* setenv will leak memory, use putenv/unsetenv/free */
782 char *s = xasprintf("%s=%s", "MDEV", node_name);
784 dbg1("running: %s", command);
785 if (system(command) == -1)
786 bb_perror_msg("can't run '%s'", command);
787 bb_unsetenv_and_free(s);
790 if (operation == OP_remove && major >= -1) {
791 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
792 if (aliaslink == '>') {
793 dbg1("unlink: %s", device_name);
797 dbg1("unlink: %s", node_name);
801 if (ENABLE_FEATURE_MDEV_RENAME)
804 /* We found matching line.
805 * Stop unless it was prefixed with '-'
807 if (!ENABLE_FEATURE_MDEV_CONF || !rule->keep_matching)
812 /* File callback for /sys/ traversal.
813 * We act only on "/sys/.../dev" (pseudo)file
815 static int FAST_FUNC fileAction(const char *fileName,
816 struct stat *statbuf UNUSED_PARAM,
818 int depth UNUSED_PARAM)
820 size_t len = strlen(fileName) - 4; /* can't underflow */
821 char *path = userData; /* char array[PATH_MAX + SCRATCH_SIZE] */
822 char subsys[PATH_MAX];
825 /* Is it a ".../dev" file? (len check is for paranoid reasons) */
826 if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX - 32)
827 return FALSE; /* not .../dev */
829 strcpy(path, fileName);
832 /* Read ".../subsystem" symlink in the same directory where ".../dev" is */
833 strcpy(subsys, path);
834 strcpy(subsys + len, "/subsystem");
835 res = readlink(subsys, subsys, sizeof(subsys)-1);
840 bb_unsetenv_and_free(G.subsys_env);
843 /* Set G.subsystem and $SUBSYSTEM from symlink's last component */
844 G.subsystem = strrchr(subsys, '/');
846 G.subsystem = xstrdup(G.subsystem + 1);
847 G.subsys_env = xasprintf("%s=%s", "SUBSYSTEM", G.subsystem);
848 putenv(G.subsys_env);
852 make_device(/*DEVNAME:*/ NULL, path, OP_add);
857 /* Directory callback for /sys/ traversal */
858 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
859 struct stat *statbuf UNUSED_PARAM,
860 void *userData UNUSED_PARAM,
863 return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
866 /* For the full gory details, see linux/Documentation/firmware_class/README
868 * Firmware loading works like this:
869 * - kernel sets FIRMWARE env var
870 * - userspace checks /lib/firmware/$FIRMWARE
871 * - userspace waits for /sys/$DEVPATH/loading to appear
872 * - userspace writes "1" to /sys/$DEVPATH/loading
873 * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
874 * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
875 * - kernel loads firmware into device
877 static void load_firmware(const char *firmware, const char *sysfs_path)
880 int firmware_fd, loading_fd;
882 /* check for /lib/firmware/$FIRMWARE */
884 if (chdir("/lib/firmware") == 0)
885 firmware_fd = open(firmware, O_RDONLY); /* can fail */
887 /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
889 for (cnt = 0; cnt < 30; ++cnt) {
890 loading_fd = open("loading", O_WRONLY);
899 if (firmware_fd >= 0) {
902 /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
903 if (full_write(loading_fd, "1", 1) != 1)
906 /* load firmware into /sys/$DEVPATH/data */
907 data_fd = open("data", O_WRONLY);
910 cnt = bb_copyfd_eof(firmware_fd, data_fd);
911 if (ENABLE_FEATURE_CLEAN_UP)
915 /* Tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading"
916 * Note: we emit -1 also if firmware file wasn't found.
917 * There are cases when otherwise kernel would wait for minutes
921 full_write(loading_fd, "0", 1);
923 full_write(loading_fd, "-1", 2);
927 if (ENABLE_FEATURE_CLEAN_UP) {
933 static char *curtime(void)
936 gettimeofday(&tv, NULL);
938 strftime_HHMMSS(G.timestr, sizeof(G.timestr), &tv.tv_sec),
945 static void open_mdev_log(const char *seq, unsigned my_pid)
947 int logfd = open("mdev.log", O_WRONLY | O_APPEND);
949 xmove_fd(logfd, STDERR_FILENO);
951 applet_name = xasprintf("%s[%s]", applet_name, seq ? seq : utoa(my_pid));
955 /* If it exists, does /dev/mdev.seq match $SEQNUM?
956 * If it does not match, earlier mdev is running
957 * in parallel, and we need to wait.
958 * Active mdev pokes us with SIGCHLD to check the new file.
961 wait_for_seqfile(unsigned expected_seq)
963 /* We time out after 2 sec */
964 static const struct timespec ts = { 0, 32*1000*1000 };
965 int timeout = 2000 / 32;
970 sigemptyset(&set_CHLD);
971 sigaddset(&set_CHLD, SIGCHLD);
972 sigprocmask(SIG_BLOCK, &set_CHLD, NULL);
976 char seqbuf[sizeof(long)*3 + 2];
980 seq_fd = open("mdev.seq", O_RDWR);
983 close_on_exec_on(seq_fd);
985 seqlen = pread(seq_fd, seqbuf, sizeof(seqbuf) - 1, 0);
991 seqbuf[seqlen] = '\0';
992 if (seqbuf[0] == '\n' || seqbuf[0] == '\0') {
993 /* seed file: write out seq ASAP */
994 xwrite_str(seq_fd, utoa(expected_seq));
995 xlseek(seq_fd, 0, SEEK_SET);
996 dbg2("first seq written");
999 seqbufnum = atoll(seqbuf);
1000 if (seqbufnum == expected_seq) {
1004 if (seqbufnum > expected_seq) {
1005 /* a later mdev runs already (this was seen by users to happen) */
1006 /* do not overwrite seqfile on exit */
1012 dbg2("%s mdev.seq='%s', need '%u'", curtime(), seqbuf, expected_seq);
1015 if (sigtimedwait(&set_CHLD, NULL, &ts) >= 0) {
1017 continue; /* don't decrement timeout! */
1019 if (--timeout == 0) {
1020 dbg1("%s mdev.seq='%s'", "timed out", seqbuf);
1024 sigprocmask(SIG_UNBLOCK, &set_CHLD, NULL);
1028 static void signal_mdevs(unsigned my_pid)
1030 procps_status_t* p = NULL;
1031 while ((p = procps_scan(p, PSSCAN_ARGV0)) != NULL) {
1032 if (p->pid != my_pid
1034 && strcmp(bb_basename(p->argv0), "mdev") == 0
1036 kill(p->pid, SIGCHLD);
1041 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1042 int mdev_main(int argc UNUSED_PARAM, char **argv)
1044 RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
1048 #if ENABLE_FEATURE_MDEV_CONF
1049 G.filename = "/etc/mdev.conf";
1052 /* We can be called as hotplug helper */
1053 /* Kernel cannot provide suitable stdio fds for us, do it ourself */
1054 bb_sanitize_stdio();
1056 /* Force the configuration file settings exactly */
1061 if (argv[1] && strcmp(argv[1], "-s") == 0) {
1067 #if ENABLE_FEATURE_MDEV_CONF
1068 /* Same as xrealloc_vector(NULL, 4, 0): */
1069 G.rule_vec = xzalloc((1 << 4) * sizeof(*G.rule_vec));
1072 G.root_major = major(st.st_dev);
1073 G.root_minor = minor(st.st_dev);
1075 putenv((char*)"ACTION=add");
1077 /* Create all devices from /sys/dev hierarchy */
1078 recursive_action("/sys/dev",
1079 ACTION_RECURSE | ACTION_FOLLOWLINKS,
1080 fileAction, dirAction, temp, 0);
1088 unsigned seqnum = seqnum; /* for compiler */
1093 * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
1094 * ACTION can be "add", "remove", "change"
1095 * DEVPATH is like "/block/sda" or "/class/input/mice"
1097 env_devname = getenv("DEVNAME"); /* can be NULL */
1098 G.subsystem = getenv("SUBSYSTEM");
1099 action = getenv("ACTION");
1100 env_devpath = getenv("DEVPATH");
1101 if (!action || !env_devpath /*|| !G.subsystem*/)
1103 fw = getenv("FIRMWARE");
1104 seq = getenv("SEQNUM");
1105 op = index_in_strings(keywords, action);
1108 open_mdev_log(seq, my_pid);
1112 seqnum = atoll(seq);
1113 seq_fd = wait_for_seqfile(seqnum);
1117 "ACTION:%s SUBSYSTEM:%s DEVNAME:%s DEVPATH:%s"
1120 action, G.subsystem, env_devname, env_devpath,
1121 fw ? " FW:" : "", fw ? fw : ""
1124 snprintf(temp, PATH_MAX, "/sys%s", env_devpath);
1125 if (op == OP_remove) {
1126 /* Ignoring "remove firmware". It was reported
1127 * to happen and to cause erroneous deletion
1128 * of device nodes. */
1130 make_device(env_devname, temp, op);
1133 make_device(env_devname, temp, op);
1134 if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
1135 if (op == OP_add && fw)
1136 load_firmware(fw, temp);
1140 dbg1("%s exiting", curtime());
1142 xwrite_str(seq_fd, utoa(seqnum + 1));
1143 signal_mdevs(my_pid);
1147 if (ENABLE_FEATURE_CLEAN_UP)
1148 RELEASE_CONFIG_BUFFER(temp);
1150 return EXIT_SUCCESS;