mdev: expand --help so that it's actually useful.
[platform/upstream/busybox.git] / util-linux / mdev.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * mdev - Mini udev for busybox
4  *
5  * Copyright 2005 Rob Landley <rob@landley.net>
6  * Copyright 2005 Frank Sorenson <frank@tuxrocks.com>
7  *
8  * Licensed under GPLv2, see file LICENSE in this source tree.
9  */
10
11 //config:config MDEV
12 //config:       bool "mdev"
13 //config:       default y
14 //config:       select PLATFORM_LINUX
15 //config:       help
16 //config:         mdev is a mini-udev implementation for dynamically creating device
17 //config:         nodes in the /dev directory.
18 //config:
19 //config:         For more information, please see docs/mdev.txt
20 //config:
21 //config:config FEATURE_MDEV_CONF
22 //config:       bool "Support /etc/mdev.conf"
23 //config:       default y
24 //config:       depends on MDEV
25 //config:       help
26 //config:         Add support for the mdev config file to control ownership and
27 //config:         permissions of the device nodes.
28 //config:
29 //config:         For more information, please see docs/mdev.txt
30 //config:
31 //config:config FEATURE_MDEV_RENAME
32 //config:       bool "Support subdirs/symlinks"
33 //config:       default y
34 //config:       depends on FEATURE_MDEV_CONF
35 //config:       help
36 //config:         Add support for renaming devices and creating symlinks.
37 //config:
38 //config:         For more information, please see docs/mdev.txt
39 //config:
40 //config:config FEATURE_MDEV_RENAME_REGEXP
41 //config:       bool "Support regular expressions substitutions when renaming device"
42 //config:       default y
43 //config:       depends on FEATURE_MDEV_RENAME
44 //config:       help
45 //config:         Add support for regular expressions substitutions when renaming
46 //config:         device.
47 //config:
48 //config:config FEATURE_MDEV_EXEC
49 //config:       bool "Support command execution at device addition/removal"
50 //config:       default y
51 //config:       depends on FEATURE_MDEV_CONF
52 //config:       help
53 //config:         This adds support for an optional field to /etc/mdev.conf for
54 //config:         executing commands when devices are created/removed.
55 //config:
56 //config:         For more information, please see docs/mdev.txt
57 //config:
58 //config:config FEATURE_MDEV_LOAD_FIRMWARE
59 //config:       bool "Support loading of firmwares"
60 //config:       default y
61 //config:       depends on MDEV
62 //config:       help
63 //config:         Some devices need to load firmware before they can be usable.
64 //config:
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.
68
69 //applet:IF_MDEV(APPLET(mdev, BB_DIR_SBIN, BB_SUID_DROP))
70
71 //kbuild:lib-$(CONFIG_MDEV) += mdev.o
72
73 //usage:#define mdev_trivial_usage
74 //usage:       "[-s]"
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"
77 //usage:       "\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(
81 //usage:       "\n"
82 //usage:       "It uses /etc/mdev.conf with lines\n"
83 //usage:       "        [-]DEVNAME UID:GID PERM"
84 //usage:                        IF_FEATURE_MDEV_RENAME(" [>|=PATH]|[!]")
85 //usage:                        IF_FEATURE_MDEV_EXEC(" [@|$|*PROG]")
86 //usage:       "\n"
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"
91 //usage:        )
92 //usage:       "\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."
96 //usage:
97 //usage:#define mdev_notes_usage ""
98 //usage:        IF_FEATURE_MDEV_CONFIG(
99 //usage:       "The mdev config file contains lines that look like:\n"
100 //usage:       "  hd[a-z][0-9]* 0:3 660\n\n"
101 //usage:       "That's device name (with regex match), uid:gid, and permissions.\n\n"
102 //usage:        IF_FEATURE_MDEV_EXEC(
103 //usage:       "Optionally, that can be followed (on the same line) by a special character\n"
104 //usage:       "and a command line to run after creating/before deleting the corresponding\n"
105 //usage:       "device(s). The environment variable $MDEV indicates the active device node\n"
106 //usage:       "(which is useful if it's a regex match). For example:\n\n"
107 //usage:       "  hdc root:cdrom 660  *ln -s $MDEV cdrom\n\n"
108 //usage:       "The special characters are @ (run after creating), $ (run before deleting),\n"
109 //usage:       "and * (run both after creating and before deleting). The commands run in\n"
110 //usage:       "the /dev directory, and use system() which calls /bin/sh.\n\n"
111 //usage:        )
112 //usage:       "Config file parsing stops on the first matching line. If no config\n"
113 //usage:       "entry is matched, devices are created with default 0:0 660. (Make\n"
114 //usage:       "the last line match .* to override this.)\n\n"
115 //usage:        )
116
117 #include "libbb.h"
118 #include "xregex.h"
119
120 /* "mdev -s" scans /sys/class/xxx, looking for directories which have dev
121  * file (it is of the form "M:m\n"). Example: /sys/class/tty/tty0/dev
122  * contains "4:0\n". Directory name is taken as device name, path component
123  * directly after /sys/class/ as subsystem. In this example, "tty0" and "tty".
124  * Then mdev creates the /dev/device_name node.
125  * If /sys/class/.../dev file does not exist, mdev still may act
126  * on this device: see "@|$|*command args..." parameter in config file.
127  *
128  * mdev w/o parameters is called as hotplug helper. It takes device
129  * and subsystem names from $DEVPATH and $SUBSYSTEM, extracts
130  * maj,min from "/sys/$DEVPATH/dev" and also examines
131  * $ACTION ("add"/"delete") and $FIRMWARE.
132  *
133  * If action is "add", mdev creates /dev/device_name similarly to mdev -s.
134  * (todo: explain "delete" and $FIRMWARE)
135  *
136  * If /etc/mdev.conf exists, it may modify /dev/device_name's properties.
137  * /etc/mdev.conf file format:
138  *
139  * [-][subsystem/]device  user:grp  mode  [>|=path]|[!] [@|$|*command args...]
140  * [-]@maj,min[-min2]     user:grp  mode  [>|=path]|[!] [@|$|*command args...]
141  * [-]$envvar=val         user:grp  mode  [>|=path]|[!] [@|$|*command args...]
142  *
143  * Leading minus in 1st field means "don't stop on this line", otherwise
144  * search is stopped after the matching line is encountered.
145  *
146  * The device name or "subsystem/device" combo is matched against 1st field
147  * (which is a regex), or maj,min is matched against 1st field,
148  * or specified environment variable (as regex) is matched against 1st field.
149  *
150  * $envvar=val format is useful for loading modules for hot-plugged devices
151  * which do not have driver loaded yet. In this case /sys/class/.../dev
152  * does not exist, but $MODALIAS is set to needed module's name
153  * (actually, an alias to it) by kernel. This rule instructs mdev
154  * to load the module and exit:
155  *    $MODALIAS=.* 0:0 660 @modprobe "$MODALIAS"
156  * The kernel will generate another hotplug event when /sys/class/.../dev
157  * file appears.
158  *
159  * When line matches, the device node is created, chmod'ed and chown'ed,
160  * moved to path, and if >path, a symlink to moved node is created,
161  * all this if /sys/class/.../dev exists.
162  *    Examples:
163  *    =loop/      - moves to /dev/loop
164  *    >disk/sda%1 - moves to /dev/disk/sdaN, makes /dev/sdaN a symlink
165  *
166  * Then "command args..." is executed (via sh -c 'command args...').
167  * @:execute on creation, $:on deletion, *:on both.
168  * This happens regardless of /sys/class/.../dev existence.
169  */
170
171 struct globals {
172         int root_major, root_minor;
173         char *subsystem;
174 } FIX_ALIASING;
175 #define G (*(struct globals*)&bb_common_bufsiz1)
176
177 /* Prevent infinite loops in /sys symlinks */
178 #define MAX_SYSFS_DEPTH 3
179
180 /* We use additional 64+ bytes in make_device() */
181 #define SCRATCH_SIZE 80
182
183 /* Builds an alias path.
184  * This function potentionally reallocates the alias parameter.
185  * Only used for ENABLE_FEATURE_MDEV_RENAME
186  */
187 static char *build_alias(char *alias, const char *device_name)
188 {
189         char *dest;
190
191         /* ">bar/": rename to bar/device_name */
192         /* ">bar[/]baz": rename to bar[/]baz */
193         dest = strrchr(alias, '/');
194         if (dest) { /* ">bar/[baz]" ? */
195                 *dest = '\0'; /* mkdir bar */
196                 bb_make_directory(alias, 0755, FILEUTILS_RECUR);
197                 *dest = '/';
198                 if (dest[1] == '\0') { /* ">bar/" => ">bar/device_name" */
199                         dest = alias;
200                         alias = concat_path_file(alias, device_name);
201                         free(dest);
202                 }
203         }
204
205         return alias;
206 }
207
208 /* mknod in /dev based on a path like "/sys/block/hda/hda1"
209  * NB1: path parameter needs to have SCRATCH_SIZE scratch bytes
210  * after NUL, but we promise to not mangle (IOW: to restore if needed)
211  * path string.
212  * NB2: "mdev -s" may call us many times, do not leak memory/fds!
213  */
214 static void make_device(char *path, int delete)
215 {
216         char *device_name, *subsystem_slash_devname;
217         int major, minor, type, len;
218         mode_t mode;
219         parser_t *parser;
220
221         /* Try to read major/minor string.  Note that the kernel puts \n after
222          * the data, so we don't need to worry about null terminating the string
223          * because sscanf() will stop at the first nondigit, which \n is.
224          * We also depend on path having writeable space after it.
225          */
226         major = -1;
227         if (!delete) {
228                 char *dev_maj_min = path + strlen(path);
229
230                 strcpy(dev_maj_min, "/dev");
231                 len = open_read_close(path, dev_maj_min + 1, 64);
232                 *dev_maj_min = '\0';
233                 if (len < 1) {
234                         if (!ENABLE_FEATURE_MDEV_EXEC)
235                                 return;
236                         /* no "dev" file, but we can still run scripts
237                          * based on device name */
238                 } else if (sscanf(++dev_maj_min, "%u:%u", &major, &minor) != 2) {
239                         major = -1;
240                 }
241         }
242         /* else: for delete, -1 still deletes the node, but < -1 suppresses that */
243
244         /* Determine device name, type, major and minor */
245         device_name = (char*) bb_basename(path);
246         /* http://kernel.org/doc/pending/hotplug.txt says that only
247          * "/sys/block/..." is for block devices. "/sys/bus" etc is not.
248          * But since 2.6.25 block devices are also in /sys/class/block.
249          * We use strstr("/block/") to forestall future surprises. */
250         type = S_IFCHR;
251         if (strstr(path, "/block/") || (G.subsystem && strncmp(G.subsystem, "block", 5) == 0))
252                 type = S_IFBLK;
253
254         /* Make path point to "subsystem/device_name" */
255         subsystem_slash_devname = NULL;
256         /* Check for coldplug invocations first */
257         if (strncmp(path, "/sys/block/", 11) == 0) /* legacy case */
258                 path += sizeof("/sys/") - 1;
259         else if (strncmp(path, "/sys/class/", 11) == 0)
260                 path += sizeof("/sys/class/") - 1;
261         else {
262                 /* Example of a hotplug invocation:
263                  * SUBSYSTEM="block"
264                  * DEVPATH="/sys" + "/devices/virtual/mtd/mtd3/mtdblock3"
265                  * ("/sys" is added by mdev_main)
266                  * - path does not contain subsystem
267                  */
268                 subsystem_slash_devname = concat_path_file(G.subsystem, device_name);
269                 path = subsystem_slash_devname;
270         }
271
272         /* If we have config file, look up user settings */
273         if (ENABLE_FEATURE_MDEV_CONF)
274                 parser = config_open2("/etc/mdev.conf", fopen_for_read);
275
276         do {
277                 int keep_matching;
278                 struct bb_uidgid_t ugid;
279                 char *tokens[4];
280                 char *command = NULL;
281                 char *alias = NULL;
282                 char aliaslink = aliaslink; /* for compiler */
283
284                 /* Defaults in case we won't match any line */
285                 ugid.uid = ugid.gid = 0;
286                 keep_matching = 0;
287                 mode = 0660;
288
289                 if (ENABLE_FEATURE_MDEV_CONF
290                  && config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL)
291                 ) {
292                         char *val;
293                         char *str_to_match;
294                         regmatch_t off[1 + 9 * ENABLE_FEATURE_MDEV_RENAME_REGEXP];
295
296                         val = tokens[0];
297                         keep_matching = ('-' == val[0]);
298                         val += keep_matching; /* swallow leading dash */
299
300                         /* Match against either "subsystem/device_name"
301                          * or "device_name" alone */
302                         str_to_match = strchr(val, '/') ? path : device_name;
303
304                         /* Fields: regex uid:gid mode [alias] [cmd] */
305
306                         if (val[0] == '@') {
307                                 /* @major,minor[-minor2] */
308                                 /* (useful when name is ambiguous:
309                                  * "/sys/class/usb/lp0" and
310                                  * "/sys/class/printer/lp0") */
311                                 int cmaj, cmin0, cmin1, sc;
312                                 if (major < 0)
313                                         continue; /* no dev, no match */
314                                 sc = sscanf(val, "@%u,%u-%u", &cmaj, &cmin0, &cmin1);
315                                 if (sc < 1
316                                  || major != cmaj
317                                  || (sc == 2 && minor != cmin0)
318                                  || (sc == 3 && (minor < cmin0 || minor > cmin1))
319                                 ) {
320                                         continue; /* this line doesn't match */
321                                 }
322                                 goto line_matches;
323                         }
324                         if (val[0] == '$') {
325                                 /* regex to match an environment variable */
326                                 char *eq = strchr(++val, '=');
327                                 if (!eq)
328                                         continue;
329                                 *eq = '\0';
330                                 str_to_match = getenv(val);
331                                 if (!str_to_match)
332                                         continue;
333                                 str_to_match -= strlen(val) + 1;
334                                 *eq = '=';
335                         }
336                         /* else: regex to match [subsystem/]device_name */
337
338                         {
339                                 regex_t match;
340                                 int result;
341
342                                 xregcomp(&match, val, REG_EXTENDED);
343                                 result = regexec(&match, str_to_match, ARRAY_SIZE(off), off, 0);
344                                 regfree(&match);
345                                 //bb_error_msg("matches:");
346                                 //for (int i = 0; i < ARRAY_SIZE(off); i++) {
347                                 //      if (off[i].rm_so < 0) continue;
348                                 //      bb_error_msg("match %d: '%.*s'\n", i,
349                                 //              (int)(off[i].rm_eo - off[i].rm_so),
350                                 //              device_name + off[i].rm_so);
351                                 //}
352
353                                 /* If no match, skip rest of line */
354                                 /* (regexec returns whole pattern as "range" 0) */
355                                 if (result
356                                  || off[0].rm_so
357                                  || ((int)off[0].rm_eo != (int)strlen(str_to_match))
358                                 ) {
359                                         continue; /* this line doesn't match */
360                                 }
361                         }
362  line_matches:
363                         /* This line matches. Stop parsing after parsing
364                          * the rest the line unless keep_matching == 1 */
365
366                         /* 2nd field: uid:gid - device ownership */
367                         if (get_uidgid(&ugid, tokens[1], /*allow_numeric:*/ 1) == 0)
368                                 bb_error_msg("unknown user/group %s on line %d", tokens[1], parser->lineno);
369
370                         /* 3rd field: mode - device permissions */
371                         bb_parse_mode(tokens[2], &mode);
372
373                         val = tokens[3];
374                         /* 4th field (opt): ">|=alias" or "!" to not create the node */
375
376                         if (ENABLE_FEATURE_MDEV_RENAME && val) {
377                                 char *a, *s, *st;
378
379                                 a = val;
380                                 s = strchrnul(val, ' ');
381                                 st = strchrnul(val, '\t');
382                                 if (st < s)
383                                         s = st;
384                                 st = (s[0] && s[1]) ? s+1 : NULL;
385
386                                 aliaslink = a[0];
387                                 if (aliaslink == '!' && s == a+1) {
388                                         val = st;
389                                         /* "!": suppress node creation/deletion */
390                                         major = -2;
391                                 }
392                                 else if (aliaslink == '>' || aliaslink == '=') {
393                                         val = st;
394                                         s[0] = '\0';
395                                         if (ENABLE_FEATURE_MDEV_RENAME_REGEXP) {
396                                                 char *p;
397                                                 unsigned i, n;
398
399                                                 /* substitute %1..9 with off[1..9], if any */
400                                                 n = 0;
401                                                 s = a;
402                                                 while (*s)
403                                                         if (*s++ == '%')
404                                                                 n++;
405
406                                                 p = alias = xzalloc(strlen(a) + n * strlen(str_to_match));
407                                                 s = a + 1;
408                                                 while (*s) {
409                                                         *p = *s;
410                                                         if ('%' == *s) {
411                                                                 i = (s[1] - '0');
412                                                                 if (i <= 9 && off[i].rm_so >= 0) {
413                                                                         n = off[i].rm_eo - off[i].rm_so;
414                                                                         strncpy(p, str_to_match + off[i].rm_so, n);
415                                                                         p += n - 1;
416                                                                         s++;
417                                                                 }
418                                                         }
419                                                         p++;
420                                                         s++;
421                                                 }
422                                         } else {
423                                                 alias = xstrdup(a + 1);
424                                         }
425                                 }
426                         }
427
428                         if (ENABLE_FEATURE_MDEV_EXEC && val) {
429                                 const char *s = "$@*";
430                                 const char *s2 = strchr(s, val[0]);
431
432                                 if (!s2) {
433                                         bb_error_msg("bad line %u", parser->lineno);
434                                         if (ENABLE_FEATURE_MDEV_RENAME)
435                                                 free(alias);
436                                         continue;
437                                 }
438
439                                 /* Are we running this command now?
440                                  * Run $cmd on delete, @cmd on create, *cmd on both
441                                  */
442                                 if (s2 - s != delete) {
443                                         /* We are here if: '*',
444                                          * or: '@' and delete = 0,
445                                          * or: '$' and delete = 1
446                                          */
447                                         command = xstrdup(val + 1);
448                                 }
449                         }
450                 }
451
452                 /* End of field parsing */
453
454                 /* "Execute" the line we found */
455                 {
456                         const char *node_name;
457
458                         node_name = device_name;
459                         if (ENABLE_FEATURE_MDEV_RENAME && alias)
460                                 node_name = alias = build_alias(alias, device_name);
461
462                         if (!delete && major >= 0) {
463                                 if (mknod(node_name, mode | type, makedev(major, minor)) && errno != EEXIST)
464                                         bb_perror_msg("can't create '%s'", node_name);
465                                 if (major == G.root_major && minor == G.root_minor)
466                                         symlink(node_name, "root");
467                                 if (ENABLE_FEATURE_MDEV_CONF) {
468                                         chmod(node_name, mode);
469                                         chown(node_name, ugid.uid, ugid.gid);
470                                 }
471                                 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
472                                         if (aliaslink == '>')
473                                                 symlink(node_name, device_name);
474                                 }
475                         }
476
477                         if (ENABLE_FEATURE_MDEV_EXEC && command) {
478                                 /* setenv will leak memory, use putenv/unsetenv/free */
479                                 char *s = xasprintf("%s=%s", "MDEV", node_name);
480                                 char *s1 = xasprintf("%s=%s", "SUBSYSTEM", G.subsystem);
481                                 putenv(s);
482                                 putenv(s1);
483                                 if (system(command) == -1)
484                                         bb_perror_msg("can't run '%s'", command);
485                                 bb_unsetenv_and_free(s1);
486                                 bb_unsetenv_and_free(s);
487                                 free(command);
488                         }
489
490                         if (delete && major >= -1) {
491                                 if (ENABLE_FEATURE_MDEV_RENAME && alias) {
492                                         if (aliaslink == '>')
493                                                 unlink(device_name);
494                                 }
495                                 unlink(node_name);
496                         }
497
498                         if (ENABLE_FEATURE_MDEV_RENAME)
499                                 free(alias);
500                 }
501
502                 /* We found matching line.
503                  * Stop unless it was prefixed with '-' */
504                 if (ENABLE_FEATURE_MDEV_CONF && !keep_matching)
505                         break;
506
507         /* end of "while line is read from /etc/mdev.conf" */
508         } while (ENABLE_FEATURE_MDEV_CONF);
509
510         if (ENABLE_FEATURE_MDEV_CONF)
511                 config_close(parser);
512         free(subsystem_slash_devname);
513 }
514
515 /* File callback for /sys/ traversal */
516 static int FAST_FUNC fileAction(const char *fileName,
517                 struct stat *statbuf UNUSED_PARAM,
518                 void *userData,
519                 int depth UNUSED_PARAM)
520 {
521         size_t len = strlen(fileName) - 4; /* can't underflow */
522         char *scratch = userData;
523
524         /* len check is for paranoid reasons */
525         if (strcmp(fileName + len, "/dev") != 0 || len >= PATH_MAX)
526                 return FALSE;
527
528         strcpy(scratch, fileName);
529         scratch[len] = '\0';
530         make_device(scratch, /*delete:*/ 0);
531
532         return TRUE;
533 }
534
535 /* Directory callback for /sys/ traversal */
536 static int FAST_FUNC dirAction(const char *fileName UNUSED_PARAM,
537                 struct stat *statbuf UNUSED_PARAM,
538                 void *userData UNUSED_PARAM,
539                 int depth)
540 {
541         /* Extract device subsystem -- the name of the directory
542          * under /sys/class/ */
543         if (1 == depth) {
544                 free(G.subsystem);
545                 G.subsystem = strrchr(fileName, '/');
546                 if (G.subsystem)
547                         G.subsystem = xstrdup(G.subsystem + 1);
548         }
549
550         return (depth >= MAX_SYSFS_DEPTH ? SKIP : TRUE);
551 }
552
553 /* For the full gory details, see linux/Documentation/firmware_class/README
554  *
555  * Firmware loading works like this:
556  * - kernel sets FIRMWARE env var
557  * - userspace checks /lib/firmware/$FIRMWARE
558  * - userspace waits for /sys/$DEVPATH/loading to appear
559  * - userspace writes "1" to /sys/$DEVPATH/loading
560  * - userspace copies /lib/firmware/$FIRMWARE into /sys/$DEVPATH/data
561  * - userspace writes "0" (worked) or "-1" (failed) to /sys/$DEVPATH/loading
562  * - kernel loads firmware into device
563  */
564 static void load_firmware(const char *firmware, const char *sysfs_path)
565 {
566         int cnt;
567         int firmware_fd, loading_fd, data_fd;
568
569         /* check for /lib/firmware/$FIRMWARE */
570         xchdir("/lib/firmware");
571         firmware_fd = xopen(firmware, O_RDONLY);
572
573         /* in case we goto out ... */
574         data_fd = -1;
575
576         /* check for /sys/$DEVPATH/loading ... give 30 seconds to appear */
577         xchdir(sysfs_path);
578         for (cnt = 0; cnt < 30; ++cnt) {
579                 loading_fd = open("loading", O_WRONLY);
580                 if (loading_fd != -1)
581                         goto loading;
582                 sleep(1);
583         }
584         goto out;
585
586  loading:
587         /* tell kernel we're loading by "echo 1 > /sys/$DEVPATH/loading" */
588         if (full_write(loading_fd, "1", 1) != 1)
589                 goto out;
590
591         /* load firmware into /sys/$DEVPATH/data */
592         data_fd = open("data", O_WRONLY);
593         if (data_fd == -1)
594                 goto out;
595         cnt = bb_copyfd_eof(firmware_fd, data_fd);
596
597         /* tell kernel result by "echo [0|-1] > /sys/$DEVPATH/loading" */
598         if (cnt > 0)
599                 full_write(loading_fd, "0", 1);
600         else
601                 full_write(loading_fd, "-1", 2);
602
603  out:
604         if (ENABLE_FEATURE_CLEAN_UP) {
605                 close(firmware_fd);
606                 close(loading_fd);
607                 close(data_fd);
608         }
609 }
610
611 int mdev_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
612 int mdev_main(int argc UNUSED_PARAM, char **argv)
613 {
614         RESERVE_CONFIG_BUFFER(temp, PATH_MAX + SCRATCH_SIZE);
615
616         /* We can be called as hotplug helper */
617         /* Kernel cannot provide suitable stdio fds for us, do it ourself */
618         bb_sanitize_stdio();
619
620         /* Force the configuration file settings exactly */
621         umask(0);
622
623         xchdir("/dev");
624
625         if (argv[1] && strcmp(argv[1], "-s") == 0) {
626                 /* Scan:
627                  * mdev -s
628                  */
629                 struct stat st;
630
631                 xstat("/", &st);
632                 G.root_major = major(st.st_dev);
633                 G.root_minor = minor(st.st_dev);
634
635                 /* ACTION_FOLLOWLINKS is needed since in newer kernels
636                  * /sys/block/loop* (for example) are symlinks to dirs,
637                  * not real directories.
638                  * (kernel's CONFIG_SYSFS_DEPRECATED makes them real dirs,
639                  * but we can't enforce that on users)
640                  */
641                 if (access("/sys/class/block", F_OK) != 0) {
642                         /* Scan obsolete /sys/block only if /sys/class/block
643                          * doesn't exist. Otherwise we'll have dupes.
644                          * Also, do not complain if it doesn't exist.
645                          * Some people configure kernel to have no blockdevs.
646                          */
647                         recursive_action("/sys/block",
648                                 ACTION_RECURSE | ACTION_FOLLOWLINKS | ACTION_QUIET,
649                                 fileAction, dirAction, temp, 0);
650                 }
651                 recursive_action("/sys/class",
652                         ACTION_RECURSE | ACTION_FOLLOWLINKS,
653                         fileAction, dirAction, temp, 0);
654         } else {
655                 char *fw;
656                 char *seq;
657                 char *action;
658                 char *env_path;
659                 static const char keywords[] ALIGN1 = "remove\0add\0";
660                 enum { OP_remove = 0, OP_add };
661                 smalluint op;
662
663                 /* Hotplug:
664                  * env ACTION=... DEVPATH=... SUBSYSTEM=... [SEQNUM=...] mdev
665                  * ACTION can be "add" or "remove"
666                  * DEVPATH is like "/block/sda" or "/class/input/mice"
667                  */
668                 action = getenv("ACTION");
669                 env_path = getenv("DEVPATH");
670                 G.subsystem = getenv("SUBSYSTEM");
671                 if (!action || !env_path /*|| !G.subsystem*/)
672                         bb_show_usage();
673                 fw = getenv("FIRMWARE");
674                 op = index_in_strings(keywords, action);
675                 /* If it exists, does /dev/mdev.seq match $SEQNUM?
676                  * If it does not match, earlier mdev is running
677                  * in parallel, and we need to wait */
678                 seq = getenv("SEQNUM");
679                 if (seq) {
680                         int timeout = 2000 / 32; /* 2000 msec */
681                         do {
682                                 int seqlen;
683                                 char seqbuf[sizeof(int)*3 + 2];
684
685                                 seqlen = open_read_close("mdev.seq", seqbuf, sizeof(seqbuf-1));
686                                 if (seqlen < 0) {
687                                         seq = NULL;
688                                         break;
689                                 }
690                                 seqbuf[seqlen] = '\0';
691                                 if (seqbuf[0] == '\n' /* seed file? */
692                                  || strcmp(seq, seqbuf) == 0 /* correct idx? */
693                                 ) {
694                                         break;
695                                 }
696                                 usleep(32*1000);
697                         } while (--timeout);
698                 }
699
700                 snprintf(temp, PATH_MAX, "/sys%s", env_path);
701                 if (op == OP_remove) {
702                         /* Ignoring "remove firmware". It was reported
703                          * to happen and to cause erroneous deletion
704                          * of device nodes. */
705                         if (!fw)
706                                 make_device(temp, /*delete:*/ 1);
707                 }
708                 else if (op == OP_add) {
709                         make_device(temp, /*delete:*/ 0);
710                         if (ENABLE_FEATURE_MDEV_LOAD_FIRMWARE) {
711                                 if (fw)
712                                         load_firmware(fw, temp);
713                         }
714                 }
715
716                 if (seq) {
717                         xopen_xwrite_close("mdev.seq", utoa(xatou(seq) + 1));
718                 }
719         }
720
721         if (ENABLE_FEATURE_CLEAN_UP)
722                 RELEASE_CONFIG_BUFFER(temp);
723
724         return EXIT_SUCCESS;
725 }