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."
102 /* "mdev -s" scans /sys/class/xxx, looking for directories which have dev
103 * file (it is of the form "M:m\n"). Example: /sys/class/tty/tty0/dev
104 * contains "4:0\n". Directory name is taken as device name, path component
105 * directly after /sys/class/ as subsystem. In this example, "tty0" and "tty".
106 * Then mdev creates the /dev/device_name node.
107 * If /sys/class/.../dev file does not exist, mdev still may act
108 * on this device: see "@|$|*command args..." parameter in config file.
110 * mdev w/o parameters is called as hotplug helper. It takes device
111 * and subsystem names from $DEVPATH and $SUBSYSTEM, extracts
112 * maj,min from "/sys/$DEVPATH/dev" and also examines
113 * $ACTION ("add"/"delete") and $FIRMWARE.
115 * If action is "add", mdev creates /dev/device_name similarly to mdev -s.
116 * (todo: explain "delete" and $FIRMWARE)
118 * If /etc/mdev.conf exists, it may modify /dev/device_name's properties.
120 * Leading minus in 1st field means "don't stop on this line", otherwise
121 * search is stopped after the matching line is encountered.
123 * $envvar=regex format is useful for loading modules for hot-plugged devices
124 * which do not have driver loaded yet. In this case /sys/class/.../dev
125 * does not exist, but $MODALIAS is set to needed module's name
126 * (actually, an alias to it) by kernel. This rule instructs mdev
127 * to load the module and exit:
128 * $MODALIAS=.* 0:0 660 @modprobe "$MODALIAS"
129 * The kernel will generate another hotplug event when /sys/class/.../dev
132 * When line matches, the device node is created, chmod'ed and chown'ed,
133 * moved to path, and if >path, a symlink to moved node is created,
134 * all this if /sys/class/.../dev exists.
136 * =loop/ - moves to /dev/loop
137 * >disk/sda%1 - moves to /dev/disk/sdaN, makes /dev/sdaN a symlink
139 * Then "command args..." is executed (via sh -c 'command args...').
140 * @:execute on creation, $:on deletion, *:on both.
141 * This happens regardless of /sys/class/.../dev existence.
144 /* Kernel's hotplug environment constantly changes.
145 * Here are new cases I observed on 3.1.0:
147 * Case with $DEVNAME and $DEVICE, not just $DEVPATH:
150 * DEVICE=/proc/bus/usb/001/003
151 * DEVNAME=bus/usb/001/003
153 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5
157 * PRODUCT=18d1/4e12/227
161 * Case with $DEVICE, but no $DEVNAME - apparenty, usb iface notification?
162 * "Please load me a module" thing?
164 * DEVICE=/proc/bus/usb/001/003
165 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0
166 * DEVTYPE=usb_interface
168 * MODALIAS=usb:v18D1p4E12d0227dc00dsc00dp00ic08isc06ip50
169 * PRODUCT=18d1/4e12/227
174 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5
179 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/scsi_host/host5
180 * SUBSYSTEM=scsi_host
183 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0
184 * DEVTYPE=scsi_target
187 * Case with strange $MODALIAS:
189 * DEVPATH=/devices/pci0000:00/0000:00:02.1/usb1/1-5/1-5:1.0/host5/target5:0:0/5:0:0:0
190 * DEVTYPE=scsi_device
191 * MODALIAS=scsi:t-0x00
195 * 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
196 * SUBSYSTEM=scsi_disk
199 * 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
200 * SUBSYSTEM=scsi_device
202 * Case with explicit $MAJOR/$MINOR (no need to read /sys/$DEVPATH/dev?):
204 * DEVNAME=bsg/5:0:0:0
205 * 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
211 * DEVPATH=/devices/virtual/bdi/8:16
222 * Case with ACTION=change:
227 * DISK_MEDIA_CHANGE=1
236 # define dbg1(...) do { if (G.verbose) bb_error_msg(__VA_ARGS__); } while(0)
238 # define dbg1(...) ((void)0)
241 # define dbg2(...) do { if (G.verbose >= 2) bb_error_msg(__VA_ARGS__); } while(0)
243 # define dbg2(...) ((void)0)
246 # define dbg3(...) do { if (G.verbose >= 3) bb_error_msg(__VA_ARGS__); } while(0)
248 # define dbg3(...) ((void)0)
252 static const char keywords
[] ALIGN1
= "add\0remove\0"; // "change\0"
253 enum { OP_add
, OP_remove
};
256 struct envmatch
*next
;
266 struct bb_uidgid_t ugid
;
269 IF_FEATURE_MDEV_EXEC(char *r_cmd
;)
271 struct envmatch
*envmatch
;
275 int root_major
, root_minor
;
278 char *subsys_env
; /* for putenv("SUBSYSTEM=subsystem") */
279 #if ENABLE_FEATURE_MDEV_CONF
280 const char *filename
;
282 struct rule
**rule_vec
;
285 struct rule cur_rule
;
286 char timestr
[sizeof("60.123456")];
288 #define G (*(struct globals*)&bb_common_bufsiz1)
289 #define INIT_G() do { \
290 IF_NOT_FEATURE_MDEV_CONF(G.cur_rule.maj = -1;) \
291 IF_NOT_FEATURE_MDEV_CONF(G.cur_rule.mode = 0660;) \
295 /* Prevent infinite loops in /sys symlinks */
296 #define MAX_SYSFS_DEPTH 3
298 /* We use additional bytes in make_device() */
299 #define SCRATCH_SIZE 128
301 #if ENABLE_FEATURE_MDEV_CONF
303 static void make_default_cur_rule(void)
305 memset(&G
.cur_rule
, 0, sizeof(G
.cur_rule
));
306 G
.cur_rule
.maj
= -1; /* "not a @major,minor rule" */
307 G
.cur_rule
.mode
= 0660;
310 static void clean_up_cur_rule(void)
314 free(G
.cur_rule
.envvar
);
315 free(G
.cur_rule
.ren_mov
);
316 if (G
.cur_rule
.regex_compiled
)
317 regfree(&G
.cur_rule
.match
);
318 IF_FEATURE_MDEV_EXEC(free(G
.cur_rule
.r_cmd
);)
319 e
= G
.cur_rule
.envmatch
;
325 make_default_cur_rule();
328 /* In later versions, endofname is in libbb */
329 #define endofname mdev_endofname
331 const char* FAST_FUNC
332 endofname(const char *name
)
334 #define is_name(c) ((c) == '_' || isalpha((unsigned char)(c)))
335 #define is_in_name(c) ((c) == '_' || isalnum((unsigned char)(c)))
339 if (!is_in_name(*name
))
345 static char *parse_envmatch_pfx(char *val
)
347 struct envmatch
**nextp
= &G
.cur_rule
.envmatch
;
352 char *eq
= strchr(val
, '=');
353 if (!eq
/* || eq == val? */)
355 if (endofname(val
) != eq
)
357 semicolon
= strchr(eq
, ';');
360 /* ENVVAR=regex;... */
361 *nextp
= e
= xzalloc(sizeof(*e
));
363 e
->envname
= xstrndup(val
, eq
- val
);
365 xregcomp(&e
->match
, eq
+ 1, REG_EXTENDED
);
371 static void parse_next_rule(void)
373 /* Note: on entry, G.cur_rule is set to default */
378 /* No PARSE_EOL_COMMENTS, because command may contain '#' chars */
379 if (!config_read(G
.parser
, tokens
, 4, 3, "# \t", PARSE_NORMAL
& ~PARSE_EOL_COMMENTS
))
382 /* Fields: [-]regex uid:gid mode [alias] [cmd] */
383 dbg3("token1:'%s'", tokens
[1]);
387 G
.cur_rule
.keep_matching
= ('-' == val
[0]);
388 val
+= G
.cur_rule
.keep_matching
; /* swallow leading dash */
389 val
= parse_envmatch_pfx(val
);
391 /* @major,minor[-minor2] */
392 /* (useful when name is ambiguous:
393 * "/sys/class/usb/lp0" and
394 * "/sys/class/printer/lp0")
396 int sc
= sscanf(val
, "@%u,%u-%u", &G
.cur_rule
.maj
, &G
.cur_rule
.min0
, &G
.cur_rule
.min1
);
397 if (sc
< 2 || G
.cur_rule
.maj
< 0) {
398 bb_error_msg("bad @maj,min on line %d", G
.parser
->lineno
);
402 G
.cur_rule
.min1
= G
.cur_rule
.min0
;
404 char *eq
= strchr(val
, '=');
406 /* $ENVVAR=regex ... */
409 bb_error_msg("bad $envvar=regex on line %d", G
.parser
->lineno
);
412 G
.cur_rule
.envvar
= xstrndup(val
, eq
- val
);
415 xregcomp(&G
.cur_rule
.match
, val
, REG_EXTENDED
);
416 G
.cur_rule
.regex_compiled
= 1;
419 /* 2nd field: uid:gid - device ownership */
420 if (get_uidgid(&G
.cur_rule
.ugid
, tokens
[1], /*allow_numeric:*/ 1) == 0) {
421 bb_error_msg("unknown user/group '%s' on line %d", tokens
[1], G
.parser
->lineno
);
425 /* 3rd field: mode - device permissions */
426 bb_parse_mode(tokens
[2], &G
.cur_rule
.mode
);
428 /* 4th field (opt): ">|=alias" or "!" to not create the node */
430 if (ENABLE_FEATURE_MDEV_RENAME
&& val
&& strchr(">=!", val
[0])) {
431 char *s
= skip_non_whitespace(val
);
432 G
.cur_rule
.ren_mov
= xstrndup(val
, s
- val
);
433 val
= skip_whitespace(s
);
436 if (ENABLE_FEATURE_MDEV_EXEC
&& val
&& val
[0]) {
437 const char *s
= "$@*";
438 const char *s2
= strchr(s
, val
[0]);
440 bb_error_msg("bad line %u", G
.parser
->lineno
);
443 IF_FEATURE_MDEV_EXEC(G
.cur_rule
.r_cmd
= xstrdup(val
);)
449 } /* while (config_read) */
451 dbg3("config_close(G.parser)");
452 config_close(G
.parser
);
458 /* If mdev -s, we remember rules in G.rule_vec[].
459 * Otherwise, there is no point in doing it, and we just
460 * save only one parsed rule in G.cur_rule.
462 static const struct rule
*next_rule(void)
466 /* Open conf file if we didn't do it yet */
467 if (!G
.parser
&& G
.filename
) {
468 dbg3("config_open('%s')", G
.filename
);
469 G
.parser
= config_open2(G
.filename
, fopen_for_read
);
475 /* Do we have rule parsed already? */
476 if (G
.rule_vec
[G
.rule_idx
]) {
477 dbg3("< G.rule_vec[G.rule_idx:%d]=%p", G
.rule_idx
, G
.rule_vec
[G
.rule_idx
]);
478 return G
.rule_vec
[G
.rule_idx
++];
480 make_default_cur_rule();
486 /* Parse one more rule if file isn't fully read */
490 if (G
.rule_vec
) { /* mdev -s */
491 rule
= memcpy(xmalloc(sizeof(G
.cur_rule
)), &G
.cur_rule
, sizeof(G
.cur_rule
));
492 G
.rule_vec
= xrealloc_vector(G
.rule_vec
, 4, G
.rule_idx
);
493 G
.rule_vec
[G
.rule_idx
++] = rule
;
494 dbg3("> G.rule_vec[G.rule_idx:%d]=%p", G
.rule_idx
, G
.rule_vec
[G
.rule_idx
]);
501 static int env_matches(struct envmatch
*e
)
505 char *val
= getenv(e
->envname
);
508 r
= regexec(&e
->match
, val
, /*size*/ 0, /*range[]*/ NULL
, /*eflags*/ 0);
509 if (r
!= 0) /* no match */
518 # define next_rule() (&G.cur_rule)
522 static void mkdir_recursive(char *name
)
524 /* if name has many levels ("dir1/dir2"),
525 * bb_make_directory() will create dir1 according to umask,
526 * not according to its "mode" parameter.
527 * Since we run with umask=0, need to temporarily switch it.
529 umask(022); /* "dir1" (if any) will be 0755 too */
530 bb_make_directory(name
, 0755, FILEUTILS_RECUR
);
534 /* Builds an alias path.
535 * This function potentionally reallocates the alias parameter.
536 * Only used for ENABLE_FEATURE_MDEV_RENAME
538 static char *build_alias(char *alias
, const char *device_name
)
542 /* ">bar/": rename to bar/device_name */
543 /* ">bar[/]baz": rename to bar[/]baz */
544 dest
= strrchr(alias
, '/');
545 if (dest
) { /* ">bar/[baz]" ? */
546 *dest
= '\0'; /* mkdir bar */
547 mkdir_recursive(alias
);
549 if (dest
[1] == '\0') { /* ">bar/" => ">bar/device_name" */
551 alias
= concat_path_file(alias
, device_name
);
559 /* mknod in /dev based on a path like "/sys/block/hda/hda1"
560 * NB1: path parameter needs to have SCRATCH_SIZE scratch bytes
561 * after NUL, but we promise to not mangle (IOW: to restore NUL if needed)
563 * NB2: "mdev -s" may call us many times, do not leak memory/fds!
565 * device_name = $DEVNAME (may be NULL)
566 * path = /sys/$DEVPATH
568 static void make_device(char *device_name
, char *path
, int operation
)
570 int major
, minor
, type
, len
;
571 char *path_end
= path
+ strlen(path
);
573 /* Try to read major/minor string. Note that the kernel puts \n after
574 * the data, so we don't need to worry about null terminating the string
575 * because sscanf() will stop at the first nondigit, which \n is.
576 * We also depend on path having writeable space after it.
579 if (operation
== OP_add
) {
580 strcpy(path_end
, "/dev");
581 len
= open_read_close(path
, path_end
+ 1, SCRATCH_SIZE
- 1);
584 if (!ENABLE_FEATURE_MDEV_EXEC
)
586 /* no "dev" file, but we can still run scripts
587 * based on device name */
588 } else if (sscanf(path_end
+ 1, "%u:%u", &major
, &minor
) == 2) {
589 dbg1("dev %u,%u", major
, minor
);
594 /* else: for delete, -1 still deletes the node, but < -1 suppresses that */
596 /* Determine device name */
599 * There was no $DEVNAME envvar (for example, mdev -s never has).
600 * But it is very useful: it contains the *path*, not only basename,
601 * Thankfully, uevent file has it.
602 * Example of .../sound/card0/controlC0/uevent file on Linux-3.7.7:
605 * DEVNAME=snd/controlC0
607 strcpy(path_end
, "/uevent");
608 len
= open_read_close(path
, path_end
+ 1, SCRATCH_SIZE
- 1);
612 path_end
[1 + len
] = '\0';
613 device_name
= strstr(path_end
+ 1, "\nDEVNAME=");
615 device_name
+= sizeof("\nDEVNAME=")-1;
616 strchrnul(device_name
, '\n')[0] = '\0';
618 /* Fall back to just basename */
619 device_name
= (char*) bb_basename(path
);
622 /* Determine device type */
624 * http://kernel.org/doc/pending/hotplug.txt says that only
625 * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
626 * But since 2.6.25 block devices are also in /sys/class/block.
627 * We use strstr("/block/") to forestall future surprises.
630 if (strstr(path
, "/block/") || (G
.subsystem
&& strncmp(G
.subsystem
, "block", 5) == 0))
633 #if ENABLE_FEATURE_MDEV_CONF
634 G
.rule_idx
= 0; /* restart from the beginning (think mdev -s) */
637 const char *str_to_match
;
638 regmatch_t off
[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP
];
641 char aliaslink
= aliaslink
; /* for compiler */
643 const struct rule
*rule
;
645 str_to_match
= device_name
;
649 #if ENABLE_FEATURE_MDEV_CONF
650 if (!env_matches(rule
->envmatch
))
652 if (rule
->maj
>= 0) { /* @maj,min rule */
653 if (major
!= rule
->maj
)
655 if (minor
< rule
->min0
|| minor
> rule
->min1
)
657 memset(off
, 0, sizeof(off
));
660 if (rule
->envvar
) { /* $envvar=regex rule */
661 str_to_match
= getenv(rule
->envvar
);
662 dbg3("getenv('%s'):'%s'", rule
->envvar
, str_to_match
);
666 /* else: str_to_match = device_name */
668 if (rule
->regex_compiled
) {
669 int regex_match
= regexec(&rule
->match
, str_to_match
, ARRAY_SIZE(off
), off
, 0);
670 dbg3("regex_match for '%s':%d", str_to_match
, regex_match
);
671 //bb_error_msg("matches:");
672 //for (int i = 0; i < ARRAY_SIZE(off); i++) {
673 // if (off[i].rm_so < 0) continue;
674 // bb_error_msg("match %d: '%.*s'\n", i,
675 // (int)(off[i].rm_eo - off[i].rm_so),
676 // device_name + off[i].rm_so);
680 /* regexec returns whole pattern as "range" 0 */
682 || (int)off
[0].rm_eo
!= (int)strlen(str_to_match
)
684 continue; /* this rule doesn't match */
687 /* else: it's final implicit "match-all" rule */
689 dbg2("rule matched, line %d", G
.parser
? G
.parser
->lineno
: -1);
691 /* Build alias name */
693 if (ENABLE_FEATURE_MDEV_RENAME
&& rule
->ren_mov
) {
694 aliaslink
= rule
->ren_mov
[0];
695 if (aliaslink
== '!') {
696 /* "!": suppress node creation/deletion */
699 else if (aliaslink
== '>' || aliaslink
== '=') {
700 if (ENABLE_FEATURE_MDEV_RENAME_REGEXP
) {
705 /* substitute %1..9 with off[1..9], if any */
712 p
= alias
= xzalloc(strlen(rule
->ren_mov
) + n
* strlen(str_to_match
));
713 s
= rule
->ren_mov
+ 1;
717 unsigned i
= (s
[1] - '0');
718 if (i
<= 9 && off
[i
].rm_so
>= 0) {
719 n
= off
[i
].rm_eo
- off
[i
].rm_so
;
720 strncpy(p
, str_to_match
+ off
[i
].rm_so
, n
);
729 alias
= xstrdup(rule
->ren_mov
+ 1);
733 dbg3("alias:'%s'", alias
);
736 IF_FEATURE_MDEV_EXEC(command
= rule
->r_cmd
;)
738 /* Are we running this command now?
739 * Run @cmd on create, $cmd on delete, *cmd on any
741 if ((command
[0] == '@' && operation
== OP_add
)
742 || (command
[0] == '$' && operation
== OP_remove
)
743 || (command
[0] == '*')
750 dbg3("command:'%s'", command
);
752 /* "Execute" the line we found */
753 node_name
= device_name
;
754 if (ENABLE_FEATURE_MDEV_RENAME
&& alias
) {
755 node_name
= alias
= build_alias(alias
, device_name
);
756 dbg3("alias2:'%s'", alias
);
759 if (operation
== OP_add
&& major
>= 0) {
760 char *slash
= strrchr(node_name
, '/');
763 mkdir_recursive(node_name
);
766 if (ENABLE_FEATURE_MDEV_CONF
) {
767 dbg1("mknod %s (%d,%d) %o"
769 node_name
, major
, minor
, rule
->mode
| type
,
770 rule
->ugid
.uid
, rule
->ugid
.gid
773 dbg1("mknod %s (%d,%d) %o",
774 node_name
, major
, minor
, rule
->mode
| type
777 if (mknod(node_name
, rule
->mode
| type
, makedev(major
, minor
)) && errno
!= EEXIST
)
778 bb_perror_msg("can't create '%s'", node_name
);
779 if (ENABLE_FEATURE_MDEV_CONF
) {
780 chmod(node_name
, rule
->mode
);
781 chown(node_name
, rule
->ugid
.uid
, rule
->ugid
.gid
);
783 if (major
== G
.root_major
&& minor
== G
.root_minor
)
784 symlink(node_name
, "root");
785 if (ENABLE_FEATURE_MDEV_RENAME
&& alias
) {
786 if (aliaslink
== '>') {
787 //TODO: on devtmpfs, device_name already exists and symlink() fails.
788 //End result is that instead of symlink, we have two nodes.
789 //What should be done?
790 dbg1("symlink: %s", device_name
);
791 symlink(node_name
, device_name
);
796 if (ENABLE_FEATURE_MDEV_EXEC
&& command
) {
797 /* setenv will leak memory, use putenv/unsetenv/free */
798 char *s
= xasprintf("%s=%s", "MDEV", node_name
);
800 dbg1("running: %s", command
);
801 if (system(command
) == -1)
802 bb_perror_msg("can't run '%s'", command
);
803 bb_unsetenv_and_free(s
);
806 if (operation
== OP_remove
&& major
>= -1) {
807 if (ENABLE_FEATURE_MDEV_RENAME
&& alias
) {
808 if (aliaslink
== '>') {
809 dbg1("unlink: %s", device_name
);
813 dbg1("unlink: %s", node_name
);
817 if (ENABLE_FEATURE_MDEV_RENAME
)
820 /* We found matching line.
821 * Stop unless it was prefixed with '-'
823 if (!ENABLE_FEATURE_MDEV_CONF
|| !rule
->keep_matching
)
828 /* File callback for /sys/ traversal */
829 static int FAST_FUNC
fileAction(const char *fileName
,
830 struct stat
*statbuf UNUSED_PARAM
,
832 int depth UNUSED_PARAM
)
834 size_t len
= strlen(fileName
) - 4; /* can't underflow */
835 char *scratch
= userData
;
837 /* len check is for paranoid reasons */
838 if (strcmp(fileName
+ len
, "/dev") != 0 || len
>= PATH_MAX
)
841 strcpy(scratch
, fileName
);
843 make_device(/*DEVNAME:*/ NULL
, scratch
, OP_add
);
848 /* Directory callback for /sys/ traversal */
849 static int FAST_FUNC
dirAction(const char *fileName UNUSED_PARAM
,
850 struct stat
*statbuf UNUSED_PARAM
,
851 void *userData UNUSED_PARAM
,
854 /* Extract device subsystem -- the name of the directory
855 * under /sys/class/ */
859 bb_unsetenv_and_free(G
.subsys_env
);
862 G
.subsystem
= strrchr(fileName
, '/');
864 G
.subsystem
= xstrdup(G
.subsystem
+ 1);
865 G
.subsys_env
= xasprintf("%s=%s", "SUBSYSTEM", G
.subsystem
);
866 putenv(G
.subsys_env
);
870 return (depth
>= MAX_SYSFS_DEPTH
? SKIP
: TRUE
);
873 /* For the full gory details, see linux/Documentation/firmware_class/README
875 * Firmware loading works like this:
876 * - kernel sets FIRMWARE env var
877 * - userspace checks /lib/firmware/$FIRMWARE
878 * - userspace waits for /sys/$DEVPATH/loading to appear
879 * - userspace writes "1" to /sys/$DEVPATH/loading
880 * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
881 * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
882 * - kernel loads firmware into device
884 static void load_firmware(const char *firmware
, const char *sysfs_path
)
887 int firmware_fd
, loading_fd
;
889 /* check for /lib/firmware/$FIRMWARE */
890 xchdir("/lib/firmware");
891 firmware_fd
= open(firmware
, O_RDONLY
); /* can fail */
893 /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
895 for (cnt
= 0; cnt
< 30; ++cnt
) {
896 loading_fd
= open("loading", O_WRONLY
);
905 if (firmware_fd
>= 0) {
908 /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
909 if (full_write(loading_fd
, "1", 1) != 1)
912 /* load firmware into /sys/$DEVPATH/data */
913 data_fd
= open("data", O_WRONLY
);
916 cnt
= bb_copyfd_eof(firmware_fd
, data_fd
);
917 if (ENABLE_FEATURE_CLEAN_UP
)
921 /* Tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading"
922 * Note: we emit -1 also if firmware file wasn't found.
923 * There are cases when otherwise kernel would wait for minutes
927 full_write(loading_fd
, "0", 1);
929 full_write(loading_fd
, "-1", 2);
933 if (ENABLE_FEATURE_CLEAN_UP
) {
939 static char *curtime(void)
942 gettimeofday(&tv
, NULL
);
943 sprintf(G
.timestr
, "%u.%06u", (unsigned)tv
.tv_sec
% 60, (unsigned)tv
.tv_usec
);
947 static void open_mdev_log(const char *seq
, unsigned my_pid
)
949 int logfd
= open("mdev.log", O_WRONLY
| O_APPEND
);
951 xmove_fd(logfd
, STDERR_FILENO
);
953 applet_name
= xasprintf("%s[%s]", applet_name
, seq
? seq
: utoa(my_pid
));
957 /* If it exists, does /dev/mdev.seq match $SEQNUM?
958 * If it does not match, earlier mdev is running
959 * in parallel, and we need to wait.
960 * Active mdev pokes us with SIGCHLD to check the new file.
963 wait_for_seqfile(const char *seq
)
965 /* We time out after 2 sec */
966 static const struct timespec ts
= { 0, 32*1000*1000 };
967 int timeout
= 2000 / 32;
972 sigemptyset(&set_CHLD
);
973 sigaddset(&set_CHLD
, SIGCHLD
);
974 sigprocmask(SIG_BLOCK
, &set_CHLD
, NULL
);
978 char seqbuf
[sizeof(int)*3 + 2];
981 seq_fd
= open("mdev.seq", O_RDWR
);
985 seqlen
= pread(seq_fd
, seqbuf
, sizeof(seqbuf
) - 1, 0);
991 seqbuf
[seqlen
] = '\0';
992 if (seqbuf
[0] == '\n') {
993 /* seed file: write out seq ASAP */
994 xwrite_str(seq_fd
, seq
);
995 xlseek(seq_fd
, 0, SEEK_SET
);
996 dbg2("first seq written");
999 if (strcmp(seq
, seqbuf
) == 0) {
1004 dbg2("%s waiting for '%s'", curtime(), seqbuf
);
1007 if (sigtimedwait(&set_CHLD
, NULL
, &ts
) >= 0) {
1009 continue; /* don't decrement timeout! */
1011 if (--timeout
== 0) {
1012 dbg1("%s waiting for '%s'", "timed out", seqbuf
);
1016 sigprocmask(SIG_UNBLOCK
, &set_CHLD
, NULL
);
1020 static void signal_mdevs(unsigned my_pid
)
1022 procps_status_t
* p
= NULL
;
1023 while ((p
= procps_scan(p
, PSSCAN_ARGV0
)) != NULL
) {
1024 if (p
->pid
!= my_pid
1026 && strcmp(bb_basename(p
->argv0
), "mdev") == 0
1028 kill(p
->pid
, SIGCHLD
);
1033 int mdev_main(int argc
, char **argv
) MAIN_EXTERNALLY_VISIBLE
;
1034 int mdev_main(int argc UNUSED_PARAM
, char **argv
)
1036 RESERVE_CONFIG_BUFFER(temp
, PATH_MAX
+ SCRATCH_SIZE
);
1040 #if ENABLE_FEATURE_MDEV_CONF
1041 G
.filename
= "/etc/mdev.conf";
1044 /* We can be called as hotplug helper */
1045 /* Kernel cannot provide suitable stdio fds for us, do it ourself */
1046 bb_sanitize_stdio();
1048 /* Force the configuration file settings exactly */
1053 if (argv
[1] && strcmp(argv
[1], "-s") == 0) {
1059 #if ENABLE_FEATURE_MDEV_CONF
1060 /* Same as xrealloc_vector(NULL, 4, 0): */
1061 G
.rule_vec
= xzalloc((1 << 4) * sizeof(*G
.rule_vec
));
1064 G
.root_major
= major(st
.st_dev
);
1065 G
.root_minor
= minor(st
.st_dev
);
1067 putenv((char*)"ACTION=add");
1069 /* ACTION_FOLLOWLINKS is needed since in newer kernels
1070 * /sys/block/loop* (for example) are symlinks to dirs,
1071 * not real directories.
1072 * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
1073 * but we can't enforce that on users)
1075 if (access("/sys/class/block", F_OK
) != 0) {
1076 /* Scan obsolete /sys/block only if /sys/class/block
1077 * doesn't exist. Otherwise we'll have dupes.
1078 * Also, do not complain if it doesn't exist.
1079 * Some people configure kernel to have no blockdevs.
1081 recursive_action("/sys/block",
1082 ACTION_RECURSE
| ACTION_FOLLOWLINKS
| ACTION_QUIET
,
1083 fileAction
, dirAction
, temp
, 0);
1085 recursive_action("/sys/class",
1086 ACTION_RECURSE
| ACTION_FOLLOWLINKS
,
1087 fileAction
, dirAction
, temp
, 0);
1099 * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
1100 * ACTION can be "add", "remove", "change"
1101 * DEVPATH is like "/block/sda" or "/class/input/mice"
1103 action
= getenv("ACTION");
1104 op
= index_in_strings(keywords
, action
);
1105 env_devname
= getenv("DEVNAME"); /* can be NULL */
1106 env_devpath
= getenv("DEVPATH");
1107 G
.subsystem
= getenv("SUBSYSTEM");
1108 if (!action
|| !env_devpath
/*|| !G.subsystem*/)
1110 fw
= getenv("FIRMWARE");
1111 seq
= getenv("SEQNUM");
1114 open_mdev_log(seq
, my_pid
);
1116 seq_fd
= seq
? wait_for_seqfile(seq
) : -1;
1119 "ACTION:%s SUBSYSTEM:%s DEVNAME:%s DEVPATH:%s"
1122 action
, G
.subsystem
, env_devname
, env_devpath
,
1123 fw
? " FW:" : "", fw
? fw
: ""
1126 snprintf(temp
, PATH_MAX
, "/sys%s", env_devpath
);
1127 if (op
== OP_remove
) {
1128 /* Ignoring "remove firmware". It was reported
1129 * to happen and to cause erroneous deletion
1130 * of device nodes. */
1132 make_device(env_devname
, temp
, op
);
1135 make_device(env_devname
, temp
, op
);
1136 if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE
) {
1137 if (op
== OP_add
&& fw
)
1138 load_firmware(fw
, temp
);
1142 dbg1("%s exiting", curtime());
1144 xwrite_str(seq_fd
, utoa(xatou(seq
) + 1));
1145 signal_mdevs(my_pid
);
1149 if (ENABLE_FEATURE_CLEAN_UP
)
1150 RELEASE_CONFIG_BUFFER(temp
);
1152 return EXIT_SUCCESS
;