xref: /linux/kernel/module/main.c (revision eda40be3a5ff3fdce513d2bcfeaca8cc16cf962a)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (C) 2002 Richard Henderson
4  * Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM.
5  * Copyright (C) 2023 Luis Chamberlain <mcgrof@kernel.org>
6  */
7 
8 #define INCLUDE_VERMAGIC
9 
10 #include <linux/export.h>
11 #include <linux/extable.h>
12 #include <linux/moduleloader.h>
13 #include <linux/module_signature.h>
14 #include <linux/trace_events.h>
15 #include <linux/init.h>
16 #include <linux/kallsyms.h>
17 #include <linux/buildid.h>
18 #include <linux/fs.h>
19 #include <linux/kernel.h>
20 #include <linux/kernel_read_file.h>
21 #include <linux/kstrtox.h>
22 #include <linux/slab.h>
23 #include <linux/vmalloc.h>
24 #include <linux/elf.h>
25 #include <linux/seq_file.h>
26 #include <linux/syscalls.h>
27 #include <linux/fcntl.h>
28 #include <linux/rcupdate.h>
29 #include <linux/capability.h>
30 #include <linux/cpu.h>
31 #include <linux/moduleparam.h>
32 #include <linux/errno.h>
33 #include <linux/err.h>
34 #include <linux/vermagic.h>
35 #include <linux/notifier.h>
36 #include <linux/sched.h>
37 #include <linux/device.h>
38 #include <linux/string.h>
39 #include <linux/mutex.h>
40 #include <linux/rculist.h>
41 #include <linux/uaccess.h>
42 #include <asm/cacheflush.h>
43 #include <linux/set_memory.h>
44 #include <asm/mmu_context.h>
45 #include <linux/license.h>
46 #include <asm/sections.h>
47 #include <linux/tracepoint.h>
48 #include <linux/ftrace.h>
49 #include <linux/livepatch.h>
50 #include <linux/async.h>
51 #include <linux/percpu.h>
52 #include <linux/kmemleak.h>
53 #include <linux/jump_label.h>
54 #include <linux/pfn.h>
55 #include <linux/bsearch.h>
56 #include <linux/dynamic_debug.h>
57 #include <linux/audit.h>
58 #include <linux/cfi.h>
59 #include <linux/debugfs.h>
60 #include <linux/execmem.h>
61 #include <uapi/linux/module.h>
62 #include "internal.h"
63 
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/module.h>
66 
67 /*
68  * Mutex protects:
69  * 1) List of modules (also safely readable with preempt_disable),
70  * 2) module_use links,
71  * 3) mod_tree.addr_min/mod_tree.addr_max.
72  * (delete and add uses RCU list operations).
73  */
74 DEFINE_MUTEX(module_mutex);
75 LIST_HEAD(modules);
76 
77 /* Work queue for freeing init sections in success case */
78 static void do_free_init(struct work_struct *w);
79 static DECLARE_WORK(init_free_wq, do_free_init);
80 static LLIST_HEAD(init_free_list);
81 
82 struct mod_tree_root mod_tree __cacheline_aligned = {
83 	.addr_min = -1UL,
84 };
85 
86 struct symsearch {
87 	const struct kernel_symbol *start, *stop;
88 	const s32 *crcs;
89 	enum mod_license license;
90 };
91 
92 /*
93  * Bounds of module memory, for speeding up __module_address.
94  * Protected by module_mutex.
95  */
96 static void __mod_update_bounds(enum mod_mem_type type __maybe_unused, void *base,
97 				unsigned int size, struct mod_tree_root *tree)
98 {
99 	unsigned long min = (unsigned long)base;
100 	unsigned long max = min + size;
101 
102 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
103 	if (mod_mem_type_is_core_data(type)) {
104 		if (min < tree->data_addr_min)
105 			tree->data_addr_min = min;
106 		if (max > tree->data_addr_max)
107 			tree->data_addr_max = max;
108 		return;
109 	}
110 #endif
111 	if (min < tree->addr_min)
112 		tree->addr_min = min;
113 	if (max > tree->addr_max)
114 		tree->addr_max = max;
115 }
116 
117 static void mod_update_bounds(struct module *mod)
118 {
119 	for_each_mod_mem_type(type) {
120 		struct module_memory *mod_mem = &mod->mem[type];
121 
122 		if (mod_mem->size)
123 			__mod_update_bounds(type, mod_mem->base, mod_mem->size, &mod_tree);
124 	}
125 }
126 
127 /* Block module loading/unloading? */
128 int modules_disabled;
129 core_param(nomodule, modules_disabled, bint, 0);
130 
131 /* Waiting for a module to finish initializing? */
132 static DECLARE_WAIT_QUEUE_HEAD(module_wq);
133 
134 static BLOCKING_NOTIFIER_HEAD(module_notify_list);
135 
136 int register_module_notifier(struct notifier_block *nb)
137 {
138 	return blocking_notifier_chain_register(&module_notify_list, nb);
139 }
140 EXPORT_SYMBOL(register_module_notifier);
141 
142 int unregister_module_notifier(struct notifier_block *nb)
143 {
144 	return blocking_notifier_chain_unregister(&module_notify_list, nb);
145 }
146 EXPORT_SYMBOL(unregister_module_notifier);
147 
148 /*
149  * We require a truly strong try_module_get(): 0 means success.
150  * Otherwise an error is returned due to ongoing or failed
151  * initialization etc.
152  */
153 static inline int strong_try_module_get(struct module *mod)
154 {
155 	BUG_ON(mod && mod->state == MODULE_STATE_UNFORMED);
156 	if (mod && mod->state == MODULE_STATE_COMING)
157 		return -EBUSY;
158 	if (try_module_get(mod))
159 		return 0;
160 	else
161 		return -ENOENT;
162 }
163 
164 static inline void add_taint_module(struct module *mod, unsigned flag,
165 				    enum lockdep_ok lockdep_ok)
166 {
167 	add_taint(flag, lockdep_ok);
168 	set_bit(flag, &mod->taints);
169 }
170 
171 /*
172  * A thread that wants to hold a reference to a module only while it
173  * is running can call this to safely exit.
174  */
175 void __noreturn __module_put_and_kthread_exit(struct module *mod, long code)
176 {
177 	module_put(mod);
178 	kthread_exit(code);
179 }
180 EXPORT_SYMBOL(__module_put_and_kthread_exit);
181 
182 /* Find a module section: 0 means not found. */
183 static unsigned int find_sec(const struct load_info *info, const char *name)
184 {
185 	unsigned int i;
186 
187 	for (i = 1; i < info->hdr->e_shnum; i++) {
188 		Elf_Shdr *shdr = &info->sechdrs[i];
189 		/* Alloc bit cleared means "ignore it." */
190 		if ((shdr->sh_flags & SHF_ALLOC)
191 		    && strcmp(info->secstrings + shdr->sh_name, name) == 0)
192 			return i;
193 	}
194 	return 0;
195 }
196 
197 /* Find a module section, or NULL. */
198 static void *section_addr(const struct load_info *info, const char *name)
199 {
200 	/* Section 0 has sh_addr 0. */
201 	return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
202 }
203 
204 /* Find a module section, or NULL.  Fill in number of "objects" in section. */
205 static void *section_objs(const struct load_info *info,
206 			  const char *name,
207 			  size_t object_size,
208 			  unsigned int *num)
209 {
210 	unsigned int sec = find_sec(info, name);
211 
212 	/* Section 0 has sh_addr 0 and sh_size 0. */
213 	*num = info->sechdrs[sec].sh_size / object_size;
214 	return (void *)info->sechdrs[sec].sh_addr;
215 }
216 
217 /* Find a module section: 0 means not found. Ignores SHF_ALLOC flag. */
218 static unsigned int find_any_sec(const struct load_info *info, const char *name)
219 {
220 	unsigned int i;
221 
222 	for (i = 1; i < info->hdr->e_shnum; i++) {
223 		Elf_Shdr *shdr = &info->sechdrs[i];
224 		if (strcmp(info->secstrings + shdr->sh_name, name) == 0)
225 			return i;
226 	}
227 	return 0;
228 }
229 
230 /*
231  * Find a module section, or NULL. Fill in number of "objects" in section.
232  * Ignores SHF_ALLOC flag.
233  */
234 static __maybe_unused void *any_section_objs(const struct load_info *info,
235 					     const char *name,
236 					     size_t object_size,
237 					     unsigned int *num)
238 {
239 	unsigned int sec = find_any_sec(info, name);
240 
241 	/* Section 0 has sh_addr 0 and sh_size 0. */
242 	*num = info->sechdrs[sec].sh_size / object_size;
243 	return (void *)info->sechdrs[sec].sh_addr;
244 }
245 
246 #ifndef CONFIG_MODVERSIONS
247 #define symversion(base, idx) NULL
248 #else
249 #define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
250 #endif
251 
252 static const char *kernel_symbol_name(const struct kernel_symbol *sym)
253 {
254 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
255 	return offset_to_ptr(&sym->name_offset);
256 #else
257 	return sym->name;
258 #endif
259 }
260 
261 static const char *kernel_symbol_namespace(const struct kernel_symbol *sym)
262 {
263 #ifdef CONFIG_HAVE_ARCH_PREL32_RELOCATIONS
264 	if (!sym->namespace_offset)
265 		return NULL;
266 	return offset_to_ptr(&sym->namespace_offset);
267 #else
268 	return sym->namespace;
269 #endif
270 }
271 
272 int cmp_name(const void *name, const void *sym)
273 {
274 	return strcmp(name, kernel_symbol_name(sym));
275 }
276 
277 static bool find_exported_symbol_in_section(const struct symsearch *syms,
278 					    struct module *owner,
279 					    struct find_symbol_arg *fsa)
280 {
281 	struct kernel_symbol *sym;
282 
283 	if (!fsa->gplok && syms->license == GPL_ONLY)
284 		return false;
285 
286 	sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,
287 			sizeof(struct kernel_symbol), cmp_name);
288 	if (!sym)
289 		return false;
290 
291 	fsa->owner = owner;
292 	fsa->crc = symversion(syms->crcs, sym - syms->start);
293 	fsa->sym = sym;
294 	fsa->license = syms->license;
295 
296 	return true;
297 }
298 
299 /*
300  * Find an exported symbol and return it, along with, (optional) crc and
301  * (optional) module which owns it.  Needs preempt disabled or module_mutex.
302  */
303 bool find_symbol(struct find_symbol_arg *fsa)
304 {
305 	static const struct symsearch arr[] = {
306 		{ __start___ksymtab, __stop___ksymtab, __start___kcrctab,
307 		  NOT_GPL_ONLY },
308 		{ __start___ksymtab_gpl, __stop___ksymtab_gpl,
309 		  __start___kcrctab_gpl,
310 		  GPL_ONLY },
311 	};
312 	struct module *mod;
313 	unsigned int i;
314 
315 	module_assert_mutex_or_preempt();
316 
317 	for (i = 0; i < ARRAY_SIZE(arr); i++)
318 		if (find_exported_symbol_in_section(&arr[i], NULL, fsa))
319 			return true;
320 
321 	list_for_each_entry_rcu(mod, &modules, list,
322 				lockdep_is_held(&module_mutex)) {
323 		struct symsearch arr[] = {
324 			{ mod->syms, mod->syms + mod->num_syms, mod->crcs,
325 			  NOT_GPL_ONLY },
326 			{ mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
327 			  mod->gpl_crcs,
328 			  GPL_ONLY },
329 		};
330 
331 		if (mod->state == MODULE_STATE_UNFORMED)
332 			continue;
333 
334 		for (i = 0; i < ARRAY_SIZE(arr); i++)
335 			if (find_exported_symbol_in_section(&arr[i], mod, fsa))
336 				return true;
337 	}
338 
339 	pr_debug("Failed to find symbol %s\n", fsa->name);
340 	return false;
341 }
342 
343 /*
344  * Search for module by name: must hold module_mutex (or preempt disabled
345  * for read-only access).
346  */
347 struct module *find_module_all(const char *name, size_t len,
348 			       bool even_unformed)
349 {
350 	struct module *mod;
351 
352 	module_assert_mutex_or_preempt();
353 
354 	list_for_each_entry_rcu(mod, &modules, list,
355 				lockdep_is_held(&module_mutex)) {
356 		if (!even_unformed && mod->state == MODULE_STATE_UNFORMED)
357 			continue;
358 		if (strlen(mod->name) == len && !memcmp(mod->name, name, len))
359 			return mod;
360 	}
361 	return NULL;
362 }
363 
364 struct module *find_module(const char *name)
365 {
366 	return find_module_all(name, strlen(name), false);
367 }
368 
369 #ifdef CONFIG_SMP
370 
371 static inline void __percpu *mod_percpu(struct module *mod)
372 {
373 	return mod->percpu;
374 }
375 
376 static int percpu_modalloc(struct module *mod, struct load_info *info)
377 {
378 	Elf_Shdr *pcpusec = &info->sechdrs[info->index.pcpu];
379 	unsigned long align = pcpusec->sh_addralign;
380 
381 	if (!pcpusec->sh_size)
382 		return 0;
383 
384 	if (align > PAGE_SIZE) {
385 		pr_warn("%s: per-cpu alignment %li > %li\n",
386 			mod->name, align, PAGE_SIZE);
387 		align = PAGE_SIZE;
388 	}
389 
390 	mod->percpu = __alloc_reserved_percpu(pcpusec->sh_size, align);
391 	if (!mod->percpu) {
392 		pr_warn("%s: Could not allocate %lu bytes percpu data\n",
393 			mod->name, (unsigned long)pcpusec->sh_size);
394 		return -ENOMEM;
395 	}
396 	mod->percpu_size = pcpusec->sh_size;
397 	return 0;
398 }
399 
400 static void percpu_modfree(struct module *mod)
401 {
402 	free_percpu(mod->percpu);
403 }
404 
405 static unsigned int find_pcpusec(struct load_info *info)
406 {
407 	return find_sec(info, ".data..percpu");
408 }
409 
410 static void percpu_modcopy(struct module *mod,
411 			   const void *from, unsigned long size)
412 {
413 	int cpu;
414 
415 	for_each_possible_cpu(cpu)
416 		memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
417 }
418 
419 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
420 {
421 	struct module *mod;
422 	unsigned int cpu;
423 
424 	preempt_disable();
425 
426 	list_for_each_entry_rcu(mod, &modules, list) {
427 		if (mod->state == MODULE_STATE_UNFORMED)
428 			continue;
429 		if (!mod->percpu_size)
430 			continue;
431 		for_each_possible_cpu(cpu) {
432 			void *start = per_cpu_ptr(mod->percpu, cpu);
433 			void *va = (void *)addr;
434 
435 			if (va >= start && va < start + mod->percpu_size) {
436 				if (can_addr) {
437 					*can_addr = (unsigned long) (va - start);
438 					*can_addr += (unsigned long)
439 						per_cpu_ptr(mod->percpu,
440 							    get_boot_cpu_id());
441 				}
442 				preempt_enable();
443 				return true;
444 			}
445 		}
446 	}
447 
448 	preempt_enable();
449 	return false;
450 }
451 
452 /**
453  * is_module_percpu_address() - test whether address is from module static percpu
454  * @addr: address to test
455  *
456  * Test whether @addr belongs to module static percpu area.
457  *
458  * Return: %true if @addr is from module static percpu area
459  */
460 bool is_module_percpu_address(unsigned long addr)
461 {
462 	return __is_module_percpu_address(addr, NULL);
463 }
464 
465 #else /* ... !CONFIG_SMP */
466 
467 static inline void __percpu *mod_percpu(struct module *mod)
468 {
469 	return NULL;
470 }
471 static int percpu_modalloc(struct module *mod, struct load_info *info)
472 {
473 	/* UP modules shouldn't have this section: ENOMEM isn't quite right */
474 	if (info->sechdrs[info->index.pcpu].sh_size != 0)
475 		return -ENOMEM;
476 	return 0;
477 }
478 static inline void percpu_modfree(struct module *mod)
479 {
480 }
481 static unsigned int find_pcpusec(struct load_info *info)
482 {
483 	return 0;
484 }
485 static inline void percpu_modcopy(struct module *mod,
486 				  const void *from, unsigned long size)
487 {
488 	/* pcpusec should be 0, and size of that section should be 0. */
489 	BUG_ON(size != 0);
490 }
491 bool is_module_percpu_address(unsigned long addr)
492 {
493 	return false;
494 }
495 
496 bool __is_module_percpu_address(unsigned long addr, unsigned long *can_addr)
497 {
498 	return false;
499 }
500 
501 #endif /* CONFIG_SMP */
502 
503 #define MODINFO_ATTR(field)	\
504 static void setup_modinfo_##field(struct module *mod, const char *s)  \
505 {                                                                     \
506 	mod->field = kstrdup(s, GFP_KERNEL);                          \
507 }                                                                     \
508 static ssize_t show_modinfo_##field(struct module_attribute *mattr,   \
509 			struct module_kobject *mk, char *buffer)      \
510 {                                                                     \
511 	return scnprintf(buffer, PAGE_SIZE, "%s\n", mk->mod->field);  \
512 }                                                                     \
513 static int modinfo_##field##_exists(struct module *mod)               \
514 {                                                                     \
515 	return mod->field != NULL;                                    \
516 }                                                                     \
517 static void free_modinfo_##field(struct module *mod)                  \
518 {                                                                     \
519 	kfree(mod->field);                                            \
520 	mod->field = NULL;                                            \
521 }                                                                     \
522 static struct module_attribute modinfo_##field = {                    \
523 	.attr = { .name = __stringify(field), .mode = 0444 },         \
524 	.show = show_modinfo_##field,                                 \
525 	.setup = setup_modinfo_##field,                               \
526 	.test = modinfo_##field##_exists,                             \
527 	.free = free_modinfo_##field,                                 \
528 };
529 
530 MODINFO_ATTR(version);
531 MODINFO_ATTR(srcversion);
532 
533 static struct {
534 	char name[MODULE_NAME_LEN + 1];
535 	char taints[MODULE_FLAGS_BUF_SIZE];
536 } last_unloaded_module;
537 
538 #ifdef CONFIG_MODULE_UNLOAD
539 
540 EXPORT_TRACEPOINT_SYMBOL(module_get);
541 
542 /* MODULE_REF_BASE is the base reference count by kmodule loader. */
543 #define MODULE_REF_BASE	1
544 
545 /* Init the unload section of the module. */
546 static int module_unload_init(struct module *mod)
547 {
548 	/*
549 	 * Initialize reference counter to MODULE_REF_BASE.
550 	 * refcnt == 0 means module is going.
551 	 */
552 	atomic_set(&mod->refcnt, MODULE_REF_BASE);
553 
554 	INIT_LIST_HEAD(&mod->source_list);
555 	INIT_LIST_HEAD(&mod->target_list);
556 
557 	/* Hold reference count during initialization. */
558 	atomic_inc(&mod->refcnt);
559 
560 	return 0;
561 }
562 
563 /* Does a already use b? */
564 static int already_uses(struct module *a, struct module *b)
565 {
566 	struct module_use *use;
567 
568 	list_for_each_entry(use, &b->source_list, source_list) {
569 		if (use->source == a)
570 			return 1;
571 	}
572 	pr_debug("%s does not use %s!\n", a->name, b->name);
573 	return 0;
574 }
575 
576 /*
577  * Module a uses b
578  *  - we add 'a' as a "source", 'b' as a "target" of module use
579  *  - the module_use is added to the list of 'b' sources (so
580  *    'b' can walk the list to see who sourced them), and of 'a'
581  *    targets (so 'a' can see what modules it targets).
582  */
583 static int add_module_usage(struct module *a, struct module *b)
584 {
585 	struct module_use *use;
586 
587 	pr_debug("Allocating new usage for %s.\n", a->name);
588 	use = kmalloc(sizeof(*use), GFP_ATOMIC);
589 	if (!use)
590 		return -ENOMEM;
591 
592 	use->source = a;
593 	use->target = b;
594 	list_add(&use->source_list, &b->source_list);
595 	list_add(&use->target_list, &a->target_list);
596 	return 0;
597 }
598 
599 /* Module a uses b: caller needs module_mutex() */
600 static int ref_module(struct module *a, struct module *b)
601 {
602 	int err;
603 
604 	if (b == NULL || already_uses(a, b))
605 		return 0;
606 
607 	/* If module isn't available, we fail. */
608 	err = strong_try_module_get(b);
609 	if (err)
610 		return err;
611 
612 	err = add_module_usage(a, b);
613 	if (err) {
614 		module_put(b);
615 		return err;
616 	}
617 	return 0;
618 }
619 
620 /* Clear the unload stuff of the module. */
621 static void module_unload_free(struct module *mod)
622 {
623 	struct module_use *use, *tmp;
624 
625 	mutex_lock(&module_mutex);
626 	list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
627 		struct module *i = use->target;
628 		pr_debug("%s unusing %s\n", mod->name, i->name);
629 		module_put(i);
630 		list_del(&use->source_list);
631 		list_del(&use->target_list);
632 		kfree(use);
633 	}
634 	mutex_unlock(&module_mutex);
635 }
636 
637 #ifdef CONFIG_MODULE_FORCE_UNLOAD
638 static inline int try_force_unload(unsigned int flags)
639 {
640 	int ret = (flags & O_TRUNC);
641 	if (ret)
642 		add_taint(TAINT_FORCED_RMMOD, LOCKDEP_NOW_UNRELIABLE);
643 	return ret;
644 }
645 #else
646 static inline int try_force_unload(unsigned int flags)
647 {
648 	return 0;
649 }
650 #endif /* CONFIG_MODULE_FORCE_UNLOAD */
651 
652 /* Try to release refcount of module, 0 means success. */
653 static int try_release_module_ref(struct module *mod)
654 {
655 	int ret;
656 
657 	/* Try to decrement refcnt which we set at loading */
658 	ret = atomic_sub_return(MODULE_REF_BASE, &mod->refcnt);
659 	BUG_ON(ret < 0);
660 	if (ret)
661 		/* Someone can put this right now, recover with checking */
662 		ret = atomic_add_unless(&mod->refcnt, MODULE_REF_BASE, 0);
663 
664 	return ret;
665 }
666 
667 static int try_stop_module(struct module *mod, int flags, int *forced)
668 {
669 	/* If it's not unused, quit unless we're forcing. */
670 	if (try_release_module_ref(mod) != 0) {
671 		*forced = try_force_unload(flags);
672 		if (!(*forced))
673 			return -EWOULDBLOCK;
674 	}
675 
676 	/* Mark it as dying. */
677 	mod->state = MODULE_STATE_GOING;
678 
679 	return 0;
680 }
681 
682 /**
683  * module_refcount() - return the refcount or -1 if unloading
684  * @mod:	the module we're checking
685  *
686  * Return:
687  *	-1 if the module is in the process of unloading
688  *	otherwise the number of references in the kernel to the module
689  */
690 int module_refcount(struct module *mod)
691 {
692 	return atomic_read(&mod->refcnt) - MODULE_REF_BASE;
693 }
694 EXPORT_SYMBOL(module_refcount);
695 
696 /* This exists whether we can unload or not */
697 static void free_module(struct module *mod);
698 
699 SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
700 		unsigned int, flags)
701 {
702 	struct module *mod;
703 	char name[MODULE_NAME_LEN];
704 	char buf[MODULE_FLAGS_BUF_SIZE];
705 	int ret, forced = 0;
706 
707 	if (!capable(CAP_SYS_MODULE) || modules_disabled)
708 		return -EPERM;
709 
710 	if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
711 		return -EFAULT;
712 	name[MODULE_NAME_LEN-1] = '\0';
713 
714 	audit_log_kern_module(name);
715 
716 	if (mutex_lock_interruptible(&module_mutex) != 0)
717 		return -EINTR;
718 
719 	mod = find_module(name);
720 	if (!mod) {
721 		ret = -ENOENT;
722 		goto out;
723 	}
724 
725 	if (!list_empty(&mod->source_list)) {
726 		/* Other modules depend on us: get rid of them first. */
727 		ret = -EWOULDBLOCK;
728 		goto out;
729 	}
730 
731 	/* Doing init or already dying? */
732 	if (mod->state != MODULE_STATE_LIVE) {
733 		/* FIXME: if (force), slam module count damn the torpedoes */
734 		pr_debug("%s already dying\n", mod->name);
735 		ret = -EBUSY;
736 		goto out;
737 	}
738 
739 	/* If it has an init func, it must have an exit func to unload */
740 	if (mod->init && !mod->exit) {
741 		forced = try_force_unload(flags);
742 		if (!forced) {
743 			/* This module can't be removed */
744 			ret = -EBUSY;
745 			goto out;
746 		}
747 	}
748 
749 	ret = try_stop_module(mod, flags, &forced);
750 	if (ret != 0)
751 		goto out;
752 
753 	mutex_unlock(&module_mutex);
754 	/* Final destruction now no one is using it. */
755 	if (mod->exit != NULL)
756 		mod->exit();
757 	blocking_notifier_call_chain(&module_notify_list,
758 				     MODULE_STATE_GOING, mod);
759 	klp_module_going(mod);
760 	ftrace_release_mod(mod);
761 
762 	async_synchronize_full();
763 
764 	/* Store the name and taints of the last unloaded module for diagnostic purposes */
765 	strscpy(last_unloaded_module.name, mod->name, sizeof(last_unloaded_module.name));
766 	strscpy(last_unloaded_module.taints, module_flags(mod, buf, false), sizeof(last_unloaded_module.taints));
767 
768 	free_module(mod);
769 	/* someone could wait for the module in add_unformed_module() */
770 	wake_up_all(&module_wq);
771 	return 0;
772 out:
773 	mutex_unlock(&module_mutex);
774 	return ret;
775 }
776 
777 void __symbol_put(const char *symbol)
778 {
779 	struct find_symbol_arg fsa = {
780 		.name	= symbol,
781 		.gplok	= true,
782 	};
783 
784 	preempt_disable();
785 	BUG_ON(!find_symbol(&fsa));
786 	module_put(fsa.owner);
787 	preempt_enable();
788 }
789 EXPORT_SYMBOL(__symbol_put);
790 
791 /* Note this assumes addr is a function, which it currently always is. */
792 void symbol_put_addr(void *addr)
793 {
794 	struct module *modaddr;
795 	unsigned long a = (unsigned long)dereference_function_descriptor(addr);
796 
797 	if (core_kernel_text(a))
798 		return;
799 
800 	/*
801 	 * Even though we hold a reference on the module; we still need to
802 	 * disable preemption in order to safely traverse the data structure.
803 	 */
804 	preempt_disable();
805 	modaddr = __module_text_address(a);
806 	BUG_ON(!modaddr);
807 	module_put(modaddr);
808 	preempt_enable();
809 }
810 EXPORT_SYMBOL_GPL(symbol_put_addr);
811 
812 static ssize_t show_refcnt(struct module_attribute *mattr,
813 			   struct module_kobject *mk, char *buffer)
814 {
815 	return sprintf(buffer, "%i\n", module_refcount(mk->mod));
816 }
817 
818 static struct module_attribute modinfo_refcnt =
819 	__ATTR(refcnt, 0444, show_refcnt, NULL);
820 
821 void __module_get(struct module *module)
822 {
823 	if (module) {
824 		atomic_inc(&module->refcnt);
825 		trace_module_get(module, _RET_IP_);
826 	}
827 }
828 EXPORT_SYMBOL(__module_get);
829 
830 bool try_module_get(struct module *module)
831 {
832 	bool ret = true;
833 
834 	if (module) {
835 		/* Note: here, we can fail to get a reference */
836 		if (likely(module_is_live(module) &&
837 			   atomic_inc_not_zero(&module->refcnt) != 0))
838 			trace_module_get(module, _RET_IP_);
839 		else
840 			ret = false;
841 	}
842 	return ret;
843 }
844 EXPORT_SYMBOL(try_module_get);
845 
846 void module_put(struct module *module)
847 {
848 	int ret;
849 
850 	if (module) {
851 		ret = atomic_dec_if_positive(&module->refcnt);
852 		WARN_ON(ret < 0);	/* Failed to put refcount */
853 		trace_module_put(module, _RET_IP_);
854 	}
855 }
856 EXPORT_SYMBOL(module_put);
857 
858 #else /* !CONFIG_MODULE_UNLOAD */
859 static inline void module_unload_free(struct module *mod)
860 {
861 }
862 
863 static int ref_module(struct module *a, struct module *b)
864 {
865 	return strong_try_module_get(b);
866 }
867 
868 static inline int module_unload_init(struct module *mod)
869 {
870 	return 0;
871 }
872 #endif /* CONFIG_MODULE_UNLOAD */
873 
874 size_t module_flags_taint(unsigned long taints, char *buf)
875 {
876 	size_t l = 0;
877 	int i;
878 
879 	for (i = 0; i < TAINT_FLAGS_COUNT; i++) {
880 		if (taint_flags[i].module && test_bit(i, &taints))
881 			buf[l++] = taint_flags[i].c_true;
882 	}
883 
884 	return l;
885 }
886 
887 static ssize_t show_initstate(struct module_attribute *mattr,
888 			      struct module_kobject *mk, char *buffer)
889 {
890 	const char *state = "unknown";
891 
892 	switch (mk->mod->state) {
893 	case MODULE_STATE_LIVE:
894 		state = "live";
895 		break;
896 	case MODULE_STATE_COMING:
897 		state = "coming";
898 		break;
899 	case MODULE_STATE_GOING:
900 		state = "going";
901 		break;
902 	default:
903 		BUG();
904 	}
905 	return sprintf(buffer, "%s\n", state);
906 }
907 
908 static struct module_attribute modinfo_initstate =
909 	__ATTR(initstate, 0444, show_initstate, NULL);
910 
911 static ssize_t store_uevent(struct module_attribute *mattr,
912 			    struct module_kobject *mk,
913 			    const char *buffer, size_t count)
914 {
915 	int rc;
916 
917 	rc = kobject_synth_uevent(&mk->kobj, buffer, count);
918 	return rc ? rc : count;
919 }
920 
921 struct module_attribute module_uevent =
922 	__ATTR(uevent, 0200, NULL, store_uevent);
923 
924 static ssize_t show_coresize(struct module_attribute *mattr,
925 			     struct module_kobject *mk, char *buffer)
926 {
927 	unsigned int size = mk->mod->mem[MOD_TEXT].size;
928 
929 	if (!IS_ENABLED(CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC)) {
930 		for_class_mod_mem_type(type, core_data)
931 			size += mk->mod->mem[type].size;
932 	}
933 	return sprintf(buffer, "%u\n", size);
934 }
935 
936 static struct module_attribute modinfo_coresize =
937 	__ATTR(coresize, 0444, show_coresize, NULL);
938 
939 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
940 static ssize_t show_datasize(struct module_attribute *mattr,
941 			     struct module_kobject *mk, char *buffer)
942 {
943 	unsigned int size = 0;
944 
945 	for_class_mod_mem_type(type, core_data)
946 		size += mk->mod->mem[type].size;
947 	return sprintf(buffer, "%u\n", size);
948 }
949 
950 static struct module_attribute modinfo_datasize =
951 	__ATTR(datasize, 0444, show_datasize, NULL);
952 #endif
953 
954 static ssize_t show_initsize(struct module_attribute *mattr,
955 			     struct module_kobject *mk, char *buffer)
956 {
957 	unsigned int size = 0;
958 
959 	for_class_mod_mem_type(type, init)
960 		size += mk->mod->mem[type].size;
961 	return sprintf(buffer, "%u\n", size);
962 }
963 
964 static struct module_attribute modinfo_initsize =
965 	__ATTR(initsize, 0444, show_initsize, NULL);
966 
967 static ssize_t show_taint(struct module_attribute *mattr,
968 			  struct module_kobject *mk, char *buffer)
969 {
970 	size_t l;
971 
972 	l = module_flags_taint(mk->mod->taints, buffer);
973 	buffer[l++] = '\n';
974 	return l;
975 }
976 
977 static struct module_attribute modinfo_taint =
978 	__ATTR(taint, 0444, show_taint, NULL);
979 
980 struct module_attribute *modinfo_attrs[] = {
981 	&module_uevent,
982 	&modinfo_version,
983 	&modinfo_srcversion,
984 	&modinfo_initstate,
985 	&modinfo_coresize,
986 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
987 	&modinfo_datasize,
988 #endif
989 	&modinfo_initsize,
990 	&modinfo_taint,
991 #ifdef CONFIG_MODULE_UNLOAD
992 	&modinfo_refcnt,
993 #endif
994 	NULL,
995 };
996 
997 size_t modinfo_attrs_count = ARRAY_SIZE(modinfo_attrs);
998 
999 static const char vermagic[] = VERMAGIC_STRING;
1000 
1001 int try_to_force_load(struct module *mod, const char *reason)
1002 {
1003 #ifdef CONFIG_MODULE_FORCE_LOAD
1004 	if (!test_taint(TAINT_FORCED_MODULE))
1005 		pr_warn("%s: %s: kernel tainted.\n", mod->name, reason);
1006 	add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
1007 	return 0;
1008 #else
1009 	return -ENOEXEC;
1010 #endif
1011 }
1012 
1013 /* Parse tag=value strings from .modinfo section */
1014 char *module_next_tag_pair(char *string, unsigned long *secsize)
1015 {
1016 	/* Skip non-zero chars */
1017 	while (string[0]) {
1018 		string++;
1019 		if ((*secsize)-- <= 1)
1020 			return NULL;
1021 	}
1022 
1023 	/* Skip any zero padding. */
1024 	while (!string[0]) {
1025 		string++;
1026 		if ((*secsize)-- <= 1)
1027 			return NULL;
1028 	}
1029 	return string;
1030 }
1031 
1032 static char *get_next_modinfo(const struct load_info *info, const char *tag,
1033 			      char *prev)
1034 {
1035 	char *p;
1036 	unsigned int taglen = strlen(tag);
1037 	Elf_Shdr *infosec = &info->sechdrs[info->index.info];
1038 	unsigned long size = infosec->sh_size;
1039 
1040 	/*
1041 	 * get_modinfo() calls made before rewrite_section_headers()
1042 	 * must use sh_offset, as sh_addr isn't set!
1043 	 */
1044 	char *modinfo = (char *)info->hdr + infosec->sh_offset;
1045 
1046 	if (prev) {
1047 		size -= prev - modinfo;
1048 		modinfo = module_next_tag_pair(prev, &size);
1049 	}
1050 
1051 	for (p = modinfo; p; p = module_next_tag_pair(p, &size)) {
1052 		if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
1053 			return p + taglen + 1;
1054 	}
1055 	return NULL;
1056 }
1057 
1058 static char *get_modinfo(const struct load_info *info, const char *tag)
1059 {
1060 	return get_next_modinfo(info, tag, NULL);
1061 }
1062 
1063 static int verify_namespace_is_imported(const struct load_info *info,
1064 					const struct kernel_symbol *sym,
1065 					struct module *mod)
1066 {
1067 	const char *namespace;
1068 	char *imported_namespace;
1069 
1070 	namespace = kernel_symbol_namespace(sym);
1071 	if (namespace && namespace[0]) {
1072 		for_each_modinfo_entry(imported_namespace, info, "import_ns") {
1073 			if (strcmp(namespace, imported_namespace) == 0)
1074 				return 0;
1075 		}
1076 #ifdef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1077 		pr_warn(
1078 #else
1079 		pr_err(
1080 #endif
1081 			"%s: module uses symbol (%s) from namespace %s, but does not import it.\n",
1082 			mod->name, kernel_symbol_name(sym), namespace);
1083 #ifndef CONFIG_MODULE_ALLOW_MISSING_NAMESPACE_IMPORTS
1084 		return -EINVAL;
1085 #endif
1086 	}
1087 	return 0;
1088 }
1089 
1090 static bool inherit_taint(struct module *mod, struct module *owner, const char *name)
1091 {
1092 	if (!owner || !test_bit(TAINT_PROPRIETARY_MODULE, &owner->taints))
1093 		return true;
1094 
1095 	if (mod->using_gplonly_symbols) {
1096 		pr_err("%s: module using GPL-only symbols uses symbols %s from proprietary module %s.\n",
1097 			mod->name, name, owner->name);
1098 		return false;
1099 	}
1100 
1101 	if (!test_bit(TAINT_PROPRIETARY_MODULE, &mod->taints)) {
1102 		pr_warn("%s: module uses symbols %s from proprietary module %s, inheriting taint.\n",
1103 			mod->name, name, owner->name);
1104 		set_bit(TAINT_PROPRIETARY_MODULE, &mod->taints);
1105 	}
1106 	return true;
1107 }
1108 
1109 /* Resolve a symbol for this module.  I.e. if we find one, record usage. */
1110 static const struct kernel_symbol *resolve_symbol(struct module *mod,
1111 						  const struct load_info *info,
1112 						  const char *name,
1113 						  char ownername[])
1114 {
1115 	struct find_symbol_arg fsa = {
1116 		.name	= name,
1117 		.gplok	= !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)),
1118 		.warn	= true,
1119 	};
1120 	int err;
1121 
1122 	/*
1123 	 * The module_mutex should not be a heavily contended lock;
1124 	 * if we get the occasional sleep here, we'll go an extra iteration
1125 	 * in the wait_event_interruptible(), which is harmless.
1126 	 */
1127 	sched_annotate_sleep();
1128 	mutex_lock(&module_mutex);
1129 	if (!find_symbol(&fsa))
1130 		goto unlock;
1131 
1132 	if (fsa.license == GPL_ONLY)
1133 		mod->using_gplonly_symbols = true;
1134 
1135 	if (!inherit_taint(mod, fsa.owner, name)) {
1136 		fsa.sym = NULL;
1137 		goto getname;
1138 	}
1139 
1140 	if (!check_version(info, name, mod, fsa.crc)) {
1141 		fsa.sym = ERR_PTR(-EINVAL);
1142 		goto getname;
1143 	}
1144 
1145 	err = verify_namespace_is_imported(info, fsa.sym, mod);
1146 	if (err) {
1147 		fsa.sym = ERR_PTR(err);
1148 		goto getname;
1149 	}
1150 
1151 	err = ref_module(mod, fsa.owner);
1152 	if (err) {
1153 		fsa.sym = ERR_PTR(err);
1154 		goto getname;
1155 	}
1156 
1157 getname:
1158 	/* We must make copy under the lock if we failed to get ref. */
1159 	strncpy(ownername, module_name(fsa.owner), MODULE_NAME_LEN);
1160 unlock:
1161 	mutex_unlock(&module_mutex);
1162 	return fsa.sym;
1163 }
1164 
1165 static const struct kernel_symbol *
1166 resolve_symbol_wait(struct module *mod,
1167 		    const struct load_info *info,
1168 		    const char *name)
1169 {
1170 	const struct kernel_symbol *ksym;
1171 	char owner[MODULE_NAME_LEN];
1172 
1173 	if (wait_event_interruptible_timeout(module_wq,
1174 			!IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1175 			|| PTR_ERR(ksym) != -EBUSY,
1176 					     30 * HZ) <= 0) {
1177 		pr_warn("%s: gave up waiting for init of module %s.\n",
1178 			mod->name, owner);
1179 	}
1180 	return ksym;
1181 }
1182 
1183 void __weak module_arch_cleanup(struct module *mod)
1184 {
1185 }
1186 
1187 void __weak module_arch_freeing_init(struct module *mod)
1188 {
1189 }
1190 
1191 static int module_memory_alloc(struct module *mod, enum mod_mem_type type)
1192 {
1193 	unsigned int size = PAGE_ALIGN(mod->mem[type].size);
1194 	enum execmem_type execmem_type;
1195 	void *ptr;
1196 
1197 	mod->mem[type].size = size;
1198 
1199 	if (mod_mem_type_is_data(type))
1200 		execmem_type = EXECMEM_MODULE_DATA;
1201 	else
1202 		execmem_type = EXECMEM_MODULE_TEXT;
1203 
1204 	ptr = execmem_alloc(execmem_type, size);
1205 	if (!ptr)
1206 		return -ENOMEM;
1207 
1208 	/*
1209 	 * The pointer to these blocks of memory are stored on the module
1210 	 * structure and we keep that around so long as the module is
1211 	 * around. We only free that memory when we unload the module.
1212 	 * Just mark them as not being a leak then. The .init* ELF
1213 	 * sections *do* get freed after boot so we *could* treat them
1214 	 * slightly differently with kmemleak_ignore() and only grey
1215 	 * them out as they work as typical memory allocations which
1216 	 * *do* eventually get freed, but let's just keep things simple
1217 	 * and avoid *any* false positives.
1218 	 */
1219 	kmemleak_not_leak(ptr);
1220 
1221 	memset(ptr, 0, size);
1222 	mod->mem[type].base = ptr;
1223 
1224 	return 0;
1225 }
1226 
1227 static void module_memory_free(struct module *mod, enum mod_mem_type type)
1228 {
1229 	void *ptr = mod->mem[type].base;
1230 
1231 	execmem_free(ptr);
1232 }
1233 
1234 static void free_mod_mem(struct module *mod)
1235 {
1236 	for_each_mod_mem_type(type) {
1237 		struct module_memory *mod_mem = &mod->mem[type];
1238 
1239 		if (type == MOD_DATA)
1240 			continue;
1241 
1242 		/* Free lock-classes; relies on the preceding sync_rcu(). */
1243 		lockdep_free_key_range(mod_mem->base, mod_mem->size);
1244 		if (mod_mem->size)
1245 			module_memory_free(mod, type);
1246 	}
1247 
1248 	/* MOD_DATA hosts mod, so free it at last */
1249 	lockdep_free_key_range(mod->mem[MOD_DATA].base, mod->mem[MOD_DATA].size);
1250 	module_memory_free(mod, MOD_DATA);
1251 }
1252 
1253 /* Free a module, remove from lists, etc. */
1254 static void free_module(struct module *mod)
1255 {
1256 	trace_module_free(mod);
1257 
1258 	mod_sysfs_teardown(mod);
1259 
1260 	/*
1261 	 * We leave it in list to prevent duplicate loads, but make sure
1262 	 * that noone uses it while it's being deconstructed.
1263 	 */
1264 	mutex_lock(&module_mutex);
1265 	mod->state = MODULE_STATE_UNFORMED;
1266 	mutex_unlock(&module_mutex);
1267 
1268 	/* Arch-specific cleanup. */
1269 	module_arch_cleanup(mod);
1270 
1271 	/* Module unload stuff */
1272 	module_unload_free(mod);
1273 
1274 	/* Free any allocated parameters. */
1275 	destroy_params(mod->kp, mod->num_kp);
1276 
1277 	if (is_livepatch_module(mod))
1278 		free_module_elf(mod);
1279 
1280 	/* Now we can delete it from the lists */
1281 	mutex_lock(&module_mutex);
1282 	/* Unlink carefully: kallsyms could be walking list. */
1283 	list_del_rcu(&mod->list);
1284 	mod_tree_remove(mod);
1285 	/* Remove this module from bug list, this uses list_del_rcu */
1286 	module_bug_cleanup(mod);
1287 	/* Wait for RCU-sched synchronizing before releasing mod->list and buglist. */
1288 	synchronize_rcu();
1289 	if (try_add_tainted_module(mod))
1290 		pr_err("%s: adding tainted module to the unloaded tainted modules list failed.\n",
1291 		       mod->name);
1292 	mutex_unlock(&module_mutex);
1293 
1294 	/* This may be empty, but that's OK */
1295 	module_arch_freeing_init(mod);
1296 	kfree(mod->args);
1297 	percpu_modfree(mod);
1298 
1299 	free_mod_mem(mod);
1300 }
1301 
1302 void *__symbol_get(const char *symbol)
1303 {
1304 	struct find_symbol_arg fsa = {
1305 		.name	= symbol,
1306 		.gplok	= true,
1307 		.warn	= true,
1308 	};
1309 
1310 	preempt_disable();
1311 	if (!find_symbol(&fsa))
1312 		goto fail;
1313 	if (fsa.license != GPL_ONLY) {
1314 		pr_warn("failing symbol_get of non-GPLONLY symbol %s.\n",
1315 			symbol);
1316 		goto fail;
1317 	}
1318 	if (strong_try_module_get(fsa.owner))
1319 		goto fail;
1320 	preempt_enable();
1321 	return (void *)kernel_symbol_value(fsa.sym);
1322 fail:
1323 	preempt_enable();
1324 	return NULL;
1325 }
1326 EXPORT_SYMBOL_GPL(__symbol_get);
1327 
1328 /*
1329  * Ensure that an exported symbol [global namespace] does not already exist
1330  * in the kernel or in some other module's exported symbol table.
1331  *
1332  * You must hold the module_mutex.
1333  */
1334 static int verify_exported_symbols(struct module *mod)
1335 {
1336 	unsigned int i;
1337 	const struct kernel_symbol *s;
1338 	struct {
1339 		const struct kernel_symbol *sym;
1340 		unsigned int num;
1341 	} arr[] = {
1342 		{ mod->syms, mod->num_syms },
1343 		{ mod->gpl_syms, mod->num_gpl_syms },
1344 	};
1345 
1346 	for (i = 0; i < ARRAY_SIZE(arr); i++) {
1347 		for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
1348 			struct find_symbol_arg fsa = {
1349 				.name	= kernel_symbol_name(s),
1350 				.gplok	= true,
1351 			};
1352 			if (find_symbol(&fsa)) {
1353 				pr_err("%s: exports duplicate symbol %s"
1354 				       " (owned by %s)\n",
1355 				       mod->name, kernel_symbol_name(s),
1356 				       module_name(fsa.owner));
1357 				return -ENOEXEC;
1358 			}
1359 		}
1360 	}
1361 	return 0;
1362 }
1363 
1364 static bool ignore_undef_symbol(Elf_Half emachine, const char *name)
1365 {
1366 	/*
1367 	 * On x86, PIC code and Clang non-PIC code may have call foo@PLT. GNU as
1368 	 * before 2.37 produces an unreferenced _GLOBAL_OFFSET_TABLE_ on x86-64.
1369 	 * i386 has a similar problem but may not deserve a fix.
1370 	 *
1371 	 * If we ever have to ignore many symbols, consider refactoring the code to
1372 	 * only warn if referenced by a relocation.
1373 	 */
1374 	if (emachine == EM_386 || emachine == EM_X86_64)
1375 		return !strcmp(name, "_GLOBAL_OFFSET_TABLE_");
1376 	return false;
1377 }
1378 
1379 /* Change all symbols so that st_value encodes the pointer directly. */
1380 static int simplify_symbols(struct module *mod, const struct load_info *info)
1381 {
1382 	Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
1383 	Elf_Sym *sym = (void *)symsec->sh_addr;
1384 	unsigned long secbase;
1385 	unsigned int i;
1386 	int ret = 0;
1387 	const struct kernel_symbol *ksym;
1388 
1389 	for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
1390 		const char *name = info->strtab + sym[i].st_name;
1391 
1392 		switch (sym[i].st_shndx) {
1393 		case SHN_COMMON:
1394 			/* Ignore common symbols */
1395 			if (!strncmp(name, "__gnu_lto", 9))
1396 				break;
1397 
1398 			/*
1399 			 * We compiled with -fno-common.  These are not
1400 			 * supposed to happen.
1401 			 */
1402 			pr_debug("Common symbol: %s\n", name);
1403 			pr_warn("%s: please compile with -fno-common\n",
1404 			       mod->name);
1405 			ret = -ENOEXEC;
1406 			break;
1407 
1408 		case SHN_ABS:
1409 			/* Don't need to do anything */
1410 			pr_debug("Absolute symbol: 0x%08lx %s\n",
1411 				 (long)sym[i].st_value, name);
1412 			break;
1413 
1414 		case SHN_LIVEPATCH:
1415 			/* Livepatch symbols are resolved by livepatch */
1416 			break;
1417 
1418 		case SHN_UNDEF:
1419 			ksym = resolve_symbol_wait(mod, info, name);
1420 			/* Ok if resolved.  */
1421 			if (ksym && !IS_ERR(ksym)) {
1422 				sym[i].st_value = kernel_symbol_value(ksym);
1423 				break;
1424 			}
1425 
1426 			/* Ok if weak or ignored.  */
1427 			if (!ksym &&
1428 			    (ELF_ST_BIND(sym[i].st_info) == STB_WEAK ||
1429 			     ignore_undef_symbol(info->hdr->e_machine, name)))
1430 				break;
1431 
1432 			ret = PTR_ERR(ksym) ?: -ENOENT;
1433 			pr_warn("%s: Unknown symbol %s (err %d)\n",
1434 				mod->name, name, ret);
1435 			break;
1436 
1437 		default:
1438 			/* Divert to percpu allocation if a percpu var. */
1439 			if (sym[i].st_shndx == info->index.pcpu)
1440 				secbase = (unsigned long)mod_percpu(mod);
1441 			else
1442 				secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
1443 			sym[i].st_value += secbase;
1444 			break;
1445 		}
1446 	}
1447 
1448 	return ret;
1449 }
1450 
1451 static int apply_relocations(struct module *mod, const struct load_info *info)
1452 {
1453 	unsigned int i;
1454 	int err = 0;
1455 
1456 	/* Now do relocations. */
1457 	for (i = 1; i < info->hdr->e_shnum; i++) {
1458 		unsigned int infosec = info->sechdrs[i].sh_info;
1459 
1460 		/* Not a valid relocation section? */
1461 		if (infosec >= info->hdr->e_shnum)
1462 			continue;
1463 
1464 		/* Don't bother with non-allocated sections */
1465 		if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
1466 			continue;
1467 
1468 		if (info->sechdrs[i].sh_flags & SHF_RELA_LIVEPATCH)
1469 			err = klp_apply_section_relocs(mod, info->sechdrs,
1470 						       info->secstrings,
1471 						       info->strtab,
1472 						       info->index.sym, i,
1473 						       NULL);
1474 		else if (info->sechdrs[i].sh_type == SHT_REL)
1475 			err = apply_relocate(info->sechdrs, info->strtab,
1476 					     info->index.sym, i, mod);
1477 		else if (info->sechdrs[i].sh_type == SHT_RELA)
1478 			err = apply_relocate_add(info->sechdrs, info->strtab,
1479 						 info->index.sym, i, mod);
1480 		if (err < 0)
1481 			break;
1482 	}
1483 	return err;
1484 }
1485 
1486 /* Additional bytes needed by arch in front of individual sections */
1487 unsigned int __weak arch_mod_section_prepend(struct module *mod,
1488 					     unsigned int section)
1489 {
1490 	/* default implementation just returns zero */
1491 	return 0;
1492 }
1493 
1494 long module_get_offset_and_type(struct module *mod, enum mod_mem_type type,
1495 				Elf_Shdr *sechdr, unsigned int section)
1496 {
1497 	long offset;
1498 	long mask = ((unsigned long)(type) & SH_ENTSIZE_TYPE_MASK) << SH_ENTSIZE_TYPE_SHIFT;
1499 
1500 	mod->mem[type].size += arch_mod_section_prepend(mod, section);
1501 	offset = ALIGN(mod->mem[type].size, sechdr->sh_addralign ?: 1);
1502 	mod->mem[type].size = offset + sechdr->sh_size;
1503 
1504 	WARN_ON_ONCE(offset & mask);
1505 	return offset | mask;
1506 }
1507 
1508 bool module_init_layout_section(const char *sname)
1509 {
1510 #ifndef CONFIG_MODULE_UNLOAD
1511 	if (module_exit_section(sname))
1512 		return true;
1513 #endif
1514 	return module_init_section(sname);
1515 }
1516 
1517 static void __layout_sections(struct module *mod, struct load_info *info, bool is_init)
1518 {
1519 	unsigned int m, i;
1520 
1521 	static const unsigned long masks[][2] = {
1522 		/*
1523 		 * NOTE: all executable code must be the first section
1524 		 * in this array; otherwise modify the text_size
1525 		 * finder in the two loops below
1526 		 */
1527 		{ SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
1528 		{ SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
1529 		{ SHF_RO_AFTER_INIT | SHF_ALLOC, ARCH_SHF_SMALL },
1530 		{ SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
1531 		{ ARCH_SHF_SMALL | SHF_ALLOC, 0 }
1532 	};
1533 	static const int core_m_to_mem_type[] = {
1534 		MOD_TEXT,
1535 		MOD_RODATA,
1536 		MOD_RO_AFTER_INIT,
1537 		MOD_DATA,
1538 		MOD_DATA,
1539 	};
1540 	static const int init_m_to_mem_type[] = {
1541 		MOD_INIT_TEXT,
1542 		MOD_INIT_RODATA,
1543 		MOD_INVALID,
1544 		MOD_INIT_DATA,
1545 		MOD_INIT_DATA,
1546 	};
1547 
1548 	for (m = 0; m < ARRAY_SIZE(masks); ++m) {
1549 		enum mod_mem_type type = is_init ? init_m_to_mem_type[m] : core_m_to_mem_type[m];
1550 
1551 		for (i = 0; i < info->hdr->e_shnum; ++i) {
1552 			Elf_Shdr *s = &info->sechdrs[i];
1553 			const char *sname = info->secstrings + s->sh_name;
1554 
1555 			if ((s->sh_flags & masks[m][0]) != masks[m][0]
1556 			    || (s->sh_flags & masks[m][1])
1557 			    || s->sh_entsize != ~0UL
1558 			    || is_init != module_init_layout_section(sname))
1559 				continue;
1560 
1561 			if (WARN_ON_ONCE(type == MOD_INVALID))
1562 				continue;
1563 
1564 			s->sh_entsize = module_get_offset_and_type(mod, type, s, i);
1565 			pr_debug("\t%s\n", sname);
1566 		}
1567 	}
1568 }
1569 
1570 /*
1571  * Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
1572  * might -- code, read-only data, read-write data, small data.  Tally
1573  * sizes, and place the offsets into sh_entsize fields: high bit means it
1574  * belongs in init.
1575  */
1576 static void layout_sections(struct module *mod, struct load_info *info)
1577 {
1578 	unsigned int i;
1579 
1580 	for (i = 0; i < info->hdr->e_shnum; i++)
1581 		info->sechdrs[i].sh_entsize = ~0UL;
1582 
1583 	pr_debug("Core section allocation order for %s:\n", mod->name);
1584 	__layout_sections(mod, info, false);
1585 
1586 	pr_debug("Init section allocation order for %s:\n", mod->name);
1587 	__layout_sections(mod, info, true);
1588 }
1589 
1590 static void module_license_taint_check(struct module *mod, const char *license)
1591 {
1592 	if (!license)
1593 		license = "unspecified";
1594 
1595 	if (!license_is_gpl_compatible(license)) {
1596 		if (!test_taint(TAINT_PROPRIETARY_MODULE))
1597 			pr_warn("%s: module license '%s' taints kernel.\n",
1598 				mod->name, license);
1599 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
1600 				 LOCKDEP_NOW_UNRELIABLE);
1601 	}
1602 }
1603 
1604 static void setup_modinfo(struct module *mod, struct load_info *info)
1605 {
1606 	struct module_attribute *attr;
1607 	int i;
1608 
1609 	for (i = 0; (attr = modinfo_attrs[i]); i++) {
1610 		if (attr->setup)
1611 			attr->setup(mod, get_modinfo(info, attr->attr.name));
1612 	}
1613 }
1614 
1615 static void free_modinfo(struct module *mod)
1616 {
1617 	struct module_attribute *attr;
1618 	int i;
1619 
1620 	for (i = 0; (attr = modinfo_attrs[i]); i++) {
1621 		if (attr->free)
1622 			attr->free(mod);
1623 	}
1624 }
1625 
1626 bool __weak module_init_section(const char *name)
1627 {
1628 	return strstarts(name, ".init");
1629 }
1630 
1631 bool __weak module_exit_section(const char *name)
1632 {
1633 	return strstarts(name, ".exit");
1634 }
1635 
1636 static int validate_section_offset(struct load_info *info, Elf_Shdr *shdr)
1637 {
1638 #if defined(CONFIG_64BIT)
1639 	unsigned long long secend;
1640 #else
1641 	unsigned long secend;
1642 #endif
1643 
1644 	/*
1645 	 * Check for both overflow and offset/size being
1646 	 * too large.
1647 	 */
1648 	secend = shdr->sh_offset + shdr->sh_size;
1649 	if (secend < shdr->sh_offset || secend > info->len)
1650 		return -ENOEXEC;
1651 
1652 	return 0;
1653 }
1654 
1655 /*
1656  * Check userspace passed ELF module against our expectations, and cache
1657  * useful variables for further processing as we go.
1658  *
1659  * This does basic validity checks against section offsets and sizes, the
1660  * section name string table, and the indices used for it (sh_name).
1661  *
1662  * As a last step, since we're already checking the ELF sections we cache
1663  * useful variables which will be used later for our convenience:
1664  *
1665  * 	o pointers to section headers
1666  * 	o cache the modinfo symbol section
1667  * 	o cache the string symbol section
1668  * 	o cache the module section
1669  *
1670  * As a last step we set info->mod to the temporary copy of the module in
1671  * info->hdr. The final one will be allocated in move_module(). Any
1672  * modifications we make to our copy of the module will be carried over
1673  * to the final minted module.
1674  */
1675 static int elf_validity_cache_copy(struct load_info *info, int flags)
1676 {
1677 	unsigned int i;
1678 	Elf_Shdr *shdr, *strhdr;
1679 	int err;
1680 	unsigned int num_mod_secs = 0, mod_idx;
1681 	unsigned int num_info_secs = 0, info_idx;
1682 	unsigned int num_sym_secs = 0, sym_idx;
1683 
1684 	if (info->len < sizeof(*(info->hdr))) {
1685 		pr_err("Invalid ELF header len %lu\n", info->len);
1686 		goto no_exec;
1687 	}
1688 
1689 	if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0) {
1690 		pr_err("Invalid ELF header magic: != %s\n", ELFMAG);
1691 		goto no_exec;
1692 	}
1693 	if (info->hdr->e_type != ET_REL) {
1694 		pr_err("Invalid ELF header type: %u != %u\n",
1695 		       info->hdr->e_type, ET_REL);
1696 		goto no_exec;
1697 	}
1698 	if (!elf_check_arch(info->hdr)) {
1699 		pr_err("Invalid architecture in ELF header: %u\n",
1700 		       info->hdr->e_machine);
1701 		goto no_exec;
1702 	}
1703 	if (!module_elf_check_arch(info->hdr)) {
1704 		pr_err("Invalid module architecture in ELF header: %u\n",
1705 		       info->hdr->e_machine);
1706 		goto no_exec;
1707 	}
1708 	if (info->hdr->e_shentsize != sizeof(Elf_Shdr)) {
1709 		pr_err("Invalid ELF section header size\n");
1710 		goto no_exec;
1711 	}
1712 
1713 	/*
1714 	 * e_shnum is 16 bits, and sizeof(Elf_Shdr) is
1715 	 * known and small. So e_shnum * sizeof(Elf_Shdr)
1716 	 * will not overflow unsigned long on any platform.
1717 	 */
1718 	if (info->hdr->e_shoff >= info->len
1719 	    || (info->hdr->e_shnum * sizeof(Elf_Shdr) >
1720 		info->len - info->hdr->e_shoff)) {
1721 		pr_err("Invalid ELF section header overflow\n");
1722 		goto no_exec;
1723 	}
1724 
1725 	info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
1726 
1727 	/*
1728 	 * Verify if the section name table index is valid.
1729 	 */
1730 	if (info->hdr->e_shstrndx == SHN_UNDEF
1731 	    || info->hdr->e_shstrndx >= info->hdr->e_shnum) {
1732 		pr_err("Invalid ELF section name index: %d || e_shstrndx (%d) >= e_shnum (%d)\n",
1733 		       info->hdr->e_shstrndx, info->hdr->e_shstrndx,
1734 		       info->hdr->e_shnum);
1735 		goto no_exec;
1736 	}
1737 
1738 	strhdr = &info->sechdrs[info->hdr->e_shstrndx];
1739 	err = validate_section_offset(info, strhdr);
1740 	if (err < 0) {
1741 		pr_err("Invalid ELF section hdr(type %u)\n", strhdr->sh_type);
1742 		return err;
1743 	}
1744 
1745 	/*
1746 	 * The section name table must be NUL-terminated, as required
1747 	 * by the spec. This makes strcmp and pr_* calls that access
1748 	 * strings in the section safe.
1749 	 */
1750 	info->secstrings = (void *)info->hdr + strhdr->sh_offset;
1751 	if (strhdr->sh_size == 0) {
1752 		pr_err("empty section name table\n");
1753 		goto no_exec;
1754 	}
1755 	if (info->secstrings[strhdr->sh_size - 1] != '\0') {
1756 		pr_err("ELF Spec violation: section name table isn't null terminated\n");
1757 		goto no_exec;
1758 	}
1759 
1760 	/*
1761 	 * The code assumes that section 0 has a length of zero and
1762 	 * an addr of zero, so check for it.
1763 	 */
1764 	if (info->sechdrs[0].sh_type != SHT_NULL
1765 	    || info->sechdrs[0].sh_size != 0
1766 	    || info->sechdrs[0].sh_addr != 0) {
1767 		pr_err("ELF Spec violation: section 0 type(%d)!=SH_NULL or non-zero len or addr\n",
1768 		       info->sechdrs[0].sh_type);
1769 		goto no_exec;
1770 	}
1771 
1772 	for (i = 1; i < info->hdr->e_shnum; i++) {
1773 		shdr = &info->sechdrs[i];
1774 		switch (shdr->sh_type) {
1775 		case SHT_NULL:
1776 		case SHT_NOBITS:
1777 			continue;
1778 		case SHT_SYMTAB:
1779 			if (shdr->sh_link == SHN_UNDEF
1780 			    || shdr->sh_link >= info->hdr->e_shnum) {
1781 				pr_err("Invalid ELF sh_link!=SHN_UNDEF(%d) or (sh_link(%d) >= hdr->e_shnum(%d)\n",
1782 				       shdr->sh_link, shdr->sh_link,
1783 				       info->hdr->e_shnum);
1784 				goto no_exec;
1785 			}
1786 			num_sym_secs++;
1787 			sym_idx = i;
1788 			fallthrough;
1789 		default:
1790 			err = validate_section_offset(info, shdr);
1791 			if (err < 0) {
1792 				pr_err("Invalid ELF section in module (section %u type %u)\n",
1793 					i, shdr->sh_type);
1794 				return err;
1795 			}
1796 			if (strcmp(info->secstrings + shdr->sh_name,
1797 				   ".gnu.linkonce.this_module") == 0) {
1798 				num_mod_secs++;
1799 				mod_idx = i;
1800 			} else if (strcmp(info->secstrings + shdr->sh_name,
1801 				   ".modinfo") == 0) {
1802 				num_info_secs++;
1803 				info_idx = i;
1804 			}
1805 
1806 			if (shdr->sh_flags & SHF_ALLOC) {
1807 				if (shdr->sh_name >= strhdr->sh_size) {
1808 					pr_err("Invalid ELF section name in module (section %u type %u)\n",
1809 					       i, shdr->sh_type);
1810 					return -ENOEXEC;
1811 				}
1812 			}
1813 			break;
1814 		}
1815 	}
1816 
1817 	if (num_info_secs > 1) {
1818 		pr_err("Only one .modinfo section must exist.\n");
1819 		goto no_exec;
1820 	} else if (num_info_secs == 1) {
1821 		/* Try to find a name early so we can log errors with a module name */
1822 		info->index.info = info_idx;
1823 		info->name = get_modinfo(info, "name");
1824 	}
1825 
1826 	if (num_sym_secs != 1) {
1827 		pr_warn("%s: module has no symbols (stripped?)\n",
1828 			info->name ?: "(missing .modinfo section or name field)");
1829 		goto no_exec;
1830 	}
1831 
1832 	/* Sets internal symbols and strings. */
1833 	info->index.sym = sym_idx;
1834 	shdr = &info->sechdrs[sym_idx];
1835 	info->index.str = shdr->sh_link;
1836 	info->strtab = (char *)info->hdr + info->sechdrs[info->index.str].sh_offset;
1837 
1838 	/*
1839 	 * The ".gnu.linkonce.this_module" ELF section is special. It is
1840 	 * what modpost uses to refer to __this_module and let's use rely
1841 	 * on THIS_MODULE to point to &__this_module properly. The kernel's
1842 	 * modpost declares it on each modules's *.mod.c file. If the struct
1843 	 * module of the kernel changes a full kernel rebuild is required.
1844 	 *
1845 	 * We have a few expectaions for this special section, the following
1846 	 * code validates all this for us:
1847 	 *
1848 	 *   o Only one section must exist
1849 	 *   o We expect the kernel to always have to allocate it: SHF_ALLOC
1850 	 *   o The section size must match the kernel's run time's struct module
1851 	 *     size
1852 	 */
1853 	if (num_mod_secs != 1) {
1854 		pr_err("module %s: Only one .gnu.linkonce.this_module section must exist.\n",
1855 		       info->name ?: "(missing .modinfo section or name field)");
1856 		goto no_exec;
1857 	}
1858 
1859 	shdr = &info->sechdrs[mod_idx];
1860 
1861 	/*
1862 	 * This is already implied on the switch above, however let's be
1863 	 * pedantic about it.
1864 	 */
1865 	if (shdr->sh_type == SHT_NOBITS) {
1866 		pr_err("module %s: .gnu.linkonce.this_module section must have a size set\n",
1867 		       info->name ?: "(missing .modinfo section or name field)");
1868 		goto no_exec;
1869 	}
1870 
1871 	if (!(shdr->sh_flags & SHF_ALLOC)) {
1872 		pr_err("module %s: .gnu.linkonce.this_module must occupy memory during process execution\n",
1873 		       info->name ?: "(missing .modinfo section or name field)");
1874 		goto no_exec;
1875 	}
1876 
1877 	if (shdr->sh_size != sizeof(struct module)) {
1878 		pr_err("module %s: .gnu.linkonce.this_module section size must match the kernel's built struct module size at run time\n",
1879 		       info->name ?: "(missing .modinfo section or name field)");
1880 		goto no_exec;
1881 	}
1882 
1883 	info->index.mod = mod_idx;
1884 
1885 	/* This is temporary: point mod into copy of data. */
1886 	info->mod = (void *)info->hdr + shdr->sh_offset;
1887 
1888 	/*
1889 	 * If we didn't load the .modinfo 'name' field earlier, fall back to
1890 	 * on-disk struct mod 'name' field.
1891 	 */
1892 	if (!info->name)
1893 		info->name = info->mod->name;
1894 
1895 	if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
1896 		info->index.vers = 0; /* Pretend no __versions section! */
1897 	else
1898 		info->index.vers = find_sec(info, "__versions");
1899 
1900 	info->index.pcpu = find_pcpusec(info);
1901 
1902 	return 0;
1903 
1904 no_exec:
1905 	return -ENOEXEC;
1906 }
1907 
1908 #define COPY_CHUNK_SIZE (16*PAGE_SIZE)
1909 
1910 static int copy_chunked_from_user(void *dst, const void __user *usrc, unsigned long len)
1911 {
1912 	do {
1913 		unsigned long n = min(len, COPY_CHUNK_SIZE);
1914 
1915 		if (copy_from_user(dst, usrc, n) != 0)
1916 			return -EFAULT;
1917 		cond_resched();
1918 		dst += n;
1919 		usrc += n;
1920 		len -= n;
1921 	} while (len);
1922 	return 0;
1923 }
1924 
1925 static int check_modinfo_livepatch(struct module *mod, struct load_info *info)
1926 {
1927 	if (!get_modinfo(info, "livepatch"))
1928 		/* Nothing more to do */
1929 		return 0;
1930 
1931 	if (set_livepatch_module(mod))
1932 		return 0;
1933 
1934 	pr_err("%s: module is marked as livepatch module, but livepatch support is disabled",
1935 	       mod->name);
1936 	return -ENOEXEC;
1937 }
1938 
1939 static void check_modinfo_retpoline(struct module *mod, struct load_info *info)
1940 {
1941 	if (retpoline_module_ok(get_modinfo(info, "retpoline")))
1942 		return;
1943 
1944 	pr_warn("%s: loading module not compiled with retpoline compiler.\n",
1945 		mod->name);
1946 }
1947 
1948 /* Sets info->hdr and info->len. */
1949 static int copy_module_from_user(const void __user *umod, unsigned long len,
1950 				  struct load_info *info)
1951 {
1952 	int err;
1953 
1954 	info->len = len;
1955 	if (info->len < sizeof(*(info->hdr)))
1956 		return -ENOEXEC;
1957 
1958 	err = security_kernel_load_data(LOADING_MODULE, true);
1959 	if (err)
1960 		return err;
1961 
1962 	/* Suck in entire file: we'll want most of it. */
1963 	info->hdr = __vmalloc(info->len, GFP_KERNEL | __GFP_NOWARN);
1964 	if (!info->hdr)
1965 		return -ENOMEM;
1966 
1967 	if (copy_chunked_from_user(info->hdr, umod, info->len) != 0) {
1968 		err = -EFAULT;
1969 		goto out;
1970 	}
1971 
1972 	err = security_kernel_post_load_data((char *)info->hdr, info->len,
1973 					     LOADING_MODULE, "init_module");
1974 out:
1975 	if (err)
1976 		vfree(info->hdr);
1977 
1978 	return err;
1979 }
1980 
1981 static void free_copy(struct load_info *info, int flags)
1982 {
1983 	if (flags & MODULE_INIT_COMPRESSED_FILE)
1984 		module_decompress_cleanup(info);
1985 	else
1986 		vfree(info->hdr);
1987 }
1988 
1989 static int rewrite_section_headers(struct load_info *info, int flags)
1990 {
1991 	unsigned int i;
1992 
1993 	/* This should always be true, but let's be sure. */
1994 	info->sechdrs[0].sh_addr = 0;
1995 
1996 	for (i = 1; i < info->hdr->e_shnum; i++) {
1997 		Elf_Shdr *shdr = &info->sechdrs[i];
1998 
1999 		/*
2000 		 * Mark all sections sh_addr with their address in the
2001 		 * temporary image.
2002 		 */
2003 		shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
2004 
2005 	}
2006 
2007 	/* Track but don't keep modinfo and version sections. */
2008 	info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
2009 	info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
2010 
2011 	return 0;
2012 }
2013 
2014 /*
2015  * These calls taint the kernel depending certain module circumstances */
2016 static void module_augment_kernel_taints(struct module *mod, struct load_info *info)
2017 {
2018 	int prev_taint = test_taint(TAINT_PROPRIETARY_MODULE);
2019 
2020 	if (!get_modinfo(info, "intree")) {
2021 		if (!test_taint(TAINT_OOT_MODULE))
2022 			pr_warn("%s: loading out-of-tree module taints kernel.\n",
2023 				mod->name);
2024 		add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
2025 	}
2026 
2027 	check_modinfo_retpoline(mod, info);
2028 
2029 	if (get_modinfo(info, "staging")) {
2030 		add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
2031 		pr_warn("%s: module is from the staging directory, the quality "
2032 			"is unknown, you have been warned.\n", mod->name);
2033 	}
2034 
2035 	if (is_livepatch_module(mod)) {
2036 		add_taint_module(mod, TAINT_LIVEPATCH, LOCKDEP_STILL_OK);
2037 		pr_notice_once("%s: tainting kernel with TAINT_LIVEPATCH\n",
2038 				mod->name);
2039 	}
2040 
2041 	module_license_taint_check(mod, get_modinfo(info, "license"));
2042 
2043 	if (get_modinfo(info, "test")) {
2044 		if (!test_taint(TAINT_TEST))
2045 			pr_warn("%s: loading test module taints kernel.\n",
2046 				mod->name);
2047 		add_taint_module(mod, TAINT_TEST, LOCKDEP_STILL_OK);
2048 	}
2049 #ifdef CONFIG_MODULE_SIG
2050 	mod->sig_ok = info->sig_ok;
2051 	if (!mod->sig_ok) {
2052 		pr_notice_once("%s: module verification failed: signature "
2053 			       "and/or required key missing - tainting "
2054 			       "kernel\n", mod->name);
2055 		add_taint_module(mod, TAINT_UNSIGNED_MODULE, LOCKDEP_STILL_OK);
2056 	}
2057 #endif
2058 
2059 	/*
2060 	 * ndiswrapper is under GPL by itself, but loads proprietary modules.
2061 	 * Don't use add_taint_module(), as it would prevent ndiswrapper from
2062 	 * using GPL-only symbols it needs.
2063 	 */
2064 	if (strcmp(mod->name, "ndiswrapper") == 0)
2065 		add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
2066 
2067 	/* driverloader was caught wrongly pretending to be under GPL */
2068 	if (strcmp(mod->name, "driverloader") == 0)
2069 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2070 				 LOCKDEP_NOW_UNRELIABLE);
2071 
2072 	/* lve claims to be GPL but upstream won't provide source */
2073 	if (strcmp(mod->name, "lve") == 0)
2074 		add_taint_module(mod, TAINT_PROPRIETARY_MODULE,
2075 				 LOCKDEP_NOW_UNRELIABLE);
2076 
2077 	if (!prev_taint && test_taint(TAINT_PROPRIETARY_MODULE))
2078 		pr_warn("%s: module license taints kernel.\n", mod->name);
2079 
2080 }
2081 
2082 static int check_modinfo(struct module *mod, struct load_info *info, int flags)
2083 {
2084 	const char *modmagic = get_modinfo(info, "vermagic");
2085 	int err;
2086 
2087 	if (flags & MODULE_INIT_IGNORE_VERMAGIC)
2088 		modmagic = NULL;
2089 
2090 	/* This is allowed: modprobe --force will invalidate it. */
2091 	if (!modmagic) {
2092 		err = try_to_force_load(mod, "bad vermagic");
2093 		if (err)
2094 			return err;
2095 	} else if (!same_magic(modmagic, vermagic, info->index.vers)) {
2096 		pr_err("%s: version magic '%s' should be '%s'\n",
2097 		       info->name, modmagic, vermagic);
2098 		return -ENOEXEC;
2099 	}
2100 
2101 	err = check_modinfo_livepatch(mod, info);
2102 	if (err)
2103 		return err;
2104 
2105 	return 0;
2106 }
2107 
2108 static int find_module_sections(struct module *mod, struct load_info *info)
2109 {
2110 	mod->kp = section_objs(info, "__param",
2111 			       sizeof(*mod->kp), &mod->num_kp);
2112 	mod->syms = section_objs(info, "__ksymtab",
2113 				 sizeof(*mod->syms), &mod->num_syms);
2114 	mod->crcs = section_addr(info, "__kcrctab");
2115 	mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
2116 				     sizeof(*mod->gpl_syms),
2117 				     &mod->num_gpl_syms);
2118 	mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
2119 
2120 #ifdef CONFIG_CONSTRUCTORS
2121 	mod->ctors = section_objs(info, ".ctors",
2122 				  sizeof(*mod->ctors), &mod->num_ctors);
2123 	if (!mod->ctors)
2124 		mod->ctors = section_objs(info, ".init_array",
2125 				sizeof(*mod->ctors), &mod->num_ctors);
2126 	else if (find_sec(info, ".init_array")) {
2127 		/*
2128 		 * This shouldn't happen with same compiler and binutils
2129 		 * building all parts of the module.
2130 		 */
2131 		pr_warn("%s: has both .ctors and .init_array.\n",
2132 		       mod->name);
2133 		return -EINVAL;
2134 	}
2135 #endif
2136 
2137 	mod->noinstr_text_start = section_objs(info, ".noinstr.text", 1,
2138 						&mod->noinstr_text_size);
2139 
2140 #ifdef CONFIG_TRACEPOINTS
2141 	mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",
2142 					     sizeof(*mod->tracepoints_ptrs),
2143 					     &mod->num_tracepoints);
2144 #endif
2145 #ifdef CONFIG_TREE_SRCU
2146 	mod->srcu_struct_ptrs = section_objs(info, "___srcu_struct_ptrs",
2147 					     sizeof(*mod->srcu_struct_ptrs),
2148 					     &mod->num_srcu_structs);
2149 #endif
2150 #ifdef CONFIG_BPF_EVENTS
2151 	mod->bpf_raw_events = section_objs(info, "__bpf_raw_tp_map",
2152 					   sizeof(*mod->bpf_raw_events),
2153 					   &mod->num_bpf_raw_events);
2154 #endif
2155 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
2156 	mod->btf_data = any_section_objs(info, ".BTF", 1, &mod->btf_data_size);
2157 #endif
2158 #ifdef CONFIG_JUMP_LABEL
2159 	mod->jump_entries = section_objs(info, "__jump_table",
2160 					sizeof(*mod->jump_entries),
2161 					&mod->num_jump_entries);
2162 #endif
2163 #ifdef CONFIG_EVENT_TRACING
2164 	mod->trace_events = section_objs(info, "_ftrace_events",
2165 					 sizeof(*mod->trace_events),
2166 					 &mod->num_trace_events);
2167 	mod->trace_evals = section_objs(info, "_ftrace_eval_map",
2168 					sizeof(*mod->trace_evals),
2169 					&mod->num_trace_evals);
2170 #endif
2171 #ifdef CONFIG_TRACING
2172 	mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",
2173 					 sizeof(*mod->trace_bprintk_fmt_start),
2174 					 &mod->num_trace_bprintk_fmt);
2175 #endif
2176 #ifdef CONFIG_FTRACE_MCOUNT_RECORD
2177 	/* sechdrs[0].sh_size is always zero */
2178 	mod->ftrace_callsites = section_objs(info, FTRACE_CALLSITE_SECTION,
2179 					     sizeof(*mod->ftrace_callsites),
2180 					     &mod->num_ftrace_callsites);
2181 #endif
2182 #ifdef CONFIG_FUNCTION_ERROR_INJECTION
2183 	mod->ei_funcs = section_objs(info, "_error_injection_whitelist",
2184 					    sizeof(*mod->ei_funcs),
2185 					    &mod->num_ei_funcs);
2186 #endif
2187 #ifdef CONFIG_KPROBES
2188 	mod->kprobes_text_start = section_objs(info, ".kprobes.text", 1,
2189 						&mod->kprobes_text_size);
2190 	mod->kprobe_blacklist = section_objs(info, "_kprobe_blacklist",
2191 						sizeof(unsigned long),
2192 						&mod->num_kprobe_blacklist);
2193 #endif
2194 #ifdef CONFIG_PRINTK_INDEX
2195 	mod->printk_index_start = section_objs(info, ".printk_index",
2196 					       sizeof(*mod->printk_index_start),
2197 					       &mod->printk_index_size);
2198 #endif
2199 #ifdef CONFIG_HAVE_STATIC_CALL_INLINE
2200 	mod->static_call_sites = section_objs(info, ".static_call_sites",
2201 					      sizeof(*mod->static_call_sites),
2202 					      &mod->num_static_call_sites);
2203 #endif
2204 #if IS_ENABLED(CONFIG_KUNIT)
2205 	mod->kunit_suites = section_objs(info, ".kunit_test_suites",
2206 					      sizeof(*mod->kunit_suites),
2207 					      &mod->num_kunit_suites);
2208 	mod->kunit_init_suites = section_objs(info, ".kunit_init_test_suites",
2209 					      sizeof(*mod->kunit_init_suites),
2210 					      &mod->num_kunit_init_suites);
2211 #endif
2212 
2213 	mod->extable = section_objs(info, "__ex_table",
2214 				    sizeof(*mod->extable), &mod->num_exentries);
2215 
2216 	if (section_addr(info, "__obsparm"))
2217 		pr_warn("%s: Ignoring obsolete parameters\n", mod->name);
2218 
2219 #ifdef CONFIG_DYNAMIC_DEBUG_CORE
2220 	mod->dyndbg_info.descs = section_objs(info, "__dyndbg",
2221 					      sizeof(*mod->dyndbg_info.descs),
2222 					      &mod->dyndbg_info.num_descs);
2223 	mod->dyndbg_info.classes = section_objs(info, "__dyndbg_classes",
2224 						sizeof(*mod->dyndbg_info.classes),
2225 						&mod->dyndbg_info.num_classes);
2226 #endif
2227 
2228 	return 0;
2229 }
2230 
2231 static int move_module(struct module *mod, struct load_info *info)
2232 {
2233 	int i;
2234 	enum mod_mem_type t = 0;
2235 	int ret = -ENOMEM;
2236 
2237 	for_each_mod_mem_type(type) {
2238 		if (!mod->mem[type].size) {
2239 			mod->mem[type].base = NULL;
2240 			continue;
2241 		}
2242 
2243 		ret = module_memory_alloc(mod, type);
2244 		if (ret) {
2245 			t = type;
2246 			goto out_enomem;
2247 		}
2248 	}
2249 
2250 	/* Transfer each section which specifies SHF_ALLOC */
2251 	pr_debug("Final section addresses for %s:\n", mod->name);
2252 	for (i = 0; i < info->hdr->e_shnum; i++) {
2253 		void *dest;
2254 		Elf_Shdr *shdr = &info->sechdrs[i];
2255 		enum mod_mem_type type = shdr->sh_entsize >> SH_ENTSIZE_TYPE_SHIFT;
2256 
2257 		if (!(shdr->sh_flags & SHF_ALLOC))
2258 			continue;
2259 
2260 		dest = mod->mem[type].base + (shdr->sh_entsize & SH_ENTSIZE_OFFSET_MASK);
2261 
2262 		if (shdr->sh_type != SHT_NOBITS) {
2263 			/*
2264 			 * Our ELF checker already validated this, but let's
2265 			 * be pedantic and make the goal clearer. We actually
2266 			 * end up copying over all modifications made to the
2267 			 * userspace copy of the entire struct module.
2268 			 */
2269 			if (i == info->index.mod &&
2270 			   (WARN_ON_ONCE(shdr->sh_size != sizeof(struct module)))) {
2271 				ret = -ENOEXEC;
2272 				goto out_enomem;
2273 			}
2274 			memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
2275 		}
2276 		/*
2277 		 * Update the userspace copy's ELF section address to point to
2278 		 * our newly allocated memory as a pure convenience so that
2279 		 * users of info can keep taking advantage and using the newly
2280 		 * minted official memory area.
2281 		 */
2282 		shdr->sh_addr = (unsigned long)dest;
2283 		pr_debug("\t0x%lx 0x%.8lx %s\n", (long)shdr->sh_addr,
2284 			 (long)shdr->sh_size, info->secstrings + shdr->sh_name);
2285 	}
2286 
2287 	return 0;
2288 out_enomem:
2289 	for (t--; t >= 0; t--)
2290 		module_memory_free(mod, t);
2291 	return ret;
2292 }
2293 
2294 static int check_export_symbol_versions(struct module *mod)
2295 {
2296 #ifdef CONFIG_MODVERSIONS
2297 	if ((mod->num_syms && !mod->crcs) ||
2298 	    (mod->num_gpl_syms && !mod->gpl_crcs)) {
2299 		return try_to_force_load(mod,
2300 					 "no versions for exported symbols");
2301 	}
2302 #endif
2303 	return 0;
2304 }
2305 
2306 static void flush_module_icache(const struct module *mod)
2307 {
2308 	/*
2309 	 * Flush the instruction cache, since we've played with text.
2310 	 * Do it before processing of module parameters, so the module
2311 	 * can provide parameter accessor functions of its own.
2312 	 */
2313 	for_each_mod_mem_type(type) {
2314 		const struct module_memory *mod_mem = &mod->mem[type];
2315 
2316 		if (mod_mem->size) {
2317 			flush_icache_range((unsigned long)mod_mem->base,
2318 					   (unsigned long)mod_mem->base + mod_mem->size);
2319 		}
2320 	}
2321 }
2322 
2323 bool __weak module_elf_check_arch(Elf_Ehdr *hdr)
2324 {
2325 	return true;
2326 }
2327 
2328 int __weak module_frob_arch_sections(Elf_Ehdr *hdr,
2329 				     Elf_Shdr *sechdrs,
2330 				     char *secstrings,
2331 				     struct module *mod)
2332 {
2333 	return 0;
2334 }
2335 
2336 /* module_blacklist is a comma-separated list of module names */
2337 static char *module_blacklist;
2338 static bool blacklisted(const char *module_name)
2339 {
2340 	const char *p;
2341 	size_t len;
2342 
2343 	if (!module_blacklist)
2344 		return false;
2345 
2346 	for (p = module_blacklist; *p; p += len) {
2347 		len = strcspn(p, ",");
2348 		if (strlen(module_name) == len && !memcmp(module_name, p, len))
2349 			return true;
2350 		if (p[len] == ',')
2351 			len++;
2352 	}
2353 	return false;
2354 }
2355 core_param(module_blacklist, module_blacklist, charp, 0400);
2356 
2357 static struct module *layout_and_allocate(struct load_info *info, int flags)
2358 {
2359 	struct module *mod;
2360 	unsigned int ndx;
2361 	int err;
2362 
2363 	/* Allow arches to frob section contents and sizes.  */
2364 	err = module_frob_arch_sections(info->hdr, info->sechdrs,
2365 					info->secstrings, info->mod);
2366 	if (err < 0)
2367 		return ERR_PTR(err);
2368 
2369 	err = module_enforce_rwx_sections(info->hdr, info->sechdrs,
2370 					  info->secstrings, info->mod);
2371 	if (err < 0)
2372 		return ERR_PTR(err);
2373 
2374 	/* We will do a special allocation for per-cpu sections later. */
2375 	info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
2376 
2377 	/*
2378 	 * Mark ro_after_init section with SHF_RO_AFTER_INIT so that
2379 	 * layout_sections() can put it in the right place.
2380 	 * Note: ro_after_init sections also have SHF_{WRITE,ALLOC} set.
2381 	 */
2382 	ndx = find_sec(info, ".data..ro_after_init");
2383 	if (ndx)
2384 		info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
2385 	/*
2386 	 * Mark the __jump_table section as ro_after_init as well: these data
2387 	 * structures are never modified, with the exception of entries that
2388 	 * refer to code in the __init section, which are annotated as such
2389 	 * at module load time.
2390 	 */
2391 	ndx = find_sec(info, "__jump_table");
2392 	if (ndx)
2393 		info->sechdrs[ndx].sh_flags |= SHF_RO_AFTER_INIT;
2394 
2395 	/*
2396 	 * Determine total sizes, and put offsets in sh_entsize.  For now
2397 	 * this is done generically; there doesn't appear to be any
2398 	 * special cases for the architectures.
2399 	 */
2400 	layout_sections(info->mod, info);
2401 	layout_symtab(info->mod, info);
2402 
2403 	/* Allocate and move to the final place */
2404 	err = move_module(info->mod, info);
2405 	if (err)
2406 		return ERR_PTR(err);
2407 
2408 	/* Module has been copied to its final place now: return it. */
2409 	mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2410 	kmemleak_load_module(mod, info);
2411 	return mod;
2412 }
2413 
2414 /* mod is no longer valid after this! */
2415 static void module_deallocate(struct module *mod, struct load_info *info)
2416 {
2417 	percpu_modfree(mod);
2418 	module_arch_freeing_init(mod);
2419 
2420 	free_mod_mem(mod);
2421 }
2422 
2423 int __weak module_finalize(const Elf_Ehdr *hdr,
2424 			   const Elf_Shdr *sechdrs,
2425 			   struct module *me)
2426 {
2427 	return 0;
2428 }
2429 
2430 static int post_relocation(struct module *mod, const struct load_info *info)
2431 {
2432 	/* Sort exception table now relocations are done. */
2433 	sort_extable(mod->extable, mod->extable + mod->num_exentries);
2434 
2435 	/* Copy relocated percpu area over. */
2436 	percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
2437 		       info->sechdrs[info->index.pcpu].sh_size);
2438 
2439 	/* Setup kallsyms-specific fields. */
2440 	add_kallsyms(mod, info);
2441 
2442 	/* Arch-specific module finalizing. */
2443 	return module_finalize(info->hdr, info->sechdrs, mod);
2444 }
2445 
2446 /* Call module constructors. */
2447 static void do_mod_ctors(struct module *mod)
2448 {
2449 #ifdef CONFIG_CONSTRUCTORS
2450 	unsigned long i;
2451 
2452 	for (i = 0; i < mod->num_ctors; i++)
2453 		mod->ctors[i]();
2454 #endif
2455 }
2456 
2457 /* For freeing module_init on success, in case kallsyms traversing */
2458 struct mod_initfree {
2459 	struct llist_node node;
2460 	void *init_text;
2461 	void *init_data;
2462 	void *init_rodata;
2463 };
2464 
2465 static void do_free_init(struct work_struct *w)
2466 {
2467 	struct llist_node *pos, *n, *list;
2468 	struct mod_initfree *initfree;
2469 
2470 	list = llist_del_all(&init_free_list);
2471 
2472 	synchronize_rcu();
2473 
2474 	llist_for_each_safe(pos, n, list) {
2475 		initfree = container_of(pos, struct mod_initfree, node);
2476 		execmem_free(initfree->init_text);
2477 		execmem_free(initfree->init_data);
2478 		execmem_free(initfree->init_rodata);
2479 		kfree(initfree);
2480 	}
2481 }
2482 
2483 void flush_module_init_free_work(void)
2484 {
2485 	flush_work(&init_free_wq);
2486 }
2487 
2488 #undef MODULE_PARAM_PREFIX
2489 #define MODULE_PARAM_PREFIX "module."
2490 /* Default value for module->async_probe_requested */
2491 static bool async_probe;
2492 module_param(async_probe, bool, 0644);
2493 
2494 /*
2495  * This is where the real work happens.
2496  *
2497  * Keep it uninlined to provide a reliable breakpoint target, e.g. for the gdb
2498  * helper command 'lx-symbols'.
2499  */
2500 static noinline int do_init_module(struct module *mod)
2501 {
2502 	int ret = 0;
2503 	struct mod_initfree *freeinit;
2504 #if defined(CONFIG_MODULE_STATS)
2505 	unsigned int text_size = 0, total_size = 0;
2506 
2507 	for_each_mod_mem_type(type) {
2508 		const struct module_memory *mod_mem = &mod->mem[type];
2509 		if (mod_mem->size) {
2510 			total_size += mod_mem->size;
2511 			if (type == MOD_TEXT || type == MOD_INIT_TEXT)
2512 				text_size += mod_mem->size;
2513 		}
2514 	}
2515 #endif
2516 
2517 	freeinit = kmalloc(sizeof(*freeinit), GFP_KERNEL);
2518 	if (!freeinit) {
2519 		ret = -ENOMEM;
2520 		goto fail;
2521 	}
2522 	freeinit->init_text = mod->mem[MOD_INIT_TEXT].base;
2523 	freeinit->init_data = mod->mem[MOD_INIT_DATA].base;
2524 	freeinit->init_rodata = mod->mem[MOD_INIT_RODATA].base;
2525 
2526 	do_mod_ctors(mod);
2527 	/* Start the module */
2528 	if (mod->init != NULL)
2529 		ret = do_one_initcall(mod->init);
2530 	if (ret < 0) {
2531 		goto fail_free_freeinit;
2532 	}
2533 	if (ret > 0) {
2534 		pr_warn("%s: '%s'->init suspiciously returned %d, it should "
2535 			"follow 0/-E convention\n"
2536 			"%s: loading module anyway...\n",
2537 			__func__, mod->name, ret, __func__);
2538 		dump_stack();
2539 	}
2540 
2541 	/* Now it's a first class citizen! */
2542 	mod->state = MODULE_STATE_LIVE;
2543 	blocking_notifier_call_chain(&module_notify_list,
2544 				     MODULE_STATE_LIVE, mod);
2545 
2546 	/* Delay uevent until module has finished its init routine */
2547 	kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
2548 
2549 	/*
2550 	 * We need to finish all async code before the module init sequence
2551 	 * is done. This has potential to deadlock if synchronous module
2552 	 * loading is requested from async (which is not allowed!).
2553 	 *
2554 	 * See commit 0fdff3ec6d87 ("async, kmod: warn on synchronous
2555 	 * request_module() from async workers") for more details.
2556 	 */
2557 	if (!mod->async_probe_requested)
2558 		async_synchronize_full();
2559 
2560 	ftrace_free_mem(mod, mod->mem[MOD_INIT_TEXT].base,
2561 			mod->mem[MOD_INIT_TEXT].base + mod->mem[MOD_INIT_TEXT].size);
2562 	mutex_lock(&module_mutex);
2563 	/* Drop initial reference. */
2564 	module_put(mod);
2565 	trim_init_extable(mod);
2566 #ifdef CONFIG_KALLSYMS
2567 	/* Switch to core kallsyms now init is done: kallsyms may be walking! */
2568 	rcu_assign_pointer(mod->kallsyms, &mod->core_kallsyms);
2569 #endif
2570 	ret = module_enable_rodata_ro(mod, true);
2571 	if (ret)
2572 		goto fail_mutex_unlock;
2573 	mod_tree_remove_init(mod);
2574 	module_arch_freeing_init(mod);
2575 	for_class_mod_mem_type(type, init) {
2576 		mod->mem[type].base = NULL;
2577 		mod->mem[type].size = 0;
2578 	}
2579 
2580 #ifdef CONFIG_DEBUG_INFO_BTF_MODULES
2581 	/* .BTF is not SHF_ALLOC and will get removed, so sanitize pointer */
2582 	mod->btf_data = NULL;
2583 #endif
2584 	/*
2585 	 * We want to free module_init, but be aware that kallsyms may be
2586 	 * walking this with preempt disabled.  In all the failure paths, we
2587 	 * call synchronize_rcu(), but we don't want to slow down the success
2588 	 * path. execmem_free() cannot be called in an interrupt, so do the
2589 	 * work and call synchronize_rcu() in a work queue.
2590 	 *
2591 	 * Note that execmem_alloc() on most architectures creates W+X page
2592 	 * mappings which won't be cleaned up until do_free_init() runs.  Any
2593 	 * code such as mark_rodata_ro() which depends on those mappings to
2594 	 * be cleaned up needs to sync with the queued work by invoking
2595 	 * flush_module_init_free_work().
2596 	 */
2597 	if (llist_add(&freeinit->node, &init_free_list))
2598 		schedule_work(&init_free_wq);
2599 
2600 	mutex_unlock(&module_mutex);
2601 	wake_up_all(&module_wq);
2602 
2603 	mod_stat_add_long(text_size, &total_text_size);
2604 	mod_stat_add_long(total_size, &total_mod_size);
2605 
2606 	mod_stat_inc(&modcount);
2607 
2608 	return 0;
2609 
2610 fail_mutex_unlock:
2611 	mutex_unlock(&module_mutex);
2612 fail_free_freeinit:
2613 	kfree(freeinit);
2614 fail:
2615 	/* Try to protect us from buggy refcounters. */
2616 	mod->state = MODULE_STATE_GOING;
2617 	synchronize_rcu();
2618 	module_put(mod);
2619 	blocking_notifier_call_chain(&module_notify_list,
2620 				     MODULE_STATE_GOING, mod);
2621 	klp_module_going(mod);
2622 	ftrace_release_mod(mod);
2623 	free_module(mod);
2624 	wake_up_all(&module_wq);
2625 
2626 	return ret;
2627 }
2628 
2629 static int may_init_module(void)
2630 {
2631 	if (!capable(CAP_SYS_MODULE) || modules_disabled)
2632 		return -EPERM;
2633 
2634 	return 0;
2635 }
2636 
2637 /* Is this module of this name done loading?  No locks held. */
2638 static bool finished_loading(const char *name)
2639 {
2640 	struct module *mod;
2641 	bool ret;
2642 
2643 	/*
2644 	 * The module_mutex should not be a heavily contended lock;
2645 	 * if we get the occasional sleep here, we'll go an extra iteration
2646 	 * in the wait_event_interruptible(), which is harmless.
2647 	 */
2648 	sched_annotate_sleep();
2649 	mutex_lock(&module_mutex);
2650 	mod = find_module_all(name, strlen(name), true);
2651 	ret = !mod || mod->state == MODULE_STATE_LIVE
2652 		|| mod->state == MODULE_STATE_GOING;
2653 	mutex_unlock(&module_mutex);
2654 
2655 	return ret;
2656 }
2657 
2658 /* Must be called with module_mutex held */
2659 static int module_patient_check_exists(const char *name,
2660 				       enum fail_dup_mod_reason reason)
2661 {
2662 	struct module *old;
2663 	int err = 0;
2664 
2665 	old = find_module_all(name, strlen(name), true);
2666 	if (old == NULL)
2667 		return 0;
2668 
2669 	if (old->state == MODULE_STATE_COMING ||
2670 	    old->state == MODULE_STATE_UNFORMED) {
2671 		/* Wait in case it fails to load. */
2672 		mutex_unlock(&module_mutex);
2673 		err = wait_event_interruptible(module_wq,
2674 				       finished_loading(name));
2675 		mutex_lock(&module_mutex);
2676 		if (err)
2677 			return err;
2678 
2679 		/* The module might have gone in the meantime. */
2680 		old = find_module_all(name, strlen(name), true);
2681 	}
2682 
2683 	if (try_add_failed_module(name, reason))
2684 		pr_warn("Could not add fail-tracking for module: %s\n", name);
2685 
2686 	/*
2687 	 * We are here only when the same module was being loaded. Do
2688 	 * not try to load it again right now. It prevents long delays
2689 	 * caused by serialized module load failures. It might happen
2690 	 * when more devices of the same type trigger load of
2691 	 * a particular module.
2692 	 */
2693 	if (old && old->state == MODULE_STATE_LIVE)
2694 		return -EEXIST;
2695 	return -EBUSY;
2696 }
2697 
2698 /*
2699  * We try to place it in the list now to make sure it's unique before
2700  * we dedicate too many resources.  In particular, temporary percpu
2701  * memory exhaustion.
2702  */
2703 static int add_unformed_module(struct module *mod)
2704 {
2705 	int err;
2706 
2707 	mod->state = MODULE_STATE_UNFORMED;
2708 
2709 	mutex_lock(&module_mutex);
2710 	err = module_patient_check_exists(mod->name, FAIL_DUP_MOD_LOAD);
2711 	if (err)
2712 		goto out;
2713 
2714 	mod_update_bounds(mod);
2715 	list_add_rcu(&mod->list, &modules);
2716 	mod_tree_insert(mod);
2717 	err = 0;
2718 
2719 out:
2720 	mutex_unlock(&module_mutex);
2721 	return err;
2722 }
2723 
2724 static int complete_formation(struct module *mod, struct load_info *info)
2725 {
2726 	int err;
2727 
2728 	mutex_lock(&module_mutex);
2729 
2730 	/* Find duplicate symbols (must be called under lock). */
2731 	err = verify_exported_symbols(mod);
2732 	if (err < 0)
2733 		goto out;
2734 
2735 	/* These rely on module_mutex for list integrity. */
2736 	module_bug_finalize(info->hdr, info->sechdrs, mod);
2737 	module_cfi_finalize(info->hdr, info->sechdrs, mod);
2738 
2739 	err = module_enable_rodata_ro(mod, false);
2740 	if (err)
2741 		goto out_strict_rwx;
2742 	err = module_enable_data_nx(mod);
2743 	if (err)
2744 		goto out_strict_rwx;
2745 	err = module_enable_text_rox(mod);
2746 	if (err)
2747 		goto out_strict_rwx;
2748 
2749 	/*
2750 	 * Mark state as coming so strong_try_module_get() ignores us,
2751 	 * but kallsyms etc. can see us.
2752 	 */
2753 	mod->state = MODULE_STATE_COMING;
2754 	mutex_unlock(&module_mutex);
2755 
2756 	return 0;
2757 
2758 out_strict_rwx:
2759 	module_bug_cleanup(mod);
2760 out:
2761 	mutex_unlock(&module_mutex);
2762 	return err;
2763 }
2764 
2765 static int prepare_coming_module(struct module *mod)
2766 {
2767 	int err;
2768 
2769 	ftrace_module_enable(mod);
2770 	err = klp_module_coming(mod);
2771 	if (err)
2772 		return err;
2773 
2774 	err = blocking_notifier_call_chain_robust(&module_notify_list,
2775 			MODULE_STATE_COMING, MODULE_STATE_GOING, mod);
2776 	err = notifier_to_errno(err);
2777 	if (err)
2778 		klp_module_going(mod);
2779 
2780 	return err;
2781 }
2782 
2783 static int unknown_module_param_cb(char *param, char *val, const char *modname,
2784 				   void *arg)
2785 {
2786 	struct module *mod = arg;
2787 	int ret;
2788 
2789 	if (strcmp(param, "async_probe") == 0) {
2790 		if (kstrtobool(val, &mod->async_probe_requested))
2791 			mod->async_probe_requested = true;
2792 		return 0;
2793 	}
2794 
2795 	/* Check for magic 'dyndbg' arg */
2796 	ret = ddebug_dyndbg_module_param_cb(param, val, modname);
2797 	if (ret != 0)
2798 		pr_warn("%s: unknown parameter '%s' ignored\n", modname, param);
2799 	return 0;
2800 }
2801 
2802 /* Module within temporary copy, this doesn't do any allocation  */
2803 static int early_mod_check(struct load_info *info, int flags)
2804 {
2805 	int err;
2806 
2807 	/*
2808 	 * Now that we know we have the correct module name, check
2809 	 * if it's blacklisted.
2810 	 */
2811 	if (blacklisted(info->name)) {
2812 		pr_err("Module %s is blacklisted\n", info->name);
2813 		return -EPERM;
2814 	}
2815 
2816 	err = rewrite_section_headers(info, flags);
2817 	if (err)
2818 		return err;
2819 
2820 	/* Check module struct version now, before we try to use module. */
2821 	if (!check_modstruct_version(info, info->mod))
2822 		return -ENOEXEC;
2823 
2824 	err = check_modinfo(info->mod, info, flags);
2825 	if (err)
2826 		return err;
2827 
2828 	mutex_lock(&module_mutex);
2829 	err = module_patient_check_exists(info->mod->name, FAIL_DUP_MOD_BECOMING);
2830 	mutex_unlock(&module_mutex);
2831 
2832 	return err;
2833 }
2834 
2835 /*
2836  * Allocate and load the module: note that size of section 0 is always
2837  * zero, and we rely on this for optional sections.
2838  */
2839 static int load_module(struct load_info *info, const char __user *uargs,
2840 		       int flags)
2841 {
2842 	struct module *mod;
2843 	bool module_allocated = false;
2844 	long err = 0;
2845 	char *after_dashes;
2846 
2847 	/*
2848 	 * Do the signature check (if any) first. All that
2849 	 * the signature check needs is info->len, it does
2850 	 * not need any of the section info. That can be
2851 	 * set up later. This will minimize the chances
2852 	 * of a corrupt module causing problems before
2853 	 * we even get to the signature check.
2854 	 *
2855 	 * The check will also adjust info->len by stripping
2856 	 * off the sig length at the end of the module, making
2857 	 * checks against info->len more correct.
2858 	 */
2859 	err = module_sig_check(info, flags);
2860 	if (err)
2861 		goto free_copy;
2862 
2863 	/*
2864 	 * Do basic sanity checks against the ELF header and
2865 	 * sections. Cache useful sections and set the
2866 	 * info->mod to the userspace passed struct module.
2867 	 */
2868 	err = elf_validity_cache_copy(info, flags);
2869 	if (err)
2870 		goto free_copy;
2871 
2872 	err = early_mod_check(info, flags);
2873 	if (err)
2874 		goto free_copy;
2875 
2876 	/* Figure out module layout, and allocate all the memory. */
2877 	mod = layout_and_allocate(info, flags);
2878 	if (IS_ERR(mod)) {
2879 		err = PTR_ERR(mod);
2880 		goto free_copy;
2881 	}
2882 
2883 	module_allocated = true;
2884 
2885 	audit_log_kern_module(mod->name);
2886 
2887 	/* Reserve our place in the list. */
2888 	err = add_unformed_module(mod);
2889 	if (err)
2890 		goto free_module;
2891 
2892 	/*
2893 	 * We are tainting your kernel if your module gets into
2894 	 * the modules linked list somehow.
2895 	 */
2896 	module_augment_kernel_taints(mod, info);
2897 
2898 	/* To avoid stressing percpu allocator, do this once we're unique. */
2899 	err = percpu_modalloc(mod, info);
2900 	if (err)
2901 		goto unlink_mod;
2902 
2903 	/* Now module is in final location, initialize linked lists, etc. */
2904 	err = module_unload_init(mod);
2905 	if (err)
2906 		goto unlink_mod;
2907 
2908 	init_param_lock(mod);
2909 
2910 	/*
2911 	 * Now we've got everything in the final locations, we can
2912 	 * find optional sections.
2913 	 */
2914 	err = find_module_sections(mod, info);
2915 	if (err)
2916 		goto free_unload;
2917 
2918 	err = check_export_symbol_versions(mod);
2919 	if (err)
2920 		goto free_unload;
2921 
2922 	/* Set up MODINFO_ATTR fields */
2923 	setup_modinfo(mod, info);
2924 
2925 	/* Fix up syms, so that st_value is a pointer to location. */
2926 	err = simplify_symbols(mod, info);
2927 	if (err < 0)
2928 		goto free_modinfo;
2929 
2930 	err = apply_relocations(mod, info);
2931 	if (err < 0)
2932 		goto free_modinfo;
2933 
2934 	err = post_relocation(mod, info);
2935 	if (err < 0)
2936 		goto free_modinfo;
2937 
2938 	flush_module_icache(mod);
2939 
2940 	/* Now copy in args */
2941 	mod->args = strndup_user(uargs, ~0UL >> 1);
2942 	if (IS_ERR(mod->args)) {
2943 		err = PTR_ERR(mod->args);
2944 		goto free_arch_cleanup;
2945 	}
2946 
2947 	init_build_id(mod, info);
2948 
2949 	/* Ftrace init must be called in the MODULE_STATE_UNFORMED state */
2950 	ftrace_module_init(mod);
2951 
2952 	/* Finally it's fully formed, ready to start executing. */
2953 	err = complete_formation(mod, info);
2954 	if (err)
2955 		goto ddebug_cleanup;
2956 
2957 	err = prepare_coming_module(mod);
2958 	if (err)
2959 		goto bug_cleanup;
2960 
2961 	mod->async_probe_requested = async_probe;
2962 
2963 	/* Module is ready to execute: parsing args may do that. */
2964 	after_dashes = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,
2965 				  -32768, 32767, mod,
2966 				  unknown_module_param_cb);
2967 	if (IS_ERR(after_dashes)) {
2968 		err = PTR_ERR(after_dashes);
2969 		goto coming_cleanup;
2970 	} else if (after_dashes) {
2971 		pr_warn("%s: parameters '%s' after `--' ignored\n",
2972 		       mod->name, after_dashes);
2973 	}
2974 
2975 	/* Link in to sysfs. */
2976 	err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
2977 	if (err < 0)
2978 		goto coming_cleanup;
2979 
2980 	if (is_livepatch_module(mod)) {
2981 		err = copy_module_elf(mod, info);
2982 		if (err < 0)
2983 			goto sysfs_cleanup;
2984 	}
2985 
2986 	/* Get rid of temporary copy. */
2987 	free_copy(info, flags);
2988 
2989 	/* Done! */
2990 	trace_module_load(mod);
2991 
2992 	return do_init_module(mod);
2993 
2994  sysfs_cleanup:
2995 	mod_sysfs_teardown(mod);
2996  coming_cleanup:
2997 	mod->state = MODULE_STATE_GOING;
2998 	destroy_params(mod->kp, mod->num_kp);
2999 	blocking_notifier_call_chain(&module_notify_list,
3000 				     MODULE_STATE_GOING, mod);
3001 	klp_module_going(mod);
3002  bug_cleanup:
3003 	mod->state = MODULE_STATE_GOING;
3004 	/* module_bug_cleanup needs module_mutex protection */
3005 	mutex_lock(&module_mutex);
3006 	module_bug_cleanup(mod);
3007 	mutex_unlock(&module_mutex);
3008 
3009  ddebug_cleanup:
3010 	ftrace_release_mod(mod);
3011 	synchronize_rcu();
3012 	kfree(mod->args);
3013  free_arch_cleanup:
3014 	module_arch_cleanup(mod);
3015  free_modinfo:
3016 	free_modinfo(mod);
3017  free_unload:
3018 	module_unload_free(mod);
3019  unlink_mod:
3020 	mutex_lock(&module_mutex);
3021 	/* Unlink carefully: kallsyms could be walking list. */
3022 	list_del_rcu(&mod->list);
3023 	mod_tree_remove(mod);
3024 	wake_up_all(&module_wq);
3025 	/* Wait for RCU-sched synchronizing before releasing mod->list. */
3026 	synchronize_rcu();
3027 	mutex_unlock(&module_mutex);
3028  free_module:
3029 	mod_stat_bump_invalid(info, flags);
3030 	/* Free lock-classes; relies on the preceding sync_rcu() */
3031 	for_class_mod_mem_type(type, core_data) {
3032 		lockdep_free_key_range(mod->mem[type].base,
3033 				       mod->mem[type].size);
3034 	}
3035 
3036 	module_deallocate(mod, info);
3037  free_copy:
3038 	/*
3039 	 * The info->len is always set. We distinguish between
3040 	 * failures once the proper module was allocated and
3041 	 * before that.
3042 	 */
3043 	if (!module_allocated)
3044 		mod_stat_bump_becoming(info, flags);
3045 	free_copy(info, flags);
3046 	return err;
3047 }
3048 
3049 SYSCALL_DEFINE3(init_module, void __user *, umod,
3050 		unsigned long, len, const char __user *, uargs)
3051 {
3052 	int err;
3053 	struct load_info info = { };
3054 
3055 	err = may_init_module();
3056 	if (err)
3057 		return err;
3058 
3059 	pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",
3060 	       umod, len, uargs);
3061 
3062 	err = copy_module_from_user(umod, len, &info);
3063 	if (err) {
3064 		mod_stat_inc(&failed_kreads);
3065 		mod_stat_add_long(len, &invalid_kread_bytes);
3066 		return err;
3067 	}
3068 
3069 	return load_module(&info, uargs, 0);
3070 }
3071 
3072 struct idempotent {
3073 	const void *cookie;
3074 	struct hlist_node entry;
3075 	struct completion complete;
3076 	int ret;
3077 };
3078 
3079 #define IDEM_HASH_BITS 8
3080 static struct hlist_head idem_hash[1 << IDEM_HASH_BITS];
3081 static DEFINE_SPINLOCK(idem_lock);
3082 
3083 static bool idempotent(struct idempotent *u, const void *cookie)
3084 {
3085 	int hash = hash_ptr(cookie, IDEM_HASH_BITS);
3086 	struct hlist_head *head = idem_hash + hash;
3087 	struct idempotent *existing;
3088 	bool first;
3089 
3090 	u->ret = 0;
3091 	u->cookie = cookie;
3092 	init_completion(&u->complete);
3093 
3094 	spin_lock(&idem_lock);
3095 	first = true;
3096 	hlist_for_each_entry(existing, head, entry) {
3097 		if (existing->cookie != cookie)
3098 			continue;
3099 		first = false;
3100 		break;
3101 	}
3102 	hlist_add_head(&u->entry, idem_hash + hash);
3103 	spin_unlock(&idem_lock);
3104 
3105 	return !first;
3106 }
3107 
3108 /*
3109  * We were the first one with 'cookie' on the list, and we ended
3110  * up completing the operation. We now need to walk the list,
3111  * remove everybody - which includes ourselves - fill in the return
3112  * value, and then complete the operation.
3113  */
3114 static int idempotent_complete(struct idempotent *u, int ret)
3115 {
3116 	const void *cookie = u->cookie;
3117 	int hash = hash_ptr(cookie, IDEM_HASH_BITS);
3118 	struct hlist_head *head = idem_hash + hash;
3119 	struct hlist_node *next;
3120 	struct idempotent *pos;
3121 
3122 	spin_lock(&idem_lock);
3123 	hlist_for_each_entry_safe(pos, next, head, entry) {
3124 		if (pos->cookie != cookie)
3125 			continue;
3126 		hlist_del(&pos->entry);
3127 		pos->ret = ret;
3128 		complete(&pos->complete);
3129 	}
3130 	spin_unlock(&idem_lock);
3131 	return ret;
3132 }
3133 
3134 static int init_module_from_file(struct file *f, const char __user * uargs, int flags)
3135 {
3136 	struct load_info info = { };
3137 	void *buf = NULL;
3138 	int len;
3139 
3140 	len = kernel_read_file(f, 0, &buf, INT_MAX, NULL, READING_MODULE);
3141 	if (len < 0) {
3142 		mod_stat_inc(&failed_kreads);
3143 		return len;
3144 	}
3145 
3146 	if (flags & MODULE_INIT_COMPRESSED_FILE) {
3147 		int err = module_decompress(&info, buf, len);
3148 		vfree(buf); /* compressed data is no longer needed */
3149 		if (err) {
3150 			mod_stat_inc(&failed_decompress);
3151 			mod_stat_add_long(len, &invalid_decompress_bytes);
3152 			return err;
3153 		}
3154 	} else {
3155 		info.hdr = buf;
3156 		info.len = len;
3157 	}
3158 
3159 	return load_module(&info, uargs, flags);
3160 }
3161 
3162 static int idempotent_init_module(struct file *f, const char __user * uargs, int flags)
3163 {
3164 	struct idempotent idem;
3165 
3166 	if (!f || !(f->f_mode & FMODE_READ))
3167 		return -EBADF;
3168 
3169 	/* See if somebody else is doing the operation? */
3170 	if (idempotent(&idem, file_inode(f))) {
3171 		wait_for_completion(&idem.complete);
3172 		return idem.ret;
3173 	}
3174 
3175 	/* Otherwise, we'll do it and complete others */
3176 	return idempotent_complete(&idem,
3177 		init_module_from_file(f, uargs, flags));
3178 }
3179 
3180 SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
3181 {
3182 	int err;
3183 	struct fd f;
3184 
3185 	err = may_init_module();
3186 	if (err)
3187 		return err;
3188 
3189 	pr_debug("finit_module: fd=%d, uargs=%p, flags=%i\n", fd, uargs, flags);
3190 
3191 	if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
3192 		      |MODULE_INIT_IGNORE_VERMAGIC
3193 		      |MODULE_INIT_COMPRESSED_FILE))
3194 		return -EINVAL;
3195 
3196 	f = fdget(fd);
3197 	err = idempotent_init_module(f.file, uargs, flags);
3198 	fdput(f);
3199 	return err;
3200 }
3201 
3202 /* Keep in sync with MODULE_FLAGS_BUF_SIZE !!! */
3203 char *module_flags(struct module *mod, char *buf, bool show_state)
3204 {
3205 	int bx = 0;
3206 
3207 	BUG_ON(mod->state == MODULE_STATE_UNFORMED);
3208 	if (!mod->taints && !show_state)
3209 		goto out;
3210 	if (mod->taints ||
3211 	    mod->state == MODULE_STATE_GOING ||
3212 	    mod->state == MODULE_STATE_COMING) {
3213 		buf[bx++] = '(';
3214 		bx += module_flags_taint(mod->taints, buf + bx);
3215 		/* Show a - for module-is-being-unloaded */
3216 		if (mod->state == MODULE_STATE_GOING && show_state)
3217 			buf[bx++] = '-';
3218 		/* Show a + for module-is-being-loaded */
3219 		if (mod->state == MODULE_STATE_COMING && show_state)
3220 			buf[bx++] = '+';
3221 		buf[bx++] = ')';
3222 	}
3223 out:
3224 	buf[bx] = '\0';
3225 
3226 	return buf;
3227 }
3228 
3229 /* Given an address, look for it in the module exception tables. */
3230 const struct exception_table_entry *search_module_extables(unsigned long addr)
3231 {
3232 	const struct exception_table_entry *e = NULL;
3233 	struct module *mod;
3234 
3235 	preempt_disable();
3236 	mod = __module_address(addr);
3237 	if (!mod)
3238 		goto out;
3239 
3240 	if (!mod->num_exentries)
3241 		goto out;
3242 
3243 	e = search_extable(mod->extable,
3244 			   mod->num_exentries,
3245 			   addr);
3246 out:
3247 	preempt_enable();
3248 
3249 	/*
3250 	 * Now, if we found one, we are running inside it now, hence
3251 	 * we cannot unload the module, hence no refcnt needed.
3252 	 */
3253 	return e;
3254 }
3255 
3256 /**
3257  * is_module_address() - is this address inside a module?
3258  * @addr: the address to check.
3259  *
3260  * See is_module_text_address() if you simply want to see if the address
3261  * is code (not data).
3262  */
3263 bool is_module_address(unsigned long addr)
3264 {
3265 	bool ret;
3266 
3267 	preempt_disable();
3268 	ret = __module_address(addr) != NULL;
3269 	preempt_enable();
3270 
3271 	return ret;
3272 }
3273 
3274 /**
3275  * __module_address() - get the module which contains an address.
3276  * @addr: the address.
3277  *
3278  * Must be called with preempt disabled or module mutex held so that
3279  * module doesn't get freed during this.
3280  */
3281 struct module *__module_address(unsigned long addr)
3282 {
3283 	struct module *mod;
3284 
3285 	if (addr >= mod_tree.addr_min && addr <= mod_tree.addr_max)
3286 		goto lookup;
3287 
3288 #ifdef CONFIG_ARCH_WANTS_MODULES_DATA_IN_VMALLOC
3289 	if (addr >= mod_tree.data_addr_min && addr <= mod_tree.data_addr_max)
3290 		goto lookup;
3291 #endif
3292 
3293 	return NULL;
3294 
3295 lookup:
3296 	module_assert_mutex_or_preempt();
3297 
3298 	mod = mod_find(addr, &mod_tree);
3299 	if (mod) {
3300 		BUG_ON(!within_module(addr, mod));
3301 		if (mod->state == MODULE_STATE_UNFORMED)
3302 			mod = NULL;
3303 	}
3304 	return mod;
3305 }
3306 
3307 /**
3308  * is_module_text_address() - is this address inside module code?
3309  * @addr: the address to check.
3310  *
3311  * See is_module_address() if you simply want to see if the address is
3312  * anywhere in a module.  See kernel_text_address() for testing if an
3313  * address corresponds to kernel or module code.
3314  */
3315 bool is_module_text_address(unsigned long addr)
3316 {
3317 	bool ret;
3318 
3319 	preempt_disable();
3320 	ret = __module_text_address(addr) != NULL;
3321 	preempt_enable();
3322 
3323 	return ret;
3324 }
3325 
3326 /**
3327  * __module_text_address() - get the module whose code contains an address.
3328  * @addr: the address.
3329  *
3330  * Must be called with preempt disabled or module mutex held so that
3331  * module doesn't get freed during this.
3332  */
3333 struct module *__module_text_address(unsigned long addr)
3334 {
3335 	struct module *mod = __module_address(addr);
3336 	if (mod) {
3337 		/* Make sure it's within the text section. */
3338 		if (!within_module_mem_type(addr, mod, MOD_TEXT) &&
3339 		    !within_module_mem_type(addr, mod, MOD_INIT_TEXT))
3340 			mod = NULL;
3341 	}
3342 	return mod;
3343 }
3344 
3345 /* Don't grab lock, we're oopsing. */
3346 void print_modules(void)
3347 {
3348 	struct module *mod;
3349 	char buf[MODULE_FLAGS_BUF_SIZE];
3350 
3351 	printk(KERN_DEFAULT "Modules linked in:");
3352 	/* Most callers should already have preempt disabled, but make sure */
3353 	preempt_disable();
3354 	list_for_each_entry_rcu(mod, &modules, list) {
3355 		if (mod->state == MODULE_STATE_UNFORMED)
3356 			continue;
3357 		pr_cont(" %s%s", mod->name, module_flags(mod, buf, true));
3358 	}
3359 
3360 	print_unloaded_tainted_modules();
3361 	preempt_enable();
3362 	if (last_unloaded_module.name[0])
3363 		pr_cont(" [last unloaded: %s%s]", last_unloaded_module.name,
3364 			last_unloaded_module.taints);
3365 	pr_cont("\n");
3366 }
3367 
3368 #ifdef CONFIG_MODULE_DEBUGFS
3369 struct dentry *mod_debugfs_root;
3370 
3371 static int module_debugfs_init(void)
3372 {
3373 	mod_debugfs_root = debugfs_create_dir("modules", NULL);
3374 	return 0;
3375 }
3376 module_init(module_debugfs_init);
3377 #endif
3378