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