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