Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-or-later
0002 /*
0003  * core.c - Kernel Live Patching Core
0004  *
0005  * Copyright (C) 2014 Seth Jennings <sjenning@redhat.com>
0006  * Copyright (C) 2014 SUSE
0007  */
0008 
0009 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
0010 
0011 #include <linux/module.h>
0012 #include <linux/kernel.h>
0013 #include <linux/mutex.h>
0014 #include <linux/slab.h>
0015 #include <linux/list.h>
0016 #include <linux/kallsyms.h>
0017 #include <linux/livepatch.h>
0018 #include <linux/elf.h>
0019 #include <linux/moduleloader.h>
0020 #include <linux/completion.h>
0021 #include <linux/memory.h>
0022 #include <linux/rcupdate.h>
0023 #include <asm/cacheflush.h>
0024 #include "core.h"
0025 #include "patch.h"
0026 #include "state.h"
0027 #include "transition.h"
0028 
0029 /*
0030  * klp_mutex is a coarse lock which serializes access to klp data.  All
0031  * accesses to klp-related variables and structures must have mutex protection,
0032  * except within the following functions which carefully avoid the need for it:
0033  *
0034  * - klp_ftrace_handler()
0035  * - klp_update_patch_state()
0036  */
0037 DEFINE_MUTEX(klp_mutex);
0038 
0039 /*
0040  * Actively used patches: enabled or in transition. Note that replaced
0041  * or disabled patches are not listed even though the related kernel
0042  * module still can be loaded.
0043  */
0044 LIST_HEAD(klp_patches);
0045 
0046 static struct kobject *klp_root_kobj;
0047 
0048 static bool klp_is_module(struct klp_object *obj)
0049 {
0050     return obj->name;
0051 }
0052 
0053 /* sets obj->mod if object is not vmlinux and module is found */
0054 static void klp_find_object_module(struct klp_object *obj)
0055 {
0056     struct module *mod;
0057 
0058     if (!klp_is_module(obj))
0059         return;
0060 
0061     rcu_read_lock_sched();
0062     /*
0063      * We do not want to block removal of patched modules and therefore
0064      * we do not take a reference here. The patches are removed by
0065      * klp_module_going() instead.
0066      */
0067     mod = find_module(obj->name);
0068     /*
0069      * Do not mess work of klp_module_coming() and klp_module_going().
0070      * Note that the patch might still be needed before klp_module_going()
0071      * is called. Module functions can be called even in the GOING state
0072      * until mod->exit() finishes. This is especially important for
0073      * patches that modify semantic of the functions.
0074      */
0075     if (mod && mod->klp_alive)
0076         obj->mod = mod;
0077 
0078     rcu_read_unlock_sched();
0079 }
0080 
0081 static bool klp_initialized(void)
0082 {
0083     return !!klp_root_kobj;
0084 }
0085 
0086 static struct klp_func *klp_find_func(struct klp_object *obj,
0087                       struct klp_func *old_func)
0088 {
0089     struct klp_func *func;
0090 
0091     klp_for_each_func(obj, func) {
0092         if ((strcmp(old_func->old_name, func->old_name) == 0) &&
0093             (old_func->old_sympos == func->old_sympos)) {
0094             return func;
0095         }
0096     }
0097 
0098     return NULL;
0099 }
0100 
0101 static struct klp_object *klp_find_object(struct klp_patch *patch,
0102                       struct klp_object *old_obj)
0103 {
0104     struct klp_object *obj;
0105 
0106     klp_for_each_object(patch, obj) {
0107         if (klp_is_module(old_obj)) {
0108             if (klp_is_module(obj) &&
0109                 strcmp(old_obj->name, obj->name) == 0) {
0110                 return obj;
0111             }
0112         } else if (!klp_is_module(obj)) {
0113             return obj;
0114         }
0115     }
0116 
0117     return NULL;
0118 }
0119 
0120 struct klp_find_arg {
0121     const char *objname;
0122     const char *name;
0123     unsigned long addr;
0124     unsigned long count;
0125     unsigned long pos;
0126 };
0127 
0128 static int klp_find_callback(void *data, const char *name,
0129                  struct module *mod, unsigned long addr)
0130 {
0131     struct klp_find_arg *args = data;
0132 
0133     if ((mod && !args->objname) || (!mod && args->objname))
0134         return 0;
0135 
0136     if (strcmp(args->name, name))
0137         return 0;
0138 
0139     if (args->objname && strcmp(args->objname, mod->name))
0140         return 0;
0141 
0142     args->addr = addr;
0143     args->count++;
0144 
0145     /*
0146      * Finish the search when the symbol is found for the desired position
0147      * or the position is not defined for a non-unique symbol.
0148      */
0149     if ((args->pos && (args->count == args->pos)) ||
0150         (!args->pos && (args->count > 1)))
0151         return 1;
0152 
0153     return 0;
0154 }
0155 
0156 static int klp_find_object_symbol(const char *objname, const char *name,
0157                   unsigned long sympos, unsigned long *addr)
0158 {
0159     struct klp_find_arg args = {
0160         .objname = objname,
0161         .name = name,
0162         .addr = 0,
0163         .count = 0,
0164         .pos = sympos,
0165     };
0166 
0167     if (objname)
0168         module_kallsyms_on_each_symbol(klp_find_callback, &args);
0169     else
0170         kallsyms_on_each_symbol(klp_find_callback, &args);
0171 
0172     /*
0173      * Ensure an address was found. If sympos is 0, ensure symbol is unique;
0174      * otherwise ensure the symbol position count matches sympos.
0175      */
0176     if (args.addr == 0)
0177         pr_err("symbol '%s' not found in symbol table\n", name);
0178     else if (args.count > 1 && sympos == 0) {
0179         pr_err("unresolvable ambiguity for symbol '%s' in object '%s'\n",
0180                name, objname);
0181     } else if (sympos != args.count && sympos > 0) {
0182         pr_err("symbol position %lu for symbol '%s' in object '%s' not found\n",
0183                sympos, name, objname ? objname : "vmlinux");
0184     } else {
0185         *addr = args.addr;
0186         return 0;
0187     }
0188 
0189     *addr = 0;
0190     return -EINVAL;
0191 }
0192 
0193 static int klp_resolve_symbols(Elf_Shdr *sechdrs, const char *strtab,
0194                    unsigned int symndx, Elf_Shdr *relasec,
0195                    const char *sec_objname)
0196 {
0197     int i, cnt, ret;
0198     char sym_objname[MODULE_NAME_LEN];
0199     char sym_name[KSYM_NAME_LEN];
0200     Elf_Rela *relas;
0201     Elf_Sym *sym;
0202     unsigned long sympos, addr;
0203     bool sym_vmlinux;
0204     bool sec_vmlinux = !strcmp(sec_objname, "vmlinux");
0205 
0206     /*
0207      * Since the field widths for sym_objname and sym_name in the sscanf()
0208      * call are hard-coded and correspond to MODULE_NAME_LEN and
0209      * KSYM_NAME_LEN respectively, we must make sure that MODULE_NAME_LEN
0210      * and KSYM_NAME_LEN have the values we expect them to have.
0211      *
0212      * Because the value of MODULE_NAME_LEN can differ among architectures,
0213      * we use the smallest/strictest upper bound possible (56, based on
0214      * the current definition of MODULE_NAME_LEN) to prevent overflows.
0215      */
0216     BUILD_BUG_ON(MODULE_NAME_LEN < 56 || KSYM_NAME_LEN != 128);
0217 
0218     relas = (Elf_Rela *) relasec->sh_addr;
0219     /* For each rela in this klp relocation section */
0220     for (i = 0; i < relasec->sh_size / sizeof(Elf_Rela); i++) {
0221         sym = (Elf_Sym *)sechdrs[symndx].sh_addr + ELF_R_SYM(relas[i].r_info);
0222         if (sym->st_shndx != SHN_LIVEPATCH) {
0223             pr_err("symbol %s is not marked as a livepatch symbol\n",
0224                    strtab + sym->st_name);
0225             return -EINVAL;
0226         }
0227 
0228         /* Format: .klp.sym.sym_objname.sym_name,sympos */
0229         cnt = sscanf(strtab + sym->st_name,
0230                  ".klp.sym.%55[^.].%127[^,],%lu",
0231                  sym_objname, sym_name, &sympos);
0232         if (cnt != 3) {
0233             pr_err("symbol %s has an incorrectly formatted name\n",
0234                    strtab + sym->st_name);
0235             return -EINVAL;
0236         }
0237 
0238         sym_vmlinux = !strcmp(sym_objname, "vmlinux");
0239 
0240         /*
0241          * Prevent module-specific KLP rela sections from referencing
0242          * vmlinux symbols.  This helps prevent ordering issues with
0243          * module special section initializations.  Presumably such
0244          * symbols are exported and normal relas can be used instead.
0245          */
0246         if (!sec_vmlinux && sym_vmlinux) {
0247             pr_err("invalid access to vmlinux symbol '%s' from module-specific livepatch relocation section",
0248                    sym_name);
0249             return -EINVAL;
0250         }
0251 
0252         /* klp_find_object_symbol() treats a NULL objname as vmlinux */
0253         ret = klp_find_object_symbol(sym_vmlinux ? NULL : sym_objname,
0254                          sym_name, sympos, &addr);
0255         if (ret)
0256             return ret;
0257 
0258         sym->st_value = addr;
0259     }
0260 
0261     return 0;
0262 }
0263 
0264 /*
0265  * At a high-level, there are two types of klp relocation sections: those which
0266  * reference symbols which live in vmlinux; and those which reference symbols
0267  * which live in other modules.  This function is called for both types:
0268  *
0269  * 1) When a klp module itself loads, the module code calls this function to
0270  *    write vmlinux-specific klp relocations (.klp.rela.vmlinux.* sections).
0271  *    These relocations are written to the klp module text to allow the patched
0272  *    code/data to reference unexported vmlinux symbols.  They're written as
0273  *    early as possible to ensure that other module init code (.e.g.,
0274  *    jump_label_apply_nops) can access any unexported vmlinux symbols which
0275  *    might be referenced by the klp module's special sections.
0276  *
0277  * 2) When a to-be-patched module loads -- or is already loaded when a
0278  *    corresponding klp module loads -- klp code calls this function to write
0279  *    module-specific klp relocations (.klp.rela.{module}.* sections).  These
0280  *    are written to the klp module text to allow the patched code/data to
0281  *    reference symbols which live in the to-be-patched module or one of its
0282  *    module dependencies.  Exported symbols are supported, in addition to
0283  *    unexported symbols, in order to enable late module patching, which allows
0284  *    the to-be-patched module to be loaded and patched sometime *after* the
0285  *    klp module is loaded.
0286  */
0287 int klp_apply_section_relocs(struct module *pmod, Elf_Shdr *sechdrs,
0288                  const char *shstrtab, const char *strtab,
0289                  unsigned int symndx, unsigned int secndx,
0290                  const char *objname)
0291 {
0292     int cnt, ret;
0293     char sec_objname[MODULE_NAME_LEN];
0294     Elf_Shdr *sec = sechdrs + secndx;
0295 
0296     /*
0297      * Format: .klp.rela.sec_objname.section_name
0298      * See comment in klp_resolve_symbols() for an explanation
0299      * of the selected field width value.
0300      */
0301     cnt = sscanf(shstrtab + sec->sh_name, ".klp.rela.%55[^.]",
0302              sec_objname);
0303     if (cnt != 1) {
0304         pr_err("section %s has an incorrectly formatted name\n",
0305                shstrtab + sec->sh_name);
0306         return -EINVAL;
0307     }
0308 
0309     if (strcmp(objname ? objname : "vmlinux", sec_objname))
0310         return 0;
0311 
0312     ret = klp_resolve_symbols(sechdrs, strtab, symndx, sec, sec_objname);
0313     if (ret)
0314         return ret;
0315 
0316     return apply_relocate_add(sechdrs, strtab, symndx, secndx, pmod);
0317 }
0318 
0319 /*
0320  * Sysfs Interface
0321  *
0322  * /sys/kernel/livepatch
0323  * /sys/kernel/livepatch/<patch>
0324  * /sys/kernel/livepatch/<patch>/enabled
0325  * /sys/kernel/livepatch/<patch>/transition
0326  * /sys/kernel/livepatch/<patch>/force
0327  * /sys/kernel/livepatch/<patch>/<object>
0328  * /sys/kernel/livepatch/<patch>/<object>/<function,sympos>
0329  */
0330 static int __klp_disable_patch(struct klp_patch *patch);
0331 
0332 static ssize_t enabled_store(struct kobject *kobj, struct kobj_attribute *attr,
0333                  const char *buf, size_t count)
0334 {
0335     struct klp_patch *patch;
0336     int ret;
0337     bool enabled;
0338 
0339     ret = kstrtobool(buf, &enabled);
0340     if (ret)
0341         return ret;
0342 
0343     patch = container_of(kobj, struct klp_patch, kobj);
0344 
0345     mutex_lock(&klp_mutex);
0346 
0347     if (patch->enabled == enabled) {
0348         /* already in requested state */
0349         ret = -EINVAL;
0350         goto out;
0351     }
0352 
0353     /*
0354      * Allow to reverse a pending transition in both ways. It might be
0355      * necessary to complete the transition without forcing and breaking
0356      * the system integrity.
0357      *
0358      * Do not allow to re-enable a disabled patch.
0359      */
0360     if (patch == klp_transition_patch)
0361         klp_reverse_transition();
0362     else if (!enabled)
0363         ret = __klp_disable_patch(patch);
0364     else
0365         ret = -EINVAL;
0366 
0367 out:
0368     mutex_unlock(&klp_mutex);
0369 
0370     if (ret)
0371         return ret;
0372     return count;
0373 }
0374 
0375 static ssize_t enabled_show(struct kobject *kobj,
0376                 struct kobj_attribute *attr, char *buf)
0377 {
0378     struct klp_patch *patch;
0379 
0380     patch = container_of(kobj, struct klp_patch, kobj);
0381     return snprintf(buf, PAGE_SIZE-1, "%d\n", patch->enabled);
0382 }
0383 
0384 static ssize_t transition_show(struct kobject *kobj,
0385                    struct kobj_attribute *attr, char *buf)
0386 {
0387     struct klp_patch *patch;
0388 
0389     patch = container_of(kobj, struct klp_patch, kobj);
0390     return snprintf(buf, PAGE_SIZE-1, "%d\n",
0391             patch == klp_transition_patch);
0392 }
0393 
0394 static ssize_t force_store(struct kobject *kobj, struct kobj_attribute *attr,
0395                const char *buf, size_t count)
0396 {
0397     struct klp_patch *patch;
0398     int ret;
0399     bool val;
0400 
0401     ret = kstrtobool(buf, &val);
0402     if (ret)
0403         return ret;
0404 
0405     if (!val)
0406         return count;
0407 
0408     mutex_lock(&klp_mutex);
0409 
0410     patch = container_of(kobj, struct klp_patch, kobj);
0411     if (patch != klp_transition_patch) {
0412         mutex_unlock(&klp_mutex);
0413         return -EINVAL;
0414     }
0415 
0416     klp_force_transition();
0417 
0418     mutex_unlock(&klp_mutex);
0419 
0420     return count;
0421 }
0422 
0423 static struct kobj_attribute enabled_kobj_attr = __ATTR_RW(enabled);
0424 static struct kobj_attribute transition_kobj_attr = __ATTR_RO(transition);
0425 static struct kobj_attribute force_kobj_attr = __ATTR_WO(force);
0426 static struct attribute *klp_patch_attrs[] = {
0427     &enabled_kobj_attr.attr,
0428     &transition_kobj_attr.attr,
0429     &force_kobj_attr.attr,
0430     NULL
0431 };
0432 ATTRIBUTE_GROUPS(klp_patch);
0433 
0434 static void klp_free_object_dynamic(struct klp_object *obj)
0435 {
0436     kfree(obj->name);
0437     kfree(obj);
0438 }
0439 
0440 static void klp_init_func_early(struct klp_object *obj,
0441                 struct klp_func *func);
0442 static void klp_init_object_early(struct klp_patch *patch,
0443                   struct klp_object *obj);
0444 
0445 static struct klp_object *klp_alloc_object_dynamic(const char *name,
0446                            struct klp_patch *patch)
0447 {
0448     struct klp_object *obj;
0449 
0450     obj = kzalloc(sizeof(*obj), GFP_KERNEL);
0451     if (!obj)
0452         return NULL;
0453 
0454     if (name) {
0455         obj->name = kstrdup(name, GFP_KERNEL);
0456         if (!obj->name) {
0457             kfree(obj);
0458             return NULL;
0459         }
0460     }
0461 
0462     klp_init_object_early(patch, obj);
0463     obj->dynamic = true;
0464 
0465     return obj;
0466 }
0467 
0468 static void klp_free_func_nop(struct klp_func *func)
0469 {
0470     kfree(func->old_name);
0471     kfree(func);
0472 }
0473 
0474 static struct klp_func *klp_alloc_func_nop(struct klp_func *old_func,
0475                        struct klp_object *obj)
0476 {
0477     struct klp_func *func;
0478 
0479     func = kzalloc(sizeof(*func), GFP_KERNEL);
0480     if (!func)
0481         return NULL;
0482 
0483     if (old_func->old_name) {
0484         func->old_name = kstrdup(old_func->old_name, GFP_KERNEL);
0485         if (!func->old_name) {
0486             kfree(func);
0487             return NULL;
0488         }
0489     }
0490 
0491     klp_init_func_early(obj, func);
0492     /*
0493      * func->new_func is same as func->old_func. These addresses are
0494      * set when the object is loaded, see klp_init_object_loaded().
0495      */
0496     func->old_sympos = old_func->old_sympos;
0497     func->nop = true;
0498 
0499     return func;
0500 }
0501 
0502 static int klp_add_object_nops(struct klp_patch *patch,
0503                    struct klp_object *old_obj)
0504 {
0505     struct klp_object *obj;
0506     struct klp_func *func, *old_func;
0507 
0508     obj = klp_find_object(patch, old_obj);
0509 
0510     if (!obj) {
0511         obj = klp_alloc_object_dynamic(old_obj->name, patch);
0512         if (!obj)
0513             return -ENOMEM;
0514     }
0515 
0516     klp_for_each_func(old_obj, old_func) {
0517         func = klp_find_func(obj, old_func);
0518         if (func)
0519             continue;
0520 
0521         func = klp_alloc_func_nop(old_func, obj);
0522         if (!func)
0523             return -ENOMEM;
0524     }
0525 
0526     return 0;
0527 }
0528 
0529 /*
0530  * Add 'nop' functions which simply return to the caller to run
0531  * the original function. The 'nop' functions are added to a
0532  * patch to facilitate a 'replace' mode.
0533  */
0534 static int klp_add_nops(struct klp_patch *patch)
0535 {
0536     struct klp_patch *old_patch;
0537     struct klp_object *old_obj;
0538 
0539     klp_for_each_patch(old_patch) {
0540         klp_for_each_object(old_patch, old_obj) {
0541             int err;
0542 
0543             err = klp_add_object_nops(patch, old_obj);
0544             if (err)
0545                 return err;
0546         }
0547     }
0548 
0549     return 0;
0550 }
0551 
0552 static void klp_kobj_release_patch(struct kobject *kobj)
0553 {
0554     struct klp_patch *patch;
0555 
0556     patch = container_of(kobj, struct klp_patch, kobj);
0557     complete(&patch->finish);
0558 }
0559 
0560 static struct kobj_type klp_ktype_patch = {
0561     .release = klp_kobj_release_patch,
0562     .sysfs_ops = &kobj_sysfs_ops,
0563     .default_groups = klp_patch_groups,
0564 };
0565 
0566 static void klp_kobj_release_object(struct kobject *kobj)
0567 {
0568     struct klp_object *obj;
0569 
0570     obj = container_of(kobj, struct klp_object, kobj);
0571 
0572     if (obj->dynamic)
0573         klp_free_object_dynamic(obj);
0574 }
0575 
0576 static struct kobj_type klp_ktype_object = {
0577     .release = klp_kobj_release_object,
0578     .sysfs_ops = &kobj_sysfs_ops,
0579 };
0580 
0581 static void klp_kobj_release_func(struct kobject *kobj)
0582 {
0583     struct klp_func *func;
0584 
0585     func = container_of(kobj, struct klp_func, kobj);
0586 
0587     if (func->nop)
0588         klp_free_func_nop(func);
0589 }
0590 
0591 static struct kobj_type klp_ktype_func = {
0592     .release = klp_kobj_release_func,
0593     .sysfs_ops = &kobj_sysfs_ops,
0594 };
0595 
0596 static void __klp_free_funcs(struct klp_object *obj, bool nops_only)
0597 {
0598     struct klp_func *func, *tmp_func;
0599 
0600     klp_for_each_func_safe(obj, func, tmp_func) {
0601         if (nops_only && !func->nop)
0602             continue;
0603 
0604         list_del(&func->node);
0605         kobject_put(&func->kobj);
0606     }
0607 }
0608 
0609 /* Clean up when a patched object is unloaded */
0610 static void klp_free_object_loaded(struct klp_object *obj)
0611 {
0612     struct klp_func *func;
0613 
0614     obj->mod = NULL;
0615 
0616     klp_for_each_func(obj, func) {
0617         func->old_func = NULL;
0618 
0619         if (func->nop)
0620             func->new_func = NULL;
0621     }
0622 }
0623 
0624 static void __klp_free_objects(struct klp_patch *patch, bool nops_only)
0625 {
0626     struct klp_object *obj, *tmp_obj;
0627 
0628     klp_for_each_object_safe(patch, obj, tmp_obj) {
0629         __klp_free_funcs(obj, nops_only);
0630 
0631         if (nops_only && !obj->dynamic)
0632             continue;
0633 
0634         list_del(&obj->node);
0635         kobject_put(&obj->kobj);
0636     }
0637 }
0638 
0639 static void klp_free_objects(struct klp_patch *patch)
0640 {
0641     __klp_free_objects(patch, false);
0642 }
0643 
0644 static void klp_free_objects_dynamic(struct klp_patch *patch)
0645 {
0646     __klp_free_objects(patch, true);
0647 }
0648 
0649 /*
0650  * This function implements the free operations that can be called safely
0651  * under klp_mutex.
0652  *
0653  * The operation must be completed by calling klp_free_patch_finish()
0654  * outside klp_mutex.
0655  */
0656 static void klp_free_patch_start(struct klp_patch *patch)
0657 {
0658     if (!list_empty(&patch->list))
0659         list_del(&patch->list);
0660 
0661     klp_free_objects(patch);
0662 }
0663 
0664 /*
0665  * This function implements the free part that must be called outside
0666  * klp_mutex.
0667  *
0668  * It must be called after klp_free_patch_start(). And it has to be
0669  * the last function accessing the livepatch structures when the patch
0670  * gets disabled.
0671  */
0672 static void klp_free_patch_finish(struct klp_patch *patch)
0673 {
0674     /*
0675      * Avoid deadlock with enabled_store() sysfs callback by
0676      * calling this outside klp_mutex. It is safe because
0677      * this is called when the patch gets disabled and it
0678      * cannot get enabled again.
0679      */
0680     kobject_put(&patch->kobj);
0681     wait_for_completion(&patch->finish);
0682 
0683     /* Put the module after the last access to struct klp_patch. */
0684     if (!patch->forced)
0685         module_put(patch->mod);
0686 }
0687 
0688 /*
0689  * The livepatch might be freed from sysfs interface created by the patch.
0690  * This work allows to wait until the interface is destroyed in a separate
0691  * context.
0692  */
0693 static void klp_free_patch_work_fn(struct work_struct *work)
0694 {
0695     struct klp_patch *patch =
0696         container_of(work, struct klp_patch, free_work);
0697 
0698     klp_free_patch_finish(patch);
0699 }
0700 
0701 void klp_free_patch_async(struct klp_patch *patch)
0702 {
0703     klp_free_patch_start(patch);
0704     schedule_work(&patch->free_work);
0705 }
0706 
0707 void klp_free_replaced_patches_async(struct klp_patch *new_patch)
0708 {
0709     struct klp_patch *old_patch, *tmp_patch;
0710 
0711     klp_for_each_patch_safe(old_patch, tmp_patch) {
0712         if (old_patch == new_patch)
0713             return;
0714         klp_free_patch_async(old_patch);
0715     }
0716 }
0717 
0718 static int klp_init_func(struct klp_object *obj, struct klp_func *func)
0719 {
0720     if (!func->old_name)
0721         return -EINVAL;
0722 
0723     /*
0724      * NOPs get the address later. The patched module must be loaded,
0725      * see klp_init_object_loaded().
0726      */
0727     if (!func->new_func && !func->nop)
0728         return -EINVAL;
0729 
0730     if (strlen(func->old_name) >= KSYM_NAME_LEN)
0731         return -EINVAL;
0732 
0733     INIT_LIST_HEAD(&func->stack_node);
0734     func->patched = false;
0735     func->transition = false;
0736 
0737     /* The format for the sysfs directory is <function,sympos> where sympos
0738      * is the nth occurrence of this symbol in kallsyms for the patched
0739      * object. If the user selects 0 for old_sympos, then 1 will be used
0740      * since a unique symbol will be the first occurrence.
0741      */
0742     return kobject_add(&func->kobj, &obj->kobj, "%s,%lu",
0743                func->old_name,
0744                func->old_sympos ? func->old_sympos : 1);
0745 }
0746 
0747 static int klp_apply_object_relocs(struct klp_patch *patch,
0748                    struct klp_object *obj)
0749 {
0750     int i, ret;
0751     struct klp_modinfo *info = patch->mod->klp_info;
0752 
0753     for (i = 1; i < info->hdr.e_shnum; i++) {
0754         Elf_Shdr *sec = info->sechdrs + i;
0755 
0756         if (!(sec->sh_flags & SHF_RELA_LIVEPATCH))
0757             continue;
0758 
0759         ret = klp_apply_section_relocs(patch->mod, info->sechdrs,
0760                            info->secstrings,
0761                            patch->mod->core_kallsyms.strtab,
0762                            info->symndx, i, obj->name);
0763         if (ret)
0764             return ret;
0765     }
0766 
0767     return 0;
0768 }
0769 
0770 /* parts of the initialization that is done only when the object is loaded */
0771 static int klp_init_object_loaded(struct klp_patch *patch,
0772                   struct klp_object *obj)
0773 {
0774     struct klp_func *func;
0775     int ret;
0776 
0777     if (klp_is_module(obj)) {
0778         /*
0779          * Only write module-specific relocations here
0780          * (.klp.rela.{module}.*).  vmlinux-specific relocations were
0781          * written earlier during the initialization of the klp module
0782          * itself.
0783          */
0784         ret = klp_apply_object_relocs(patch, obj);
0785         if (ret)
0786             return ret;
0787     }
0788 
0789     klp_for_each_func(obj, func) {
0790         ret = klp_find_object_symbol(obj->name, func->old_name,
0791                          func->old_sympos,
0792                          (unsigned long *)&func->old_func);
0793         if (ret)
0794             return ret;
0795 
0796         ret = kallsyms_lookup_size_offset((unsigned long)func->old_func,
0797                           &func->old_size, NULL);
0798         if (!ret) {
0799             pr_err("kallsyms size lookup failed for '%s'\n",
0800                    func->old_name);
0801             return -ENOENT;
0802         }
0803 
0804         if (func->nop)
0805             func->new_func = func->old_func;
0806 
0807         ret = kallsyms_lookup_size_offset((unsigned long)func->new_func,
0808                           &func->new_size, NULL);
0809         if (!ret) {
0810             pr_err("kallsyms size lookup failed for '%s' replacement\n",
0811                    func->old_name);
0812             return -ENOENT;
0813         }
0814     }
0815 
0816     return 0;
0817 }
0818 
0819 static int klp_init_object(struct klp_patch *patch, struct klp_object *obj)
0820 {
0821     struct klp_func *func;
0822     int ret;
0823     const char *name;
0824 
0825     if (klp_is_module(obj) && strlen(obj->name) >= MODULE_NAME_LEN)
0826         return -EINVAL;
0827 
0828     obj->patched = false;
0829     obj->mod = NULL;
0830 
0831     klp_find_object_module(obj);
0832 
0833     name = klp_is_module(obj) ? obj->name : "vmlinux";
0834     ret = kobject_add(&obj->kobj, &patch->kobj, "%s", name);
0835     if (ret)
0836         return ret;
0837 
0838     klp_for_each_func(obj, func) {
0839         ret = klp_init_func(obj, func);
0840         if (ret)
0841             return ret;
0842     }
0843 
0844     if (klp_is_object_loaded(obj))
0845         ret = klp_init_object_loaded(patch, obj);
0846 
0847     return ret;
0848 }
0849 
0850 static void klp_init_func_early(struct klp_object *obj,
0851                 struct klp_func *func)
0852 {
0853     kobject_init(&func->kobj, &klp_ktype_func);
0854     list_add_tail(&func->node, &obj->func_list);
0855 }
0856 
0857 static void klp_init_object_early(struct klp_patch *patch,
0858                   struct klp_object *obj)
0859 {
0860     INIT_LIST_HEAD(&obj->func_list);
0861     kobject_init(&obj->kobj, &klp_ktype_object);
0862     list_add_tail(&obj->node, &patch->obj_list);
0863 }
0864 
0865 static void klp_init_patch_early(struct klp_patch *patch)
0866 {
0867     struct klp_object *obj;
0868     struct klp_func *func;
0869 
0870     INIT_LIST_HEAD(&patch->list);
0871     INIT_LIST_HEAD(&patch->obj_list);
0872     kobject_init(&patch->kobj, &klp_ktype_patch);
0873     patch->enabled = false;
0874     patch->forced = false;
0875     INIT_WORK(&patch->free_work, klp_free_patch_work_fn);
0876     init_completion(&patch->finish);
0877 
0878     klp_for_each_object_static(patch, obj) {
0879         klp_init_object_early(patch, obj);
0880 
0881         klp_for_each_func_static(obj, func) {
0882             klp_init_func_early(obj, func);
0883         }
0884     }
0885 }
0886 
0887 static int klp_init_patch(struct klp_patch *patch)
0888 {
0889     struct klp_object *obj;
0890     int ret;
0891 
0892     ret = kobject_add(&patch->kobj, klp_root_kobj, "%s", patch->mod->name);
0893     if (ret)
0894         return ret;
0895 
0896     if (patch->replace) {
0897         ret = klp_add_nops(patch);
0898         if (ret)
0899             return ret;
0900     }
0901 
0902     klp_for_each_object(patch, obj) {
0903         ret = klp_init_object(patch, obj);
0904         if (ret)
0905             return ret;
0906     }
0907 
0908     list_add_tail(&patch->list, &klp_patches);
0909 
0910     return 0;
0911 }
0912 
0913 static int __klp_disable_patch(struct klp_patch *patch)
0914 {
0915     struct klp_object *obj;
0916 
0917     if (WARN_ON(!patch->enabled))
0918         return -EINVAL;
0919 
0920     if (klp_transition_patch)
0921         return -EBUSY;
0922 
0923     klp_init_transition(patch, KLP_UNPATCHED);
0924 
0925     klp_for_each_object(patch, obj)
0926         if (obj->patched)
0927             klp_pre_unpatch_callback(obj);
0928 
0929     /*
0930      * Enforce the order of the func->transition writes in
0931      * klp_init_transition() and the TIF_PATCH_PENDING writes in
0932      * klp_start_transition().  In the rare case where klp_ftrace_handler()
0933      * is called shortly after klp_update_patch_state() switches the task,
0934      * this ensures the handler sees that func->transition is set.
0935      */
0936     smp_wmb();
0937 
0938     klp_start_transition();
0939     patch->enabled = false;
0940     klp_try_complete_transition();
0941 
0942     return 0;
0943 }
0944 
0945 static int __klp_enable_patch(struct klp_patch *patch)
0946 {
0947     struct klp_object *obj;
0948     int ret;
0949 
0950     if (klp_transition_patch)
0951         return -EBUSY;
0952 
0953     if (WARN_ON(patch->enabled))
0954         return -EINVAL;
0955 
0956     pr_notice("enabling patch '%s'\n", patch->mod->name);
0957 
0958     klp_init_transition(patch, KLP_PATCHED);
0959 
0960     /*
0961      * Enforce the order of the func->transition writes in
0962      * klp_init_transition() and the ops->func_stack writes in
0963      * klp_patch_object(), so that klp_ftrace_handler() will see the
0964      * func->transition updates before the handler is registered and the
0965      * new funcs become visible to the handler.
0966      */
0967     smp_wmb();
0968 
0969     klp_for_each_object(patch, obj) {
0970         if (!klp_is_object_loaded(obj))
0971             continue;
0972 
0973         ret = klp_pre_patch_callback(obj);
0974         if (ret) {
0975             pr_warn("pre-patch callback failed for object '%s'\n",
0976                 klp_is_module(obj) ? obj->name : "vmlinux");
0977             goto err;
0978         }
0979 
0980         ret = klp_patch_object(obj);
0981         if (ret) {
0982             pr_warn("failed to patch object '%s'\n",
0983                 klp_is_module(obj) ? obj->name : "vmlinux");
0984             goto err;
0985         }
0986     }
0987 
0988     klp_start_transition();
0989     patch->enabled = true;
0990     klp_try_complete_transition();
0991 
0992     return 0;
0993 err:
0994     pr_warn("failed to enable patch '%s'\n", patch->mod->name);
0995 
0996     klp_cancel_transition();
0997     return ret;
0998 }
0999 
1000 /**
1001  * klp_enable_patch() - enable the livepatch
1002  * @patch:  patch to be enabled
1003  *
1004  * Initializes the data structure associated with the patch, creates the sysfs
1005  * interface, performs the needed symbol lookups and code relocations,
1006  * registers the patched functions with ftrace.
1007  *
1008  * This function is supposed to be called from the livepatch module_init()
1009  * callback.
1010  *
1011  * Return: 0 on success, otherwise error
1012  */
1013 int klp_enable_patch(struct klp_patch *patch)
1014 {
1015     int ret;
1016     struct klp_object *obj;
1017 
1018     if (!patch || !patch->mod || !patch->objs)
1019         return -EINVAL;
1020 
1021     klp_for_each_object_static(patch, obj) {
1022         if (!obj->funcs)
1023             return -EINVAL;
1024     }
1025 
1026 
1027     if (!is_livepatch_module(patch->mod)) {
1028         pr_err("module %s is not marked as a livepatch module\n",
1029                patch->mod->name);
1030         return -EINVAL;
1031     }
1032 
1033     if (!klp_initialized())
1034         return -ENODEV;
1035 
1036     if (!klp_have_reliable_stack()) {
1037         pr_warn("This architecture doesn't have support for the livepatch consistency model.\n");
1038         pr_warn("The livepatch transition may never complete.\n");
1039     }
1040 
1041     mutex_lock(&klp_mutex);
1042 
1043     if (!klp_is_patch_compatible(patch)) {
1044         pr_err("Livepatch patch (%s) is not compatible with the already installed livepatches.\n",
1045             patch->mod->name);
1046         mutex_unlock(&klp_mutex);
1047         return -EINVAL;
1048     }
1049 
1050     if (!try_module_get(patch->mod)) {
1051         mutex_unlock(&klp_mutex);
1052         return -ENODEV;
1053     }
1054 
1055     klp_init_patch_early(patch);
1056 
1057     ret = klp_init_patch(patch);
1058     if (ret)
1059         goto err;
1060 
1061     ret = __klp_enable_patch(patch);
1062     if (ret)
1063         goto err;
1064 
1065     mutex_unlock(&klp_mutex);
1066 
1067     return 0;
1068 
1069 err:
1070     klp_free_patch_start(patch);
1071 
1072     mutex_unlock(&klp_mutex);
1073 
1074     klp_free_patch_finish(patch);
1075 
1076     return ret;
1077 }
1078 EXPORT_SYMBOL_GPL(klp_enable_patch);
1079 
1080 /*
1081  * This function unpatches objects from the replaced livepatches.
1082  *
1083  * We could be pretty aggressive here. It is called in the situation where
1084  * these structures are no longer accessed from the ftrace handler.
1085  * All functions are redirected by the klp_transition_patch. They
1086  * use either a new code or they are in the original code because
1087  * of the special nop function patches.
1088  *
1089  * The only exception is when the transition was forced. In this case,
1090  * klp_ftrace_handler() might still see the replaced patch on the stack.
1091  * Fortunately, it is carefully designed to work with removed functions
1092  * thanks to RCU. We only have to keep the patches on the system. Also
1093  * this is handled transparently by patch->module_put.
1094  */
1095 void klp_unpatch_replaced_patches(struct klp_patch *new_patch)
1096 {
1097     struct klp_patch *old_patch;
1098 
1099     klp_for_each_patch(old_patch) {
1100         if (old_patch == new_patch)
1101             return;
1102 
1103         old_patch->enabled = false;
1104         klp_unpatch_objects(old_patch);
1105     }
1106 }
1107 
1108 /*
1109  * This function removes the dynamically allocated 'nop' functions.
1110  *
1111  * We could be pretty aggressive. NOPs do not change the existing
1112  * behavior except for adding unnecessary delay by the ftrace handler.
1113  *
1114  * It is safe even when the transition was forced. The ftrace handler
1115  * will see a valid ops->func_stack entry thanks to RCU.
1116  *
1117  * We could even free the NOPs structures. They must be the last entry
1118  * in ops->func_stack. Therefore unregister_ftrace_function() is called.
1119  * It does the same as klp_synchronize_transition() to make sure that
1120  * nobody is inside the ftrace handler once the operation finishes.
1121  *
1122  * IMPORTANT: It must be called right after removing the replaced patches!
1123  */
1124 void klp_discard_nops(struct klp_patch *new_patch)
1125 {
1126     klp_unpatch_objects_dynamic(klp_transition_patch);
1127     klp_free_objects_dynamic(klp_transition_patch);
1128 }
1129 
1130 /*
1131  * Remove parts of patches that touch a given kernel module. The list of
1132  * patches processed might be limited. When limit is NULL, all patches
1133  * will be handled.
1134  */
1135 static void klp_cleanup_module_patches_limited(struct module *mod,
1136                            struct klp_patch *limit)
1137 {
1138     struct klp_patch *patch;
1139     struct klp_object *obj;
1140 
1141     klp_for_each_patch(patch) {
1142         if (patch == limit)
1143             break;
1144 
1145         klp_for_each_object(patch, obj) {
1146             if (!klp_is_module(obj) || strcmp(obj->name, mod->name))
1147                 continue;
1148 
1149             if (patch != klp_transition_patch)
1150                 klp_pre_unpatch_callback(obj);
1151 
1152             pr_notice("reverting patch '%s' on unloading module '%s'\n",
1153                   patch->mod->name, obj->mod->name);
1154             klp_unpatch_object(obj);
1155 
1156             klp_post_unpatch_callback(obj);
1157 
1158             klp_free_object_loaded(obj);
1159             break;
1160         }
1161     }
1162 }
1163 
1164 int klp_module_coming(struct module *mod)
1165 {
1166     int ret;
1167     struct klp_patch *patch;
1168     struct klp_object *obj;
1169 
1170     if (WARN_ON(mod->state != MODULE_STATE_COMING))
1171         return -EINVAL;
1172 
1173     if (!strcmp(mod->name, "vmlinux")) {
1174         pr_err("vmlinux.ko: invalid module name");
1175         return -EINVAL;
1176     }
1177 
1178     mutex_lock(&klp_mutex);
1179     /*
1180      * Each module has to know that klp_module_coming()
1181      * has been called. We never know what module will
1182      * get patched by a new patch.
1183      */
1184     mod->klp_alive = true;
1185 
1186     klp_for_each_patch(patch) {
1187         klp_for_each_object(patch, obj) {
1188             if (!klp_is_module(obj) || strcmp(obj->name, mod->name))
1189                 continue;
1190 
1191             obj->mod = mod;
1192 
1193             ret = klp_init_object_loaded(patch, obj);
1194             if (ret) {
1195                 pr_warn("failed to initialize patch '%s' for module '%s' (%d)\n",
1196                     patch->mod->name, obj->mod->name, ret);
1197                 goto err;
1198             }
1199 
1200             pr_notice("applying patch '%s' to loading module '%s'\n",
1201                   patch->mod->name, obj->mod->name);
1202 
1203             ret = klp_pre_patch_callback(obj);
1204             if (ret) {
1205                 pr_warn("pre-patch callback failed for object '%s'\n",
1206                     obj->name);
1207                 goto err;
1208             }
1209 
1210             ret = klp_patch_object(obj);
1211             if (ret) {
1212                 pr_warn("failed to apply patch '%s' to module '%s' (%d)\n",
1213                     patch->mod->name, obj->mod->name, ret);
1214 
1215                 klp_post_unpatch_callback(obj);
1216                 goto err;
1217             }
1218 
1219             if (patch != klp_transition_patch)
1220                 klp_post_patch_callback(obj);
1221 
1222             break;
1223         }
1224     }
1225 
1226     mutex_unlock(&klp_mutex);
1227 
1228     return 0;
1229 
1230 err:
1231     /*
1232      * If a patch is unsuccessfully applied, return
1233      * error to the module loader.
1234      */
1235     pr_warn("patch '%s' failed for module '%s', refusing to load module '%s'\n",
1236         patch->mod->name, obj->mod->name, obj->mod->name);
1237     mod->klp_alive = false;
1238     obj->mod = NULL;
1239     klp_cleanup_module_patches_limited(mod, patch);
1240     mutex_unlock(&klp_mutex);
1241 
1242     return ret;
1243 }
1244 
1245 void klp_module_going(struct module *mod)
1246 {
1247     if (WARN_ON(mod->state != MODULE_STATE_GOING &&
1248             mod->state != MODULE_STATE_COMING))
1249         return;
1250 
1251     mutex_lock(&klp_mutex);
1252     /*
1253      * Each module has to know that klp_module_going()
1254      * has been called. We never know what module will
1255      * get patched by a new patch.
1256      */
1257     mod->klp_alive = false;
1258 
1259     klp_cleanup_module_patches_limited(mod, NULL);
1260 
1261     mutex_unlock(&klp_mutex);
1262 }
1263 
1264 static int __init klp_init(void)
1265 {
1266     klp_root_kobj = kobject_create_and_add("livepatch", kernel_kobj);
1267     if (!klp_root_kobj)
1268         return -ENOMEM;
1269 
1270     return 0;
1271 }
1272 
1273 module_init(klp_init);