xref: /openbmc/linux/kernel/livepatch/core.c (revision 9d5dbfe0)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * core.c - Kernel Live Patching Core
4  *
5  * Copyright (C) 2014 Seth Jennings <sjenning@redhat.com>
6  * Copyright (C) 2014 SUSE
7  */
8 
9 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
10 
11 #include <linux/module.h>
12 #include <linux/kernel.h>
13 #include <linux/mutex.h>
14 #include <linux/slab.h>
15 #include <linux/list.h>
16 #include <linux/kallsyms.h>
17 #include <linux/livepatch.h>
18 #include <linux/elf.h>
19 #include <linux/moduleloader.h>
20 #include <linux/completion.h>
21 #include <linux/memory.h>
22 #include <linux/rcupdate.h>
23 #include <asm/cacheflush.h>
24 #include "core.h"
25 #include "patch.h"
26 #include "state.h"
27 #include "transition.h"
28 
29 /*
30  * klp_mutex is a coarse lock which serializes access to klp data.  All
31  * accesses to klp-related variables and structures must have mutex protection,
32  * except within the following functions which carefully avoid the need for it:
33  *
34  * - klp_ftrace_handler()
35  * - klp_update_patch_state()
36  */
37 DEFINE_MUTEX(klp_mutex);
38 
39 /*
40  * Actively used patches: enabled or in transition. Note that replaced
41  * or disabled patches are not listed even though the related kernel
42  * module still can be loaded.
43  */
44 LIST_HEAD(klp_patches);
45 
46 static struct kobject *klp_root_kobj;
47 
48 static bool klp_is_module(struct klp_object *obj)
49 {
50 	return obj->name;
51 }
52 
53 /* sets obj->mod if object is not vmlinux and module is found */
54 static void klp_find_object_module(struct klp_object *obj)
55 {
56 	struct module *mod;
57 
58 	if (!klp_is_module(obj))
59 		return;
60 
61 	rcu_read_lock_sched();
62 	/*
63 	 * We do not want to block removal of patched modules and therefore
64 	 * we do not take a reference here. The patches are removed by
65 	 * klp_module_going() instead.
66 	 */
67 	mod = find_module(obj->name);
68 	/*
69 	 * Do not mess work of klp_module_coming() and klp_module_going().
70 	 * Note that the patch might still be needed before klp_module_going()
71 	 * is called. Module functions can be called even in the GOING state
72 	 * until mod->exit() finishes. This is especially important for
73 	 * patches that modify semantic of the functions.
74 	 */
75 	if (mod && mod->klp_alive)
76 		obj->mod = mod;
77 
78 	rcu_read_unlock_sched();
79 }
80 
81 static bool klp_initialized(void)
82 {
83 	return !!klp_root_kobj;
84 }
85 
86 static struct klp_func *klp_find_func(struct klp_object *obj,
87 				      struct klp_func *old_func)
88 {
89 	struct klp_func *func;
90 
91 	klp_for_each_func(obj, func) {
92 		if ((strcmp(old_func->old_name, func->old_name) == 0) &&
93 		    (old_func->old_sympos == func->old_sympos)) {
94 			return func;
95 		}
96 	}
97 
98 	return NULL;
99 }
100 
101 static struct klp_object *klp_find_object(struct klp_patch *patch,
102 					  struct klp_object *old_obj)
103 {
104 	struct klp_object *obj;
105 
106 	klp_for_each_object(patch, obj) {
107 		if (klp_is_module(old_obj)) {
108 			if (klp_is_module(obj) &&
109 			    strcmp(old_obj->name, obj->name) == 0) {
110 				return obj;
111 			}
112 		} else if (!klp_is_module(obj)) {
113 			return obj;
114 		}
115 	}
116 
117 	return NULL;
118 }
119 
120 struct klp_find_arg {
121 	const char *name;
122 	unsigned long addr;
123 	unsigned long count;
124 	unsigned long pos;
125 };
126 
127 static int klp_match_callback(void *data, unsigned long addr)
128 {
129 	struct klp_find_arg *args = data;
130 
131 	args->addr = addr;
132 	args->count++;
133 
134 	/*
135 	 * Finish the search when the symbol is found for the desired position
136 	 * or the position is not defined for a non-unique symbol.
137 	 */
138 	if ((args->pos && (args->count == args->pos)) ||
139 	    (!args->pos && (args->count > 1)))
140 		return 1;
141 
142 	return 0;
143 }
144 
145 static int klp_find_callback(void *data, const char *name,
146 			     struct module *mod, unsigned long addr)
147 {
148 	struct klp_find_arg *args = data;
149 
150 	if (strcmp(args->name, name))
151 		return 0;
152 
153 	return klp_match_callback(data, addr);
154 }
155 
156 static int klp_find_object_symbol(const char *objname, const char *name,
157 				  unsigned long sympos, unsigned long *addr)
158 {
159 	struct klp_find_arg args = {
160 		.name = name,
161 		.addr = 0,
162 		.count = 0,
163 		.pos = sympos,
164 	};
165 
166 	if (objname)
167 		module_kallsyms_on_each_symbol(objname, klp_find_callback, &args);
168 	else
169 		kallsyms_on_each_match_symbol(klp_match_callback, name, &args);
170 
171 	/*
172 	 * Ensure an address was found. If sympos is 0, ensure symbol is unique;
173 	 * otherwise ensure the symbol position count matches sympos.
174 	 */
175 	if (args.addr == 0)
176 		pr_err("symbol '%s' not found in symbol table\n", name);
177 	else if (args.count > 1 && sympos == 0) {
178 		pr_err("unresolvable ambiguity for symbol '%s' in object '%s'\n",
179 		       name, objname);
180 	} else if (sympos != args.count && sympos > 0) {
181 		pr_err("symbol position %lu for symbol '%s' in object '%s' not found\n",
182 		       sympos, name, objname ? objname : "vmlinux");
183 	} else {
184 		*addr = args.addr;
185 		return 0;
186 	}
187 
188 	*addr = 0;
189 	return -EINVAL;
190 }
191 
192 static int klp_resolve_symbols(Elf_Shdr *sechdrs, const char *strtab,
193 			       unsigned int symndx, Elf_Shdr *relasec,
194 			       const char *sec_objname)
195 {
196 	int i, cnt, ret;
197 	char sym_objname[MODULE_NAME_LEN];
198 	char sym_name[KSYM_NAME_LEN];
199 	Elf_Rela *relas;
200 	Elf_Sym *sym;
201 	unsigned long sympos, addr;
202 	bool sym_vmlinux;
203 	bool sec_vmlinux = !strcmp(sec_objname, "vmlinux");
204 
205 	/*
206 	 * Since the field widths for sym_objname and sym_name in the sscanf()
207 	 * call are hard-coded and correspond to MODULE_NAME_LEN and
208 	 * KSYM_NAME_LEN respectively, we must make sure that MODULE_NAME_LEN
209 	 * and KSYM_NAME_LEN have the values we expect them to have.
210 	 *
211 	 * Because the value of MODULE_NAME_LEN can differ among architectures,
212 	 * we use the smallest/strictest upper bound possible (56, based on
213 	 * the current definition of MODULE_NAME_LEN) to prevent overflows.
214 	 */
215 	BUILD_BUG_ON(MODULE_NAME_LEN < 56 || KSYM_NAME_LEN != 512);
216 
217 	relas = (Elf_Rela *) relasec->sh_addr;
218 	/* For each rela in this klp relocation section */
219 	for (i = 0; i < relasec->sh_size / sizeof(Elf_Rela); i++) {
220 		sym = (Elf_Sym *)sechdrs[symndx].sh_addr + ELF_R_SYM(relas[i].r_info);
221 		if (sym->st_shndx != SHN_LIVEPATCH) {
222 			pr_err("symbol %s is not marked as a livepatch symbol\n",
223 			       strtab + sym->st_name);
224 			return -EINVAL;
225 		}
226 
227 		/* Format: .klp.sym.sym_objname.sym_name,sympos */
228 		cnt = sscanf(strtab + sym->st_name,
229 			     ".klp.sym.%55[^.].%511[^,],%lu",
230 			     sym_objname, sym_name, &sympos);
231 		if (cnt != 3) {
232 			pr_err("symbol %s has an incorrectly formatted name\n",
233 			       strtab + sym->st_name);
234 			return -EINVAL;
235 		}
236 
237 		sym_vmlinux = !strcmp(sym_objname, "vmlinux");
238 
239 		/*
240 		 * Prevent module-specific KLP rela sections from referencing
241 		 * vmlinux symbols.  This helps prevent ordering issues with
242 		 * module special section initializations.  Presumably such
243 		 * symbols are exported and normal relas can be used instead.
244 		 */
245 		if (!sec_vmlinux && sym_vmlinux) {
246 			pr_err("invalid access to vmlinux symbol '%s' from module-specific livepatch relocation section",
247 			       sym_name);
248 			return -EINVAL;
249 		}
250 
251 		/* klp_find_object_symbol() treats a NULL objname as vmlinux */
252 		ret = klp_find_object_symbol(sym_vmlinux ? NULL : sym_objname,
253 					     sym_name, sympos, &addr);
254 		if (ret)
255 			return ret;
256 
257 		sym->st_value = addr;
258 	}
259 
260 	return 0;
261 }
262 
263 /*
264  * At a high-level, there are two types of klp relocation sections: those which
265  * reference symbols which live in vmlinux; and those which reference symbols
266  * which live in other modules.  This function is called for both types:
267  *
268  * 1) When a klp module itself loads, the module code calls this function to
269  *    write vmlinux-specific klp relocations (.klp.rela.vmlinux.* sections).
270  *    These relocations are written to the klp module text to allow the patched
271  *    code/data to reference unexported vmlinux symbols.  They're written as
272  *    early as possible to ensure that other module init code (.e.g.,
273  *    jump_label_apply_nops) can access any unexported vmlinux symbols which
274  *    might be referenced by the klp module's special sections.
275  *
276  * 2) When a to-be-patched module loads -- or is already loaded when a
277  *    corresponding klp module loads -- klp code calls this function to write
278  *    module-specific klp relocations (.klp.rela.{module}.* sections).  These
279  *    are written to the klp module text to allow the patched code/data to
280  *    reference symbols which live in the to-be-patched module or one of its
281  *    module dependencies.  Exported symbols are supported, in addition to
282  *    unexported symbols, in order to enable late module patching, which allows
283  *    the to-be-patched module to be loaded and patched sometime *after* the
284  *    klp module is loaded.
285  */
286 int klp_apply_section_relocs(struct module *pmod, Elf_Shdr *sechdrs,
287 			     const char *shstrtab, const char *strtab,
288 			     unsigned int symndx, unsigned int secndx,
289 			     const char *objname)
290 {
291 	int cnt, ret;
292 	char sec_objname[MODULE_NAME_LEN];
293 	Elf_Shdr *sec = sechdrs + secndx;
294 
295 	/*
296 	 * Format: .klp.rela.sec_objname.section_name
297 	 * See comment in klp_resolve_symbols() for an explanation
298 	 * of the selected field width value.
299 	 */
300 	cnt = sscanf(shstrtab + sec->sh_name, ".klp.rela.%55[^.]",
301 		     sec_objname);
302 	if (cnt != 1) {
303 		pr_err("section %s has an incorrectly formatted name\n",
304 		       shstrtab + sec->sh_name);
305 		return -EINVAL;
306 	}
307 
308 	if (strcmp(objname ? objname : "vmlinux", sec_objname))
309 		return 0;
310 
311 	ret = klp_resolve_symbols(sechdrs, strtab, symndx, sec, sec_objname);
312 	if (ret)
313 		return ret;
314 
315 	return apply_relocate_add(sechdrs, strtab, symndx, secndx, pmod);
316 }
317 
318 /*
319  * Sysfs Interface
320  *
321  * /sys/kernel/livepatch
322  * /sys/kernel/livepatch/<patch>
323  * /sys/kernel/livepatch/<patch>/enabled
324  * /sys/kernel/livepatch/<patch>/transition
325  * /sys/kernel/livepatch/<patch>/force
326  * /sys/kernel/livepatch/<patch>/<object>
327  * /sys/kernel/livepatch/<patch>/<object>/patched
328  * /sys/kernel/livepatch/<patch>/<object>/<function,sympos>
329  */
330 static int __klp_disable_patch(struct klp_patch *patch);
331 
332 static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
333 			     const char *buf, size_t count)
334 {
335 	struct klp_patch *patch;
336 	int ret;
337 	bool enabled;
338 
339 	ret = kstrtobool(buf, &enabled);
340 	if (ret)
341 		return ret;
342 
343 	patch = container_of(kobj, struct klp_patch, kobj);
344 
345 	mutex_lock(&klp_mutex);
346 
347 	if (patch->enabled == enabled) {
348 		/* already in requested state */
349 		ret = -EINVAL;
350 		goto out;
351 	}
352 
353 	/*
354 	 * Allow to reverse a pending transition in both ways. It might be
355 	 * necessary to complete the transition without forcing and breaking
356 	 * the system integrity.
357 	 *
358 	 * Do not allow to re-enable a disabled patch.
359 	 */
360 	if (patch == klp_transition_patch)
361 		klp_reverse_transition();
362 	else if (!enabled)
363 		ret = __klp_disable_patch(patch);
364 	else
365 		ret = -EINVAL;
366 
367 out:
368 	mutex_unlock(&klp_mutex);
369 
370 	if (ret)
371 		return ret;
372 	return count;
373 }
374 
375 static ssize_t enabled_show(struct kobject *kobj,
376 			    struct kobj_attribute *attr, char *buf)
377 {
378 	struct klp_patch *patch;
379 
380 	patch = container_of(kobj, struct klp_patch, kobj);
381 	return snprintf(buf, PAGE_SIZE-1, "%d\n", patch->enabled);
382 }
383 
384 static ssize_t transition_show(struct kobject *kobj,
385 			       struct kobj_attribute *attr, char *buf)
386 {
387 	struct klp_patch *patch;
388 
389 	patch = container_of(kobj, struct klp_patch, kobj);
390 	return snprintf(buf, PAGE_SIZE-1, "%d\n",
391 			patch == klp_transition_patch);
392 }
393 
394 static ssize_t force_store(struct kobject *kobj, struct kobj_attribute *attr,
395 			   const char *buf, size_t count)
396 {
397 	struct klp_patch *patch;
398 	int ret;
399 	bool val;
400 
401 	ret = kstrtobool(buf, &val);
402 	if (ret)
403 		return ret;
404 
405 	if (!val)
406 		return count;
407 
408 	mutex_lock(&klp_mutex);
409 
410 	patch = container_of(kobj, struct klp_patch, kobj);
411 	if (patch != klp_transition_patch) {
412 		mutex_unlock(&klp_mutex);
413 		return -EINVAL;
414 	}
415 
416 	klp_force_transition();
417 
418 	mutex_unlock(&klp_mutex);
419 
420 	return count;
421 }
422 
423 static struct kobj_attribute enabled_kobj_attr = __ATTR_RW(enabled);
424 static struct kobj_attribute transition_kobj_attr = __ATTR_RO(transition);
425 static struct kobj_attribute force_kobj_attr = __ATTR_WO(force);
426 static struct attribute *klp_patch_attrs[] = {
427 	&enabled_kobj_attr.attr,
428 	&transition_kobj_attr.attr,
429 	&force_kobj_attr.attr,
430 	NULL
431 };
432 ATTRIBUTE_GROUPS(klp_patch);
433 
434 static ssize_t patched_show(struct kobject *kobj,
435 			    struct kobj_attribute *attr, char *buf)
436 {
437 	struct klp_object *obj;
438 
439 	obj = container_of(kobj, struct klp_object, kobj);
440 	return sysfs_emit(buf, "%d\n", obj->patched);
441 }
442 
443 static struct kobj_attribute patched_kobj_attr = __ATTR_RO(patched);
444 static struct attribute *klp_object_attrs[] = {
445 	&patched_kobj_attr.attr,
446 	NULL,
447 };
448 ATTRIBUTE_GROUPS(klp_object);
449 
450 static void klp_free_object_dynamic(struct klp_object *obj)
451 {
452 	kfree(obj->name);
453 	kfree(obj);
454 }
455 
456 static void klp_init_func_early(struct klp_object *obj,
457 				struct klp_func *func);
458 static void klp_init_object_early(struct klp_patch *patch,
459 				  struct klp_object *obj);
460 
461 static struct klp_object *klp_alloc_object_dynamic(const char *name,
462 						   struct klp_patch *patch)
463 {
464 	struct klp_object *obj;
465 
466 	obj = kzalloc(sizeof(*obj), GFP_KERNEL);
467 	if (!obj)
468 		return NULL;
469 
470 	if (name) {
471 		obj->name = kstrdup(name, GFP_KERNEL);
472 		if (!obj->name) {
473 			kfree(obj);
474 			return NULL;
475 		}
476 	}
477 
478 	klp_init_object_early(patch, obj);
479 	obj->dynamic = true;
480 
481 	return obj;
482 }
483 
484 static void klp_free_func_nop(struct klp_func *func)
485 {
486 	kfree(func->old_name);
487 	kfree(func);
488 }
489 
490 static struct klp_func *klp_alloc_func_nop(struct klp_func *old_func,
491 					   struct klp_object *obj)
492 {
493 	struct klp_func *func;
494 
495 	func = kzalloc(sizeof(*func), GFP_KERNEL);
496 	if (!func)
497 		return NULL;
498 
499 	if (old_func->old_name) {
500 		func->old_name = kstrdup(old_func->old_name, GFP_KERNEL);
501 		if (!func->old_name) {
502 			kfree(func);
503 			return NULL;
504 		}
505 	}
506 
507 	klp_init_func_early(obj, func);
508 	/*
509 	 * func->new_func is same as func->old_func. These addresses are
510 	 * set when the object is loaded, see klp_init_object_loaded().
511 	 */
512 	func->old_sympos = old_func->old_sympos;
513 	func->nop = true;
514 
515 	return func;
516 }
517 
518 static int klp_add_object_nops(struct klp_patch *patch,
519 			       struct klp_object *old_obj)
520 {
521 	struct klp_object *obj;
522 	struct klp_func *func, *old_func;
523 
524 	obj = klp_find_object(patch, old_obj);
525 
526 	if (!obj) {
527 		obj = klp_alloc_object_dynamic(old_obj->name, patch);
528 		if (!obj)
529 			return -ENOMEM;
530 	}
531 
532 	klp_for_each_func(old_obj, old_func) {
533 		func = klp_find_func(obj, old_func);
534 		if (func)
535 			continue;
536 
537 		func = klp_alloc_func_nop(old_func, obj);
538 		if (!func)
539 			return -ENOMEM;
540 	}
541 
542 	return 0;
543 }
544 
545 /*
546  * Add 'nop' functions which simply return to the caller to run
547  * the original function. The 'nop' functions are added to a
548  * patch to facilitate a 'replace' mode.
549  */
550 static int klp_add_nops(struct klp_patch *patch)
551 {
552 	struct klp_patch *old_patch;
553 	struct klp_object *old_obj;
554 
555 	klp_for_each_patch(old_patch) {
556 		klp_for_each_object(old_patch, old_obj) {
557 			int err;
558 
559 			err = klp_add_object_nops(patch, old_obj);
560 			if (err)
561 				return err;
562 		}
563 	}
564 
565 	return 0;
566 }
567 
568 static void klp_kobj_release_patch(struct kobject *kobj)
569 {
570 	struct klp_patch *patch;
571 
572 	patch = container_of(kobj, struct klp_patch, kobj);
573 	complete(&patch->finish);
574 }
575 
576 static struct kobj_type klp_ktype_patch = {
577 	.release = klp_kobj_release_patch,
578 	.sysfs_ops = &kobj_sysfs_ops,
579 	.default_groups = klp_patch_groups,
580 };
581 
582 static void klp_kobj_release_object(struct kobject *kobj)
583 {
584 	struct klp_object *obj;
585 
586 	obj = container_of(kobj, struct klp_object, kobj);
587 
588 	if (obj->dynamic)
589 		klp_free_object_dynamic(obj);
590 }
591 
592 static struct kobj_type klp_ktype_object = {
593 	.release = klp_kobj_release_object,
594 	.sysfs_ops = &kobj_sysfs_ops,
595 	.default_groups = klp_object_groups,
596 };
597 
598 static void klp_kobj_release_func(struct kobject *kobj)
599 {
600 	struct klp_func *func;
601 
602 	func = container_of(kobj, struct klp_func, kobj);
603 
604 	if (func->nop)
605 		klp_free_func_nop(func);
606 }
607 
608 static struct kobj_type klp_ktype_func = {
609 	.release = klp_kobj_release_func,
610 	.sysfs_ops = &kobj_sysfs_ops,
611 };
612 
613 static void __klp_free_funcs(struct klp_object *obj, bool nops_only)
614 {
615 	struct klp_func *func, *tmp_func;
616 
617 	klp_for_each_func_safe(obj, func, tmp_func) {
618 		if (nops_only && !func->nop)
619 			continue;
620 
621 		list_del(&func->node);
622 		kobject_put(&func->kobj);
623 	}
624 }
625 
626 /* Clean up when a patched object is unloaded */
627 static void klp_free_object_loaded(struct klp_object *obj)
628 {
629 	struct klp_func *func;
630 
631 	obj->mod = NULL;
632 
633 	klp_for_each_func(obj, func) {
634 		func->old_func = NULL;
635 
636 		if (func->nop)
637 			func->new_func = NULL;
638 	}
639 }
640 
641 static void __klp_free_objects(struct klp_patch *patch, bool nops_only)
642 {
643 	struct klp_object *obj, *tmp_obj;
644 
645 	klp_for_each_object_safe(patch, obj, tmp_obj) {
646 		__klp_free_funcs(obj, nops_only);
647 
648 		if (nops_only && !obj->dynamic)
649 			continue;
650 
651 		list_del(&obj->node);
652 		kobject_put(&obj->kobj);
653 	}
654 }
655 
656 static void klp_free_objects(struct klp_patch *patch)
657 {
658 	__klp_free_objects(patch, false);
659 }
660 
661 static void klp_free_objects_dynamic(struct klp_patch *patch)
662 {
663 	__klp_free_objects(patch, true);
664 }
665 
666 /*
667  * This function implements the free operations that can be called safely
668  * under klp_mutex.
669  *
670  * The operation must be completed by calling klp_free_patch_finish()
671  * outside klp_mutex.
672  */
673 static void klp_free_patch_start(struct klp_patch *patch)
674 {
675 	if (!list_empty(&patch->list))
676 		list_del(&patch->list);
677 
678 	klp_free_objects(patch);
679 }
680 
681 /*
682  * This function implements the free part that must be called outside
683  * klp_mutex.
684  *
685  * It must be called after klp_free_patch_start(). And it has to be
686  * the last function accessing the livepatch structures when the patch
687  * gets disabled.
688  */
689 static void klp_free_patch_finish(struct klp_patch *patch)
690 {
691 	/*
692 	 * Avoid deadlock with enabled_store() sysfs callback by
693 	 * calling this outside klp_mutex. It is safe because
694 	 * this is called when the patch gets disabled and it
695 	 * cannot get enabled again.
696 	 */
697 	kobject_put(&patch->kobj);
698 	wait_for_completion(&patch->finish);
699 
700 	/* Put the module after the last access to struct klp_patch. */
701 	if (!patch->forced)
702 		module_put(patch->mod);
703 }
704 
705 /*
706  * The livepatch might be freed from sysfs interface created by the patch.
707  * This work allows to wait until the interface is destroyed in a separate
708  * context.
709  */
710 static void klp_free_patch_work_fn(struct work_struct *work)
711 {
712 	struct klp_patch *patch =
713 		container_of(work, struct klp_patch, free_work);
714 
715 	klp_free_patch_finish(patch);
716 }
717 
718 void klp_free_patch_async(struct klp_patch *patch)
719 {
720 	klp_free_patch_start(patch);
721 	schedule_work(&patch->free_work);
722 }
723 
724 void klp_free_replaced_patches_async(struct klp_patch *new_patch)
725 {
726 	struct klp_patch *old_patch, *tmp_patch;
727 
728 	klp_for_each_patch_safe(old_patch, tmp_patch) {
729 		if (old_patch == new_patch)
730 			return;
731 		klp_free_patch_async(old_patch);
732 	}
733 }
734 
735 static int klp_init_func(struct klp_object *obj, struct klp_func *func)
736 {
737 	if (!func->old_name)
738 		return -EINVAL;
739 
740 	/*
741 	 * NOPs get the address later. The patched module must be loaded,
742 	 * see klp_init_object_loaded().
743 	 */
744 	if (!func->new_func && !func->nop)
745 		return -EINVAL;
746 
747 	if (strlen(func->old_name) >= KSYM_NAME_LEN)
748 		return -EINVAL;
749 
750 	INIT_LIST_HEAD(&func->stack_node);
751 	func->patched = false;
752 	func->transition = false;
753 
754 	/* The format for the sysfs directory is <function,sympos> where sympos
755 	 * is the nth occurrence of this symbol in kallsyms for the patched
756 	 * object. If the user selects 0 for old_sympos, then 1 will be used
757 	 * since a unique symbol will be the first occurrence.
758 	 */
759 	return kobject_add(&func->kobj, &obj->kobj, "%s,%lu",
760 			   func->old_name,
761 			   func->old_sympos ? func->old_sympos : 1);
762 }
763 
764 static int klp_apply_object_relocs(struct klp_patch *patch,
765 				   struct klp_object *obj)
766 {
767 	int i, ret;
768 	struct klp_modinfo *info = patch->mod->klp_info;
769 
770 	for (i = 1; i < info->hdr.e_shnum; i++) {
771 		Elf_Shdr *sec = info->sechdrs + i;
772 
773 		if (!(sec->sh_flags & SHF_RELA_LIVEPATCH))
774 			continue;
775 
776 		ret = klp_apply_section_relocs(patch->mod, info->sechdrs,
777 					       info->secstrings,
778 					       patch->mod->core_kallsyms.strtab,
779 					       info->symndx, i, obj->name);
780 		if (ret)
781 			return ret;
782 	}
783 
784 	return 0;
785 }
786 
787 /* parts of the initialization that is done only when the object is loaded */
788 static int klp_init_object_loaded(struct klp_patch *patch,
789 				  struct klp_object *obj)
790 {
791 	struct klp_func *func;
792 	int ret;
793 
794 	if (klp_is_module(obj)) {
795 		/*
796 		 * Only write module-specific relocations here
797 		 * (.klp.rela.{module}.*).  vmlinux-specific relocations were
798 		 * written earlier during the initialization of the klp module
799 		 * itself.
800 		 */
801 		ret = klp_apply_object_relocs(patch, obj);
802 		if (ret)
803 			return ret;
804 	}
805 
806 	klp_for_each_func(obj, func) {
807 		ret = klp_find_object_symbol(obj->name, func->old_name,
808 					     func->old_sympos,
809 					     (unsigned long *)&func->old_func);
810 		if (ret)
811 			return ret;
812 
813 		ret = kallsyms_lookup_size_offset((unsigned long)func->old_func,
814 						  &func->old_size, NULL);
815 		if (!ret) {
816 			pr_err("kallsyms size lookup failed for '%s'\n",
817 			       func->old_name);
818 			return -ENOENT;
819 		}
820 
821 		if (func->nop)
822 			func->new_func = func->old_func;
823 
824 		ret = kallsyms_lookup_size_offset((unsigned long)func->new_func,
825 						  &func->new_size, NULL);
826 		if (!ret) {
827 			pr_err("kallsyms size lookup failed for '%s' replacement\n",
828 			       func->old_name);
829 			return -ENOENT;
830 		}
831 	}
832 
833 	return 0;
834 }
835 
836 static int klp_init_object(struct klp_patch *patch, struct klp_object *obj)
837 {
838 	struct klp_func *func;
839 	int ret;
840 	const char *name;
841 
842 	if (klp_is_module(obj) && strlen(obj->name) >= MODULE_NAME_LEN)
843 		return -EINVAL;
844 
845 	obj->patched = false;
846 	obj->mod = NULL;
847 
848 	klp_find_object_module(obj);
849 
850 	name = klp_is_module(obj) ? obj->name : "vmlinux";
851 	ret = kobject_add(&obj->kobj, &patch->kobj, "%s", name);
852 	if (ret)
853 		return ret;
854 
855 	klp_for_each_func(obj, func) {
856 		ret = klp_init_func(obj, func);
857 		if (ret)
858 			return ret;
859 	}
860 
861 	if (klp_is_object_loaded(obj))
862 		ret = klp_init_object_loaded(patch, obj);
863 
864 	return ret;
865 }
866 
867 static void klp_init_func_early(struct klp_object *obj,
868 				struct klp_func *func)
869 {
870 	kobject_init(&func->kobj, &klp_ktype_func);
871 	list_add_tail(&func->node, &obj->func_list);
872 }
873 
874 static void klp_init_object_early(struct klp_patch *patch,
875 				  struct klp_object *obj)
876 {
877 	INIT_LIST_HEAD(&obj->func_list);
878 	kobject_init(&obj->kobj, &klp_ktype_object);
879 	list_add_tail(&obj->node, &patch->obj_list);
880 }
881 
882 static void klp_init_patch_early(struct klp_patch *patch)
883 {
884 	struct klp_object *obj;
885 	struct klp_func *func;
886 
887 	INIT_LIST_HEAD(&patch->list);
888 	INIT_LIST_HEAD(&patch->obj_list);
889 	kobject_init(&patch->kobj, &klp_ktype_patch);
890 	patch->enabled = false;
891 	patch->forced = false;
892 	INIT_WORK(&patch->free_work, klp_free_patch_work_fn);
893 	init_completion(&patch->finish);
894 
895 	klp_for_each_object_static(patch, obj) {
896 		klp_init_object_early(patch, obj);
897 
898 		klp_for_each_func_static(obj, func) {
899 			klp_init_func_early(obj, func);
900 		}
901 	}
902 }
903 
904 static int klp_init_patch(struct klp_patch *patch)
905 {
906 	struct klp_object *obj;
907 	int ret;
908 
909 	ret = kobject_add(&patch->kobj, klp_root_kobj, "%s", patch->mod->name);
910 	if (ret)
911 		return ret;
912 
913 	if (patch->replace) {
914 		ret = klp_add_nops(patch);
915 		if (ret)
916 			return ret;
917 	}
918 
919 	klp_for_each_object(patch, obj) {
920 		ret = klp_init_object(patch, obj);
921 		if (ret)
922 			return ret;
923 	}
924 
925 	list_add_tail(&patch->list, &klp_patches);
926 
927 	return 0;
928 }
929 
930 static int __klp_disable_patch(struct klp_patch *patch)
931 {
932 	struct klp_object *obj;
933 
934 	if (WARN_ON(!patch->enabled))
935 		return -EINVAL;
936 
937 	if (klp_transition_patch)
938 		return -EBUSY;
939 
940 	klp_init_transition(patch, KLP_UNPATCHED);
941 
942 	klp_for_each_object(patch, obj)
943 		if (obj->patched)
944 			klp_pre_unpatch_callback(obj);
945 
946 	/*
947 	 * Enforce the order of the func->transition writes in
948 	 * klp_init_transition() and the TIF_PATCH_PENDING writes in
949 	 * klp_start_transition().  In the rare case where klp_ftrace_handler()
950 	 * is called shortly after klp_update_patch_state() switches the task,
951 	 * this ensures the handler sees that func->transition is set.
952 	 */
953 	smp_wmb();
954 
955 	klp_start_transition();
956 	patch->enabled = false;
957 	klp_try_complete_transition();
958 
959 	return 0;
960 }
961 
962 static int __klp_enable_patch(struct klp_patch *patch)
963 {
964 	struct klp_object *obj;
965 	int ret;
966 
967 	if (klp_transition_patch)
968 		return -EBUSY;
969 
970 	if (WARN_ON(patch->enabled))
971 		return -EINVAL;
972 
973 	pr_notice("enabling patch '%s'\n", patch->mod->name);
974 
975 	klp_init_transition(patch, KLP_PATCHED);
976 
977 	/*
978 	 * Enforce the order of the func->transition writes in
979 	 * klp_init_transition() and the ops->func_stack writes in
980 	 * klp_patch_object(), so that klp_ftrace_handler() will see the
981 	 * func->transition updates before the handler is registered and the
982 	 * new funcs become visible to the handler.
983 	 */
984 	smp_wmb();
985 
986 	klp_for_each_object(patch, obj) {
987 		if (!klp_is_object_loaded(obj))
988 			continue;
989 
990 		ret = klp_pre_patch_callback(obj);
991 		if (ret) {
992 			pr_warn("pre-patch callback failed for object '%s'\n",
993 				klp_is_module(obj) ? obj->name : "vmlinux");
994 			goto err;
995 		}
996 
997 		ret = klp_patch_object(obj);
998 		if (ret) {
999 			pr_warn("failed to patch object '%s'\n",
1000 				klp_is_module(obj) ? obj->name : "vmlinux");
1001 			goto err;
1002 		}
1003 	}
1004 
1005 	klp_start_transition();
1006 	patch->enabled = true;
1007 	klp_try_complete_transition();
1008 
1009 	return 0;
1010 err:
1011 	pr_warn("failed to enable patch '%s'\n", patch->mod->name);
1012 
1013 	klp_cancel_transition();
1014 	return ret;
1015 }
1016 
1017 /**
1018  * klp_enable_patch() - enable the livepatch
1019  * @patch:	patch to be enabled
1020  *
1021  * Initializes the data structure associated with the patch, creates the sysfs
1022  * interface, performs the needed symbol lookups and code relocations,
1023  * registers the patched functions with ftrace.
1024  *
1025  * This function is supposed to be called from the livepatch module_init()
1026  * callback.
1027  *
1028  * Return: 0 on success, otherwise error
1029  */
1030 int klp_enable_patch(struct klp_patch *patch)
1031 {
1032 	int ret;
1033 	struct klp_object *obj;
1034 
1035 	if (!patch || !patch->mod || !patch->objs)
1036 		return -EINVAL;
1037 
1038 	klp_for_each_object_static(patch, obj) {
1039 		if (!obj->funcs)
1040 			return -EINVAL;
1041 	}
1042 
1043 
1044 	if (!is_livepatch_module(patch->mod)) {
1045 		pr_err("module %s is not marked as a livepatch module\n",
1046 		       patch->mod->name);
1047 		return -EINVAL;
1048 	}
1049 
1050 	if (!klp_initialized())
1051 		return -ENODEV;
1052 
1053 	if (!klp_have_reliable_stack()) {
1054 		pr_warn("This architecture doesn't have support for the livepatch consistency model.\n");
1055 		pr_warn("The livepatch transition may never complete.\n");
1056 	}
1057 
1058 	mutex_lock(&klp_mutex);
1059 
1060 	if (!klp_is_patch_compatible(patch)) {
1061 		pr_err("Livepatch patch (%s) is not compatible with the already installed livepatches.\n",
1062 			patch->mod->name);
1063 		mutex_unlock(&klp_mutex);
1064 		return -EINVAL;
1065 	}
1066 
1067 	if (!try_module_get(patch->mod)) {
1068 		mutex_unlock(&klp_mutex);
1069 		return -ENODEV;
1070 	}
1071 
1072 	klp_init_patch_early(patch);
1073 
1074 	ret = klp_init_patch(patch);
1075 	if (ret)
1076 		goto err;
1077 
1078 	ret = __klp_enable_patch(patch);
1079 	if (ret)
1080 		goto err;
1081 
1082 	mutex_unlock(&klp_mutex);
1083 
1084 	return 0;
1085 
1086 err:
1087 	klp_free_patch_start(patch);
1088 
1089 	mutex_unlock(&klp_mutex);
1090 
1091 	klp_free_patch_finish(patch);
1092 
1093 	return ret;
1094 }
1095 EXPORT_SYMBOL_GPL(klp_enable_patch);
1096 
1097 /*
1098  * This function unpatches objects from the replaced livepatches.
1099  *
1100  * We could be pretty aggressive here. It is called in the situation where
1101  * these structures are no longer accessed from the ftrace handler.
1102  * All functions are redirected by the klp_transition_patch. They
1103  * use either a new code or they are in the original code because
1104  * of the special nop function patches.
1105  *
1106  * The only exception is when the transition was forced. In this case,
1107  * klp_ftrace_handler() might still see the replaced patch on the stack.
1108  * Fortunately, it is carefully designed to work with removed functions
1109  * thanks to RCU. We only have to keep the patches on the system. Also
1110  * this is handled transparently by patch->module_put.
1111  */
1112 void klp_unpatch_replaced_patches(struct klp_patch *new_patch)
1113 {
1114 	struct klp_patch *old_patch;
1115 
1116 	klp_for_each_patch(old_patch) {
1117 		if (old_patch == new_patch)
1118 			return;
1119 
1120 		old_patch->enabled = false;
1121 		klp_unpatch_objects(old_patch);
1122 	}
1123 }
1124 
1125 /*
1126  * This function removes the dynamically allocated 'nop' functions.
1127  *
1128  * We could be pretty aggressive. NOPs do not change the existing
1129  * behavior except for adding unnecessary delay by the ftrace handler.
1130  *
1131  * It is safe even when the transition was forced. The ftrace handler
1132  * will see a valid ops->func_stack entry thanks to RCU.
1133  *
1134  * We could even free the NOPs structures. They must be the last entry
1135  * in ops->func_stack. Therefore unregister_ftrace_function() is called.
1136  * It does the same as klp_synchronize_transition() to make sure that
1137  * nobody is inside the ftrace handler once the operation finishes.
1138  *
1139  * IMPORTANT: It must be called right after removing the replaced patches!
1140  */
1141 void klp_discard_nops(struct klp_patch *new_patch)
1142 {
1143 	klp_unpatch_objects_dynamic(klp_transition_patch);
1144 	klp_free_objects_dynamic(klp_transition_patch);
1145 }
1146 
1147 /*
1148  * Remove parts of patches that touch a given kernel module. The list of
1149  * patches processed might be limited. When limit is NULL, all patches
1150  * will be handled.
1151  */
1152 static void klp_cleanup_module_patches_limited(struct module *mod,
1153 					       struct klp_patch *limit)
1154 {
1155 	struct klp_patch *patch;
1156 	struct klp_object *obj;
1157 
1158 	klp_for_each_patch(patch) {
1159 		if (patch == limit)
1160 			break;
1161 
1162 		klp_for_each_object(patch, obj) {
1163 			if (!klp_is_module(obj) || strcmp(obj->name, mod->name))
1164 				continue;
1165 
1166 			if (patch != klp_transition_patch)
1167 				klp_pre_unpatch_callback(obj);
1168 
1169 			pr_notice("reverting patch '%s' on unloading module '%s'\n",
1170 				  patch->mod->name, obj->mod->name);
1171 			klp_unpatch_object(obj);
1172 
1173 			klp_post_unpatch_callback(obj);
1174 
1175 			klp_free_object_loaded(obj);
1176 			break;
1177 		}
1178 	}
1179 }
1180 
1181 int klp_module_coming(struct module *mod)
1182 {
1183 	int ret;
1184 	struct klp_patch *patch;
1185 	struct klp_object *obj;
1186 
1187 	if (WARN_ON(mod->state != MODULE_STATE_COMING))
1188 		return -EINVAL;
1189 
1190 	if (!strcmp(mod->name, "vmlinux")) {
1191 		pr_err("vmlinux.ko: invalid module name\n");
1192 		return -EINVAL;
1193 	}
1194 
1195 	mutex_lock(&klp_mutex);
1196 	/*
1197 	 * Each module has to know that klp_module_coming()
1198 	 * has been called. We never know what module will
1199 	 * get patched by a new patch.
1200 	 */
1201 	mod->klp_alive = true;
1202 
1203 	klp_for_each_patch(patch) {
1204 		klp_for_each_object(patch, obj) {
1205 			if (!klp_is_module(obj) || strcmp(obj->name, mod->name))
1206 				continue;
1207 
1208 			obj->mod = mod;
1209 
1210 			ret = klp_init_object_loaded(patch, obj);
1211 			if (ret) {
1212 				pr_warn("failed to initialize patch '%s' for module '%s' (%d)\n",
1213 					patch->mod->name, obj->mod->name, ret);
1214 				goto err;
1215 			}
1216 
1217 			pr_notice("applying patch '%s' to loading module '%s'\n",
1218 				  patch->mod->name, obj->mod->name);
1219 
1220 			ret = klp_pre_patch_callback(obj);
1221 			if (ret) {
1222 				pr_warn("pre-patch callback failed for object '%s'\n",
1223 					obj->name);
1224 				goto err;
1225 			}
1226 
1227 			ret = klp_patch_object(obj);
1228 			if (ret) {
1229 				pr_warn("failed to apply patch '%s' to module '%s' (%d)\n",
1230 					patch->mod->name, obj->mod->name, ret);
1231 
1232 				klp_post_unpatch_callback(obj);
1233 				goto err;
1234 			}
1235 
1236 			if (patch != klp_transition_patch)
1237 				klp_post_patch_callback(obj);
1238 
1239 			break;
1240 		}
1241 	}
1242 
1243 	mutex_unlock(&klp_mutex);
1244 
1245 	return 0;
1246 
1247 err:
1248 	/*
1249 	 * If a patch is unsuccessfully applied, return
1250 	 * error to the module loader.
1251 	 */
1252 	pr_warn("patch '%s' failed for module '%s', refusing to load module '%s'\n",
1253 		patch->mod->name, obj->mod->name, obj->mod->name);
1254 	mod->klp_alive = false;
1255 	obj->mod = NULL;
1256 	klp_cleanup_module_patches_limited(mod, patch);
1257 	mutex_unlock(&klp_mutex);
1258 
1259 	return ret;
1260 }
1261 
1262 void klp_module_going(struct module *mod)
1263 {
1264 	if (WARN_ON(mod->state != MODULE_STATE_GOING &&
1265 		    mod->state != MODULE_STATE_COMING))
1266 		return;
1267 
1268 	mutex_lock(&klp_mutex);
1269 	/*
1270 	 * Each module has to know that klp_module_going()
1271 	 * has been called. We never know what module will
1272 	 * get patched by a new patch.
1273 	 */
1274 	mod->klp_alive = false;
1275 
1276 	klp_cleanup_module_patches_limited(mod, NULL);
1277 
1278 	mutex_unlock(&klp_mutex);
1279 }
1280 
1281 static int __init klp_init(void)
1282 {
1283 	klp_root_kobj = kobject_create_and_add("livepatch", kernel_kobj);
1284 	if (!klp_root_kobj)
1285 		return -ENOMEM;
1286 
1287 	return 0;
1288 }
1289 
1290 module_init(klp_init);
1291