mdev.c 19 KB

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