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