2 * Copyright (C) 2013 Felix Fietkau <nbd@openwrt.org>
3 * Copyright (C) 2013 John Crispin <blogic@openwrt.org>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU Lesser General Public License version 2.1
7 * as published by the Free Software Foundation
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
16 #include <sys/syscall.h>
18 #include <sys/utsname.h>
22 #include <sys/syscall.h>
23 #include <sys/types.h>
34 #include <libubox/avl.h>
35 #include <libubox/avl-cmp.h>
36 #include <libubox/utils.h>
37 #include <libubox/ulog.h>
39 #define DEF_MOD_PATH "/modules/%s/"
40 /* duplicated from in-kernel include/linux/module.h */
41 #define MODULE_NAME_LEN (64 - sizeof(unsigned long))
58 int refcnt; /* number of references from module_node.m */
67 static struct avl_tree modules;
69 static char **module_folders = NULL;
71 static void free_module(struct module *m);
73 static int init_module_folders(void)
78 char *s, *e, *p, path[330], ldpath[256];
81 s = getenv("LD_LIBRARY_PATH");
84 e += snprintf(ldpath, sizeof(ldpath), "%s:", s);
86 e += snprintf(e, sizeof(ldpath) - (e - ldpath), "/lib");
90 for (s = p = ldpath; p <= e; p++) {
91 if (*p != ':' && *p != '\0')
95 snprintf(path, sizeof(path), "%s" DEF_MOD_PATH, s, ver.release);
97 if (!stat(path, &st) && S_ISDIR(st.st_mode)) {
98 module_folders = realloc(module_folders, sizeof(p) * (n + 2));
100 if (!module_folders) {
101 ULOG_ERR("out of memory\n");
105 module_folders[n++] = strdup(path);
111 if (!module_folders) {
112 ULOG_ERR("no module folders for kernel version %s found\n", ver.release);
116 module_folders[n] = NULL;
120 static struct module *find_module(const char *name)
122 struct module_node *mn;
123 mn = avl_find_element(&modules, name, mn, avl);
130 static void free_modules(void)
132 struct module_node *mn, *tmp;
134 avl_remove_all_elements(&modules, mn, avl, tmp) {
135 struct module *m = mn->m;
144 static char* get_module_path(char *name)
147 static char path[256];
150 if (!stat(name, &s) && S_ISREG(s.st_mode))
153 for (p = module_folders; *p; p++) {
154 snprintf(path, sizeof(path), "%s%s.ko", *p, name);
155 if (!stat(path, &s) && S_ISREG(s.st_mode))
162 static char* get_module_name(char *path)
164 static char name[MODULE_NAME_LEN];
167 strncpy(name, basename(path), sizeof(name) - 1);
169 t = strstr(name, ".ko");
176 static int elf64_find_section(char *map, const char *section, unsigned int *offset, unsigned int *size)
178 const char *secnames;
183 e = (Elf64_Ehdr *) map;
184 sh = (Elf64_Shdr *) (map + e->e_shoff);
186 secnames = map + sh[e->e_shstrndx].sh_offset;
187 for (i = 0; i < e->e_shnum; i++) {
188 if (!strcmp(section, secnames + sh[i].sh_name)) {
189 *size = sh[i].sh_size;
190 *offset = sh[i].sh_offset;
198 static int elf32_find_section(char *map, const char *section, unsigned int *offset, unsigned int *size)
200 const char *secnames;
205 e = (Elf32_Ehdr *) map;
206 sh = (Elf32_Shdr *) (map + e->e_shoff);
208 secnames = map + sh[e->e_shstrndx].sh_offset;
209 for (i = 0; i < e->e_shnum; i++) {
210 if (!strcmp(section, secnames + sh[i].sh_name)) {
211 *size = sh[i].sh_size;
212 *offset = sh[i].sh_offset;
220 static int elf_find_section(char *map, const char *section, unsigned int *offset, unsigned int *size)
222 int clazz = map[EI_CLASS];
223 int endian = map[EI_DATA];
225 #if __BYTE_ORDER == __LITTLE_ENDIAN
226 if (endian != ELFDATA2LSB)
227 #elif __BYTE_ORDER == __BIG_ENDIAN
228 if (endian != ELFDATA2MSB)
230 #error "unsupported endian"
233 ULOG_ERR("invalid endianess: %d\n", endian);
237 if (clazz == ELFCLASS32)
238 return elf32_find_section(map, section, offset, size);
239 else if (clazz == ELFCLASS64)
240 return elf64_find_section(map, section, offset, size);
242 ULOG_ERR("unknown elf format %d\n", clazz);
247 static struct module_node *
248 alloc_module_node(const char *name, struct module *m, bool is_alias)
250 struct module_node *mn;
253 mn = calloc_a(sizeof(*mn),
254 &_name, strlen(name) + 1);
256 mn->avl.key = strcpy(_name, name);
258 mn->is_alias = is_alias;
259 avl_insert(&modules, &mn->avl);
265 static struct module *
266 alloc_module(const char *name, const char * const *aliases, int naliases, const char *depends, int size)
272 m = calloc_a(sizeof(*m),
273 &_name, strlen(name) + 1,
274 &_dep, depends ? strlen(depends) + 2 : 0);
278 m->name = strcpy(_name, name);
282 m->depends = strcpy(_dep, depends);
292 alloc_module_node(m->name, m, false);
293 for (i = 0; i < naliases; i++)
294 alloc_module_node(aliases[i], m, true);
299 static void free_module(struct module *m)
306 static int scan_loaded_modules(void)
312 fp = fopen("/proc/modules", "r");
314 ULOG_ERR("failed to open /proc/modules\n");
318 while (getline(&buf, &buf_len, fp) > 0) {
322 m.name = strtok(buf, " ");
323 m.size = atoi(strtok(NULL, " "));
324 m.usage = atoi(strtok(NULL, " "));
325 m.depends = strtok(NULL, " ");
327 if (!m.name || !m.depends)
330 n = find_module(m.name);
332 /* possibly a module outside /lib/modules/<ver>/ */
333 n = alloc_module(m.name, NULL, 0, m.depends, m.size);
344 static struct module* get_module_info(const char *module, const char *name)
346 int fd = open(module, O_RDONLY);
347 unsigned int offset, size;
348 char *map = MAP_FAILED, *strings, *dep = NULL;
349 const char **aliases = NULL;
351 struct module *m = NULL;
355 ULOG_ERR("failed to open %s\n", module);
359 if (fstat(fd, &s) == -1) {
360 ULOG_ERR("failed to stat %s\n", module);
364 map = mmap(NULL, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
365 if (map == MAP_FAILED) {
366 ULOG_ERR("failed to mmap %s\n", module);
370 if (elf_find_section(map, ".modinfo", &offset, &size)) {
371 ULOG_ERR("failed to load the .modinfo section from %s\n", module);
375 strings = map + offset;
382 if (strings >= map + offset + size)
384 sep = strstr(strings, "=");
389 if (!strncmp(strings, "depends=", len + 1))
391 else if (!strncmp(strings, "alias=", len + 1)) {
392 aliases = realloc(aliases, sizeof(sep) * (naliases + 1));
394 ULOG_ERR("out of memory\n");
398 aliases[naliases++] = sep;
400 strings = &sep[strlen(sep)];
403 m = alloc_module(name, aliases, naliases, dep, s.st_size);
409 if (map != MAP_FAILED)
410 munmap(map, s.st_size);
420 static int scan_module_folder(const char *dir)
422 int gl_flags = GLOB_NOESCAPE | GLOB_MARK;
429 path = alloca(strlen(dir) + sizeof("*.ko") + 1);
430 sprintf(path, "%s*.ko", dir);
432 if (glob(path, gl_flags, NULL, &gl) < 0)
435 for (j = 0; j < gl.gl_pathc; j++) {
436 char *name = get_module_name(gl.gl_pathv[j]);
442 m = find_module(name);
444 if (!get_module_info(gl.gl_pathv[j], name))
454 static int scan_module_folders(void)
459 if (init_module_folders())
462 for (p = module_folders; *p; p++)
463 rv |= scan_module_folder(*p);
468 static int print_modinfo(char *module)
470 int fd = open(module, O_RDONLY);
471 unsigned int offset, size;
473 char *map = MAP_FAILED, *strings;
477 ULOG_ERR("failed to open %s\n", module);
481 if (fstat(fd, &s) == -1) {
482 ULOG_ERR("failed to stat %s\n", module);
486 map = mmap(NULL, s.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
487 if (map == MAP_FAILED) {
488 ULOG_ERR("failed to mmap %s\n", module);
492 if (elf_find_section(map, ".modinfo", &offset, &size)) {
493 ULOG_ERR("failed to load the .modinfo section from %s\n", module);
497 strings = map + offset;
498 printf("module:\t\t%s\n", module);
505 if (strings >= map + offset + size)
507 sep = strstr(strings, "=");
510 dup = strndup(strings, sep - strings);
512 if (strncmp(strings, "parm", 4)) {
514 printf("%s:\t\t%s\n", dup, sep);
516 printf("%s:\t%s\n", dup, sep);
518 strings = &sep[strlen(sep)];
526 if (map != MAP_FAILED)
527 munmap(map, s.st_size);
535 static int deps_available(struct module *m, int verbose)
540 if (!m->depends || !strcmp(m->depends, "-") || !strcmp(m->depends, ""))
546 m = find_module(dep);
549 ULOG_ERR("missing dependency %s\n", dep);
550 if (verbose && m && (m->state != LOADED))
551 ULOG_ERR("dependency not loaded %s\n", dep);
552 if (!m || (m->state != LOADED))
554 dep += strlen(dep) + 1;
560 static int insert_module(char *path, const char *options)
566 if (stat(path, &s)) {
567 ULOG_ERR("missing module %s\n", path);
571 fd = open(path, O_RDONLY);
573 ULOG_ERR("cannot open %s\n", path);
577 data = malloc(s.st_size);
579 ULOG_ERR("out of memory\n");
583 if (read(fd, data, s.st_size) == s.st_size) {
584 ret = syscall(__NR_init_module, data, (unsigned long) s.st_size, options);
589 ULOG_ERR("failed to read full module %s\n", path);
598 static void load_moddeps(struct module *_m)
603 if (!strcmp(_m->depends, "-") || !strcmp(_m->depends, ""))
609 m = find_module(dep);
612 ULOG_ERR("failed to find dependency %s\n", dep);
613 if (m && (m->state != LOADED)) {
618 dep = dep + strlen(dep) + 1;
622 static int load_modprobe(bool allow_load_retry)
624 int loaded, skipped, failed;
625 struct module_node *mn;
627 bool load_retry = false;
628 static bool first_iteration = true;
630 avl_for_each_element(&modules, mn, avl) {
634 if (m->state == PROBE)
642 avl_for_each_element(&modules, mn, avl) {
646 if ((m->state == PROBE) && (!deps_available(m, 0)) && (!m->error || load_retry)) {
647 if (!insert_module(get_module_path(m->name), (m->opts) ? (m->opts) : (""))) {
659 else if (m->state == PROBE)
663 if (allow_load_retry) {
664 /* if we can't load anything else let's try to load failed modules */
665 load_retry = loaded ? (failed && !skipped) : (failed && !load_retry && !first_iteration);
668 first_iteration = false;
669 } while (loaded || load_retry);
671 return skipped + failed;
674 static int print_insmod_usage(void)
676 ULOG_INFO("Usage:\n\tinsmod filename [args]\n");
681 static int print_modprobe_usage(void)
685 "\tmodprobe [-q] [-v] filename\n"
686 "\tmodprobe -a [-q] [-v] filename [filename...]\n"
692 static int print_usage(char *arg)
694 ULOG_INFO("Usage:\n\t%s module\n", arg);
699 static int main_insmod(int argc, char **argv)
701 char *name, *cur, *options;
705 return print_insmod_usage();
707 name = get_module_name(argv[1]);
709 ULOG_ERR("cannot find module - %s\n", argv[1]);
713 if (scan_loaded_modules())
716 if (find_module(name)) {
717 ULOG_ERR("module is already loaded - %s\n", name);
724 for (len = 0, i = 2; i < argc; i++)
725 len += strlen(argv[i]) + 1;
727 options = malloc(len);
729 ULOG_ERR("out of memory\n");
736 for (i = 2; i < argc; i++) {
741 cur += sprintf(cur, "%s", argv[i]);
744 if (init_module_folders()) {
745 fprintf(stderr, "Failed to find the folder holding the modules\n");
750 if (get_module_path(argv[1])) {
752 } else if (!get_module_path(name)) {
753 fprintf(stderr, "Failed to find %s. Maybe it is a built in module ?\n", name);
758 ret = insert_module(get_module_path(name), options);
760 ULOG_ERR("failed to insert %s\n", get_module_path(name));
767 static int main_rmmod(int argc, char **argv)
774 return print_usage("rmmod");
776 if (scan_loaded_modules())
779 name = get_module_name(argv[1]);
780 m = find_module(name);
782 ULOG_ERR("module is not loaded\n");
785 ret = syscall(__NR_delete_module, m->name, 0);
788 ULOG_ERR("unloading the module failed\n");
795 static int main_lsmod(int argc, char **argv)
797 struct module_node *mn;
801 if (scan_loaded_modules())
804 avl_for_each_element(&modules, mn, avl) {
808 if (m->state == LOADED) {
809 printf("%-20s%8d%3d ",
810 m->name, m->size, m->usage);
811 if (m->depends && strcmp(m->depends, "-") && strcmp(m->depends, "")) {
815 dep = dep + strlen(dep) + 1;
829 static int main_modinfo(int argc, char **argv)
835 return print_usage("modinfo");
837 if (scan_module_folders())
840 name = get_module_name(argv[1]);
841 m = find_module(name);
843 ULOG_ERR("cannot find module - %s\n", argv[1]);
847 name = get_module_path(m->name);
849 ULOG_ERR("cannot find path of module - %s\n", m->name);
858 static int main_modprobe(int argc, char **argv)
860 struct module_node *mn;
864 int log_level = LOG_WARNING;
867 bool use_all = false;
869 while ((opt = getopt(argc, argv, "aqv")) != -1 ) {
874 case 'q': /* shhhh! */
878 log_level = LOG_DEBUG;
881 return print_modprobe_usage();
887 return print_modprobe_usage(); /* expected module after options */
889 /* after print_modprobe_usage() so it won't be filtered out */
890 ulog_threshold(log_level);
892 if (scan_module_folders())
895 if (scan_loaded_modules())
901 name = get_module_name(argv[optind]);
902 m = find_module(name);
904 if (m && m->state == LOADED) {
906 ULOG_INFO("%s is already loaded\n", name);
909 ULOG_ERR("failed to find a module named %s\n", name);
916 } while (use_all && optind < argc);
918 load_fail = load_modprobe(true);
920 ULOG_ERR("%d module%s could not be probed\n",
921 load_fail, (load_fail == 1) ? ("") : ("s"));
923 avl_for_each_element(&modules, mn, avl) {
927 if ((m->state == PROBE) || m->error)
928 ULOG_ERR("- %s\n", m->name);
939 static int main_loader(int argc, char **argv)
941 int gl_flags = GLOB_NOESCAPE | GLOB_MARK;
942 char *dir = "/etc/modules.d/";
943 struct module_node *mn;
952 path = malloc(strlen(dir) + 2);
954 ULOG_ERR("out of memory\n");
961 if (scan_module_folders()) {
966 if (scan_loaded_modules()) {
971 ULOG_INFO("loading kernel modules from %s\n", path);
973 if (glob(path, gl_flags, NULL, &gl) < 0)
976 for (j = 0; j < gl.gl_pathc; j++) {
977 FILE *fp = fopen(gl.gl_pathv[j], "r");
982 ULOG_ERR("failed to open %s\n", gl.gl_pathv[j]);
986 while (getline(&mod, &mod_len, fp) > 0) {
987 char *nl = strchr(mod, '\n');
994 opts = strchr(mod, ' ');
998 m = find_module(get_module_name(mod));
999 if (!m || (m->state == LOADED))
1003 m->opts = strdup(opts);
1005 if (basename(gl.gl_pathv[j])[0] - '0' <= 9)
1006 load_modprobe(false);
1013 fail = load_modprobe(true);
1016 ULOG_ERR("%d module%s could not be probed\n",
1017 fail, (fail == 1) ? ("") : ("s"));
1019 avl_for_each_element(&modules, mn, avl) {
1023 if ((m->state == PROBE) || (m->error))
1024 ULOG_ERR("- %s - %d\n", m->name, deps_available(m, 1));
1027 ULOG_INFO("done loading kernel modules from %s\n", path);
1037 static inline char weight(char c)
1039 return c == '_' ? '-' : c;
1042 static int avl_modcmp(const void *k1, const void *k2, void *ptr)
1044 const char *s1 = k1;
1045 const char *s2 = k2;
1047 while (*s1 && (weight(*s1) == weight(*s2)))
1053 return (unsigned char)weight(*s1) - (unsigned char)weight(*s2);
1056 int main(int argc, char **argv)
1058 char *exec = basename(*argv);
1060 avl_init(&modules, avl_modcmp, false, NULL);
1061 if (!strcmp(exec, "insmod"))
1062 return main_insmod(argc, argv);
1064 if (!strcmp(exec, "rmmod"))
1065 return main_rmmod(argc, argv);
1067 if (!strcmp(exec, "lsmod"))
1068 return main_lsmod(argc, argv);
1070 if (!strcmp(exec, "modinfo"))
1071 return main_modinfo(argc, argv);
1073 if (!strcmp(exec, "modprobe"))
1074 return main_modprobe(argc, argv);
1076 ulog_open(ULOG_KMSG, LOG_USER, "kmodloader");
1077 return main_loader(argc, argv);