1/* Modified by Broadcom Corp. Portions Copyright (c) Broadcom Corp, 2012. */
2/*
3   Copyright (C) 2002 Richard Henderson
4   Copyright (C) 2001 Rusty Russell, 2002, 2010 Rusty Russell IBM.
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19*/
20#include <linux/module.h>
21#include <linux/moduleloader.h>
22#include <linux/ftrace_event.h>
23#include <linux/init.h>
24#include <linux/kallsyms.h>
25#include <linux/fs.h>
26#include <linux/sysfs.h>
27#include <linux/kernel.h>
28#include <linux/slab.h>
29#include <linux/vmalloc.h>
30#include <linux/elf.h>
31#include <linux/proc_fs.h>
32#include <linux/seq_file.h>
33#include <linux/syscalls.h>
34#include <linux/fcntl.h>
35#include <linux/rcupdate.h>
36#include <linux/capability.h>
37#include <linux/cpu.h>
38#include <linux/moduleparam.h>
39#include <linux/errno.h>
40#include <linux/err.h>
41#include <linux/vermagic.h>
42#include <linux/notifier.h>
43#include <linux/sched.h>
44#include <linux/stop_machine.h>
45#include <linux/device.h>
46#include <linux/string.h>
47#include <linux/mutex.h>
48#include <linux/rculist.h>
49#include <asm/uaccess.h>
50#include <asm/cacheflush.h>
51#include <asm/mmu_context.h>
52#include <linux/license.h>
53#include <asm/sections.h>
54#include <linux/tracepoint.h>
55#include <linux/ftrace.h>
56#include <linux/async.h>
57#include <linux/percpu.h>
58#include <linux/kmemleak.h>
59
60#define CREATE_TRACE_POINTS
61#include <trace/events/module.h>
62
63#define DEBUGP(fmt , a...)
64
65#ifndef ARCH_SHF_SMALL
66#define ARCH_SHF_SMALL 0
67#endif
68
69/* If this is set, the section belongs in the init part of the module */
70#define INIT_OFFSET_MASK (1UL << (BITS_PER_LONG-1))
71
72/*
73 * Mutex protects:
74 * 1) List of modules (also safely readable with preempt_disable),
75 * 2) module_use links,
76 * 3) module_addr_min/module_addr_max.
77 * (delete uses stop_machine/add uses RCU list operations). */
78DEFINE_MUTEX(module_mutex);
79EXPORT_SYMBOL_GPL(module_mutex);
80static LIST_HEAD(modules);
81#ifdef CONFIG_KGDB_KDB
82struct list_head *kdb_modules = &modules; /* kdb needs the list of modules */
83#endif /* CONFIG_KGDB_KDB */
84
85
86/* Block module loading/unloading? */
87int modules_disabled = 0;
88
89/* Waiting for a module to finish initializing? */
90static DECLARE_WAIT_QUEUE_HEAD(module_wq);
91
92static BLOCKING_NOTIFIER_HEAD(module_notify_list);
93
94/* Bounds of module allocation, for speeding __module_address.
95 * Protected by module_mutex. */
96static unsigned long module_addr_min = -1UL, module_addr_max = 0;
97
98int register_module_notifier(struct notifier_block * nb)
99{
100	return blocking_notifier_chain_register(&module_notify_list, nb);
101}
102EXPORT_SYMBOL(register_module_notifier);
103
104int unregister_module_notifier(struct notifier_block * nb)
105{
106	return blocking_notifier_chain_unregister(&module_notify_list, nb);
107}
108EXPORT_SYMBOL(unregister_module_notifier);
109
110struct load_info {
111	Elf_Ehdr *hdr;
112	unsigned long len;
113	Elf_Shdr *sechdrs;
114	char *secstrings, *strtab;
115	unsigned long *strmap;
116	unsigned long symoffs, stroffs;
117	struct _ddebug *debug;
118	unsigned int num_debug;
119	struct {
120		unsigned int sym, str, mod, vers, info, pcpu;
121	} index;
122};
123
124/* We require a truly strong try_module_get(): 0 means failure due to
125   ongoing or failed initialization etc. */
126static inline int strong_try_module_get(struct module *mod)
127{
128	if (mod && mod->state == MODULE_STATE_COMING)
129		return -EBUSY;
130	if (try_module_get(mod))
131		return 0;
132	else
133		return -ENOENT;
134}
135
136static inline void add_taint_module(struct module *mod, unsigned flag)
137{
138	add_taint(flag);
139	mod->taints |= (1U << flag);
140}
141
142/*
143 * A thread that wants to hold a reference to a module only while it
144 * is running can call this to safely exit.  nfsd and lockd use this.
145 */
146void __module_put_and_exit(struct module *mod, long code)
147{
148	module_put(mod);
149	do_exit(code);
150}
151EXPORT_SYMBOL(__module_put_and_exit);
152
153/* Find a module section: 0 means not found. */
154static unsigned int find_sec(const struct load_info *info, const char *name)
155{
156	unsigned int i;
157
158	for (i = 1; i < info->hdr->e_shnum; i++) {
159		Elf_Shdr *shdr = &info->sechdrs[i];
160		/* Alloc bit cleared means "ignore it." */
161		if ((shdr->sh_flags & SHF_ALLOC)
162		    && strcmp(info->secstrings + shdr->sh_name, name) == 0)
163			return i;
164	}
165	return 0;
166}
167
168/* Find a module section, or NULL. */
169static void *section_addr(const struct load_info *info, const char *name)
170{
171	/* Section 0 has sh_addr 0. */
172	return (void *)info->sechdrs[find_sec(info, name)].sh_addr;
173}
174
175/* Find a module section, or NULL.  Fill in number of "objects" in section. */
176static void *section_objs(const struct load_info *info,
177			  const char *name,
178			  size_t object_size,
179			  unsigned int *num)
180{
181	unsigned int sec = find_sec(info, name);
182
183	/* Section 0 has sh_addr 0 and sh_size 0. */
184	*num = info->sechdrs[sec].sh_size / object_size;
185	return (void *)info->sechdrs[sec].sh_addr;
186}
187
188/* Provided by the linker */
189extern const struct kernel_symbol __start___ksymtab[];
190extern const struct kernel_symbol __stop___ksymtab[];
191extern const struct kernel_symbol __start___ksymtab_gpl[];
192extern const struct kernel_symbol __stop___ksymtab_gpl[];
193extern const struct kernel_symbol __start___ksymtab_gpl_future[];
194extern const struct kernel_symbol __stop___ksymtab_gpl_future[];
195extern const unsigned long __start___kcrctab[];
196extern const unsigned long __start___kcrctab_gpl[];
197extern const unsigned long __start___kcrctab_gpl_future[];
198#ifdef CONFIG_UNUSED_SYMBOLS
199extern const struct kernel_symbol __start___ksymtab_unused[];
200extern const struct kernel_symbol __stop___ksymtab_unused[];
201extern const struct kernel_symbol __start___ksymtab_unused_gpl[];
202extern const struct kernel_symbol __stop___ksymtab_unused_gpl[];
203extern const unsigned long __start___kcrctab_unused[];
204extern const unsigned long __start___kcrctab_unused_gpl[];
205#endif
206
207#ifndef CONFIG_MODVERSIONS
208#define symversion(base, idx) NULL
209#else
210#define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
211#endif
212
213static bool each_symbol_in_section(const struct symsearch *arr,
214				   unsigned int arrsize,
215				   struct module *owner,
216				   bool (*fn)(const struct symsearch *syms,
217					      struct module *owner,
218					      unsigned int symnum, void *data),
219				   void *data)
220{
221	unsigned int i, j;
222
223	for (j = 0; j < arrsize; j++) {
224		for (i = 0; i < arr[j].stop - arr[j].start; i++)
225			if (fn(&arr[j], owner, i, data))
226				return true;
227	}
228
229	return false;
230}
231
232/* Returns true as soon as fn returns true, otherwise false. */
233bool each_symbol(bool (*fn)(const struct symsearch *arr, struct module *owner,
234			    unsigned int symnum, void *data), void *data)
235{
236	struct module *mod;
237	static const struct symsearch arr[] = {
238		{ __start___ksymtab, __stop___ksymtab, __start___kcrctab,
239		  NOT_GPL_ONLY, false },
240		{ __start___ksymtab_gpl, __stop___ksymtab_gpl,
241		  __start___kcrctab_gpl,
242		  GPL_ONLY, false },
243		{ __start___ksymtab_gpl_future, __stop___ksymtab_gpl_future,
244		  __start___kcrctab_gpl_future,
245		  WILL_BE_GPL_ONLY, false },
246#ifdef CONFIG_UNUSED_SYMBOLS
247		{ __start___ksymtab_unused, __stop___ksymtab_unused,
248		  __start___kcrctab_unused,
249		  NOT_GPL_ONLY, true },
250		{ __start___ksymtab_unused_gpl, __stop___ksymtab_unused_gpl,
251		  __start___kcrctab_unused_gpl,
252		  GPL_ONLY, true },
253#endif
254	};
255
256	if (each_symbol_in_section(arr, ARRAY_SIZE(arr), NULL, fn, data))
257		return true;
258
259	list_for_each_entry_rcu(mod, &modules, list) {
260		struct symsearch arr[] = {
261			{ mod->syms, mod->syms + mod->num_syms, mod->crcs,
262			  NOT_GPL_ONLY, false },
263			{ mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
264			  mod->gpl_crcs,
265			  GPL_ONLY, false },
266			{ mod->gpl_future_syms,
267			  mod->gpl_future_syms + mod->num_gpl_future_syms,
268			  mod->gpl_future_crcs,
269			  WILL_BE_GPL_ONLY, false },
270#ifdef CONFIG_UNUSED_SYMBOLS
271			{ mod->unused_syms,
272			  mod->unused_syms + mod->num_unused_syms,
273			  mod->unused_crcs,
274			  NOT_GPL_ONLY, true },
275			{ mod->unused_gpl_syms,
276			  mod->unused_gpl_syms + mod->num_unused_gpl_syms,
277			  mod->unused_gpl_crcs,
278			  GPL_ONLY, true },
279#endif
280		};
281
282		if (each_symbol_in_section(arr, ARRAY_SIZE(arr), mod, fn, data))
283			return true;
284	}
285	return false;
286}
287EXPORT_SYMBOL_GPL(each_symbol);
288
289struct find_symbol_arg {
290	/* Input */
291	const char *name;
292	bool gplok;
293	bool warn;
294
295	/* Output */
296	struct module *owner;
297	const unsigned long *crc;
298	const struct kernel_symbol *sym;
299};
300
301static bool find_symbol_in_section(const struct symsearch *syms,
302				   struct module *owner,
303				   unsigned int symnum, void *data)
304{
305	struct find_symbol_arg *fsa = data;
306
307	if (strcmp(syms->start[symnum].name, fsa->name) != 0)
308		return false;
309
310	if (!fsa->gplok) {
311		if (syms->licence == GPL_ONLY)
312			return false;
313		if (syms->licence == WILL_BE_GPL_ONLY && fsa->warn) {
314			printk(KERN_WARNING "Symbol %s is being used "
315			       "by a non-GPL module, which will not "
316			       "be allowed in the future\n", fsa->name);
317			printk(KERN_WARNING "Please see the file "
318			       "Documentation/feature-removal-schedule.txt "
319			       "in the kernel source tree for more details.\n");
320		}
321	}
322
323#ifdef CONFIG_UNUSED_SYMBOLS
324	if (syms->unused && fsa->warn) {
325		printk(KERN_WARNING "Symbol %s is marked as UNUSED, "
326		       "however this module is using it.\n", fsa->name);
327		printk(KERN_WARNING
328		       "This symbol will go away in the future.\n");
329		printk(KERN_WARNING
330		       "Please evalute if this is the right api to use and if "
331		       "it really is, submit a report the linux kernel "
332		       "mailinglist together with submitting your code for "
333		       "inclusion.\n");
334	}
335#endif
336
337	fsa->owner = owner;
338	fsa->crc = symversion(syms->crcs, symnum);
339	fsa->sym = &syms->start[symnum];
340	return true;
341}
342
343/* Find a symbol and return it, along with, (optional) crc and
344 * (optional) module which owns it.  Needs preempt disabled or module_mutex. */
345const struct kernel_symbol *find_symbol(const char *name,
346					struct module **owner,
347					const unsigned long **crc,
348					bool gplok,
349					bool warn)
350{
351	struct find_symbol_arg fsa;
352
353	fsa.name = name;
354	fsa.gplok = gplok;
355	fsa.warn = warn;
356
357	if (each_symbol(find_symbol_in_section, &fsa)) {
358		if (owner)
359			*owner = fsa.owner;
360		if (crc)
361			*crc = fsa.crc;
362		return fsa.sym;
363	}
364
365	DEBUGP("Failed to find symbol %s\n", name);
366	return NULL;
367}
368EXPORT_SYMBOL_GPL(find_symbol);
369
370/* Search for module by name: must hold module_mutex. */
371struct module *find_module(const char *name)
372{
373	struct module *mod;
374
375	list_for_each_entry(mod, &modules, list) {
376		if (strcmp(mod->name, name) == 0)
377			return mod;
378	}
379	return NULL;
380}
381EXPORT_SYMBOL_GPL(find_module);
382
383#ifdef CONFIG_SMP
384
385static inline void __percpu *mod_percpu(struct module *mod)
386{
387	return mod->percpu;
388}
389
390static int percpu_modalloc(struct module *mod,
391			   unsigned long size, unsigned long align)
392{
393	if (align > PAGE_SIZE) {
394		printk(KERN_WARNING "%s: per-cpu alignment %li > %li\n",
395		       mod->name, align, PAGE_SIZE);
396		align = PAGE_SIZE;
397	}
398
399	mod->percpu = __alloc_reserved_percpu(size, align);
400	if (!mod->percpu) {
401		printk(KERN_WARNING
402		       "%s: Could not allocate %lu bytes percpu data\n",
403		       mod->name, size);
404		return -ENOMEM;
405	}
406	mod->percpu_size = size;
407	return 0;
408}
409
410static void percpu_modfree(struct module *mod)
411{
412	free_percpu(mod->percpu);
413}
414
415static unsigned int find_pcpusec(struct load_info *info)
416{
417	return find_sec(info, ".data..percpu");
418}
419
420static void percpu_modcopy(struct module *mod,
421			   const void *from, unsigned long size)
422{
423	int cpu;
424
425	for_each_possible_cpu(cpu)
426		memcpy(per_cpu_ptr(mod->percpu, cpu), from, size);
427}
428
429/**
430 * is_module_percpu_address - test whether address is from module static percpu
431 * @addr: address to test
432 *
433 * Test whether @addr belongs to module static percpu area.
434 *
435 * RETURNS:
436 * %true if @addr is from module static percpu area
437 */
438bool is_module_percpu_address(unsigned long addr)
439{
440	struct module *mod;
441	unsigned int cpu;
442
443	preempt_disable();
444
445	list_for_each_entry_rcu(mod, &modules, list) {
446		if (!mod->percpu_size)
447			continue;
448		for_each_possible_cpu(cpu) {
449			void *start = per_cpu_ptr(mod->percpu, cpu);
450
451			if ((void *)addr >= start &&
452			    (void *)addr < start + mod->percpu_size) {
453				preempt_enable();
454				return true;
455			}
456		}
457	}
458
459	preempt_enable();
460	return false;
461}
462
463#else /* ... !CONFIG_SMP */
464
465static inline void __percpu *mod_percpu(struct module *mod)
466{
467	return NULL;
468}
469static inline int percpu_modalloc(struct module *mod,
470				  unsigned long size, unsigned long align)
471{
472	return -ENOMEM;
473}
474static inline void percpu_modfree(struct module *mod)
475{
476}
477static unsigned int find_pcpusec(struct load_info *info)
478{
479	return 0;
480}
481static inline void percpu_modcopy(struct module *mod,
482				  const void *from, unsigned long size)
483{
484	/* pcpusec should be 0, and size of that section should be 0. */
485	BUG_ON(size != 0);
486}
487bool is_module_percpu_address(unsigned long addr)
488{
489	return false;
490}
491
492#endif /* CONFIG_SMP */
493
494#define MODINFO_ATTR(field)	\
495static void setup_modinfo_##field(struct module *mod, const char *s)  \
496{                                                                     \
497	mod->field = kstrdup(s, GFP_KERNEL);                          \
498}                                                                     \
499static ssize_t show_modinfo_##field(struct module_attribute *mattr,   \
500	                struct module *mod, char *buffer)             \
501{                                                                     \
502	return sprintf(buffer, "%s\n", mod->field);                   \
503}                                                                     \
504static int modinfo_##field##_exists(struct module *mod)               \
505{                                                                     \
506	return mod->field != NULL;                                    \
507}                                                                     \
508static void free_modinfo_##field(struct module *mod)                  \
509{                                                                     \
510	kfree(mod->field);                                            \
511	mod->field = NULL;                                            \
512}                                                                     \
513static struct module_attribute modinfo_##field = {                    \
514	.attr = { .name = __stringify(field), .mode = 0444 },         \
515	.show = show_modinfo_##field,                                 \
516	.setup = setup_modinfo_##field,                               \
517	.test = modinfo_##field##_exists,                             \
518	.free = free_modinfo_##field,                                 \
519};
520
521MODINFO_ATTR(version);
522MODINFO_ATTR(srcversion);
523
524static char last_unloaded_module[MODULE_NAME_LEN+1];
525
526#ifdef CONFIG_MODULE_UNLOAD
527
528EXPORT_TRACEPOINT_SYMBOL(module_get);
529
530/* Init the unload section of the module. */
531static int module_unload_init(struct module *mod)
532{
533	mod->refptr = alloc_percpu(struct module_ref);
534	if (!mod->refptr)
535		return -ENOMEM;
536
537	INIT_LIST_HEAD(&mod->source_list);
538	INIT_LIST_HEAD(&mod->target_list);
539
540	/* Hold reference count during initialization. */
541	__this_cpu_write(mod->refptr->incs, 1);
542	/* Backwards compatibility macros put refcount during init. */
543	mod->waiter = current;
544
545	return 0;
546}
547
548/* Does a already use b? */
549static int already_uses(struct module *a, struct module *b)
550{
551	struct module_use *use;
552
553	list_for_each_entry(use, &b->source_list, source_list) {
554		if (use->source == a) {
555			DEBUGP("%s uses %s!\n", a->name, b->name);
556			return 1;
557		}
558	}
559	DEBUGP("%s does not use %s!\n", a->name, b->name);
560	return 0;
561}
562
563/*
564 * Module a uses b
565 *  - we add 'a' as a "source", 'b' as a "target" of module use
566 *  - the module_use is added to the list of 'b' sources (so
567 *    'b' can walk the list to see who sourced them), and of 'a'
568 *    targets (so 'a' can see what modules it targets).
569 */
570static int add_module_usage(struct module *a, struct module *b)
571{
572	struct module_use *use;
573
574	DEBUGP("Allocating new usage for %s.\n", a->name);
575	use = kmalloc(sizeof(*use), GFP_ATOMIC);
576	if (!use) {
577		printk(KERN_WARNING "%s: out of memory loading\n", a->name);
578		return -ENOMEM;
579	}
580
581	use->source = a;
582	use->target = b;
583	list_add(&use->source_list, &b->source_list);
584	list_add(&use->target_list, &a->target_list);
585	return 0;
586}
587
588/* Module a uses b: caller needs module_mutex() */
589int ref_module(struct module *a, struct module *b)
590{
591	int err;
592
593	if (b == NULL || already_uses(a, b))
594		return 0;
595
596	/* If module isn't available, we fail. */
597	err = strong_try_module_get(b);
598	if (err)
599		return err;
600
601	err = add_module_usage(a, b);
602	if (err) {
603		module_put(b);
604		return err;
605	}
606	return 0;
607}
608EXPORT_SYMBOL_GPL(ref_module);
609
610/* Clear the unload stuff of the module. */
611static void module_unload_free(struct module *mod)
612{
613	struct module_use *use, *tmp;
614
615	mutex_lock(&module_mutex);
616	list_for_each_entry_safe(use, tmp, &mod->target_list, target_list) {
617		struct module *i = use->target;
618		DEBUGP("%s unusing %s\n", mod->name, i->name);
619		module_put(i);
620		list_del(&use->source_list);
621		list_del(&use->target_list);
622		kfree(use);
623	}
624	mutex_unlock(&module_mutex);
625
626	free_percpu(mod->refptr);
627}
628
629#ifdef CONFIG_MODULE_FORCE_UNLOAD
630static inline int try_force_unload(unsigned int flags)
631{
632	int ret = (flags & O_TRUNC);
633	if (ret)
634		add_taint(TAINT_FORCED_RMMOD);
635	return ret;
636}
637#else
638static inline int try_force_unload(unsigned int flags)
639{
640	return 0;
641}
642#endif /* CONFIG_MODULE_FORCE_UNLOAD */
643
644struct stopref
645{
646	struct module *mod;
647	int flags;
648	int *forced;
649};
650
651/* Whole machine is stopped with interrupts off when this runs. */
652static int __try_stop_module(void *_sref)
653{
654	struct stopref *sref = _sref;
655
656	/* If it's not unused, quit unless we're forcing. */
657	if (module_refcount(sref->mod) != 0) {
658		if (!(*sref->forced = try_force_unload(sref->flags)))
659			return -EWOULDBLOCK;
660	}
661
662	/* Mark it as dying. */
663	sref->mod->state = MODULE_STATE_GOING;
664	return 0;
665}
666
667static int try_stop_module(struct module *mod, int flags, int *forced)
668{
669	if (flags & O_NONBLOCK) {
670		struct stopref sref = { mod, flags, forced };
671
672		return stop_machine(__try_stop_module, &sref, NULL);
673	} else {
674		/* We don't need to stop the machine for this. */
675		mod->state = MODULE_STATE_GOING;
676		synchronize_sched();
677		return 0;
678	}
679}
680
681unsigned int module_refcount(struct module *mod)
682{
683	unsigned int incs = 0, decs = 0;
684	int cpu;
685
686	for_each_possible_cpu(cpu)
687		decs += per_cpu_ptr(mod->refptr, cpu)->decs;
688	/*
689	 * ensure the incs are added up after the decs.
690	 * module_put ensures incs are visible before decs with smp_wmb.
691	 *
692	 * This 2-count scheme avoids the situation where the refcount
693	 * for CPU0 is read, then CPU0 increments the module refcount,
694	 * then CPU1 drops that refcount, then the refcount for CPU1 is
695	 * read. We would record a decrement but not its corresponding
696	 * increment so we would see a low count (disaster).
697	 *
698	 * Rare situation? But module_refcount can be preempted, and we
699	 * might be tallying up 4096+ CPUs. So it is not impossible.
700	 */
701	smp_rmb();
702	for_each_possible_cpu(cpu)
703		incs += per_cpu_ptr(mod->refptr, cpu)->incs;
704	return incs - decs;
705}
706EXPORT_SYMBOL(module_refcount);
707
708/* This exists whether we can unload or not */
709static void free_module(struct module *mod);
710
711static void wait_for_zero_refcount(struct module *mod)
712{
713	/* Since we might sleep for some time, release the mutex first */
714	mutex_unlock(&module_mutex);
715	for (;;) {
716		DEBUGP("Looking at refcount...\n");
717		set_current_state(TASK_UNINTERRUPTIBLE);
718		if (module_refcount(mod) == 0)
719			break;
720		schedule();
721	}
722	current->state = TASK_RUNNING;
723	mutex_lock(&module_mutex);
724}
725
726SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
727		unsigned int, flags)
728{
729	struct module *mod;
730	char name[MODULE_NAME_LEN];
731	int ret, forced = 0;
732
733	if (!capable(CAP_SYS_MODULE) || modules_disabled)
734		return -EPERM;
735
736	if (strncpy_from_user(name, name_user, MODULE_NAME_LEN-1) < 0)
737		return -EFAULT;
738	name[MODULE_NAME_LEN-1] = '\0';
739
740	if (mutex_lock_interruptible(&module_mutex) != 0)
741		return -EINTR;
742
743	mod = find_module(name);
744	if (!mod) {
745		ret = -ENOENT;
746		goto out;
747	}
748
749	if (!list_empty(&mod->source_list)) {
750		/* Other modules depend on us: get rid of them first. */
751		ret = -EWOULDBLOCK;
752		goto out;
753	}
754
755	/* Doing init or already dying? */
756	if (mod->state != MODULE_STATE_LIVE) {
757		DEBUGP("%s already dying\n", mod->name);
758		ret = -EBUSY;
759		goto out;
760	}
761
762	/* If it has an init func, it must have an exit func to unload */
763	if (mod->init && !mod->exit) {
764		forced = try_force_unload(flags);
765		if (!forced) {
766			/* This module can't be removed */
767			ret = -EBUSY;
768			goto out;
769		}
770	}
771
772	/* Set this up before setting mod->state */
773	mod->waiter = current;
774
775	/* Stop the machine so refcounts can't move and disable module. */
776	ret = try_stop_module(mod, flags, &forced);
777	if (ret != 0)
778		goto out;
779
780	/* Never wait if forced. */
781	if (!forced && module_refcount(mod) != 0)
782		wait_for_zero_refcount(mod);
783
784	mutex_unlock(&module_mutex);
785	/* Final destruction now noone is using it. */
786	if (mod->exit != NULL)
787		mod->exit();
788	blocking_notifier_call_chain(&module_notify_list,
789				     MODULE_STATE_GOING, mod);
790	async_synchronize_full();
791
792	/* Store the name of the last unloaded module for diagnostic purposes */
793	strlcpy(last_unloaded_module, mod->name, sizeof(last_unloaded_module));
794
795	free_module(mod);
796	return 0;
797out:
798	mutex_unlock(&module_mutex);
799	return ret;
800}
801
802static inline void print_unload_info(struct seq_file *m, struct module *mod)
803{
804	struct module_use *use;
805	int printed_something = 0;
806
807	seq_printf(m, " %u ", module_refcount(mod));
808
809	/* Always include a trailing , so userspace can differentiate
810           between this and the old multi-field proc format. */
811	list_for_each_entry(use, &mod->source_list, source_list) {
812		printed_something = 1;
813		seq_printf(m, "%s,", use->source->name);
814	}
815
816	if (mod->init != NULL && mod->exit == NULL) {
817		printed_something = 1;
818		seq_printf(m, "[permanent],");
819	}
820
821	if (!printed_something)
822		seq_printf(m, "-");
823}
824
825void __symbol_put(const char *symbol)
826{
827	struct module *owner;
828
829	preempt_disable();
830	if (!find_symbol(symbol, &owner, NULL, true, false))
831		BUG();
832	module_put(owner);
833	preempt_enable();
834}
835EXPORT_SYMBOL(__symbol_put);
836
837/* Note this assumes addr is a function, which it currently always is. */
838void symbol_put_addr(void *addr)
839{
840	struct module *modaddr;
841	unsigned long a = (unsigned long)dereference_function_descriptor(addr);
842
843	if (core_kernel_text(a))
844		return;
845
846	/* module_text_address is safe here: we're supposed to have reference
847	 * to module from symbol_get, so it can't go away. */
848	modaddr = __module_text_address(a);
849	BUG_ON(!modaddr);
850	module_put(modaddr);
851}
852EXPORT_SYMBOL_GPL(symbol_put_addr);
853
854static ssize_t show_refcnt(struct module_attribute *mattr,
855			   struct module *mod, char *buffer)
856{
857	return sprintf(buffer, "%u\n", module_refcount(mod));
858}
859
860static struct module_attribute refcnt = {
861	.attr = { .name = "refcnt", .mode = 0444 },
862	.show = show_refcnt,
863};
864
865void module_put(struct module *module)
866{
867	if (module) {
868		preempt_disable();
869		smp_wmb(); /* see comment in module_refcount */
870		__this_cpu_inc(module->refptr->decs);
871
872		trace_module_put(module, _RET_IP_);
873		/* Maybe they're waiting for us to drop reference? */
874		if (unlikely(!module_is_live(module)))
875			wake_up_process(module->waiter);
876		preempt_enable();
877	}
878}
879EXPORT_SYMBOL(module_put);
880
881#else /* !CONFIG_MODULE_UNLOAD */
882static inline void print_unload_info(struct seq_file *m, struct module *mod)
883{
884	/* We don't know the usage count, or what modules are using. */
885	seq_printf(m, " - -");
886}
887
888static inline void module_unload_free(struct module *mod)
889{
890}
891
892int ref_module(struct module *a, struct module *b)
893{
894	return strong_try_module_get(b);
895}
896EXPORT_SYMBOL_GPL(ref_module);
897
898static inline int module_unload_init(struct module *mod)
899{
900	return 0;
901}
902#endif /* CONFIG_MODULE_UNLOAD */
903
904static ssize_t show_initstate(struct module_attribute *mattr,
905			   struct module *mod, char *buffer)
906{
907	const char *state = "unknown";
908
909	switch (mod->state) {
910	case MODULE_STATE_LIVE:
911		state = "live";
912		break;
913	case MODULE_STATE_COMING:
914		state = "coming";
915		break;
916	case MODULE_STATE_GOING:
917		state = "going";
918		break;
919	}
920	return sprintf(buffer, "%s\n", state);
921}
922
923static struct module_attribute initstate = {
924	.attr = { .name = "initstate", .mode = 0444 },
925	.show = show_initstate,
926};
927
928static struct module_attribute *modinfo_attrs[] = {
929	&modinfo_version,
930	&modinfo_srcversion,
931	&initstate,
932#ifdef CONFIG_MODULE_UNLOAD
933	&refcnt,
934#endif
935	NULL,
936};
937
938static const char vermagic[] = VERMAGIC_STRING;
939
940static int try_to_force_load(struct module *mod, const char *reason)
941{
942#ifdef CONFIG_MODULE_FORCE_LOAD
943	if (!test_taint(TAINT_FORCED_MODULE))
944		printk(KERN_WARNING "%s: %s: kernel tainted.\n",
945		       mod->name, reason);
946	add_taint_module(mod, TAINT_FORCED_MODULE);
947	return 0;
948#else
949	return -ENOEXEC;
950#endif
951}
952
953#ifdef CONFIG_MODVERSIONS
954/* If the arch applies (non-zero) relocations to kernel kcrctab, unapply it. */
955static unsigned long maybe_relocated(unsigned long crc,
956				     const struct module *crc_owner)
957{
958#ifdef ARCH_RELOCATES_KCRCTAB
959	if (crc_owner == NULL)
960		return crc - (unsigned long)reloc_start;
961#endif
962	return crc;
963}
964
965static int check_version(Elf_Shdr *sechdrs,
966			 unsigned int versindex,
967			 const char *symname,
968			 struct module *mod,
969			 const unsigned long *crc,
970			 const struct module *crc_owner)
971{
972	unsigned int i, num_versions;
973	struct modversion_info *versions;
974
975	/* Exporting module didn't supply crcs?  OK, we're already tainted. */
976	if (!crc)
977		return 1;
978
979	/* No versions at all?  modprobe --force does this. */
980	if (versindex == 0)
981		return try_to_force_load(mod, symname) == 0;
982
983	versions = (void *) sechdrs[versindex].sh_addr;
984	num_versions = sechdrs[versindex].sh_size
985		/ sizeof(struct modversion_info);
986
987	for (i = 0; i < num_versions; i++) {
988		if (strcmp(versions[i].name, symname) != 0)
989			continue;
990
991		if (versions[i].crc == maybe_relocated(*crc, crc_owner))
992			return 1;
993		DEBUGP("Found checksum %lX vs module %lX\n",
994		       maybe_relocated(*crc, crc_owner), versions[i].crc);
995		goto bad_version;
996	}
997
998	printk(KERN_WARNING "%s: no symbol version for %s\n",
999	       mod->name, symname);
1000	return 0;
1001
1002bad_version:
1003	printk("%s: disagrees about version of symbol %s\n",
1004	       mod->name, symname);
1005	return 0;
1006}
1007
1008static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1009					  unsigned int versindex,
1010					  struct module *mod)
1011{
1012	const unsigned long *crc;
1013
1014	/* Since this should be found in kernel (which can't be removed),
1015	 * no locking is necessary. */
1016	if (!find_symbol(MODULE_SYMBOL_PREFIX "module_layout", NULL,
1017			 &crc, true, false))
1018		BUG();
1019	return check_version(sechdrs, versindex, "module_layout", mod, crc,
1020			     NULL);
1021}
1022
1023/* First part is kernel version, which we ignore if module has crcs. */
1024static inline int same_magic(const char *amagic, const char *bmagic,
1025			     bool has_crcs)
1026{
1027	if (has_crcs) {
1028		amagic += strcspn(amagic, " ");
1029		bmagic += strcspn(bmagic, " ");
1030	}
1031	return strcmp(amagic, bmagic) == 0;
1032}
1033#else
1034static inline int check_version(Elf_Shdr *sechdrs,
1035				unsigned int versindex,
1036				const char *symname,
1037				struct module *mod,
1038				const unsigned long *crc,
1039				const struct module *crc_owner)
1040{
1041	return 1;
1042}
1043
1044static inline int check_modstruct_version(Elf_Shdr *sechdrs,
1045					  unsigned int versindex,
1046					  struct module *mod)
1047{
1048	return 1;
1049}
1050
1051static inline int same_magic(const char *amagic, const char *bmagic,
1052			     bool has_crcs)
1053{
1054	return strcmp(amagic, bmagic) == 0;
1055}
1056#endif /* CONFIG_MODVERSIONS */
1057
1058/* Resolve a symbol for this module.  I.e. if we find one, record usage. */
1059static const struct kernel_symbol *resolve_symbol(struct module *mod,
1060						  const struct load_info *info,
1061						  const char *name,
1062						  char ownername[])
1063{
1064	struct module *owner;
1065	const struct kernel_symbol *sym;
1066	const unsigned long *crc;
1067	int err;
1068
1069	mutex_lock(&module_mutex);
1070	sym = find_symbol(name, &owner, &crc,
1071			  !(mod->taints & (1 << TAINT_PROPRIETARY_MODULE)), true);
1072	if (!sym)
1073		goto unlock;
1074
1075	if (!check_version(info->sechdrs, info->index.vers, name, mod, crc,
1076			   owner)) {
1077		sym = ERR_PTR(-EINVAL);
1078		goto getname;
1079	}
1080
1081	err = ref_module(mod, owner);
1082	if (err) {
1083		sym = ERR_PTR(err);
1084		goto getname;
1085	}
1086
1087getname:
1088	/* We must make copy under the lock if we failed to get ref. */
1089	strncpy(ownername, module_name(owner), MODULE_NAME_LEN);
1090unlock:
1091	mutex_unlock(&module_mutex);
1092	return sym;
1093}
1094
1095static const struct kernel_symbol *
1096resolve_symbol_wait(struct module *mod,
1097		    const struct load_info *info,
1098		    const char *name)
1099{
1100	const struct kernel_symbol *ksym;
1101	char owner[MODULE_NAME_LEN];
1102
1103	if (wait_event_interruptible_timeout(module_wq,
1104			!IS_ERR(ksym = resolve_symbol(mod, info, name, owner))
1105			|| PTR_ERR(ksym) != -EBUSY,
1106					     30 * HZ) <= 0) {
1107		printk(KERN_WARNING "%s: gave up waiting for init of module %s.\n",
1108		       mod->name, owner);
1109	}
1110	return ksym;
1111}
1112
1113/*
1114 * /sys/module/foo/sections stuff
1115 * J. Corbet <corbet@lwn.net>
1116 */
1117#ifdef CONFIG_SYSFS
1118
1119#ifdef CONFIG_KALLSYMS
1120static inline bool sect_empty(const Elf_Shdr *sect)
1121{
1122	return !(sect->sh_flags & SHF_ALLOC) || sect->sh_size == 0;
1123}
1124
1125struct module_sect_attr
1126{
1127	struct module_attribute mattr;
1128	char *name;
1129	unsigned long address;
1130};
1131
1132struct module_sect_attrs
1133{
1134	struct attribute_group grp;
1135	unsigned int nsections;
1136	struct module_sect_attr attrs[0];
1137};
1138
1139static ssize_t module_sect_show(struct module_attribute *mattr,
1140				struct module *mod, char *buf)
1141{
1142	struct module_sect_attr *sattr =
1143		container_of(mattr, struct module_sect_attr, mattr);
1144	return sprintf(buf, "0x%lx\n", sattr->address);
1145}
1146
1147static void free_sect_attrs(struct module_sect_attrs *sect_attrs)
1148{
1149	unsigned int section;
1150
1151	for (section = 0; section < sect_attrs->nsections; section++)
1152		kfree(sect_attrs->attrs[section].name);
1153	kfree(sect_attrs);
1154}
1155
1156static void add_sect_attrs(struct module *mod, const struct load_info *info)
1157{
1158	unsigned int nloaded = 0, i, size[2];
1159	struct module_sect_attrs *sect_attrs;
1160	struct module_sect_attr *sattr;
1161	struct attribute **gattr;
1162
1163	/* Count loaded sections and allocate structures */
1164	for (i = 0; i < info->hdr->e_shnum; i++)
1165		if (!sect_empty(&info->sechdrs[i]))
1166			nloaded++;
1167	size[0] = ALIGN(sizeof(*sect_attrs)
1168			+ nloaded * sizeof(sect_attrs->attrs[0]),
1169			sizeof(sect_attrs->grp.attrs[0]));
1170	size[1] = (nloaded + 1) * sizeof(sect_attrs->grp.attrs[0]);
1171	sect_attrs = kzalloc(size[0] + size[1], GFP_KERNEL);
1172	if (sect_attrs == NULL)
1173		return;
1174
1175	/* Setup section attributes. */
1176	sect_attrs->grp.name = "sections";
1177	sect_attrs->grp.attrs = (void *)sect_attrs + size[0];
1178
1179	sect_attrs->nsections = 0;
1180	sattr = &sect_attrs->attrs[0];
1181	gattr = &sect_attrs->grp.attrs[0];
1182	for (i = 0; i < info->hdr->e_shnum; i++) {
1183		Elf_Shdr *sec = &info->sechdrs[i];
1184		if (sect_empty(sec))
1185			continue;
1186		sattr->address = sec->sh_addr;
1187		sattr->name = kstrdup(info->secstrings + sec->sh_name,
1188					GFP_KERNEL);
1189		if (sattr->name == NULL)
1190			goto out;
1191		sect_attrs->nsections++;
1192		sysfs_attr_init(&sattr->mattr.attr);
1193		sattr->mattr.show = module_sect_show;
1194		sattr->mattr.store = NULL;
1195		sattr->mattr.attr.name = sattr->name;
1196		sattr->mattr.attr.mode = S_IRUGO;
1197		*(gattr++) = &(sattr++)->mattr.attr;
1198	}
1199	*gattr = NULL;
1200
1201	if (sysfs_create_group(&mod->mkobj.kobj, &sect_attrs->grp))
1202		goto out;
1203
1204	mod->sect_attrs = sect_attrs;
1205	return;
1206  out:
1207	free_sect_attrs(sect_attrs);
1208}
1209
1210static void remove_sect_attrs(struct module *mod)
1211{
1212	if (mod->sect_attrs) {
1213		sysfs_remove_group(&mod->mkobj.kobj,
1214				   &mod->sect_attrs->grp);
1215		/* We are positive that no one is using any sect attrs
1216		 * at this point.  Deallocate immediately. */
1217		free_sect_attrs(mod->sect_attrs);
1218		mod->sect_attrs = NULL;
1219	}
1220}
1221
1222/*
1223 * /sys/module/foo/notes/.section.name gives contents of SHT_NOTE sections.
1224 */
1225
1226struct module_notes_attrs {
1227	struct kobject *dir;
1228	unsigned int notes;
1229	struct bin_attribute attrs[0];
1230};
1231
1232static ssize_t module_notes_read(struct file *filp, struct kobject *kobj,
1233				 struct bin_attribute *bin_attr,
1234				 char *buf, loff_t pos, size_t count)
1235{
1236	/*
1237	 * The caller checked the pos and count against our size.
1238	 */
1239	memcpy(buf, bin_attr->private + pos, count);
1240	return count;
1241}
1242
1243static void free_notes_attrs(struct module_notes_attrs *notes_attrs,
1244			     unsigned int i)
1245{
1246	if (notes_attrs->dir) {
1247		while (i-- > 0)
1248			sysfs_remove_bin_file(notes_attrs->dir,
1249					      &notes_attrs->attrs[i]);
1250		kobject_put(notes_attrs->dir);
1251	}
1252	kfree(notes_attrs);
1253}
1254
1255static void add_notes_attrs(struct module *mod, const struct load_info *info)
1256{
1257	unsigned int notes, loaded, i;
1258	struct module_notes_attrs *notes_attrs;
1259	struct bin_attribute *nattr;
1260
1261	/* failed to create section attributes, so can't create notes */
1262	if (!mod->sect_attrs)
1263		return;
1264
1265	/* Count notes sections and allocate structures.  */
1266	notes = 0;
1267	for (i = 0; i < info->hdr->e_shnum; i++)
1268		if (!sect_empty(&info->sechdrs[i]) &&
1269		    (info->sechdrs[i].sh_type == SHT_NOTE))
1270			++notes;
1271
1272	if (notes == 0)
1273		return;
1274
1275	notes_attrs = kzalloc(sizeof(*notes_attrs)
1276			      + notes * sizeof(notes_attrs->attrs[0]),
1277			      GFP_KERNEL);
1278	if (notes_attrs == NULL)
1279		return;
1280
1281	notes_attrs->notes = notes;
1282	nattr = &notes_attrs->attrs[0];
1283	for (loaded = i = 0; i < info->hdr->e_shnum; ++i) {
1284		if (sect_empty(&info->sechdrs[i]))
1285			continue;
1286		if (info->sechdrs[i].sh_type == SHT_NOTE) {
1287			sysfs_bin_attr_init(nattr);
1288			nattr->attr.name = mod->sect_attrs->attrs[loaded].name;
1289			nattr->attr.mode = S_IRUGO;
1290			nattr->size = info->sechdrs[i].sh_size;
1291			nattr->private = (void *) info->sechdrs[i].sh_addr;
1292			nattr->read = module_notes_read;
1293			++nattr;
1294		}
1295		++loaded;
1296	}
1297
1298	notes_attrs->dir = kobject_create_and_add("notes", &mod->mkobj.kobj);
1299	if (!notes_attrs->dir)
1300		goto out;
1301
1302	for (i = 0; i < notes; ++i)
1303		if (sysfs_create_bin_file(notes_attrs->dir,
1304					  &notes_attrs->attrs[i]))
1305			goto out;
1306
1307	mod->notes_attrs = notes_attrs;
1308	return;
1309
1310  out:
1311	free_notes_attrs(notes_attrs, i);
1312}
1313
1314static void remove_notes_attrs(struct module *mod)
1315{
1316	if (mod->notes_attrs)
1317		free_notes_attrs(mod->notes_attrs, mod->notes_attrs->notes);
1318}
1319
1320#else
1321
1322static inline void add_sect_attrs(struct module *mod,
1323				  const struct load_info *info)
1324{
1325}
1326
1327static inline void remove_sect_attrs(struct module *mod)
1328{
1329}
1330
1331static inline void add_notes_attrs(struct module *mod,
1332				   const struct load_info *info)
1333{
1334}
1335
1336static inline void remove_notes_attrs(struct module *mod)
1337{
1338}
1339#endif /* CONFIG_KALLSYMS */
1340
1341static void add_usage_links(struct module *mod)
1342{
1343#ifdef CONFIG_MODULE_UNLOAD
1344	struct module_use *use;
1345	int nowarn;
1346
1347	mutex_lock(&module_mutex);
1348	list_for_each_entry(use, &mod->target_list, target_list) {
1349		nowarn = sysfs_create_link(use->target->holders_dir,
1350					   &mod->mkobj.kobj, mod->name);
1351	}
1352	mutex_unlock(&module_mutex);
1353#endif
1354}
1355
1356static void del_usage_links(struct module *mod)
1357{
1358#ifdef CONFIG_MODULE_UNLOAD
1359	struct module_use *use;
1360
1361	mutex_lock(&module_mutex);
1362	list_for_each_entry(use, &mod->target_list, target_list)
1363		sysfs_remove_link(use->target->holders_dir, mod->name);
1364	mutex_unlock(&module_mutex);
1365#endif
1366}
1367
1368static int module_add_modinfo_attrs(struct module *mod)
1369{
1370	struct module_attribute *attr;
1371	struct module_attribute *temp_attr;
1372	int error = 0;
1373	int i;
1374
1375	mod->modinfo_attrs = kzalloc((sizeof(struct module_attribute) *
1376					(ARRAY_SIZE(modinfo_attrs) + 1)),
1377					GFP_KERNEL);
1378	if (!mod->modinfo_attrs)
1379		return -ENOMEM;
1380
1381	temp_attr = mod->modinfo_attrs;
1382	for (i = 0; (attr = modinfo_attrs[i]) && !error; i++) {
1383		if (!attr->test ||
1384		    (attr->test && attr->test(mod))) {
1385			memcpy(temp_attr, attr, sizeof(*temp_attr));
1386			sysfs_attr_init(&temp_attr->attr);
1387			error = sysfs_create_file(&mod->mkobj.kobj,&temp_attr->attr);
1388			++temp_attr;
1389		}
1390	}
1391	return error;
1392}
1393
1394static void module_remove_modinfo_attrs(struct module *mod)
1395{
1396	struct module_attribute *attr;
1397	int i;
1398
1399	for (i = 0; (attr = &mod->modinfo_attrs[i]); i++) {
1400		/* pick a field to test for end of list */
1401		if (!attr->attr.name)
1402			break;
1403		sysfs_remove_file(&mod->mkobj.kobj,&attr->attr);
1404		if (attr->free)
1405			attr->free(mod);
1406	}
1407	kfree(mod->modinfo_attrs);
1408}
1409
1410static int mod_sysfs_init(struct module *mod)
1411{
1412	int err;
1413	struct kobject *kobj;
1414
1415	if (!module_sysfs_initialized) {
1416		printk(KERN_ERR "%s: module sysfs not initialized\n",
1417		       mod->name);
1418		err = -EINVAL;
1419		goto out;
1420	}
1421
1422	kobj = kset_find_obj(module_kset, mod->name);
1423	if (kobj) {
1424		printk(KERN_ERR "%s: module is already loaded\n", mod->name);
1425		kobject_put(kobj);
1426		err = -EINVAL;
1427		goto out;
1428	}
1429
1430	mod->mkobj.mod = mod;
1431
1432	memset(&mod->mkobj.kobj, 0, sizeof(mod->mkobj.kobj));
1433	mod->mkobj.kobj.kset = module_kset;
1434	err = kobject_init_and_add(&mod->mkobj.kobj, &module_ktype, NULL,
1435				   "%s", mod->name);
1436	if (err)
1437		kobject_put(&mod->mkobj.kobj);
1438
1439	/* delay uevent until full sysfs population */
1440out:
1441	return err;
1442}
1443
1444static int mod_sysfs_setup(struct module *mod,
1445			   const struct load_info *info,
1446			   struct kernel_param *kparam,
1447			   unsigned int num_params)
1448{
1449	int err;
1450
1451	err = mod_sysfs_init(mod);
1452	if (err)
1453		goto out;
1454
1455	mod->holders_dir = kobject_create_and_add("holders", &mod->mkobj.kobj);
1456	if (!mod->holders_dir) {
1457		err = -ENOMEM;
1458		goto out_unreg;
1459	}
1460
1461	err = module_param_sysfs_setup(mod, kparam, num_params);
1462	if (err)
1463		goto out_unreg_holders;
1464
1465	err = module_add_modinfo_attrs(mod);
1466	if (err)
1467		goto out_unreg_param;
1468
1469	add_usage_links(mod);
1470	add_sect_attrs(mod, info);
1471	add_notes_attrs(mod, info);
1472
1473	kobject_uevent(&mod->mkobj.kobj, KOBJ_ADD);
1474	return 0;
1475
1476out_unreg_param:
1477	module_param_sysfs_remove(mod);
1478out_unreg_holders:
1479	kobject_put(mod->holders_dir);
1480out_unreg:
1481	kobject_put(&mod->mkobj.kobj);
1482out:
1483	return err;
1484}
1485
1486static void mod_sysfs_fini(struct module *mod)
1487{
1488	remove_notes_attrs(mod);
1489	remove_sect_attrs(mod);
1490	kobject_put(&mod->mkobj.kobj);
1491}
1492
1493#else /* !CONFIG_SYSFS */
1494
1495static int mod_sysfs_setup(struct module *mod,
1496			   const struct load_info *info,
1497			   struct kernel_param *kparam,
1498			   unsigned int num_params)
1499{
1500	return 0;
1501}
1502
1503static void mod_sysfs_fini(struct module *mod)
1504{
1505}
1506
1507static void module_remove_modinfo_attrs(struct module *mod)
1508{
1509}
1510
1511static void del_usage_links(struct module *mod)
1512{
1513}
1514
1515#endif /* CONFIG_SYSFS */
1516
1517static void mod_sysfs_teardown(struct module *mod)
1518{
1519	del_usage_links(mod);
1520	module_remove_modinfo_attrs(mod);
1521	module_param_sysfs_remove(mod);
1522	kobject_put(mod->mkobj.drivers_dir);
1523	kobject_put(mod->holders_dir);
1524	mod_sysfs_fini(mod);
1525}
1526
1527/*
1528 * unlink the module with the whole machine is stopped with interrupts off
1529 * - this defends against kallsyms not taking locks
1530 */
1531static int __unlink_module(void *_mod)
1532{
1533	struct module *mod = _mod;
1534	list_del(&mod->list);
1535	module_bug_cleanup(mod);
1536	return 0;
1537}
1538
1539/* Free a module, remove from lists, etc. */
1540static void free_module(struct module *mod)
1541{
1542	trace_module_free(mod);
1543
1544	/* Delete from various lists */
1545	mutex_lock(&module_mutex);
1546	stop_machine(__unlink_module, mod, NULL);
1547	mutex_unlock(&module_mutex);
1548	mod_sysfs_teardown(mod);
1549
1550	/* Remove dynamic debug info */
1551	ddebug_remove_module(mod->name);
1552
1553	/* Arch-specific cleanup. */
1554	module_arch_cleanup(mod);
1555
1556	/* Module unload stuff */
1557	module_unload_free(mod);
1558
1559	/* Free any allocated parameters. */
1560	destroy_params(mod->kp, mod->num_kp);
1561
1562	/* This may be NULL, but that's OK */
1563	module_free(mod, mod->module_init);
1564	kfree(mod->args);
1565	percpu_modfree(mod);
1566
1567	/* Free lock-classes: */
1568	lockdep_free_key_range(mod->module_core, mod->core_size);
1569
1570	/* Finally, free the core (containing the module structure) */
1571	module_free(mod, mod->module_core);
1572
1573#ifdef CONFIG_MPU
1574	update_protections(current->mm);
1575#endif
1576}
1577
1578void *__symbol_get(const char *symbol)
1579{
1580	struct module *owner;
1581	const struct kernel_symbol *sym;
1582
1583	preempt_disable();
1584	sym = find_symbol(symbol, &owner, NULL, true, true);
1585	if (sym && strong_try_module_get(owner))
1586		sym = NULL;
1587	preempt_enable();
1588
1589	return sym ? (void *)sym->value : NULL;
1590}
1591EXPORT_SYMBOL_GPL(__symbol_get);
1592
1593/*
1594 * Ensure that an exported symbol [global namespace] does not already exist
1595 * in the kernel or in some other module's exported symbol table.
1596 *
1597 * You must hold the module_mutex.
1598 */
1599static int verify_export_symbols(struct module *mod)
1600{
1601	unsigned int i;
1602	struct module *owner;
1603	const struct kernel_symbol *s;
1604	struct {
1605		const struct kernel_symbol *sym;
1606		unsigned int num;
1607	} arr[] = {
1608		{ mod->syms, mod->num_syms },
1609		{ mod->gpl_syms, mod->num_gpl_syms },
1610		{ mod->gpl_future_syms, mod->num_gpl_future_syms },
1611#ifdef CONFIG_UNUSED_SYMBOLS
1612		{ mod->unused_syms, mod->num_unused_syms },
1613		{ mod->unused_gpl_syms, mod->num_unused_gpl_syms },
1614#endif
1615	};
1616
1617	for (i = 0; i < ARRAY_SIZE(arr); i++) {
1618		for (s = arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
1619			if (find_symbol(s->name, &owner, NULL, true, false)) {
1620				printk(KERN_ERR
1621				       "%s: exports duplicate symbol %s"
1622				       " (owned by %s)\n",
1623				       mod->name, s->name, module_name(owner));
1624				return -ENOEXEC;
1625			}
1626		}
1627	}
1628	return 0;
1629}
1630
1631/* Change all symbols so that st_value encodes the pointer directly. */
1632static int simplify_symbols(struct module *mod, const struct load_info *info)
1633{
1634	Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
1635	Elf_Sym *sym = (void *)symsec->sh_addr;
1636	unsigned long secbase;
1637	unsigned int i;
1638	int ret = 0;
1639	const struct kernel_symbol *ksym;
1640
1641	for (i = 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) {
1642		const char *name = info->strtab + sym[i].st_name;
1643
1644		switch (sym[i].st_shndx) {
1645		case SHN_COMMON:
1646			/* We compiled with -fno-common.  These are not
1647			   supposed to happen.  */
1648			DEBUGP("Common symbol: %s\n", name);
1649			printk("%s: please compile with -fno-common\n",
1650			       mod->name);
1651			ret = -ENOEXEC;
1652			break;
1653
1654		case SHN_ABS:
1655			/* Don't need to do anything */
1656			DEBUGP("Absolute symbol: 0x%08lx\n",
1657			       (long)sym[i].st_value);
1658			break;
1659
1660		case SHN_UNDEF:
1661			ksym = resolve_symbol_wait(mod, info, name);
1662			/* Ok if resolved.  */
1663			if (ksym && !IS_ERR(ksym)) {
1664				sym[i].st_value = ksym->value;
1665				break;
1666			}
1667
1668			/* Ok if weak.  */
1669			if (!ksym && ELF_ST_BIND(sym[i].st_info) == STB_WEAK)
1670				break;
1671
1672			printk(KERN_WARNING "%s: Unknown symbol %s (err %li)\n",
1673			       mod->name, name, PTR_ERR(ksym));
1674			ret = PTR_ERR(ksym) ?: -ENOENT;
1675			break;
1676
1677		default:
1678			/* Divert to percpu allocation if a percpu var. */
1679			if (sym[i].st_shndx == info->index.pcpu)
1680				secbase = (unsigned long)mod_percpu(mod);
1681			else
1682				secbase = info->sechdrs[sym[i].st_shndx].sh_addr;
1683			sym[i].st_value += secbase;
1684			break;
1685		}
1686	}
1687
1688	return ret;
1689}
1690
1691static int apply_relocations(struct module *mod, const struct load_info *info)
1692{
1693	unsigned int i;
1694	int err = 0;
1695
1696	/* Now do relocations. */
1697	for (i = 1; i < info->hdr->e_shnum; i++) {
1698		unsigned int infosec = info->sechdrs[i].sh_info;
1699
1700		/* Not a valid relocation section? */
1701		if (infosec >= info->hdr->e_shnum)
1702			continue;
1703
1704		/* Don't bother with non-allocated sections */
1705		if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
1706			continue;
1707
1708		if (info->sechdrs[i].sh_type == SHT_REL)
1709			err = apply_relocate(info->sechdrs, info->strtab,
1710					     info->index.sym, i, mod);
1711		else if (info->sechdrs[i].sh_type == SHT_RELA)
1712			err = apply_relocate_add(info->sechdrs, info->strtab,
1713						 info->index.sym, i, mod);
1714		if (err < 0)
1715			break;
1716	}
1717	return err;
1718}
1719
1720/* Additional bytes needed by arch in front of individual sections */
1721unsigned int __weak arch_mod_section_prepend(struct module *mod,
1722					     unsigned int section)
1723{
1724	/* default implementation just returns zero */
1725	return 0;
1726}
1727
1728/* Update size with this section: return offset. */
1729static long get_offset(struct module *mod, unsigned int *size,
1730		       Elf_Shdr *sechdr, unsigned int section)
1731{
1732	long ret;
1733
1734	*size += arch_mod_section_prepend(mod, section);
1735	ret = ALIGN(*size, sechdr->sh_addralign ?: 1);
1736	*size = ret + sechdr->sh_size;
1737	return ret;
1738}
1739
1740/* Lay out the SHF_ALLOC sections in a way not dissimilar to how ld
1741   might -- code, read-only data, read-write data, small data.  Tally
1742   sizes, and place the offsets into sh_entsize fields: high bit means it
1743   belongs in init. */
1744static void layout_sections(struct module *mod, struct load_info *info)
1745{
1746	static unsigned long const masks[][2] = {
1747		/* NOTE: all executable code must be the first section
1748		 * in this array; otherwise modify the text_size
1749		 * finder in the two loops below */
1750		{ SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },
1751		{ SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },
1752		{ SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },
1753		{ ARCH_SHF_SMALL | SHF_ALLOC, 0 }
1754	};
1755	unsigned int m, i;
1756
1757	for (i = 0; i < info->hdr->e_shnum; i++)
1758		info->sechdrs[i].sh_entsize = ~0UL;
1759
1760	DEBUGP("Core section allocation order:\n");
1761	for (m = 0; m < ARRAY_SIZE(masks); ++m) {
1762		for (i = 0; i < info->hdr->e_shnum; ++i) {
1763			Elf_Shdr *s = &info->sechdrs[i];
1764			const char *sname = info->secstrings + s->sh_name;
1765
1766			if ((s->sh_flags & masks[m][0]) != masks[m][0]
1767			    || (s->sh_flags & masks[m][1])
1768			    || s->sh_entsize != ~0UL
1769			    || strstarts(sname, ".init"))
1770				continue;
1771			s->sh_entsize = get_offset(mod, &mod->core_size, s, i);
1772			DEBUGP("\t%s\n", name);
1773		}
1774		if (m == 0)
1775			mod->core_text_size = mod->core_size;
1776	}
1777
1778	DEBUGP("Init section allocation order:\n");
1779	for (m = 0; m < ARRAY_SIZE(masks); ++m) {
1780		for (i = 0; i < info->hdr->e_shnum; ++i) {
1781			Elf_Shdr *s = &info->sechdrs[i];
1782			const char *sname = info->secstrings + s->sh_name;
1783
1784			if ((s->sh_flags & masks[m][0]) != masks[m][0]
1785			    || (s->sh_flags & masks[m][1])
1786			    || s->sh_entsize != ~0UL
1787			    || !strstarts(sname, ".init"))
1788				continue;
1789			s->sh_entsize = (get_offset(mod, &mod->init_size, s, i)
1790					 | INIT_OFFSET_MASK);
1791			DEBUGP("\t%s\n", sname);
1792		}
1793		if (m == 0)
1794			mod->init_text_size = mod->init_size;
1795	}
1796}
1797
1798static void set_license(struct module *mod, const char *license)
1799{
1800	if (!license)
1801		license = "unspecified";
1802
1803#ifndef	CONFIG_LOCKDEP
1804	if (!license_is_gpl_compatible(license)) {
1805		if (!test_taint(TAINT_PROPRIETARY_MODULE))
1806			printk(KERN_WARNING "%s: module license '%s' taints "
1807				"kernel.\n", mod->name, license);
1808		add_taint_module(mod, TAINT_PROPRIETARY_MODULE);
1809	}
1810#endif
1811}
1812
1813/* Parse tag=value strings from .modinfo section */
1814static char *next_string(char *string, unsigned long *secsize)
1815{
1816	/* Skip non-zero chars */
1817	while (string[0]) {
1818		string++;
1819		if ((*secsize)-- <= 1)
1820			return NULL;
1821	}
1822
1823	/* Skip any zero padding. */
1824	while (!string[0]) {
1825		string++;
1826		if ((*secsize)-- <= 1)
1827			return NULL;
1828	}
1829	return string;
1830}
1831
1832static char *get_modinfo(struct load_info *info, const char *tag)
1833{
1834	char *p;
1835	unsigned int taglen = strlen(tag);
1836	Elf_Shdr *infosec = &info->sechdrs[info->index.info];
1837	unsigned long size = infosec->sh_size;
1838
1839	for (p = (char *)infosec->sh_addr; p; p = next_string(p, &size)) {
1840		if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
1841			return p + taglen + 1;
1842	}
1843	return NULL;
1844}
1845
1846static void setup_modinfo(struct module *mod, struct load_info *info)
1847{
1848	struct module_attribute *attr;
1849	int i;
1850
1851	for (i = 0; (attr = modinfo_attrs[i]); i++) {
1852		if (attr->setup)
1853			attr->setup(mod, get_modinfo(info, attr->attr.name));
1854	}
1855}
1856
1857static void free_modinfo(struct module *mod)
1858{
1859	struct module_attribute *attr;
1860	int i;
1861
1862	for (i = 0; (attr = modinfo_attrs[i]); i++) {
1863		if (attr->free)
1864			attr->free(mod);
1865	}
1866}
1867
1868#ifdef CONFIG_KALLSYMS
1869
1870/* lookup symbol in given range of kernel_symbols */
1871static const struct kernel_symbol *lookup_symbol(const char *name,
1872	const struct kernel_symbol *start,
1873	const struct kernel_symbol *stop)
1874{
1875	const struct kernel_symbol *ks = start;
1876	for (; ks < stop; ks++)
1877		if (strcmp(ks->name, name) == 0)
1878			return ks;
1879	return NULL;
1880}
1881
1882static int is_exported(const char *name, unsigned long value,
1883		       const struct module *mod)
1884{
1885	const struct kernel_symbol *ks;
1886	if (!mod)
1887		ks = lookup_symbol(name, __start___ksymtab, __stop___ksymtab);
1888	else
1889		ks = lookup_symbol(name, mod->syms, mod->syms + mod->num_syms);
1890	return ks != NULL && ks->value == value;
1891}
1892
1893/* As per nm */
1894static char elf_type(const Elf_Sym *sym, const struct load_info *info)
1895{
1896	const Elf_Shdr *sechdrs = info->sechdrs;
1897
1898	if (ELF_ST_BIND(sym->st_info) == STB_WEAK) {
1899		if (ELF_ST_TYPE(sym->st_info) == STT_OBJECT)
1900			return 'v';
1901		else
1902			return 'w';
1903	}
1904	if (sym->st_shndx == SHN_UNDEF)
1905		return 'U';
1906	if (sym->st_shndx == SHN_ABS)
1907		return 'a';
1908	if (sym->st_shndx >= SHN_LORESERVE)
1909		return '?';
1910	if (sechdrs[sym->st_shndx].sh_flags & SHF_EXECINSTR)
1911		return 't';
1912	if (sechdrs[sym->st_shndx].sh_flags & SHF_ALLOC
1913	    && sechdrs[sym->st_shndx].sh_type != SHT_NOBITS) {
1914		if (!(sechdrs[sym->st_shndx].sh_flags & SHF_WRITE))
1915			return 'r';
1916		else if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
1917			return 'g';
1918		else
1919			return 'd';
1920	}
1921	if (sechdrs[sym->st_shndx].sh_type == SHT_NOBITS) {
1922		if (sechdrs[sym->st_shndx].sh_flags & ARCH_SHF_SMALL)
1923			return 's';
1924		else
1925			return 'b';
1926	}
1927	if (strstarts(info->secstrings + sechdrs[sym->st_shndx].sh_name,
1928		      ".debug")) {
1929		return 'n';
1930	}
1931	return '?';
1932}
1933
1934static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,
1935                           unsigned int shnum)
1936{
1937	const Elf_Shdr *sec;
1938
1939	if (src->st_shndx == SHN_UNDEF
1940	    || src->st_shndx >= shnum
1941	    || !src->st_name)
1942		return false;
1943
1944	sec = sechdrs + src->st_shndx;
1945	if (!(sec->sh_flags & SHF_ALLOC)
1946#ifndef CONFIG_KALLSYMS_ALL
1947	    || !(sec->sh_flags & SHF_EXECINSTR)
1948#endif
1949	    || (sec->sh_entsize & INIT_OFFSET_MASK))
1950		return false;
1951
1952	return true;
1953}
1954
1955static void layout_symtab(struct module *mod, struct load_info *info)
1956{
1957	Elf_Shdr *symsect = info->sechdrs + info->index.sym;
1958	Elf_Shdr *strsect = info->sechdrs + info->index.str;
1959	const Elf_Sym *src;
1960	unsigned int i, nsrc, ndst;
1961
1962	/* Put symbol section at end of init part of module. */
1963	symsect->sh_flags |= SHF_ALLOC;
1964	symsect->sh_entsize = get_offset(mod, &mod->init_size, symsect,
1965					 info->index.sym) | INIT_OFFSET_MASK;
1966	DEBUGP("\t%s\n", info->secstrings + symsect->sh_name);
1967
1968	src = (void *)info->hdr + symsect->sh_offset;
1969	nsrc = symsect->sh_size / sizeof(*src);
1970	for (ndst = i = 1; i < nsrc; ++i, ++src)
1971		if (is_core_symbol(src, info->sechdrs, info->hdr->e_shnum)) {
1972			unsigned int j = src->st_name;
1973
1974			while (!__test_and_set_bit(j, info->strmap)
1975			       && info->strtab[j])
1976				++j;
1977			++ndst;
1978		}
1979
1980	/* Append room for core symbols at end of core part. */
1981	info->symoffs = ALIGN(mod->core_size, symsect->sh_addralign ?: 1);
1982	mod->core_size = info->symoffs + ndst * sizeof(Elf_Sym);
1983
1984	/* Put string table section at end of init part of module. */
1985	strsect->sh_flags |= SHF_ALLOC;
1986	strsect->sh_entsize = get_offset(mod, &mod->init_size, strsect,
1987					 info->index.str) | INIT_OFFSET_MASK;
1988	DEBUGP("\t%s\n", info->secstrings + strsect->sh_name);
1989
1990	/* Append room for core symbols' strings at end of core part. */
1991	info->stroffs = mod->core_size;
1992	__set_bit(0, info->strmap);
1993	mod->core_size += bitmap_weight(info->strmap, strsect->sh_size);
1994}
1995
1996static void add_kallsyms(struct module *mod, const struct load_info *info)
1997{
1998	unsigned int i, ndst;
1999	const Elf_Sym *src;
2000	Elf_Sym *dst;
2001	char *s;
2002	Elf_Shdr *symsec = &info->sechdrs[info->index.sym];
2003
2004	mod->symtab = (void *)symsec->sh_addr;
2005	mod->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
2006	/* Make sure we get permanent strtab: don't use info->strtab. */
2007	mod->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
2008
2009	/* Set types up while we still have access to sections. */
2010	for (i = 0; i < mod->num_symtab; i++)
2011		mod->symtab[i].st_info = elf_type(&mod->symtab[i], info);
2012
2013	mod->core_symtab = dst = mod->module_core + info->symoffs;
2014	src = mod->symtab;
2015	*dst = *src;
2016	for (ndst = i = 1; i < mod->num_symtab; ++i, ++src) {
2017		if (!is_core_symbol(src, info->sechdrs, info->hdr->e_shnum))
2018			continue;
2019		dst[ndst] = *src;
2020		dst[ndst].st_name = bitmap_weight(info->strmap,
2021						  dst[ndst].st_name);
2022		++ndst;
2023	}
2024	mod->core_num_syms = ndst;
2025
2026	mod->core_strtab = s = mod->module_core + info->stroffs;
2027	for (*s = 0, i = 1; i < info->sechdrs[info->index.str].sh_size; ++i)
2028		if (test_bit(i, info->strmap))
2029			*++s = mod->strtab[i];
2030}
2031#else
2032static inline void layout_symtab(struct module *mod, struct load_info *info)
2033{
2034}
2035
2036static void add_kallsyms(struct module *mod, struct load_info *info)
2037{
2038}
2039#endif /* CONFIG_KALLSYMS */
2040
2041static void dynamic_debug_setup(struct _ddebug *debug, unsigned int num)
2042{
2043	if (!debug)
2044		return;
2045#ifdef CONFIG_DYNAMIC_DEBUG
2046	if (ddebug_add_module(debug, num, debug->modname))
2047		printk(KERN_ERR "dynamic debug error adding module: %s\n",
2048					debug->modname);
2049#endif
2050}
2051
2052static void dynamic_debug_remove(struct _ddebug *debug)
2053{
2054	if (debug)
2055		ddebug_remove_module(debug->modname);
2056}
2057
2058static void *module_alloc_update_bounds(unsigned long size)
2059{
2060	void *ret = module_alloc(size);
2061
2062	if (ret) {
2063		mutex_lock(&module_mutex);
2064		/* Update module bounds. */
2065		if ((unsigned long)ret < module_addr_min)
2066			module_addr_min = (unsigned long)ret;
2067		if ((unsigned long)ret + size > module_addr_max)
2068			module_addr_max = (unsigned long)ret + size;
2069		mutex_unlock(&module_mutex);
2070	}
2071	return ret;
2072}
2073
2074#ifdef CONFIG_DEBUG_KMEMLEAK
2075static void kmemleak_load_module(const struct module *mod,
2076				 const struct load_info *info)
2077{
2078	unsigned int i;
2079
2080	/* only scan the sections containing data */
2081	kmemleak_scan_area(mod, sizeof(struct module), GFP_KERNEL);
2082
2083	for (i = 1; i < info->hdr->e_shnum; i++) {
2084		const char *name = info->secstrings + info->sechdrs[i].sh_name;
2085		if (!(info->sechdrs[i].sh_flags & SHF_ALLOC))
2086			continue;
2087		if (!strstarts(name, ".data") && !strstarts(name, ".bss"))
2088			continue;
2089
2090		kmemleak_scan_area((void *)info->sechdrs[i].sh_addr,
2091				   info->sechdrs[i].sh_size, GFP_KERNEL);
2092	}
2093}
2094#else
2095static inline void kmemleak_load_module(const struct module *mod,
2096					const struct load_info *info)
2097{
2098}
2099#endif
2100
2101/* Sets info->hdr and info->len. */
2102static int copy_and_check(struct load_info *info,
2103			  const void __user *umod, unsigned long len,
2104			  const char __user *uargs)
2105{
2106	int err;
2107	Elf_Ehdr *hdr;
2108
2109	if (len < sizeof(*hdr))
2110		return -ENOEXEC;
2111
2112	/* Suck in entire file: we'll want most of it. */
2113	/* vmalloc barfs on "unusual" numbers.  Check here */
2114	if (len > 64 * 1024 * 1024 || (hdr = vmalloc(len)) == NULL)
2115		return -ENOMEM;
2116
2117	if (copy_from_user(hdr, umod, len) != 0) {
2118		err = -EFAULT;
2119		goto free_hdr;
2120	}
2121
2122	/* Sanity checks against insmoding binaries or wrong arch,
2123	   weird elf version */
2124	if (memcmp(hdr->e_ident, ELFMAG, SELFMAG) != 0
2125	    || hdr->e_type != ET_REL
2126	    || !elf_check_arch(hdr)
2127	    || hdr->e_shentsize != sizeof(Elf_Shdr)) {
2128		err = -ENOEXEC;
2129		goto free_hdr;
2130	}
2131
2132	if (len < hdr->e_shoff + hdr->e_shnum * sizeof(Elf_Shdr)) {
2133		err = -ENOEXEC;
2134		goto free_hdr;
2135	}
2136
2137	info->hdr = hdr;
2138	info->len = len;
2139	return 0;
2140
2141free_hdr:
2142	vfree(hdr);
2143	return err;
2144}
2145
2146static void free_copy(struct load_info *info)
2147{
2148	vfree(info->hdr);
2149}
2150
2151static int rewrite_section_headers(struct load_info *info)
2152{
2153	unsigned int i;
2154
2155	/* This should always be true, but let's be sure. */
2156	info->sechdrs[0].sh_addr = 0;
2157
2158	for (i = 1; i < info->hdr->e_shnum; i++) {
2159		Elf_Shdr *shdr = &info->sechdrs[i];
2160		if (shdr->sh_type != SHT_NOBITS
2161		    && info->len < shdr->sh_offset + shdr->sh_size) {
2162			printk(KERN_ERR "Module len %lu truncated\n",
2163			       info->len);
2164			return -ENOEXEC;
2165		}
2166
2167		/* Mark all sections sh_addr with their address in the
2168		   temporary image. */
2169		shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
2170
2171#ifndef CONFIG_MODULE_UNLOAD
2172		/* Don't load .exit sections */
2173		if (strstarts(info->secstrings+shdr->sh_name, ".exit"))
2174			shdr->sh_flags &= ~(unsigned long)SHF_ALLOC;
2175#endif
2176	}
2177
2178	/* Track but don't keep modinfo and version sections. */
2179	info->index.vers = find_sec(info, "__versions");
2180	info->index.info = find_sec(info, ".modinfo");
2181	info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
2182	info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
2183	return 0;
2184}
2185
2186/*
2187 * Set up our basic convenience variables (pointers to section headers,
2188 * search for module section index etc), and do some basic section
2189 * verification.
2190 *
2191 * Return the temporary module pointer (we'll replace it with the final
2192 * one when we move the module sections around).
2193 */
2194static struct module *setup_load_info(struct load_info *info)
2195{
2196	unsigned int i;
2197	int err;
2198	struct module *mod;
2199
2200	/* Set up the convenience variables */
2201	info->sechdrs = (void *)info->hdr + info->hdr->e_shoff;
2202	info->secstrings = (void *)info->hdr
2203		+ info->sechdrs[info->hdr->e_shstrndx].sh_offset;
2204
2205	err = rewrite_section_headers(info);
2206	if (err)
2207		return ERR_PTR(err);
2208
2209	/* Find internal symbols and strings. */
2210	for (i = 1; i < info->hdr->e_shnum; i++) {
2211		if (info->sechdrs[i].sh_type == SHT_SYMTAB) {
2212			info->index.sym = i;
2213			info->index.str = info->sechdrs[i].sh_link;
2214			info->strtab = (char *)info->hdr
2215				+ info->sechdrs[info->index.str].sh_offset;
2216			break;
2217		}
2218	}
2219
2220	info->index.mod = find_sec(info, ".gnu.linkonce.this_module");
2221	if (!info->index.mod) {
2222		printk(KERN_WARNING "No module found in object\n");
2223		return ERR_PTR(-ENOEXEC);
2224	}
2225	/* This is temporary: point mod into copy of data. */
2226	mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2227
2228	if (info->index.sym == 0) {
2229		printk(KERN_WARNING "%s: module has no symbols (stripped?)\n",
2230		       mod->name);
2231		return ERR_PTR(-ENOEXEC);
2232	}
2233
2234	info->index.pcpu = find_pcpusec(info);
2235
2236	/* Check module struct version now, before we try to use module. */
2237	if (!check_modstruct_version(info->sechdrs, info->index.vers, mod))
2238		return ERR_PTR(-ENOEXEC);
2239
2240	return mod;
2241}
2242
2243static int check_modinfo(struct module *mod, struct load_info *info)
2244{
2245	const char *modmagic = get_modinfo(info, "vermagic");
2246	int err;
2247
2248	/* This is allowed: modprobe --force will invalidate it. */
2249	if (!modmagic) {
2250		err = try_to_force_load(mod, "bad vermagic");
2251		if (err)
2252			return err;
2253	} else if (!same_magic(modmagic, vermagic, info->index.vers)) {
2254		printk(KERN_ERR "%s: version magic '%s' should be '%s'\n",
2255		       mod->name, modmagic, vermagic);
2256		return -ENOEXEC;
2257	}
2258
2259	if (get_modinfo(info, "staging")) {
2260		add_taint_module(mod, TAINT_CRAP);
2261		printk(KERN_WARNING "%s: module is from the staging directory,"
2262		       " the quality is unknown, you have been warned.\n",
2263		       mod->name);
2264	}
2265
2266	/* Set up license info based on the info section */
2267	set_license(mod, get_modinfo(info, "license"));
2268
2269	return 0;
2270}
2271
2272static void find_module_sections(struct module *mod, struct load_info *info)
2273{
2274	mod->kp = section_objs(info, "__param",
2275			       sizeof(*mod->kp), &mod->num_kp);
2276	mod->syms = section_objs(info, "__ksymtab",
2277				 sizeof(*mod->syms), &mod->num_syms);
2278	mod->crcs = section_addr(info, "__kcrctab");
2279	mod->gpl_syms = section_objs(info, "__ksymtab_gpl",
2280				     sizeof(*mod->gpl_syms),
2281				     &mod->num_gpl_syms);
2282	mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
2283	mod->gpl_future_syms = section_objs(info,
2284					    "__ksymtab_gpl_future",
2285					    sizeof(*mod->gpl_future_syms),
2286					    &mod->num_gpl_future_syms);
2287	mod->gpl_future_crcs = section_addr(info, "__kcrctab_gpl_future");
2288
2289#ifdef CONFIG_UNUSED_SYMBOLS
2290	mod->unused_syms = section_objs(info, "__ksymtab_unused",
2291					sizeof(*mod->unused_syms),
2292					&mod->num_unused_syms);
2293	mod->unused_crcs = section_addr(info, "__kcrctab_unused");
2294	mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",
2295					    sizeof(*mod->unused_gpl_syms),
2296					    &mod->num_unused_gpl_syms);
2297	mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
2298#endif
2299#ifdef CONFIG_CONSTRUCTORS
2300	mod->ctors = section_objs(info, ".ctors",
2301				  sizeof(*mod->ctors), &mod->num_ctors);
2302#endif
2303
2304#ifdef CONFIG_TRACEPOINTS
2305	mod->tracepoints = section_objs(info, "__tracepoints",
2306					sizeof(*mod->tracepoints),
2307					&mod->num_tracepoints);
2308#endif
2309#ifdef CONFIG_EVENT_TRACING
2310	mod->trace_events = section_objs(info, "_ftrace_events",
2311					 sizeof(*mod->trace_events),
2312					 &mod->num_trace_events);
2313	/*
2314	 * This section contains pointers to allocated objects in the trace
2315	 * code and not scanning it leads to false positives.
2316	 */
2317	kmemleak_scan_area(mod->trace_events, sizeof(*mod->trace_events) *
2318			   mod->num_trace_events, GFP_KERNEL);
2319#endif
2320#ifdef CONFIG_FTRACE_MCOUNT_RECORD
2321	/* sechdrs[0].sh_size is always zero */
2322	mod->ftrace_callsites = section_objs(info, "__mcount_loc",
2323					     sizeof(*mod->ftrace_callsites),
2324					     &mod->num_ftrace_callsites);
2325#endif
2326
2327	mod->extable = section_objs(info, "__ex_table",
2328				    sizeof(*mod->extable), &mod->num_exentries);
2329
2330	if (section_addr(info, "__obsparm"))
2331		printk(KERN_WARNING "%s: Ignoring obsolete parameters\n",
2332		       mod->name);
2333
2334	info->debug = section_objs(info, "__verbose",
2335				   sizeof(*info->debug), &info->num_debug);
2336}
2337
2338static int move_module(struct module *mod, struct load_info *info)
2339{
2340	int i;
2341	void *ptr;
2342
2343	/* Do the allocs. */
2344	ptr = module_alloc_update_bounds(mod->core_size);
2345	/*
2346	 * The pointer to this block is stored in the module structure
2347	 * which is inside the block. Just mark it as not being a
2348	 * leak.
2349	 */
2350	kmemleak_not_leak(ptr);
2351	if (!ptr)
2352		return -ENOMEM;
2353
2354	memset(ptr, 0, mod->core_size);
2355	mod->module_core = ptr;
2356
2357	ptr = module_alloc_update_bounds(mod->init_size);
2358	/*
2359	 * The pointer to this block is stored in the module structure
2360	 * which is inside the block. This block doesn't need to be
2361	 * scanned as it contains data and code that will be freed
2362	 * after the module is initialized.
2363	 */
2364	kmemleak_ignore(ptr);
2365	if (!ptr && mod->init_size) {
2366		module_free(mod, mod->module_core);
2367		return -ENOMEM;
2368	}
2369	memset(ptr, 0, mod->init_size);
2370	mod->module_init = ptr;
2371
2372	/* Transfer each section which specifies SHF_ALLOC */
2373	DEBUGP("final section addresses:\n");
2374	for (i = 0; i < info->hdr->e_shnum; i++) {
2375		void *dest;
2376		Elf_Shdr *shdr = &info->sechdrs[i];
2377
2378		if (!(shdr->sh_flags & SHF_ALLOC))
2379			continue;
2380
2381		if (shdr->sh_entsize & INIT_OFFSET_MASK)
2382			dest = mod->module_init
2383				+ (shdr->sh_entsize & ~INIT_OFFSET_MASK);
2384		else
2385			dest = mod->module_core + shdr->sh_entsize;
2386
2387		if (shdr->sh_type != SHT_NOBITS)
2388			memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
2389		/* Update sh_addr to point to copy in image. */
2390		shdr->sh_addr = (unsigned long)dest;
2391		DEBUGP("\t0x%lx %s\n",
2392		       shdr->sh_addr, info->secstrings + shdr->sh_name);
2393	}
2394
2395	return 0;
2396}
2397
2398static int check_module_license_and_versions(struct module *mod)
2399{
2400	/*
2401	 * ndiswrapper is under GPL by itself, but loads proprietary modules.
2402	 * Don't use add_taint_module(), as it would prevent ndiswrapper from
2403	 * using GPL-only symbols it needs.
2404	 */
2405	if (strcmp(mod->name, "ndiswrapper") == 0)
2406		add_taint(TAINT_PROPRIETARY_MODULE);
2407
2408	/* driverloader was caught wrongly pretending to be under GPL */
2409	if (strcmp(mod->name, "driverloader") == 0)
2410		add_taint_module(mod, TAINT_PROPRIETARY_MODULE);
2411
2412#ifdef CONFIG_MODVERSIONS
2413	if ((mod->num_syms && !mod->crcs)
2414	    || (mod->num_gpl_syms && !mod->gpl_crcs)
2415	    || (mod->num_gpl_future_syms && !mod->gpl_future_crcs)
2416#ifdef CONFIG_UNUSED_SYMBOLS
2417	    || (mod->num_unused_syms && !mod->unused_crcs)
2418	    || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
2419#endif
2420		) {
2421		return try_to_force_load(mod,
2422					 "no versions for exported symbols");
2423	}
2424#endif
2425	return 0;
2426}
2427
2428static void flush_module_icache(const struct module *mod)
2429{
2430	mm_segment_t old_fs;
2431
2432	/* flush the icache in correct context */
2433	old_fs = get_fs();
2434	set_fs(KERNEL_DS);
2435
2436	/*
2437	 * Flush the instruction cache, since we've played with text.
2438	 * Do it before processing of module parameters, so the module
2439	 * can provide parameter accessor functions of its own.
2440	 */
2441	if (mod->module_init)
2442		flush_icache_range((unsigned long)mod->module_init,
2443				   (unsigned long)mod->module_init
2444				   + mod->init_size);
2445	flush_icache_range((unsigned long)mod->module_core,
2446			   (unsigned long)mod->module_core + mod->core_size);
2447
2448	set_fs(old_fs);
2449}
2450
2451static struct module *layout_and_allocate(struct load_info *info)
2452{
2453	/* Module within temporary copy. */
2454	struct module *mod;
2455	Elf_Shdr *pcpusec;
2456	int err;
2457
2458	mod = setup_load_info(info);
2459	if (IS_ERR(mod))
2460		return mod;
2461
2462	err = check_modinfo(mod, info);
2463	if (err)
2464		return ERR_PTR(err);
2465
2466	/* Allow arches to frob section contents and sizes.  */
2467	err = module_frob_arch_sections(info->hdr, info->sechdrs,
2468					info->secstrings, mod);
2469	if (err < 0)
2470		goto out;
2471
2472	pcpusec = &info->sechdrs[info->index.pcpu];
2473	if (pcpusec->sh_size) {
2474		/* We have a special allocation for this section. */
2475		err = percpu_modalloc(mod,
2476				      pcpusec->sh_size, pcpusec->sh_addralign);
2477		if (err)
2478			goto out;
2479		pcpusec->sh_flags &= ~(unsigned long)SHF_ALLOC;
2480	}
2481
2482	/* Determine total sizes, and put offsets in sh_entsize.  For now
2483	   this is done generically; there doesn't appear to be any
2484	   special cases for the architectures. */
2485	layout_sections(mod, info);
2486
2487	info->strmap = kzalloc(BITS_TO_LONGS(info->sechdrs[info->index.str].sh_size)
2488			 * sizeof(long), GFP_KERNEL);
2489	if (!info->strmap) {
2490		err = -ENOMEM;
2491		goto free_percpu;
2492	}
2493	layout_symtab(mod, info);
2494
2495	/* Allocate and move to the final place */
2496	err = move_module(mod, info);
2497	if (err)
2498		goto free_strmap;
2499
2500	/* Module has been copied to its final place now: return it. */
2501	mod = (void *)info->sechdrs[info->index.mod].sh_addr;
2502	kmemleak_load_module(mod, info);
2503	return mod;
2504
2505free_strmap:
2506	kfree(info->strmap);
2507free_percpu:
2508	percpu_modfree(mod);
2509out:
2510	return ERR_PTR(err);
2511}
2512
2513/* mod is no longer valid after this! */
2514static void module_deallocate(struct module *mod, struct load_info *info)
2515{
2516	kfree(info->strmap);
2517	percpu_modfree(mod);
2518	module_free(mod, mod->module_init);
2519	module_free(mod, mod->module_core);
2520}
2521
2522static int post_relocation(struct module *mod, const struct load_info *info)
2523{
2524	/* Sort exception table now relocations are done. */
2525	sort_extable(mod->extable, mod->extable + mod->num_exentries);
2526
2527	/* Copy relocated percpu area over. */
2528	percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,
2529		       info->sechdrs[info->index.pcpu].sh_size);
2530
2531	/* Setup kallsyms-specific fields. */
2532	add_kallsyms(mod, info);
2533
2534	/* Arch-specific module finalizing. */
2535	return module_finalize(info->hdr, info->sechdrs, mod);
2536}
2537
2538/* Allocate and load the module: note that size of section 0 is always
2539   zero, and we rely on this for optional sections. */
2540static struct module *load_module(void __user *umod,
2541				  unsigned long len,
2542				  const char __user *uargs)
2543{
2544	struct load_info info = { NULL, };
2545	struct module *mod;
2546	long err;
2547
2548	DEBUGP("load_module: umod=%p, len=%lu, uargs=%p\n",
2549	       umod, len, uargs);
2550
2551	/* Copy in the blobs from userspace, check they are vaguely sane. */
2552	err = copy_and_check(&info, umod, len, uargs);
2553	if (err)
2554		return ERR_PTR(err);
2555
2556	/* Figure out module layout, and allocate all the memory. */
2557	mod = layout_and_allocate(&info);
2558	if (IS_ERR(mod)) {
2559		err = PTR_ERR(mod);
2560		goto free_copy;
2561	}
2562
2563	/* Now module is in final location, initialize linked lists, etc. */
2564	err = module_unload_init(mod);
2565	if (err)
2566		goto free_module;
2567
2568	/* Now we've got everything in the final locations, we can
2569	 * find optional sections. */
2570	find_module_sections(mod, &info);
2571
2572	err = check_module_license_and_versions(mod);
2573	if (err)
2574		goto free_unload;
2575
2576	/* Set up MODINFO_ATTR fields */
2577	setup_modinfo(mod, &info);
2578
2579	/* Fix up syms, so that st_value is a pointer to location. */
2580	err = simplify_symbols(mod, &info);
2581	if (err < 0)
2582		goto free_modinfo;
2583
2584	err = apply_relocations(mod, &info);
2585	if (err < 0)
2586		goto free_modinfo;
2587
2588	err = post_relocation(mod, &info);
2589	if (err < 0)
2590		goto free_modinfo;
2591
2592	flush_module_icache(mod);
2593
2594	/* Now copy in args */
2595	mod->args = strndup_user(uargs, ~0UL >> 1);
2596	if (IS_ERR(mod->args)) {
2597		err = PTR_ERR(mod->args);
2598		goto free_arch_cleanup;
2599	}
2600
2601	/* Mark state as coming so strong_try_module_get() ignores us. */
2602	mod->state = MODULE_STATE_COMING;
2603
2604	/* Now sew it into the lists so we can get lockdep and oops
2605	 * info during argument parsing.  Noone should access us, since
2606	 * strong_try_module_get() will fail.
2607	 * lockdep/oops can run asynchronous, so use the RCU list insertion
2608	 * function to insert in a way safe to concurrent readers.
2609	 * The mutex protects against concurrent writers.
2610	 */
2611	mutex_lock(&module_mutex);
2612	if (find_module(mod->name)) {
2613		err = -EEXIST;
2614		goto unlock;
2615	}
2616
2617	/* This has to be done once we're sure module name is unique. */
2618	if (!mod->taints)
2619		dynamic_debug_setup(info.debug, info.num_debug);
2620
2621	/* Find duplicate symbols */
2622	err = verify_export_symbols(mod);
2623	if (err < 0)
2624		goto ddebug;
2625
2626	module_bug_finalize(info.hdr, info.sechdrs, mod);
2627	list_add_rcu(&mod->list, &modules);
2628	mutex_unlock(&module_mutex);
2629
2630	/* Module is ready to execute: parsing args may do that. */
2631	err = parse_args(mod->name, mod->args, mod->kp, mod->num_kp, NULL);
2632	if (err < 0)
2633		goto unlink;
2634
2635	/* Link in to syfs. */
2636	err = mod_sysfs_setup(mod, &info, mod->kp, mod->num_kp);
2637	if (err < 0)
2638		goto unlink;
2639
2640	/* Get rid of temporary copy and strmap. */
2641	kfree(info.strmap);
2642	free_copy(&info);
2643
2644	/* Done! */
2645	trace_module_load(mod);
2646	return mod;
2647
2648 unlink:
2649	mutex_lock(&module_mutex);
2650	/* Unlink carefully: kallsyms could be walking list. */
2651	list_del_rcu(&mod->list);
2652	module_bug_cleanup(mod);
2653
2654 ddebug:
2655	if (!mod->taints)
2656		dynamic_debug_remove(info.debug);
2657 unlock:
2658	mutex_unlock(&module_mutex);
2659	synchronize_sched();
2660	kfree(mod->args);
2661 free_arch_cleanup:
2662	module_arch_cleanup(mod);
2663 free_modinfo:
2664	free_modinfo(mod);
2665 free_unload:
2666	module_unload_free(mod);
2667 free_module:
2668	module_deallocate(mod, &info);
2669 free_copy:
2670	free_copy(&info);
2671	return ERR_PTR(err);
2672}
2673
2674/* Call module constructors. */
2675static void do_mod_ctors(struct module *mod)
2676{
2677#ifdef CONFIG_CONSTRUCTORS
2678	unsigned long i;
2679
2680	for (i = 0; i < mod->num_ctors; i++)
2681		mod->ctors[i]();
2682#endif
2683}
2684
2685/* This is where the real work happens */
2686SYSCALL_DEFINE3(init_module, void __user *, umod,
2687		unsigned long, len, const char __user *, uargs)
2688{
2689	struct module *mod;
2690	int ret = 0;
2691
2692	/* Must have permission */
2693	if (!capable(CAP_SYS_MODULE) || modules_disabled)
2694		return -EPERM;
2695
2696	/* Do all the hard work */
2697	mod = load_module(umod, len, uargs);
2698	if (IS_ERR(mod))
2699		return PTR_ERR(mod);
2700
2701	blocking_notifier_call_chain(&module_notify_list,
2702			MODULE_STATE_COMING, mod);
2703
2704	do_mod_ctors(mod);
2705	/* Start the module */
2706	if (mod->init != NULL)
2707		ret = do_one_initcall(mod->init);
2708	if (ret < 0) {
2709		/* Init routine failed: abort.  Try to protect us from
2710                   buggy refcounters. */
2711		mod->state = MODULE_STATE_GOING;
2712		synchronize_sched();
2713		module_put(mod);
2714		blocking_notifier_call_chain(&module_notify_list,
2715					     MODULE_STATE_GOING, mod);
2716		free_module(mod);
2717		wake_up(&module_wq);
2718		return ret;
2719	}
2720	if (ret > 0) {
2721		printk(KERN_WARNING
2722"%s: '%s'->init suspiciously returned %d, it should follow 0/-E convention\n"
2723"%s: loading module anyway...\n",
2724		       __func__, mod->name, ret,
2725		       __func__);
2726		dump_stack();
2727	}
2728
2729	/* Now it's a first class citizen!  Wake up anyone waiting for it. */
2730	mod->state = MODULE_STATE_LIVE;
2731	wake_up(&module_wq);
2732	blocking_notifier_call_chain(&module_notify_list,
2733				     MODULE_STATE_LIVE, mod);
2734
2735	/* We need to finish all async code before the module init sequence is done */
2736	async_synchronize_full();
2737
2738	mutex_lock(&module_mutex);
2739	/* Drop initial reference. */
2740	module_put(mod);
2741	trim_init_extable(mod);
2742#ifdef CONFIG_KALLSYMS
2743	mod->num_symtab = mod->core_num_syms;
2744	mod->symtab = mod->core_symtab;
2745	mod->strtab = mod->core_strtab;
2746#endif
2747	module_free(mod, mod->module_init);
2748	mod->module_init = NULL;
2749	mod->init_size = 0;
2750	mod->init_text_size = 0;
2751	mutex_unlock(&module_mutex);
2752
2753	return 0;
2754}
2755
2756static inline int within(unsigned long addr, void *start, unsigned long size)
2757{
2758	return ((void *)addr >= start && (void *)addr < start + size);
2759}
2760
2761#ifdef CONFIG_KALLSYMS
2762/*
2763 * This ignores the intensely annoying "mapping symbols" found
2764 * in ARM ELF files: $a, $t and $d.
2765 */
2766static inline int is_arm_mapping_symbol(const char *str)
2767{
2768	return str[0] == '$' && strchr("atd", str[1])
2769	       && (str[2] == '\0' || str[2] == '.');
2770}
2771
2772static const char *get_ksymbol(struct module *mod,
2773			       unsigned long addr,
2774			       unsigned long *size,
2775			       unsigned long *offset)
2776{
2777	unsigned int i, best = 0;
2778	unsigned long nextval;
2779
2780	/* At worse, next value is at end of module */
2781	if (within_module_init(addr, mod))
2782		nextval = (unsigned long)mod->module_init+mod->init_text_size;
2783	else
2784		nextval = (unsigned long)mod->module_core+mod->core_text_size;
2785
2786	/* Scan for closest preceeding symbol, and next symbol. (ELF
2787	   starts real symbols at 1). */
2788	for (i = 1; i < mod->num_symtab; i++) {
2789		if (mod->symtab[i].st_shndx == SHN_UNDEF)
2790			continue;
2791
2792		/* We ignore unnamed symbols: they're uninformative
2793		 * and inserted at a whim. */
2794		if (mod->symtab[i].st_value <= addr
2795		    && mod->symtab[i].st_value > mod->symtab[best].st_value
2796		    && *(mod->strtab + mod->symtab[i].st_name) != '\0'
2797		    && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
2798			best = i;
2799		if (mod->symtab[i].st_value > addr
2800		    && mod->symtab[i].st_value < nextval
2801		    && *(mod->strtab + mod->symtab[i].st_name) != '\0'
2802		    && !is_arm_mapping_symbol(mod->strtab + mod->symtab[i].st_name))
2803			nextval = mod->symtab[i].st_value;
2804	}
2805
2806	if (!best)
2807		return NULL;
2808
2809	if (size)
2810		*size = nextval - mod->symtab[best].st_value;
2811	if (offset)
2812		*offset = addr - mod->symtab[best].st_value;
2813	return mod->strtab + mod->symtab[best].st_name;
2814}
2815
2816/* For kallsyms to ask for address resolution.  NULL means not found.  Careful
2817 * not to lock to avoid deadlock on oopses, simply disable preemption. */
2818const char *module_address_lookup(unsigned long addr,
2819			    unsigned long *size,
2820			    unsigned long *offset,
2821			    char **modname,
2822			    char *namebuf)
2823{
2824	struct module *mod;
2825	const char *ret = NULL;
2826
2827	preempt_disable();
2828	list_for_each_entry_rcu(mod, &modules, list) {
2829		if (within_module_init(addr, mod) ||
2830		    within_module_core(addr, mod)) {
2831			if (modname)
2832				*modname = mod->name;
2833			ret = get_ksymbol(mod, addr, size, offset);
2834			break;
2835		}
2836	}
2837	/* Make a copy in here where it's safe */
2838	if (ret) {
2839		strncpy(namebuf, ret, KSYM_NAME_LEN - 1);
2840		ret = namebuf;
2841	}
2842	preempt_enable();
2843	return ret;
2844}
2845
2846int lookup_module_symbol_name(unsigned long addr, char *symname)
2847{
2848	struct module *mod;
2849
2850	preempt_disable();
2851	list_for_each_entry_rcu(mod, &modules, list) {
2852		if (within_module_init(addr, mod) ||
2853		    within_module_core(addr, mod)) {
2854			const char *sym;
2855
2856			sym = get_ksymbol(mod, addr, NULL, NULL);
2857			if (!sym)
2858				goto out;
2859			strlcpy(symname, sym, KSYM_NAME_LEN);
2860			preempt_enable();
2861			return 0;
2862		}
2863	}
2864out:
2865	preempt_enable();
2866	return -ERANGE;
2867}
2868
2869int lookup_module_symbol_attrs(unsigned long addr, unsigned long *size,
2870			unsigned long *offset, char *modname, char *name)
2871{
2872	struct module *mod;
2873
2874	preempt_disable();
2875	list_for_each_entry_rcu(mod, &modules, list) {
2876		if (within_module_init(addr, mod) ||
2877		    within_module_core(addr, mod)) {
2878			const char *sym;
2879
2880			sym = get_ksymbol(mod, addr, size, offset);
2881			if (!sym)
2882				goto out;
2883			if (modname)
2884				strlcpy(modname, mod->name, MODULE_NAME_LEN);
2885			if (name)
2886				strlcpy(name, sym, KSYM_NAME_LEN);
2887			preempt_enable();
2888			return 0;
2889		}
2890	}
2891out:
2892	preempt_enable();
2893	return -ERANGE;
2894}
2895
2896int module_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
2897			char *name, char *module_name, int *exported)
2898{
2899	struct module *mod;
2900
2901	preempt_disable();
2902	list_for_each_entry_rcu(mod, &modules, list) {
2903		if (symnum < mod->num_symtab) {
2904			*value = mod->symtab[symnum].st_value;
2905			*type = mod->symtab[symnum].st_info;
2906			strlcpy(name, mod->strtab + mod->symtab[symnum].st_name,
2907				KSYM_NAME_LEN);
2908			strlcpy(module_name, mod->name, MODULE_NAME_LEN);
2909			*exported = is_exported(name, *value, mod);
2910			preempt_enable();
2911			return 0;
2912		}
2913		symnum -= mod->num_symtab;
2914	}
2915	preempt_enable();
2916	return -ERANGE;
2917}
2918
2919static unsigned long mod_find_symname(struct module *mod, const char *name)
2920{
2921	unsigned int i;
2922
2923	for (i = 0; i < mod->num_symtab; i++)
2924		if (strcmp(name, mod->strtab+mod->symtab[i].st_name) == 0 &&
2925		    mod->symtab[i].st_info != 'U')
2926			return mod->symtab[i].st_value;
2927	return 0;
2928}
2929
2930/* Look for this name: can be of form module:name. */
2931unsigned long module_kallsyms_lookup_name(const char *name)
2932{
2933	struct module *mod;
2934	char *colon;
2935	unsigned long ret = 0;
2936
2937	/* Don't lock: we're in enough trouble already. */
2938	preempt_disable();
2939	if ((colon = strchr(name, ':')) != NULL) {
2940		*colon = '\0';
2941		if ((mod = find_module(name)) != NULL)
2942			ret = mod_find_symname(mod, colon+1);
2943		*colon = ':';
2944	} else {
2945		list_for_each_entry_rcu(mod, &modules, list)
2946			if ((ret = mod_find_symname(mod, name)) != 0)
2947				break;
2948	}
2949	preempt_enable();
2950	return ret;
2951}
2952
2953int module_kallsyms_on_each_symbol(int (*fn)(void *, const char *,
2954					     struct module *, unsigned long),
2955				   void *data)
2956{
2957	struct module *mod;
2958	unsigned int i;
2959	int ret;
2960
2961	list_for_each_entry(mod, &modules, list) {
2962		for (i = 0; i < mod->num_symtab; i++) {
2963			ret = fn(data, mod->strtab + mod->symtab[i].st_name,
2964				 mod, mod->symtab[i].st_value);
2965			if (ret != 0)
2966				return ret;
2967		}
2968	}
2969	return 0;
2970}
2971#endif /* CONFIG_KALLSYMS */
2972
2973static char *module_flags(struct module *mod, char *buf)
2974{
2975	int bx = 0;
2976
2977	if (mod->taints ||
2978	    mod->state == MODULE_STATE_GOING ||
2979	    mod->state == MODULE_STATE_COMING) {
2980		buf[bx++] = '(';
2981		if (mod->taints & (1 << TAINT_PROPRIETARY_MODULE))
2982			buf[bx++] = 'P';
2983		if (mod->taints & (1 << TAINT_FORCED_MODULE))
2984			buf[bx++] = 'F';
2985		if (mod->taints & (1 << TAINT_CRAP))
2986			buf[bx++] = 'C';
2987		/*
2988		 * TAINT_FORCED_RMMOD: could be added.
2989		 * TAINT_UNSAFE_SMP, TAINT_MACHINE_CHECK, TAINT_BAD_PAGE don't
2990		 * apply to modules.
2991		 */
2992
2993		/* Show a - for module-is-being-unloaded */
2994		if (mod->state == MODULE_STATE_GOING)
2995			buf[bx++] = '-';
2996		/* Show a + for module-is-being-loaded */
2997		if (mod->state == MODULE_STATE_COMING)
2998			buf[bx++] = '+';
2999		buf[bx++] = ')';
3000	}
3001	buf[bx] = '\0';
3002
3003	return buf;
3004}
3005
3006#ifdef CONFIG_PROC_FS
3007/* Called by the /proc file system to return a list of modules. */
3008static void *m_start(struct seq_file *m, loff_t *pos)
3009{
3010	mutex_lock(&module_mutex);
3011	return seq_list_start(&modules, *pos);
3012}
3013
3014static void *m_next(struct seq_file *m, void *p, loff_t *pos)
3015{
3016	return seq_list_next(p, &modules, pos);
3017}
3018
3019static void m_stop(struct seq_file *m, void *p)
3020{
3021	mutex_unlock(&module_mutex);
3022}
3023
3024static int m_show(struct seq_file *m, void *p)
3025{
3026	struct module *mod = list_entry(p, struct module, list);
3027	char buf[8];
3028
3029	seq_printf(m, "%s %u",
3030		   mod->name, mod->init_size + mod->core_size);
3031	print_unload_info(m, mod);
3032
3033	/* Informative for users. */
3034	seq_printf(m, " %s",
3035		   mod->state == MODULE_STATE_GOING ? "Unloading":
3036		   mod->state == MODULE_STATE_COMING ? "Loading":
3037		   "Live");
3038	/* Used by oprofile and other similar tools. */
3039	seq_printf(m, " 0x%p", mod->module_core);
3040
3041	/* Taints info */
3042	if (mod->taints)
3043		seq_printf(m, " %s", module_flags(mod, buf));
3044
3045	seq_printf(m, "\n");
3046	return 0;
3047}
3048
3049/* Format: modulename size refcount deps address
3050
3051   Where refcount is a number or -, and deps is a comma-separated list
3052   of depends or -.
3053*/
3054static const struct seq_operations modules_op = {
3055	.start	= m_start,
3056	.next	= m_next,
3057	.stop	= m_stop,
3058	.show	= m_show
3059};
3060
3061static int modules_open(struct inode *inode, struct file *file)
3062{
3063	return seq_open(file, &modules_op);
3064}
3065
3066static const struct file_operations proc_modules_operations = {
3067	.open		= modules_open,
3068	.read		= seq_read,
3069	.llseek		= seq_lseek,
3070	.release	= seq_release,
3071};
3072
3073static int __init proc_modules_init(void)
3074{
3075	proc_create("modules", 0, NULL, &proc_modules_operations);
3076	return 0;
3077}
3078module_init(proc_modules_init);
3079#endif
3080
3081/* Given an address, look for it in the module exception tables. */
3082const struct exception_table_entry *search_module_extables(unsigned long addr)
3083{
3084	const struct exception_table_entry *e = NULL;
3085	struct module *mod;
3086
3087	preempt_disable();
3088	list_for_each_entry_rcu(mod, &modules, list) {
3089		if (mod->num_exentries == 0)
3090			continue;
3091
3092		e = search_extable(mod->extable,
3093				   mod->extable + mod->num_exentries - 1,
3094				   addr);
3095		if (e)
3096			break;
3097	}
3098	preempt_enable();
3099
3100	/* Now, if we found one, we are running inside it now, hence
3101	   we cannot unload the module, hence no refcnt needed. */
3102	return e;
3103}
3104
3105/*
3106 * is_module_address - is this address inside a module?
3107 * @addr: the address to check.
3108 *
3109 * See is_module_text_address() if you simply want to see if the address
3110 * is code (not data).
3111 */
3112bool is_module_address(unsigned long addr)
3113{
3114	bool ret;
3115
3116	preempt_disable();
3117	ret = __module_address(addr) != NULL;
3118	preempt_enable();
3119
3120	return ret;
3121}
3122
3123/*
3124 * __module_address - get the module which contains an address.
3125 * @addr: the address.
3126 *
3127 * Must be called with preempt disabled or module mutex held so that
3128 * module doesn't get freed during this.
3129 */
3130struct module *__module_address(unsigned long addr)
3131{
3132	struct module *mod;
3133
3134	if (addr < module_addr_min || addr > module_addr_max)
3135		return NULL;
3136
3137	list_for_each_entry_rcu(mod, &modules, list)
3138		if (within_module_core(addr, mod)
3139		    || within_module_init(addr, mod))
3140			return mod;
3141	return NULL;
3142}
3143EXPORT_SYMBOL_GPL(__module_address);
3144
3145/*
3146 * is_module_text_address - is this address inside module code?
3147 * @addr: the address to check.
3148 *
3149 * See is_module_address() if you simply want to see if the address is
3150 * anywhere in a module.  See kernel_text_address() for testing if an
3151 * address corresponds to kernel or module code.
3152 */
3153bool is_module_text_address(unsigned long addr)
3154{
3155	bool ret;
3156
3157	preempt_disable();
3158	ret = __module_text_address(addr) != NULL;
3159	preempt_enable();
3160
3161	return ret;
3162}
3163
3164/*
3165 * __module_text_address - get the module whose code contains an address.
3166 * @addr: the address.
3167 *
3168 * Must be called with preempt disabled or module mutex held so that
3169 * module doesn't get freed during this.
3170 */
3171struct module *__module_text_address(unsigned long addr)
3172{
3173	struct module *mod = __module_address(addr);
3174	if (mod) {
3175		/* Make sure it's within the text section. */
3176		if (!within(addr, mod->module_init, mod->init_text_size)
3177		    && !within(addr, mod->module_core, mod->core_text_size))
3178			mod = NULL;
3179	}
3180	return mod;
3181}
3182EXPORT_SYMBOL_GPL(__module_text_address);
3183
3184/* Don't grab lock, we're oopsing. */
3185void print_modules(void)
3186{
3187	struct module *mod;
3188	char buf[8];
3189
3190	/* Show each module name and core base address for
3191	 * GDB source code trace dump
3192	 */
3193	preempt_disable();
3194	list_for_each_entry_rcu(mod, &modules, list) {
3195		printk("module:  %s\t %p\t %u\n",
3196			mod->name,
3197			mod->module_core,
3198			mod->init_size + mod->core_size);
3199	}
3200	preempt_enable();
3201
3202	printk(KERN_DEFAULT "Modules linked in:");
3203	/* Most callers should already have preempt disabled, but make sure */
3204	preempt_disable();
3205	list_for_each_entry_rcu(mod, &modules, list)
3206		printk(" %s%s", mod->name, module_flags(mod, buf));
3207	preempt_enable();
3208	if (last_unloaded_module[0])
3209		printk(" [last unloaded: %s]", last_unloaded_module);
3210	printk("\n");
3211}
3212
3213#ifdef CONFIG_MODVERSIONS
3214/* Generate the signature for all relevant module structures here.
3215 * If these change, we don't want to try to parse the module. */
3216void module_layout(struct module *mod,
3217		   struct modversion_info *ver,
3218		   struct kernel_param *kp,
3219		   struct kernel_symbol *ks,
3220		   struct tracepoint *tp)
3221{
3222}
3223EXPORT_SYMBOL(module_layout);
3224#endif
3225
3226#ifdef CONFIG_TRACEPOINTS
3227void module_update_tracepoints(void)
3228{
3229	struct module *mod;
3230
3231	mutex_lock(&module_mutex);
3232	list_for_each_entry(mod, &modules, list)
3233		if (!mod->taints)
3234			tracepoint_update_probe_range(mod->tracepoints,
3235				mod->tracepoints + mod->num_tracepoints);
3236	mutex_unlock(&module_mutex);
3237}
3238
3239/*
3240 * Returns 0 if current not found.
3241 * Returns 1 if current found.
3242 */
3243int module_get_iter_tracepoints(struct tracepoint_iter *iter)
3244{
3245	struct module *iter_mod;
3246	int found = 0;
3247
3248	mutex_lock(&module_mutex);
3249	list_for_each_entry(iter_mod, &modules, list) {
3250		if (!iter_mod->taints) {
3251			/*
3252			 * Sorted module list
3253			 */
3254			if (iter_mod < iter->module)
3255				continue;
3256			else if (iter_mod > iter->module)
3257				iter->tracepoint = NULL;
3258			found = tracepoint_get_iter_range(&iter->tracepoint,
3259				iter_mod->tracepoints,
3260				iter_mod->tracepoints
3261					+ iter_mod->num_tracepoints);
3262			if (found) {
3263				iter->module = iter_mod;
3264				break;
3265			}
3266		}
3267	}
3268	mutex_unlock(&module_mutex);
3269	return found;
3270}
3271#endif
3272