2 * libkmod - interface to kernel module operations
4 * Copyright (C) 2011-2013 ProFUSION embedded systems
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
32 #include <sys/utsname.h>
34 #include <shared/hash.h>
35 #include <shared/util.h>
38 #include "libkmod-internal.h"
39 #include "libkmod-index.h"
41 #define KMOD_HASH_SIZE (256)
42 #define KMOD_LRU_MAX (128)
43 #define _KMOD_INDEX_MODULES_SIZE KMOD_INDEX_MODULES_BUILTIN + 1
47 * @short_description: libkmod context
49 * The context contains the default values for the library user,
50 * and is passed to all library operations.
53 static struct _index_files {
57 [KMOD_INDEX_MODULES_DEP] = { .fn = "modules.dep", .prefix = "" },
58 [KMOD_INDEX_MODULES_ALIAS] = { .fn = "modules.alias", .prefix = "alias " },
59 [KMOD_INDEX_MODULES_SYMBOL] = { .fn = "modules.symbols", .prefix = "alias "},
60 [KMOD_INDEX_MODULES_BUILTIN_ALIAS] = { .fn = "modules.builtin.alias", .prefix = "" },
61 [KMOD_INDEX_MODULES_BUILTIN] = { .fn = "modules.builtin", .prefix = ""},
64 static const char *default_config_paths[] = {
65 SYSCONFDIR "/modprobe.d",
74 * Opaque object representing the library context.
79 void (*log_fn)(void *data,
80 int priority, const char *file, int line,
81 const char *fn, const char *format, va_list args);
85 struct kmod_config *config;
86 struct hash *modules_by_name;
87 struct index_mm *indexes[_KMOD_INDEX_MODULES_SIZE];
88 unsigned long long indexes_stamp[_KMOD_INDEX_MODULES_SIZE];
91 void kmod_log(const struct kmod_ctx *ctx,
92 int priority, const char *file, int line, const char *fn,
93 const char *format, ...)
97 if (ctx->log_fn == NULL)
100 va_start(args, format);
101 ctx->log_fn(ctx->log_data, priority, file, line, fn, format, args);
105 _printf_format_(6, 0)
106 static void log_filep(void *data,
107 int priority, const char *file, int line,
108 const char *fn, const char *format, va_list args)
116 priname = "EMERGENCY";
122 priname = "CRITICAL";
140 snprintf(buf, sizeof(buf), "L:%d", priority);
143 fprintf(fp, "libkmod: %s %s:%d %s: ", priname, file, line, fn);
145 fprintf(fp, "libkmod: %s: ", fn);
147 vfprintf(fp, format, args);
153 * @ctx: kmod library context
155 * Retrieve the absolute path used for linux modules in this context. The path
156 * is computed from the arguments to kmod_new().
158 KMOD_EXPORT const char *kmod_get_dirname(const struct kmod_ctx *ctx)
165 * @ctx: kmod library context
167 * Retrieve stored data pointer from library context. This might be useful
168 * to access from callbacks.
170 * Returns: stored userdata
172 KMOD_EXPORT void *kmod_get_userdata(const struct kmod_ctx *ctx)
176 return (void *)ctx->userdata;
181 * @ctx: kmod library context
182 * @userdata: data pointer
184 * Store custom @userdata in the library context.
186 KMOD_EXPORT void kmod_set_userdata(struct kmod_ctx *ctx, const void *userdata)
190 ctx->userdata = userdata;
193 static int log_priority(const char *priority)
198 prio = strtol(priority, &endptr, 10);
199 if (endptr[0] == '\0' || isspace(endptr[0]))
201 if (strncmp(priority, "err", 3) == 0)
203 if (strncmp(priority, "info", 4) == 0)
205 if (strncmp(priority, "debug", 5) == 0)
210 static const char *dirname_default_prefix = "/lib/modules";
212 static char *get_kernel_release(const char *dirname)
218 return path_make_absolute_cwd(dirname);
223 if (asprintf(&p, "%s/%s", dirname_default_prefix, u.release) < 0)
231 * @dirname: what to consider as linux module's directory, if NULL
232 * defaults to /lib/modules/`uname -r`. If it's relative,
233 * it's treated as relative to the current working directory.
234 * Otherwise, give an absolute dirname.
235 * @config_paths: ordered array of paths (directories or files) where
236 * to load from user-defined configuration parameters such as
237 * alias, blacklists, commands (install, remove). If
238 * NULL defaults to /etc/modprobe.d, /run/modprobe.d and
239 * /lib/modprobe.d. Give an empty vector if configuration should
240 * not be read. This array must be null terminated.
242 * Create kmod library context. This reads the kmod configuration
243 * and fills in the default values.
245 * The initial refcount is 1, and needs to be decremented to
246 * release the resources of the kmod library context.
248 * Returns: a new kmod library context
250 KMOD_EXPORT struct kmod_ctx *kmod_new(const char *dirname,
251 const char * const *config_paths)
254 struct kmod_ctx *ctx;
257 ctx = calloc(1, sizeof(struct kmod_ctx));
262 ctx->log_fn = log_filep;
263 ctx->log_data = stderr;
264 ctx->log_priority = LOG_ERR;
266 ctx->dirname = get_kernel_release(dirname);
268 /* environment overwrites config */
269 env = secure_getenv("KMOD_LOG");
271 kmod_set_log_priority(ctx, log_priority(env));
273 if (config_paths == NULL)
274 config_paths = default_config_paths;
275 err = kmod_config_new(ctx, &ctx->config, config_paths);
277 ERR(ctx, "could not create config\n");
281 ctx->modules_by_name = hash_new(KMOD_HASH_SIZE, NULL);
282 if (ctx->modules_by_name == NULL) {
283 ERR(ctx, "could not create by-name hash\n");
287 INFO(ctx, "ctx %p created\n", ctx);
288 DBG(ctx, "log_priority=%d\n", ctx->log_priority);
293 free(ctx->modules_by_name);
301 * @ctx: kmod library context
303 * Take a reference of the kmod library context.
305 * Returns: the passed kmod library context
307 KMOD_EXPORT struct kmod_ctx *kmod_ref(struct kmod_ctx *ctx)
317 * @ctx: kmod library context
319 * Drop a reference of the kmod library context. If the refcount
320 * reaches zero, the resources of the context will be released.
322 * Returns: the passed kmod library context or NULL if it's freed
324 KMOD_EXPORT struct kmod_ctx *kmod_unref(struct kmod_ctx *ctx)
329 if (--ctx->refcount > 0)
332 INFO(ctx, "context %p released\n", ctx);
334 kmod_unload_resources(ctx);
335 hash_free(ctx->modules_by_name);
338 kmod_config_free(ctx->config);
346 * @ctx: kmod library context
347 * @log_fn: function to be called for logging messages
348 * @data: data to pass to log function
350 * The built-in logging writes to stderr. It can be
351 * overridden by a custom function, to plug log messages
352 * into the user's logging functionality.
354 KMOD_EXPORT void kmod_set_log_fn(struct kmod_ctx *ctx,
355 void (*log_fn)(void *data,
356 int priority, const char *file,
357 int line, const char *fn,
358 const char *format, va_list args),
363 ctx->log_fn = log_fn;
364 ctx->log_data = (void *)data;
365 INFO(ctx, "custom logging function %p registered\n", log_fn);
369 * kmod_get_log_priority:
370 * @ctx: kmod library context
372 * Returns: the current logging priority
374 KMOD_EXPORT int kmod_get_log_priority(const struct kmod_ctx *ctx)
378 return ctx->log_priority;
382 * kmod_set_log_priority:
383 * @ctx: kmod library context
384 * @priority: the new logging priority
386 * Set the current logging priority. The value controls which messages
389 KMOD_EXPORT void kmod_set_log_priority(struct kmod_ctx *ctx, int priority)
393 ctx->log_priority = priority;
396 struct kmod_module *kmod_pool_get_module(struct kmod_ctx *ctx,
399 struct kmod_module *mod;
401 mod = hash_find(ctx->modules_by_name, key);
403 DBG(ctx, "get module name='%s' found=%p\n", key, mod);
408 void kmod_pool_add_module(struct kmod_ctx *ctx, struct kmod_module *mod,
411 DBG(ctx, "add %p key='%s'\n", mod, key);
413 hash_add(ctx->modules_by_name, key, mod);
416 void kmod_pool_del_module(struct kmod_ctx *ctx, struct kmod_module *mod,
419 DBG(ctx, "del %p key='%s'\n", mod, key);
421 hash_del(ctx->modules_by_name, key);
424 static int kmod_lookup_alias_from_alias_bin(struct kmod_ctx *ctx,
425 enum kmod_index index_number,
427 struct kmod_list **list)
430 struct index_file *idx;
431 struct index_value *realnames, *realname;
433 if (ctx->indexes[index_number] != NULL) {
434 DBG(ctx, "use mmaped index '%s' for name=%s\n",
435 index_files[index_number].fn, name);
436 realnames = index_mm_searchwild(ctx->indexes[index_number],
441 snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
442 index_files[index_number].fn);
444 DBG(ctx, "file=%s name=%s\n", fn, name);
446 idx = index_file_open(fn);
450 realnames = index_searchwild(idx, name);
451 index_file_close(idx);
454 for (realname = realnames; realname; realname = realname->next) {
455 struct kmod_module *mod;
457 err = kmod_module_new_from_alias(ctx, name, realname->value, &mod);
459 ERR(ctx, "Could not create module for alias=%s realname=%s: %s\n",
460 name, realname->value, strerror(-err));
464 *list = kmod_list_append(*list, mod);
468 index_values_free(realnames);
472 *list = kmod_list_remove_n_latest(*list, nmatch);
473 index_values_free(realnames);
478 int kmod_lookup_alias_from_symbols_file(struct kmod_ctx *ctx, const char *name,
479 struct kmod_list **list)
481 if (!strstartswith(name, "symbol:"))
484 return kmod_lookup_alias_from_alias_bin(ctx, KMOD_INDEX_MODULES_SYMBOL,
488 int kmod_lookup_alias_from_aliases_file(struct kmod_ctx *ctx, const char *name,
489 struct kmod_list **list)
491 return kmod_lookup_alias_from_alias_bin(ctx, KMOD_INDEX_MODULES_ALIAS,
495 static char *lookup_builtin_file(struct kmod_ctx *ctx, const char *name)
499 if (ctx->indexes[KMOD_INDEX_MODULES_BUILTIN]) {
500 DBG(ctx, "use mmaped index '%s' modname=%s\n",
501 index_files[KMOD_INDEX_MODULES_BUILTIN].fn,
503 line = index_mm_search(ctx->indexes[KMOD_INDEX_MODULES_BUILTIN],
506 struct index_file *idx;
509 snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
510 index_files[KMOD_INDEX_MODULES_BUILTIN].fn);
511 DBG(ctx, "file=%s modname=%s\n", fn, name);
513 idx = index_file_open(fn);
515 DBG(ctx, "could not open builtin file '%s'\n", fn);
519 line = index_search(idx, name);
520 index_file_close(idx);
526 int kmod_lookup_alias_from_kernel_builtin_file(struct kmod_ctx *ctx,
528 struct kmod_list **list)
533 assert(*list == NULL);
535 ret = kmod_lookup_alias_from_alias_bin(ctx,
536 KMOD_INDEX_MODULES_BUILTIN_ALIAS,
539 kmod_list_foreach(l, *list) {
540 struct kmod_module *mod = l->data;
541 kmod_module_set_builtin(mod, true);
547 int kmod_lookup_alias_from_builtin_file(struct kmod_ctx *ctx, const char *name,
548 struct kmod_list **list)
553 assert(*list == NULL);
555 line = lookup_builtin_file(ctx, name);
557 struct kmod_module *mod;
559 err = kmod_module_new_from_name(ctx, name, &mod);
561 ERR(ctx, "Could not create module from name %s: %s\n",
562 name, strerror(-err));
566 /* already mark it as builtin since it's being created from
568 kmod_module_set_builtin(mod, true);
569 *list = kmod_list_append(*list, mod);
579 bool kmod_lookup_alias_is_builtin(struct kmod_ctx *ctx, const char *name)
581 _cleanup_free_ char *line;
583 line = lookup_builtin_file(ctx, name);
588 char *kmod_search_moddep(struct kmod_ctx *ctx, const char *name)
590 struct index_file *idx;
594 if (ctx->indexes[KMOD_INDEX_MODULES_DEP]) {
595 DBG(ctx, "use mmaped index '%s' modname=%s\n",
596 index_files[KMOD_INDEX_MODULES_DEP].fn, name);
597 return index_mm_search(ctx->indexes[KMOD_INDEX_MODULES_DEP],
601 snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
602 index_files[KMOD_INDEX_MODULES_DEP].fn);
604 DBG(ctx, "file=%s modname=%s\n", fn, name);
606 idx = index_file_open(fn);
608 DBG(ctx, "could not open moddep file '%s'\n", fn);
612 line = index_search(idx, name);
613 index_file_close(idx);
618 int kmod_lookup_alias_from_moddep_file(struct kmod_ctx *ctx, const char *name,
619 struct kmod_list **list)
625 * Module names do not contain ':'. Return early if we know it will
628 if (strchr(name, ':'))
631 line = kmod_search_moddep(ctx, name);
633 struct kmod_module *mod;
635 n = kmod_module_new_from_name(ctx, name, &mod);
637 ERR(ctx, "Could not create module from name %s: %s\n",
642 *list = kmod_list_append(*list, mod);
643 kmod_module_parse_depline(mod, line);
652 int kmod_lookup_alias_from_config(struct kmod_ctx *ctx, const char *name,
653 struct kmod_list **list)
655 struct kmod_config *config = ctx->config;
659 kmod_list_foreach(l, config->aliases) {
660 const char *aliasname = kmod_alias_get_name(l);
661 const char *modname = kmod_alias_get_modname(l);
663 if (fnmatch(aliasname, name, 0) == 0) {
664 struct kmod_module *mod;
666 err = kmod_module_new_from_alias(ctx, aliasname,
669 ERR(ctx, "Could not create module for alias=%s modname=%s: %s\n",
670 name, modname, strerror(-err));
674 *list = kmod_list_append(*list, mod);
682 *list = kmod_list_remove_n_latest(*list, nmatch);
686 int kmod_lookup_alias_from_commands(struct kmod_ctx *ctx, const char *name,
687 struct kmod_list **list)
689 struct kmod_config *config = ctx->config;
690 struct kmod_list *l, *node;
693 kmod_list_foreach(l, config->install_commands) {
694 const char *modname = kmod_command_get_modname(l);
696 if (streq(modname, name)) {
697 const char *cmd = kmod_command_get_command(l);
698 struct kmod_module *mod;
700 err = kmod_module_new_from_name(ctx, modname, &mod);
702 ERR(ctx, "Could not create module from name %s: %s\n",
703 modname, strerror(-err));
707 node = kmod_list_append(*list, mod);
709 ERR(ctx, "out of memory\n");
716 kmod_module_set_install_commands(mod, cmd);
719 * match only the first one, like modprobe from
720 * module-init-tools does
729 kmod_list_foreach(l, config->remove_commands) {
730 const char *modname = kmod_command_get_modname(l);
732 if (streq(modname, name)) {
733 const char *cmd = kmod_command_get_command(l);
734 struct kmod_module *mod;
736 err = kmod_module_new_from_name(ctx, modname, &mod);
738 ERR(ctx, "Could not create module from name %s: %s\n",
739 modname, strerror(-err));
743 node = kmod_list_append(*list, mod);
745 ERR(ctx, "out of memory\n");
752 kmod_module_set_remove_commands(mod, cmd);
755 * match only the first one, like modprobe from
756 * module-init-tools does
765 void kmod_set_modules_visited(struct kmod_ctx *ctx, bool visited)
767 struct hash_iter iter;
770 hash_iter_init(ctx->modules_by_name, &iter);
771 while (hash_iter_next(&iter, NULL, &v))
772 kmod_module_set_visited((struct kmod_module *)v, visited);
775 void kmod_set_modules_required(struct kmod_ctx *ctx, bool required)
777 struct hash_iter iter;
780 hash_iter_init(ctx->modules_by_name, &iter);
781 while (hash_iter_next(&iter, NULL, &v))
782 kmod_module_set_required((struct kmod_module *)v, required);
785 static bool is_cache_invalid(const char *path, unsigned long long stamp)
789 if (stat(path, &st) < 0)
792 if (stamp != stat_mstamp(&st))
799 * kmod_validate_resources:
800 * @ctx: kmod library context
802 * Check if indexes and configuration files changed on disk and the current
803 * context is not valid anymore.
805 * Returns: KMOD_RESOURCES_OK if resources are still valid,
806 * KMOD_RESOURCES_MUST_RELOAD if it's sufficient to call
807 * kmod_unload_resources() and kmod_load_resources() or
808 * KMOD_RESOURCES_MUST_RECREATE if @ctx must be re-created.
810 KMOD_EXPORT int kmod_validate_resources(struct kmod_ctx *ctx)
815 if (ctx == NULL || ctx->config == NULL)
816 return KMOD_RESOURCES_MUST_RECREATE;
818 kmod_list_foreach(l, ctx->config->paths) {
819 struct kmod_config_path *cf = l->data;
821 if (is_cache_invalid(cf->path, cf->stamp))
822 return KMOD_RESOURCES_MUST_RECREATE;
825 for (i = 0; i < _KMOD_INDEX_MODULES_SIZE; i++) {
828 if (ctx->indexes[i] == NULL)
831 snprintf(path, sizeof(path), "%s/%s.bin", ctx->dirname,
834 if (is_cache_invalid(path, ctx->indexes_stamp[i]))
835 return KMOD_RESOURCES_MUST_RELOAD;
838 return KMOD_RESOURCES_OK;
842 * kmod_load_resources:
843 * @ctx: kmod library context
845 * Load indexes and keep them open in @ctx. This way it's faster to lookup
846 * information within the indexes. If this function is not called before a
847 * search, the necessary index is always opened and closed.
849 * If user will do more than one or two lookups, insertions, deletions, most
850 * likely it's good to call this function first. Particularly in a daemon like
851 * udev that on bootup issues hundreds of calls to lookup the index, calling
852 * this function will speedup the searches.
854 * Returns: 0 on success or < 0 otherwise.
856 KMOD_EXPORT int kmod_load_resources(struct kmod_ctx *ctx)
864 for (i = 0; i < _KMOD_INDEX_MODULES_SIZE; i++) {
867 if (ctx->indexes[i] != NULL) {
868 INFO(ctx, "Index %s already loaded\n",
873 snprintf(path, sizeof(path), "%s/%s.bin", ctx->dirname,
875 ret = index_mm_open(ctx, path, &ctx->indexes_stamp[i],
879 * modules.builtin.alias are considered optional since it's
880 * recently added and older installations may not have it;
881 * we allow failing for any reason
884 if (i != KMOD_INDEX_MODULES_BUILTIN_ALIAS)
891 kmod_unload_resources(ctx);
897 * kmod_unload_resources:
898 * @ctx: kmod library context
900 * Unload all the indexes. This will free the resources to maintain the index
901 * open and all subsequent searches will need to open and close the index.
903 * User is free to call kmod_load_resources() and kmod_unload_resources() as
904 * many times as wanted during the lifecycle of @ctx. For example, if a daemon
905 * knows that when starting up it will lookup a lot of modules, it could call
906 * kmod_load_resources() and after the first burst of searches is gone, it
907 * could free the resources by calling kmod_unload_resources().
909 * Returns: 0 on success or < 0 otherwise.
911 KMOD_EXPORT void kmod_unload_resources(struct kmod_ctx *ctx)
918 for (i = 0; i < _KMOD_INDEX_MODULES_SIZE; i++) {
919 if (ctx->indexes[i] != NULL) {
920 index_mm_close(ctx->indexes[i]);
921 ctx->indexes[i] = NULL;
922 ctx->indexes_stamp[i] = 0;
929 * @ctx: kmod library context
930 * @type: index to dump, valid indexes are
931 * KMOD_INDEX_MODULES_DEP: index of module dependencies;
932 * KMOD_INDEX_MODULES_ALIAS: index of module aliases;
933 * KMOD_INDEX_MODULES_SYMBOL: index of symbol aliases;
934 * KMOD_INDEX_MODULES_BUILTIN: index of builtin module.
935 * @fd: file descriptor to dump index to
937 * Dump index to file descriptor. Note that this function doesn't use stdio.h
938 * so call fflush() before calling this function to be sure data is written in
941 * Returns: 0 on success or < 0 otherwise.
943 KMOD_EXPORT int kmod_dump_index(struct kmod_ctx *ctx, enum kmod_index type,
949 if (type < 0 || type >= _KMOD_INDEX_MODULES_SIZE)
952 if (ctx->indexes[type] != NULL) {
953 DBG(ctx, "use mmaped index '%s'\n", index_files[type].fn);
954 index_mm_dump(ctx->indexes[type], fd,
955 index_files[type].prefix);
958 struct index_file *idx;
960 snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
961 index_files[type].fn);
963 DBG(ctx, "file=%s\n", fn);
965 idx = index_file_open(fn);
969 index_dump(idx, fd, index_files[type].prefix);
970 index_file_close(idx);
976 const struct kmod_config *kmod_get_config(const struct kmod_ctx *ctx)