1 /* vi: set sw=4 ts=4: */
4 * mdev - Mini udev for busybox
6 * Copyright 2005 Rob Landley <rob@landley.net>
7 * Copyright 2005 Frank Sorenson <frank@tuxrocks.com>
9 * Licensed under GPL version 2, see file LICENSE in this tarball for details.
16 int root_major, root_minor;
18 #define G (*(struct globals*)&bb_common_bufsiz1)
19 #define root_major (G.root_major)
20 #define root_minor (G.root_minor)
22 /* Prevent infinite loops in /sys symlinks */
23 #define MAX_SYSFS_DEPTH 3
25 /* We use additional 64+ bytes in make_device() */
26 #define SCRATCH_SIZE 80
28 #if ENABLE_FEATURE_MDEV_RENAME
29 /* Builds an alias path.
30 * This function potentionally reallocates the alias parameter.
32 static char *build_alias(char *alias, const char *device_name)
36 /* ">bar/": rename to bar/device_name */
37 /* ">bar[/]baz": rename to bar[/]baz */
38 dest = strrchr(alias, '/');
39 if (dest) { /* ">bar/[baz]" ? */
40 *dest = '\0'; /* mkdir bar */
41 bb_make_directory(alias, 0755, FILEUTILS_RECUR);
43 if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
45 alias = concat_path_file(alias, device_name);
54 /* mknod in /dev based on a path like "/sys/block/hda/hda1" */
55 /* NB: "mdev -s" may call us many times, do not leak memory/fds! */
56 static void make_device(char *path, int delete)
58 const char *device_name;
59 int major, minor, type, len;
61 #if ENABLE_FEATURE_MDEV_CONF
62 struct bb_uidgid_t ugid = { 0, 0 };
66 #if ENABLE_FEATURE_MDEV_EXEC
69 #if ENABLE_FEATURE_MDEV_RENAME
71 char aliaslink = aliaslink; /* for compiler */
73 char *dev_maj_min = path + strlen(path);
75 /* Force the configuration file settings exactly. */
78 /* Try to read major/minor string. Note that the kernel puts \n after
79 * the data, so we don't need to worry about null terminating the string
80 * because sscanf() will stop at the first nondigit, which \n is.
81 * We also depend on path having writeable space after it.
85 strcpy(dev_maj_min, "/dev");
86 len = open_read_close(path, dev_maj_min + 1, 64);
87 *dev_maj_min++ = '\0';
89 if (!ENABLE_FEATURE_MDEV_EXEC)
91 /* no "dev" file, so just try to run script */
93 } else if (sscanf(dev_maj_min, "%u:%u", &major, &minor) != 2) {
98 /* Determine device name, type, major and minor */
99 device_name = bb_basename(path);
100 /* http://kernel.org/doc/pending/hotplug.txt says that only
101 * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
102 * But since 2.6.25 block devices are also in /sys/class/block.
103 * We use strstr("/block/") to forestall future surprises. */
105 if (strstr(path, "/block/"))
108 #if ENABLE_FEATURE_MDEV_CONF
109 parser = config_open2("/etc/mdev.conf", fopen_for_read);
111 /* If we have config file, look up user settings */
112 while (config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL)) {
113 regmatch_t off[1 + 9*ENABLE_FEATURE_MDEV_RENAME_REGEXP];
116 /* Fields: regex uid:gid mode [alias] [cmd] */
118 /* 1st field: @<numeric maj,min>... */
119 if (tokens[0][0] == '@') {
120 /* @major,minor[-last] */
121 /* (useful when name is ambiguous:
122 * "/sys/class/usb/lp0" and
123 * "/sys/class/printer/lp0") */
124 int cmaj, cmin0, cmin1, sc;
126 continue; /* no dev, no match */
127 sc = sscanf(tokens[0], "@%u,%u-%u", &cmaj, &cmin0, &cmin1);
128 if (sc < 1 || major != cmaj
129 || (sc == 2 && minor != cmin0)
130 || (sc == 3 && (minor < cmin0 || minor > cmin1))
132 continue; /* no match */
134 } else { /* ... or regex to match device name */
139 xregcomp(&match, tokens[0], REG_EXTENDED);
140 result = regexec(&match, device_name, ARRAY_SIZE(off), off, 0);
143 //bb_error_msg("matches:");
144 //for (int i = 0; i < ARRAY_SIZE(off); i++) {
145 // if (off[i].rm_so < 0) continue;
146 // bb_error_msg("match %d: '%.*s'\n", i,
147 // (int)(off[i].rm_eo - off[i].rm_so),
148 // device_name + off[i].rm_so);
151 /* If not this device, skip rest of line */
152 /* (regexec returns whole pattern as "range" 0) */
153 if (result || off[0].rm_so
154 || ((int)off[0].rm_eo != (int)strlen(device_name))
160 /* This line matches: stop parsing the file
161 * after parsing the rest of fields */
163 /* 2nd field: uid:gid - device ownership */
164 parse_chown_usergroup_or_die(&ugid, tokens[1]);
166 /* 3rd field: mode - device permissions */
167 mode = strtoul(tokens[2], NULL, 8);
170 /* 4th field (opt): >alias */
171 #if ENABLE_FEATURE_MDEV_RENAME
175 if (aliaslink == '>' || aliaslink == '=') {
177 #if ENABLE_FEATURE_MDEV_RENAME_REGEXP
182 s = strchrnul(val, ' ');
183 val = (s[0] && s[1]) ? s+1 : NULL;
185 #if ENABLE_FEATURE_MDEV_RENAME_REGEXP
186 /* substitute %1..9 with off[1..9], if any */
193 p = alias = xzalloc(strlen(a) + n * strlen(device_name));
199 if (i <= 9 && off[i].rm_so >= 0) {
200 n = off[i].rm_eo - off[i].rm_so;
201 strncpy(p, device_name + off[i].rm_so, n);
210 alias = xstrdup(a + 1);
213 #endif /* ENABLE_FEATURE_MDEV_RENAME */
215 #if ENABLE_FEATURE_MDEV_EXEC
216 /* The rest (opt): command to run */
220 const char *s = "@$*";
221 const char *s2 = strchr(s, *val);
224 bb_error_msg_and_die("bad line %u", parser->lineno);
226 /* Correlate the position in the "@$*" with the delete
227 * step so that we get the proper behavior:
228 * @cmd: run on create
229 * $cmd: run on delete
232 if ((s2 - s + 1) /*1/2/3*/ & /*1/2*/ (1 + delete)) {
233 command = xstrdup(val + 1);
237 /* end of field parsing */
238 break; /* we found matching line, stop */
239 } /* end of "while line is read from /etc/mdev.conf" */
241 config_close(parser);
242 #endif /* ENABLE_FEATURE_MDEV_CONF */
244 if (!delete && major >= 0) {
246 if (ENABLE_FEATURE_MDEV_RENAME)
249 if (mknod(device_name, mode | type, makedev(major, minor)) && errno != EEXIST)
250 bb_perror_msg_and_die("mknod %s", device_name);
252 if (major == root_major && minor == root_minor)
253 symlink(device_name, "root");
255 #if ENABLE_FEATURE_MDEV_CONF
256 chown(device_name, ugid.uid, ugid.gid);
258 #if ENABLE_FEATURE_MDEV_RENAME
260 alias = build_alias(alias, device_name);
262 /* move the device, and optionally
263 * make a symlink to moved device node */
264 if (rename(device_name, alias) == 0 && aliaslink == '>')
265 symlink(alias, device_name);
273 #if ENABLE_FEATURE_MDEV_EXEC
275 /* setenv will leak memory, use putenv/unsetenv/free */
276 char *s = xasprintf("MDEV=%s", device_name);
278 if (system(command) == -1)
279 bb_perror_msg_and_die("can't run '%s'", command);
288 /* At creation time, device might have been moved
289 * and a symlink might have been created. Undo that. */
290 #if ENABLE_FEATURE_MDEV_RENAME
292 alias = build_alias(alias, device_name);
300 /* File callback for /sys/ traversal */
301 static int FAST_FUNC fileAction(const char *fileName,
302 struct stat *statbuf UNUSED_PARAM,
304 int depth UNUSED_PARAM)
306 size_t len = strlen(fileName) - 4; /* can't underflow */
307 char *scratch = userData;
309 /* len check is for paranoid reasons */
310 if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
313 strcpy(scratch, fileName);
315 make_device(scratch, 0);
320 /* Directory callback for /sys/ traversal */
321 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
322 struct stat *statbuf UNUSED_PARAM,
323 void *userData UNUSED_PARAM,
326 return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
329 /* For the full gory details, see linux/Documentation/firmware_class/README
331 * Firmware loading works like this:
332 * - kernel sets FIRMWARE env var
333 * - userspace checks /lib/firmware/$FIRMWARE
334 * - userspace waits for /sys/$DEVPATH/loading to appear
335 * - userspace writes "1" to /sys/$DEVPATH/loading
336 * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
337 * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
338 * - kernel loads firmware into device
340 static void load_firmware(const char *const firmware, const char *const sysfs_path)
343 int firmware_fd, loading_fd, data_fd;
345 /* check for /lib/firmware/$FIRMWARE */
346 xchdir("/lib/firmware");
347 firmware_fd = xopen(firmware, O_RDONLY);
349 /* in case we goto out ... */
352 /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
354 for (cnt = 0; cnt < 30; ++cnt) {
355 loading_fd = open("loading", O_WRONLY);
356 if (loading_fd != -1)
363 /* tell kernel we're loading by `echo 1 > /sys/$DEVPATH/loading` */
364 if (full_write(loading_fd, "1", 1) != 1)
367 /* load firmware by `cat /lib/firmware/$FIRMWARE > /sys/$DEVPATH/data */
368 data_fd = open("data", O_WRONLY);
371 cnt = bb_copyfd_eof(firmware_fd, data_fd);
373 /* tell kernel result by `echo [0|-1] > /sys/$DEVPATH/loading` */
375 full_write(loading_fd, "0", 1);
377 full_write(loading_fd, "-1", 2);
380 if (ENABLE_FEATURE_CLEAN_UP) {
387 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
388 int mdev_main(int argc UNUSED_PARAM, char **argv)
390 RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
392 /* We can be called as hotplug helper */
393 /* Kernel cannot provide suitable stdio fds for us, do it ourself */
398 /* Replace LOGFILE by other file or device name if you need */
399 #define LOGFILE "/dev/console"
400 /* Just making sure fd 0 is not closed,
401 * we don't really intend to read from it */
402 xmove_fd(xopen("/", O_RDONLY), STDIN_FILENO);
403 xmove_fd(xopen(LOGFILE, O_WRONLY|O_APPEND), STDOUT_FILENO);
404 xmove_fd(xopen(LOGFILE, O_WRONLY|O_APPEND), STDERR_FILENO);
409 if (argv[1] && !strcmp(argv[1], "-s")) {
416 root_major = major(st.st_dev);
417 root_minor = minor(st.st_dev);
419 /* ACTION_FOLLOWLINKS is needed since in newer kernels
420 * /sys/block/loop* (for example) are symlinks to dirs,
421 * not real directories.
422 * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
423 * but we can't enforce that on users)
425 if (access("/sys/class/block", F_OK) != 0) {
426 /* Scan obsolete /sys/block only if /sys/class/block
427 * doesn't exist. Otherwise we'll have dupes.
429 recursive_action("/sys/block",
430 ACTION_RECURSE | ACTION_FOLLOWLINKS,
431 // not needed now? | ACTION_QUIET
432 fileAction, dirAction, temp, 0);
434 recursive_action("/sys/class",
435 ACTION_RECURSE | ACTION_FOLLOWLINKS,
436 fileAction, dirAction, temp, 0);
441 char seqbuf[sizeof(int)*3 + 2];
442 int seqlen = seqlen; /* for compiler */
445 * env ACTION=... DEVPATH=... [SEQNUM=...] mdev
446 * ACTION can be "add" or "remove"
447 * DEVPATH is like "/block/sda" or "/class/input/mice"
449 action = getenv("ACTION");
450 env_path = getenv("DEVPATH");
451 if (!action || !env_path)
454 seq = getenv("SEQNUM");
456 int timeout = 2000 / 32;
458 seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf-1));
461 seqbuf[seqlen] = '\0';
462 if (seqbuf[0] == '\n' /* seed file? */
463 || strcmp(seq, seqbuf) == 0 /* correct idx? */
471 snprintf(temp, PATH_MAX, "/sys%s", env_path);
472 if (!strcmp(action, "remove"))
473 make_device(temp, 1);
474 else if (!strcmp(action, "add")) {
475 make_device(temp, 0);
477 if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
478 char *fw = getenv("FIRMWARE");
480 load_firmware(fw, temp);
484 if (seq && seqlen >= 0) {
485 xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
489 if (ENABLE_FEATURE_CLEAN_UP)
490 RELEASE_CONFIG_BUFFER(temp);