Add /lib/modules/modprobe.d to configuration search path
[platform/upstream/kmod.git] / libkmod / libkmod.c
1 /*
2  * libkmod - interface to kernel module operations
3  *
4  * Copyright (C) 2011-2013  ProFUSION embedded systems
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 #include <assert.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #include <fnmatch.h>
24 #include <limits.h>
25 #include <stdarg.h>
26 #include <stddef.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <sys/stat.h>
32 #include <sys/utsname.h>
33
34 #include <shared/hash.h>
35 #include <shared/util.h>
36
37 #include "libkmod.h"
38 #include "libkmod-internal.h"
39 #include "libkmod-index.h"
40
41 #define KMOD_HASH_SIZE (256)
42 #define KMOD_LRU_MAX (128)
43 #define _KMOD_INDEX_MODULES_SIZE KMOD_INDEX_MODULES_BUILTIN + 1
44
45 /**
46  * SECTION:libkmod
47  * @short_description: libkmod context
48  *
49  * The context contains the default values for the library user,
50  * and is passed to all library operations.
51  */
52
53 static struct _index_files {
54         const char *fn;
55         const char *prefix;
56 } 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 = ""},
62 };
63
64 static const char *default_config_paths[] = {
65         SYSCONFDIR "/modprobe.d",
66         "/run/modprobe.d",
67         "/usr/local/lib/modprobe.d",
68         "/lib/modprobe.d",
69         "/lib/modules/modprobe.d",
70         NULL
71 };
72
73 /**
74  * kmod_ctx:
75  *
76  * Opaque object representing the library context.
77  */
78 struct kmod_ctx {
79         int refcount;
80         int log_priority;
81         void (*log_fn)(void *data,
82                         int priority, const char *file, int line,
83                         const char *fn, const char *format, va_list args);
84         void *log_data;
85         const void *userdata;
86         char *dirname;
87         struct kmod_config *config;
88         struct hash *modules_by_name;
89         struct index_mm *indexes[_KMOD_INDEX_MODULES_SIZE];
90         unsigned long long indexes_stamp[_KMOD_INDEX_MODULES_SIZE];
91 };
92
93 void kmod_log(const struct kmod_ctx *ctx,
94                 int priority, const char *file, int line, const char *fn,
95                 const char *format, ...)
96 {
97         va_list args;
98
99         if (ctx->log_fn == NULL)
100                 return;
101
102         va_start(args, format);
103         ctx->log_fn(ctx->log_data, priority, file, line, fn, format, args);
104         va_end(args);
105 }
106
107 _printf_format_(6, 0)
108 static void log_filep(void *data,
109                         int priority, const char *file, int line,
110                         const char *fn, const char *format, va_list args)
111 {
112         FILE *fp = data;
113 #ifdef ENABLE_DEBUG
114         char buf[16];
115         const char *priname;
116         switch (priority) {
117         case LOG_EMERG:
118                 priname = "EMERGENCY";
119                 break;
120         case LOG_ALERT:
121                 priname = "ALERT";
122                 break;
123         case LOG_CRIT:
124                 priname = "CRITICAL";
125                 break;
126         case LOG_ERR:
127                 priname = "ERROR";
128                 break;
129         case LOG_WARNING:
130                 priname = "WARNING";
131                 break;
132         case LOG_NOTICE:
133                 priname = "NOTICE";
134                 break;
135         case LOG_INFO:
136                 priname = "INFO";
137                 break;
138         case LOG_DEBUG:
139                 priname = "DEBUG";
140                 break;
141         default:
142                 snprintf(buf, sizeof(buf), "L:%d", priority);
143                 priname = buf;
144         }
145         fprintf(fp, "libkmod: %s %s:%d %s: ", priname, file, line, fn);
146 #else
147         fprintf(fp, "libkmod: %s: ", fn);
148 #endif
149         vfprintf(fp, format, args);
150 }
151
152
153 /**
154  * kmod_get_dirname:
155  * @ctx: kmod library context
156  *
157  * Retrieve the absolute path used for linux modules in this context. The path
158  * is computed from the arguments to kmod_new().
159  */
160 KMOD_EXPORT const char *kmod_get_dirname(const struct kmod_ctx *ctx)
161 {
162         return ctx->dirname;
163 }
164
165 /**
166  * kmod_get_userdata:
167  * @ctx: kmod library context
168  *
169  * Retrieve stored data pointer from library context. This might be useful
170  * to access from callbacks.
171  *
172  * Returns: stored userdata
173  */
174 KMOD_EXPORT void *kmod_get_userdata(const struct kmod_ctx *ctx)
175 {
176         if (ctx == NULL)
177                 return NULL;
178         return (void *)ctx->userdata;
179 }
180
181 /**
182  * kmod_set_userdata:
183  * @ctx: kmod library context
184  * @userdata: data pointer
185  *
186  * Store custom @userdata in the library context.
187  */
188 KMOD_EXPORT void kmod_set_userdata(struct kmod_ctx *ctx, const void *userdata)
189 {
190         if (ctx == NULL)
191                 return;
192         ctx->userdata = userdata;
193 }
194
195 static int log_priority(const char *priority)
196 {
197         char *endptr;
198         int prio;
199
200         prio = strtol(priority, &endptr, 10);
201         if (endptr[0] == '\0' || isspace(endptr[0]))
202                 return prio;
203         if (strncmp(priority, "err", 3) == 0)
204                 return LOG_ERR;
205         if (strncmp(priority, "info", 4) == 0)
206                 return LOG_INFO;
207         if (strncmp(priority, "debug", 5) == 0)
208                 return LOG_DEBUG;
209         return 0;
210 }
211
212 static const char *dirname_default_prefix = "/lib/modules";
213
214 static char *get_kernel_release(const char *dirname)
215 {
216         struct utsname u;
217         char *p;
218
219         if (dirname != NULL)
220                 return path_make_absolute_cwd(dirname);
221
222         if (uname(&u) < 0)
223                 return NULL;
224
225         if (asprintf(&p, "%s/%s", dirname_default_prefix, u.release) < 0)
226                 return NULL;
227
228         return p;
229 }
230
231 /**
232  * kmod_new:
233  * @dirname: what to consider as linux module's directory, if NULL
234  *           defaults to /lib/modules/`uname -r`. If it's relative,
235  *           it's treated as relative to the current working directory.
236  *           Otherwise, give an absolute dirname.
237  * @config_paths: ordered array of paths (directories or files) where
238  *                to load from user-defined configuration parameters such as
239  *                alias, blacklists, commands (install, remove). If NULL
240  *                defaults to /etc/modprobe.d, /run/modprobe.d,
241  *                /usr/local/lib/modprobe.d and /lib/modprobe.d. Give an empty
242  *                vector if configuration should not be read. This array must
243  *                be null terminated.
244  *
245  * Create kmod library context. This reads the kmod configuration
246  * and fills in the default values.
247  *
248  * The initial refcount is 1, and needs to be decremented to
249  * release the resources of the kmod library context.
250  *
251  * Returns: a new kmod library context
252  */
253 KMOD_EXPORT struct kmod_ctx *kmod_new(const char *dirname,
254                                         const char * const *config_paths)
255 {
256         const char *env;
257         struct kmod_ctx *ctx;
258         int err;
259
260         ctx = calloc(1, sizeof(struct kmod_ctx));
261         if (!ctx)
262                 return NULL;
263
264         ctx->refcount = 1;
265         ctx->log_fn = log_filep;
266         ctx->log_data = stderr;
267         ctx->log_priority = LOG_ERR;
268
269         ctx->dirname = get_kernel_release(dirname);
270
271         /* environment overwrites config */
272         env = secure_getenv("KMOD_LOG");
273         if (env != NULL)
274                 kmod_set_log_priority(ctx, log_priority(env));
275
276         if (config_paths == NULL)
277                 config_paths = default_config_paths;
278         err = kmod_config_new(ctx, &ctx->config, config_paths);
279         if (err < 0) {
280                 ERR(ctx, "could not create config\n");
281                 goto fail;
282         }
283
284         ctx->modules_by_name = hash_new(KMOD_HASH_SIZE, NULL);
285         if (ctx->modules_by_name == NULL) {
286                 ERR(ctx, "could not create by-name hash\n");
287                 goto fail;
288         }
289
290         INFO(ctx, "ctx %p created\n", ctx);
291         DBG(ctx, "log_priority=%d\n", ctx->log_priority);
292
293         return ctx;
294
295 fail:
296         free(ctx->modules_by_name);
297         free(ctx->dirname);
298         free(ctx);
299         return NULL;
300 }
301
302 /**
303  * kmod_ref:
304  * @ctx: kmod library context
305  *
306  * Take a reference of the kmod library context.
307  *
308  * Returns: the passed kmod library context
309  */
310 KMOD_EXPORT struct kmod_ctx *kmod_ref(struct kmod_ctx *ctx)
311 {
312         if (ctx == NULL)
313                 return NULL;
314         ctx->refcount++;
315         return ctx;
316 }
317
318 /**
319  * kmod_unref:
320  * @ctx: kmod library context
321  *
322  * Drop a reference of the kmod library context. If the refcount
323  * reaches zero, the resources of the context will be released.
324  *
325  * Returns: the passed kmod library context or NULL if it's freed
326  */
327 KMOD_EXPORT struct kmod_ctx *kmod_unref(struct kmod_ctx *ctx)
328 {
329         if (ctx == NULL)
330                 return NULL;
331
332         if (--ctx->refcount > 0)
333                 return ctx;
334
335         INFO(ctx, "context %p released\n", ctx);
336
337         kmod_unload_resources(ctx);
338         hash_free(ctx->modules_by_name);
339         free(ctx->dirname);
340         if (ctx->config)
341                 kmod_config_free(ctx->config);
342
343         free(ctx);
344         return NULL;
345 }
346
347 /**
348  * kmod_set_log_fn:
349  * @ctx: kmod library context
350  * @log_fn: function to be called for logging messages
351  * @data: data to pass to log function
352  *
353  * The built-in logging writes to stderr. It can be
354  * overridden by a custom function, to plug log messages
355  * into the user's logging functionality.
356  */
357 KMOD_EXPORT void kmod_set_log_fn(struct kmod_ctx *ctx,
358                                         void (*log_fn)(void *data,
359                                                 int priority, const char *file,
360                                                 int line, const char *fn,
361                                                 const char *format, va_list args),
362                                         const void *data)
363 {
364         if (ctx == NULL)
365                 return;
366         ctx->log_fn = log_fn;
367         ctx->log_data = (void *)data;
368         INFO(ctx, "custom logging function %p registered\n", log_fn);
369 }
370
371 /**
372  * kmod_get_log_priority:
373  * @ctx: kmod library context
374  *
375  * Returns: the current logging priority
376  */
377 KMOD_EXPORT int kmod_get_log_priority(const struct kmod_ctx *ctx)
378 {
379         if (ctx == NULL)
380                 return -1;
381         return ctx->log_priority;
382 }
383
384 /**
385  * kmod_set_log_priority:
386  * @ctx: kmod library context
387  * @priority: the new logging priority
388  *
389  * Set the current logging priority. The value controls which messages
390  * are logged.
391  */
392 KMOD_EXPORT void kmod_set_log_priority(struct kmod_ctx *ctx, int priority)
393 {
394         if (ctx == NULL)
395                 return;
396         ctx->log_priority = priority;
397 }
398
399 struct kmod_module *kmod_pool_get_module(struct kmod_ctx *ctx,
400                                                         const char *key)
401 {
402         struct kmod_module *mod;
403
404         mod = hash_find(ctx->modules_by_name, key);
405
406         DBG(ctx, "get module name='%s' found=%p\n", key, mod);
407
408         return mod;
409 }
410
411 void kmod_pool_add_module(struct kmod_ctx *ctx, struct kmod_module *mod,
412                                                         const char *key)
413 {
414         DBG(ctx, "add %p key='%s'\n", mod, key);
415
416         hash_add(ctx->modules_by_name, key, mod);
417 }
418
419 void kmod_pool_del_module(struct kmod_ctx *ctx, struct kmod_module *mod,
420                                                         const char *key)
421 {
422         DBG(ctx, "del %p key='%s'\n", mod, key);
423
424         hash_del(ctx->modules_by_name, key);
425 }
426
427 static int kmod_lookup_alias_from_alias_bin(struct kmod_ctx *ctx,
428                                                 enum kmod_index index_number,
429                                                 const char *name,
430                                                 struct kmod_list **list)
431 {
432         int err, nmatch = 0;
433         struct index_file *idx;
434         struct index_value *realnames, *realname;
435
436         if (ctx->indexes[index_number] != NULL) {
437                 DBG(ctx, "use mmaped index '%s' for name=%s\n",
438                         index_files[index_number].fn, name);
439                 realnames = index_mm_searchwild(ctx->indexes[index_number],
440                                                                         name);
441         } else {
442                 char fn[PATH_MAX];
443
444                 snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
445                                         index_files[index_number].fn);
446
447                 DBG(ctx, "file=%s name=%s\n", fn, name);
448
449                 idx = index_file_open(fn);
450                 if (idx == NULL)
451                         return -ENOSYS;
452
453                 realnames = index_searchwild(idx, name);
454                 index_file_close(idx);
455         }
456
457         for (realname = realnames; realname; realname = realname->next) {
458                 struct kmod_module *mod;
459
460                 err = kmod_module_new_from_alias(ctx, name, realname->value, &mod);
461                 if (err < 0) {
462                         ERR(ctx, "Could not create module for alias=%s realname=%s: %s\n",
463                             name, realname->value, strerror(-err));
464                         goto fail;
465                 }
466
467                 *list = kmod_list_append(*list, mod);
468                 nmatch++;
469         }
470
471         index_values_free(realnames);
472         return nmatch;
473
474 fail:
475         *list = kmod_list_remove_n_latest(*list, nmatch);
476         index_values_free(realnames);
477         return err;
478
479 }
480
481 int kmod_lookup_alias_from_symbols_file(struct kmod_ctx *ctx, const char *name,
482                                                 struct kmod_list **list)
483 {
484         if (!strstartswith(name, "symbol:"))
485                 return 0;
486
487         return kmod_lookup_alias_from_alias_bin(ctx, KMOD_INDEX_MODULES_SYMBOL,
488                                                                 name, list);
489 }
490
491 int kmod_lookup_alias_from_aliases_file(struct kmod_ctx *ctx, const char *name,
492                                                 struct kmod_list **list)
493 {
494         return kmod_lookup_alias_from_alias_bin(ctx, KMOD_INDEX_MODULES_ALIAS,
495                                                                 name, list);
496 }
497
498 static char *lookup_builtin_file(struct kmod_ctx *ctx, const char *name)
499 {
500         char *line;
501
502         if (ctx->indexes[KMOD_INDEX_MODULES_BUILTIN]) {
503                 DBG(ctx, "use mmaped index '%s' modname=%s\n",
504                                 index_files[KMOD_INDEX_MODULES_BUILTIN].fn,
505                                 name);
506                 line = index_mm_search(ctx->indexes[KMOD_INDEX_MODULES_BUILTIN],
507                                                                         name);
508         } else {
509                 struct index_file *idx;
510                 char fn[PATH_MAX];
511
512                 snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
513                                 index_files[KMOD_INDEX_MODULES_BUILTIN].fn);
514                 DBG(ctx, "file=%s modname=%s\n", fn, name);
515
516                 idx = index_file_open(fn);
517                 if (idx == NULL) {
518                         DBG(ctx, "could not open builtin file '%s'\n", fn);
519                         return NULL;
520                 }
521
522                 line = index_search(idx, name);
523                 index_file_close(idx);
524         }
525
526         return line;
527 }
528
529 int kmod_lookup_alias_from_kernel_builtin_file(struct kmod_ctx *ctx,
530                                                 const char *name,
531                                                 struct kmod_list **list)
532 {
533         struct kmod_list *l;
534         int ret;
535
536         assert(*list == NULL);
537
538         ret = kmod_lookup_alias_from_alias_bin(ctx,
539                                                KMOD_INDEX_MODULES_BUILTIN_ALIAS,
540                                                name, list);
541
542         kmod_list_foreach(l, *list) {
543                 struct kmod_module *mod = l->data;
544                 kmod_module_set_builtin(mod, true);
545         }
546
547         return ret;
548 }
549
550 int kmod_lookup_alias_from_builtin_file(struct kmod_ctx *ctx, const char *name,
551                                                 struct kmod_list **list)
552 {
553         char *line;
554         int err = 0;
555
556         assert(*list == NULL);
557
558         line = lookup_builtin_file(ctx, name);
559         if (line != NULL) {
560                 struct kmod_module *mod;
561
562                 err = kmod_module_new_from_name(ctx, name, &mod);
563                 if (err < 0) {
564                         ERR(ctx, "Could not create module from name %s: %s\n",
565                                                         name, strerror(-err));
566                         goto finish;
567                 }
568
569                 /* already mark it as builtin since it's being created from
570                  * this index */
571                 kmod_module_set_builtin(mod, true);
572                 *list = kmod_list_append(*list, mod);
573                 if (*list == NULL)
574                         err = -ENOMEM;
575         }
576
577 finish:
578         free(line);
579         return err;
580 }
581
582 bool kmod_lookup_alias_is_builtin(struct kmod_ctx *ctx, const char *name)
583 {
584         _cleanup_free_ char *line;
585
586         line = lookup_builtin_file(ctx, name);
587
588         return line != NULL;
589 }
590
591 char *kmod_search_moddep(struct kmod_ctx *ctx, const char *name)
592 {
593         struct index_file *idx;
594         char fn[PATH_MAX];
595         char *line;
596
597         if (ctx->indexes[KMOD_INDEX_MODULES_DEP]) {
598                 DBG(ctx, "use mmaped index '%s' modname=%s\n",
599                                 index_files[KMOD_INDEX_MODULES_DEP].fn, name);
600                 return index_mm_search(ctx->indexes[KMOD_INDEX_MODULES_DEP],
601                                                                         name);
602         }
603
604         snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
605                                         index_files[KMOD_INDEX_MODULES_DEP].fn);
606
607         DBG(ctx, "file=%s modname=%s\n", fn, name);
608
609         idx = index_file_open(fn);
610         if (idx == NULL) {
611                 DBG(ctx, "could not open moddep file '%s'\n", fn);
612                 return NULL;
613         }
614
615         line = index_search(idx, name);
616         index_file_close(idx);
617
618         return line;
619 }
620
621 int kmod_lookup_alias_from_moddep_file(struct kmod_ctx *ctx, const char *name,
622                                                 struct kmod_list **list)
623 {
624         char *line;
625         int n = 0;
626
627         /*
628          * Module names do not contain ':'. Return early if we know it will
629          * not be found.
630          */
631         if (strchr(name, ':'))
632                 return 0;
633
634         line = kmod_search_moddep(ctx, name);
635         if (line != NULL) {
636                 struct kmod_module *mod;
637
638                 n = kmod_module_new_from_name(ctx, name, &mod);
639                 if (n < 0) {
640                         ERR(ctx, "Could not create module from name %s: %s\n",
641                             name, strerror(-n));
642                         goto finish;
643                 }
644
645                 *list = kmod_list_append(*list, mod);
646                 kmod_module_parse_depline(mod, line);
647         }
648
649 finish:
650         free(line);
651
652         return n;
653 }
654
655 int kmod_lookup_alias_from_config(struct kmod_ctx *ctx, const char *name,
656                                                 struct kmod_list **list)
657 {
658         struct kmod_config *config = ctx->config;
659         struct kmod_list *l;
660         int err, nmatch = 0;
661
662         kmod_list_foreach(l, config->aliases) {
663                 const char *aliasname = kmod_alias_get_name(l);
664                 const char *modname = kmod_alias_get_modname(l);
665
666                 if (fnmatch(aliasname, name, 0) == 0) {
667                         struct kmod_module *mod;
668
669                         err = kmod_module_new_from_alias(ctx, aliasname,
670                                                                 modname, &mod);
671                         if (err < 0) {
672                                 ERR(ctx, "Could not create module for alias=%s modname=%s: %s\n",
673                                     name, modname, strerror(-err));
674                                 goto fail;
675                         }
676
677                         *list = kmod_list_append(*list, mod);
678                         nmatch++;
679                 }
680         }
681
682         return nmatch;
683
684 fail:
685         *list = kmod_list_remove_n_latest(*list, nmatch);
686         return err;
687 }
688
689 int kmod_lookup_alias_from_commands(struct kmod_ctx *ctx, const char *name,
690                                                 struct kmod_list **list)
691 {
692         struct kmod_config *config = ctx->config;
693         struct kmod_list *l, *node;
694         int err, nmatch = 0;
695
696         kmod_list_foreach(l, config->install_commands) {
697                 const char *modname = kmod_command_get_modname(l);
698
699                 if (streq(modname, name)) {
700                         const char *cmd = kmod_command_get_command(l);
701                         struct kmod_module *mod;
702
703                         err = kmod_module_new_from_name(ctx, modname, &mod);
704                         if (err < 0) {
705                                 ERR(ctx, "Could not create module from name %s: %s\n",
706                                     modname, strerror(-err));
707                                 return err;
708                         }
709
710                         node = kmod_list_append(*list, mod);
711                         if (node == NULL) {
712                                 ERR(ctx, "out of memory\n");
713                                 return -ENOMEM;
714                         }
715
716                         *list = node;
717                         nmatch = 1;
718
719                         kmod_module_set_install_commands(mod, cmd);
720
721                         /*
722                          * match only the first one, like modprobe from
723                          * module-init-tools does
724                          */
725                         break;
726                 }
727         }
728
729         if (nmatch)
730                 return nmatch;
731
732         kmod_list_foreach(l, config->remove_commands) {
733                 const char *modname = kmod_command_get_modname(l);
734
735                 if (streq(modname, name)) {
736                         const char *cmd = kmod_command_get_command(l);
737                         struct kmod_module *mod;
738
739                         err = kmod_module_new_from_name(ctx, modname, &mod);
740                         if (err < 0) {
741                                 ERR(ctx, "Could not create module from name %s: %s\n",
742                                     modname, strerror(-err));
743                                 return err;
744                         }
745
746                         node = kmod_list_append(*list, mod);
747                         if (node == NULL) {
748                                 ERR(ctx, "out of memory\n");
749                                 return -ENOMEM;
750                         }
751
752                         *list = node;
753                         nmatch = 1;
754
755                         kmod_module_set_remove_commands(mod, cmd);
756
757                         /*
758                          * match only the first one, like modprobe from
759                          * module-init-tools does
760                          */
761                         break;
762                 }
763         }
764
765         return nmatch;
766 }
767
768 void kmod_set_modules_visited(struct kmod_ctx *ctx, bool visited)
769 {
770         struct hash_iter iter;
771         const void *v;
772
773         hash_iter_init(ctx->modules_by_name, &iter);
774         while (hash_iter_next(&iter, NULL, &v))
775                 kmod_module_set_visited((struct kmod_module *)v, visited);
776 }
777
778 void kmod_set_modules_required(struct kmod_ctx *ctx, bool required)
779 {
780         struct hash_iter iter;
781         const void *v;
782
783         hash_iter_init(ctx->modules_by_name, &iter);
784         while (hash_iter_next(&iter, NULL, &v))
785                 kmod_module_set_required((struct kmod_module *)v, required);
786 }
787
788 static bool is_cache_invalid(const char *path, unsigned long long stamp)
789 {
790         struct stat st;
791
792         if (stat(path, &st) < 0)
793                 return true;
794
795         if (stamp != stat_mstamp(&st))
796                 return true;
797
798         return false;
799 }
800
801 /**
802  * kmod_validate_resources:
803  * @ctx: kmod library context
804  *
805  * Check if indexes and configuration files changed on disk and the current
806  * context is not valid anymore.
807  *
808  * Returns: KMOD_RESOURCES_OK if resources are still valid,
809  * KMOD_RESOURCES_MUST_RELOAD if it's sufficient to call
810  * kmod_unload_resources() and kmod_load_resources() or
811  * KMOD_RESOURCES_MUST_RECREATE if @ctx must be re-created.
812  */
813 KMOD_EXPORT int kmod_validate_resources(struct kmod_ctx *ctx)
814 {
815         struct kmod_list *l;
816         size_t i;
817
818         if (ctx == NULL || ctx->config == NULL)
819                 return KMOD_RESOURCES_MUST_RECREATE;
820
821         kmod_list_foreach(l, ctx->config->paths) {
822                 struct kmod_config_path *cf = l->data;
823
824                 if (is_cache_invalid(cf->path, cf->stamp))
825                         return KMOD_RESOURCES_MUST_RECREATE;
826         }
827
828         for (i = 0; i < _KMOD_INDEX_MODULES_SIZE; i++) {
829                 char path[PATH_MAX];
830
831                 if (ctx->indexes[i] == NULL)
832                         continue;
833
834                 snprintf(path, sizeof(path), "%s/%s.bin", ctx->dirname,
835                                                 index_files[i].fn);
836
837                 if (is_cache_invalid(path, ctx->indexes_stamp[i]))
838                         return KMOD_RESOURCES_MUST_RELOAD;
839         }
840
841         return KMOD_RESOURCES_OK;
842 }
843
844 /**
845  * kmod_load_resources:
846  * @ctx: kmod library context
847  *
848  * Load indexes and keep them open in @ctx. This way it's faster to lookup
849  * information within the indexes. If this function is not called before a
850  * search, the necessary index is always opened and closed.
851  *
852  * If user will do more than one or two lookups, insertions, deletions, most
853  * likely it's good to call this function first. Particularly in a daemon like
854  * udev that on bootup issues hundreds of calls to lookup the index, calling
855  * this function will speedup the searches.
856  *
857  * Returns: 0 on success or < 0 otherwise.
858  */
859 KMOD_EXPORT int kmod_load_resources(struct kmod_ctx *ctx)
860 {
861         int ret = 0;
862         size_t i;
863
864         if (ctx == NULL)
865                 return -ENOENT;
866
867         for (i = 0; i < _KMOD_INDEX_MODULES_SIZE; i++) {
868                 char path[PATH_MAX];
869
870                 if (ctx->indexes[i] != NULL) {
871                         INFO(ctx, "Index %s already loaded\n",
872                                                         index_files[i].fn);
873                         continue;
874                 }
875
876                 snprintf(path, sizeof(path), "%s/%s.bin", ctx->dirname,
877                                                         index_files[i].fn);
878                 ret = index_mm_open(ctx, path, &ctx->indexes_stamp[i],
879                                     &ctx->indexes[i]);
880
881                 /*
882                  * modules.builtin.alias are considered optional since it's
883                  * recently added and older installations may not have it;
884                  * we allow failing for any reason
885                  */
886                 if (ret) {
887                         if (i != KMOD_INDEX_MODULES_BUILTIN_ALIAS)
888                                 break;
889                         ret = 0;
890                 }
891         }
892
893         if (ret)
894                 kmod_unload_resources(ctx);
895
896         return ret;
897 }
898
899 /**
900  * kmod_unload_resources:
901  * @ctx: kmod library context
902  *
903  * Unload all the indexes. This will free the resources to maintain the index
904  * open and all subsequent searches will need to open and close the index.
905  *
906  * User is free to call kmod_load_resources() and kmod_unload_resources() as
907  * many times as wanted during the lifecycle of @ctx. For example, if a daemon
908  * knows that when starting up it will lookup a lot of modules, it could call
909  * kmod_load_resources() and after the first burst of searches is gone, it
910  * could free the resources by calling kmod_unload_resources().
911  *
912  * Returns: 0 on success or < 0 otherwise.
913  */
914 KMOD_EXPORT void kmod_unload_resources(struct kmod_ctx *ctx)
915 {
916         size_t i;
917
918         if (ctx == NULL)
919                 return;
920
921         for (i = 0; i < _KMOD_INDEX_MODULES_SIZE; i++) {
922                 if (ctx->indexes[i] != NULL) {
923                         index_mm_close(ctx->indexes[i]);
924                         ctx->indexes[i] = NULL;
925                         ctx->indexes_stamp[i] = 0;
926                 }
927         }
928 }
929
930 /**
931  * kmod_dump_index:
932  * @ctx: kmod library context
933  * @type: index to dump, valid indexes are
934  * KMOD_INDEX_MODULES_DEP: index of module dependencies;
935  * KMOD_INDEX_MODULES_ALIAS: index of module aliases;
936  * KMOD_INDEX_MODULES_SYMBOL: index of symbol aliases;
937  * KMOD_INDEX_MODULES_BUILTIN: index of builtin module.
938  * @fd: file descriptor to dump index to
939  *
940  * Dump index to file descriptor. Note that this function doesn't use stdio.h
941  * so call fflush() before calling this function to be sure data is written in
942  * order.
943  *
944  * Returns: 0 on success or < 0 otherwise.
945  */
946 KMOD_EXPORT int kmod_dump_index(struct kmod_ctx *ctx, enum kmod_index type,
947                                                                         int fd)
948 {
949         if (ctx == NULL)
950                 return -ENOSYS;
951
952         if (type < 0 || type >= _KMOD_INDEX_MODULES_SIZE)
953                 return -ENOENT;
954
955         if (ctx->indexes[type] != NULL) {
956                 DBG(ctx, "use mmaped index '%s'\n", index_files[type].fn);
957                 index_mm_dump(ctx->indexes[type], fd,
958                                                 index_files[type].prefix);
959         } else {
960                 char fn[PATH_MAX];
961                 struct index_file *idx;
962
963                 snprintf(fn, sizeof(fn), "%s/%s.bin", ctx->dirname,
964                                                 index_files[type].fn);
965
966                 DBG(ctx, "file=%s\n", fn);
967
968                 idx = index_file_open(fn);
969                 if (idx == NULL)
970                         return -ENOSYS;
971
972                 index_dump(idx, fd, index_files[type].prefix);
973                 index_file_close(idx);
974         }
975
976         return 0;
977 }
978
979 const struct kmod_config *kmod_get_config(const struct kmod_ctx *ctx)
980 {
981         return ctx->config;
982 }