release: module-init-tools v3.11.1
[mit.git] / modprobe.c
blobf97f17d002ce0a1c419e6dbf4c827d99e3bbaca9
1 /* modprobe.c: add or remove a module from the kernel, intelligently.
2 Copyright (C) 2001 Rusty Russell.
3 Copyright (C) 2002, 2003 Rusty Russell, IBM Corporation.
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #define _GNU_SOURCE /* asprintf */
21 #include <sys/utsname.h>
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <sys/mman.h>
25 #include <fcntl.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <ctype.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <unistd.h>
33 #include <dirent.h>
34 #include <limits.h>
35 #include <elf.h>
36 #include <getopt.h>
37 #include <fnmatch.h>
38 #include <asm/unistd.h>
39 #include <sys/wait.h>
40 #include <syslog.h>
42 #include "util.h"
43 #include "elfops.h"
44 #include "zlibsupport.h"
45 #include "logging.h"
46 #include "index.h"
47 #include "list.h"
48 #include "config_filter.h"
50 #include "testing.h"
52 int use_binary_indexes = 1; /* default to enabled. */
54 extern long init_module(void *, unsigned long, const char *);
55 extern long delete_module(const char *, unsigned int);
57 struct module {
58 struct list_head list;
59 char *modname;
60 char filename[0];
63 typedef enum
65 mit_remove = 1,
66 mit_dry_run = 2,
67 mit_first_time = 4,
68 mit_use_blacklist = 8,
69 mit_ignore_commands = 16,
70 mit_ignore_loaded = 32,
71 mit_strip_vermagic = 64,
72 mit_strip_modversion = 128,
73 mit_resolve_alias = 256
75 } modprobe_flags_t;
77 #ifndef MODULE_DIR
78 #define MODULE_DIR "/lib/modules"
79 #endif
81 static void print_usage(const char *progname)
83 fprintf(stderr,
84 "Usage: %s [-v] [-V] [-C config-file] [-d <dirname> ] [-n] [-i] [-q] [-b] [-o <modname>] [ --dump-modversions ] <modname> [parameters...]\n"
85 "%s -r [-n] [-i] [-v] <modulename> ...\n"
86 "%s -l -t <dirname> [ -a <modulename> ...]\n",
87 progname, progname, progname);
88 exit(1);
91 static struct module *find_module(const char *filename, struct list_head *list)
93 struct module *i;
95 list_for_each_entry(i, list, list) {
96 if (streq(i->filename, filename))
97 return i;
99 return NULL;
102 /* We used to lock with a write flock but that allows regular users to block
103 * module load by having a read lock on the module file (no way to bust the
104 * existing locks without killing the offending process). Instead, we now
105 * do the system call/init_module and allow the kernel to fail us instead.
107 static int open_file(const char *filename)
109 int fd = open(filename, O_RDONLY, 0);
111 return fd;
114 static void close_file(int fd)
116 /* Valgrind is picky... */
117 close(fd);
120 static void add_module(char *filename, int namelen, struct list_head *list)
122 struct module *mod;
124 /* If it's a duplicate: move it to the end, so it gets
125 inserted where it is *first* required. */
126 mod = find_module(filename, list);
127 if (mod)
128 list_del(&mod->list);
129 else {
130 /* No match. Create a new module. */
131 mod = NOFAIL(malloc(sizeof(struct module) + namelen + 1));
132 memcpy(mod->filename, filename, namelen);
133 mod->filename[namelen] = '\0';
134 mod->modname = NOFAIL(malloc(namelen + 1));
135 filename2modname(mod->modname, mod->filename);
138 list_add_tail(&mod->list, list);
141 /* Compare len chars of a to b, with _ and - equivalent. */
142 static int modname_equal(const char *a, const char *b, unsigned int len)
144 unsigned int i;
146 if (strlen(b) != len)
147 return 0;
149 for (i = 0; i < len; i++) {
150 if ((a[i] == '_' || a[i] == '-')
151 && (b[i] == '_' || b[i] == '-'))
152 continue;
153 if (a[i] != b[i])
154 return 0;
156 return 1;
159 /* Fills in list of modules if this is the line we want. */
160 static int add_modules_dep_line(char *line,
161 const char *name,
162 struct list_head *list,
163 const char *dirname)
165 char *ptr;
166 int len;
167 char *modname, *fullpath;
169 /* Ignore lines without : or which start with a # */
170 ptr = strchr(line, ':');
171 if (ptr == NULL || line[strspn(line, "\t ")] == '#')
172 return 0;
174 /* Is this the module we are looking for? */
175 *ptr = '\0';
176 modname = my_basename(line);
178 len = strlen(modname);
179 if (strchr(modname, '.'))
180 len = strchr(modname, '.') - modname;
181 if (!modname_equal(modname, name, len))
182 return 0;
184 /* Create the list. */
185 if ('/' == line[0]) { /* old style deps - absolute path specified */
186 add_module(line, ptr - line, list);
187 } else {
188 nofail_asprintf(&fullpath, "%s/%s", dirname, line);
189 add_module(fullpath, strlen(dirname)+1+(ptr - line), list);
190 free(fullpath);
193 ptr++;
194 for(;;) {
195 char *dep_start;
196 ptr += strspn(ptr, " \t");
197 if (*ptr == '\0')
198 break;
199 dep_start = ptr;
200 ptr += strcspn(ptr, " \t");
201 if ('/' == dep_start[0]) { /* old style deps */
202 add_module(dep_start, ptr - dep_start, list);
203 } else {
204 nofail_asprintf(&fullpath, "%s/%s", dirname, dep_start);
205 add_module(fullpath,
206 strlen(dirname)+1+(ptr - dep_start), list);
207 free(fullpath);
210 return 1;
213 static int read_depends_file(const char *dirname,
214 const char *start_name,
215 struct list_head *list)
217 char *modules_dep_name;
218 char *line;
219 struct index_file *modules_dep;
221 nofail_asprintf(&modules_dep_name, "%s/%s", dirname, "modules.dep.bin");
222 modules_dep = index_file_open(modules_dep_name);
223 if (!modules_dep) {
224 free(modules_dep_name);
225 return 0;
228 line = index_search(modules_dep, start_name);
229 if (line) {
230 /* Value is standard dependency line format */
231 if (!add_modules_dep_line(line, start_name, list, dirname))
232 fatal("Module index is inconsistent\n");
233 free(line);
236 index_file_close(modules_dep);
237 free(modules_dep_name);
239 return 1;
242 static void read_depends(const char *dirname,
243 const char *start_name,
244 struct list_head *list)
246 char *modules_dep_name;
247 char *line;
248 FILE *modules_dep;
249 int done = 0;
251 if (use_binary_indexes)
252 if (read_depends_file(dirname, start_name, list))
253 return;
255 nofail_asprintf(&modules_dep_name, "%s/%s", dirname, "modules.dep");
256 modules_dep = fopen(modules_dep_name, "r");
257 if (!modules_dep)
258 fatal("Could not load %s: %s\n",
259 modules_dep_name, strerror(errno));
261 /* Stop at first line, as we can have duplicates (eg. symlinks
262 from boot/ */
263 while (!done && (line = getline_wrapped(modules_dep, NULL)) != NULL) {
264 done = add_modules_dep_line(line, start_name, list, dirname);
265 free(line);
267 fclose(modules_dep);
268 free(modules_dep_name);
271 /* We use error numbers in a loose translation... */
272 static const char *insert_moderror(int err)
274 switch (err) {
275 case ENOEXEC:
276 return "Invalid module format";
277 case ENOENT:
278 return "Unknown symbol in module, or unknown parameter (see dmesg)";
279 case ENOSYS:
280 return "Kernel does not have module support";
281 default:
282 return strerror(err);
286 static const char *remove_moderror(int err)
288 switch (err) {
289 case ENOENT:
290 return "No such module";
291 case ENOSYS:
292 return "Kernel does not have module unloading support";
293 default:
294 return strerror(err);
298 static void replace_modname(struct elf_file *module,
299 void *mem, unsigned long len,
300 const char *oldname, const char *newname)
302 char *p;
304 /* 64 - sizeof(unsigned long) - 1 */
305 if (strlen(newname) > 55)
306 fatal("New name %s is too long\n", newname);
308 /* Find where it is in the module structure. Don't assume layout! */
309 for (p = mem; p < (char *)mem + len - strlen(oldname); p++) {
310 if (memcmp(p, oldname, strlen(oldname)) == 0) {
311 strcpy(p, newname);
312 return;
316 warn("Could not find old name in %s to replace!\n", module->pathname);
319 static void rename_module(struct elf_file *module,
320 const char *oldname,
321 const char *newname)
323 void *modstruct;
324 unsigned long len;
326 /* Old-style */
327 modstruct = module->ops->load_section(module,
328 ".gnu.linkonce.this_module", &len);
329 /* New-style */
330 if (!modstruct)
331 modstruct = module->ops->load_section(module, "__module", &len);
332 if (!modstruct)
333 warn("Could not find module name to change in %s\n",
334 module->pathname);
335 else
336 replace_modname(module, modstruct, len, oldname, newname);
339 static void clear_magic(struct elf_file *module)
341 struct string_table *tbl;
342 int j;
344 /* Old-style: __vermagic section */
345 module->ops->strip_section(module, "__vermagic");
347 /* New-style: in .modinfo section */
348 tbl = module->ops->load_strings(module, ".modinfo", NULL, fatal);
349 for (j = 0; tbl && j < tbl->cnt; j++) {
350 const char *p = tbl->str[j];
351 if (strstarts(p, "vermagic=")) {
352 memset((char *)p, 0, strlen(p));
353 return;
358 struct module_options
360 struct module_options *next;
361 char *modulename;
362 char *options;
365 struct module_command
367 struct module_command *next;
368 char *modulename;
369 char *command;
372 struct module_alias
374 struct module_alias *next;
375 char *module;
378 struct module_blacklist
380 struct module_blacklist *next;
381 char *modulename;
384 /* Link in a new option line from the config file. */
385 static struct module_options *
386 add_options(const char *modname,
387 const char *option,
388 struct module_options *options)
390 struct module_options *new;
391 char *tab;
393 new = NOFAIL(malloc(sizeof(*new)));
394 new->modulename = NOFAIL(strdup(modname));
395 new->options = NOFAIL(strdup(option));
396 /* We can handle tabs, kernel can't. */
397 for (tab = strchr(new->options, '\t'); tab; tab = strchr(tab, '\t'))
398 *tab = ' ';
399 new->next = options;
400 return new;
403 /* Link in a new install line from the config file. */
404 static struct module_command *
405 add_command(const char *modname,
406 const char *command,
407 struct module_command *commands)
409 struct module_command *new;
411 new = NOFAIL(malloc(sizeof(*new)));
412 new->modulename = NOFAIL(strdup(modname));
413 new->command = NOFAIL(strdup(command));
414 new->next = commands;
415 return new;
418 /* Link in a new alias line from the config file. */
419 static struct module_alias *
420 add_alias(const char *modname, struct module_alias *aliases)
422 struct module_alias *new;
424 new = NOFAIL(malloc(sizeof(*new)));
425 new->module = NOFAIL(strdup(modname));
426 new->next = aliases;
427 return new;
430 /* Link in a new blacklist line from the config file. */
431 static struct module_blacklist *
432 add_blacklist(const char *modname, struct module_blacklist *blacklist)
434 struct module_blacklist *new;
436 new = NOFAIL(malloc(sizeof(*new)));
437 new->modulename = NOFAIL(strdup(modname));
438 new->next = blacklist;
439 return new;
442 /* Find blacklist commands if any. */
443 static int
444 find_blacklist(const char *modname, const struct module_blacklist *blacklist)
446 while (blacklist) {
447 if (streq(blacklist->modulename, modname))
448 return 1;
449 blacklist = blacklist->next;
451 return 0;
454 /* return a new alias list, with backlisted elems filtered out */
455 static struct module_alias *
456 apply_blacklist(const struct module_alias *aliases,
457 const struct module_blacklist *blacklist)
459 struct module_alias *result = NULL;
460 while (aliases) {
461 char *modname = aliases->module;
462 if (!find_blacklist(modname, blacklist))
463 result = add_alias(modname, result);
464 aliases = aliases->next;
466 return result;
469 /* Find install commands if any. */
470 static const char *find_command(const char *modname,
471 const struct module_command *commands)
473 while (commands) {
474 if (fnmatch(commands->modulename, modname, 0) == 0)
475 return commands->command;
476 commands = commands->next;
478 return NULL;
481 static char *append_option(char *options, const char *newoption)
483 options = NOFAIL(realloc(options, strlen(options) + 1
484 + strlen(newoption) + 1));
485 if (strlen(options)) strcat(options, " ");
486 strcat(options, newoption);
487 return options;
490 static char *prepend_option(char *options, const char *newoption)
492 size_t l1, l2;
493 l1 = strlen(options);
494 l2 = strlen(newoption);
495 /* the resulting string will look like
496 * newoption + ' ' + options + '\0' */
497 if (l1) {
498 options = NOFAIL(realloc(options, l2 + 1 + l1 + 1));
499 memmove(options + l2 + 1, options, l1 + 1);
500 options[l2] = ' ';
501 memcpy(options, newoption, l2);
502 } else {
503 options = NOFAIL(realloc(options, l2 + 1));
504 memcpy(options, newoption, l2);
505 options[l2] = '\0';
507 return options;
510 /* Add to options */
511 static char *add_extra_options(const char *modname,
512 char *optstring,
513 const struct module_options *options)
515 while (options) {
516 if (streq(options->modulename, modname))
517 optstring = prepend_option(optstring, options->options);
518 options = options->next;
520 return optstring;
523 /* Read sysfs attribute into a buffer.
524 * returns: 1 = ok, 0 = attribute missing,
525 * -1 = file error (or empty file, but we don't care).
527 static int read_attribute(const char *filename, char *buf, size_t buflen)
529 FILE *file;
530 char *s;
532 file = fopen(filename, "r");
533 if (file == NULL)
534 return (errno == ENOENT) ? 0 : -1;
535 s = fgets(buf, buflen, file);
536 fclose(file);
538 return (s == NULL) ? -1 : 1;
541 /* is this a built-in module?
542 * 0: no, 1: yes, -1: don't know
544 static int module_builtin(const char *dirname, const char *modname)
546 struct index_file *index;
547 char *filename, *value;
549 nofail_asprintf(&filename, "%s/modules.builtin.bin", dirname);
550 index = index_file_open(filename);
551 free(filename);
552 if (!index)
553 return -1;
554 value = index_search(index, modname);
555 free(value);
556 return value ? 1 : 0;
559 /* Is module in /sys/module? If so, fill in usecount if not NULL.
560 0 means no, 1 means yes, -1 means unknown.
562 static int module_in_kernel(const char *modname, unsigned int *usecount)
564 int ret;
565 char *name;
566 struct stat finfo;
568 const int ATTR_LEN = 16;
569 char attr[ATTR_LEN];
571 /* Check sysfs is mounted */
572 if (stat("/sys/module", &finfo) < 0)
573 return -1;
575 /* Find module. */
576 nofail_asprintf(&name, "/sys/module/%s", modname);
577 ret = stat(name, &finfo);
578 free(name);
579 if (ret < 0)
580 return (errno == ENOENT) ? 0 : -1; /* Not found or unknown. */
582 /* Wait for the existing module to either go live or disappear. */
583 nofail_asprintf(&name, "/sys/module/%s/initstate", modname);
584 while (1) {
585 ret = read_attribute(name, attr, ATTR_LEN);
586 if (ret != 1 || streq(attr, "live\n"))
587 break;
589 usleep(100000);
591 free(name);
593 if (ret != 1)
594 return ret;
596 /* Get reference count, if it exists. */
597 if (usecount != NULL) {
598 nofail_asprintf(&name, "/sys/module/%s/refcnt", modname);
599 ret = read_attribute(name, attr, ATTR_LEN);
600 free(name);
601 if (ret == 1)
602 *usecount = atoi(attr);
605 return 1;
608 void dump_modversions(const char *filename, errfn_t error)
610 struct elf_file *module;
612 module = grab_elf_file(filename);
613 if (!module) {
614 error("%s: %s\n", filename, strerror(errno));
615 return;
617 if (module->ops->dump_modvers(module) < 0)
618 error("Wrong section size in '%s'\n", filename);
619 release_elf_file(module);
622 /* Does path contain directory(s) subpath? */
623 static int type_matches(const char *path, const char *subpath)
625 char *subpath_with_slashes;
626 int ret;
628 nofail_asprintf(&subpath_with_slashes, "/%s/", subpath);
630 ret = (strstr(path, subpath_with_slashes) != NULL);
631 free(subpath_with_slashes);
632 return ret;
636 static int do_wildcard(const char *dirname,
637 const char *type,
638 const char *wildcard)
640 char *modules_dep_name;
641 char *line, *wcard;
642 FILE *modules_dep;
644 /* Canonicalize wildcard */
645 wcard = strdup(wildcard);
646 underscores(wcard);
648 nofail_asprintf(&modules_dep_name, "%s/%s", dirname, "modules.dep");
649 modules_dep = fopen(modules_dep_name, "r");
650 if (!modules_dep)
651 fatal("Could not load %s: %s\n",
652 modules_dep_name, strerror(errno));
654 while ((line = getline_wrapped(modules_dep, NULL)) != NULL) {
655 char *ptr;
657 /* Ignore lines without : or which start with a # */
658 ptr = strchr(line, ':');
659 if (ptr == NULL || line[strspn(line, "\t ")] == '#')
660 goto next;
661 *ptr = '\0';
663 /* "type" must match complete directory component(s). */
664 if (!type || type_matches(line, type)) {
665 char modname[strlen(line)+1];
667 filename2modname(modname, line);
668 if (fnmatch(wcard, modname, 0) == 0)
669 printf("%s\n", line);
671 next:
672 free(line);
675 free(modules_dep_name);
676 free(wcard);
677 return 0;
680 static char *strsep_skipspace(char **string, char *delim)
682 if (!*string)
683 return NULL;
684 *string += strspn(*string, delim);
685 return strsep(string, delim);
688 static int parse_config_scan(const char *filename,
689 const char *name,
690 int dump_only,
691 int removing,
692 struct module_options **options,
693 struct module_command **commands,
694 struct module_alias **alias,
695 struct module_blacklist **blacklist);
697 static int parse_config_file(const char *filename,
698 const char *name,
699 int dump_only,
700 int removing,
701 struct module_options **options,
702 struct module_command **commands,
703 struct module_alias **aliases,
704 struct module_blacklist **blacklist)
706 char *line;
707 unsigned int linenum = 0;
708 FILE *cfile;
710 cfile = fopen(filename, "r");
711 if (!cfile)
712 return 0;
714 while ((line = getline_wrapped(cfile, &linenum)) != NULL) {
715 char *ptr = line;
716 char *cmd, *modname;
718 if (dump_only)
719 printf("%s\n", line);
721 cmd = strsep_skipspace(&ptr, "\t ");
722 if (cmd == NULL || cmd[0] == '#' || cmd[0] == '\0') {
723 free(line);
724 continue;
727 if (streq(cmd, "alias")) {
728 char *wildcard = strsep_skipspace(&ptr, "\t ");
729 char *realname = strsep_skipspace(&ptr, "\t ");
731 if (!wildcard || !realname)
732 grammar(cmd, filename, linenum);
733 else if (fnmatch(underscores(wildcard),name,0) == 0)
734 *aliases = add_alias(underscores(realname), *aliases);
735 } else if (streq(cmd, "include")) {
736 struct module_alias *newalias = NULL;
737 char *newfilename;
739 newfilename = strsep_skipspace(&ptr, "\t ");
740 if (!newfilename) {
741 grammar(cmd, filename, linenum);
742 } else {
743 warn("\"include %s\" is deprecated, "
744 "please use /etc/modprobe.d\n", newfilename);
745 if (strstarts(newfilename, "/etc/modprobe.d")) {
746 warn("\"include /etc/modprobe.d\" is "
747 "the default, ignored\n");
748 } else {
749 if (!parse_config_scan(newfilename, name,
750 dump_only, removing,
751 options, commands, &newalias,
752 blacklist))
753 warn("Failed to open included"
754 " config file %s: %s\n",
755 newfilename, strerror(errno));
757 /* Files included override aliases,
758 etc that was already set ... */
759 if (newalias)
760 *aliases = newalias;
762 } else if (streq(cmd, "options")) {
763 modname = strsep_skipspace(&ptr, "\t ");
764 if (!modname || !ptr)
765 grammar(cmd, filename, linenum);
766 else {
767 ptr += strspn(ptr, "\t ");
768 *options = add_options(underscores(modname),
769 ptr, *options);
771 } else if (streq(cmd, "install")) {
772 modname = strsep_skipspace(&ptr, "\t ");
773 if (!modname || !ptr)
774 grammar(cmd, filename, linenum);
775 else if (!removing) {
776 ptr += strspn(ptr, "\t ");
777 *commands = add_command(underscores(modname),
778 ptr, *commands);
780 } else if (streq(cmd, "blacklist")) {
781 modname = strsep_skipspace(&ptr, "\t ");
782 if (!modname)
783 grammar(cmd, filename, linenum);
784 else if (!removing) {
785 *blacklist = add_blacklist(underscores(modname),
786 *blacklist);
788 } else if (streq(cmd, "remove")) {
789 modname = strsep_skipspace(&ptr, "\t ");
790 if (!modname || !ptr)
791 grammar(cmd, filename, linenum);
792 else if (removing) {
793 ptr += strspn(ptr, "\t ");
794 *commands = add_command(underscores(modname),
795 ptr, *commands);
797 } else if (streq(cmd, "config")) {
798 char *tmp = strsep_skipspace(&ptr, "\t ");
800 if (!tmp)
801 grammar(cmd, filename, linenum);
802 else if (streq(tmp, "binary_indexes")) {
803 tmp = strsep_skipspace(&ptr, "\t ");
804 if (streq(tmp, "yes"))
805 use_binary_indexes = 1;
806 if (streq(tmp, "no"))
807 use_binary_indexes = 0;
809 } else
810 grammar(cmd, filename, linenum);
812 free(line);
814 fclose(cfile);
815 return 1;
818 /* fallback to plain-text aliases file as necessary */
819 static int read_aliases_file(const char *filename,
820 const char *name,
821 int dump_only,
822 int removing,
823 struct module_options **options,
824 struct module_command **commands,
825 struct module_alias **aliases,
826 struct module_blacklist **blacklist)
828 struct index_value *realnames;
829 struct index_value *realname;
830 char *binfile;
831 struct index_file *index;
833 if (!use_binary_indexes)
834 goto plain_text;
836 nofail_asprintf(&binfile, "%s.bin", filename);
837 index = index_file_open(binfile);
838 if (!index) {
839 free(binfile);
840 goto plain_text;
843 if (dump_only) {
844 index_dump(index, stdout, "alias ");
845 free(binfile);
846 index_file_close(index);
847 return 1;
850 realnames = index_searchwild(index, name);
851 for (realname = realnames; realname; realname = realname->next)
852 *aliases = add_alias(realname->value, *aliases);
853 index_values_free(realnames);
855 free(binfile);
856 index_file_close(index);
857 return 1;
859 plain_text:
860 return parse_config_file(filename, name, dump_only, removing,
861 options, commands, aliases, blacklist);
864 static int parse_config_scan(const char *filename,
865 const char *name,
866 int dump_only,
867 int removing,
868 struct module_options **options,
869 struct module_command **commands,
870 struct module_alias **aliases,
871 struct module_blacklist **blacklist)
873 DIR *dir;
874 int ret = 0;
876 dir = opendir(filename);
877 if (dir) {
878 struct file_entry {
879 struct list_head node;
880 char name[];
882 LIST_HEAD(files_list);
883 struct file_entry *fe, *fe_tmp;
884 struct dirent *i;
886 /* sort files from directory into list */
887 while ((i = readdir(dir)) != NULL) {
888 size_t len;
890 if (i->d_name[0] == '.')
891 continue;
892 if (!config_filter(i->d_name))
893 continue;
895 len = strlen(i->d_name);
896 if (len < 6 ||
897 (strcmp(&i->d_name[len-5], ".conf") != 0 &&
898 strcmp(&i->d_name[len-6], ".alias") != 0))
899 warn("All config files need .conf: %s/%s, "
900 "it will be ignored in a future release.\n",
901 filename, i->d_name);
902 fe = malloc(sizeof(struct file_entry) + len + 1);
903 if (fe == NULL)
904 continue;
905 strcpy(fe->name, i->d_name);
906 list_for_each_entry(fe_tmp, &files_list, node)
907 if (strcmp(fe_tmp->name, fe->name) >= 0)
908 break;
909 list_add_tail(&fe->node, &fe_tmp->node);
911 closedir(dir);
913 /* parse list of files */
914 list_for_each_entry_safe(fe, fe_tmp, &files_list, node) {
915 char *cfgfile;
917 nofail_asprintf(&cfgfile, "%s/%s", filename, fe->name);
918 if (!parse_config_file(cfgfile, name,
919 dump_only, removing,
920 options, commands,
921 aliases, blacklist))
922 warn("Failed to open config file "
923 "%s: %s\n", fe->name, strerror(errno));
924 free(cfgfile);
925 list_del(&fe->node);
926 free(fe);
929 ret = 1;
930 } else {
931 if (parse_config_file(filename, name, dump_only, removing,
932 options, commands, aliases, blacklist))
933 ret = 1;
935 return ret;
938 /* Read binary index file containing aliases only */
939 static void parse_toplevel_config(const char *filename,
940 const char *name,
941 int dump_only,
942 int removing,
943 struct module_options **options,
944 struct module_command **commands,
945 struct module_alias **aliases,
946 struct module_blacklist **blacklist)
948 if (filename) {
949 if (!parse_config_scan(filename, name, dump_only, removing,
950 options, commands, aliases, blacklist))
951 fatal("Failed to open config file %s: %s\n",
952 filename, strerror(errno));
953 return;
956 /* deprecated config file */
957 if (parse_config_file("/etc/modprobe.conf", name, dump_only, removing,
958 options, commands, aliases, blacklist) > 0)
959 warn("Deprecated config file /etc/modprobe.conf, "
960 "all config files belong into /etc/modprobe.d/.\n");
962 /* default config */
963 parse_config_scan("/etc/modprobe.d", name, dump_only, removing,
964 options, commands, aliases, blacklist);
967 /* Read possible module arguments from the kernel command line. */
968 static int parse_kcmdline(int dump_only, struct module_options **options)
970 char *line;
971 unsigned int linenum = 0;
972 FILE *kcmdline;
974 kcmdline = fopen("/proc/cmdline", "r");
975 if (!kcmdline)
976 return 0;
978 while ((line = getline_wrapped(kcmdline, &linenum)) != NULL) {
979 char *ptr = line;
980 char *arg;
982 while ((arg = strsep_skipspace(&ptr, "\t ")) != NULL) {
983 char *sep, *modname, *opt;
985 sep = strchr(arg, '.');
986 if (sep) {
987 if (!strchr(sep, '='))
988 continue;
989 modname = arg;
990 *sep = '\0';
991 opt = ++sep;
993 if (dump_only)
994 printf("options %s %s\n", modname, opt);
996 *options = add_options(underscores(modname),
997 opt, *options);
1001 free(line);
1003 fclose(kcmdline);
1004 return 1;
1007 static void add_to_env_var(const char *option)
1009 const char *oldenv;
1011 if ((oldenv = getenv("MODPROBE_OPTIONS")) != NULL) {
1012 char *newenv;
1013 nofail_asprintf(&newenv, "%s %s", oldenv, option);
1014 setenv("MODPROBE_OPTIONS", newenv, 1);
1015 } else
1016 setenv("MODPROBE_OPTIONS", option, 1);
1019 /* Prepend options from environment. */
1020 static char **merge_args(char *args, char *argv[], int *argc)
1022 char *arg, *argstring;
1023 char **newargs = NULL;
1024 unsigned int i, num_env = 0;
1026 if (!args)
1027 return argv;
1029 argstring = NOFAIL(strdup(args));
1030 for (arg = strtok(argstring, " "); arg; arg = strtok(NULL, " ")) {
1031 num_env++;
1032 newargs = NOFAIL(realloc(newargs,
1033 sizeof(newargs[0])
1034 * (num_env + *argc + 1)));
1035 newargs[num_env] = arg;
1038 if (!newargs)
1039 return argv;
1041 /* Append commandline args */
1042 newargs[0] = argv[0];
1043 for (i = 1; i <= *argc; i++)
1044 newargs[num_env+i] = argv[i];
1046 *argc += num_env;
1047 return newargs;
1050 static char *gather_options(char *argv[])
1052 char *optstring = NOFAIL(strdup(""));
1054 /* Rest is module options */
1055 while (*argv) {
1056 /* Quote value if it contains spaces. */
1057 unsigned int eq = strcspn(*argv, "=");
1059 if (strchr(*argv+eq, ' ') && !strchr(*argv, '"')) {
1060 char quoted[strlen(*argv) + 3];
1061 (*argv)[eq] = '\0';
1062 sprintf(quoted, "%s=\"%s\"", *argv, *argv+eq+1);
1063 optstring = append_option(optstring, quoted);
1064 } else
1065 optstring = append_option(optstring, *argv);
1066 argv++;
1068 return optstring;
1071 /* Do an install/remove command: replace $CMDLINE_OPTS if it's specified. */
1072 static void do_command(const char *modname,
1073 const char *command,
1074 int dry_run,
1075 errfn_t error,
1076 const char *type,
1077 const char *cmdline_opts)
1079 int ret;
1080 char *p, *replaced_cmd = NOFAIL(strdup(command));
1082 while ((p = strstr(replaced_cmd, "$CMDLINE_OPTS")) != NULL) {
1083 char *new;
1084 nofail_asprintf(&new, "%.*s%s%s",
1085 (int)(p - replaced_cmd), replaced_cmd, cmdline_opts,
1086 p + strlen("$CMDLINE_OPTS"));
1087 free(replaced_cmd);
1088 replaced_cmd = new;
1091 info("%s %s\n", type, replaced_cmd);
1092 if (dry_run)
1093 return;
1095 setenv("MODPROBE_MODULE", modname, 1);
1096 ret = system(replaced_cmd);
1097 if (ret == -1 || WEXITSTATUS(ret))
1098 error("Error running %s command for %s\n", type, modname);
1099 free(replaced_cmd);
1102 /* Actually do the insert. Frees second arg. */
1103 static int insmod(struct list_head *list,
1104 char *optstring,
1105 const char *newname,
1106 const struct module_options *options,
1107 const struct module_command *commands,
1108 const char *cmdline_opts,
1109 errfn_t error,
1110 modprobe_flags_t flags)
1112 int ret, fd;
1113 struct elf_file *module;
1114 const char *command;
1115 struct module *mod = list_entry(list->next, struct module, list);
1116 int rc = 0;
1118 /* Take us off the list. */
1119 list_del(&mod->list);
1121 /* Do things we (or parent) depend on first. */
1122 if (!list_empty(list)) {
1123 modprobe_flags_t f = flags;
1124 f &= ~mit_first_time;
1125 f &= ~mit_ignore_commands;
1126 if ((rc = insmod(list, NOFAIL(strdup("")), NULL,
1127 options, commands, "", warn, f)) != 0) {
1128 error("Error inserting %s (%s): %s\n",
1129 mod->modname, mod->filename,
1130 insert_moderror(errno));
1131 goto out_optstring;
1135 fd = open_file(mod->filename);
1136 if (fd < 0) {
1137 error("Could not open '%s': %s\n",
1138 mod->filename, strerror(errno));
1139 goto out_optstring;
1142 /* Don't do ANYTHING if already in kernel. */
1143 if (!(flags & mit_ignore_loaded)
1144 && module_in_kernel(newname ?: mod->modname, NULL) == 1) {
1145 if (flags & mit_first_time)
1146 error("Module %s already in kernel.\n",
1147 newname ?: mod->modname);
1148 goto out_unlock;
1151 command = find_command(mod->modname, commands);
1152 if (command && !(flags & mit_ignore_commands)) {
1153 close_file(fd);
1154 do_command(mod->modname, command, flags & mit_dry_run, error,
1155 "install", cmdline_opts);
1156 goto out_optstring;
1159 module = grab_elf_file_fd(mod->filename, fd);
1160 if (!module) {
1161 error("Could not read '%s': %s\n", mod->filename,
1162 (errno == ENOEXEC) ? "Invalid module format" :
1163 strerror(errno));
1164 goto out_unlock;
1166 if (newname)
1167 rename_module(module, mod->modname, newname);
1168 if (flags & mit_strip_modversion)
1169 module->ops->strip_section(module, "__versions");
1170 if (flags & mit_strip_vermagic)
1171 clear_magic(module);
1173 /* Config file might have given more options */
1174 optstring = add_extra_options(mod->modname, optstring, options);
1176 info("insmod %s %s\n", mod->filename, optstring);
1178 if (flags & mit_dry_run)
1179 goto out;
1181 ret = init_module(module->data, module->len, optstring);
1182 if (ret != 0) {
1183 if (errno == EEXIST) {
1184 if (flags & mit_first_time)
1185 error("Module %s already in kernel.\n",
1186 newname ?: mod->modname);
1187 goto out_unlock;
1189 /* don't warn noisely if we're loading multiple aliases. */
1190 /* one of the aliases may try to use hardware we don't have. */
1191 if ((error != warn) || (verbose))
1192 error("Error inserting %s (%s): %s\n",
1193 mod->modname, mod->filename,
1194 insert_moderror(errno));
1195 rc = 1;
1197 out:
1198 release_elf_file(module);
1199 out_unlock:
1200 close_file(fd);
1201 out_optstring:
1202 free(optstring);
1203 return rc;
1206 /* Do recursive removal. */
1207 static void rmmod(struct list_head *list,
1208 const char *name,
1209 struct module_command *commands,
1210 const char *cmdline_opts,
1211 errfn_t error,
1212 modprobe_flags_t flags)
1214 const char *command;
1215 unsigned int usecount = 0;
1216 struct module *mod = list_entry(list->next, struct module, list);
1218 /* Take first one off the list. */
1219 list_del(&mod->list);
1221 if (!name)
1222 name = mod->modname;
1224 /* Even if renamed, find commands to orig. name. */
1225 command = find_command(mod->modname, commands);
1226 if (command && !(flags & mit_ignore_commands)) {
1227 do_command(mod->modname, command, flags & mit_dry_run, error,
1228 "remove", cmdline_opts);
1229 goto remove_rest;
1232 if (module_in_kernel(name, &usecount) == 0)
1233 goto nonexistent_module;
1235 if (usecount != 0) {
1236 if (!(flags & mit_ignore_loaded))
1237 error("Module %s is in use.\n", name);
1238 goto remove_rest;
1241 info("rmmod %s\n", mod->filename);
1243 if (flags & mit_dry_run)
1244 goto remove_rest;
1246 if (delete_module(name, O_EXCL) != 0) {
1247 if (errno == ENOENT)
1248 goto nonexistent_module;
1249 error("Error removing %s (%s): %s\n",
1250 name, mod->filename,
1251 remove_moderror(errno));
1254 remove_rest:
1255 /* Now do things we depend. */
1256 if (!list_empty(list)) {
1257 flags &= ~mit_first_time;
1258 flags &= ~mit_ignore_commands;
1259 flags |= mit_ignore_loaded;
1261 rmmod(list, NULL, commands, "", warn, flags);
1263 return;
1265 nonexistent_module:
1266 if (flags & mit_first_time)
1267 fatal("Module %s is not in kernel.\n", mod->modname);
1268 goto remove_rest;
1271 static int handle_module(const char *modname,
1272 struct list_head *todo_list,
1273 const char *newname,
1274 char *options,
1275 struct module_options *modoptions,
1276 struct module_command *commands,
1277 const char *cmdline_opts,
1278 errfn_t error,
1279 modprobe_flags_t flags)
1281 if (list_empty(todo_list)) {
1282 const char *command;
1284 /* The dependencies have to be real modules, but
1285 handle case where the first is completely bogus. */
1286 command = find_command(modname, commands);
1287 if (command && !(flags & mit_ignore_commands)) {
1288 do_command(modname, command, flags & mit_dry_run, error,
1289 (flags & mit_remove) ? "remove":"install", cmdline_opts);
1290 return 0;
1293 if (!quiet)
1294 error("Module %s not found.\n", modname);
1295 return 1;
1298 if (flags & mit_remove) {
1299 flags &= ~mit_ignore_loaded;
1300 rmmod(todo_list, newname, commands, cmdline_opts, error, flags);
1301 } else
1302 insmod(todo_list, NOFAIL(strdup(options)), newname,
1303 modoptions, commands, cmdline_opts, error, flags);
1305 return 0;
1308 int handle_builtin_module(const char *modname,
1309 errfn_t error,
1310 modprobe_flags_t flags)
1312 if (flags & mit_remove) {
1313 error("Module %s is builtin\n", modname);
1314 return 1;
1315 } else if (flags & mit_first_time) {
1316 error("Module %s already in kernel (builtin).\n", modname);
1317 return 1;
1318 } else if (flags & mit_ignore_loaded) {
1319 /* --show-depends given */
1320 info("builtin %s\n", modname);
1322 return 0;
1325 int do_modprobe(char *modname,
1326 char *newname,
1327 char *cmdline_opts,
1328 const char *configname,
1329 const char *dirname,
1330 const char *aliasfilename,
1331 const char *symfilename,
1332 errfn_t error,
1333 modprobe_flags_t flags)
1335 struct module_command *commands = NULL;
1336 struct module_options *modoptions = NULL;
1337 struct module_alias *aliases = NULL;
1338 struct module_blacklist *blacklist = NULL;
1339 LIST_HEAD(list);
1340 int failed = 0;
1342 /* Convert name we are looking for */
1343 underscores(modname);
1345 /* Returns the resolved alias, options */
1346 parse_toplevel_config(configname, modname, 0,
1347 flags & mit_remove, &modoptions, &commands, &aliases, &blacklist);
1349 /* Read module options from kernel command line */
1350 parse_kcmdline(0, &modoptions);
1352 /* No luck? Try symbol names, if starts with symbol:. */
1353 if (!aliases && strstarts(modname, "symbol:")) {
1354 parse_config_file(symfilename, modname, 0,
1355 flags & mit_remove, &modoptions, &commands,
1356 &aliases, &blacklist);
1358 if (!aliases) {
1359 if(!strchr(modname, ':'))
1360 read_depends(dirname, modname, &list);
1362 /* We only use canned aliases as last resort. */
1363 if (list_empty(&list)
1364 && !find_command(modname, commands))
1366 read_aliases_file(aliasfilename,
1367 modname, 0, flags & mit_remove,
1368 &modoptions, &commands,
1369 &aliases, &blacklist);
1370 /* builtin module? */
1371 if (!aliases && module_builtin(dirname, modname) > 0) {
1372 return handle_builtin_module(modname, error,
1373 flags);
1378 aliases = apply_blacklist(aliases, blacklist);
1379 if(flags & mit_resolve_alias) {
1380 for(; aliases; aliases=aliases->next)
1381 printf("%s\n", aliases->module);
1382 return 0;
1384 if (aliases) {
1385 errfn_t err = error;
1387 /* More than one alias? Don't bail out on failure. */
1388 if (aliases->next)
1389 err = warn;
1390 while (aliases) {
1391 /* Add the options for this alias. */
1392 char *opts = NOFAIL(strdup(cmdline_opts));
1393 opts = add_extra_options(modname,
1394 opts, modoptions);
1396 read_depends(dirname, aliases->module, &list);
1397 failed |= handle_module(aliases->module,
1398 &list, newname, opts, modoptions,
1399 commands, cmdline_opts, err, flags);
1401 aliases = aliases->next;
1402 INIT_LIST_HEAD(&list);
1404 } else {
1405 if (flags & mit_use_blacklist
1406 && find_blacklist(modname, blacklist))
1407 return failed;
1409 failed |= handle_module(modname, &list, newname, cmdline_opts,
1410 modoptions, commands, cmdline_opts, error, flags);
1412 return failed;
1415 static struct option options[] = { { "version", 0, NULL, 'V' },
1416 { "verbose", 0, NULL, 'v' },
1417 { "quiet", 0, NULL, 'q' },
1418 { "syslog", 0, NULL, 's' },
1419 { "show", 0, NULL, 'n' },
1420 { "dry-run", 0, NULL, 'n' },
1421 { "show-depends", 0, NULL, 'D' },
1422 { "resolve-alias", 0, NULL, 'R' },
1423 { "dirname", 1, NULL, 'd' },
1424 { "set-version", 1, NULL, 'S' },
1425 { "config", 1, NULL, 'C' },
1426 { "name", 1, NULL, 'o' },
1427 { "remove", 0, NULL, 'r' },
1428 { "showconfig", 0, NULL, 'c' },
1429 { "list", 0, NULL, 'l' },
1430 { "type", 1, NULL, 't' },
1431 { "all", 0, NULL, 'a' },
1432 { "ignore-install", 0, NULL, 'i' },
1433 { "ignore-remove", 0, NULL, 'i' },
1434 { "use-blacklist", 0, NULL, 'b' },
1435 { "force", 0, NULL, 'f' },
1436 { "force-vermagic", 0, NULL, 1 },
1437 { "force-modversion", 0, NULL, 2 },
1438 { "first-time", 0, NULL, 3 },
1439 { "dump-modversions", 0, NULL, 4 },
1440 { NULL, 0, NULL, 0 } };
1442 int main(int argc, char *argv[])
1444 struct utsname buf;
1445 struct stat statbuf;
1446 int opt;
1447 int dump_config = 0;
1448 int list_only = 0;
1449 int all = 0;
1450 int dump_modver = 0;
1451 unsigned int i, num_modules;
1452 char *type = NULL;
1453 const char *configname = NULL;
1454 char *basedir = "";
1455 char *cmdline_opts = NULL;
1456 char *newname = NULL;
1457 char *dirname, *aliasfilename, *symfilename;
1458 errfn_t error = fatal;
1459 int failed = 0;
1460 modprobe_flags_t flags = 0;
1462 /* Prepend options from environment. */
1463 argv = merge_args(getenv("MODPROBE_OPTIONS"), argv, &argc);
1465 uname(&buf);
1466 while ((opt = getopt_long(argc, argv, "Vvqsnd:C:o:rclt:aibf", options, NULL)) != -1){
1467 switch (opt) {
1468 case 'V':
1469 puts(PACKAGE " version " VERSION);
1470 exit(0);
1471 case 'v':
1472 add_to_env_var("-v");
1473 verbose = 1;
1474 break;
1475 case 'q':
1476 quiet = 1;
1477 add_to_env_var("-q");
1478 break;
1479 case 's':
1480 add_to_env_var("-s");
1481 logging = 1;
1482 break;
1483 case 'n':
1484 flags |= mit_dry_run;
1485 break;
1486 case 'd':
1487 basedir = optarg;
1488 break;
1489 case 'S':
1490 strncpy(buf.release, optarg, sizeof(buf.release));
1491 buf.release[sizeof(buf.release)-1] = '\0';
1492 break;
1493 case 'C':
1494 configname = optarg;
1495 add_to_env_var("-C");
1496 add_to_env_var(configname);
1497 break;
1498 case 'D':
1499 flags |= mit_dry_run;
1500 flags |= mit_ignore_loaded;
1501 verbose = 1;
1502 break;
1503 case 'R':
1504 flags |= mit_resolve_alias;
1505 break;
1506 case 'o':
1507 newname = optarg;
1508 break;
1509 case 'r':
1510 flags |= mit_remove;
1511 break;
1512 case 'c':
1513 dump_config = 1;
1514 break;
1515 case 'l':
1516 list_only = 1;
1517 break;
1518 case 't':
1519 type = optarg;
1520 break;
1521 case 'a':
1522 all = 1;
1523 error = warn;
1524 break;
1525 case 'i':
1526 flags |= mit_ignore_commands;
1527 break;
1528 case 'b':
1529 flags |= mit_use_blacklist;
1530 break;
1531 case 'f':
1532 flags |= mit_strip_vermagic;
1533 flags |= mit_strip_modversion;
1534 break;
1535 case 1:
1536 flags |= mit_strip_vermagic;
1537 break;
1538 case 2:
1539 flags |= mit_strip_modversion;
1540 break;
1541 case 3:
1542 flags |= mit_first_time;
1543 break;
1544 case 4:
1545 dump_modver = 1;
1546 break;
1547 default:
1548 print_usage(argv[0]);
1552 /* If stderr not open, go to syslog */
1553 if (logging || fstat(STDERR_FILENO, &statbuf) != 0) {
1554 openlog("modprobe", LOG_CONS, LOG_DAEMON);
1555 logging = 1;
1558 if (argc < optind + 1 && !dump_config && !list_only)
1559 print_usage(argv[0]);
1561 nofail_asprintf(&dirname, "%s%s/%s", basedir, MODULE_DIR, buf.release);
1562 nofail_asprintf(&aliasfilename, "%s/modules.alias", dirname);
1563 nofail_asprintf(&symfilename, "%s/modules.symbols", dirname);
1565 /* Old-style -t xxx wildcard? Only with -l. */
1566 if (list_only) {
1567 if (optind+1 < argc)
1568 fatal("Can't have multiple wildcards\n");
1569 /* fprintf(stderr, "man find\n"); return 1; */
1570 return do_wildcard(dirname, type, argv[optind]?:"*");
1572 if (type)
1573 fatal("-t only supported with -l");
1575 if (dump_config) {
1576 struct module_command *commands = NULL;
1577 struct module_options *modoptions = NULL;
1578 struct module_alias *aliases = NULL;
1579 struct module_blacklist *blacklist = NULL;
1581 parse_toplevel_config(configname, "", 1, 0, &modoptions,
1582 &commands, &aliases, &blacklist);
1583 /* Read module options from kernel command line */
1584 parse_kcmdline(1, &modoptions);
1585 parse_config_file(aliasfilename, "", 1, 0, &modoptions,
1586 &commands, &aliases, &blacklist);
1587 parse_config_file(symfilename, "", 1, 0, &modoptions,
1588 &commands, &aliases, &blacklist);
1589 exit(0);
1592 if ((flags & mit_remove) || all) {
1593 num_modules = argc - optind;
1594 cmdline_opts = NOFAIL(strdup(""));
1595 } else {
1596 num_modules = 1;
1597 cmdline_opts = gather_options(argv+optind+1);
1600 /* num_modules is always 1 except for -r or -a. */
1601 for (i = 0; i < num_modules; i++) {
1602 char *modname = argv[optind + i];
1604 if (dump_modver)
1605 dump_modversions(modname, error);
1606 else
1607 failed |= do_modprobe(modname, newname, cmdline_opts,
1608 configname, dirname, aliasfilename, symfilename,
1609 error, flags);
1612 if (logging)
1613 closelog();
1615 free(dirname);
1616 free(aliasfilename);
1617 free(symfilename);
1618 free(cmdline_opts);
1620 exit(failed);