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