release: bump the release to 3.14
[module-init-tools.git] / modprobe.c
blob5464f45d2cc1c74b08ce5c31dd97afcc034c4a3b
1 /* modprobe.c: add or remove a module from the kernel, intelligently.
3 * Copyright (C) 2001 Rusty Russell.
4 * Copyright (C) 2002, 2003 Rusty Russell, IBM Corporation.
5 * Copyright (C) 2006-2011 Jon Masters <jcm@jonmasters.org>, and others.
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor,
20 * Boston, MA 02110-1301, USA.
22 #define _GNU_SOURCE /* asprintf */
24 #include <sys/utsname.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <sys/mman.h>
28 #include <fcntl.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <ctype.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <unistd.h>
36 #include <dirent.h>
37 #include <limits.h>
38 #include <elf.h>
39 #include <getopt.h>
40 #include <fnmatch.h>
41 #include <asm/unistd.h>
42 #include <sys/wait.h>
43 #include <syslog.h>
45 #include "util.h"
46 #include "elfops.h"
47 #include "zlibsupport.h"
48 #include "logging.h"
49 #include "index.h"
50 #include "list.h"
51 #include "config_filter.h"
53 #include "testing.h"
55 /* NOTE: in the future, binary indexes will always be used */
56 static int use_binary_indexes = 1; /* default to enabled. */
58 /* Limit do_softdep/do_modprobe recursion.
59 * This is a simple way to handle dependency loops
60 * caused by poorly written softdep commands.
62 static int recursion_depth = 0;
63 static const int MAX_RECURSION = 50; /* Arbitrary choice */
65 extern long init_module(void *, unsigned long, const char *);
66 extern long delete_module(const char *, unsigned int);
68 struct module {
69 struct list_head list;
70 char *modname;
71 char filename[0];
74 typedef enum
76 mit_remove = 1,
77 mit_dry_run = 2,
78 mit_first_time = 4,
79 mit_use_blacklist = 8,
80 mit_ignore_commands = 16,
81 mit_ignore_loaded = 32,
82 mit_quiet_inuse = 64,
83 mit_strip_vermagic = 128,
84 mit_strip_modversion = 256,
85 mit_resolve_alias = 512
87 } modprobe_flags_t;
89 #ifndef MODULE_DIR
90 #define MODULE_DIR "/lib/modules"
91 #endif
93 /**
94 * print_usage - output the prefered program usage
96 * @progname: binary name invoked
99 static void print_usage(const char *progname)
101 fprintf(stderr,
102 "Usage: %s [-v] [-V] [-C config-file] [-d <dirname> ] [-n] [-i] [-q] [-b] [-o <modname>] [ --dump-modversions ] <modname> [parameters...]\n"
103 "%s -r [-n] [-i] [-v] <modulename> ...\n"
104 "%s -l -t <dirname> [ -a <modulename> ...]\n",
105 progname, progname, progname);
106 exit(1);
110 * find_module - search module list for module name
112 * @filename: module file name
113 * @list: module list
116 static struct module *find_module(const char *filename, struct list_head *list)
118 struct module *i;
120 list_for_each_entry(i, list, list) {
121 if (streq(i->filename, filename))
122 return i;
124 return NULL;
128 * add_module - add a module to the global module list
130 * @filename: module file name
131 * @list: module list
134 static void add_module(char *filename, int namelen, struct list_head *list)
136 struct module *mod;
138 /* If it's a duplicate: move it to the end, so it gets
139 inserted where it is *first* required. */
140 mod = find_module(filename, list);
141 if (mod)
142 list_del(&mod->list);
143 else {
144 /* No match. Create a new module. */
145 mod = NOFAIL(malloc(sizeof(struct module) + namelen + 1));
146 memcpy(mod->filename, filename, namelen);
147 mod->filename[namelen] = '\0';
148 mod->modname = NOFAIL(malloc(namelen + 1));
149 filename2modname(mod->modname, mod->filename);
152 list_add_tail(&mod->list, list);
156 * free_module - de-allocate module structure
158 * @mod: module structure
161 static void free_module(struct module *mod)
163 free(mod->modname);
164 free(mod);
168 * modname_equal - compare module names (up to len), with '_' and '-' equal
170 * @a: first module name
171 * @b: second module name
172 * @len: length to compare
175 static int modname_equal(const char *a, const char *b, unsigned int len)
177 unsigned int i;
179 if (strlen(b) != len)
180 return 0;
182 for (i = 0; i < len; i++) {
183 if ((a[i] == '_' || a[i] == '-')
184 && (b[i] == '_' || b[i] == '-'))
185 continue;
186 if (a[i] != b[i])
187 return 0;
189 return 1;
193 * add_modules_dep_line - parse a dep line from the module.dep[.bin] file
195 * @line: input file line
196 * @name: module name
197 * @list: list of modules
198 * @dirname: module directory
200 * Add dependency information if this line of the dep file matches mod name
202 static int add_modules_dep_line(char *line,
203 const char *name,
204 struct list_head *list,
205 const char *dirname)
207 char *ptr;
208 int len;
209 char *modname, *fullpath;
211 /* Ignore lines without : or which start with a # */
212 ptr = strchr(line, ':');
213 if (ptr == NULL || line[strspn(line, "\t ")] == '#')
214 return 0;
216 /* Is this the module we are looking for? */
217 *ptr = '\0';
218 modname = my_basename(line);
220 len = strlen(modname);
221 if (strchr(modname, '.'))
222 len = strchr(modname, '.') - modname;
223 if (!modname_equal(modname, name, len))
224 return 0;
226 /* Create the list. */
227 if ('/' == line[0]) { /* old style deps - absolute path specified */
228 add_module(line, ptr - line, list);
229 } else {
230 nofail_asprintf(&fullpath, "%s/%s", dirname, line);
231 add_module(fullpath, strlen(dirname)+1+(ptr - line), list);
232 free(fullpath);
235 ptr++;
236 for(;;) {
237 char *dep_start;
238 ptr += strspn(ptr, " \t");
239 if (*ptr == '\0')
240 break;
241 dep_start = ptr;
242 ptr += strcspn(ptr, " \t");
244 /* We handle deps in two possible ways. Either they have */
245 /* an absolute path, or a relative path (to toplevel moddir). */
247 if ('/' == dep_start[0]) { /* old style deps */
248 add_module(dep_start, ptr - dep_start, list);
249 } else {
250 nofail_asprintf(&fullpath, "%s/%s", dirname, dep_start);
251 add_module(fullpath,
252 strlen(dirname)+1+(ptr - dep_start), list);
253 free(fullpath);
256 return 1;
260 * read_depends_file - import the modules.dep.bin file
262 * @dirname: module directory
263 * @start_name: initial module name to search
264 * @list: list of modules
267 static int read_depends_file(const char *dirname,
268 const char *start_name,
269 struct list_head *list)
271 char *modules_dep_name;
272 char *line;
273 struct index_file *modules_dep;
275 nofail_asprintf(&modules_dep_name, "%s/%s", dirname, "modules.dep.bin");
276 modules_dep = index_file_open(modules_dep_name);
277 if (!modules_dep) {
278 free(modules_dep_name);
279 return 0;
282 line = index_search(modules_dep, start_name);
283 if (line) {
284 /* Value is standard dependency line format */
285 if (!add_modules_dep_line(line, start_name, list, dirname))
286 fatal("Module index is inconsistent\n");
287 free(line);
290 index_file_close(modules_dep);
291 free(modules_dep_name);
293 return 1;
297 * read_depends - import the modules.dep[.bin] file
299 * @dirname: module directory
300 * @start_name: initial module name to search
301 * @list: list of modules
304 static void read_depends(const char *dirname,
305 const char *start_name,
306 struct list_head *list)
308 char *modules_dep_name;
309 char *line;
310 FILE *modules_dep;
311 int done = 0;
313 if (use_binary_indexes)
314 if (read_depends_file(dirname, start_name, list))
315 return;
317 nofail_asprintf(&modules_dep_name, "%s/%s", dirname, "modules.dep");
318 modules_dep = fopen(modules_dep_name, "r");
319 if (!modules_dep)
320 fatal("Could not load %s: %s\n",
321 modules_dep_name, strerror(errno));
323 /* Stop at first line, as we can have duplicates (eg. symlinks
324 from boot/ */
325 while (!done && (line = getline_wrapped(modules_dep, NULL)) != NULL) {
326 done = add_modules_dep_line(line, start_name, list, dirname);
327 free(line);
329 fclose(modules_dep);
330 free(modules_dep_name);
334 * insert_moderror - convert standard insert error numbers into error messages
336 * @err: error number
339 static const char *insert_moderror(int err)
341 switch (err) {
342 case ENOEXEC:
343 return "Invalid module format";
344 case ENOENT:
345 return "Unknown symbol in module, or unknown parameter (see dmesg)";
346 case ENOSYS:
347 return "Kernel does not have module support";
348 default:
349 return strerror(err);
354 * remove_moderror - convert standard remove error numbers into error messages
356 * @err: error number
359 static const char *remove_moderror(int err)
361 switch (err) {
362 case ENOENT:
363 return "No such module";
364 case ENOSYS:
365 return "Kernel does not have module unloading support";
366 default:
367 return strerror(err);
371 * clear_magic - strip any versioning information from the module
373 * @module: mapped module file
376 static void clear_magic(struct elf_file *module)
378 struct string_table *tbl;
379 int j;
381 /* Old-style: __vermagic section */
382 module->ops->strip_section(module, "__vermagic");
384 /* New-style: in .modinfo section */
385 tbl = module->ops->load_strings(module, ".modinfo", NULL);
386 for (j = 0; tbl && j < tbl->cnt; j++) {
387 const char *p = tbl->str[j];
388 if (strstarts(p, "vermagic=")) {
389 memset((char *)p, 0, strlen(p));
390 return;
395 /* keep track of module options from config file(s) */
396 struct module_options
398 struct module_options *next;
399 char *modulename;
400 char *options;
403 /* keep track of module install commands from config file(s) */
404 struct module_command
406 struct module_command *next;
407 char *modulename;
408 char *command;
411 /* keep track of module aliases added in the config file(s) */
412 struct module_alias
414 struct module_alias *next;
415 char *aliasname;
416 char *module;
419 /* keep track of modules blacklisted in the config file(s) */
420 struct module_blacklist
422 struct module_blacklist *next;
423 char *modulename;
426 /* keep track of module softdeps added in the config file(s) */
427 struct module_softdep
429 struct module_softdep *next;
430 char *buf;
431 /* The modname and string tables point to buf. */
432 char *modname;
433 struct string_table *pre;
434 struct string_table *post;
437 /* keep track of all config options */
438 struct modprobe_conf
440 struct module_options *options;
441 struct module_command *commands;
442 struct module_alias *aliases;
443 struct module_blacklist *blacklist;
444 struct module_softdep *softdeps;
448 * add_options - module options added in the config file(s)
450 * @modname: module name
451 * @option: options string
452 * @options: list of options
455 static struct module_options *
456 add_options(const char *modname,
457 const char *option,
458 struct module_options *options)
460 struct module_options *new;
461 char *tab;
463 new = NOFAIL(malloc(sizeof(*new)));
464 new->modulename = NOFAIL(strdup(modname));
465 new->options = NOFAIL(strdup(option));
466 /* We can handle tabs, kernel can't. */
467 for (tab = strchr(new->options, '\t'); tab; tab = strchr(tab, '\t'))
468 *tab = ' ';
469 new->next = options;
470 return new;
474 * add_command - module install commands added in the config file(s)
476 * @modname: module name
477 * @command: command string
478 * @commands: list of commands
481 static struct module_command *
482 add_command(const char *modname,
483 const char *command,
484 struct module_command *commands)
486 struct module_command *new;
488 new = NOFAIL(malloc(sizeof(*new)));
489 new->modulename = NOFAIL(strdup(modname));
490 new->command = NOFAIL(strdup(command));
491 new->next = commands;
492 return new;
496 * add_alias - module aliases added in the config file(s)
498 * @aliasname: alias string
499 * @modname: module name
500 * @aliases: list of aliases
503 static struct module_alias *
504 add_alias(const char *aliasname, const char *modname, struct module_alias *aliases)
506 struct module_alias *new;
508 new = NOFAIL(malloc(sizeof(*new)));
509 new->aliasname = NOFAIL(strdup(aliasname));
510 new->module = NOFAIL(strdup(modname));
511 new->next = aliases;
512 return new;
517 * find_aliases - find aliases for a module
519 * @aliases: list of aliases
520 * @name: module name
523 static struct module_alias *
524 find_aliases(const struct module_alias *aliases,
525 const char *name)
527 struct module_alias *result = NULL;
528 while (aliases) {
529 char *aliasname = aliases->aliasname;
530 char *modname = aliases->module;
531 if (fnmatch(aliasname, name, 0) == 0)
532 result = add_alias(aliasname, modname, result);
533 aliases = aliases->next;
535 return result;
539 * free_aliases - de-allocate the aliases list
541 * @alias_list: list of aliases
544 static void free_aliases(struct module_alias *alias_list)
546 while (alias_list) {
547 struct module_alias *alias;
549 alias = alias_list;
550 alias_list = alias_list->next;
552 free(alias->aliasname);
553 free(alias->module);
554 free(alias);
559 * add_blacklist - blacklist modules in config file(s)
561 * @modname: module name
562 * @blacklist list of blacklisted module names
565 static struct module_blacklist *
566 add_blacklist(const char *modname, struct module_blacklist *blacklist)
568 struct module_blacklist *new;
570 new = NOFAIL(malloc(sizeof(*new)));
571 new->modulename = NOFAIL(strdup(modname));
572 new->next = blacklist;
573 return new;
577 * find_blacklist - lookup any potentially blacklisted module
579 * @modname: module name
580 * @blacklist: list of blacklisted module names
583 static int
584 find_blacklist(const char *modname, const struct module_blacklist *blacklist)
586 while (blacklist) {
587 if (streq(blacklist->modulename, modname))
588 return 1;
589 blacklist = blacklist->next;
591 return 0;
595 * apply_blacklist - remove blacklisted modules from alias list
597 * @aliases: module alias list
598 * @blacklist: list of blacklisted module names
601 static void
602 apply_blacklist(struct module_alias **aliases,
603 const struct module_blacklist *blacklist)
605 struct module_alias *result = NULL;
606 struct module_alias *alias = *aliases;
607 while (alias) {
608 char *modname = alias->module;
609 if (!find_blacklist(modname, blacklist))
610 result = add_alias(alias->aliasname, modname, result);
611 alias = alias->next;
613 free_aliases(*aliases);
614 *aliases = result;
618 * find_command - lookup any install commands for a module
620 * @modname: module name
621 * @commands: list of install commands
624 static const char *find_command(const char *modname,
625 const struct module_command *commands)
627 while (commands) {
628 if (fnmatch(commands->modulename, modname, 0) == 0)
629 return commands->command;
630 commands = commands->next;
632 return NULL;
636 * find_softdep - lookup any softdeps for a module
638 * @modname: module name
639 * @softdeps: list of module softdeps
642 static const struct module_softdep *
643 find_softdep(const char *modname, const struct module_softdep *softdeps)
645 while (softdeps) {
646 if (fnmatch(softdeps->modname, modname, 0) == 0)
647 return softdeps;
648 softdeps = softdeps->next;
650 return NULL;
654 * append_option - add further options to modules (tail)
656 * @options: existing option string
657 * @newoption: additional option string
659 * options supplied on the command line
661 static char *append_option(char *options, const char *newoption)
663 options = NOFAIL(realloc(options, strlen(options) + 1
664 + strlen(newoption) + 1));
665 if (strlen(options)) strcat(options, " ");
666 strcat(options, newoption);
667 return options;
671 * prepend_option - add further options to modules (head)
673 * @options: existing option string
674 * @newoption: additional option string
676 * options supplied in the config file(s)
678 static char *prepend_option(char *options, const char *newoption)
680 size_t l1, l2;
681 l1 = strlen(options);
682 l2 = strlen(newoption);
683 /* the resulting string will look like
684 * newoption + ' ' + options + '\0' */
685 if (l1) {
686 options = NOFAIL(realloc(options, l2 + 1 + l1 + 1));
687 memmove(options + l2 + 1, options, l1 + 1);
688 options[l2] = ' ';
689 memcpy(options, newoption, l2);
690 } else {
691 options = NOFAIL(realloc(options, l2 + 1));
692 memcpy(options, newoption, l2);
693 options[l2] = '\0';
695 return options;
699 * add_extra_options - add any relevant options from the config file(s)
701 * @modname: module name
702 * @optstring: options
703 * @options: list of options
706 static char *add_extra_options(const char *modname,
707 const char *optstring,
708 const struct module_options *options)
710 char *opts = NOFAIL(strdup(optstring));
712 while (options) {
713 if (streq(options->modulename, modname))
714 opts = prepend_option(opts, options->options);
715 options = options->next;
717 return opts;
721 * module_in_procfs - check if module is known to be loaded already
723 * @modname: module name
724 * @usecount: update usecount if possible (-1 if unknown)
727 static int module_in_procfs(const char *modname, unsigned int *usecount)
729 FILE *proc_modules;
730 char *line;
732 again:
733 /* Might not be mounted yet. Don't fail. */
734 proc_modules = fopen("/proc/modules", "r");
735 if (!proc_modules)
736 return -1;
738 while ((line = getline_wrapped(proc_modules, NULL)) != NULL) {
739 char *entry = strtok(line, " \n");
741 if (entry && streq(entry, modname)) {
742 /* If it exists, usecount is the third entry. */
743 if (!strtok(NULL, " \n"))
744 goto out;
746 if (!(entry = strtok(NULL, " \n"))) /* usecount */
747 goto out;
748 else
749 if (usecount)
750 *usecount = atoi(entry);
752 /* Followed by - then status. */
753 if (strtok(NULL, " \n")
754 && (entry = strtok(NULL, " \n")) != NULL) {
755 /* No locking, we might hit cases
756 * where module is in flux. Spin. */
757 if (streq(entry, "Loading")
758 || streq(entry, "Unloading")) {
759 usleep(100000);
760 free(line);
761 fclose(proc_modules);
762 goto again;
766 out:
767 free(line);
768 fclose(proc_modules);
769 return 1;
771 free(line);
773 fclose(proc_modules);
774 return 0;
778 * read_attribute - read sysfs file attributes into a buffer
780 * @filename: name of sysfs file
781 * @buf: buffer
782 * @buflen: size of buffer
785 static int read_attribute(const char *filename, char *buf, size_t buflen)
787 FILE *file;
788 char *s;
790 file = fopen(filename, "r");
791 if (file == NULL)
792 return (errno == ENOENT) ? 0 : -1;
793 s = fgets(buf, buflen, file);
794 fclose(file);
796 /* return -1 if any problems */
798 return (s == NULL) ? -1 : 1;
802 * module_builtin - try to determine whether a module is built-in
804 * @dirname: module directory
805 * @modname: name of module
808 static int module_builtin(const char *dirname, const char *modname)
810 struct index_file *index;
811 char *filename, *value;
813 nofail_asprintf(&filename, "%s/modules.builtin.bin", dirname);
814 index = index_file_open(filename);
815 free(filename);
817 /* return -1 if no builtin list available (modern depmod file) */
818 if (!index)
819 return -1;
821 value = index_search(index, modname);
822 free(value);
823 return value ? 1 : 0;
827 * module_in_sysfs - try to determine if module has a sysfs entry
829 * @modname: module name
830 * @usecount: update use count if possible (-1 if unknown)
833 static int module_in_sysfs(const char *modname, unsigned int *usecount)
835 int ret;
836 char *name;
837 struct stat finfo;
839 const int ATTR_LEN = 16;
840 char attr[ATTR_LEN];
842 /* Check sysfs is mounted */
843 if (stat("/sys/module", &finfo) < 0)
844 return -1;
846 /* Find module. */
847 nofail_asprintf(&name, "/sys/module/%s", modname);
848 ret = stat(name, &finfo);
849 free(name);
850 if (ret < 0)
851 return (errno == ENOENT) ? 0 : -1; /* Not found or unknown. */
853 nofail_asprintf(&name, "/sys/module/%s/initstate", modname);
854 ret = read_attribute(name, attr, ATTR_LEN);
855 if (ret == 0) {
856 free(name);
857 nofail_asprintf(&name, "/sys/module/%s", modname);
858 if (stat(name, &finfo) < 0) {
859 /* module was removed before we could read initstate */
860 ret = 0;
861 } else {
862 /* initstate not available (2.6.19 or earlier) */
863 ret = -1;
865 free(name);
866 return ret;
869 /* Wait for the existing module to either go live or disappear. */
870 while (ret == 1 && !streq(attr, "live\n")) {
871 usleep(100000);
872 ret = read_attribute(name, attr, ATTR_LEN);
874 free(name);
876 if (ret != 1)
877 return ret;
879 /* Get reference count, if it exists. */
880 if (usecount != NULL) {
881 nofail_asprintf(&name, "/sys/module/%s/refcnt", modname);
882 ret = read_attribute(name, attr, ATTR_LEN);
883 free(name);
884 if (ret == 1)
885 *usecount = atoi(attr);
888 return 1;
892 * module_in_kernel - try to determine if the module is loaded (sysfs,procfs)
894 * @modname: name of module
895 * @usecount: update module use count (-1 if unknown)
898 static int module_in_kernel(const char *modname, unsigned int *usecount)
900 int result;
902 result = module_in_sysfs(modname, usecount);
903 if (result != -1)
904 return result;
906 /* /sys/module/%s/initstate is only available since 2.6.20,
907 fallback to /proc/modules to get module state on earlier kernels. */
908 return module_in_procfs(modname, usecount);
912 * dump_modversions - output list of module version checksums
914 * @filename: module file name
915 * @error: error function to use
918 static void dump_modversions(const char *filename, errfn_t error)
920 struct elf_file *module;
922 module = grab_elf_file(filename);
923 if (!module) {
924 error("%s: %s\n", filename, strerror(errno));
925 return;
927 if (module->ops->dump_modvers(module) < 0)
928 error("Wrong section size in '%s'\n", filename);
929 release_elf_file(module);
933 * type_matches - constrain wildcard module matching to subdirectory
935 * @path: path string
936 * @subpath: search path for subpath
938 * Legacy function used to support deprecated option
940 static int type_matches(const char *path, const char *subpath)
942 char *subpath_with_slashes;
943 int ret;
945 nofail_asprintf(&subpath_with_slashes, "/%s/", subpath);
947 ret = (strstr(path, subpath_with_slashes) != NULL);
948 free(subpath_with_slashes);
949 return ret;
953 * do_wildcard - match modules (possibly in directory names containing "type")
955 * @dirname: module directory
956 * @type: possible subdirectory limiting
957 * @wildcard: what to match
960 static int do_wildcard(const char *dirname,
961 const char *type,
962 const char *wildcard)
964 char *modules_dep_name;
965 char *line, *wcard;
966 FILE *modules_dep;
968 /* Canonicalize wildcard */
969 wcard = strdup(wildcard);
970 underscores(wcard);
972 nofail_asprintf(&modules_dep_name, "%s/%s", dirname, "modules.dep");
973 modules_dep = fopen(modules_dep_name, "r");
974 if (!modules_dep)
975 fatal("Could not load %s: %s\n",
976 modules_dep_name, strerror(errno));
978 while ((line = getline_wrapped(modules_dep, NULL)) != NULL) {
979 char *ptr;
981 /* Ignore lines without : or which start with a # */
982 ptr = strchr(line, ':');
983 if (ptr == NULL || line[strspn(line, "\t ")] == '#')
984 goto next;
985 *ptr = '\0';
987 /* "type" must match complete directory component(s). */
988 if (!type || type_matches(line, type)) {
989 char modname[strlen(line)+1];
991 filename2modname(modname, line);
992 if (fnmatch(wcard, modname, 0) == 0)
993 printf("%s\n", line);
995 next:
996 free(line);
999 free(modules_dep_name);
1000 free(wcard);
1001 return 0;
1005 * strsep_skipspace - ignore certain delimitor characters in strings
1007 * @string: what to search
1008 * @delim: delimitor string
1011 static char *strsep_skipspace(char **string, char *delim)
1013 if (!*string)
1014 return NULL;
1015 *string += strspn(*string, delim);
1016 return strsep(string, delim);
1019 static int parse_config_scan(struct modprobe_conf *conf,
1020 int dump_only,
1021 int removing, ...);
1024 * parse_config_file - read in configuration file options
1026 * @filename: name of file
1027 * @conf: config options lists
1028 * @dump_only: print out config
1029 * @removing: determine whether to run install/softdep/etc.
1032 static int parse_config_file(const char *filename,
1033 struct modprobe_conf *conf,
1034 int dump_only,
1035 int removing)
1037 char *line;
1038 unsigned int linenum = 0;
1039 FILE *cfile;
1041 struct module_options **options = &conf->options;
1042 struct module_command **commands = &conf->commands;
1043 struct module_alias **aliases = &conf->aliases;
1044 struct module_blacklist **blacklist = &conf->blacklist;
1046 cfile = fopen(filename, "r");
1047 if (!cfile)
1048 return 0;
1050 while ((line = getline_wrapped(cfile, &linenum)) != NULL) {
1051 char *ptr = line;
1052 char *cmd, *modname;
1054 /* output configuration */
1055 if (dump_only)
1056 printf("%s\n", line);
1058 cmd = strsep_skipspace(&ptr, "\t ");
1059 if (cmd == NULL || cmd[0] == '#' || cmd[0] == '\0') {
1060 free(line);
1061 continue;
1064 if (streq(cmd, "alias")) {
1065 char *wildcard = strsep_skipspace(&ptr, "\t ");
1066 char *realname = strsep_skipspace(&ptr, "\t ");
1067 if (!wildcard || !realname)
1068 goto syntax_error;
1069 *aliases = add_alias(underscores(wildcard),
1070 underscores(realname),
1071 *aliases);
1072 } else if (streq(cmd, "include")) {
1073 struct modprobe_conf newconf = *conf;
1074 newconf.aliases = NULL;
1075 char *newfilename;
1076 newfilename = strsep_skipspace(&ptr, "\t ");
1077 if (!newfilename)
1078 goto syntax_error;
1080 warn("\"include %s\" is deprecated, "
1081 "please use /etc/modprobe.d\n", newfilename);
1082 if (strstarts(newfilename, "/etc/modprobe.d")) {
1083 warn("\"include /etc/modprobe.d\" is "
1084 "the default, ignored\n");
1085 } else {
1086 if (!parse_config_scan(&newconf, dump_only,
1087 removing, newfilename,
1088 NULL))
1089 warn("Failed to open included"
1090 " config file %s: %s\n",
1091 newfilename, strerror(errno));
1093 /* Files included override aliases,
1094 etc that was already set ... */
1095 if (newconf.aliases)
1096 *aliases = newconf.aliases;
1098 } else if (streq(cmd, "options")) {
1099 modname = strsep_skipspace(&ptr, "\t ");
1100 if (!modname || !ptr)
1101 goto syntax_error;
1103 ptr += strspn(ptr, "\t ");
1104 *options = add_options(underscores(modname),
1105 ptr, *options);
1107 } else if (streq(cmd, "install")) {
1108 modname = strsep_skipspace(&ptr, "\t ");
1109 if (!modname || !ptr)
1110 goto syntax_error;
1111 if (!removing) {
1112 ptr += strspn(ptr, "\t ");
1113 *commands = add_command(underscores(modname),
1114 ptr, *commands);
1116 } else if (streq(cmd, "blacklist")) {
1117 modname = strsep_skipspace(&ptr, "\t ");
1118 if (!modname)
1119 goto syntax_error;
1120 if (!removing) {
1121 *blacklist = add_blacklist(underscores(modname),
1122 *blacklist);
1124 } else if (streq(cmd, "remove")) {
1125 modname = strsep_skipspace(&ptr, "\t ");
1126 if (!modname || !ptr)
1127 goto syntax_error;
1128 if (removing) {
1129 ptr += strspn(ptr, "\t ");
1130 *commands = add_command(underscores(modname),
1131 ptr, *commands);
1133 } else if (streq(cmd, "softdep")) {
1134 char *tk;
1135 int pre = 0, post = 0;
1136 struct string_table *pre_modnames = NULL;
1137 struct string_table *post_modnames = NULL;
1138 struct module_softdep *new;
1140 modname = strsep_skipspace(&ptr, "\t ");
1141 if (!modname || !ptr)
1142 goto syntax_error;
1143 modname = underscores(modname);
1145 while ((tk = strsep_skipspace(&ptr, "\t ")) != NULL) {
1146 tk = underscores(tk);
1148 if (streq(tk, "pre:")) {
1149 pre = 1; post = 0;
1150 } else if (streq(tk, "post:")) {
1151 pre = 0; post = 1;
1152 } else if (pre) {
1153 pre_modnames = NOFAIL(
1154 strtbl_add(tk, pre_modnames));
1155 } else if (post) {
1156 post_modnames = NOFAIL(
1157 strtbl_add(tk, post_modnames));
1158 } else {
1159 strtbl_free(pre_modnames);
1160 strtbl_free(post_modnames);
1161 goto syntax_error;
1164 new = NOFAIL(malloc(sizeof(*new)));
1165 new->buf = line;
1166 new->modname = modname;
1167 new->pre = pre_modnames;
1168 new->post = post_modnames;
1169 new->next = conf->softdeps;
1170 conf->softdeps = new;
1172 line = NULL; /* Don't free() this line. */
1173 /* allocated in buf above */
1175 } else if (streq(cmd, "config")) {
1176 char *tmp = strsep_skipspace(&ptr, "\t ");
1178 if (!tmp)
1179 goto syntax_error;
1180 if (streq(tmp, "binary_indexes")) {
1181 tmp = strsep_skipspace(&ptr, "\t ");
1182 if (streq(tmp, "yes"))
1183 use_binary_indexes = 1;
1184 if (streq(tmp, "no"))
1185 use_binary_indexes = 0;
1187 } else {
1188 syntax_error:
1189 grammar(cmd, filename, linenum);
1192 free(line);
1194 fclose(cfile);
1195 return 1;
1199 * read_aliases_file - process binary module aliases file
1201 * @filename: alias file
1202 * @name: module name
1203 * @dump_only: dump aliases only
1204 * @aliases: list of aliases
1207 static int read_aliases_file(const char *filename,
1208 const char *name,
1209 int dump_only,
1210 struct module_alias **aliases)
1212 struct index_value *realnames;
1213 struct index_value *realname;
1214 char *binfile;
1215 struct index_file *index;
1217 nofail_asprintf(&binfile, "%s.bin", filename);
1218 index = index_file_open(binfile);
1219 if (!index) {
1220 free(binfile);
1221 return 0;
1224 if (dump_only) {
1225 index_dump(index, stdout, "alias ");
1226 free(binfile);
1227 index_file_close(index);
1228 return 1;
1231 realnames = index_searchwild(index, name);
1232 for (realname = realnames; realname; realname = realname->next)
1233 *aliases = add_alias("*", realname->value, *aliases);
1234 index_values_free(realnames);
1236 free(binfile);
1237 index_file_close(index);
1238 return 1;
1242 * read_aliases - process module aliases file
1244 * @filename: alias file
1245 * @name: module name
1246 * @dump_only: dump aliases only
1247 * @aliases: list of aliases
1250 static int read_aliases(const char *filename,
1251 const char *name,
1252 int dump_only,
1253 struct module_alias **aliases)
1255 char *line;
1256 unsigned int linenum = 0;
1257 FILE *cfile;
1259 /* prefer the binary version if available and configured */
1260 if (use_binary_indexes)
1261 if (read_aliases_file(filename, name, dump_only, aliases))
1262 return 1;
1264 cfile = fopen(filename, "r");
1265 if (!cfile)
1266 return 0;
1268 while ((line = getline_wrapped(cfile, &linenum)) != NULL) {
1269 char *ptr = line;
1270 char *cmd;
1272 if (dump_only)
1273 printf("%s\n", line);
1275 cmd = strsep_skipspace(&ptr, "\t ");
1276 if (cmd == NULL || cmd[0] == '#' || cmd[0] == '\0') {
1277 free(line);
1278 continue;
1281 if (streq(cmd, "alias")) {
1282 char *wildcard = strsep_skipspace(&ptr, "\t ");
1283 char *realname = strsep_skipspace(&ptr, "\t ");
1284 if (!wildcard || !realname)
1285 goto syntax_error;
1286 if (fnmatch(underscores(wildcard),name,0) == 0)
1287 *aliases = add_alias(wildcard,
1288 underscores(realname),
1289 *aliases);
1290 } else {
1291 syntax_error:
1292 grammar(cmd, filename, linenum);
1295 free(line);
1297 fclose(cfile);
1298 return 1;
1302 * parse_config_scan - process a directory of configuration files
1304 * @conf: config options lists
1305 * @dump_only: print out config
1306 * @removing: determine whether to run install/softdep/etc.
1309 static int parse_config_scan(struct modprobe_conf *conf,
1310 int dump_only,
1311 int removing, ...)
1313 va_list filelist;
1314 char *filename;
1315 DIR *dir;
1316 struct file_entry {
1317 struct list_head node;
1318 char *name;
1319 char *path;
1321 struct file_entry *fe, *fe_tmp;
1322 LIST_HEAD(files_list);
1323 int ret = 0;
1325 va_start(filelist, removing);
1327 while ((filename = va_arg(filelist, char*))) {
1328 dir = opendir(filename);
1329 if (dir) {
1330 struct dirent *i;
1332 /* sort files from directories into list, ignoring duplicates */
1333 while ((i = readdir(dir)) != NULL) {
1334 size_t len;
1335 int cmp = -1;
1337 if (i->d_name[0] == '.')
1338 continue;
1339 if (!config_filter(i->d_name))
1340 continue;
1342 len = strlen(i->d_name);
1343 if (len < 6 ||
1344 (strcmp(&i->d_name[len-5], ".conf") != 0 &&
1345 strcmp(&i->d_name[len-6], ".alias") != 0))
1346 warn("All config files need .conf: %s/%s, "
1347 "it will be ignored in a future release.\n",
1348 filename, i->d_name);
1349 fe = malloc(sizeof(struct file_entry));
1350 if (fe == NULL)
1351 continue;
1353 list_for_each_entry(fe_tmp, &files_list, node)
1354 if ((cmp = strcmp(fe_tmp->name, i->d_name)) >= 0)
1355 break;
1357 if (cmp != 0) {
1358 fe->name = malloc(len + 1);
1359 fe->path = malloc(strlen(filename) + 1);
1360 strcpy(fe->name, i->d_name);
1361 strcpy(fe->path, filename);
1363 if (cmp < 0)
1364 list_add_tail(&fe->node, &files_list);
1365 else
1366 list_add_tail(&fe->node, &fe_tmp->node);
1367 } else
1368 info("Ignoring config file %s/%s\n", filename, i->d_name);
1371 closedir(dir);
1373 ret = 1;
1374 } else {
1375 if (parse_config_file(filename, conf, dump_only, removing))
1376 ret = 1;
1380 /* parse list of files */
1381 list_for_each_entry_safe(fe, fe_tmp, &files_list, node) {
1382 char *cfgfile;
1384 nofail_asprintf(&cfgfile, "%s/%s", fe->path, fe->name);
1385 if (!parse_config_file(cfgfile, conf,
1386 dump_only, removing))
1387 warn("Failed to open config file %s: %s\n",
1388 cfgfile, strerror(errno));
1389 free(cfgfile);
1390 list_del(&fe->node);
1391 free(fe->name);
1392 free(fe->path);
1393 free(fe);
1396 va_end(filelist);
1397 return ret;
1401 * parse_toplevel_config - search configuration directories
1403 * @filename: specified on command line
1404 * @conf: config options lists
1405 * @dump_only: print out config
1406 * @removing: determine whether to run install/softdep/etc.
1409 static void parse_toplevel_config(const char *filename,
1410 struct modprobe_conf *conf,
1411 int dump_only,
1412 int removing)
1414 if (filename) {
1415 if (!parse_config_scan(conf, dump_only, removing, filename,
1416 NULL))
1417 fatal("Failed to open config file %s: %s\n",
1418 filename, strerror(errno));
1419 return;
1422 /* deprecated config file */
1423 if (parse_config_file("/etc/modprobe.conf", conf,
1424 dump_only, removing) > 0)
1425 warn("Deprecated config file /etc/modprobe.conf, "
1426 "all config files belong into /etc/modprobe.d/.\n");
1428 /* default config */
1429 parse_config_scan(conf, dump_only, removing, "/run/modprobe.d",
1430 "/etc/modprobe.d", "/usr/local/lib/modprobe.d",
1431 "/lib/modprobe.d", NULL);
1435 * parse_kcmdline - process configuration options on kernel boot line
1437 * @dump_only: print out config
1438 * @conf: config options lists
1441 static int parse_kcmdline(int dump_only, struct modprobe_conf *conf)
1443 char *line;
1444 unsigned int linenum = 0;
1445 FILE *kcmdline;
1446 struct module_options **options = &conf->options;
1447 struct module_blacklist **blacklist = &conf->blacklist;
1449 kcmdline = fopen("/proc/cmdline", "r");
1450 if (!kcmdline)
1451 return 0;
1453 while ((line = getline_wrapped(kcmdline, &linenum)) != NULL) {
1454 char *ptr = line;
1455 char *arg;
1457 while ((arg = strsep_skipspace(&ptr, "\t ")) != NULL) {
1458 char *sep, *modname, *opt;
1460 if (strstr(arg, "modprobe.blacklist=") != NULL) {
1461 ptr = strchr(arg,'=') + 1;
1463 while ((modname = strsep(&ptr, ",")) != NULL) {
1464 if (dump_only)
1465 printf("blacklist %s\n", modname);
1467 *blacklist = add_blacklist(underscores(modname), *blacklist);
1471 sep = strchr(arg, '.');
1472 if (sep) {
1473 if (!strchr(sep, '='))
1474 continue;
1475 modname = arg;
1476 *sep = '\0';
1477 opt = ++sep;
1479 if (dump_only)
1480 printf("options %s %s\n", modname, opt);
1482 *options = add_options(underscores(modname),
1483 opt, *options);
1487 free(line);
1489 fclose(kcmdline);
1490 return 1;
1494 * add_to_env_var - set environment variables
1496 * @option: variable to set
1499 static void add_to_env_var(const char *option)
1501 const char *oldenv;
1503 if ((oldenv = getenv("MODPROBE_OPTIONS")) != NULL) {
1504 char *newenv;
1505 nofail_asprintf(&newenv, "%s %s", oldenv, option);
1506 setenv("MODPROBE_OPTIONS", newenv, 1);
1507 free(newenv);
1508 } else
1509 setenv("MODPROBE_OPTIONS", option, 1);
1513 * merge_args - load options from the environment (head)
1515 * @args: list of arguments
1516 * @argv: program arguments
1517 * @argc: argument count
1520 static char **merge_args(char *args, char *argv[], int *argc)
1522 char *arg, *argstring;
1523 char **newargs = NULL;
1524 unsigned int i, num_env = 0;
1526 if (!args)
1527 return argv;
1529 argstring = NOFAIL(strdup(args));
1530 for (arg = strtok(argstring, " "); arg; arg = strtok(NULL, " ")) {
1531 num_env++;
1532 newargs = NOFAIL(realloc(newargs,
1533 sizeof(newargs[0])
1534 * (num_env + *argc + 1)));
1535 newargs[num_env] = arg;
1538 if (!newargs)
1539 return argv;
1541 /* Append commandline args */
1542 newargs[0] = argv[0];
1543 for (i = 1; i <= *argc; i++)
1544 newargs[num_env+i] = argv[i];
1546 *argc += num_env;
1547 return newargs;
1551 * gather_options - load options from command line
1553 * @argv: program arguments
1556 static char *gather_options(char *argv[])
1558 char *optstring = NOFAIL(strdup(""));
1560 /* Rest is module options */
1561 while (*argv) {
1562 /* Quote value if it contains spaces. */
1563 unsigned int eq = strcspn(*argv, "=");
1565 if (strchr(*argv+eq, ' ') && !strchr(*argv, '"')) {
1566 char quoted[strlen(*argv) + 3];
1567 (*argv)[eq] = '\0';
1568 sprintf(quoted, "%s=\"%s\"", *argv, *argv+eq+1);
1569 optstring = append_option(optstring, quoted);
1570 } else
1571 optstring = append_option(optstring, *argv);
1572 argv++;
1574 return optstring;
1578 * do_command - execute a module install or remove command
1580 * @modname: module name
1581 * @command: command string
1582 * @dry_run: possibly do nothing
1583 * @error: error function
1584 * @type: install or remove
1585 * @cmdline_opts: substitute for $CMDLINE_OPTS
1588 static void do_command(const char *modname,
1589 const char *command,
1590 int dry_run,
1591 errfn_t error,
1592 const char *type,
1593 const char *cmdline_opts)
1595 int ret;
1596 char *p, *replaced_cmd = NOFAIL(strdup(command));
1598 while ((p = strstr(replaced_cmd, "$CMDLINE_OPTS")) != NULL) {
1599 char *new;
1600 nofail_asprintf(&new, "%.*s%s%s",
1601 (int)(p - replaced_cmd), replaced_cmd, cmdline_opts,
1602 p + strlen("$CMDLINE_OPTS"));
1603 free(replaced_cmd);
1604 replaced_cmd = new;
1607 info("%s %s\n", type, replaced_cmd);
1608 if (dry_run)
1609 goto out;
1611 setenv("MODPROBE_MODULE", modname, 1);
1612 ret = system(replaced_cmd);
1613 if (ret == -1 || WEXITSTATUS(ret))
1614 error("Error running %s command for %s\n", type, modname);
1616 out:
1617 free(replaced_cmd);
1620 /* Forward declaration */
1621 static int do_modprobe(const char *modname,
1622 const char *cmdline_opts,
1623 const struct modprobe_conf *conf,
1624 const char *dirname,
1625 errfn_t error,
1626 modprobe_flags_t flags);
1629 * do_softdep - load or unload module soft dependencies
1631 * @softdep: soft dependency module(s)
1632 * @cmdline_opts: command line options
1633 * @conf: config options lists
1634 * @dirname: module directory
1635 * @error: error function
1636 * @flags: general flags
1639 static void do_softdep(const struct module_softdep *softdep,
1640 const char *cmdline_opts,
1641 const struct modprobe_conf *conf,
1642 const char *dirname,
1643 errfn_t error,
1644 modprobe_flags_t flags)
1646 struct string_table *pre_modnames, *post_modnames;
1647 modprobe_flags_t softdep_flags = flags;
1648 int i, j;
1650 softdep_flags &= ~mit_first_time;
1651 softdep_flags &= ~mit_ignore_commands;
1652 if (flags & mit_remove)
1653 softdep_flags |= mit_quiet_inuse;
1655 if (++recursion_depth >= MAX_RECURSION)
1656 fatal("modprobe: softdep dependency loop encountered %s %s\n",
1657 (flags & mit_remove) ? "removing" : "inserting",
1658 softdep->modname);
1660 if (flags & mit_remove) {
1661 /* Reverse module order if removing. */
1662 pre_modnames = softdep->post;
1663 post_modnames = softdep->pre;
1664 } else {
1665 pre_modnames = softdep->pre;
1666 post_modnames = softdep->post;
1669 /* Modprobe pre_modnames */
1671 for (i = 0; pre_modnames && i < pre_modnames->cnt; i++) {
1672 /* Reverse module order if removing. */
1673 j = (flags & mit_remove) ? pre_modnames->cnt-1 - i : i;
1675 do_modprobe(pre_modnames->str[j], "",
1676 conf, dirname, warn, softdep_flags);
1679 /* Modprobe main module, passing cmdline_opts, ignoring softdep */
1681 do_modprobe(softdep->modname, cmdline_opts,
1682 conf, dirname, warn, flags | mit_ignore_commands);
1684 /* Modprobe post_modnames */
1686 for (i = 0; post_modnames && i < post_modnames->cnt; i++) {
1687 /* Reverse module order if removing. */
1688 j = (flags & mit_remove) ? post_modnames->cnt-1 - i : i;
1690 do_modprobe(post_modnames->str[j], "", conf,
1691 dirname, warn, softdep_flags);
1696 * insmod - load a module(s)
1698 * @list: list of modules
1699 * @optstring: module options
1700 * @cmdline_opts: command line options
1701 * @conf: config options lists
1702 * @dirname: module directory
1703 * @error: error function
1704 * @flags: general flags
1707 static int insmod(struct list_head *list,
1708 const char *optstring,
1709 const char *cmdline_opts,
1710 const struct modprobe_conf *conf,
1711 const char *dirname,
1712 errfn_t error,
1713 modprobe_flags_t flags)
1715 int ret;
1716 struct elf_file *module;
1717 const struct module_softdep *softdep;
1718 const char *command;
1719 struct module *mod = list_entry(list->next, struct module, list);
1720 int rc = 0;
1721 int already_loaded;
1722 char *opts = NULL;
1724 /* Take us off the list. */
1725 list_del(&mod->list);
1727 /* Do things we (or parent) depend on first. */
1728 if (!list_empty(list)) {
1729 modprobe_flags_t f = flags;
1730 f &= ~mit_first_time;
1731 f &= ~mit_ignore_commands;
1732 if ((rc = insmod(list, "", "", conf, dirname, warn, f)) != 0)
1734 error("Error inserting %s (%s): %s\n",
1735 mod->modname, mod->filename,
1736 insert_moderror(errno));
1737 goto out;
1741 /* Don't do ANYTHING if already in kernel. */
1742 already_loaded = module_in_kernel(mod->modname, NULL);
1744 if (!(flags & mit_ignore_loaded) && already_loaded == 1) {
1745 if (flags & mit_first_time)
1746 error("Module %s already in kernel.\n", mod->modname);
1747 goto out;
1750 /* load any soft dependency modules */
1751 softdep = find_softdep(mod->modname, conf->softdeps);
1752 if (softdep && !(flags & mit_ignore_commands)) {
1753 do_softdep(softdep, cmdline_opts, conf, dirname, error, flags);
1754 goto out;
1757 /* run any install commands for this module */
1758 command = find_command(mod->modname, conf->commands);
1759 if (command && !(flags & mit_ignore_commands)) {
1760 if (already_loaded == -1) {
1761 warn("/sys/module/ not present or too old,"
1762 " and /proc/modules does not exist.\n");
1763 warn("Ignoring install commands for %s"
1764 " in case it is already loaded.\n",
1765 mod->modname);
1766 } else {
1767 do_command(mod->modname, command, flags & mit_dry_run,
1768 error, "install", cmdline_opts);
1769 goto out;
1773 /* open the module */
1774 module = grab_elf_file(mod->filename);
1775 if (!module) {
1776 error("Could not read '%s': %s\n", mod->filename,
1777 (errno == ENOEXEC) ? "Invalid module format" :
1778 strerror(errno));
1779 goto out;
1781 if (flags & mit_strip_modversion)
1782 module->ops->strip_section(module, "__versions");
1783 if (flags & mit_strip_vermagic)
1784 clear_magic(module);
1786 /* Config file might have given more options */
1787 opts = add_extra_options(mod->modname, optstring, conf->options);
1789 info("insmod %s %s\n", mod->filename, opts);
1791 if (flags & mit_dry_run)
1792 goto out_elf_file;
1794 /* request kernel linkage */
1795 ret = init_module(module->data, module->len, opts);
1796 if (ret != 0) {
1797 if (errno == EEXIST) {
1798 if (flags & mit_first_time)
1799 error("Module %s already in kernel.\n",
1800 mod->modname);
1801 goto out_elf_file;
1803 /* don't warn noisely if we're loading multiple aliases. */
1804 /* one of the aliases may try to use hardware we don't have. */
1805 if ((error != warn) || (verbose))
1806 error("Error inserting %s (%s): %s\n",
1807 mod->modname, mod->filename,
1808 insert_moderror(errno));
1809 rc = 1;
1811 out_elf_file:
1812 release_elf_file(module);
1813 free(opts);
1814 out:
1815 free_module(mod);
1816 return rc;
1820 * rmmod - unload a module(s)
1822 * @list: list of modules
1823 * @cmdline_opts: command line options
1824 * @conf: config options lists
1825 * @dirname: module directory
1826 * @error: error function
1827 * @flags: general flags
1830 static void rmmod(struct list_head *list,
1831 const char *cmdline_opts,
1832 const struct modprobe_conf *conf,
1833 const char *dirname,
1834 errfn_t error,
1835 modprobe_flags_t flags)
1837 const struct module_softdep *softdep;
1838 const char *command;
1839 unsigned int usecount = 0;
1840 struct module *mod = list_entry(list->next, struct module, list);
1841 int exists;
1843 /* Take first one off the list. */
1844 list_del(&mod->list);
1846 /* Don't do ANYTHING if not loaded. */
1847 exists = module_in_kernel(mod->modname, &usecount);
1848 if (exists == 0)
1849 goto nonexistent_module;
1851 /* Even if renamed, find commands/softdeps to orig. name. */
1853 softdep = find_softdep(mod->modname, conf->softdeps);
1854 if (softdep && !(flags & mit_ignore_commands)) {
1855 do_softdep(softdep, cmdline_opts, conf, dirname, error, flags);
1856 goto remove_rest;
1859 /* run any remove commands for this module */
1860 command = find_command(mod->modname, conf->commands);
1861 if (command && !(flags & mit_ignore_commands)) {
1862 if (exists == -1) {
1863 warn("/sys/module/ not present or too old,"
1864 " and /proc/modules does not exist.\n");
1865 warn("Ignoring remove commands for %s"
1866 " in case it is not loaded.\n",
1867 mod->modname);
1868 } else {
1869 do_command(mod->modname, command, flags & mit_dry_run,
1870 error, "remove", cmdline_opts);
1871 goto remove_rest;
1875 /* abort if use count is not zero */
1876 if (usecount != 0) {
1877 if (!(flags & mit_quiet_inuse))
1878 error("Module %s is in use.\n", mod->modname);
1879 goto remove_rest;
1882 info("rmmod %s\n", mod->filename);
1884 if (flags & mit_dry_run)
1885 goto remove_rest;
1887 /* request kernel unlinkage */
1888 if (delete_module(mod->modname, O_EXCL) != 0) {
1889 if (errno == ENOENT)
1890 goto nonexistent_module;
1891 error("Error removing %s (%s): %s\n",
1892 mod->modname, mod->filename,
1893 remove_moderror(errno));
1896 remove_rest:
1897 /* Now do things we depend. */
1898 if (!list_empty(list)) {
1899 flags &= ~mit_first_time;
1900 flags &= ~mit_ignore_commands;
1901 flags |= mit_quiet_inuse;
1903 rmmod(list, "", conf, dirname, warn, flags);
1905 free_module(mod);
1906 return;
1908 nonexistent_module:
1909 if (flags & mit_first_time)
1910 fatal("Module %s is not in kernel.\n", mod->modname);
1911 goto remove_rest;
1915 * handle_module - load or unload a module(s)
1917 * @modname: module requested
1918 * @todo_list: dependency list
1919 * @options: module options
1920 * @cmdline_opts: options passed on command line
1921 * @conf: config options lists
1922 * @dirname: module directory
1923 * @error: error function
1924 * @flags: general flags
1927 static int handle_module(const char *modname,
1928 struct list_head *todo_list,
1929 const char *options,
1930 const char *cmdline_opts,
1931 const struct modprobe_conf *conf,
1932 const char *dirname,
1933 errfn_t error,
1934 modprobe_flags_t flags)
1936 if (list_empty(todo_list)) {
1937 const char *command;
1939 /* The dependencies have to be real modules, but
1940 handle case where the first is completely bogus. */
1942 command = find_command(modname, conf->commands);
1943 if (command && !(flags & mit_ignore_commands)) {
1944 do_command(modname, command, flags & mit_dry_run, error,
1945 (flags & mit_remove) ? "remove":"install", cmdline_opts);
1946 return 0;
1949 if (!quiet)
1950 error("Module %s not found.\n", modname);
1951 return 1;
1954 if (flags & mit_remove)
1955 rmmod(todo_list, cmdline_opts,
1956 conf, dirname, error, flags);
1957 else
1958 insmod(todo_list, options,
1959 cmdline_opts, conf, dirname, error, flags);
1961 return 0;
1965 * handle_builtin_module - report built-in modules
1967 * @modname: module name
1968 * @error: error function
1969 * @flags: general flags
1972 static int handle_builtin_module(const char *modname,
1973 errfn_t error,
1974 modprobe_flags_t flags)
1976 if (flags & mit_remove) {
1977 error("Module %s is builtin\n", modname);
1978 return 1;
1979 } else if (flags & mit_first_time) {
1980 error("Module %s already in kernel (builtin).\n", modname);
1981 return 1;
1982 } else if (flags & mit_ignore_loaded) {
1983 /* --show-depends given */
1984 info("builtin %s\n", modname);
1986 return 0;
1990 * do_modprobe - find a module by name or alias and load or unload
1992 * @modname: module name
1993 * @cmdline_opts: command line options
1994 * @conf: config options lists
1995 * @dirname: module directory
1996 * @error: error function
1997 * @flags: general flags
2000 static int do_modprobe(const char *modname,
2001 const char *cmdline_opts,
2002 const struct modprobe_conf *conf,
2003 const char *dirname,
2004 errfn_t error,
2005 modprobe_flags_t flags)
2007 struct module_alias *matching_aliases;
2008 LIST_HEAD(list);
2009 int failed = 0;
2011 matching_aliases = find_aliases(conf->aliases, modname);
2013 /* No luck? Try symbol names, if starts with symbol:. */
2014 if (!matching_aliases && strstarts(modname, "symbol:")) {
2015 char *symfilename;
2017 nofail_asprintf(&symfilename, "%s/modules.symbols", dirname);
2018 read_aliases(symfilename, modname, 0, &matching_aliases);
2019 free(symfilename);
2021 if (!matching_aliases) {
2022 if(!strchr(modname, ':'))
2023 read_depends(dirname, modname, &list);
2025 /* We only use canned aliases as last resort. */
2026 if (list_empty(&list)
2027 && !find_softdep(modname, conf->softdeps)
2028 && !find_command(modname, conf->commands))
2030 char *aliasfilename;
2032 nofail_asprintf(&aliasfilename, "%s/modules.alias",
2033 dirname);
2034 read_aliases(aliasfilename, modname, 0,
2035 &matching_aliases);
2036 free(aliasfilename);
2037 /* builtin module? */
2038 if (!matching_aliases && module_builtin(dirname, modname) > 0) {
2039 failed |= handle_builtin_module(modname, error,
2040 flags);
2041 goto out;
2046 /* only load blacklisted modules with specific request (no alias) */
2047 apply_blacklist(&matching_aliases, conf->blacklist);
2049 if(flags & mit_resolve_alias) {
2050 struct module_alias *aliases = matching_aliases;
2052 for(; aliases; aliases=aliases->next)
2053 printf("%s\n", aliases->module);
2054 goto out;
2056 if (matching_aliases) {
2057 errfn_t err = error;
2058 struct module_alias *aliases = matching_aliases;
2060 /* More than one alias? Don't bail out on failure. */
2061 if (aliases->next)
2062 err = warn;
2063 while (aliases) {
2064 /* Add the options for this alias. */
2065 char *opts;
2066 opts = add_extra_options(modname,
2067 cmdline_opts, conf->options);
2069 read_depends(dirname, aliases->module, &list);
2070 failed |= handle_module(aliases->module,
2071 &list, opts, cmdline_opts,
2072 conf, dirname, err, flags);
2074 aliases = aliases->next;
2075 free(opts);
2076 INIT_LIST_HEAD(&list);
2078 } else {
2079 if (flags & mit_use_blacklist
2080 && find_blacklist(modname, conf->blacklist))
2081 goto out;
2083 failed |= handle_module(modname, &list, cmdline_opts,
2084 cmdline_opts, conf, dirname, error, flags);
2087 out:
2088 free_aliases(matching_aliases);
2089 return failed;
2092 static const struct option options[] = { { "version", 0, NULL, 'V' },
2093 { "verbose", 0, NULL, 'v' },
2094 { "quiet", 0, NULL, 'q' },
2095 { "syslog", 0, NULL, 's' },
2096 { "show", 0, NULL, 'n' },
2097 { "dry-run", 0, NULL, 'n' },
2098 { "show-depends", 0, NULL, 'D' },
2099 { "resolve-alias", 0, NULL, 'R' },
2100 { "dirname", 1, NULL, 'd' },
2101 { "set-version", 1, NULL, 'S' },
2102 { "config", 1, NULL, 'C' },
2103 { "remove", 0, NULL, 'r' },
2104 { "showconfig", 0, NULL, 'c' },
2105 { "list", 0, NULL, 'l' },
2106 { "type", 1, NULL, 't' },
2107 { "all", 0, NULL, 'a' },
2108 { "ignore-install", 0, NULL, 'i' },
2109 { "ignore-remove", 0, NULL, 'i' },
2110 { "use-blacklist", 0, NULL, 'b' },
2111 { "force", 0, NULL, 'f' },
2112 { "force-vermagic", 0, NULL, 1 },
2113 { "force-modversion", 0, NULL, 2 },
2114 { "first-time", 0, NULL, 3 },
2115 { "dump-modversions", 0, NULL, 4 },
2116 { NULL, 0, NULL, 0 } };
2118 int main(int argc, char *argv[])
2120 struct utsname buf;
2121 struct stat statbuf;
2122 int opt;
2123 int dump_config = 0;
2124 int list_only = 0;
2125 int all = 0;
2126 int dump_modver = 0;
2127 unsigned int i, num_modules;
2128 char *type = NULL;
2129 const char *configname = NULL;
2130 char *basedir = "";
2131 char *cmdline_opts = NULL;
2132 char *dirname;
2133 errfn_t error = fatal;
2134 int failed = 0;
2135 modprobe_flags_t flags = 0;
2136 struct modprobe_conf conf = {};
2138 recursion_depth = 0;
2140 /* Prepend options from environment. */
2141 argv = merge_args(getenv("MODPROBE_OPTIONS"), argv, &argc);
2143 uname(&buf);
2144 while ((opt = getopt_long(argc, argv, "Vvqsnd:S:C:DRrclt:aibf", options, NULL)) != -1){
2145 switch (opt) {
2146 case 'V':
2147 puts(PACKAGE " version " VERSION);
2148 exit(0);
2149 case 'v':
2150 add_to_env_var("-v");
2151 verbose = 1;
2152 break;
2153 case 'q':
2154 quiet = 1;
2155 add_to_env_var("-q");
2156 break;
2157 case 's':
2158 add_to_env_var("-s");
2159 logging = 1;
2160 break;
2161 case 'n':
2162 flags |= mit_dry_run;
2163 break;
2164 case 'd':
2165 basedir = optarg;
2166 break;
2167 case 'S':
2168 strncpy(buf.release, optarg, sizeof(buf.release));
2169 buf.release[sizeof(buf.release)-1] = '\0';
2170 break;
2171 case 'C':
2172 configname = optarg;
2173 add_to_env_var("-C");
2174 add_to_env_var(configname);
2175 break;
2176 case 'D':
2177 flags |= mit_dry_run;
2178 flags |= mit_ignore_loaded;
2179 verbose = 1;
2180 break;
2181 case 'R':
2182 flags |= mit_resolve_alias;
2183 break;
2184 case 'r':
2185 flags |= mit_remove;
2186 break;
2187 case 'c':
2188 dump_config = 1;
2189 break;
2190 case 'l':
2191 list_only = 1;
2192 break;
2193 case 't':
2194 type = optarg;
2195 break;
2196 case 'a':
2197 all = 1;
2198 error = warn;
2199 break;
2200 case 'i':
2201 flags |= mit_ignore_commands;
2202 break;
2203 case 'b':
2204 flags |= mit_use_blacklist;
2205 break;
2206 case 'f':
2207 flags |= mit_strip_vermagic;
2208 flags |= mit_strip_modversion;
2209 break;
2210 case 1:
2211 flags |= mit_strip_vermagic;
2212 break;
2213 case 2:
2214 flags |= mit_strip_modversion;
2215 break;
2216 case 3:
2217 flags |= mit_first_time;
2218 break;
2219 case 4:
2220 dump_modver = 1;
2221 break;
2222 default:
2223 print_usage(argv[0]);
2227 /* If stderr not open, go to syslog */
2228 if (logging || fstat(STDERR_FILENO, &statbuf) != 0) {
2229 openlog("modprobe", LOG_CONS, LOG_DAEMON);
2230 logging = 1;
2233 if (argc < optind + 1 && !dump_config && !list_only)
2234 print_usage(argv[0]);
2236 nofail_asprintf(&dirname, "%s%s/%s", basedir, MODULE_DIR, buf.release);
2238 /* Old-style -t xxx wildcard? Only with -l. */
2239 if (list_only) {
2240 if (optind+1 < argc)
2241 fatal("Can't have multiple wildcards\n");
2242 /* fprintf(stderr, "man find\n"); return 1; */
2243 failed = do_wildcard(dirname, type, argv[optind]?:"*");
2244 goto out;
2246 if (type)
2247 fatal("-t only supported with -l");
2249 if (dump_modver) {
2250 dump_modversions(argv[optind], error);
2251 goto out;
2254 /* Read aliases, options etc. */
2255 parse_toplevel_config(configname, &conf, dump_config, flags & mit_remove);
2257 /* Read module options from kernel command line */
2258 parse_kcmdline(dump_config, &conf);
2260 /* report config only? */
2261 if (dump_config) {
2262 char *aliasfilename, *symfilename;
2263 struct modprobe_conf conf = {};
2265 nofail_asprintf(&aliasfilename, "%s/modules.alias", dirname);
2266 nofail_asprintf(&symfilename, "%s/modules.symbols", dirname);
2268 read_aliases(aliasfilename, "", 1, &conf.aliases);
2269 read_aliases(symfilename, "", 1, &conf.aliases);
2271 goto out;
2274 if ((flags & mit_remove) || all) {
2275 num_modules = argc - optind;
2276 cmdline_opts = NOFAIL(strdup(""));
2277 } else {
2278 num_modules = 1;
2279 cmdline_opts = gather_options(argv+optind+1);
2282 /* Convert names we are looking for */
2283 for (i = 0; i < num_modules; i++)
2284 underscores(argv[optind + i]);
2286 /* If we have a list of modules to remove, try the unused ones first.
2287 Aliases and modules which don't seem to exist are handled later. */
2288 if (flags & mit_remove) {
2289 int progress;
2290 do {
2291 progress = 0;
2293 for (i = 0; i < num_modules; i++) {
2294 const char *modname;
2295 unsigned usecount;
2296 LIST_HEAD(list);
2298 modname = argv[optind + i];
2299 if (!modname)
2300 continue;
2301 if (module_in_kernel(modname, &usecount) != 1)
2302 continue;
2303 if (usecount != 0)
2304 continue;
2306 read_depends(dirname, modname, &list);
2308 failed |= handle_module(modname, &list,
2309 cmdline_opts, cmdline_opts,
2310 &conf, dirname, error, flags);
2311 progress++;
2312 argv[optind + i] = NULL;
2313 INIT_LIST_HEAD(&list);
2315 } while (progress > 0);
2318 /* num_modules is always 1 except for -r or -a. */
2319 for (i = 0; i < num_modules; i++) {
2320 const char *modname = argv[optind + i];
2322 if (!modname)
2323 continue;
2325 failed |= do_modprobe(modname, cmdline_opts,
2326 &conf, dirname, error, flags);
2329 out:
2330 if (logging)
2331 closelog();
2332 free(dirname);
2333 free(cmdline_opts);
2334 /* Don't bother to free conf */
2336 exit(failed);