Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /* Copyright (c) 2019 Facebook */
0003 #include <linux/hash.h>
0004 #include <linux/bpf.h>
0005 #include <linux/filter.h>
0006 #include <linux/ftrace.h>
0007 #include <linux/rbtree_latch.h>
0008 #include <linux/perf_event.h>
0009 #include <linux/btf.h>
0010 #include <linux/rcupdate_trace.h>
0011 #include <linux/rcupdate_wait.h>
0012 #include <linux/module.h>
0013 #include <linux/static_call.h>
0014 #include <linux/bpf_verifier.h>
0015 #include <linux/bpf_lsm.h>
0016 #include <linux/delay.h>
0017 
0018 /* dummy _ops. The verifier will operate on target program's ops. */
0019 const struct bpf_verifier_ops bpf_extension_verifier_ops = {
0020 };
0021 const struct bpf_prog_ops bpf_extension_prog_ops = {
0022 };
0023 
0024 /* btf_vmlinux has ~22k attachable functions. 1k htab is enough. */
0025 #define TRAMPOLINE_HASH_BITS 10
0026 #define TRAMPOLINE_TABLE_SIZE (1 << TRAMPOLINE_HASH_BITS)
0027 
0028 static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE];
0029 
0030 /* serializes access to trampoline_table */
0031 static DEFINE_MUTEX(trampoline_mutex);
0032 
0033 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
0034 static int bpf_trampoline_update(struct bpf_trampoline *tr, bool lock_direct_mutex);
0035 
0036 static int bpf_tramp_ftrace_ops_func(struct ftrace_ops *ops, enum ftrace_ops_cmd cmd)
0037 {
0038     struct bpf_trampoline *tr = ops->private;
0039     int ret = 0;
0040 
0041     if (cmd == FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF) {
0042         /* This is called inside register_ftrace_direct_multi(), so
0043          * tr->mutex is already locked.
0044          */
0045         lockdep_assert_held_once(&tr->mutex);
0046 
0047         /* Instead of updating the trampoline here, we propagate
0048          * -EAGAIN to register_ftrace_direct_multi(). Then we can
0049          * retry register_ftrace_direct_multi() after updating the
0050          * trampoline.
0051          */
0052         if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
0053             !(tr->flags & BPF_TRAMP_F_ORIG_STACK)) {
0054             if (WARN_ON_ONCE(tr->flags & BPF_TRAMP_F_SHARE_IPMODIFY))
0055                 return -EBUSY;
0056 
0057             tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
0058             return -EAGAIN;
0059         }
0060 
0061         return 0;
0062     }
0063 
0064     /* The normal locking order is
0065      *    tr->mutex => direct_mutex (ftrace.c) => ftrace_lock (ftrace.c)
0066      *
0067      * The following two commands are called from
0068      *
0069      *   prepare_direct_functions_for_ipmodify
0070      *   cleanup_direct_functions_after_ipmodify
0071      *
0072      * In both cases, direct_mutex is already locked. Use
0073      * mutex_trylock(&tr->mutex) to avoid deadlock in race condition
0074      * (something else is making changes to this same trampoline).
0075      */
0076     if (!mutex_trylock(&tr->mutex)) {
0077         /* sleep 1 ms to make sure whatever holding tr->mutex makes
0078          * some progress.
0079          */
0080         msleep(1);
0081         return -EAGAIN;
0082     }
0083 
0084     switch (cmd) {
0085     case FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER:
0086         tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
0087 
0088         if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
0089             !(tr->flags & BPF_TRAMP_F_ORIG_STACK))
0090             ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */);
0091         break;
0092     case FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER:
0093         tr->flags &= ~BPF_TRAMP_F_SHARE_IPMODIFY;
0094 
0095         if (tr->flags & BPF_TRAMP_F_ORIG_STACK)
0096             ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */);
0097         break;
0098     default:
0099         ret = -EINVAL;
0100         break;
0101     }
0102 
0103     mutex_unlock(&tr->mutex);
0104     return ret;
0105 }
0106 #endif
0107 
0108 bool bpf_prog_has_trampoline(const struct bpf_prog *prog)
0109 {
0110     enum bpf_attach_type eatype = prog->expected_attach_type;
0111     enum bpf_prog_type ptype = prog->type;
0112 
0113     return (ptype == BPF_PROG_TYPE_TRACING &&
0114         (eatype == BPF_TRACE_FENTRY || eatype == BPF_TRACE_FEXIT ||
0115          eatype == BPF_MODIFY_RETURN)) ||
0116         (ptype == BPF_PROG_TYPE_LSM && eatype == BPF_LSM_MAC);
0117 }
0118 
0119 void *bpf_jit_alloc_exec_page(void)
0120 {
0121     void *image;
0122 
0123     image = bpf_jit_alloc_exec(PAGE_SIZE);
0124     if (!image)
0125         return NULL;
0126 
0127     set_vm_flush_reset_perms(image);
0128     /* Keep image as writeable. The alternative is to keep flipping ro/rw
0129      * every time new program is attached or detached.
0130      */
0131     set_memory_x((long)image, 1);
0132     return image;
0133 }
0134 
0135 void bpf_image_ksym_add(void *data, struct bpf_ksym *ksym)
0136 {
0137     ksym->start = (unsigned long) data;
0138     ksym->end = ksym->start + PAGE_SIZE;
0139     bpf_ksym_add(ksym);
0140     perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, ksym->start,
0141                PAGE_SIZE, false, ksym->name);
0142 }
0143 
0144 void bpf_image_ksym_del(struct bpf_ksym *ksym)
0145 {
0146     bpf_ksym_del(ksym);
0147     perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, ksym->start,
0148                PAGE_SIZE, true, ksym->name);
0149 }
0150 
0151 static struct bpf_trampoline *bpf_trampoline_lookup(u64 key)
0152 {
0153     struct bpf_trampoline *tr;
0154     struct hlist_head *head;
0155     int i;
0156 
0157     mutex_lock(&trampoline_mutex);
0158     head = &trampoline_table[hash_64(key, TRAMPOLINE_HASH_BITS)];
0159     hlist_for_each_entry(tr, head, hlist) {
0160         if (tr->key == key) {
0161             refcount_inc(&tr->refcnt);
0162             goto out;
0163         }
0164     }
0165     tr = kzalloc(sizeof(*tr), GFP_KERNEL);
0166     if (!tr)
0167         goto out;
0168 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
0169     tr->fops = kzalloc(sizeof(struct ftrace_ops), GFP_KERNEL);
0170     if (!tr->fops) {
0171         kfree(tr);
0172         tr = NULL;
0173         goto out;
0174     }
0175     tr->fops->private = tr;
0176     tr->fops->ops_func = bpf_tramp_ftrace_ops_func;
0177 #endif
0178 
0179     tr->key = key;
0180     INIT_HLIST_NODE(&tr->hlist);
0181     hlist_add_head(&tr->hlist, head);
0182     refcount_set(&tr->refcnt, 1);
0183     mutex_init(&tr->mutex);
0184     for (i = 0; i < BPF_TRAMP_MAX; i++)
0185         INIT_HLIST_HEAD(&tr->progs_hlist[i]);
0186 out:
0187     mutex_unlock(&trampoline_mutex);
0188     return tr;
0189 }
0190 
0191 static int bpf_trampoline_module_get(struct bpf_trampoline *tr)
0192 {
0193     struct module *mod;
0194     int err = 0;
0195 
0196     preempt_disable();
0197     mod = __module_text_address((unsigned long) tr->func.addr);
0198     if (mod && !try_module_get(mod))
0199         err = -ENOENT;
0200     preempt_enable();
0201     tr->mod = mod;
0202     return err;
0203 }
0204 
0205 static void bpf_trampoline_module_put(struct bpf_trampoline *tr)
0206 {
0207     module_put(tr->mod);
0208     tr->mod = NULL;
0209 }
0210 
0211 static int unregister_fentry(struct bpf_trampoline *tr, void *old_addr)
0212 {
0213     void *ip = tr->func.addr;
0214     int ret;
0215 
0216     if (tr->func.ftrace_managed)
0217         ret = unregister_ftrace_direct_multi(tr->fops, (long)old_addr);
0218     else
0219         ret = bpf_arch_text_poke(ip, BPF_MOD_CALL, old_addr, NULL);
0220 
0221     if (!ret)
0222         bpf_trampoline_module_put(tr);
0223     return ret;
0224 }
0225 
0226 static int modify_fentry(struct bpf_trampoline *tr, void *old_addr, void *new_addr,
0227              bool lock_direct_mutex)
0228 {
0229     void *ip = tr->func.addr;
0230     int ret;
0231 
0232     if (tr->func.ftrace_managed) {
0233         if (lock_direct_mutex)
0234             ret = modify_ftrace_direct_multi(tr->fops, (long)new_addr);
0235         else
0236             ret = modify_ftrace_direct_multi_nolock(tr->fops, (long)new_addr);
0237     } else {
0238         ret = bpf_arch_text_poke(ip, BPF_MOD_CALL, old_addr, new_addr);
0239     }
0240     return ret;
0241 }
0242 
0243 /* first time registering */
0244 static int register_fentry(struct bpf_trampoline *tr, void *new_addr)
0245 {
0246     void *ip = tr->func.addr;
0247     unsigned long faddr;
0248     int ret;
0249 
0250     faddr = ftrace_location((unsigned long)ip);
0251     if (faddr) {
0252         if (!tr->fops)
0253             return -ENOTSUPP;
0254         tr->func.ftrace_managed = true;
0255     }
0256 
0257     if (bpf_trampoline_module_get(tr))
0258         return -ENOENT;
0259 
0260     if (tr->func.ftrace_managed) {
0261         ftrace_set_filter_ip(tr->fops, (unsigned long)ip, 0, 1);
0262         ret = register_ftrace_direct_multi(tr->fops, (long)new_addr);
0263     } else {
0264         ret = bpf_arch_text_poke(ip, BPF_MOD_CALL, NULL, new_addr);
0265     }
0266 
0267     if (ret)
0268         bpf_trampoline_module_put(tr);
0269     return ret;
0270 }
0271 
0272 static struct bpf_tramp_links *
0273 bpf_trampoline_get_progs(const struct bpf_trampoline *tr, int *total, bool *ip_arg)
0274 {
0275     struct bpf_tramp_link *link;
0276     struct bpf_tramp_links *tlinks;
0277     struct bpf_tramp_link **links;
0278     int kind;
0279 
0280     *total = 0;
0281     tlinks = kcalloc(BPF_TRAMP_MAX, sizeof(*tlinks), GFP_KERNEL);
0282     if (!tlinks)
0283         return ERR_PTR(-ENOMEM);
0284 
0285     for (kind = 0; kind < BPF_TRAMP_MAX; kind++) {
0286         tlinks[kind].nr_links = tr->progs_cnt[kind];
0287         *total += tr->progs_cnt[kind];
0288         links = tlinks[kind].links;
0289 
0290         hlist_for_each_entry(link, &tr->progs_hlist[kind], tramp_hlist) {
0291             *ip_arg |= link->link.prog->call_get_func_ip;
0292             *links++ = link;
0293         }
0294     }
0295     return tlinks;
0296 }
0297 
0298 static void __bpf_tramp_image_put_deferred(struct work_struct *work)
0299 {
0300     struct bpf_tramp_image *im;
0301 
0302     im = container_of(work, struct bpf_tramp_image, work);
0303     bpf_image_ksym_del(&im->ksym);
0304     bpf_jit_free_exec(im->image);
0305     bpf_jit_uncharge_modmem(PAGE_SIZE);
0306     percpu_ref_exit(&im->pcref);
0307     kfree_rcu(im, rcu);
0308 }
0309 
0310 /* callback, fexit step 3 or fentry step 2 */
0311 static void __bpf_tramp_image_put_rcu(struct rcu_head *rcu)
0312 {
0313     struct bpf_tramp_image *im;
0314 
0315     im = container_of(rcu, struct bpf_tramp_image, rcu);
0316     INIT_WORK(&im->work, __bpf_tramp_image_put_deferred);
0317     schedule_work(&im->work);
0318 }
0319 
0320 /* callback, fexit step 2. Called after percpu_ref_kill confirms. */
0321 static void __bpf_tramp_image_release(struct percpu_ref *pcref)
0322 {
0323     struct bpf_tramp_image *im;
0324 
0325     im = container_of(pcref, struct bpf_tramp_image, pcref);
0326     call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu);
0327 }
0328 
0329 /* callback, fexit or fentry step 1 */
0330 static void __bpf_tramp_image_put_rcu_tasks(struct rcu_head *rcu)
0331 {
0332     struct bpf_tramp_image *im;
0333 
0334     im = container_of(rcu, struct bpf_tramp_image, rcu);
0335     if (im->ip_after_call)
0336         /* the case of fmod_ret/fexit trampoline and CONFIG_PREEMPTION=y */
0337         percpu_ref_kill(&im->pcref);
0338     else
0339         /* the case of fentry trampoline */
0340         call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu);
0341 }
0342 
0343 static void bpf_tramp_image_put(struct bpf_tramp_image *im)
0344 {
0345     /* The trampoline image that calls original function is using:
0346      * rcu_read_lock_trace to protect sleepable bpf progs
0347      * rcu_read_lock to protect normal bpf progs
0348      * percpu_ref to protect trampoline itself
0349      * rcu tasks to protect trampoline asm not covered by percpu_ref
0350      * (which are few asm insns before __bpf_tramp_enter and
0351      *  after __bpf_tramp_exit)
0352      *
0353      * The trampoline is unreachable before bpf_tramp_image_put().
0354      *
0355      * First, patch the trampoline to avoid calling into fexit progs.
0356      * The progs will be freed even if the original function is still
0357      * executing or sleeping.
0358      * In case of CONFIG_PREEMPT=y use call_rcu_tasks() to wait on
0359      * first few asm instructions to execute and call into
0360      * __bpf_tramp_enter->percpu_ref_get.
0361      * Then use percpu_ref_kill to wait for the trampoline and the original
0362      * function to finish.
0363      * Then use call_rcu_tasks() to make sure few asm insns in
0364      * the trampoline epilogue are done as well.
0365      *
0366      * In !PREEMPT case the task that got interrupted in the first asm
0367      * insns won't go through an RCU quiescent state which the
0368      * percpu_ref_kill will be waiting for. Hence the first
0369      * call_rcu_tasks() is not necessary.
0370      */
0371     if (im->ip_after_call) {
0372         int err = bpf_arch_text_poke(im->ip_after_call, BPF_MOD_JUMP,
0373                          NULL, im->ip_epilogue);
0374         WARN_ON(err);
0375         if (IS_ENABLED(CONFIG_PREEMPTION))
0376             call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu_tasks);
0377         else
0378             percpu_ref_kill(&im->pcref);
0379         return;
0380     }
0381 
0382     /* The trampoline without fexit and fmod_ret progs doesn't call original
0383      * function and doesn't use percpu_ref.
0384      * Use call_rcu_tasks_trace() to wait for sleepable progs to finish.
0385      * Then use call_rcu_tasks() to wait for the rest of trampoline asm
0386      * and normal progs.
0387      */
0388     call_rcu_tasks_trace(&im->rcu, __bpf_tramp_image_put_rcu_tasks);
0389 }
0390 
0391 static struct bpf_tramp_image *bpf_tramp_image_alloc(u64 key, u32 idx)
0392 {
0393     struct bpf_tramp_image *im;
0394     struct bpf_ksym *ksym;
0395     void *image;
0396     int err = -ENOMEM;
0397 
0398     im = kzalloc(sizeof(*im), GFP_KERNEL);
0399     if (!im)
0400         goto out;
0401 
0402     err = bpf_jit_charge_modmem(PAGE_SIZE);
0403     if (err)
0404         goto out_free_im;
0405 
0406     err = -ENOMEM;
0407     im->image = image = bpf_jit_alloc_exec_page();
0408     if (!image)
0409         goto out_uncharge;
0410 
0411     err = percpu_ref_init(&im->pcref, __bpf_tramp_image_release, 0, GFP_KERNEL);
0412     if (err)
0413         goto out_free_image;
0414 
0415     ksym = &im->ksym;
0416     INIT_LIST_HEAD_RCU(&ksym->lnode);
0417     snprintf(ksym->name, KSYM_NAME_LEN, "bpf_trampoline_%llu_%u", key, idx);
0418     bpf_image_ksym_add(image, ksym);
0419     return im;
0420 
0421 out_free_image:
0422     bpf_jit_free_exec(im->image);
0423 out_uncharge:
0424     bpf_jit_uncharge_modmem(PAGE_SIZE);
0425 out_free_im:
0426     kfree(im);
0427 out:
0428     return ERR_PTR(err);
0429 }
0430 
0431 static int bpf_trampoline_update(struct bpf_trampoline *tr, bool lock_direct_mutex)
0432 {
0433     struct bpf_tramp_image *im;
0434     struct bpf_tramp_links *tlinks;
0435     u32 orig_flags = tr->flags;
0436     bool ip_arg = false;
0437     int err, total;
0438 
0439     tlinks = bpf_trampoline_get_progs(tr, &total, &ip_arg);
0440     if (IS_ERR(tlinks))
0441         return PTR_ERR(tlinks);
0442 
0443     if (total == 0) {
0444         err = unregister_fentry(tr, tr->cur_image->image);
0445         bpf_tramp_image_put(tr->cur_image);
0446         tr->cur_image = NULL;
0447         tr->selector = 0;
0448         goto out;
0449     }
0450 
0451     im = bpf_tramp_image_alloc(tr->key, tr->selector);
0452     if (IS_ERR(im)) {
0453         err = PTR_ERR(im);
0454         goto out;
0455     }
0456 
0457     /* clear all bits except SHARE_IPMODIFY */
0458     tr->flags &= BPF_TRAMP_F_SHARE_IPMODIFY;
0459 
0460     if (tlinks[BPF_TRAMP_FEXIT].nr_links ||
0461         tlinks[BPF_TRAMP_MODIFY_RETURN].nr_links) {
0462         /* NOTE: BPF_TRAMP_F_RESTORE_REGS and BPF_TRAMP_F_SKIP_FRAME
0463          * should not be set together.
0464          */
0465         tr->flags |= BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_SKIP_FRAME;
0466     } else {
0467         tr->flags |= BPF_TRAMP_F_RESTORE_REGS;
0468     }
0469 
0470     if (ip_arg)
0471         tr->flags |= BPF_TRAMP_F_IP_ARG;
0472 
0473 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
0474 again:
0475     if ((tr->flags & BPF_TRAMP_F_SHARE_IPMODIFY) &&
0476         (tr->flags & BPF_TRAMP_F_CALL_ORIG))
0477         tr->flags |= BPF_TRAMP_F_ORIG_STACK;
0478 #endif
0479 
0480     err = arch_prepare_bpf_trampoline(im, im->image, im->image + PAGE_SIZE,
0481                       &tr->func.model, tr->flags, tlinks,
0482                       tr->func.addr);
0483     if (err < 0)
0484         goto out;
0485 
0486     WARN_ON(tr->cur_image && tr->selector == 0);
0487     WARN_ON(!tr->cur_image && tr->selector);
0488     if (tr->cur_image)
0489         /* progs already running at this address */
0490         err = modify_fentry(tr, tr->cur_image->image, im->image, lock_direct_mutex);
0491     else
0492         /* first time registering */
0493         err = register_fentry(tr, im->image);
0494 
0495 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
0496     if (err == -EAGAIN) {
0497         /* -EAGAIN from bpf_tramp_ftrace_ops_func. Now
0498          * BPF_TRAMP_F_SHARE_IPMODIFY is set, we can generate the
0499          * trampoline again, and retry register.
0500          */
0501         /* reset fops->func and fops->trampoline for re-register */
0502         tr->fops->func = NULL;
0503         tr->fops->trampoline = 0;
0504         goto again;
0505     }
0506 #endif
0507     if (err)
0508         goto out;
0509 
0510     if (tr->cur_image)
0511         bpf_tramp_image_put(tr->cur_image);
0512     tr->cur_image = im;
0513     tr->selector++;
0514 out:
0515     /* If any error happens, restore previous flags */
0516     if (err)
0517         tr->flags = orig_flags;
0518     kfree(tlinks);
0519     return err;
0520 }
0521 
0522 static enum bpf_tramp_prog_type bpf_attach_type_to_tramp(struct bpf_prog *prog)
0523 {
0524     switch (prog->expected_attach_type) {
0525     case BPF_TRACE_FENTRY:
0526         return BPF_TRAMP_FENTRY;
0527     case BPF_MODIFY_RETURN:
0528         return BPF_TRAMP_MODIFY_RETURN;
0529     case BPF_TRACE_FEXIT:
0530         return BPF_TRAMP_FEXIT;
0531     case BPF_LSM_MAC:
0532         if (!prog->aux->attach_func_proto->type)
0533             /* The function returns void, we cannot modify its
0534              * return value.
0535              */
0536             return BPF_TRAMP_FEXIT;
0537         else
0538             return BPF_TRAMP_MODIFY_RETURN;
0539     default:
0540         return BPF_TRAMP_REPLACE;
0541     }
0542 }
0543 
0544 static int __bpf_trampoline_link_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
0545 {
0546     enum bpf_tramp_prog_type kind;
0547     struct bpf_tramp_link *link_exiting;
0548     int err = 0;
0549     int cnt = 0, i;
0550 
0551     kind = bpf_attach_type_to_tramp(link->link.prog);
0552     if (tr->extension_prog)
0553         /* cannot attach fentry/fexit if extension prog is attached.
0554          * cannot overwrite extension prog either.
0555          */
0556         return -EBUSY;
0557 
0558     for (i = 0; i < BPF_TRAMP_MAX; i++)
0559         cnt += tr->progs_cnt[i];
0560 
0561     if (kind == BPF_TRAMP_REPLACE) {
0562         /* Cannot attach extension if fentry/fexit are in use. */
0563         if (cnt)
0564             return -EBUSY;
0565         tr->extension_prog = link->link.prog;
0566         return bpf_arch_text_poke(tr->func.addr, BPF_MOD_JUMP, NULL,
0567                       link->link.prog->bpf_func);
0568     }
0569     if (cnt >= BPF_MAX_TRAMP_LINKS)
0570         return -E2BIG;
0571     if (!hlist_unhashed(&link->tramp_hlist))
0572         /* prog already linked */
0573         return -EBUSY;
0574     hlist_for_each_entry(link_exiting, &tr->progs_hlist[kind], tramp_hlist) {
0575         if (link_exiting->link.prog != link->link.prog)
0576             continue;
0577         /* prog already linked */
0578         return -EBUSY;
0579     }
0580 
0581     hlist_add_head(&link->tramp_hlist, &tr->progs_hlist[kind]);
0582     tr->progs_cnt[kind]++;
0583     err = bpf_trampoline_update(tr, true /* lock_direct_mutex */);
0584     if (err) {
0585         hlist_del_init(&link->tramp_hlist);
0586         tr->progs_cnt[kind]--;
0587     }
0588     return err;
0589 }
0590 
0591 int bpf_trampoline_link_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
0592 {
0593     int err;
0594 
0595     mutex_lock(&tr->mutex);
0596     err = __bpf_trampoline_link_prog(link, tr);
0597     mutex_unlock(&tr->mutex);
0598     return err;
0599 }
0600 
0601 static int __bpf_trampoline_unlink_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
0602 {
0603     enum bpf_tramp_prog_type kind;
0604     int err;
0605 
0606     kind = bpf_attach_type_to_tramp(link->link.prog);
0607     if (kind == BPF_TRAMP_REPLACE) {
0608         WARN_ON_ONCE(!tr->extension_prog);
0609         err = bpf_arch_text_poke(tr->func.addr, BPF_MOD_JUMP,
0610                      tr->extension_prog->bpf_func, NULL);
0611         tr->extension_prog = NULL;
0612         return err;
0613     }
0614     hlist_del_init(&link->tramp_hlist);
0615     tr->progs_cnt[kind]--;
0616     return bpf_trampoline_update(tr, true /* lock_direct_mutex */);
0617 }
0618 
0619 /* bpf_trampoline_unlink_prog() should never fail. */
0620 int bpf_trampoline_unlink_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
0621 {
0622     int err;
0623 
0624     mutex_lock(&tr->mutex);
0625     err = __bpf_trampoline_unlink_prog(link, tr);
0626     mutex_unlock(&tr->mutex);
0627     return err;
0628 }
0629 
0630 #if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_BPF_LSM)
0631 static void bpf_shim_tramp_link_release(struct bpf_link *link)
0632 {
0633     struct bpf_shim_tramp_link *shim_link =
0634         container_of(link, struct bpf_shim_tramp_link, link.link);
0635 
0636     /* paired with 'shim_link->trampoline = tr' in bpf_trampoline_link_cgroup_shim */
0637     if (!shim_link->trampoline)
0638         return;
0639 
0640     WARN_ON_ONCE(bpf_trampoline_unlink_prog(&shim_link->link, shim_link->trampoline));
0641     bpf_trampoline_put(shim_link->trampoline);
0642 }
0643 
0644 static void bpf_shim_tramp_link_dealloc(struct bpf_link *link)
0645 {
0646     struct bpf_shim_tramp_link *shim_link =
0647         container_of(link, struct bpf_shim_tramp_link, link.link);
0648 
0649     kfree(shim_link);
0650 }
0651 
0652 static const struct bpf_link_ops bpf_shim_tramp_link_lops = {
0653     .release = bpf_shim_tramp_link_release,
0654     .dealloc = bpf_shim_tramp_link_dealloc,
0655 };
0656 
0657 static struct bpf_shim_tramp_link *cgroup_shim_alloc(const struct bpf_prog *prog,
0658                              bpf_func_t bpf_func,
0659                              int cgroup_atype)
0660 {
0661     struct bpf_shim_tramp_link *shim_link = NULL;
0662     struct bpf_prog *p;
0663 
0664     shim_link = kzalloc(sizeof(*shim_link), GFP_USER);
0665     if (!shim_link)
0666         return NULL;
0667 
0668     p = bpf_prog_alloc(1, 0);
0669     if (!p) {
0670         kfree(shim_link);
0671         return NULL;
0672     }
0673 
0674     p->jited = false;
0675     p->bpf_func = bpf_func;
0676 
0677     p->aux->cgroup_atype = cgroup_atype;
0678     p->aux->attach_func_proto = prog->aux->attach_func_proto;
0679     p->aux->attach_btf_id = prog->aux->attach_btf_id;
0680     p->aux->attach_btf = prog->aux->attach_btf;
0681     btf_get(p->aux->attach_btf);
0682     p->type = BPF_PROG_TYPE_LSM;
0683     p->expected_attach_type = BPF_LSM_MAC;
0684     bpf_prog_inc(p);
0685     bpf_link_init(&shim_link->link.link, BPF_LINK_TYPE_UNSPEC,
0686               &bpf_shim_tramp_link_lops, p);
0687     bpf_cgroup_atype_get(p->aux->attach_btf_id, cgroup_atype);
0688 
0689     return shim_link;
0690 }
0691 
0692 static struct bpf_shim_tramp_link *cgroup_shim_find(struct bpf_trampoline *tr,
0693                             bpf_func_t bpf_func)
0694 {
0695     struct bpf_tramp_link *link;
0696     int kind;
0697 
0698     for (kind = 0; kind < BPF_TRAMP_MAX; kind++) {
0699         hlist_for_each_entry(link, &tr->progs_hlist[kind], tramp_hlist) {
0700             struct bpf_prog *p = link->link.prog;
0701 
0702             if (p->bpf_func == bpf_func)
0703                 return container_of(link, struct bpf_shim_tramp_link, link);
0704         }
0705     }
0706 
0707     return NULL;
0708 }
0709 
0710 int bpf_trampoline_link_cgroup_shim(struct bpf_prog *prog,
0711                     int cgroup_atype)
0712 {
0713     struct bpf_shim_tramp_link *shim_link = NULL;
0714     struct bpf_attach_target_info tgt_info = {};
0715     struct bpf_trampoline *tr;
0716     bpf_func_t bpf_func;
0717     u64 key;
0718     int err;
0719 
0720     err = bpf_check_attach_target(NULL, prog, NULL,
0721                       prog->aux->attach_btf_id,
0722                       &tgt_info);
0723     if (err)
0724         return err;
0725 
0726     key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf,
0727                      prog->aux->attach_btf_id);
0728 
0729     bpf_lsm_find_cgroup_shim(prog, &bpf_func);
0730     tr = bpf_trampoline_get(key, &tgt_info);
0731     if (!tr)
0732         return  -ENOMEM;
0733 
0734     mutex_lock(&tr->mutex);
0735 
0736     shim_link = cgroup_shim_find(tr, bpf_func);
0737     if (shim_link) {
0738         /* Reusing existing shim attached by the other program. */
0739         bpf_link_inc(&shim_link->link.link);
0740 
0741         mutex_unlock(&tr->mutex);
0742         bpf_trampoline_put(tr); /* bpf_trampoline_get above */
0743         return 0;
0744     }
0745 
0746     /* Allocate and install new shim. */
0747 
0748     shim_link = cgroup_shim_alloc(prog, bpf_func, cgroup_atype);
0749     if (!shim_link) {
0750         err = -ENOMEM;
0751         goto err;
0752     }
0753 
0754     err = __bpf_trampoline_link_prog(&shim_link->link, tr);
0755     if (err)
0756         goto err;
0757 
0758     shim_link->trampoline = tr;
0759     /* note, we're still holding tr refcnt from above */
0760 
0761     mutex_unlock(&tr->mutex);
0762 
0763     return 0;
0764 err:
0765     mutex_unlock(&tr->mutex);
0766 
0767     if (shim_link)
0768         bpf_link_put(&shim_link->link.link);
0769 
0770     /* have to release tr while _not_ holding its mutex */
0771     bpf_trampoline_put(tr); /* bpf_trampoline_get above */
0772 
0773     return err;
0774 }
0775 
0776 void bpf_trampoline_unlink_cgroup_shim(struct bpf_prog *prog)
0777 {
0778     struct bpf_shim_tramp_link *shim_link = NULL;
0779     struct bpf_trampoline *tr;
0780     bpf_func_t bpf_func;
0781     u64 key;
0782 
0783     key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf,
0784                      prog->aux->attach_btf_id);
0785 
0786     bpf_lsm_find_cgroup_shim(prog, &bpf_func);
0787     tr = bpf_trampoline_lookup(key);
0788     if (WARN_ON_ONCE(!tr))
0789         return;
0790 
0791     mutex_lock(&tr->mutex);
0792     shim_link = cgroup_shim_find(tr, bpf_func);
0793     mutex_unlock(&tr->mutex);
0794 
0795     if (shim_link)
0796         bpf_link_put(&shim_link->link.link);
0797 
0798     bpf_trampoline_put(tr); /* bpf_trampoline_lookup above */
0799 }
0800 #endif
0801 
0802 struct bpf_trampoline *bpf_trampoline_get(u64 key,
0803                       struct bpf_attach_target_info *tgt_info)
0804 {
0805     struct bpf_trampoline *tr;
0806 
0807     tr = bpf_trampoline_lookup(key);
0808     if (!tr)
0809         return NULL;
0810 
0811     mutex_lock(&tr->mutex);
0812     if (tr->func.addr)
0813         goto out;
0814 
0815     memcpy(&tr->func.model, &tgt_info->fmodel, sizeof(tgt_info->fmodel));
0816     tr->func.addr = (void *)tgt_info->tgt_addr;
0817 out:
0818     mutex_unlock(&tr->mutex);
0819     return tr;
0820 }
0821 
0822 void bpf_trampoline_put(struct bpf_trampoline *tr)
0823 {
0824     int i;
0825 
0826     if (!tr)
0827         return;
0828     mutex_lock(&trampoline_mutex);
0829     if (!refcount_dec_and_test(&tr->refcnt))
0830         goto out;
0831     WARN_ON_ONCE(mutex_is_locked(&tr->mutex));
0832 
0833     for (i = 0; i < BPF_TRAMP_MAX; i++)
0834         if (WARN_ON_ONCE(!hlist_empty(&tr->progs_hlist[i])))
0835             goto out;
0836 
0837     /* This code will be executed even when the last bpf_tramp_image
0838      * is alive. All progs are detached from the trampoline and the
0839      * trampoline image is patched with jmp into epilogue to skip
0840      * fexit progs. The fentry-only trampoline will be freed via
0841      * multiple rcu callbacks.
0842      */
0843     hlist_del(&tr->hlist);
0844     if (tr->fops) {
0845         ftrace_free_filter(tr->fops);
0846         kfree(tr->fops);
0847     }
0848     kfree(tr);
0849 out:
0850     mutex_unlock(&trampoline_mutex);
0851 }
0852 
0853 #define NO_START_TIME 1
0854 static __always_inline u64 notrace bpf_prog_start_time(void)
0855 {
0856     u64 start = NO_START_TIME;
0857 
0858     if (static_branch_unlikely(&bpf_stats_enabled_key)) {
0859         start = sched_clock();
0860         if (unlikely(!start))
0861             start = NO_START_TIME;
0862     }
0863     return start;
0864 }
0865 
0866 static void notrace inc_misses_counter(struct bpf_prog *prog)
0867 {
0868     struct bpf_prog_stats *stats;
0869     unsigned int flags;
0870 
0871     stats = this_cpu_ptr(prog->stats);
0872     flags = u64_stats_update_begin_irqsave(&stats->syncp);
0873     u64_stats_inc(&stats->misses);
0874     u64_stats_update_end_irqrestore(&stats->syncp, flags);
0875 }
0876 
0877 /* The logic is similar to bpf_prog_run(), but with an explicit
0878  * rcu_read_lock() and migrate_disable() which are required
0879  * for the trampoline. The macro is split into
0880  * call __bpf_prog_enter
0881  * call prog->bpf_func
0882  * call __bpf_prog_exit
0883  *
0884  * __bpf_prog_enter returns:
0885  * 0 - skip execution of the bpf prog
0886  * 1 - execute bpf prog
0887  * [2..MAX_U64] - execute bpf prog and record execution time.
0888  *     This is start time.
0889  */
0890 u64 notrace __bpf_prog_enter(struct bpf_prog *prog, struct bpf_tramp_run_ctx *run_ctx)
0891     __acquires(RCU)
0892 {
0893     rcu_read_lock();
0894     migrate_disable();
0895 
0896     run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
0897 
0898     if (unlikely(__this_cpu_inc_return(*(prog->active)) != 1)) {
0899         inc_misses_counter(prog);
0900         return 0;
0901     }
0902     return bpf_prog_start_time();
0903 }
0904 
0905 static void notrace update_prog_stats(struct bpf_prog *prog,
0906                       u64 start)
0907 {
0908     struct bpf_prog_stats *stats;
0909 
0910     if (static_branch_unlikely(&bpf_stats_enabled_key) &&
0911         /* static_key could be enabled in __bpf_prog_enter*
0912          * and disabled in __bpf_prog_exit*.
0913          * And vice versa.
0914          * Hence check that 'start' is valid.
0915          */
0916         start > NO_START_TIME) {
0917         unsigned long flags;
0918 
0919         stats = this_cpu_ptr(prog->stats);
0920         flags = u64_stats_update_begin_irqsave(&stats->syncp);
0921         u64_stats_inc(&stats->cnt);
0922         u64_stats_add(&stats->nsecs, sched_clock() - start);
0923         u64_stats_update_end_irqrestore(&stats->syncp, flags);
0924     }
0925 }
0926 
0927 void notrace __bpf_prog_exit(struct bpf_prog *prog, u64 start, struct bpf_tramp_run_ctx *run_ctx)
0928     __releases(RCU)
0929 {
0930     bpf_reset_run_ctx(run_ctx->saved_run_ctx);
0931 
0932     update_prog_stats(prog, start);
0933     __this_cpu_dec(*(prog->active));
0934     migrate_enable();
0935     rcu_read_unlock();
0936 }
0937 
0938 u64 notrace __bpf_prog_enter_lsm_cgroup(struct bpf_prog *prog,
0939                     struct bpf_tramp_run_ctx *run_ctx)
0940     __acquires(RCU)
0941 {
0942     /* Runtime stats are exported via actual BPF_LSM_CGROUP
0943      * programs, not the shims.
0944      */
0945     rcu_read_lock();
0946     migrate_disable();
0947 
0948     run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
0949 
0950     return NO_START_TIME;
0951 }
0952 
0953 void notrace __bpf_prog_exit_lsm_cgroup(struct bpf_prog *prog, u64 start,
0954                     struct bpf_tramp_run_ctx *run_ctx)
0955     __releases(RCU)
0956 {
0957     bpf_reset_run_ctx(run_ctx->saved_run_ctx);
0958 
0959     migrate_enable();
0960     rcu_read_unlock();
0961 }
0962 
0963 u64 notrace __bpf_prog_enter_sleepable(struct bpf_prog *prog, struct bpf_tramp_run_ctx *run_ctx)
0964 {
0965     rcu_read_lock_trace();
0966     migrate_disable();
0967     might_fault();
0968 
0969     if (unlikely(__this_cpu_inc_return(*(prog->active)) != 1)) {
0970         inc_misses_counter(prog);
0971         return 0;
0972     }
0973 
0974     run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
0975 
0976     return bpf_prog_start_time();
0977 }
0978 
0979 void notrace __bpf_prog_exit_sleepable(struct bpf_prog *prog, u64 start,
0980                        struct bpf_tramp_run_ctx *run_ctx)
0981 {
0982     bpf_reset_run_ctx(run_ctx->saved_run_ctx);
0983 
0984     update_prog_stats(prog, start);
0985     __this_cpu_dec(*(prog->active));
0986     migrate_enable();
0987     rcu_read_unlock_trace();
0988 }
0989 
0990 void notrace __bpf_tramp_enter(struct bpf_tramp_image *tr)
0991 {
0992     percpu_ref_get(&tr->pcref);
0993 }
0994 
0995 void notrace __bpf_tramp_exit(struct bpf_tramp_image *tr)
0996 {
0997     percpu_ref_put(&tr->pcref);
0998 }
0999 
1000 int __weak
1001 arch_prepare_bpf_trampoline(struct bpf_tramp_image *tr, void *image, void *image_end,
1002                 const struct btf_func_model *m, u32 flags,
1003                 struct bpf_tramp_links *tlinks,
1004                 void *orig_call)
1005 {
1006     return -ENOTSUPP;
1007 }
1008 
1009 static int __init init_trampolines(void)
1010 {
1011     int i;
1012 
1013     for (i = 0; i < TRAMPOLINE_TABLE_SIZE; i++)
1014         INIT_HLIST_HEAD(&trampoline_table[i]);
1015     return 0;
1016 }
1017 late_initcall(init_trampolines);