summaryrefslogtreecommitdiff
path: root/modutils/modprobe-small.c (plain)
blob: 51ba42f7ac135f36c5cde4f965753797cc0dcbd6
1/* vi: set sw=4 ts=4: */
2/*
3 * simplified modprobe
4 *
5 * Copyright (c) 2008 Vladimir Dronnikov
6 * Copyright (c) 2008 Bernhard Reutner-Fischer (initial depmod code)
7 *
8 * Licensed under GPLv2, see file LICENSE in this source tree.
9 */
10//config:config MODPROBE_SMALL
11//config: bool "Simplified modutils"
12//config: default y
13//config: select PLATFORM_LINUX
14//config: help
15//config: Simplified modutils.
16//config:
17//config: With this option modprobe does not require modules.dep file
18//config: and does not use /etc/modules.conf file.
19//config: It scans module files in /lib/modules/`uname -r` and
20//config: determines dependencies and module alias names on the fly.
21//config: This may make module loading slower, most notably
22//config: when one needs to load module by alias (this requires
23//config: scanning through module _bodies_).
24//config:
25//config: At the first attempt to load a module by alias modprobe
26//config: will try to generate modules.dep.bb file in order to speed up
27//config: future loads by alias. Failure to do so (read-only /lib/modules,
28//config: etc) is not reported, and future modprobes will be slow too.
29//config:
30//config: NB: modules.dep.bb file format is not compatible
31//config: with modules.dep file as created/used by standard module tools.
32//config:
33//config: Additional module parameters can be stored in
34//config: /etc/modules/$module_name files.
35//config:
36//config: Apart from modprobe, other utilities are also provided:
37//config: - insmod is an alias to modprobe
38//config: - rmmod is an alias to modprobe -r
39//config: - depmod generates modules.dep.bb
40//config:
41//config:config FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
42//config: bool "Accept module options on modprobe command line"
43//config: default y
44//config: depends on MODPROBE_SMALL
45//config: select PLATFORM_LINUX
46//config: help
47//config: Allow insmod and modprobe take module options from command line.
48//config:
49//config:config FEATURE_MODPROBE_SMALL_CHECK_ALREADY_LOADED
50//config: bool "Skip loading of already loaded modules"
51//config: default y
52//config: depends on MODPROBE_SMALL
53//config: help
54//config: Check if the module is already loaded.
55
56//applet:IF_MODPROBE_SMALL(APPLET(modprobe, BB_DIR_SBIN, BB_SUID_DROP))
57//applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(depmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, depmod))
58//applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(insmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, insmod))
59//applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(lsmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, lsmod))
60//applet:IF_MODPROBE_SMALL(APPLET_ODDNAME(rmmod, modprobe, BB_DIR_SBIN, BB_SUID_DROP, rmmod))
61
62//kbuild:lib-$(CONFIG_MODPROBE_SMALL) += modprobe-small.o
63
64#include "libbb.h"
65/* After libbb.h, since it needs sys/types.h on some systems */
66#include <sys/utsname.h> /* uname() */
67#include <fnmatch.h>
68#include <sys/syscall.h>
69
70extern int init_module(void *module, unsigned long len, const char *options);
71extern int delete_module(const char *module, unsigned flags);
72#ifdef __NR_finit_module
73# define finit_module(fd, uargs, flags) syscall(__NR_finit_module, fd, uargs, flags)
74#endif
75/* linux/include/linux/module.h has limit of 64 chars on module names */
76#undef MODULE_NAME_LEN
77#define MODULE_NAME_LEN 64
78
79
80#if 1
81# define dbg1_error_msg(...) ((void)0)
82# define dbg2_error_msg(...) ((void)0)
83#else
84# define dbg1_error_msg(...) bb_error_msg(__VA_ARGS__)
85# define dbg2_error_msg(...) bb_error_msg(__VA_ARGS__)
86#endif
87
88#define DEPFILE_BB CONFIG_DEFAULT_DEPMOD_FILE".bb"
89
90enum {
91 OPT_q = (1 << 0), /* be quiet */
92 OPT_r = (1 << 1), /* module removal instead of loading */
93};
94
95typedef struct module_info {
96 char *pathname;
97 char *aliases;
98 char *deps;
99 smallint open_read_failed;
100} module_info;
101
102/*
103 * GLOBALS
104 */
105struct globals {
106 module_info *modinfo;
107 char *module_load_options;
108 smallint dep_bb_seen;
109 smallint wrote_dep_bb_ok;
110 unsigned module_count;
111 int module_found_idx;
112 unsigned stringbuf_idx;
113 unsigned stringbuf_size;
114 char *stringbuf; /* some modules have lots of stuff */
115 /* for example, drivers/media/video/saa7134/saa7134.ko */
116 /* therefore having a fixed biggish buffer is not wise */
117};
118#define G (*ptr_to_globals)
119#define modinfo (G.modinfo )
120#define dep_bb_seen (G.dep_bb_seen )
121#define wrote_dep_bb_ok (G.wrote_dep_bb_ok )
122#define module_count (G.module_count )
123#define module_found_idx (G.module_found_idx )
124#define module_load_options (G.module_load_options)
125#define stringbuf_idx (G.stringbuf_idx )
126#define stringbuf_size (G.stringbuf_size )
127#define stringbuf (G.stringbuf )
128#define INIT_G() do { \
129 SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
130} while (0)
131
132static void append(const char *s)
133{
134 unsigned len = strlen(s);
135 if (stringbuf_idx + len + 15 > stringbuf_size) {
136 stringbuf_size = stringbuf_idx + len + 127;
137 dbg2_error_msg("grow stringbuf to %u", stringbuf_size);
138 stringbuf = xrealloc(stringbuf, stringbuf_size);
139 }
140 memcpy(stringbuf + stringbuf_idx, s, len);
141 stringbuf_idx += len;
142}
143
144static void appendc(char c)
145{
146 /* We appendc() only after append(), + 15 trick in append()
147 * makes it unnecessary to check for overflow here */
148 stringbuf[stringbuf_idx++] = c;
149}
150
151static void bksp(void)
152{
153 if (stringbuf_idx)
154 stringbuf_idx--;
155}
156
157static void reset_stringbuf(void)
158{
159 stringbuf_idx = 0;
160}
161
162static char* copy_stringbuf(void)
163{
164 char *copy = xzalloc(stringbuf_idx + 1); /* terminating NUL */
165 return memcpy(copy, stringbuf, stringbuf_idx);
166}
167
168static char* find_keyword(char *ptr, size_t len, const char *word)
169{
170 if (!ptr) /* happens if xmalloc_open_zipped_read_close cannot read it */
171 return NULL;
172
173 len -= strlen(word) - 1;
174 while ((ssize_t)len > 0) {
175 char *old = ptr;
176 char *after_word;
177
178 /* search for the first char in word */
179 ptr = memchr(ptr, word[0], len);
180 if (ptr == NULL) /* no occurance left, done */
181 break;
182 after_word = is_prefixed_with(ptr, word);
183 if (after_word)
184 return after_word; /* found, return ptr past it */
185 ++ptr;
186 len -= (ptr - old);
187 }
188 return NULL;
189}
190
191static void replace(char *s, char what, char with)
192{
193 while (*s) {
194 if (what == *s)
195 *s = with;
196 ++s;
197 }
198}
199
200static char *filename2modname(const char *filename, char *modname)
201{
202 int i;
203 const char *from;
204
205 // Disabled since otherwise "modprobe dir/name" would work
206 // as if it is "modprobe name". It is unclear why
207 // 'basenamization' was here in the first place.
208 //from = bb_get_last_path_component_nostrip(filename);
209 from = filename;
210 for (i = 0; i < (MODULE_NAME_LEN-1) && from[i] != '\0' && from[i] != '.'; i++)
211 modname[i] = (from[i] == '-') ? '_' : from[i];
212 modname[i] = '\0';
213
214 return modname;
215}
216
217static int pathname_matches_modname(const char *pathname, const char *modname)
218{
219 int r;
220 char name[MODULE_NAME_LEN];
221 filename2modname(bb_get_last_path_component_nostrip(pathname), name);
222 r = (strcmp(name, modname) == 0);
223 return r;
224}
225
226/* Take "word word", return malloced "word",NUL,"word",NUL,NUL */
227static char* str_2_list(const char *str)
228{
229 int len = strlen(str) + 1;
230 char *dst = xmalloc(len + 1);
231
232 dst[len] = '\0';
233 memcpy(dst, str, len);
234//TODO: protect against 2+ spaces: "word word"
235 replace(dst, ' ', '\0');
236 return dst;
237}
238
239/* We use error numbers in a loose translation... */
240static const char *moderror(int err)
241{
242 switch (err) {
243 case ENOEXEC:
244 return "invalid module format";
245 case ENOENT:
246 return "unknown symbol in module or invalid parameter";
247 case ESRCH:
248 return "module has wrong symbol version";
249 case EINVAL: /* "invalid parameter" */
250 return "unknown symbol in module or invalid parameter"
251 + sizeof("unknown symbol in module or");
252 default:
253 return strerror(err);
254 }
255}
256
257static int load_module(const char *fname, const char *options)
258{
259#if 1
260 int r;
261 size_t len = MAXINT(ssize_t);
262 char *module_image;
263
264 if (!options)
265 options = "";
266
267 dbg1_error_msg("load_module('%s','%s')", fname, options);
268
269 /*
270 * First we try finit_module if available. Some kernels are configured
271 * to only allow loading of modules off of secure storage (like a read-
272 * only rootfs) which needs the finit_module call. If it fails, we fall
273 * back to normal module loading to support compressed modules.
274 */
275 r = 1;
276# ifdef __NR_finit_module
277 {
278 int fd = open(fname, O_RDONLY | O_CLOEXEC);
279 if (fd >= 0) {
280 r = finit_module(fd, options, 0) != 0;
281 close(fd);
282 }
283 }
284# endif
285 if (r != 0) {
286 module_image = xmalloc_open_zipped_read_close(fname, &len);
287 r = (!module_image || init_module(module_image, len, options) != 0);
288 free(module_image);
289 }
290
291 dbg1_error_msg("load_module:%d", r);
292 return r; /* 0 = success */
293#else
294 /* For testing */
295 dbg1_error_msg("load_module('%s','%s')", fname, options);
296 return 1;
297#endif
298}
299
300/* Returns !0 if open/read was unsuccessful */
301static int parse_module(module_info *info, const char *pathname)
302{
303 char *module_image;
304 char *ptr;
305 size_t len;
306 size_t pos;
307 dbg1_error_msg("parse_module('%s')", pathname);
308
309 /* Read (possibly compressed) module */
310 errno = 0;
311 len = 64 * 1024 * 1024; /* 64 Mb at most */
312 module_image = xmalloc_open_zipped_read_close(pathname, &len);
313 /* module_image == NULL is ok here, find_keyword handles it */
314//TODO: optimize redundant module body reads
315
316 /* "alias1 symbol:sym1 alias2 symbol:sym2" */
317 reset_stringbuf();
318 pos = 0;
319 while (1) {
320 unsigned start = stringbuf_idx;
321 ptr = find_keyword(module_image + pos, len - pos, "alias=");
322 if (!ptr) {
323 ptr = find_keyword(module_image + pos, len - pos, "__ksymtab_");
324 if (!ptr)
325 break;
326 /* DOCME: __ksymtab_gpl and __ksymtab_strings occur
327 * in many modules. What do they mean? */
328 if (strcmp(ptr, "gpl") == 0 || strcmp(ptr, "strings") == 0)
329 goto skip;
330 dbg2_error_msg("alias:'symbol:%s'", ptr);
331 append("symbol:");
332 } else {
333 dbg2_error_msg("alias:'%s'", ptr);
334 }
335 append(ptr);
336 appendc(' ');
337 /*
338 * Don't add redundant aliases, such as:
339 * libcrc32c.ko symbol:crc32c symbol:crc32c
340 */
341 if (start) { /* "if we aren't the first alias" */
342 char *found, *last;
343 stringbuf[stringbuf_idx] = '\0';
344 last = stringbuf + start;
345 /*
346 * String at last-1 is " symbol:crc32c "
347 * (with both leading and trailing spaces).
348 */
349 if (strncmp(stringbuf, last, stringbuf_idx - start) == 0)
350 /* First alias matches us */
351 found = stringbuf;
352 else
353 /* Does any other alias match? */
354 found = strstr(stringbuf, last-1);
355 if (found < last-1) {
356 /* There is absolutely the same string before us */
357 dbg2_error_msg("redundant:'%s'", last);
358 stringbuf_idx = start;
359 goto skip;
360 }
361 }
362 skip:
363 pos = (ptr - module_image);
364 }
365 bksp(); /* remove last ' ' */
366 info->aliases = copy_stringbuf();
367 replace(info->aliases, '-', '_');
368
369 /* "dependency1 depandency2" */
370 reset_stringbuf();
371 ptr = find_keyword(module_image, len, "depends=");
372 if (ptr && *ptr) {
373 replace(ptr, ',', ' ');
374 replace(ptr, '-', '_');
375 dbg2_error_msg("dep:'%s'", ptr);
376 append(ptr);
377 }
378 free(module_image);
379 info->deps = copy_stringbuf();
380
381 info->open_read_failed = (module_image == NULL);
382 return info->open_read_failed;
383}
384
385static FAST_FUNC int fileAction(const char *pathname,
386 struct stat *sb UNUSED_PARAM,
387 void *modname_to_match,
388 int depth UNUSED_PARAM)
389{
390 int cur;
391 const char *fname;
392
393 pathname += 2; /* skip "./" */
394 fname = bb_get_last_path_component_nostrip(pathname);
395 if (!strrstr(fname, ".ko")) {
396 dbg1_error_msg("'%s' is not a module", pathname);
397 return TRUE; /* not a module, continue search */
398 }
399
400 cur = module_count++;
401 modinfo = xrealloc_vector(modinfo, 12, cur);
402 modinfo[cur].pathname = xstrdup(pathname);
403 /*modinfo[cur].aliases = NULL; - xrealloc_vector did it */
404 /*modinfo[cur+1].pathname = NULL;*/
405
406 if (!pathname_matches_modname(fname, modname_to_match)) {
407 dbg1_error_msg("'%s' module name doesn't match", pathname);
408 return TRUE; /* module name doesn't match, continue search */
409 }
410
411 dbg1_error_msg("'%s' module name matches", pathname);
412 module_found_idx = cur;
413 if (parse_module(&modinfo[cur], pathname) != 0)
414 return TRUE; /* failed to open/read it, no point in trying loading */
415
416 if (!(option_mask32 & OPT_r)) {
417 if (load_module(pathname, module_load_options) == 0) {
418 /* Load was successful, there is nothing else to do.
419 * This can happen ONLY for "top-level" module load,
420 * not a dep, because deps dont do dirscan. */
421 exit(EXIT_SUCCESS);
422 }
423 }
424
425 return TRUE;
426}
427
428static int load_dep_bb(void)
429{
430 char *line;
431 FILE *fp = fopen_for_read(DEPFILE_BB);
432
433 if (!fp)
434 return 0;
435
436 dep_bb_seen = 1;
437 dbg1_error_msg("loading "DEPFILE_BB);
438
439 /* Why? There is a rare scenario: we did not find modprobe.dep.bb,
440 * we scanned the dir and found no module by name, then we search
441 * for alias (full scan), and we decided to generate modprobe.dep.bb.
442 * But we see modprobe.dep.bb.new! Other modprobe is at work!
443 * We wait and other modprobe renames it to modprobe.dep.bb.
444 * Now we can use it.
445 * But we already have modinfo[] filled, and "module_count = 0"
446 * makes us start anew. Yes, we leak modinfo[].xxx pointers -
447 * there is not much of data there anyway. */
448 module_count = 0;
449 memset(&modinfo[0], 0, sizeof(modinfo[0]));
450
451 while ((line = xmalloc_fgetline(fp)) != NULL) {
452 char* space;
453 char* linebuf;
454 int cur;
455
456 if (!line[0]) {
457 free(line);
458 continue;
459 }
460 space = strchrnul(line, ' ');
461 cur = module_count++;
462 modinfo = xrealloc_vector(modinfo, 12, cur);
463 /*modinfo[cur+1].pathname = NULL; - xrealloc_vector did it */
464 modinfo[cur].pathname = line; /* we take ownership of malloced block here */
465 if (*space)
466 *space++ = '\0';
467 modinfo[cur].aliases = space;
468 linebuf = xmalloc_fgetline(fp);
469 modinfo[cur].deps = linebuf ? linebuf : xzalloc(1);
470 if (modinfo[cur].deps[0]) {
471 /* deps are not "", so next line must be empty */
472 line = xmalloc_fgetline(fp);
473 /* Refuse to work with damaged config file */
474 if (line && line[0])
475 bb_error_msg_and_die("error in %s at '%s'", DEPFILE_BB, line);
476 free(line);
477 }
478 }
479 return 1;
480}
481
482static int start_dep_bb_writeout(void)
483{
484 int fd;
485
486 /* depmod -n: write result to stdout */
487 if (applet_name[0] == 'd' && (option_mask32 & 1))
488 return STDOUT_FILENO;
489
490 fd = open(DEPFILE_BB".new", O_WRONLY | O_CREAT | O_TRUNC | O_EXCL, 0644);
491 if (fd < 0) {
492 if (errno == EEXIST) {
493 int count = 5 * 20;
494 dbg1_error_msg(DEPFILE_BB".new exists, waiting for "DEPFILE_BB);
495 while (1) {
496 usleep(1000*1000 / 20);
497 if (load_dep_bb()) {
498 dbg1_error_msg(DEPFILE_BB" appeared");
499 return -2; /* magic number */
500 }
501 if (!--count)
502 break;
503 }
504 bb_error_msg("deleting stale %s", DEPFILE_BB".new");
505 fd = open_or_warn(DEPFILE_BB".new", O_WRONLY | O_CREAT | O_TRUNC);
506 }
507 }
508 dbg1_error_msg("opened "DEPFILE_BB".new:%d", fd);
509 return fd;
510}
511
512static void write_out_dep_bb(int fd)
513{
514 int i;
515 FILE *fp;
516
517 /* We want good error reporting. fdprintf is not good enough. */
518 fp = xfdopen_for_write(fd);
519 i = 0;
520 while (modinfo[i].pathname) {
521 fprintf(fp, "%s%s%s\n" "%s%s\n",
522 modinfo[i].pathname, modinfo[i].aliases[0] ? " " : "", modinfo[i].aliases,
523 modinfo[i].deps, modinfo[i].deps[0] ? "\n" : "");
524 i++;
525 }
526 /* Badly formatted depfile is a no-no. Be paranoid. */
527 errno = 0;
528 if (ferror(fp) | fclose(fp)) /* | instead of || is intended */
529 goto err;
530
531 if (fd == STDOUT_FILENO) /* it was depmod -n */
532 goto ok;
533
534 if (rename(DEPFILE_BB".new", DEPFILE_BB) != 0) {
535 err:
536 bb_perror_msg("can't create '%s'", DEPFILE_BB);
537 unlink(DEPFILE_BB".new");
538 } else {
539 ok:
540 wrote_dep_bb_ok = 1;
541 dbg1_error_msg("created "DEPFILE_BB);
542 }
543}
544
545static module_info** find_alias(const char *alias)
546{
547 int i;
548 int dep_bb_fd;
549 int infoidx;
550 module_info **infovec;
551 dbg1_error_msg("find_alias('%s')", alias);
552
553 try_again:
554 /* First try to find by name (cheaper) */
555 i = 0;
556 while (modinfo[i].pathname) {
557 if (pathname_matches_modname(modinfo[i].pathname, alias)) {
558 dbg1_error_msg("found '%s' in module '%s'",
559 alias, modinfo[i].pathname);
560 if (!modinfo[i].aliases) {
561 parse_module(&modinfo[i], modinfo[i].pathname);
562 }
563 infovec = xzalloc(2 * sizeof(infovec[0]));
564 infovec[0] = &modinfo[i];
565 return infovec;
566 }
567 i++;
568 }
569
570 /* Ok, we definitely have to scan module bodies. This is a good
571 * moment to generate modprobe.dep.bb, if it does not exist yet */
572 dep_bb_fd = dep_bb_seen ? -1 : start_dep_bb_writeout();
573 if (dep_bb_fd == -2) /* modprobe.dep.bb appeared? */
574 goto try_again;
575
576 /* Scan all module bodies, extract modinfo (it contains aliases) */
577 i = 0;
578 infoidx = 0;
579 infovec = NULL;
580 while (modinfo[i].pathname) {
581 char *desc, *s;
582 if (!modinfo[i].aliases) {
583 parse_module(&modinfo[i], modinfo[i].pathname);
584 }
585 /* "alias1 symbol:sym1 alias2 symbol:sym2" */
586 desc = str_2_list(modinfo[i].aliases);
587 /* Does matching substring exist? */
588 for (s = desc; *s; s += strlen(s) + 1) {
589 /* Aliases in module bodies can be defined with
590 * shell patterns. Example:
591 * "pci:v000010DEd000000D9sv*sd*bc*sc*i*".
592 * Plain strcmp() won't catch that */
593 if (fnmatch(s, alias, 0) == 0) {
594 dbg1_error_msg("found alias '%s' in module '%s'",
595 alias, modinfo[i].pathname);
596 infovec = xrealloc_vector(infovec, 1, infoidx);
597 infovec[infoidx++] = &modinfo[i];
598 break;
599 }
600 }
601 free(desc);
602 i++;
603 }
604
605 /* Create module.dep.bb if needed */
606 if (dep_bb_fd >= 0) {
607 write_out_dep_bb(dep_bb_fd);
608 }
609
610 dbg1_error_msg("find_alias '%s' returns %d results", alias, infoidx);
611 return infovec;
612}
613
614#if ENABLE_FEATURE_MODPROBE_SMALL_CHECK_ALREADY_LOADED
615// TODO: open only once, invent config_rewind()
616static int already_loaded(const char *name)
617{
618 int ret;
619 char *line;
620 FILE *fp;
621
622 ret = 5 * 2;
623 again:
624 fp = fopen_for_read("/proc/modules");
625 if (!fp)
626 return 0;
627 while ((line = xmalloc_fgetline(fp)) != NULL) {
628 char *live;
629 char *after_name;
630
631 // Examples from kernel 3.14.6:
632 //pcspkr 12718 0 - Live 0xffffffffa017e000
633 //snd_timer 28690 2 snd_seq,snd_pcm, Live 0xffffffffa025e000
634 //i915 801405 2 - Live 0xffffffffa0096000
635 after_name = is_prefixed_with(line, name);
636 if (!after_name || *after_name != ' ') {
637 free(line);
638 continue;
639 }
640 live = strstr(line, " Live");
641 free(line);
642 if (!live) {
643 /* State can be Unloading, Loading, or Live.
644 * modprobe must not return prematurely if we see "Loading":
645 * it can cause further programs to assume load completed,
646 * but it did not (yet)!
647 * Wait up to 5*20 ms for it to resolve.
648 */
649 ret -= 2;
650 if (ret == 0)
651 break; /* huh? report as "not loaded" */
652 fclose(fp);
653 usleep(20*1000);
654 goto again;
655 }
656 ret = 1;
657 break;
658 }
659 fclose(fp);
660
661 return ret & 1;
662}
663#else
664#define already_loaded(name) 0
665#endif
666
667static int rmmod(const char *filename)
668{
669 int r;
670 char modname[MODULE_NAME_LEN];
671
672 filename2modname(filename, modname);
673 r = delete_module(modname, O_NONBLOCK | O_EXCL);
674 dbg1_error_msg("delete_module('%s', O_NONBLOCK | O_EXCL):%d", modname, r);
675 if (r != 0 && !(option_mask32 & OPT_q)) {
676 bb_perror_msg("remove '%s'", modname);
677 }
678 return r;
679}
680
681/*
682 * Given modules definition and module name (or alias, or symbol)
683 * load/remove the module respecting dependencies.
684 * NB: also called by depmod with bogus name "/",
685 * just in order to force modprobe.dep.bb creation.
686*/
687#if !ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
688#define process_module(a,b) process_module(a)
689#define cmdline_options ""
690#endif
691static int process_module(char *name, const char *cmdline_options)
692{
693 char *s, *deps, *options;
694 module_info **infovec;
695 module_info *info;
696 int infoidx;
697 int is_remove = (option_mask32 & OPT_r) != 0;
698 int exitcode = EXIT_SUCCESS;
699
700 dbg1_error_msg("process_module('%s','%s')", name, cmdline_options);
701
702 replace(name, '-', '_');
703
704 dbg1_error_msg("already_loaded:%d is_remove:%d", already_loaded(name), is_remove);
705
706 if (applet_name[0] == 'r') {
707 /* rmmod.
708 * Does not remove dependencies, no need to scan, just remove.
709 * (compat note: this allows and strips .ko suffix)
710 */
711 rmmod(name);
712 return EXIT_SUCCESS;
713 }
714
715 /*
716 * We used to have "is_remove != already_loaded(name)" check here, but
717 * modprobe -r pci:v00008086d00007010sv00000000sd00000000bc01sc01i80
718 * won't unload modules (there are more than one)
719 * which have this alias.
720 */
721 if (!is_remove && already_loaded(name)) {
722 dbg1_error_msg("nothing to do for '%s'", name);
723 return EXIT_SUCCESS;
724 }
725
726 options = NULL;
727 if (!is_remove) {
728 char *opt_filename = xasprintf("/etc/modules/%s", name);
729 options = xmalloc_open_read_close(opt_filename, NULL);
730 if (options)
731 replace(options, '\n', ' ');
732#if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
733 if (cmdline_options) {
734 /* NB: cmdline_options always have one leading ' '
735 * (see main()), we remove it here */
736 char *op = xasprintf(options ? "%s %s" : "%s %s" + 3,
737 cmdline_options + 1, options);
738 free(options);
739 options = op;
740 }
741#endif
742 free(opt_filename);
743 module_load_options = options;
744 dbg1_error_msg("process_module('%s'): options:'%s'", name, options);
745 }
746
747 if (!module_count) {
748 /* Scan module directory. This is done only once.
749 * It will attempt module load, and will exit(EXIT_SUCCESS)
750 * on success.
751 */
752 module_found_idx = -1;
753 recursive_action(".",
754 ACTION_RECURSE, /* flags */
755 fileAction, /* file action */
756 NULL, /* dir action */
757 name, /* user data */
758 0 /* depth */
759 );
760 dbg1_error_msg("dirscan complete");
761 /* Module was not found, or load failed, or is_remove */
762 if (module_found_idx >= 0) { /* module was found */
763 infovec = xzalloc(2 * sizeof(infovec[0]));
764 infovec[0] = &modinfo[module_found_idx];
765 } else { /* search for alias, not a plain module name */
766 infovec = find_alias(name);
767 }
768 } else {
769 infovec = find_alias(name);
770 }
771
772 if (!infovec) {
773 /* both dirscan and find_alias found nothing */
774 if (!is_remove && applet_name[0] != 'd') /* it wasn't rmmod or depmod */
775 bb_error_msg("module '%s' not found", name);
776//TODO: _and_die()? or should we continue (un)loading modules listed on cmdline?
777 goto ret;
778 }
779
780 /* There can be more than one module for the given alias. For example,
781 * "pci:v00008086d00007010sv00000000sd00000000bc01sc01i80" matches
782 * ata_piix because it has alias "pci:v00008086d00007010sv*sd*bc*sc*i*"
783 * and ata_generic, it has alias "pci:v*d*sv*sd*bc01sc01i*"
784 * Standard modprobe loads them both. We achieve it by returning
785 * a *list* of modinfo pointers from find_alias().
786 */
787
788 /* modprobe -r? unload module(s) */
789 if (is_remove) {
790 infoidx = 0;
791 while ((info = infovec[infoidx++]) != NULL) {
792 int r = rmmod(bb_get_last_path_component_nostrip(info->pathname));
793 if (r != 0) {
794 goto ret; /* error */
795 }
796 }
797 /* modprobe -r: we do not stop here -
798 * continue to unload modules on which the module depends:
799 * "-r --remove: option causes modprobe to remove a module.
800 * If the modules it depends on are also unused, modprobe
801 * will try to remove them, too."
802 */
803 }
804
805 infoidx = 0;
806 while ((info = infovec[infoidx++]) != NULL) {
807 /* Iterate thru dependencies, trying to (un)load them */
808 deps = str_2_list(info->deps);
809 for (s = deps; *s; s += strlen(s) + 1) {
810 //if (strcmp(name, s) != 0) // N.B. do loops exist?
811 dbg1_error_msg("recurse on dep '%s'", s);
812 process_module(s, NULL);
813 dbg1_error_msg("recurse on dep '%s' done", s);
814 }
815 free(deps);
816
817 if (is_remove)
818 continue;
819
820 /* We are modprobe: load it */
821 if (options && strstr(options, "blacklist")) {
822 dbg1_error_msg("'%s': blacklisted", info->pathname);
823 continue;
824 }
825 if (info->open_read_failed) {
826 /* We already tried it, didn't work. Don't try load again */
827 exitcode = EXIT_FAILURE;
828 continue;
829 }
830 errno = 0;
831 if (load_module(info->pathname, options) != 0) {
832 if (EEXIST != errno) {
833 bb_error_msg("'%s': %s",
834 info->pathname,
835 moderror(errno));
836 } else {
837 dbg1_error_msg("'%s': %s",
838 info->pathname,
839 moderror(errno));
840 }
841 exitcode = EXIT_FAILURE;
842 }
843 }
844 ret:
845 free(infovec);
846 free(options);
847
848 return exitcode;
849}
850#undef cmdline_options
851
852
853/* For reference, module-init-tools v3.4 options:
854
855# insmod
856Usage: insmod filename [args]
857
858# rmmod --help
859Usage: rmmod [-fhswvV] modulename ...
860 -f (or --force) forces a module unload, and may crash your
861 machine. This requires the Forced Module Removal option
862 when the kernel was compiled.
863 -h (or --help) prints this help text
864 -s (or --syslog) says use syslog, not stderr
865 -v (or --verbose) enables more messages
866 -V (or --version) prints the version code
867 -w (or --wait) begins module removal even if it is used
868 and will stop new users from accessing the module (so it
869 should eventually fall to zero).
870
871# modprobe
872Usage: modprobe [-v] [-V] [-C config-file] [-n] [-i] [-q] [-b]
873 [-o <modname>] [ --dump-modversions ] <modname> [parameters...]
874modprobe -r [-n] [-i] [-v] <modulename> ...
875modprobe -l -t <dirname> [ -a <modulename> ...]
876
877# depmod --help
878depmod 3.4 -- part of module-init-tools
879depmod -[aA] [-n -e -v -q -V -r -u]
880 [-b basedirectory] [forced_version]
881depmod [-n -e -v -q -r -u] [-F kernelsyms] module1.ko module2.ko ...
882If no arguments (except options) are given, "depmod -a" is assumed.
883depmod will output a dependency list suitable for the modprobe utility.
884Options:
885 -a, --all Probe all modules
886 -A, --quick Only does the work if there's a new module
887 -n, --show Write the dependency file on stdout only
888 -e, --errsyms Report not supplied symbols
889 -V, --version Print the release version
890 -v, --verbose Enable verbose mode
891 -h, --help Print this usage message
892The following options are useful for people managing distributions:
893 -b basedirectory
894 --basedir basedirectory
895 Use an image of a module tree
896 -F kernelsyms
897 --filesyms kernelsyms
898 Use the file instead of the current kernel symbols
899*/
900
901//usage:#if ENABLE_MODPROBE_SMALL
902
903//usage:#define depmod_trivial_usage NOUSAGE_STR
904//usage:#define depmod_full_usage ""
905
906//usage:#define lsmod_trivial_usage
907//usage: ""
908//usage:#define lsmod_full_usage "\n\n"
909//usage: "List the currently loaded kernel modules"
910
911//usage:#define insmod_trivial_usage
912//usage: IF_FEATURE_2_4_MODULES("[OPTIONS] MODULE ")
913//usage: IF_NOT_FEATURE_2_4_MODULES("FILE ")
914//usage: "[SYMBOL=VALUE]..."
915//usage:#define insmod_full_usage "\n\n"
916//usage: "Load kernel module"
917//usage: IF_FEATURE_2_4_MODULES( "\n"
918//usage: "\n -f Force module to load into the wrong kernel version"
919//usage: "\n -k Make module autoclean-able"
920//usage: "\n -v Verbose"
921//usage: "\n -q Quiet"
922//usage: "\n -L Lock: prevent simultaneous loads"
923//usage: IF_FEATURE_INSMOD_LOAD_MAP(
924//usage: "\n -m Output load map to stdout"
925//usage: )
926//usage: "\n -x Don't export externs"
927//usage: )
928
929//usage:#define rmmod_trivial_usage
930//usage: "[-wfa] [MODULE]..."
931//usage:#define rmmod_full_usage "\n\n"
932//usage: "Unload kernel modules\n"
933//usage: "\n -w Wait until the module is no longer used"
934//usage: "\n -f Force unload"
935//usage: "\n -a Remove all unused modules (recursively)"
936//usage:
937//usage:#define rmmod_example_usage
938//usage: "$ rmmod tulip\n"
939
940//usage:#define modprobe_trivial_usage
941//usage: "[-qfwrsv] MODULE [SYMBOL=VALUE]..."
942//usage:#define modprobe_full_usage "\n\n"
943//usage: " -r Remove MODULE (stacks) or do autoclean"
944//usage: "\n -q Quiet"
945//usage: "\n -v Verbose"
946//usage: "\n -f Force"
947//usage: "\n -w Wait for unload"
948//usage: "\n -s Report via syslog instead of stderr"
949
950//usage:#endif
951
952int modprobe_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
953int modprobe_main(int argc UNUSED_PARAM, char **argv)
954{
955 int exitcode;
956 struct utsname uts;
957 char applet0 = applet_name[0];
958 IF_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(char *options;)
959
960 /* are we lsmod? -> just dump /proc/modules */
961 if ('l' == applet0) {
962 xprint_and_close_file(xfopen_for_read("/proc/modules"));
963 return EXIT_SUCCESS;
964 }
965
966 INIT_G();
967
968 /* Prevent ugly corner cases with no modules at all */
969 modinfo = xzalloc(sizeof(modinfo[0]));
970
971 if ('i' != applet0) { /* not insmod */
972 /* Goto modules directory */
973 xchdir(CONFIG_DEFAULT_MODULES_DIR);
974 }
975 uname(&uts); /* never fails */
976
977 /* depmod? */
978 if ('d' == applet0) {
979 /* Supported:
980 * -n: print result to stdout
981 * -a: process all modules (default)
982 * optional VERSION parameter
983 * Ignored:
984 * -A: do work only if a module is newer than depfile
985 * -e: report any symbols which a module needs
986 * which are not supplied by other modules or the kernel
987 * -F FILE: System.map (symbols for -e)
988 * -q, -r, -u: noop?
989 * Not supported:
990 * -b BASEDIR: (TODO!) modules are in
991 * $BASEDIR/lib/modules/$VERSION
992 * -v: human readable deps to stdout
993 * -V: version (don't want to support it - people may depend
994 * on it as an indicator of "standard" depmod)
995 * -h: help (well duh)
996 * module1.o module2.o parameters (just ignored for now)
997 */
998 getopt32(argv, "na" "AeF:qru" /* "b:vV", NULL */, NULL);
999 argv += optind;
1000 /* if (argv[0] && argv[1]) bb_show_usage(); */
1001 /* Goto $VERSION directory */
1002 xchdir(argv[0] ? argv[0] : uts.release);
1003 /* Force full module scan by asking to find a bogus module.
1004 * This will generate modules.dep.bb as a side effect. */
1005 process_module((char*)"/", NULL);
1006 return !wrote_dep_bb_ok;
1007 }
1008
1009 /* insmod, modprobe, rmmod require at least one argument */
1010 opt_complementary = "-1";
1011 /* only -q (quiet) and -r (rmmod),
1012 * the rest are accepted and ignored (compat) */
1013 getopt32(argv, "qrfsvwb");
1014 argv += optind;
1015
1016 /* are we rmmod? -> simulate modprobe -r */
1017 if ('r' == applet0) {
1018 option_mask32 |= OPT_r;
1019 }
1020
1021 if ('i' != applet0) { /* not insmod */
1022 /* Goto $VERSION directory */
1023 xchdir(uts.release);
1024 }
1025
1026#if ENABLE_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE
1027 /* If not rmmod/-r, parse possible module options given on command line.
1028 * insmod/modprobe takes one module name, the rest are parameters. */
1029 options = NULL;
1030 if (!(option_mask32 & OPT_r)) {
1031 char **arg = argv;
1032 while (*++arg) {
1033 /* Enclose options in quotes */
1034 char *s = options;
1035 options = xasprintf("%s \"%s\"", s ? s : "", *arg);
1036 free(s);
1037 *arg = NULL;
1038 }
1039 }
1040#else
1041 if (!(option_mask32 & OPT_r))
1042 argv[1] = NULL;
1043#endif
1044
1045 if ('i' == applet0) { /* insmod */
1046 size_t len;
1047 void *map;
1048
1049 len = MAXINT(ssize_t);
1050 map = xmalloc_open_zipped_read_close(*argv, &len);
1051 if (!map)
1052 bb_perror_msg_and_die("can't read '%s'", *argv);
1053 if (init_module(map, len,
1054 IF_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(options ? options : "")
1055 IF_NOT_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE("")
1056 ) != 0
1057 ) {
1058 bb_error_msg_and_die("can't insert '%s': %s",
1059 *argv, moderror(errno));
1060 }
1061 return EXIT_SUCCESS;
1062 }
1063
1064 /* Try to load modprobe.dep.bb */
1065 if ('r' != applet0) { /* not rmmod */
1066 load_dep_bb();
1067 }
1068
1069 /* Load/remove modules.
1070 * Only rmmod/modprobe -r loops here, insmod/modprobe has only argv[0] */
1071 exitcode = EXIT_SUCCESS;
1072 do {
1073 exitcode |= process_module(*argv, options);
1074 } while (*++argv);
1075
1076 if (ENABLE_FEATURE_CLEAN_UP) {
1077 IF_FEATURE_MODPROBE_SMALL_OPTIONS_ON_CMDLINE(free(options);)
1078 }
1079 return exitcode;
1080}
1081