mdev.c 24 KB

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