bpf: Fix memleak due to fentry attach failure
[platform/kernel/linux-starfive.git] / kernel / bpf / trampoline.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2019 Facebook */
3 #include <linux/hash.h>
4 #include <linux/bpf.h>
5 #include <linux/filter.h>
6 #include <linux/ftrace.h>
7 #include <linux/rbtree_latch.h>
8 #include <linux/perf_event.h>
9 #include <linux/btf.h>
10 #include <linux/rcupdate_trace.h>
11 #include <linux/rcupdate_wait.h>
12 #include <linux/module.h>
13 #include <linux/static_call.h>
14 #include <linux/bpf_verifier.h>
15 #include <linux/bpf_lsm.h>
16 #include <linux/delay.h>
17
18 /* dummy _ops. The verifier will operate on target program's ops. */
19 const struct bpf_verifier_ops bpf_extension_verifier_ops = {
20 };
21 const struct bpf_prog_ops bpf_extension_prog_ops = {
22 };
23
24 /* btf_vmlinux has ~22k attachable functions. 1k htab is enough. */
25 #define TRAMPOLINE_HASH_BITS 10
26 #define TRAMPOLINE_TABLE_SIZE (1 << TRAMPOLINE_HASH_BITS)
27
28 static struct hlist_head trampoline_table[TRAMPOLINE_TABLE_SIZE];
29
30 /* serializes access to trampoline_table */
31 static DEFINE_MUTEX(trampoline_mutex);
32
33 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
34 static int bpf_trampoline_update(struct bpf_trampoline *tr, bool lock_direct_mutex);
35
36 static int bpf_tramp_ftrace_ops_func(struct ftrace_ops *ops, enum ftrace_ops_cmd cmd)
37 {
38         struct bpf_trampoline *tr = ops->private;
39         int ret = 0;
40
41         if (cmd == FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_SELF) {
42                 /* This is called inside register_ftrace_direct_multi(), so
43                  * tr->mutex is already locked.
44                  */
45                 lockdep_assert_held_once(&tr->mutex);
46
47                 /* Instead of updating the trampoline here, we propagate
48                  * -EAGAIN to register_ftrace_direct_multi(). Then we can
49                  * retry register_ftrace_direct_multi() after updating the
50                  * trampoline.
51                  */
52                 if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
53                     !(tr->flags & BPF_TRAMP_F_ORIG_STACK)) {
54                         if (WARN_ON_ONCE(tr->flags & BPF_TRAMP_F_SHARE_IPMODIFY))
55                                 return -EBUSY;
56
57                         tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
58                         return -EAGAIN;
59                 }
60
61                 return 0;
62         }
63
64         /* The normal locking order is
65          *    tr->mutex => direct_mutex (ftrace.c) => ftrace_lock (ftrace.c)
66          *
67          * The following two commands are called from
68          *
69          *   prepare_direct_functions_for_ipmodify
70          *   cleanup_direct_functions_after_ipmodify
71          *
72          * In both cases, direct_mutex is already locked. Use
73          * mutex_trylock(&tr->mutex) to avoid deadlock in race condition
74          * (something else is making changes to this same trampoline).
75          */
76         if (!mutex_trylock(&tr->mutex)) {
77                 /* sleep 1 ms to make sure whatever holding tr->mutex makes
78                  * some progress.
79                  */
80                 msleep(1);
81                 return -EAGAIN;
82         }
83
84         switch (cmd) {
85         case FTRACE_OPS_CMD_ENABLE_SHARE_IPMODIFY_PEER:
86                 tr->flags |= BPF_TRAMP_F_SHARE_IPMODIFY;
87
88                 if ((tr->flags & BPF_TRAMP_F_CALL_ORIG) &&
89                     !(tr->flags & BPF_TRAMP_F_ORIG_STACK))
90                         ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */);
91                 break;
92         case FTRACE_OPS_CMD_DISABLE_SHARE_IPMODIFY_PEER:
93                 tr->flags &= ~BPF_TRAMP_F_SHARE_IPMODIFY;
94
95                 if (tr->flags & BPF_TRAMP_F_ORIG_STACK)
96                         ret = bpf_trampoline_update(tr, false /* lock_direct_mutex */);
97                 break;
98         default:
99                 ret = -EINVAL;
100                 break;
101         }
102
103         mutex_unlock(&tr->mutex);
104         return ret;
105 }
106 #endif
107
108 bool bpf_prog_has_trampoline(const struct bpf_prog *prog)
109 {
110         enum bpf_attach_type eatype = prog->expected_attach_type;
111         enum bpf_prog_type ptype = prog->type;
112
113         return (ptype == BPF_PROG_TYPE_TRACING &&
114                 (eatype == BPF_TRACE_FENTRY || eatype == BPF_TRACE_FEXIT ||
115                  eatype == BPF_MODIFY_RETURN)) ||
116                 (ptype == BPF_PROG_TYPE_LSM && eatype == BPF_LSM_MAC);
117 }
118
119 void bpf_image_ksym_add(void *data, struct bpf_ksym *ksym)
120 {
121         ksym->start = (unsigned long) data;
122         ksym->end = ksym->start + PAGE_SIZE;
123         bpf_ksym_add(ksym);
124         perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, ksym->start,
125                            PAGE_SIZE, false, ksym->name);
126 }
127
128 void bpf_image_ksym_del(struct bpf_ksym *ksym)
129 {
130         bpf_ksym_del(ksym);
131         perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, ksym->start,
132                            PAGE_SIZE, true, ksym->name);
133 }
134
135 static struct bpf_trampoline *bpf_trampoline_lookup(u64 key)
136 {
137         struct bpf_trampoline *tr;
138         struct hlist_head *head;
139         int i;
140
141         mutex_lock(&trampoline_mutex);
142         head = &trampoline_table[hash_64(key, TRAMPOLINE_HASH_BITS)];
143         hlist_for_each_entry(tr, head, hlist) {
144                 if (tr->key == key) {
145                         refcount_inc(&tr->refcnt);
146                         goto out;
147                 }
148         }
149         tr = kzalloc(sizeof(*tr), GFP_KERNEL);
150         if (!tr)
151                 goto out;
152 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
153         tr->fops = kzalloc(sizeof(struct ftrace_ops), GFP_KERNEL);
154         if (!tr->fops) {
155                 kfree(tr);
156                 tr = NULL;
157                 goto out;
158         }
159         tr->fops->private = tr;
160         tr->fops->ops_func = bpf_tramp_ftrace_ops_func;
161 #endif
162
163         tr->key = key;
164         INIT_HLIST_NODE(&tr->hlist);
165         hlist_add_head(&tr->hlist, head);
166         refcount_set(&tr->refcnt, 1);
167         mutex_init(&tr->mutex);
168         for (i = 0; i < BPF_TRAMP_MAX; i++)
169                 INIT_HLIST_HEAD(&tr->progs_hlist[i]);
170 out:
171         mutex_unlock(&trampoline_mutex);
172         return tr;
173 }
174
175 static int bpf_trampoline_module_get(struct bpf_trampoline *tr)
176 {
177         struct module *mod;
178         int err = 0;
179
180         preempt_disable();
181         mod = __module_text_address((unsigned long) tr->func.addr);
182         if (mod && !try_module_get(mod))
183                 err = -ENOENT;
184         preempt_enable();
185         tr->mod = mod;
186         return err;
187 }
188
189 static void bpf_trampoline_module_put(struct bpf_trampoline *tr)
190 {
191         module_put(tr->mod);
192         tr->mod = NULL;
193 }
194
195 static int unregister_fentry(struct bpf_trampoline *tr, void *old_addr)
196 {
197         void *ip = tr->func.addr;
198         int ret;
199
200         if (tr->func.ftrace_managed)
201                 ret = unregister_ftrace_direct_multi(tr->fops, (long)old_addr);
202         else
203                 ret = bpf_arch_text_poke(ip, BPF_MOD_CALL, old_addr, NULL);
204
205         if (!ret)
206                 bpf_trampoline_module_put(tr);
207         return ret;
208 }
209
210 static int modify_fentry(struct bpf_trampoline *tr, void *old_addr, void *new_addr,
211                          bool lock_direct_mutex)
212 {
213         void *ip = tr->func.addr;
214         int ret;
215
216         if (tr->func.ftrace_managed) {
217                 if (lock_direct_mutex)
218                         ret = modify_ftrace_direct_multi(tr->fops, (long)new_addr);
219                 else
220                         ret = modify_ftrace_direct_multi_nolock(tr->fops, (long)new_addr);
221         } else {
222                 ret = bpf_arch_text_poke(ip, BPF_MOD_CALL, old_addr, new_addr);
223         }
224         return ret;
225 }
226
227 /* first time registering */
228 static int register_fentry(struct bpf_trampoline *tr, void *new_addr)
229 {
230         void *ip = tr->func.addr;
231         unsigned long faddr;
232         int ret;
233
234         faddr = ftrace_location((unsigned long)ip);
235         if (faddr) {
236                 if (!tr->fops)
237                         return -ENOTSUPP;
238                 tr->func.ftrace_managed = true;
239         }
240
241         if (bpf_trampoline_module_get(tr))
242                 return -ENOENT;
243
244         if (tr->func.ftrace_managed) {
245                 ftrace_set_filter_ip(tr->fops, (unsigned long)ip, 0, 1);
246                 ret = register_ftrace_direct_multi(tr->fops, (long)new_addr);
247         } else {
248                 ret = bpf_arch_text_poke(ip, BPF_MOD_CALL, NULL, new_addr);
249         }
250
251         if (ret)
252                 bpf_trampoline_module_put(tr);
253         return ret;
254 }
255
256 static struct bpf_tramp_links *
257 bpf_trampoline_get_progs(const struct bpf_trampoline *tr, int *total, bool *ip_arg)
258 {
259         struct bpf_tramp_link *link;
260         struct bpf_tramp_links *tlinks;
261         struct bpf_tramp_link **links;
262         int kind;
263
264         *total = 0;
265         tlinks = kcalloc(BPF_TRAMP_MAX, sizeof(*tlinks), GFP_KERNEL);
266         if (!tlinks)
267                 return ERR_PTR(-ENOMEM);
268
269         for (kind = 0; kind < BPF_TRAMP_MAX; kind++) {
270                 tlinks[kind].nr_links = tr->progs_cnt[kind];
271                 *total += tr->progs_cnt[kind];
272                 links = tlinks[kind].links;
273
274                 hlist_for_each_entry(link, &tr->progs_hlist[kind], tramp_hlist) {
275                         *ip_arg |= link->link.prog->call_get_func_ip;
276                         *links++ = link;
277                 }
278         }
279         return tlinks;
280 }
281
282 static void bpf_tramp_image_free(struct bpf_tramp_image *im)
283 {
284         bpf_image_ksym_del(&im->ksym);
285         bpf_jit_free_exec(im->image);
286         bpf_jit_uncharge_modmem(PAGE_SIZE);
287         percpu_ref_exit(&im->pcref);
288         kfree_rcu(im, rcu);
289 }
290
291 static void __bpf_tramp_image_put_deferred(struct work_struct *work)
292 {
293         struct bpf_tramp_image *im;
294
295         im = container_of(work, struct bpf_tramp_image, work);
296         bpf_tramp_image_free(im);
297 }
298
299 /* callback, fexit step 3 or fentry step 2 */
300 static void __bpf_tramp_image_put_rcu(struct rcu_head *rcu)
301 {
302         struct bpf_tramp_image *im;
303
304         im = container_of(rcu, struct bpf_tramp_image, rcu);
305         INIT_WORK(&im->work, __bpf_tramp_image_put_deferred);
306         schedule_work(&im->work);
307 }
308
309 /* callback, fexit step 2. Called after percpu_ref_kill confirms. */
310 static void __bpf_tramp_image_release(struct percpu_ref *pcref)
311 {
312         struct bpf_tramp_image *im;
313
314         im = container_of(pcref, struct bpf_tramp_image, pcref);
315         call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu);
316 }
317
318 /* callback, fexit or fentry step 1 */
319 static void __bpf_tramp_image_put_rcu_tasks(struct rcu_head *rcu)
320 {
321         struct bpf_tramp_image *im;
322
323         im = container_of(rcu, struct bpf_tramp_image, rcu);
324         if (im->ip_after_call)
325                 /* the case of fmod_ret/fexit trampoline and CONFIG_PREEMPTION=y */
326                 percpu_ref_kill(&im->pcref);
327         else
328                 /* the case of fentry trampoline */
329                 call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu);
330 }
331
332 static void bpf_tramp_image_put(struct bpf_tramp_image *im)
333 {
334         /* The trampoline image that calls original function is using:
335          * rcu_read_lock_trace to protect sleepable bpf progs
336          * rcu_read_lock to protect normal bpf progs
337          * percpu_ref to protect trampoline itself
338          * rcu tasks to protect trampoline asm not covered by percpu_ref
339          * (which are few asm insns before __bpf_tramp_enter and
340          *  after __bpf_tramp_exit)
341          *
342          * The trampoline is unreachable before bpf_tramp_image_put().
343          *
344          * First, patch the trampoline to avoid calling into fexit progs.
345          * The progs will be freed even if the original function is still
346          * executing or sleeping.
347          * In case of CONFIG_PREEMPT=y use call_rcu_tasks() to wait on
348          * first few asm instructions to execute and call into
349          * __bpf_tramp_enter->percpu_ref_get.
350          * Then use percpu_ref_kill to wait for the trampoline and the original
351          * function to finish.
352          * Then use call_rcu_tasks() to make sure few asm insns in
353          * the trampoline epilogue are done as well.
354          *
355          * In !PREEMPT case the task that got interrupted in the first asm
356          * insns won't go through an RCU quiescent state which the
357          * percpu_ref_kill will be waiting for. Hence the first
358          * call_rcu_tasks() is not necessary.
359          */
360         if (im->ip_after_call) {
361                 int err = bpf_arch_text_poke(im->ip_after_call, BPF_MOD_JUMP,
362                                              NULL, im->ip_epilogue);
363                 WARN_ON(err);
364                 if (IS_ENABLED(CONFIG_PREEMPTION))
365                         call_rcu_tasks(&im->rcu, __bpf_tramp_image_put_rcu_tasks);
366                 else
367                         percpu_ref_kill(&im->pcref);
368                 return;
369         }
370
371         /* The trampoline without fexit and fmod_ret progs doesn't call original
372          * function and doesn't use percpu_ref.
373          * Use call_rcu_tasks_trace() to wait for sleepable progs to finish.
374          * Then use call_rcu_tasks() to wait for the rest of trampoline asm
375          * and normal progs.
376          */
377         call_rcu_tasks_trace(&im->rcu, __bpf_tramp_image_put_rcu_tasks);
378 }
379
380 static struct bpf_tramp_image *bpf_tramp_image_alloc(u64 key)
381 {
382         struct bpf_tramp_image *im;
383         struct bpf_ksym *ksym;
384         void *image;
385         int err = -ENOMEM;
386
387         im = kzalloc(sizeof(*im), GFP_KERNEL);
388         if (!im)
389                 goto out;
390
391         err = bpf_jit_charge_modmem(PAGE_SIZE);
392         if (err)
393                 goto out_free_im;
394
395         err = -ENOMEM;
396         im->image = image = bpf_jit_alloc_exec(PAGE_SIZE);
397         if (!image)
398                 goto out_uncharge;
399         set_vm_flush_reset_perms(image);
400
401         err = percpu_ref_init(&im->pcref, __bpf_tramp_image_release, 0, GFP_KERNEL);
402         if (err)
403                 goto out_free_image;
404
405         ksym = &im->ksym;
406         INIT_LIST_HEAD_RCU(&ksym->lnode);
407         snprintf(ksym->name, KSYM_NAME_LEN, "bpf_trampoline_%llu", key);
408         bpf_image_ksym_add(image, ksym);
409         return im;
410
411 out_free_image:
412         bpf_jit_free_exec(im->image);
413 out_uncharge:
414         bpf_jit_uncharge_modmem(PAGE_SIZE);
415 out_free_im:
416         kfree(im);
417 out:
418         return ERR_PTR(err);
419 }
420
421 static int bpf_trampoline_update(struct bpf_trampoline *tr, bool lock_direct_mutex)
422 {
423         struct bpf_tramp_image *im;
424         struct bpf_tramp_links *tlinks;
425         u32 orig_flags = tr->flags;
426         bool ip_arg = false;
427         int err, total;
428
429         tlinks = bpf_trampoline_get_progs(tr, &total, &ip_arg);
430         if (IS_ERR(tlinks))
431                 return PTR_ERR(tlinks);
432
433         if (total == 0) {
434                 err = unregister_fentry(tr, tr->cur_image->image);
435                 bpf_tramp_image_put(tr->cur_image);
436                 tr->cur_image = NULL;
437                 goto out;
438         }
439
440         im = bpf_tramp_image_alloc(tr->key);
441         if (IS_ERR(im)) {
442                 err = PTR_ERR(im);
443                 goto out;
444         }
445
446         /* clear all bits except SHARE_IPMODIFY */
447         tr->flags &= BPF_TRAMP_F_SHARE_IPMODIFY;
448
449         if (tlinks[BPF_TRAMP_FEXIT].nr_links ||
450             tlinks[BPF_TRAMP_MODIFY_RETURN].nr_links) {
451                 /* NOTE: BPF_TRAMP_F_RESTORE_REGS and BPF_TRAMP_F_SKIP_FRAME
452                  * should not be set together.
453                  */
454                 tr->flags |= BPF_TRAMP_F_CALL_ORIG | BPF_TRAMP_F_SKIP_FRAME;
455         } else {
456                 tr->flags |= BPF_TRAMP_F_RESTORE_REGS;
457         }
458
459         if (ip_arg)
460                 tr->flags |= BPF_TRAMP_F_IP_ARG;
461
462 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
463 again:
464         if ((tr->flags & BPF_TRAMP_F_SHARE_IPMODIFY) &&
465             (tr->flags & BPF_TRAMP_F_CALL_ORIG))
466                 tr->flags |= BPF_TRAMP_F_ORIG_STACK;
467 #endif
468
469         err = arch_prepare_bpf_trampoline(im, im->image, im->image + PAGE_SIZE,
470                                           &tr->func.model, tr->flags, tlinks,
471                                           tr->func.addr);
472         if (err < 0)
473                 goto out_free;
474
475         set_memory_ro((long)im->image, 1);
476         set_memory_x((long)im->image, 1);
477
478         WARN_ON(tr->cur_image && total == 0);
479         if (tr->cur_image)
480                 /* progs already running at this address */
481                 err = modify_fentry(tr, tr->cur_image->image, im->image, lock_direct_mutex);
482         else
483                 /* first time registering */
484                 err = register_fentry(tr, im->image);
485
486 #ifdef CONFIG_DYNAMIC_FTRACE_WITH_DIRECT_CALLS
487         if (err == -EAGAIN) {
488                 /* -EAGAIN from bpf_tramp_ftrace_ops_func. Now
489                  * BPF_TRAMP_F_SHARE_IPMODIFY is set, we can generate the
490                  * trampoline again, and retry register.
491                  */
492                 /* reset fops->func and fops->trampoline for re-register */
493                 tr->fops->func = NULL;
494                 tr->fops->trampoline = 0;
495
496                 /* reset im->image memory attr for arch_prepare_bpf_trampoline */
497                 set_memory_nx((long)im->image, 1);
498                 set_memory_rw((long)im->image, 1);
499                 goto again;
500         }
501 #endif
502         if (err)
503                 goto out_free;
504
505         if (tr->cur_image)
506                 bpf_tramp_image_put(tr->cur_image);
507         tr->cur_image = im;
508 out:
509         /* If any error happens, restore previous flags */
510         if (err)
511                 tr->flags = orig_flags;
512         kfree(tlinks);
513         return err;
514
515 out_free:
516         bpf_tramp_image_free(im);
517         goto out;
518 }
519
520 static enum bpf_tramp_prog_type bpf_attach_type_to_tramp(struct bpf_prog *prog)
521 {
522         switch (prog->expected_attach_type) {
523         case BPF_TRACE_FENTRY:
524                 return BPF_TRAMP_FENTRY;
525         case BPF_MODIFY_RETURN:
526                 return BPF_TRAMP_MODIFY_RETURN;
527         case BPF_TRACE_FEXIT:
528                 return BPF_TRAMP_FEXIT;
529         case BPF_LSM_MAC:
530                 if (!prog->aux->attach_func_proto->type)
531                         /* The function returns void, we cannot modify its
532                          * return value.
533                          */
534                         return BPF_TRAMP_FEXIT;
535                 else
536                         return BPF_TRAMP_MODIFY_RETURN;
537         default:
538                 return BPF_TRAMP_REPLACE;
539         }
540 }
541
542 static int __bpf_trampoline_link_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
543 {
544         enum bpf_tramp_prog_type kind;
545         struct bpf_tramp_link *link_exiting;
546         int err = 0;
547         int cnt = 0, i;
548
549         kind = bpf_attach_type_to_tramp(link->link.prog);
550         if (tr->extension_prog)
551                 /* cannot attach fentry/fexit if extension prog is attached.
552                  * cannot overwrite extension prog either.
553                  */
554                 return -EBUSY;
555
556         for (i = 0; i < BPF_TRAMP_MAX; i++)
557                 cnt += tr->progs_cnt[i];
558
559         if (kind == BPF_TRAMP_REPLACE) {
560                 /* Cannot attach extension if fentry/fexit are in use. */
561                 if (cnt)
562                         return -EBUSY;
563                 tr->extension_prog = link->link.prog;
564                 return bpf_arch_text_poke(tr->func.addr, BPF_MOD_JUMP, NULL,
565                                           link->link.prog->bpf_func);
566         }
567         if (cnt >= BPF_MAX_TRAMP_LINKS)
568                 return -E2BIG;
569         if (!hlist_unhashed(&link->tramp_hlist))
570                 /* prog already linked */
571                 return -EBUSY;
572         hlist_for_each_entry(link_exiting, &tr->progs_hlist[kind], tramp_hlist) {
573                 if (link_exiting->link.prog != link->link.prog)
574                         continue;
575                 /* prog already linked */
576                 return -EBUSY;
577         }
578
579         hlist_add_head(&link->tramp_hlist, &tr->progs_hlist[kind]);
580         tr->progs_cnt[kind]++;
581         err = bpf_trampoline_update(tr, true /* lock_direct_mutex */);
582         if (err) {
583                 hlist_del_init(&link->tramp_hlist);
584                 tr->progs_cnt[kind]--;
585         }
586         return err;
587 }
588
589 int bpf_trampoline_link_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
590 {
591         int err;
592
593         mutex_lock(&tr->mutex);
594         err = __bpf_trampoline_link_prog(link, tr);
595         mutex_unlock(&tr->mutex);
596         return err;
597 }
598
599 static int __bpf_trampoline_unlink_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
600 {
601         enum bpf_tramp_prog_type kind;
602         int err;
603
604         kind = bpf_attach_type_to_tramp(link->link.prog);
605         if (kind == BPF_TRAMP_REPLACE) {
606                 WARN_ON_ONCE(!tr->extension_prog);
607                 err = bpf_arch_text_poke(tr->func.addr, BPF_MOD_JUMP,
608                                          tr->extension_prog->bpf_func, NULL);
609                 tr->extension_prog = NULL;
610                 return err;
611         }
612         hlist_del_init(&link->tramp_hlist);
613         tr->progs_cnt[kind]--;
614         return bpf_trampoline_update(tr, true /* lock_direct_mutex */);
615 }
616
617 /* bpf_trampoline_unlink_prog() should never fail. */
618 int bpf_trampoline_unlink_prog(struct bpf_tramp_link *link, struct bpf_trampoline *tr)
619 {
620         int err;
621
622         mutex_lock(&tr->mutex);
623         err = __bpf_trampoline_unlink_prog(link, tr);
624         mutex_unlock(&tr->mutex);
625         return err;
626 }
627
628 #if defined(CONFIG_CGROUP_BPF) && defined(CONFIG_BPF_LSM)
629 static void bpf_shim_tramp_link_release(struct bpf_link *link)
630 {
631         struct bpf_shim_tramp_link *shim_link =
632                 container_of(link, struct bpf_shim_tramp_link, link.link);
633
634         /* paired with 'shim_link->trampoline = tr' in bpf_trampoline_link_cgroup_shim */
635         if (!shim_link->trampoline)
636                 return;
637
638         WARN_ON_ONCE(bpf_trampoline_unlink_prog(&shim_link->link, shim_link->trampoline));
639         bpf_trampoline_put(shim_link->trampoline);
640 }
641
642 static void bpf_shim_tramp_link_dealloc(struct bpf_link *link)
643 {
644         struct bpf_shim_tramp_link *shim_link =
645                 container_of(link, struct bpf_shim_tramp_link, link.link);
646
647         kfree(shim_link);
648 }
649
650 static const struct bpf_link_ops bpf_shim_tramp_link_lops = {
651         .release = bpf_shim_tramp_link_release,
652         .dealloc = bpf_shim_tramp_link_dealloc,
653 };
654
655 static struct bpf_shim_tramp_link *cgroup_shim_alloc(const struct bpf_prog *prog,
656                                                      bpf_func_t bpf_func,
657                                                      int cgroup_atype)
658 {
659         struct bpf_shim_tramp_link *shim_link = NULL;
660         struct bpf_prog *p;
661
662         shim_link = kzalloc(sizeof(*shim_link), GFP_USER);
663         if (!shim_link)
664                 return NULL;
665
666         p = bpf_prog_alloc(1, 0);
667         if (!p) {
668                 kfree(shim_link);
669                 return NULL;
670         }
671
672         p->jited = false;
673         p->bpf_func = bpf_func;
674
675         p->aux->cgroup_atype = cgroup_atype;
676         p->aux->attach_func_proto = prog->aux->attach_func_proto;
677         p->aux->attach_btf_id = prog->aux->attach_btf_id;
678         p->aux->attach_btf = prog->aux->attach_btf;
679         btf_get(p->aux->attach_btf);
680         p->type = BPF_PROG_TYPE_LSM;
681         p->expected_attach_type = BPF_LSM_MAC;
682         bpf_prog_inc(p);
683         bpf_link_init(&shim_link->link.link, BPF_LINK_TYPE_UNSPEC,
684                       &bpf_shim_tramp_link_lops, p);
685         bpf_cgroup_atype_get(p->aux->attach_btf_id, cgroup_atype);
686
687         return shim_link;
688 }
689
690 static struct bpf_shim_tramp_link *cgroup_shim_find(struct bpf_trampoline *tr,
691                                                     bpf_func_t bpf_func)
692 {
693         struct bpf_tramp_link *link;
694         int kind;
695
696         for (kind = 0; kind < BPF_TRAMP_MAX; kind++) {
697                 hlist_for_each_entry(link, &tr->progs_hlist[kind], tramp_hlist) {
698                         struct bpf_prog *p = link->link.prog;
699
700                         if (p->bpf_func == bpf_func)
701                                 return container_of(link, struct bpf_shim_tramp_link, link);
702                 }
703         }
704
705         return NULL;
706 }
707
708 int bpf_trampoline_link_cgroup_shim(struct bpf_prog *prog,
709                                     int cgroup_atype)
710 {
711         struct bpf_shim_tramp_link *shim_link = NULL;
712         struct bpf_attach_target_info tgt_info = {};
713         struct bpf_trampoline *tr;
714         bpf_func_t bpf_func;
715         u64 key;
716         int err;
717
718         err = bpf_check_attach_target(NULL, prog, NULL,
719                                       prog->aux->attach_btf_id,
720                                       &tgt_info);
721         if (err)
722                 return err;
723
724         key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf,
725                                          prog->aux->attach_btf_id);
726
727         bpf_lsm_find_cgroup_shim(prog, &bpf_func);
728         tr = bpf_trampoline_get(key, &tgt_info);
729         if (!tr)
730                 return  -ENOMEM;
731
732         mutex_lock(&tr->mutex);
733
734         shim_link = cgroup_shim_find(tr, bpf_func);
735         if (shim_link) {
736                 /* Reusing existing shim attached by the other program. */
737                 bpf_link_inc(&shim_link->link.link);
738
739                 mutex_unlock(&tr->mutex);
740                 bpf_trampoline_put(tr); /* bpf_trampoline_get above */
741                 return 0;
742         }
743
744         /* Allocate and install new shim. */
745
746         shim_link = cgroup_shim_alloc(prog, bpf_func, cgroup_atype);
747         if (!shim_link) {
748                 err = -ENOMEM;
749                 goto err;
750         }
751
752         err = __bpf_trampoline_link_prog(&shim_link->link, tr);
753         if (err)
754                 goto err;
755
756         shim_link->trampoline = tr;
757         /* note, we're still holding tr refcnt from above */
758
759         mutex_unlock(&tr->mutex);
760
761         return 0;
762 err:
763         mutex_unlock(&tr->mutex);
764
765         if (shim_link)
766                 bpf_link_put(&shim_link->link.link);
767
768         /* have to release tr while _not_ holding its mutex */
769         bpf_trampoline_put(tr); /* bpf_trampoline_get above */
770
771         return err;
772 }
773
774 void bpf_trampoline_unlink_cgroup_shim(struct bpf_prog *prog)
775 {
776         struct bpf_shim_tramp_link *shim_link = NULL;
777         struct bpf_trampoline *tr;
778         bpf_func_t bpf_func;
779         u64 key;
780
781         key = bpf_trampoline_compute_key(NULL, prog->aux->attach_btf,
782                                          prog->aux->attach_btf_id);
783
784         bpf_lsm_find_cgroup_shim(prog, &bpf_func);
785         tr = bpf_trampoline_lookup(key);
786         if (WARN_ON_ONCE(!tr))
787                 return;
788
789         mutex_lock(&tr->mutex);
790         shim_link = cgroup_shim_find(tr, bpf_func);
791         mutex_unlock(&tr->mutex);
792
793         if (shim_link)
794                 bpf_link_put(&shim_link->link.link);
795
796         bpf_trampoline_put(tr); /* bpf_trampoline_lookup above */
797 }
798 #endif
799
800 struct bpf_trampoline *bpf_trampoline_get(u64 key,
801                                           struct bpf_attach_target_info *tgt_info)
802 {
803         struct bpf_trampoline *tr;
804
805         tr = bpf_trampoline_lookup(key);
806         if (!tr)
807                 return NULL;
808
809         mutex_lock(&tr->mutex);
810         if (tr->func.addr)
811                 goto out;
812
813         memcpy(&tr->func.model, &tgt_info->fmodel, sizeof(tgt_info->fmodel));
814         tr->func.addr = (void *)tgt_info->tgt_addr;
815 out:
816         mutex_unlock(&tr->mutex);
817         return tr;
818 }
819
820 void bpf_trampoline_put(struct bpf_trampoline *tr)
821 {
822         int i;
823
824         if (!tr)
825                 return;
826         mutex_lock(&trampoline_mutex);
827         if (!refcount_dec_and_test(&tr->refcnt))
828                 goto out;
829         WARN_ON_ONCE(mutex_is_locked(&tr->mutex));
830
831         for (i = 0; i < BPF_TRAMP_MAX; i++)
832                 if (WARN_ON_ONCE(!hlist_empty(&tr->progs_hlist[i])))
833                         goto out;
834
835         /* This code will be executed even when the last bpf_tramp_image
836          * is alive. All progs are detached from the trampoline and the
837          * trampoline image is patched with jmp into epilogue to skip
838          * fexit progs. The fentry-only trampoline will be freed via
839          * multiple rcu callbacks.
840          */
841         hlist_del(&tr->hlist);
842         if (tr->fops) {
843                 ftrace_free_filter(tr->fops);
844                 kfree(tr->fops);
845         }
846         kfree(tr);
847 out:
848         mutex_unlock(&trampoline_mutex);
849 }
850
851 #define NO_START_TIME 1
852 static __always_inline u64 notrace bpf_prog_start_time(void)
853 {
854         u64 start = NO_START_TIME;
855
856         if (static_branch_unlikely(&bpf_stats_enabled_key)) {
857                 start = sched_clock();
858                 if (unlikely(!start))
859                         start = NO_START_TIME;
860         }
861         return start;
862 }
863
864 /* The logic is similar to bpf_prog_run(), but with an explicit
865  * rcu_read_lock() and migrate_disable() which are required
866  * for the trampoline. The macro is split into
867  * call __bpf_prog_enter
868  * call prog->bpf_func
869  * call __bpf_prog_exit
870  *
871  * __bpf_prog_enter returns:
872  * 0 - skip execution of the bpf prog
873  * 1 - execute bpf prog
874  * [2..MAX_U64] - execute bpf prog and record execution time.
875  *     This is start time.
876  */
877 u64 notrace __bpf_prog_enter(struct bpf_prog *prog, struct bpf_tramp_run_ctx *run_ctx)
878         __acquires(RCU)
879 {
880         rcu_read_lock();
881         migrate_disable();
882
883         run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
884
885         if (unlikely(this_cpu_inc_return(*(prog->active)) != 1)) {
886                 bpf_prog_inc_misses_counter(prog);
887                 return 0;
888         }
889         return bpf_prog_start_time();
890 }
891
892 static void notrace update_prog_stats(struct bpf_prog *prog,
893                                       u64 start)
894 {
895         struct bpf_prog_stats *stats;
896
897         if (static_branch_unlikely(&bpf_stats_enabled_key) &&
898             /* static_key could be enabled in __bpf_prog_enter*
899              * and disabled in __bpf_prog_exit*.
900              * And vice versa.
901              * Hence check that 'start' is valid.
902              */
903             start > NO_START_TIME) {
904                 unsigned long flags;
905
906                 stats = this_cpu_ptr(prog->stats);
907                 flags = u64_stats_update_begin_irqsave(&stats->syncp);
908                 u64_stats_inc(&stats->cnt);
909                 u64_stats_add(&stats->nsecs, sched_clock() - start);
910                 u64_stats_update_end_irqrestore(&stats->syncp, flags);
911         }
912 }
913
914 void notrace __bpf_prog_exit(struct bpf_prog *prog, u64 start, struct bpf_tramp_run_ctx *run_ctx)
915         __releases(RCU)
916 {
917         bpf_reset_run_ctx(run_ctx->saved_run_ctx);
918
919         update_prog_stats(prog, start);
920         this_cpu_dec(*(prog->active));
921         migrate_enable();
922         rcu_read_unlock();
923 }
924
925 u64 notrace __bpf_prog_enter_lsm_cgroup(struct bpf_prog *prog,
926                                         struct bpf_tramp_run_ctx *run_ctx)
927         __acquires(RCU)
928 {
929         /* Runtime stats are exported via actual BPF_LSM_CGROUP
930          * programs, not the shims.
931          */
932         rcu_read_lock();
933         migrate_disable();
934
935         run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
936
937         return NO_START_TIME;
938 }
939
940 void notrace __bpf_prog_exit_lsm_cgroup(struct bpf_prog *prog, u64 start,
941                                         struct bpf_tramp_run_ctx *run_ctx)
942         __releases(RCU)
943 {
944         bpf_reset_run_ctx(run_ctx->saved_run_ctx);
945
946         migrate_enable();
947         rcu_read_unlock();
948 }
949
950 u64 notrace __bpf_prog_enter_sleepable(struct bpf_prog *prog, struct bpf_tramp_run_ctx *run_ctx)
951 {
952         rcu_read_lock_trace();
953         migrate_disable();
954         might_fault();
955
956         if (unlikely(this_cpu_inc_return(*(prog->active)) != 1)) {
957                 bpf_prog_inc_misses_counter(prog);
958                 return 0;
959         }
960
961         run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
962
963         return bpf_prog_start_time();
964 }
965
966 void notrace __bpf_prog_exit_sleepable(struct bpf_prog *prog, u64 start,
967                                        struct bpf_tramp_run_ctx *run_ctx)
968 {
969         bpf_reset_run_ctx(run_ctx->saved_run_ctx);
970
971         update_prog_stats(prog, start);
972         this_cpu_dec(*(prog->active));
973         migrate_enable();
974         rcu_read_unlock_trace();
975 }
976
977 u64 notrace __bpf_prog_enter_struct_ops(struct bpf_prog *prog,
978                                         struct bpf_tramp_run_ctx *run_ctx)
979         __acquires(RCU)
980 {
981         rcu_read_lock();
982         migrate_disable();
983
984         run_ctx->saved_run_ctx = bpf_set_run_ctx(&run_ctx->run_ctx);
985
986         return bpf_prog_start_time();
987 }
988
989 void notrace __bpf_prog_exit_struct_ops(struct bpf_prog *prog, u64 start,
990                                         struct bpf_tramp_run_ctx *run_ctx)
991         __releases(RCU)
992 {
993         bpf_reset_run_ctx(run_ctx->saved_run_ctx);
994
995         update_prog_stats(prog, start);
996         migrate_enable();
997         rcu_read_unlock();
998 }
999
1000 void notrace __bpf_tramp_enter(struct bpf_tramp_image *tr)
1001 {
1002         percpu_ref_get(&tr->pcref);
1003 }
1004
1005 void notrace __bpf_tramp_exit(struct bpf_tramp_image *tr)
1006 {
1007         percpu_ref_put(&tr->pcref);
1008 }
1009
1010 int __weak
1011 arch_prepare_bpf_trampoline(struct bpf_tramp_image *tr, void *image, void *image_end,
1012                             const struct btf_func_model *m, u32 flags,
1013                             struct bpf_tramp_links *tlinks,
1014                             void *orig_call)
1015 {
1016         return -ENOTSUPP;
1017 }
1018
1019 static int __init init_trampolines(void)
1020 {
1021         int i;
1022
1023         for (i = 0; i < TRAMPOLINE_TABLE_SIZE; i++)
1024                 INIT_HLIST_HEAD(&trampoline_table[i]);
1025         return 0;
1026 }
1027 late_initcall(init_trampolines);