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