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.
11
//config: bool "mdev (17 kb)"
13
//config: select PLATFORM_LINUX
15
//config: mdev is a mini-udev implementation for dynamically creating device
16
//config: nodes in the /dev directory.
18
//config: For more information, please see docs/mdev.txt
20
//config:config FEATURE_MDEV_CONF
21
//config: bool "Support /etc/mdev.conf"
23
//config: depends on MDEV
25
//config: Add support for the mdev config file to control ownership and
26
//config: permissions of the device nodes.
28
//config: For more information, please see docs/mdev.txt
30
//config:config FEATURE_MDEV_RENAME
31
//config: bool "Support subdirs/symlinks"
33
//config: depends on FEATURE_MDEV_CONF
35
//config: Add support for renaming devices and creating symlinks.
37
//config: For more information, please see docs/mdev.txt
39
//config:config FEATURE_MDEV_RENAME_REGEXP
40
//config: bool "Support regular expressions substitutions when renaming device"
42
//config: depends on FEATURE_MDEV_RENAME
44
//config: Add support for regular expressions substitutions when renaming
47
//config:config FEATURE_MDEV_EXEC
48
//config: bool "Support command execution at device addition/removal"
50
//config: depends on FEATURE_MDEV_CONF
52
//config: This adds support for an optional field to /etc/mdev.conf for
53
//config: executing commands when devices are created/removed.
55
//config: For more information, please see docs/mdev.txt
57
//config:config FEATURE_MDEV_LOAD_FIRMWARE
58
//config: bool "Support loading of firmware"
60
//config: depends on MDEV
62
//config: Some devices need to load firmware before they can be usable.
64
//config: These devices will request userspace look up the files in
65
//config: /lib/firmware/ and if it exists, send it to the kernel for
66
//config: loading into the hardware.
68
//applet:IF_MDEV(APPLET(mdev, BB_DIR_SBIN, BB_SUID_DROP))
70
//kbuild:lib-$(CONFIG_MDEV) += mdev.o
72
//usage:#define mdev_trivial_usage
74
//usage:#define mdev_full_usage "\n\n"
75
//usage: "mdev -s is to be run during boot to scan /sys and populate /dev.\n"
77
//usage: "Bare mdev is a kernel hotplug helper. To activate it:\n"
78
//usage: " echo /sbin/mdev >/proc/sys/kernel/hotplug\n"
79
//usage: IF_FEATURE_MDEV_CONF(
81
//usage: "It uses /etc/mdev.conf with lines\n"
82
//usage: " [-][ENV=regex;]...DEVNAME UID:GID PERM"
83
//usage: IF_FEATURE_MDEV_RENAME(" [>|=PATH]|[!]")
84
//usage: IF_FEATURE_MDEV_EXEC(" [@|$|*PROG]")
86
//usage: "where DEVNAME is device name regex, @major,minor[-minor2], or\n"
87
//usage: "environment variable regex. A common use of the latter is\n"
88
//usage: "to load modules for hotplugged devices:\n"
89
//usage: " $MODALIAS=.* 0:0 660 @modprobe \"$MODALIAS\"\n"
92
//usage: "If /dev/mdev.seq file exists, mdev will wait for its value\n"
93
//usage: "to match $SEQNUM variable. This prevents plug/unplug races.\n"
94
//usage: "To activate this feature, create empty /dev/mdev.seq at boot.\n"
96
//usage: "If /dev/mdev.log file exists, debug log will be appended to it."
99
#include "common_bufsiz.h"
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("HH:MM:SS.123456")];
288
#define G (*(struct globals*)bb_common_bufsiz1)
289
#define INIT_G() do { \
290
setup_common_bufsiz(); \
291
IF_NOT_FEATURE_MDEV_CONF(G.cur_rule.maj = -1;) \
292
IF_NOT_FEATURE_MDEV_CONF(G.cur_rule.mode = 0660;) \
296
/* Prevent infinite loops in /sys symlinks */
297
#define MAX_SYSFS_DEPTH 3
299
/* We use additional bytes in make_device() */
300
#define SCRATCH_SIZE 128
302
#if ENABLE_FEATURE_MDEV_CONF
304
static void make_default_cur_rule(void)
306
memset(&G.cur_rule, 0, sizeof(G.cur_rule));
307
G.cur_rule.maj = -1; /* "not a @major,minor rule" */
308
G.cur_rule.mode = 0660;
311
static void clean_up_cur_rule(void)
315
free(G.cur_rule.envvar);
316
free(G.cur_rule.ren_mov);
317
if (G.cur_rule.regex_compiled)
318
regfree(&G.cur_rule.match);
319
IF_FEATURE_MDEV_EXEC(free(G.cur_rule.r_cmd);)
320
e = G.cur_rule.envmatch;
326
make_default_cur_rule();
329
static char *parse_envmatch_pfx(char *val)
331
struct envmatch **nextp = &G.cur_rule.envmatch;
336
char *eq = strchr(val, '=');
337
if (!eq /* || eq == val? */)
339
if (endofname(val) != eq)
341
semicolon = strchr(eq, ';');
344
/* ENVVAR=regex;... */
345
*nextp = e = xzalloc(sizeof(*e));
347
e->envname = xstrndup(val, eq - val);
349
xregcomp(&e->match, eq + 1, REG_EXTENDED);
355
static void parse_next_rule(void)
357
/* Note: on entry, G.cur_rule is set to default */
362
/* No PARSE_EOL_COMMENTS, because command may contain '#' chars */
363
if (!config_read(G.parser, tokens, 4, 3, "# \t", PARSE_NORMAL & ~PARSE_EOL_COMMENTS))
366
/* Fields: [-]regex uid:gid mode [alias] [cmd] */
367
dbg3("token1:'%s'", tokens[1]);
371
G.cur_rule.keep_matching = ('-' == val[0]);
372
val += G.cur_rule.keep_matching; /* swallow leading dash */
373
val = parse_envmatch_pfx(val);
375
/* @major,minor[-minor2] */
376
/* (useful when name is ambiguous:
377
* "/sys/class/usb/lp0" and
378
* "/sys/class/printer/lp0")
380
int sc = sscanf(val, "@%u,%u-%u", &G.cur_rule.maj, &G.cur_rule.min0, &G.cur_rule.min1);
381
if (sc < 2 || G.cur_rule.maj < 0) {
382
bb_error_msg("bad @maj,min on line %d", G.parser->lineno);
386
G.cur_rule.min1 = G.cur_rule.min0;
388
char *eq = strchr(val, '=');
390
/* $ENVVAR=regex ... */
393
bb_error_msg("bad $envvar=regex on line %d", G.parser->lineno);
396
G.cur_rule.envvar = xstrndup(val, eq - val);
399
xregcomp(&G.cur_rule.match, val, REG_EXTENDED);
400
G.cur_rule.regex_compiled = 1;
403
/* 2nd field: uid:gid - device ownership */
404
if (get_uidgid(&G.cur_rule.ugid, tokens[1]) == 0) {
405
bb_error_msg("unknown user/group '%s' on line %d", tokens[1], G.parser->lineno);
409
/* 3rd field: mode - device permissions */
410
G.cur_rule.mode = bb_parse_mode(tokens[2], G.cur_rule.mode);
412
/* 4th field (opt): ">|=alias" or "!" to not create the node */
414
if (ENABLE_FEATURE_MDEV_RENAME && val && strchr(">=!", val[0])) {
415
char *s = skip_non_whitespace(val);
416
G.cur_rule.ren_mov = xstrndup(val, s - val);
417
val = skip_whitespace(s);
420
if (ENABLE_FEATURE_MDEV_EXEC && val && val[0]) {
421
const char *s = "$@*";
422
const char *s2 = strchr(s, val[0]);
424
bb_error_msg("bad line %u", G.parser->lineno);
427
IF_FEATURE_MDEV_EXEC(G.cur_rule.r_cmd = xstrdup(val);)
433
} /* while (config_read) */
435
dbg3("config_close(G.parser)");
436
config_close(G.parser);
442
/* If mdev -s, we remember rules in G.rule_vec[].
443
* Otherwise, there is no point in doing it, and we just
444
* save only one parsed rule in G.cur_rule.
446
static const struct rule *next_rule(void)
450
/* Open conf file if we didn't do it yet */
451
if (!G.parser && G.filename) {
452
dbg3("config_open('%s')", G.filename);
453
G.parser = config_open2(G.filename, fopen_for_read);
459
/* Do we have rule parsed already? */
460
if (G.rule_vec[G.rule_idx]) {
461
dbg3("< G.rule_vec[G.rule_idx:%d]=%p", G.rule_idx, G.rule_vec[G.rule_idx]);
462
return G.rule_vec[G.rule_idx++];
464
make_default_cur_rule();
470
/* Parse one more rule if file isn't fully read */
474
if (G.rule_vec) { /* mdev -s */
475
rule = xmemdup(&G.cur_rule, sizeof(G.cur_rule));
476
G.rule_vec = xrealloc_vector(G.rule_vec, 4, G.rule_idx);
477
G.rule_vec[G.rule_idx++] = rule;
478
dbg3("> G.rule_vec[G.rule_idx:%d]=%p", G.rule_idx, G.rule_vec[G.rule_idx]);
485
static int env_matches(struct envmatch *e)
489
char *val = getenv(e->envname);
492
r = regexec(&e->match, val, /*size*/ 0, /*range[]*/ NULL, /*eflags*/ 0);
493
if (r != 0) /* no match */
502
# define next_rule() (&G.cur_rule)
506
static void mkdir_recursive(char *name)
508
/* if name has many levels ("dir1/dir2"),
509
* bb_make_directory() will create dir1 according to umask,
510
* not according to its "mode" parameter.
511
* Since we run with umask=0, need to temporarily switch it.
513
umask(022); /* "dir1" (if any) will be 0755 too */
514
bb_make_directory(name, 0755, FILEUTILS_RECUR);
518
/* Builds an alias path.
519
* This function potentionally reallocates the alias parameter.
520
* Only used for ENABLE_FEATURE_MDEV_RENAME
522
static char *build_alias(char *alias, const char *device_name)
526
/* ">bar/": rename to bar/device_name */
527
/* ">bar[/]baz": rename to bar[/]baz */
528
dest = strrchr(alias, '/');
529
if (dest) { /* ">bar/[baz]" ? */
530
*dest = '\0'; /* mkdir bar */
531
mkdir_recursive(alias);
533
if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
535
alias = concat_path_file(alias, device_name);
543
/* mknod in /dev based on a path like "/sys/block/hda/hda1"
544
* NB1: path parameter needs to have SCRATCH_SIZE scratch bytes
545
* after NUL, but we promise to not mangle it (IOW: to restore NUL if needed).
546
* NB2: "mdev -s" may call us many times, do not leak memory/fds!
548
* device_name = $DEVNAME (may be NULL)
549
* path = /sys/$DEVPATH
551
static void make_device(char *device_name, char *path, int operation)
553
int major, minor, type, len;
554
char *path_end = path + strlen(path);
556
/* Try to read major/minor string. Note that the kernel puts \n after
557
* the data, so we don't need to worry about null terminating the string
558
* because sscanf() will stop at the first nondigit, which \n is.
559
* We also depend on path having writeable space after it.
562
if (operation == OP_add) {
563
strcpy(path_end, "/dev");
564
len = open_read_close(path, path_end + 1, SCRATCH_SIZE - 1);
567
if (!ENABLE_FEATURE_MDEV_EXEC)
569
/* no "dev" file, but we can still run scripts
570
* based on device name */
571
} else if (sscanf(path_end + 1, "%u:%u", &major, &minor) == 2) {
572
dbg1("dev %u,%u", major, minor);
577
/* else: for delete, -1 still deletes the node, but < -1 suppresses that */
579
/* Determine device name */
582
* There was no $DEVNAME envvar (for example, mdev -s never has).
583
* But it is very useful: it contains the *path*, not only basename,
584
* Thankfully, uevent file has it.
585
* Example of .../sound/card0/controlC0/uevent file on Linux-3.7.7:
588
* DEVNAME=snd/controlC0
590
strcpy(path_end, "/uevent");
591
len = open_read_close(path, path_end + 1, SCRATCH_SIZE - 1);
595
path_end[1 + len] = '\0';
596
device_name = strstr(path_end + 1, "\nDEVNAME=");
598
device_name += sizeof("\nDEVNAME=")-1;
599
strchrnul(device_name, '\n')[0] = '\0';
601
/* Fall back to just basename */
602
device_name = (char*) bb_basename(path);
605
/* Determine device type */
607
* http://kernel.org/doc/pending/hotplug.txt says that only
608
* "/sys/block/..." is for block devices. "/sys/bus" etc is not.
609
* But since 2.6.25 block devices are also in /sys/class/block.
610
* We use strstr("/block/") to forestall future surprises.
613
if (strstr(path, "/block/") || (G.subsystem && is_prefixed_with(G.subsystem, "block")))
616
#if ENABLE_FEATURE_MDEV_CONF
617
G.rule_idx = 0; /* restart from the beginning (think mdev -s) */
620
const char *str_to_match;
621
regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
624
char aliaslink = aliaslink; /* for compiler */
626
const struct rule *rule;
628
str_to_match = device_name;
632
#if ENABLE_FEATURE_MDEV_CONF
633
if (!env_matches(rule->envmatch))
635
if (rule->maj >= 0) { /* @maj,min rule */
636
if (major != rule->maj)
638
if (minor < rule->min0 || minor > rule->min1)
640
memset(off, 0, sizeof(off));
643
if (rule->envvar) { /* $envvar=regex rule */
644
str_to_match = getenv(rule->envvar);
645
dbg3("getenv('%s'):'%s'", rule->envvar, str_to_match);
649
/* else: str_to_match = device_name */
651
if (rule->regex_compiled) {
652
int regex_match = regexec(&rule->match, str_to_match, ARRAY_SIZE(off), off, 0);
653
dbg3("regex_match for '%s':%d", str_to_match, regex_match);
654
//bb_error_msg("matches:");
655
//for (int i = 0; i < ARRAY_SIZE(off); i++) {
656
// if (off[i].rm_so < 0) continue;
657
// bb_error_msg("match %d: '%.*s'\n", i,
658
// (int)(off[i].rm_eo - off[i].rm_so),
659
// device_name + off[i].rm_so);
663
/* regexec returns whole pattern as "range" 0 */
665
|| (int)off[0].rm_eo != (int)strlen(str_to_match)
667
continue; /* this rule doesn't match */
670
/* else: it's final implicit "match-all" rule */
672
dbg2("rule matched, line %d", G.parser ? G.parser->lineno : -1);
674
/* Build alias name */
676
if (ENABLE_FEATURE_MDEV_RENAME && rule->ren_mov) {
677
aliaslink = rule->ren_mov[0];
678
if (aliaslink == '!') {
679
/* "!": suppress node creation/deletion */
682
else if (aliaslink == '>' || aliaslink == '=') {
683
if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
688
/* substitute %1..9 with off[1..9], if any */
695
p = alias = xzalloc(strlen(rule->ren_mov) + n * strlen(str_to_match));
696
s = rule->ren_mov + 1;
700
unsigned i = (s[1] - '0');
701
if (i <= 9 && off[i].rm_so >= 0) {
702
n = off[i].rm_eo - off[i].rm_so;
703
strncpy(p, str_to_match + off[i].rm_so, n);
712
alias = xstrdup(rule->ren_mov + 1);
716
dbg3("alias:'%s'", alias);
719
IF_FEATURE_MDEV_EXEC(command = rule->r_cmd;)
721
/* Are we running this command now?
722
* Run @cmd on create, $cmd on delete, *cmd on any
724
if ((command[0] == '@' && operation == OP_add)
725
|| (command[0] == '$' && operation == OP_remove)
726
|| (command[0] == '*')
733
dbg3("command:'%s'", command);
735
/* "Execute" the line we found */
736
node_name = device_name;
737
if (ENABLE_FEATURE_MDEV_RENAME && alias) {
738
node_name = alias = build_alias(alias, device_name);
739
dbg3("alias2:'%s'", alias);
742
if (operation == OP_add && major >= 0) {
743
char *slash = strrchr(node_name, '/');
746
mkdir_recursive(node_name);
749
if (ENABLE_FEATURE_MDEV_CONF) {
750
dbg1("mknod %s (%d,%d) %o"
752
node_name, major, minor, rule->mode | type,
753
rule->ugid.uid, rule->ugid.gid
756
dbg1("mknod %s (%d,%d) %o",
757
node_name, major, minor, rule->mode | type
760
if (mknod(node_name, rule->mode | type, makedev(major, minor)) && errno != EEXIST)
761
bb_perror_msg("can't create '%s'", node_name);
762
if (ENABLE_FEATURE_MDEV_CONF) {
763
chmod(node_name, rule->mode);
764
chown(node_name, rule->ugid.uid, rule->ugid.gid);
766
if (major == G.root_major && minor == G.root_minor)
767
symlink(node_name, "root");
768
if (ENABLE_FEATURE_MDEV_RENAME && alias) {
769
if (aliaslink == '>') {
770
//TODO: on devtmpfs, device_name already exists and symlink() fails.
771
//End result is that instead of symlink, we have two nodes.
772
//What should be done?
773
dbg1("symlink: %s", device_name);
774
symlink(node_name, device_name);
779
if (ENABLE_FEATURE_MDEV_EXEC && command) {
780
/* setenv will leak memory, use putenv/unsetenv/free */
781
char *s = xasprintf("%s=%s", "MDEV", node_name);
783
dbg1("running: %s", command);
784
if (system(command) == -1)
785
bb_perror_msg("can't run '%s'", command);
786
bb_unsetenv_and_free(s);
789
if (operation == OP_remove && major >= -1) {
790
if (ENABLE_FEATURE_MDEV_RENAME && alias) {
791
if (aliaslink == '>') {
792
dbg1("unlink: %s", device_name);
796
dbg1("unlink: %s", node_name);
800
if (ENABLE_FEATURE_MDEV_RENAME)
803
/* We found matching line.
804
* Stop unless it was prefixed with '-'
806
if (!ENABLE_FEATURE_MDEV_CONF || !rule->keep_matching)
811
static ssize_t readlink2(char *buf, size_t bufsize)
814
// "passing argument 2 to restrict-qualified parameter aliases with argument 1"
815
// dance around that...
816
char *obuf FIX_ALIASING;
818
return readlink(buf, obuf, bufsize);
821
/* File callback for /sys/ traversal.
822
* We act only on "/sys/.../dev" (pseudo)file
824
static int FAST_FUNC fileAction(const char *fileName,
825
struct stat *statbuf UNUSED_PARAM,
827
int depth UNUSED_PARAM)
829
size_t len = strlen(fileName) - 4; /* can't underflow */
830
char *path = userData; /* char array[PATH_MAX + SCRATCH_SIZE] */
831
char subsys[PATH_MAX];
834
/* Is it a ".../dev" file? (len check is for paranoid reasons) */
835
if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX - 32)
836
return FALSE; /* not .../dev */
838
strcpy(path, fileName);
841
/* Read ".../subsystem" symlink in the same directory where ".../dev" is */
842
strcpy(subsys, path);
843
strcpy(subsys + len, "/subsystem");
844
res = readlink2(subsys, sizeof(subsys)-1);
849
bb_unsetenv_and_free(G.subsys_env);
852
/* Set G.subsystem and $SUBSYSTEM from symlink's last component */
853
G.subsystem = strrchr(subsys, '/');
855
G.subsystem = xstrdup(G.subsystem + 1);
856
G.subsys_env = xasprintf("%s=%s", "SUBSYSTEM", G.subsystem);
857
putenv(G.subsys_env);
861
make_device(/*DEVNAME:*/ NULL, path, OP_add);
866
/* Directory callback for /sys/ traversal */
867
static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
868
struct stat *statbuf UNUSED_PARAM,
869
void *userData UNUSED_PARAM,
872
return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
875
/* For the full gory details, see linux/Documentation/firmware_class/README
877
* Firmware loading works like this:
878
* - kernel sets FIRMWARE env var
879
* - userspace checks /lib/firmware/$FIRMWARE
880
* - userspace waits for /sys/$DEVPATH/loading to appear
881
* - userspace writes "1" to /sys/$DEVPATH/loading
882
* - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
883
* - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
884
* - kernel loads firmware into device
886
static void load_firmware(const char *firmware, const char *sysfs_path)
889
int firmware_fd, loading_fd;
891
/* check for /lib/firmware/$FIRMWARE */
893
if (chdir("/lib/firmware") == 0)
894
firmware_fd = open(firmware, O_RDONLY); /* can fail */
896
/* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
898
for (cnt = 0; cnt < 30; ++cnt) {
899
loading_fd = open("loading", O_WRONLY);
908
if (firmware_fd >= 0) {
911
/* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
912
if (full_write(loading_fd, "1", 1) != 1)
915
/* load firmware into /sys/$DEVPATH/data */
916
data_fd = open("data", O_WRONLY);
919
cnt = bb_copyfd_eof(firmware_fd, data_fd);
920
if (ENABLE_FEATURE_CLEAN_UP)
924
/* Tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading"
925
* Note: we emit -1 also if firmware file wasn't found.
926
* There are cases when otherwise kernel would wait for minutes
930
full_write(loading_fd, "0", 1);
932
full_write(loading_fd, "-1", 2);
936
if (ENABLE_FEATURE_CLEAN_UP) {
942
static char *curtime(void)
945
gettimeofday(&tv, NULL);
947
strftime_HHMMSS(G.timestr, sizeof(G.timestr), &tv.tv_sec),
954
static void open_mdev_log(const char *seq, unsigned my_pid)
956
int logfd = open("mdev.log", O_WRONLY | O_APPEND);
958
xmove_fd(logfd, STDERR_FILENO);
960
applet_name = xasprintf("%s[%s]", applet_name, seq ? seq : utoa(my_pid));
964
/* If it exists, does /dev/mdev.seq match $SEQNUM?
965
* If it does not match, earlier mdev is running
966
* in parallel, and we need to wait.
967
* Active mdev pokes us with SIGCHLD to check the new file.
970
wait_for_seqfile(unsigned expected_seq)
972
/* We time out after 2 sec */
973
static const struct timespec ts = { 0, 32*1000*1000 };
974
int timeout = 2000 / 32;
979
sigemptyset(&set_CHLD);
980
sigaddset(&set_CHLD, SIGCHLD);
981
sigprocmask(SIG_BLOCK, &set_CHLD, NULL);
985
char seqbuf[sizeof(long)*3 + 2];
989
seq_fd = open("mdev.seq", O_RDWR);
992
close_on_exec_on(seq_fd);
994
seqlen = pread(seq_fd, seqbuf, sizeof(seqbuf) - 1, 0);
1000
seqbuf[seqlen] = '\0';
1001
if (seqbuf[0] == '\n' || seqbuf[0] == '\0') {
1002
/* seed file: write out seq ASAP */
1003
xwrite_str(seq_fd, utoa(expected_seq));
1004
xlseek(seq_fd, 0, SEEK_SET);
1005
dbg2("first seq written");
1008
seqbufnum = atoll(seqbuf);
1009
if (seqbufnum == expected_seq) {
1013
if (seqbufnum > expected_seq) {
1014
/* a later mdev runs already (this was seen by users to happen) */
1015
/* do not overwrite seqfile on exit */
1021
dbg2("%s mdev.seq='%s', need '%u'", curtime(), seqbuf, expected_seq);
1024
if (sigtimedwait(&set_CHLD, NULL, &ts) >= 0) {
1026
continue; /* don't decrement timeout! */
1028
if (--timeout == 0) {
1029
dbg1("%s mdev.seq='%s'", "timed out", seqbuf);
1033
sigprocmask(SIG_UNBLOCK, &set_CHLD, NULL);
1037
static void signal_mdevs(unsigned my_pid)
1039
procps_status_t* p = NULL;
1040
while ((p = procps_scan(p, PSSCAN_ARGV0)) != NULL) {
1041
if (p->pid != my_pid
1043
&& strcmp(bb_basename(p->argv0), "mdev") == 0
1045
kill(p->pid, SIGCHLD);
1050
int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
1051
int mdev_main(int argc UNUSED_PARAM, char **argv)
1053
RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
1057
#if ENABLE_FEATURE_MDEV_CONF
1058
G.filename = "/etc/mdev.conf";
1061
/* We can be called as hotplug helper */
1062
/* Kernel cannot provide suitable stdio fds for us, do it ourself */
1063
bb_sanitize_stdio();
1065
/* Force the configuration file settings exactly */
1070
if (argv[1] && strcmp(argv[1], "-s") == 0) {
1076
#if ENABLE_FEATURE_MDEV_CONF
1077
/* Same as xrealloc_vector(NULL, 4, 0): */
1078
G.rule_vec = xzalloc((1 << 4) * sizeof(*G.rule_vec));
1081
G.root_major = major(st.st_dev);
1082
G.root_minor = minor(st.st_dev);
1084
putenv((char*)"ACTION=add");
1086
/* Create all devices from /sys/dev hierarchy */
1087
recursive_action("/sys/dev",
1088
ACTION_RECURSE | ACTION_FOLLOWLINKS,
1089
fileAction, dirAction, temp, 0);
1097
unsigned seqnum = seqnum; /* for compiler */
1102
* env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
1103
* ACTION can be "add", "remove", "change"
1104
* DEVPATH is like "/block/sda" or "/class/input/mice"
1106
env_devname = getenv("DEVNAME"); /* can be NULL */
1107
G.subsystem = getenv("SUBSYSTEM");
1108
action = getenv("ACTION");
1109
env_devpath = getenv("DEVPATH");
1110
if (!action || !env_devpath /*|| !G.subsystem*/)
1112
fw = getenv("FIRMWARE");
1113
seq = getenv("SEQNUM");
1114
op = index_in_strings(keywords, action);
1117
open_mdev_log(seq, my_pid);
1121
seqnum = atoll(seq);
1122
seq_fd = wait_for_seqfile(seqnum);
1126
"ACTION:%s SUBSYSTEM:%s DEVNAME:%s DEVPATH:%s"
1129
action, G.subsystem, env_devname, env_devpath,
1130
fw ? " FW:" : "", fw ? fw : ""
1133
snprintf(temp, PATH_MAX, "/sys%s", env_devpath);
1134
if (op == OP_remove) {
1135
/* Ignoring "remove firmware". It was reported
1136
* to happen and to cause erroneous deletion
1137
* of device nodes. */
1139
make_device(env_devname, temp, op);
1142
make_device(env_devname, temp, op);
1143
if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
1144
if (op == OP_add && fw)
1145
load_firmware(fw, temp);
1149
dbg1("%s exiting", curtime());
1151
xwrite_str(seq_fd, utoa(seqnum + 1));
1152
signal_mdevs(my_pid);
1156
if (ENABLE_FEATURE_CLEAN_UP)
1157
RELEASE_CONFIG_BUFFER(temp);
1159
return EXIT_SUCCESS;