xref: /linux-6.15/kernel/livepatch/core.c (revision 958ef1e3)
1 /*
2  * core.c - Kernel Live Patching Core
3  *
4  * Copyright (C) 2014 Seth Jennings <[email protected]>
5  * Copyright (C) 2014 SUSE
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20 
21 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
22 
23 #include <linux/module.h>
24 #include <linux/kernel.h>
25 #include <linux/mutex.h>
26 #include <linux/slab.h>
27 #include <linux/list.h>
28 #include <linux/kallsyms.h>
29 #include <linux/livepatch.h>
30 #include <linux/elf.h>
31 #include <linux/moduleloader.h>
32 #include <linux/completion.h>
33 #include <asm/cacheflush.h>
34 #include "core.h"
35 #include "patch.h"
36 #include "transition.h"
37 
38 /*
39  * klp_mutex is a coarse lock which serializes access to klp data.  All
40  * accesses to klp-related variables and structures must have mutex protection,
41  * except within the following functions which carefully avoid the need for it:
42  *
43  * - klp_ftrace_handler()
44  * - klp_update_patch_state()
45  */
46 DEFINE_MUTEX(klp_mutex);
47 
48 /*
49  * Actively used patches: enabled or in transition. Note that replaced
50  * or disabled patches are not listed even though the related kernel
51  * module still can be loaded.
52  */
53 LIST_HEAD(klp_patches);
54 
55 static struct kobject *klp_root_kobj;
56 
57 static bool klp_is_module(struct klp_object *obj)
58 {
59 	return obj->name;
60 }
61 
62 /* sets obj->mod if object is not vmlinux and module is found */
63 static void klp_find_object_module(struct klp_object *obj)
64 {
65 	struct module *mod;
66 
67 	if (!klp_is_module(obj))
68 		return;
69 
70 	mutex_lock(&module_mutex);
71 	/*
72 	 * We do not want to block removal of patched modules and therefore
73 	 * we do not take a reference here. The patches are removed by
74 	 * klp_module_going() instead.
75 	 */
76 	mod = find_module(obj->name);
77 	/*
78 	 * Do not mess work of klp_module_coming() and klp_module_going().
79 	 * Note that the patch might still be needed before klp_module_going()
80 	 * is called. Module functions can be called even in the GOING state
81 	 * until mod->exit() finishes. This is especially important for
82 	 * patches that modify semantic of the functions.
83 	 */
84 	if (mod && mod->klp_alive)
85 		obj->mod = mod;
86 
87 	mutex_unlock(&module_mutex);
88 }
89 
90 static bool klp_initialized(void)
91 {
92 	return !!klp_root_kobj;
93 }
94 
95 struct klp_find_arg {
96 	const char *objname;
97 	const char *name;
98 	unsigned long addr;
99 	unsigned long count;
100 	unsigned long pos;
101 };
102 
103 static int klp_find_callback(void *data, const char *name,
104 			     struct module *mod, unsigned long addr)
105 {
106 	struct klp_find_arg *args = data;
107 
108 	if ((mod && !args->objname) || (!mod && args->objname))
109 		return 0;
110 
111 	if (strcmp(args->name, name))
112 		return 0;
113 
114 	if (args->objname && strcmp(args->objname, mod->name))
115 		return 0;
116 
117 	args->addr = addr;
118 	args->count++;
119 
120 	/*
121 	 * Finish the search when the symbol is found for the desired position
122 	 * or the position is not defined for a non-unique symbol.
123 	 */
124 	if ((args->pos && (args->count == args->pos)) ||
125 	    (!args->pos && (args->count > 1)))
126 		return 1;
127 
128 	return 0;
129 }
130 
131 static int klp_find_object_symbol(const char *objname, const char *name,
132 				  unsigned long sympos, unsigned long *addr)
133 {
134 	struct klp_find_arg args = {
135 		.objname = objname,
136 		.name = name,
137 		.addr = 0,
138 		.count = 0,
139 		.pos = sympos,
140 	};
141 
142 	mutex_lock(&module_mutex);
143 	if (objname)
144 		module_kallsyms_on_each_symbol(klp_find_callback, &args);
145 	else
146 		kallsyms_on_each_symbol(klp_find_callback, &args);
147 	mutex_unlock(&module_mutex);
148 
149 	/*
150 	 * Ensure an address was found. If sympos is 0, ensure symbol is unique;
151 	 * otherwise ensure the symbol position count matches sympos.
152 	 */
153 	if (args.addr == 0)
154 		pr_err("symbol '%s' not found in symbol table\n", name);
155 	else if (args.count > 1 && sympos == 0) {
156 		pr_err("unresolvable ambiguity for symbol '%s' in object '%s'\n",
157 		       name, objname);
158 	} else if (sympos != args.count && sympos > 0) {
159 		pr_err("symbol position %lu for symbol '%s' in object '%s' not found\n",
160 		       sympos, name, objname ? objname : "vmlinux");
161 	} else {
162 		*addr = args.addr;
163 		return 0;
164 	}
165 
166 	*addr = 0;
167 	return -EINVAL;
168 }
169 
170 static int klp_resolve_symbols(Elf_Shdr *relasec, struct module *pmod)
171 {
172 	int i, cnt, vmlinux, ret;
173 	char objname[MODULE_NAME_LEN];
174 	char symname[KSYM_NAME_LEN];
175 	char *strtab = pmod->core_kallsyms.strtab;
176 	Elf_Rela *relas;
177 	Elf_Sym *sym;
178 	unsigned long sympos, addr;
179 
180 	/*
181 	 * Since the field widths for objname and symname in the sscanf()
182 	 * call are hard-coded and correspond to MODULE_NAME_LEN and
183 	 * KSYM_NAME_LEN respectively, we must make sure that MODULE_NAME_LEN
184 	 * and KSYM_NAME_LEN have the values we expect them to have.
185 	 *
186 	 * Because the value of MODULE_NAME_LEN can differ among architectures,
187 	 * we use the smallest/strictest upper bound possible (56, based on
188 	 * the current definition of MODULE_NAME_LEN) to prevent overflows.
189 	 */
190 	BUILD_BUG_ON(MODULE_NAME_LEN < 56 || KSYM_NAME_LEN != 128);
191 
192 	relas = (Elf_Rela *) relasec->sh_addr;
193 	/* For each rela in this klp relocation section */
194 	for (i = 0; i < relasec->sh_size / sizeof(Elf_Rela); i++) {
195 		sym = pmod->core_kallsyms.symtab + ELF_R_SYM(relas[i].r_info);
196 		if (sym->st_shndx != SHN_LIVEPATCH) {
197 			pr_err("symbol %s is not marked as a livepatch symbol\n",
198 			       strtab + sym->st_name);
199 			return -EINVAL;
200 		}
201 
202 		/* Format: .klp.sym.objname.symname,sympos */
203 		cnt = sscanf(strtab + sym->st_name,
204 			     ".klp.sym.%55[^.].%127[^,],%lu",
205 			     objname, symname, &sympos);
206 		if (cnt != 3) {
207 			pr_err("symbol %s has an incorrectly formatted name\n",
208 			       strtab + sym->st_name);
209 			return -EINVAL;
210 		}
211 
212 		/* klp_find_object_symbol() treats a NULL objname as vmlinux */
213 		vmlinux = !strcmp(objname, "vmlinux");
214 		ret = klp_find_object_symbol(vmlinux ? NULL : objname,
215 					     symname, sympos, &addr);
216 		if (ret)
217 			return ret;
218 
219 		sym->st_value = addr;
220 	}
221 
222 	return 0;
223 }
224 
225 static int klp_write_object_relocations(struct module *pmod,
226 					struct klp_object *obj)
227 {
228 	int i, cnt, ret = 0;
229 	const char *objname, *secname;
230 	char sec_objname[MODULE_NAME_LEN];
231 	Elf_Shdr *sec;
232 
233 	if (WARN_ON(!klp_is_object_loaded(obj)))
234 		return -EINVAL;
235 
236 	objname = klp_is_module(obj) ? obj->name : "vmlinux";
237 
238 	/* For each klp relocation section */
239 	for (i = 1; i < pmod->klp_info->hdr.e_shnum; i++) {
240 		sec = pmod->klp_info->sechdrs + i;
241 		secname = pmod->klp_info->secstrings + sec->sh_name;
242 		if (!(sec->sh_flags & SHF_RELA_LIVEPATCH))
243 			continue;
244 
245 		/*
246 		 * Format: .klp.rela.sec_objname.section_name
247 		 * See comment in klp_resolve_symbols() for an explanation
248 		 * of the selected field width value.
249 		 */
250 		cnt = sscanf(secname, ".klp.rela.%55[^.]", sec_objname);
251 		if (cnt != 1) {
252 			pr_err("section %s has an incorrectly formatted name\n",
253 			       secname);
254 			ret = -EINVAL;
255 			break;
256 		}
257 
258 		if (strcmp(objname, sec_objname))
259 			continue;
260 
261 		ret = klp_resolve_symbols(sec, pmod);
262 		if (ret)
263 			break;
264 
265 		ret = apply_relocate_add(pmod->klp_info->sechdrs,
266 					 pmod->core_kallsyms.strtab,
267 					 pmod->klp_info->symndx, i, pmod);
268 		if (ret)
269 			break;
270 	}
271 
272 	return ret;
273 }
274 
275 /*
276  * Sysfs Interface
277  *
278  * /sys/kernel/livepatch
279  * /sys/kernel/livepatch/<patch>
280  * /sys/kernel/livepatch/<patch>/enabled
281  * /sys/kernel/livepatch/<patch>/transition
282  * /sys/kernel/livepatch/<patch>/signal
283  * /sys/kernel/livepatch/<patch>/force
284  * /sys/kernel/livepatch/<patch>/<object>
285  * /sys/kernel/livepatch/<patch>/<object>/<function,sympos>
286  */
287 static int __klp_disable_patch(struct klp_patch *patch);
288 
289 static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
290 			     const char *buf, size_t count)
291 {
292 	struct klp_patch *patch;
293 	int ret;
294 	bool enabled;
295 
296 	ret = kstrtobool(buf, &enabled);
297 	if (ret)
298 		return ret;
299 
300 	patch = container_of(kobj, struct klp_patch, kobj);
301 
302 	mutex_lock(&klp_mutex);
303 
304 	if (patch->enabled == enabled) {
305 		/* already in requested state */
306 		ret = -EINVAL;
307 		goto out;
308 	}
309 
310 	/*
311 	 * Allow to reverse a pending transition in both ways. It might be
312 	 * necessary to complete the transition without forcing and breaking
313 	 * the system integrity.
314 	 *
315 	 * Do not allow to re-enable a disabled patch.
316 	 */
317 	if (patch == klp_transition_patch)
318 		klp_reverse_transition();
319 	else if (!enabled)
320 		ret = __klp_disable_patch(patch);
321 	else
322 		ret = -EINVAL;
323 
324 out:
325 	mutex_unlock(&klp_mutex);
326 
327 	if (ret)
328 		return ret;
329 	return count;
330 }
331 
332 static ssize_t enabled_show(struct kobject *kobj,
333 			    struct kobj_attribute *attr, char *buf)
334 {
335 	struct klp_patch *patch;
336 
337 	patch = container_of(kobj, struct klp_patch, kobj);
338 	return snprintf(buf, PAGE_SIZE-1, "%d\n", patch->enabled);
339 }
340 
341 static ssize_t transition_show(struct kobject *kobj,
342 			       struct kobj_attribute *attr, char *buf)
343 {
344 	struct klp_patch *patch;
345 
346 	patch = container_of(kobj, struct klp_patch, kobj);
347 	return snprintf(buf, PAGE_SIZE-1, "%d\n",
348 			patch == klp_transition_patch);
349 }
350 
351 static ssize_t signal_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 val;
357 
358 	ret = kstrtobool(buf, &val);
359 	if (ret)
360 		return ret;
361 
362 	if (!val)
363 		return count;
364 
365 	mutex_lock(&klp_mutex);
366 
367 	patch = container_of(kobj, struct klp_patch, kobj);
368 	if (patch != klp_transition_patch) {
369 		mutex_unlock(&klp_mutex);
370 		return -EINVAL;
371 	}
372 
373 	klp_send_signals();
374 
375 	mutex_unlock(&klp_mutex);
376 
377 	return count;
378 }
379 
380 static ssize_t force_store(struct kobject *kobj, struct kobj_attribute *attr,
381 			   const char *buf, size_t count)
382 {
383 	struct klp_patch *patch;
384 	int ret;
385 	bool val;
386 
387 	ret = kstrtobool(buf, &val);
388 	if (ret)
389 		return ret;
390 
391 	if (!val)
392 		return count;
393 
394 	mutex_lock(&klp_mutex);
395 
396 	patch = container_of(kobj, struct klp_patch, kobj);
397 	if (patch != klp_transition_patch) {
398 		mutex_unlock(&klp_mutex);
399 		return -EINVAL;
400 	}
401 
402 	klp_force_transition();
403 
404 	mutex_unlock(&klp_mutex);
405 
406 	return count;
407 }
408 
409 static struct kobj_attribute enabled_kobj_attr = __ATTR_RW(enabled);
410 static struct kobj_attribute transition_kobj_attr = __ATTR_RO(transition);
411 static struct kobj_attribute signal_kobj_attr = __ATTR_WO(signal);
412 static struct kobj_attribute force_kobj_attr = __ATTR_WO(force);
413 static struct attribute *klp_patch_attrs[] = {
414 	&enabled_kobj_attr.attr,
415 	&transition_kobj_attr.attr,
416 	&signal_kobj_attr.attr,
417 	&force_kobj_attr.attr,
418 	NULL
419 };
420 
421 static void klp_kobj_release_patch(struct kobject *kobj)
422 {
423 	struct klp_patch *patch;
424 
425 	patch = container_of(kobj, struct klp_patch, kobj);
426 	complete(&patch->finish);
427 }
428 
429 static struct kobj_type klp_ktype_patch = {
430 	.release = klp_kobj_release_patch,
431 	.sysfs_ops = &kobj_sysfs_ops,
432 	.default_attrs = klp_patch_attrs,
433 };
434 
435 static void klp_kobj_release_object(struct kobject *kobj)
436 {
437 }
438 
439 static struct kobj_type klp_ktype_object = {
440 	.release = klp_kobj_release_object,
441 	.sysfs_ops = &kobj_sysfs_ops,
442 };
443 
444 static void klp_kobj_release_func(struct kobject *kobj)
445 {
446 }
447 
448 static struct kobj_type klp_ktype_func = {
449 	.release = klp_kobj_release_func,
450 	.sysfs_ops = &kobj_sysfs_ops,
451 };
452 
453 static void klp_free_funcs(struct klp_object *obj)
454 {
455 	struct klp_func *func;
456 
457 	klp_for_each_func(obj, func) {
458 		/* Might be called from klp_init_patch() error path. */
459 		if (func->kobj_added)
460 			kobject_put(&func->kobj);
461 	}
462 }
463 
464 /* Clean up when a patched object is unloaded */
465 static void klp_free_object_loaded(struct klp_object *obj)
466 {
467 	struct klp_func *func;
468 
469 	obj->mod = NULL;
470 
471 	klp_for_each_func(obj, func)
472 		func->old_func = NULL;
473 }
474 
475 static void klp_free_objects(struct klp_patch *patch)
476 {
477 	struct klp_object *obj;
478 
479 	klp_for_each_object(patch, obj) {
480 		klp_free_funcs(obj);
481 
482 		/* Might be called from klp_init_patch() error path. */
483 		if (obj->kobj_added)
484 			kobject_put(&obj->kobj);
485 	}
486 }
487 
488 /*
489  * This function implements the free operations that can be called safely
490  * under klp_mutex.
491  *
492  * The operation must be completed by calling klp_free_patch_finish()
493  * outside klp_mutex.
494  */
495 void klp_free_patch_start(struct klp_patch *patch)
496 {
497 	if (!list_empty(&patch->list))
498 		list_del(&patch->list);
499 
500 	klp_free_objects(patch);
501 }
502 
503 /*
504  * This function implements the free part that must be called outside
505  * klp_mutex.
506  *
507  * It must be called after klp_free_patch_start(). And it has to be
508  * the last function accessing the livepatch structures when the patch
509  * gets disabled.
510  */
511 static void klp_free_patch_finish(struct klp_patch *patch)
512 {
513 	/*
514 	 * Avoid deadlock with enabled_store() sysfs callback by
515 	 * calling this outside klp_mutex. It is safe because
516 	 * this is called when the patch gets disabled and it
517 	 * cannot get enabled again.
518 	 */
519 	if (patch->kobj_added) {
520 		kobject_put(&patch->kobj);
521 		wait_for_completion(&patch->finish);
522 	}
523 
524 	/* Put the module after the last access to struct klp_patch. */
525 	if (!patch->forced)
526 		module_put(patch->mod);
527 }
528 
529 /*
530  * The livepatch might be freed from sysfs interface created by the patch.
531  * This work allows to wait until the interface is destroyed in a separate
532  * context.
533  */
534 static void klp_free_patch_work_fn(struct work_struct *work)
535 {
536 	struct klp_patch *patch =
537 		container_of(work, struct klp_patch, free_work);
538 
539 	klp_free_patch_finish(patch);
540 }
541 
542 static int klp_init_func(struct klp_object *obj, struct klp_func *func)
543 {
544 	int ret;
545 
546 	if (!func->old_name || !func->new_func)
547 		return -EINVAL;
548 
549 	if (strlen(func->old_name) >= KSYM_NAME_LEN)
550 		return -EINVAL;
551 
552 	INIT_LIST_HEAD(&func->stack_node);
553 	func->patched = false;
554 	func->transition = false;
555 
556 	/* The format for the sysfs directory is <function,sympos> where sympos
557 	 * is the nth occurrence of this symbol in kallsyms for the patched
558 	 * object. If the user selects 0 for old_sympos, then 1 will be used
559 	 * since a unique symbol will be the first occurrence.
560 	 */
561 	ret = kobject_init_and_add(&func->kobj, &klp_ktype_func,
562 				   &obj->kobj, "%s,%lu", func->old_name,
563 				   func->old_sympos ? func->old_sympos : 1);
564 	if (!ret)
565 		func->kobj_added = true;
566 
567 	return ret;
568 }
569 
570 /* Arches may override this to finish any remaining arch-specific tasks */
571 void __weak arch_klp_init_object_loaded(struct klp_patch *patch,
572 					struct klp_object *obj)
573 {
574 }
575 
576 /* parts of the initialization that is done only when the object is loaded */
577 static int klp_init_object_loaded(struct klp_patch *patch,
578 				  struct klp_object *obj)
579 {
580 	struct klp_func *func;
581 	int ret;
582 
583 	module_disable_ro(patch->mod);
584 	ret = klp_write_object_relocations(patch->mod, obj);
585 	if (ret) {
586 		module_enable_ro(patch->mod, true);
587 		return ret;
588 	}
589 
590 	arch_klp_init_object_loaded(patch, obj);
591 	module_enable_ro(patch->mod, true);
592 
593 	klp_for_each_func(obj, func) {
594 		ret = klp_find_object_symbol(obj->name, func->old_name,
595 					     func->old_sympos,
596 					     (unsigned long *)&func->old_func);
597 		if (ret)
598 			return ret;
599 
600 		ret = kallsyms_lookup_size_offset((unsigned long)func->old_func,
601 						  &func->old_size, NULL);
602 		if (!ret) {
603 			pr_err("kallsyms size lookup failed for '%s'\n",
604 			       func->old_name);
605 			return -ENOENT;
606 		}
607 
608 		ret = kallsyms_lookup_size_offset((unsigned long)func->new_func,
609 						  &func->new_size, NULL);
610 		if (!ret) {
611 			pr_err("kallsyms size lookup failed for '%s' replacement\n",
612 			       func->old_name);
613 			return -ENOENT;
614 		}
615 	}
616 
617 	return 0;
618 }
619 
620 static int klp_init_object(struct klp_patch *patch, struct klp_object *obj)
621 {
622 	struct klp_func *func;
623 	int ret;
624 	const char *name;
625 
626 	if (klp_is_module(obj) && strlen(obj->name) >= MODULE_NAME_LEN)
627 		return -EINVAL;
628 
629 	obj->patched = false;
630 	obj->mod = NULL;
631 
632 	klp_find_object_module(obj);
633 
634 	name = klp_is_module(obj) ? obj->name : "vmlinux";
635 	ret = kobject_init_and_add(&obj->kobj, &klp_ktype_object,
636 				   &patch->kobj, "%s", name);
637 	if (ret)
638 		return ret;
639 	obj->kobj_added = true;
640 
641 	klp_for_each_func(obj, func) {
642 		ret = klp_init_func(obj, func);
643 		if (ret)
644 			return ret;
645 	}
646 
647 	if (klp_is_object_loaded(obj))
648 		ret = klp_init_object_loaded(patch, obj);
649 
650 	return ret;
651 }
652 
653 static int klp_init_patch_early(struct klp_patch *patch)
654 {
655 	struct klp_object *obj;
656 	struct klp_func *func;
657 
658 	if (!patch->objs)
659 		return -EINVAL;
660 
661 	INIT_LIST_HEAD(&patch->list);
662 	patch->kobj_added = false;
663 	patch->enabled = false;
664 	patch->forced = false;
665 	INIT_WORK(&patch->free_work, klp_free_patch_work_fn);
666 	init_completion(&patch->finish);
667 
668 	klp_for_each_object(patch, obj) {
669 		if (!obj->funcs)
670 			return -EINVAL;
671 
672 		obj->kobj_added = false;
673 
674 		klp_for_each_func(obj, func)
675 			func->kobj_added = false;
676 	}
677 
678 	if (!try_module_get(patch->mod))
679 		return -ENODEV;
680 
681 	return 0;
682 }
683 
684 static int klp_init_patch(struct klp_patch *patch)
685 {
686 	struct klp_object *obj;
687 	int ret;
688 
689 	ret = kobject_init_and_add(&patch->kobj, &klp_ktype_patch,
690 				   klp_root_kobj, "%s", patch->mod->name);
691 	if (ret)
692 		return ret;
693 	patch->kobj_added = true;
694 
695 	klp_for_each_object(patch, obj) {
696 		ret = klp_init_object(patch, obj);
697 		if (ret)
698 			return ret;
699 	}
700 
701 	list_add_tail(&patch->list, &klp_patches);
702 
703 	return 0;
704 }
705 
706 static int __klp_disable_patch(struct klp_patch *patch)
707 {
708 	struct klp_object *obj;
709 
710 	if (WARN_ON(!patch->enabled))
711 		return -EINVAL;
712 
713 	if (klp_transition_patch)
714 		return -EBUSY;
715 
716 	/* enforce stacking: only the last enabled patch can be disabled */
717 	if (!list_is_last(&patch->list, &klp_patches))
718 		return -EBUSY;
719 
720 	klp_init_transition(patch, KLP_UNPATCHED);
721 
722 	klp_for_each_object(patch, obj)
723 		if (obj->patched)
724 			klp_pre_unpatch_callback(obj);
725 
726 	/*
727 	 * Enforce the order of the func->transition writes in
728 	 * klp_init_transition() and the TIF_PATCH_PENDING writes in
729 	 * klp_start_transition().  In the rare case where klp_ftrace_handler()
730 	 * is called shortly after klp_update_patch_state() switches the task,
731 	 * this ensures the handler sees that func->transition is set.
732 	 */
733 	smp_wmb();
734 
735 	klp_start_transition();
736 	patch->enabled = false;
737 	klp_try_complete_transition();
738 
739 	return 0;
740 }
741 
742 static int __klp_enable_patch(struct klp_patch *patch)
743 {
744 	struct klp_object *obj;
745 	int ret;
746 
747 	if (klp_transition_patch)
748 		return -EBUSY;
749 
750 	if (WARN_ON(patch->enabled))
751 		return -EINVAL;
752 
753 	if (!patch->kobj_added)
754 		return -EINVAL;
755 
756 	pr_notice("enabling patch '%s'\n", patch->mod->name);
757 
758 	klp_init_transition(patch, KLP_PATCHED);
759 
760 	/*
761 	 * Enforce the order of the func->transition writes in
762 	 * klp_init_transition() and the ops->func_stack writes in
763 	 * klp_patch_object(), so that klp_ftrace_handler() will see the
764 	 * func->transition updates before the handler is registered and the
765 	 * new funcs become visible to the handler.
766 	 */
767 	smp_wmb();
768 
769 	klp_for_each_object(patch, obj) {
770 		if (!klp_is_object_loaded(obj))
771 			continue;
772 
773 		ret = klp_pre_patch_callback(obj);
774 		if (ret) {
775 			pr_warn("pre-patch callback failed for object '%s'\n",
776 				klp_is_module(obj) ? obj->name : "vmlinux");
777 			goto err;
778 		}
779 
780 		ret = klp_patch_object(obj);
781 		if (ret) {
782 			pr_warn("failed to patch object '%s'\n",
783 				klp_is_module(obj) ? obj->name : "vmlinux");
784 			goto err;
785 		}
786 	}
787 
788 	klp_start_transition();
789 	patch->enabled = true;
790 	klp_try_complete_transition();
791 
792 	return 0;
793 err:
794 	pr_warn("failed to enable patch '%s'\n", patch->mod->name);
795 
796 	klp_cancel_transition();
797 	return ret;
798 }
799 
800 /**
801  * klp_enable_patch() - enable the livepatch
802  * @patch:	patch to be enabled
803  *
804  * Initializes the data structure associated with the patch, creates the sysfs
805  * interface, performs the needed symbol lookups and code relocations,
806  * registers the patched functions with ftrace.
807  *
808  * This function is supposed to be called from the livepatch module_init()
809  * callback.
810  *
811  * Return: 0 on success, otherwise error
812  */
813 int klp_enable_patch(struct klp_patch *patch)
814 {
815 	int ret;
816 
817 	if (!patch || !patch->mod)
818 		return -EINVAL;
819 
820 	if (!is_livepatch_module(patch->mod)) {
821 		pr_err("module %s is not marked as a livepatch module\n",
822 		       patch->mod->name);
823 		return -EINVAL;
824 	}
825 
826 	if (!klp_initialized())
827 		return -ENODEV;
828 
829 	if (!klp_have_reliable_stack()) {
830 		pr_err("This architecture doesn't have support for the livepatch consistency model.\n");
831 		return -ENOSYS;
832 	}
833 
834 
835 	mutex_lock(&klp_mutex);
836 
837 	ret = klp_init_patch_early(patch);
838 	if (ret) {
839 		mutex_unlock(&klp_mutex);
840 		return ret;
841 	}
842 
843 	ret = klp_init_patch(patch);
844 	if (ret)
845 		goto err;
846 
847 	ret = __klp_enable_patch(patch);
848 	if (ret)
849 		goto err;
850 
851 	mutex_unlock(&klp_mutex);
852 
853 	return 0;
854 
855 err:
856 	klp_free_patch_start(patch);
857 
858 	mutex_unlock(&klp_mutex);
859 
860 	klp_free_patch_finish(patch);
861 
862 	return ret;
863 }
864 EXPORT_SYMBOL_GPL(klp_enable_patch);
865 
866 /*
867  * Remove parts of patches that touch a given kernel module. The list of
868  * patches processed might be limited. When limit is NULL, all patches
869  * will be handled.
870  */
871 static void klp_cleanup_module_patches_limited(struct module *mod,
872 					       struct klp_patch *limit)
873 {
874 	struct klp_patch *patch;
875 	struct klp_object *obj;
876 
877 	list_for_each_entry(patch, &klp_patches, list) {
878 		if (patch == limit)
879 			break;
880 
881 		klp_for_each_object(patch, obj) {
882 			if (!klp_is_module(obj) || strcmp(obj->name, mod->name))
883 				continue;
884 
885 			/*
886 			 * Only unpatch the module if the patch is enabled or
887 			 * is in transition.
888 			 */
889 			if (patch->enabled || patch == klp_transition_patch) {
890 
891 				if (patch != klp_transition_patch)
892 					klp_pre_unpatch_callback(obj);
893 
894 				pr_notice("reverting patch '%s' on unloading module '%s'\n",
895 					  patch->mod->name, obj->mod->name);
896 				klp_unpatch_object(obj);
897 
898 				klp_post_unpatch_callback(obj);
899 			}
900 
901 			klp_free_object_loaded(obj);
902 			break;
903 		}
904 	}
905 }
906 
907 int klp_module_coming(struct module *mod)
908 {
909 	int ret;
910 	struct klp_patch *patch;
911 	struct klp_object *obj;
912 
913 	if (WARN_ON(mod->state != MODULE_STATE_COMING))
914 		return -EINVAL;
915 
916 	mutex_lock(&klp_mutex);
917 	/*
918 	 * Each module has to know that klp_module_coming()
919 	 * has been called. We never know what module will
920 	 * get patched by a new patch.
921 	 */
922 	mod->klp_alive = true;
923 
924 	list_for_each_entry(patch, &klp_patches, list) {
925 		klp_for_each_object(patch, obj) {
926 			if (!klp_is_module(obj) || strcmp(obj->name, mod->name))
927 				continue;
928 
929 			obj->mod = mod;
930 
931 			ret = klp_init_object_loaded(patch, obj);
932 			if (ret) {
933 				pr_warn("failed to initialize patch '%s' for module '%s' (%d)\n",
934 					patch->mod->name, obj->mod->name, ret);
935 				goto err;
936 			}
937 
938 			/*
939 			 * Only patch the module if the patch is enabled or is
940 			 * in transition.
941 			 */
942 			if (!patch->enabled && patch != klp_transition_patch)
943 				break;
944 
945 			pr_notice("applying patch '%s' to loading module '%s'\n",
946 				  patch->mod->name, obj->mod->name);
947 
948 			ret = klp_pre_patch_callback(obj);
949 			if (ret) {
950 				pr_warn("pre-patch callback failed for object '%s'\n",
951 					obj->name);
952 				goto err;
953 			}
954 
955 			ret = klp_patch_object(obj);
956 			if (ret) {
957 				pr_warn("failed to apply patch '%s' to module '%s' (%d)\n",
958 					patch->mod->name, obj->mod->name, ret);
959 
960 				klp_post_unpatch_callback(obj);
961 				goto err;
962 			}
963 
964 			if (patch != klp_transition_patch)
965 				klp_post_patch_callback(obj);
966 
967 			break;
968 		}
969 	}
970 
971 	mutex_unlock(&klp_mutex);
972 
973 	return 0;
974 
975 err:
976 	/*
977 	 * If a patch is unsuccessfully applied, return
978 	 * error to the module loader.
979 	 */
980 	pr_warn("patch '%s' failed for module '%s', refusing to load module '%s'\n",
981 		patch->mod->name, obj->mod->name, obj->mod->name);
982 	mod->klp_alive = false;
983 	klp_cleanup_module_patches_limited(mod, patch);
984 	mutex_unlock(&klp_mutex);
985 
986 	return ret;
987 }
988 
989 void klp_module_going(struct module *mod)
990 {
991 	if (WARN_ON(mod->state != MODULE_STATE_GOING &&
992 		    mod->state != MODULE_STATE_COMING))
993 		return;
994 
995 	mutex_lock(&klp_mutex);
996 	/*
997 	 * Each module has to know that klp_module_going()
998 	 * has been called. We never know what module will
999 	 * get patched by a new patch.
1000 	 */
1001 	mod->klp_alive = false;
1002 
1003 	klp_cleanup_module_patches_limited(mod, NULL);
1004 
1005 	mutex_unlock(&klp_mutex);
1006 }
1007 
1008 static int __init klp_init(void)
1009 {
1010 	int ret;
1011 
1012 	ret = klp_check_compiler_support();
1013 	if (ret) {
1014 		pr_info("Your compiler is too old; turning off.\n");
1015 		return -EINVAL;
1016 	}
1017 
1018 	klp_root_kobj = kobject_create_and_add("livepatch", kernel_kobj);
1019 	if (!klp_root_kobj)
1020 		return -ENOMEM;
1021 
1022 	return 0;
1023 }
1024 
1025 module_init(klp_init);
1026