1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Linux Socket Filter - Kernel level socket filtering
4 *
5 * Based on the design of the Berkeley Packet Filter. The new
6 * internal format has been designed by PLUMgrid:
7 *
8 * Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
9 *
10 * Authors:
11 *
12 * Jay Schulist <jschlst@samba.org>
13 * Alexei Starovoitov <ast@plumgrid.com>
14 * Daniel Borkmann <dborkman@redhat.com>
15 *
16 * Andi Kleen - Fix a few bad bugs and races.
17 * Kris Katterjohn - Added many additional checks in bpf_check_classic()
18 */
19
20 #include <uapi/linux/btf.h>
21 #include <linux/filter.h>
22 #include <linux/skbuff.h>
23 #include <linux/static_call.h>
24 #include <linux/vmalloc.h>
25 #include <linux/prandom.h>
26 #include <linux/bpf.h>
27 #include <linux/btf.h>
28 #include <linux/hex.h>
29 #include <linux/objtool.h>
30 #include <linux/overflow.h>
31 #include <linux/rbtree_latch.h>
32 #include <linux/kallsyms.h>
33 #include <linux/rcupdate.h>
34 #include <linux/perf_event.h>
35 #include <linux/extable.h>
36 #include <linux/log2.h>
37 #include <linux/bpf_verifier.h>
38 #include <linux/nodemask.h>
39 #include <linux/nospec.h>
40 #include <linux/bpf_mem_alloc.h>
41 #include <linux/memcontrol.h>
42 #include <linux/execmem.h>
43 #include <crypto/sha2.h>
44
45 #include <asm/barrier.h>
46 #include <linux/unaligned.h>
47
48 /* Registers */
49 #define BPF_R0 regs[BPF_REG_0]
50 #define BPF_R1 regs[BPF_REG_1]
51 #define BPF_R2 regs[BPF_REG_2]
52 #define BPF_R3 regs[BPF_REG_3]
53 #define BPF_R4 regs[BPF_REG_4]
54 #define BPF_R5 regs[BPF_REG_5]
55 #define BPF_R6 regs[BPF_REG_6]
56 #define BPF_R7 regs[BPF_REG_7]
57 #define BPF_R8 regs[BPF_REG_8]
58 #define BPF_R9 regs[BPF_REG_9]
59 #define BPF_R10 regs[BPF_REG_10]
60
61 /* Named registers */
62 #define DST regs[insn->dst_reg]
63 #define SRC regs[insn->src_reg]
64 #define FP regs[BPF_REG_FP]
65 #define AX regs[BPF_REG_AX]
66 #define ARG1 regs[BPF_REG_ARG1]
67 #define CTX regs[BPF_REG_CTX]
68 #define OFF insn->off
69 #define IMM insn->imm
70
71 struct bpf_mem_alloc bpf_global_ma;
72 bool bpf_global_ma_set;
73
74 /* No hurry in this branch
75 *
76 * Exported for the bpf jit load helper.
77 */
bpf_internal_load_pointer_neg_helper(const struct sk_buff * skb,int k,unsigned int size)78 void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, unsigned int size)
79 {
80 u8 *ptr = NULL;
81
82 if (k >= SKF_NET_OFF) {
83 ptr = skb_network_header(skb) + k - SKF_NET_OFF;
84 } else if (k >= SKF_LL_OFF) {
85 if (unlikely(!skb_mac_header_was_set(skb)))
86 return NULL;
87 ptr = skb_mac_header(skb) + k - SKF_LL_OFF;
88 }
89 if (ptr >= skb->head && ptr + size <= skb_tail_pointer(skb))
90 return ptr;
91
92 return NULL;
93 }
94
95 /* tell bpf programs that include vmlinux.h kernel's PAGE_SIZE */
96 enum page_size_enum {
97 __PAGE_SIZE = PAGE_SIZE
98 };
99
bpf_prog_alloc_no_stats(unsigned int size,gfp_t gfp_extra_flags)100 struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)
101 {
102 gfp_t gfp_flags = bpf_memcg_flags(GFP_KERNEL | __GFP_ZERO | gfp_extra_flags);
103 struct bpf_prog_aux *aux;
104 struct bpf_prog *fp;
105
106 size = round_up(size, __PAGE_SIZE);
107 fp = __vmalloc(size, gfp_flags);
108 if (fp == NULL)
109 return NULL;
110
111 aux = kzalloc_obj(*aux, bpf_memcg_flags(GFP_KERNEL | gfp_extra_flags));
112 if (aux == NULL) {
113 vfree(fp);
114 return NULL;
115 }
116 fp->active = __alloc_percpu_gfp(sizeof(u8[BPF_NR_CONTEXTS]), 4,
117 bpf_memcg_flags(GFP_KERNEL | gfp_extra_flags));
118 if (!fp->active) {
119 vfree(fp);
120 kfree(aux);
121 return NULL;
122 }
123
124 fp->pages = size / PAGE_SIZE;
125 fp->aux = aux;
126 fp->aux->main_prog_aux = aux;
127 fp->aux->prog = fp;
128 fp->jit_requested = ebpf_jit_enabled();
129 fp->blinding_requested = bpf_jit_blinding_enabled(fp);
130 #ifdef CONFIG_CGROUP_BPF
131 aux->cgroup_atype = CGROUP_BPF_ATTACH_TYPE_INVALID;
132 #endif
133
134 INIT_LIST_HEAD_RCU(&fp->aux->ksym.lnode);
135 #ifdef CONFIG_FINEIBT
136 INIT_LIST_HEAD_RCU(&fp->aux->ksym_prefix.lnode);
137 #endif
138 mutex_init(&fp->aux->used_maps_mutex);
139 mutex_init(&fp->aux->ext_mutex);
140 mutex_init(&fp->aux->dst_mutex);
141 mutex_init(&fp->aux->st_ops_assoc_mutex);
142
143 #ifdef CONFIG_BPF_SYSCALL
144 bpf_prog_stream_init(fp);
145 #endif
146
147 return fp;
148 }
149
bpf_prog_alloc(unsigned int size,gfp_t gfp_extra_flags)150 struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags)
151 {
152 gfp_t gfp_flags = bpf_memcg_flags(GFP_KERNEL | __GFP_ZERO | gfp_extra_flags);
153 struct bpf_prog *prog;
154 int cpu;
155
156 prog = bpf_prog_alloc_no_stats(size, gfp_extra_flags);
157 if (!prog)
158 return NULL;
159
160 prog->stats = alloc_percpu_gfp(struct bpf_prog_stats, gfp_flags);
161 if (!prog->stats) {
162 free_percpu(prog->active);
163 kfree(prog->aux);
164 vfree(prog);
165 return NULL;
166 }
167
168 for_each_possible_cpu(cpu) {
169 struct bpf_prog_stats *pstats;
170
171 pstats = per_cpu_ptr(prog->stats, cpu);
172 u64_stats_init(&pstats->syncp);
173 }
174 return prog;
175 }
176 EXPORT_SYMBOL_GPL(bpf_prog_alloc);
177
bpf_prog_alloc_jited_linfo(struct bpf_prog * prog)178 int bpf_prog_alloc_jited_linfo(struct bpf_prog *prog)
179 {
180 if (!prog->aux->nr_linfo || !prog->jit_requested)
181 return 0;
182
183 prog->aux->jited_linfo = kvzalloc_objs(*prog->aux->jited_linfo,
184 prog->aux->nr_linfo,
185 bpf_memcg_flags(GFP_KERNEL | __GFP_NOWARN));
186 if (!prog->aux->jited_linfo)
187 return -ENOMEM;
188
189 return 0;
190 }
191
bpf_prog_jit_attempt_done(struct bpf_prog * prog)192 void bpf_prog_jit_attempt_done(struct bpf_prog *prog)
193 {
194 if (prog->aux->jited_linfo &&
195 (!prog->jited || !prog->aux->jited_linfo[0])) {
196 kvfree(prog->aux->jited_linfo);
197 prog->aux->jited_linfo = NULL;
198 }
199
200 kfree(prog->aux->kfunc_tab);
201 prog->aux->kfunc_tab = NULL;
202 }
203
204 /* The jit engine is responsible to provide an array
205 * for insn_off to the jited_off mapping (insn_to_jit_off).
206 *
207 * The idx to this array is the insn_off. Hence, the insn_off
208 * here is relative to the prog itself instead of the main prog.
209 * This array has one entry for each xlated bpf insn.
210 *
211 * jited_off is the byte off to the end of the jited insn.
212 *
213 * Hence, with
214 * insn_start:
215 * The first bpf insn off of the prog. The insn off
216 * here is relative to the main prog.
217 * e.g. if prog is a subprog, insn_start > 0
218 * linfo_idx:
219 * The prog's idx to prog->aux->linfo and jited_linfo
220 *
221 * jited_linfo[linfo_idx] = prog->bpf_func
222 *
223 * For i > linfo_idx,
224 *
225 * jited_linfo[i] = prog->bpf_func +
226 * insn_to_jit_off[linfo[i].insn_off - insn_start - 1]
227 */
bpf_prog_fill_jited_linfo(struct bpf_prog * prog,const u32 * insn_to_jit_off)228 void bpf_prog_fill_jited_linfo(struct bpf_prog *prog,
229 const u32 *insn_to_jit_off)
230 {
231 u32 linfo_idx, insn_start, insn_end, nr_linfo, i;
232 const struct bpf_line_info *linfo;
233 void **jited_linfo;
234
235 if (!prog->aux->jited_linfo || prog->aux->func_idx > prog->aux->func_cnt)
236 /* Userspace did not provide linfo */
237 return;
238
239 linfo_idx = prog->aux->linfo_idx;
240 linfo = &prog->aux->linfo[linfo_idx];
241 insn_start = linfo[0].insn_off;
242 insn_end = insn_start + prog->len;
243
244 jited_linfo = &prog->aux->jited_linfo[linfo_idx];
245 jited_linfo[0] = prog->bpf_func;
246
247 nr_linfo = prog->aux->nr_linfo - linfo_idx;
248
249 for (i = 1; i < nr_linfo && linfo[i].insn_off < insn_end; i++)
250 /* The verifier ensures that linfo[i].insn_off is
251 * strictly increasing
252 */
253 jited_linfo[i] = prog->bpf_func +
254 insn_to_jit_off[linfo[i].insn_off - insn_start - 1];
255 }
256
bpf_prog_realloc(struct bpf_prog * fp_old,unsigned int size,gfp_t gfp_extra_flags)257 struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
258 gfp_t gfp_extra_flags)
259 {
260 gfp_t gfp_flags = bpf_memcg_flags(GFP_KERNEL | __GFP_ZERO | gfp_extra_flags);
261 struct bpf_prog *fp;
262 u32 pages;
263
264 size = round_up(size, PAGE_SIZE);
265 pages = size / PAGE_SIZE;
266 if (pages <= fp_old->pages)
267 return fp_old;
268
269 fp = __vmalloc(size, gfp_flags);
270 if (fp) {
271 memcpy(fp, fp_old, fp_old->pages * PAGE_SIZE);
272 fp->pages = pages;
273 fp->aux->prog = fp;
274
275 /* We keep fp->aux from fp_old around in the new
276 * reallocated structure.
277 */
278 fp_old->aux = NULL;
279 fp_old->stats = NULL;
280 fp_old->active = NULL;
281 __bpf_prog_free(fp_old);
282 }
283
284 return fp;
285 }
286
__bpf_prog_free(struct bpf_prog * fp)287 void __bpf_prog_free(struct bpf_prog *fp)
288 {
289 if (fp->aux) {
290 mutex_destroy(&fp->aux->used_maps_mutex);
291 mutex_destroy(&fp->aux->dst_mutex);
292 mutex_destroy(&fp->aux->st_ops_assoc_mutex);
293 kfree(fp->aux->poke_tab);
294 kfree(fp->aux);
295 }
296 free_percpu(fp->stats);
297 free_percpu(fp->active);
298 vfree(fp);
299 }
300
bpf_prog_calc_tag(struct bpf_prog * fp)301 int bpf_prog_calc_tag(struct bpf_prog *fp)
302 {
303 size_t size = bpf_prog_insn_size(fp);
304 struct bpf_insn *dst;
305 bool was_ld_map;
306 u32 i;
307
308 dst = vmalloc(size);
309 if (!dst)
310 return -ENOMEM;
311
312 /* We need to take out the map fd for the digest calculation
313 * since they are unstable from user space side.
314 */
315 for (i = 0, was_ld_map = false; i < fp->len; i++) {
316 dst[i] = fp->insnsi[i];
317 if (!was_ld_map &&
318 dst[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
319 (dst[i].src_reg == BPF_PSEUDO_MAP_FD ||
320 dst[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
321 was_ld_map = true;
322 dst[i].imm = 0;
323 } else if (was_ld_map &&
324 dst[i].code == 0 &&
325 dst[i].dst_reg == 0 &&
326 dst[i].src_reg == 0 &&
327 dst[i].off == 0) {
328 was_ld_map = false;
329 dst[i].imm = 0;
330 } else {
331 was_ld_map = false;
332 }
333 }
334 sha256((u8 *)dst, size, fp->digest);
335 vfree(dst);
336 return 0;
337 }
338
bpf_adj_delta_to_imm(struct bpf_insn * insn,u32 pos,s32 end_old,s32 end_new,s32 curr,const bool probe_pass)339 static int bpf_adj_delta_to_imm(struct bpf_insn *insn, u32 pos, s32 end_old,
340 s32 end_new, s32 curr, const bool probe_pass)
341 {
342 const s64 imm_min = S32_MIN, imm_max = S32_MAX;
343 s32 delta = end_new - end_old;
344 s64 imm = insn->imm;
345
346 if (curr < pos && curr + imm + 1 >= end_old)
347 imm += delta;
348 else if (curr >= end_new && curr + imm + 1 < end_new)
349 imm -= delta;
350 if (imm < imm_min || imm > imm_max)
351 return -ERANGE;
352 if (!probe_pass)
353 insn->imm = imm;
354 return 0;
355 }
356
bpf_adj_delta_to_off(struct bpf_insn * insn,u32 pos,s32 end_old,s32 end_new,s32 curr,const bool probe_pass)357 static int bpf_adj_delta_to_off(struct bpf_insn *insn, u32 pos, s32 end_old,
358 s32 end_new, s32 curr, const bool probe_pass)
359 {
360 s64 off_min, off_max, off;
361 s32 delta = end_new - end_old;
362
363 if (insn->code == (BPF_JMP32 | BPF_JA)) {
364 off = insn->imm;
365 off_min = S32_MIN;
366 off_max = S32_MAX;
367 } else {
368 off = insn->off;
369 off_min = S16_MIN;
370 off_max = S16_MAX;
371 }
372
373 if (curr < pos && curr + off + 1 >= end_old)
374 off += delta;
375 else if (curr >= end_new && curr + off + 1 < end_new)
376 off -= delta;
377 if (off < off_min || off > off_max)
378 return -ERANGE;
379 if (!probe_pass) {
380 if (insn->code == (BPF_JMP32 | BPF_JA))
381 insn->imm = off;
382 else
383 insn->off = off;
384 }
385 return 0;
386 }
387
bpf_adj_branches(struct bpf_prog * prog,u32 pos,s32 end_old,s32 end_new,const bool probe_pass)388 static int bpf_adj_branches(struct bpf_prog *prog, u32 pos, s32 end_old,
389 s32 end_new, const bool probe_pass)
390 {
391 u32 i, insn_cnt = prog->len + (probe_pass ? end_new - end_old : 0);
392 struct bpf_insn *insn = prog->insnsi;
393 int ret = 0;
394
395 for (i = 0; i < insn_cnt; i++, insn++) {
396 u8 code;
397
398 /* In the probing pass we still operate on the original,
399 * unpatched image in order to check overflows before we
400 * do any other adjustments. Therefore skip the patchlet.
401 */
402 if (probe_pass && i == pos) {
403 i = end_new;
404 insn = prog->insnsi + end_old;
405 }
406 if (bpf_pseudo_func(insn)) {
407 ret = bpf_adj_delta_to_imm(insn, pos, end_old,
408 end_new, i, probe_pass);
409 if (ret)
410 return ret;
411 continue;
412 }
413 code = insn->code;
414 if ((BPF_CLASS(code) != BPF_JMP &&
415 BPF_CLASS(code) != BPF_JMP32) ||
416 BPF_OP(code) == BPF_EXIT)
417 continue;
418 /* Adjust offset of jmps if we cross patch boundaries. */
419 if (BPF_OP(code) == BPF_CALL) {
420 if (insn->src_reg != BPF_PSEUDO_CALL)
421 continue;
422 ret = bpf_adj_delta_to_imm(insn, pos, end_old,
423 end_new, i, probe_pass);
424 } else {
425 ret = bpf_adj_delta_to_off(insn, pos, end_old,
426 end_new, i, probe_pass);
427 }
428 if (ret)
429 break;
430 }
431
432 return ret;
433 }
434
bpf_adj_linfo(struct bpf_prog * prog,u32 off,u32 delta)435 static void bpf_adj_linfo(struct bpf_prog *prog, u32 off, u32 delta)
436 {
437 struct bpf_line_info *linfo;
438 u32 i, nr_linfo;
439
440 nr_linfo = prog->aux->nr_linfo;
441 if (!nr_linfo || !delta)
442 return;
443
444 linfo = prog->aux->linfo;
445
446 for (i = 0; i < nr_linfo; i++)
447 if (off < linfo[i].insn_off)
448 break;
449
450 /* Push all off < linfo[i].insn_off by delta */
451 for (; i < nr_linfo; i++)
452 linfo[i].insn_off += delta;
453 }
454
bpf_patch_insn_single(struct bpf_prog * prog,u32 off,const struct bpf_insn * patch,u32 len)455 struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off,
456 const struct bpf_insn *patch, u32 len)
457 {
458 u32 insn_adj_cnt, insn_rest, insn_delta = len - 1;
459 const u32 cnt_max = S16_MAX;
460 struct bpf_prog *prog_adj;
461 int err;
462
463 /* Since our patchlet doesn't expand the image, we're done. */
464 if (insn_delta == 0) {
465 memcpy(prog->insnsi + off, patch, sizeof(*patch));
466 return prog;
467 }
468
469 insn_adj_cnt = prog->len + insn_delta;
470
471 /* Reject anything that would potentially let the insn->off
472 * target overflow when we have excessive program expansions.
473 * We need to probe here before we do any reallocation where
474 * we afterwards may not fail anymore.
475 */
476 if (insn_adj_cnt > cnt_max &&
477 (err = bpf_adj_branches(prog, off, off + 1, off + len, true)))
478 return ERR_PTR(err);
479
480 /* Several new instructions need to be inserted. Make room
481 * for them. Likely, there's no need for a new allocation as
482 * last page could have large enough tailroom.
483 */
484 prog_adj = bpf_prog_realloc(prog, bpf_prog_size(insn_adj_cnt),
485 GFP_USER);
486 if (!prog_adj)
487 return ERR_PTR(-ENOMEM);
488
489 prog_adj->len = insn_adj_cnt;
490
491 /* Patching happens in 3 steps:
492 *
493 * 1) Move over tail of insnsi from next instruction onwards,
494 * so we can patch the single target insn with one or more
495 * new ones (patching is always from 1 to n insns, n > 0).
496 * 2) Inject new instructions at the target location.
497 * 3) Adjust branch offsets if necessary.
498 */
499 insn_rest = insn_adj_cnt - off - len;
500
501 memmove(prog_adj->insnsi + off + len, prog_adj->insnsi + off + 1,
502 sizeof(*patch) * insn_rest);
503 memcpy(prog_adj->insnsi + off, patch, sizeof(*patch) * len);
504
505 /* We are guaranteed to not fail at this point, otherwise
506 * the ship has sailed to reverse to the original state. An
507 * overflow cannot happen at this point.
508 */
509 BUG_ON(bpf_adj_branches(prog_adj, off, off + 1, off + len, false));
510
511 bpf_adj_linfo(prog_adj, off, insn_delta);
512
513 return prog_adj;
514 }
515
bpf_remove_insns(struct bpf_prog * prog,u32 off,u32 cnt)516 int bpf_remove_insns(struct bpf_prog *prog, u32 off, u32 cnt)
517 {
518 int err;
519
520 /* Branch offsets can't overflow when program is shrinking, no need
521 * to call bpf_adj_branches(..., true) here
522 */
523 memmove(prog->insnsi + off, prog->insnsi + off + cnt,
524 sizeof(struct bpf_insn) * (prog->len - off - cnt));
525 prog->len -= cnt;
526
527 err = bpf_adj_branches(prog, off, off + cnt, off, false);
528 WARN_ON_ONCE(err);
529 return err;
530 }
531
bpf_prog_kallsyms_del_subprogs(struct bpf_prog * fp)532 static void bpf_prog_kallsyms_del_subprogs(struct bpf_prog *fp)
533 {
534 int i;
535
536 for (i = 0; i < fp->aux->real_func_cnt; i++)
537 bpf_prog_kallsyms_del(fp->aux->func[i]);
538 }
539
bpf_prog_kallsyms_del_all(struct bpf_prog * fp)540 void bpf_prog_kallsyms_del_all(struct bpf_prog *fp)
541 {
542 bpf_prog_kallsyms_del_subprogs(fp);
543 bpf_prog_kallsyms_del(fp);
544 }
545
546 #ifdef CONFIG_BPF_JIT
547 /* All BPF JIT sysctl knobs here. */
548 int bpf_jit_enable __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_DEFAULT_ON);
549 int bpf_jit_kallsyms __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_DEFAULT_ON);
550 int bpf_jit_harden __read_mostly;
551 long bpf_jit_limit __read_mostly;
552 long bpf_jit_limit_max __read_mostly;
553
554 static void
bpf_prog_ksym_set_addr(struct bpf_prog * prog)555 bpf_prog_ksym_set_addr(struct bpf_prog *prog)
556 {
557 WARN_ON_ONCE(!bpf_prog_ebpf_jited(prog));
558
559 prog->aux->ksym.start = (unsigned long) prog->bpf_func;
560 prog->aux->ksym.end = prog->aux->ksym.start + prog->jited_len;
561 }
562
563 static void
bpf_prog_ksym_set_name(struct bpf_prog * prog)564 bpf_prog_ksym_set_name(struct bpf_prog *prog)
565 {
566 char *sym = prog->aux->ksym.name;
567 const char *end = sym + KSYM_NAME_LEN;
568 const struct btf_type *type;
569 const char *func_name;
570
571 BUILD_BUG_ON(sizeof("bpf_prog_") +
572 sizeof(prog->tag) * 2 +
573 /* name has been null terminated.
574 * We should need +1 for the '_' preceding
575 * the name. However, the null character
576 * is double counted between the name and the
577 * sizeof("bpf_prog_") above, so we omit
578 * the +1 here.
579 */
580 sizeof(prog->aux->name) > KSYM_NAME_LEN);
581
582 sym += snprintf(sym, KSYM_NAME_LEN, "bpf_prog_");
583 sym = bin2hex(sym, prog->tag, sizeof(prog->tag));
584
585 /* prog->aux->name will be ignored if full btf name is available */
586 if (prog->aux->func_info_cnt && prog->aux->func_idx < prog->aux->func_info_cnt) {
587 type = btf_type_by_id(prog->aux->btf,
588 prog->aux->func_info[prog->aux->func_idx].type_id);
589 func_name = btf_name_by_offset(prog->aux->btf, type->name_off);
590 snprintf(sym, (size_t)(end - sym), "_%s", func_name);
591 return;
592 }
593
594 if (prog->aux->name[0])
595 snprintf(sym, (size_t)(end - sym), "_%s", prog->aux->name);
596 else
597 *sym = 0;
598 }
599
bpf_get_ksym_start(struct latch_tree_node * n)600 static unsigned long bpf_get_ksym_start(struct latch_tree_node *n)
601 {
602 return container_of(n, struct bpf_ksym, tnode)->start;
603 }
604
bpf_tree_less(struct latch_tree_node * a,struct latch_tree_node * b)605 static __always_inline bool bpf_tree_less(struct latch_tree_node *a,
606 struct latch_tree_node *b)
607 {
608 return bpf_get_ksym_start(a) < bpf_get_ksym_start(b);
609 }
610
bpf_tree_comp(void * key,struct latch_tree_node * n)611 static __always_inline int bpf_tree_comp(void *key, struct latch_tree_node *n)
612 {
613 unsigned long val = (unsigned long)key;
614 const struct bpf_ksym *ksym;
615
616 ksym = container_of(n, struct bpf_ksym, tnode);
617
618 if (val < ksym->start)
619 return -1;
620 /* Ensure that we detect return addresses as part of the program, when
621 * the final instruction is a call for a program part of the stack
622 * trace. Therefore, do val > ksym->end instead of val >= ksym->end.
623 */
624 if (val > ksym->end)
625 return 1;
626
627 return 0;
628 }
629
630 static const struct latch_tree_ops bpf_tree_ops = {
631 .less = bpf_tree_less,
632 .comp = bpf_tree_comp,
633 };
634
635 static DEFINE_SPINLOCK(bpf_lock);
636 static LIST_HEAD(bpf_kallsyms);
637 static struct latch_tree_root bpf_tree __cacheline_aligned;
638
bpf_ksym_add(struct bpf_ksym * ksym)639 void bpf_ksym_add(struct bpf_ksym *ksym)
640 {
641 spin_lock_bh(&bpf_lock);
642 WARN_ON_ONCE(!list_empty(&ksym->lnode));
643 list_add_tail_rcu(&ksym->lnode, &bpf_kallsyms);
644 latch_tree_insert(&ksym->tnode, &bpf_tree, &bpf_tree_ops);
645 spin_unlock_bh(&bpf_lock);
646 }
647
__bpf_ksym_del(struct bpf_ksym * ksym)648 static void __bpf_ksym_del(struct bpf_ksym *ksym)
649 {
650 if (list_empty(&ksym->lnode))
651 return;
652
653 latch_tree_erase(&ksym->tnode, &bpf_tree, &bpf_tree_ops);
654 list_del_rcu(&ksym->lnode);
655 }
656
bpf_ksym_del(struct bpf_ksym * ksym)657 void bpf_ksym_del(struct bpf_ksym *ksym)
658 {
659 spin_lock_bh(&bpf_lock);
660 __bpf_ksym_del(ksym);
661 spin_unlock_bh(&bpf_lock);
662 }
663
bpf_prog_kallsyms_candidate(const struct bpf_prog * fp)664 static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp)
665 {
666 return fp->jited && !bpf_prog_was_classic(fp);
667 }
668
bpf_prog_kallsyms_add(struct bpf_prog * fp)669 void bpf_prog_kallsyms_add(struct bpf_prog *fp)
670 {
671 if (!bpf_prog_kallsyms_candidate(fp) ||
672 !bpf_token_capable(fp->aux->token, CAP_BPF))
673 return;
674
675 bpf_prog_ksym_set_addr(fp);
676 bpf_prog_ksym_set_name(fp);
677 fp->aux->ksym.prog = true;
678
679 bpf_ksym_add(&fp->aux->ksym);
680
681 #ifdef CONFIG_FINEIBT
682 /*
683 * When FineIBT, code in the __cfi_foo() symbols can get executed
684 * and hence unwinder needs help.
685 */
686 if (cfi_mode != CFI_FINEIBT)
687 return;
688
689 snprintf(fp->aux->ksym_prefix.name, KSYM_NAME_LEN,
690 "__cfi_%s", fp->aux->ksym.name);
691
692 fp->aux->ksym_prefix.start = (unsigned long) fp->bpf_func - 16;
693 fp->aux->ksym_prefix.end = (unsigned long) fp->bpf_func;
694
695 bpf_ksym_add(&fp->aux->ksym_prefix);
696 #endif
697 }
698
bpf_prog_kallsyms_del(struct bpf_prog * fp)699 void bpf_prog_kallsyms_del(struct bpf_prog *fp)
700 {
701 if (!bpf_prog_kallsyms_candidate(fp))
702 return;
703
704 bpf_ksym_del(&fp->aux->ksym);
705 #ifdef CONFIG_FINEIBT
706 if (cfi_mode != CFI_FINEIBT)
707 return;
708 bpf_ksym_del(&fp->aux->ksym_prefix);
709 #endif
710 }
711
bpf_ksym_find(unsigned long addr)712 static struct bpf_ksym *bpf_ksym_find(unsigned long addr)
713 {
714 struct latch_tree_node *n;
715
716 n = latch_tree_find((void *)addr, &bpf_tree, &bpf_tree_ops);
717 return n ? container_of(n, struct bpf_ksym, tnode) : NULL;
718 }
719
bpf_address_lookup(unsigned long addr,unsigned long * size,unsigned long * off,char * sym)720 int bpf_address_lookup(unsigned long addr, unsigned long *size,
721 unsigned long *off, char *sym)
722 {
723 struct bpf_ksym *ksym;
724 int ret = 0;
725
726 rcu_read_lock();
727 ksym = bpf_ksym_find(addr);
728 if (ksym) {
729 unsigned long symbol_start = ksym->start;
730 unsigned long symbol_end = ksym->end;
731
732 ret = strscpy(sym, ksym->name, KSYM_NAME_LEN);
733
734 if (size)
735 *size = symbol_end - symbol_start;
736 if (off)
737 *off = addr - symbol_start;
738 }
739 rcu_read_unlock();
740
741 return ret;
742 }
743
is_bpf_text_address(unsigned long addr)744 bool is_bpf_text_address(unsigned long addr)
745 {
746 bool ret;
747
748 rcu_read_lock();
749 ret = bpf_ksym_find(addr) != NULL;
750 rcu_read_unlock();
751
752 return ret;
753 }
754
bpf_prog_ksym_find(unsigned long addr)755 struct bpf_prog *bpf_prog_ksym_find(unsigned long addr)
756 {
757 struct bpf_ksym *ksym;
758
759 WARN_ON_ONCE(!rcu_read_lock_held());
760 ksym = bpf_ksym_find(addr);
761
762 return ksym && ksym->prog ?
763 container_of(ksym, struct bpf_prog_aux, ksym)->prog :
764 NULL;
765 }
766
bpf_has_frame_pointer(unsigned long ip)767 bool bpf_has_frame_pointer(unsigned long ip)
768 {
769 struct bpf_ksym *ksym;
770 unsigned long offset;
771
772 guard(rcu)();
773
774 ksym = bpf_ksym_find(ip);
775 if (!ksym || !ksym->fp_start || !ksym->fp_end)
776 return false;
777
778 offset = ip - ksym->start;
779
780 return offset >= ksym->fp_start && offset < ksym->fp_end;
781 }
782
search_bpf_extables(unsigned long addr)783 const struct exception_table_entry *search_bpf_extables(unsigned long addr)
784 {
785 const struct exception_table_entry *e = NULL;
786 struct bpf_prog *prog;
787
788 rcu_read_lock();
789 prog = bpf_prog_ksym_find(addr);
790 if (!prog)
791 goto out;
792 if (!prog->aux->num_exentries)
793 goto out;
794
795 e = search_extable(prog->aux->extable, prog->aux->num_exentries, addr);
796 out:
797 rcu_read_unlock();
798 return e;
799 }
800
bpf_get_kallsym(unsigned int symnum,unsigned long * value,char * type,char * sym)801 int bpf_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
802 char *sym)
803 {
804 struct bpf_ksym *ksym;
805 unsigned int it = 0;
806 int ret = -ERANGE;
807
808 if (!bpf_jit_kallsyms_enabled())
809 return ret;
810
811 rcu_read_lock();
812 list_for_each_entry_rcu(ksym, &bpf_kallsyms, lnode) {
813 if (it++ != symnum)
814 continue;
815
816 strscpy(sym, ksym->name, KSYM_NAME_LEN);
817
818 *value = ksym->start;
819 *type = BPF_SYM_ELF_TYPE;
820
821 ret = 0;
822 break;
823 }
824 rcu_read_unlock();
825
826 return ret;
827 }
828
bpf_jit_add_poke_descriptor(struct bpf_prog * prog,struct bpf_jit_poke_descriptor * poke)829 int bpf_jit_add_poke_descriptor(struct bpf_prog *prog,
830 struct bpf_jit_poke_descriptor *poke)
831 {
832 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
833 static const u32 poke_tab_max = 1024;
834 u32 slot = prog->aux->size_poke_tab;
835 u32 size = slot + 1;
836
837 if (size > poke_tab_max)
838 return -ENOSPC;
839 if (poke->tailcall_target || poke->tailcall_target_stable ||
840 poke->tailcall_bypass || poke->adj_off || poke->bypass_addr)
841 return -EINVAL;
842
843 switch (poke->reason) {
844 case BPF_POKE_REASON_TAIL_CALL:
845 if (!poke->tail_call.map)
846 return -EINVAL;
847 break;
848 default:
849 return -EINVAL;
850 }
851
852 tab = krealloc_array(tab, size, sizeof(*poke), GFP_KERNEL);
853 if (!tab)
854 return -ENOMEM;
855
856 memcpy(&tab[slot], poke, sizeof(*poke));
857 prog->aux->size_poke_tab = size;
858 prog->aux->poke_tab = tab;
859
860 return slot;
861 }
862
863 /*
864 * BPF program pack allocator.
865 *
866 * Most BPF programs are pretty small. Allocating a hole page for each
867 * program is sometime a waste. Many small bpf program also adds pressure
868 * to instruction TLB. To solve this issue, we introduce a BPF program pack
869 * allocator. The prog_pack allocator uses HPAGE_PMD_SIZE page (2MB on x86)
870 * to host BPF programs.
871 */
872 #define BPF_PROG_CHUNK_SHIFT 6
873 #define BPF_PROG_CHUNK_SIZE (1 << BPF_PROG_CHUNK_SHIFT)
874 #define BPF_PROG_CHUNK_MASK (~(BPF_PROG_CHUNK_SIZE - 1))
875
876 struct bpf_prog_pack {
877 struct list_head list;
878 void *ptr;
879 bool arch_flush_needed;
880 unsigned long bitmap[];
881 };
882
bpf_jit_fill_hole_with_zero(void * area,unsigned int size)883 void bpf_jit_fill_hole_with_zero(void *area, unsigned int size)
884 {
885 memset(area, 0, size);
886 }
887
888 DEFINE_STATIC_CALL_NULL(bpf_arch_pred_flush, bpf_arch_pred_flush);
889
890 /*
891 * Enabled once bpf_arch_pred_flush points at a real flush routine. Lets the
892 * pack allocator test "is a predictor flush wired up at all" with a cheap
893 * static branch instead of repeatedly querying the static call target.
894 */
895 DEFINE_STATIC_KEY_FALSE(bpf_pred_flush_enabled);
896
897 #define BPF_PROG_SIZE_TO_NBITS(size) (round_up(size, BPF_PROG_CHUNK_SIZE) / BPF_PROG_CHUNK_SIZE)
898
899 static DEFINE_MUTEX(pack_mutex);
900 static LIST_HEAD(pack_list);
901
902 /* PMD_SIZE is not available in some special config, e.g. ARCH=arm with
903 * CONFIG_MMU=n. Use PAGE_SIZE in these cases.
904 */
905 #ifdef PMD_SIZE
906 /* PMD_SIZE is really big for some archs. It doesn't make sense to
907 * reserve too much memory in one allocation. Hardcode BPF_PROG_PACK_SIZE to
908 * 2MiB * num_possible_nodes(). On most architectures PMD_SIZE will be
909 * greater than or equal to 2MB.
910 */
911 #define BPF_PROG_PACK_SIZE (SZ_2M * num_possible_nodes())
912 #else
913 #define BPF_PROG_PACK_SIZE PAGE_SIZE
914 #endif
915
916 #define BPF_PROG_CHUNK_COUNT (BPF_PROG_PACK_SIZE / BPF_PROG_CHUNK_SIZE)
917
alloc_new_pack(bpf_jit_fill_hole_t bpf_fill_ill_insns)918 static struct bpf_prog_pack *alloc_new_pack(bpf_jit_fill_hole_t bpf_fill_ill_insns)
919 {
920 struct bpf_prog_pack *pack;
921 int err;
922
923 pack = kzalloc_flex(*pack, bitmap, BITS_TO_LONGS(BPF_PROG_CHUNK_COUNT));
924 if (!pack)
925 return NULL;
926 pack->ptr = bpf_jit_alloc_exec(BPF_PROG_PACK_SIZE);
927 if (!pack->ptr)
928 goto out;
929 bpf_fill_ill_insns(pack->ptr, BPF_PROG_PACK_SIZE);
930 bitmap_zero(pack->bitmap, BPF_PROG_PACK_SIZE / BPF_PROG_CHUNK_SIZE);
931
932 if (static_branch_unlikely(&bpf_pred_flush_enabled))
933 pack->arch_flush_needed = true;
934 set_vm_flush_reset_perms(pack->ptr);
935 err = set_memory_rox((unsigned long)pack->ptr,
936 BPF_PROG_PACK_SIZE / PAGE_SIZE);
937 if (err)
938 goto out;
939 list_add_tail(&pack->list, &pack_list);
940 return pack;
941
942 out:
943 bpf_jit_free_exec(pack->ptr);
944 kfree(pack);
945 return NULL;
946 }
947
bpf_prog_pack_alloc(u32 size,bpf_jit_fill_hole_t bpf_fill_ill_insns,bool was_classic)948 void *bpf_prog_pack_alloc(u32 size, bpf_jit_fill_hole_t bpf_fill_ill_insns, bool was_classic)
949 {
950 unsigned int nbits = BPF_PROG_SIZE_TO_NBITS(size);
951 struct bpf_prog_pack *pack, *fallback_pack = NULL;
952 unsigned long pos, fallback_pos = 0;
953 void *ptr = NULL;
954
955 mutex_lock(&pack_mutex);
956 if (size > BPF_PROG_PACK_SIZE) {
957 /*
958 * Allocations larger than a pack get their own pages, and
959 * predictors are not flushed for such allocation. This is only
960 * safe because cBPF programs (the unprivileged attack surface)
961 * are bounded well below a pack size.
962 */
963 if (was_classic && static_branch_unlikely(&bpf_pred_flush_enabled))
964 pr_warn_once("BPF: Predictors not flushed for allocations greater than BPF_PROG_PACK_SIZE\n");
965 size = round_up(size, PAGE_SIZE);
966 ptr = bpf_jit_alloc_exec(size);
967 if (ptr) {
968 int err;
969
970 bpf_fill_ill_insns(ptr, size);
971 set_vm_flush_reset_perms(ptr);
972 err = set_memory_rox((unsigned long)ptr,
973 size / PAGE_SIZE);
974 if (err) {
975 bpf_jit_free_exec(ptr);
976 ptr = NULL;
977 }
978 }
979 goto out;
980 }
981 list_for_each_entry(pack, &pack_list, list) {
982 pos = bitmap_find_next_zero_area(pack->bitmap, BPF_PROG_CHUNK_COUNT, 0,
983 nbits, 0);
984 if (pos >= BPF_PROG_CHUNK_COUNT)
985 continue;
986 /* Flush not enabled, use any pack */
987 if (!static_branch_unlikely(&bpf_pred_flush_enabled))
988 goto found_free_area;
989 /*
990 * cBPF reuse of a dirty pack triggers a flush, so prefer a
991 * clean pack for cBPF. eBPF never flushes, so steer it to a
992 * dirty pack and keep clean packs free for cBPF.
993 */
994 if (was_classic ^ pack->arch_flush_needed)
995 goto found_free_area;
996 if (!fallback_pack) {
997 fallback_pack = pack;
998 fallback_pos = pos;
999 }
1000 }
1001
1002 /* No preferred pack found */
1003 if (fallback_pack) {
1004 pack = fallback_pack;
1005 pos = fallback_pos;
1006 goto found_free_area;
1007 }
1008
1009 pack = alloc_new_pack(bpf_fill_ill_insns);
1010 if (!pack)
1011 goto out;
1012
1013 pos = 0;
1014
1015 found_free_area:
1016 /* Flush only for cBPF as it may contain a crafted gadget */
1017 if (static_branch_unlikely(&bpf_pred_flush_enabled) &&
1018 pack->arch_flush_needed &&
1019 was_classic) {
1020 struct bpf_prog_pack *p;
1021
1022 static_call_cond(bpf_arch_pred_flush)();
1023 list_for_each_entry(p, &pack_list, list)
1024 p->arch_flush_needed = false;
1025 }
1026 bitmap_set(pack->bitmap, pos, nbits);
1027 ptr = (void *)(pack->ptr) + (pos << BPF_PROG_CHUNK_SHIFT);
1028
1029 out:
1030 mutex_unlock(&pack_mutex);
1031 return ptr;
1032 }
1033
bpf_prog_pack_free(void * ptr,u32 size)1034 void bpf_prog_pack_free(void *ptr, u32 size)
1035 {
1036 struct bpf_prog_pack *pack = NULL, *tmp;
1037 unsigned int nbits;
1038 unsigned long pos;
1039
1040 mutex_lock(&pack_mutex);
1041 if (size > BPF_PROG_PACK_SIZE) {
1042 bpf_jit_free_exec(ptr);
1043 goto out;
1044 }
1045
1046 list_for_each_entry(tmp, &pack_list, list) {
1047 if (ptr >= tmp->ptr && (tmp->ptr + BPF_PROG_PACK_SIZE) > ptr) {
1048 pack = tmp;
1049 break;
1050 }
1051 }
1052
1053 if (WARN_ONCE(!pack, "bpf_prog_pack bug\n"))
1054 goto out;
1055
1056 nbits = BPF_PROG_SIZE_TO_NBITS(size);
1057 pos = ((unsigned long)ptr - (unsigned long)pack->ptr) >> BPF_PROG_CHUNK_SHIFT;
1058
1059 WARN_ONCE(bpf_arch_text_invalidate(ptr, size),
1060 "bpf_prog_pack bug: missing bpf_arch_text_invalidate?\n");
1061
1062 bitmap_clear(pack->bitmap, pos, nbits);
1063
1064 if (static_branch_unlikely(&bpf_pred_flush_enabled))
1065 pack->arch_flush_needed = true;
1066 if (bitmap_find_next_zero_area(pack->bitmap, BPF_PROG_CHUNK_COUNT, 0,
1067 BPF_PROG_CHUNK_COUNT, 0) == 0) {
1068 list_del(&pack->list);
1069 bpf_jit_free_exec(pack->ptr);
1070 kfree(pack);
1071 }
1072 out:
1073 mutex_unlock(&pack_mutex);
1074 }
1075
1076 static atomic_long_t bpf_jit_current;
1077
1078 /* Can be overridden by an arch's JIT compiler if it has a custom,
1079 * dedicated BPF backend memory area, or if neither of the two
1080 * below apply.
1081 */
bpf_jit_alloc_exec_limit(void)1082 u64 __weak bpf_jit_alloc_exec_limit(void)
1083 {
1084 #if defined(MODULES_VADDR)
1085 return MODULES_END - MODULES_VADDR;
1086 #else
1087 return VMALLOC_END - VMALLOC_START;
1088 #endif
1089 }
1090
bpf_jit_charge_init(void)1091 static int __init bpf_jit_charge_init(void)
1092 {
1093 /* Only used as heuristic here to derive limit. */
1094 bpf_jit_limit_max = bpf_jit_alloc_exec_limit();
1095 bpf_jit_limit = min_t(u64, round_up(bpf_jit_limit_max >> 1,
1096 PAGE_SIZE), LONG_MAX);
1097 return 0;
1098 }
1099 pure_initcall(bpf_jit_charge_init);
1100
bpf_jit_charge_modmem(u32 size)1101 int bpf_jit_charge_modmem(u32 size)
1102 {
1103 if (atomic_long_add_return(size, &bpf_jit_current) > READ_ONCE(bpf_jit_limit)) {
1104 if (!bpf_capable()) {
1105 atomic_long_sub(size, &bpf_jit_current);
1106 return -EPERM;
1107 }
1108 }
1109
1110 return 0;
1111 }
1112
bpf_jit_uncharge_modmem(u32 size)1113 void bpf_jit_uncharge_modmem(u32 size)
1114 {
1115 atomic_long_sub(size, &bpf_jit_current);
1116 }
1117
bpf_jit_alloc_exec(unsigned long size)1118 void *__weak bpf_jit_alloc_exec(unsigned long size)
1119 {
1120 return execmem_alloc(EXECMEM_BPF, size);
1121 }
1122
bpf_jit_free_exec(void * addr)1123 void __weak bpf_jit_free_exec(void *addr)
1124 {
1125 execmem_free(addr);
1126 }
1127
1128 struct bpf_binary_header *
bpf_jit_binary_alloc(unsigned int proglen,u8 ** image_ptr,unsigned int alignment,bpf_jit_fill_hole_t bpf_fill_ill_insns)1129 bpf_jit_binary_alloc(unsigned int proglen, u8 **image_ptr,
1130 unsigned int alignment,
1131 bpf_jit_fill_hole_t bpf_fill_ill_insns)
1132 {
1133 struct bpf_binary_header *hdr;
1134 u32 size, hole, start;
1135
1136 WARN_ON_ONCE(!is_power_of_2(alignment) ||
1137 alignment > BPF_IMAGE_ALIGNMENT);
1138
1139 /* Most of BPF filters are really small, but if some of them
1140 * fill a page, allow at least 128 extra bytes to insert a
1141 * random section of illegal instructions.
1142 */
1143 size = round_up(proglen + sizeof(*hdr) + 128, PAGE_SIZE);
1144
1145 if (bpf_jit_charge_modmem(size))
1146 return NULL;
1147 hdr = bpf_jit_alloc_exec(size);
1148 if (!hdr) {
1149 bpf_jit_uncharge_modmem(size);
1150 return NULL;
1151 }
1152
1153 /* Fill space with illegal/arch-dep instructions. */
1154 bpf_fill_ill_insns(hdr, size);
1155
1156 hdr->size = size;
1157 hole = min_t(unsigned int, size - (proglen + sizeof(*hdr)),
1158 PAGE_SIZE - sizeof(*hdr));
1159 start = get_random_u32_below(hole) & ~(alignment - 1);
1160
1161 /* Leave a random number of instructions before BPF code. */
1162 *image_ptr = &hdr->image[start];
1163
1164 return hdr;
1165 }
1166
bpf_jit_binary_free(struct bpf_binary_header * hdr)1167 void bpf_jit_binary_free(struct bpf_binary_header *hdr)
1168 {
1169 u32 size = hdr->size;
1170
1171 bpf_jit_free_exec(hdr);
1172 bpf_jit_uncharge_modmem(size);
1173 }
1174
1175 /* Allocate jit binary from bpf_prog_pack allocator.
1176 * Since the allocated memory is RO+X, the JIT engine cannot write directly
1177 * to the memory. To solve this problem, a RW buffer is also allocated at
1178 * as the same time. The JIT engine should calculate offsets based on the
1179 * RO memory address, but write JITed program to the RW buffer. Once the
1180 * JIT engine finishes, it calls bpf_jit_binary_pack_finalize, which copies
1181 * the JITed program to the RO memory.
1182 */
1183 struct bpf_binary_header *
bpf_jit_binary_pack_alloc(unsigned int proglen,u8 ** image_ptr,unsigned int alignment,struct bpf_binary_header ** rw_header,u8 ** rw_image,bpf_jit_fill_hole_t bpf_fill_ill_insns,bool was_classic)1184 bpf_jit_binary_pack_alloc(unsigned int proglen, u8 **image_ptr,
1185 unsigned int alignment,
1186 struct bpf_binary_header **rw_header,
1187 u8 **rw_image,
1188 bpf_jit_fill_hole_t bpf_fill_ill_insns,
1189 bool was_classic)
1190 {
1191 struct bpf_binary_header *ro_header;
1192 u32 size, hole, start;
1193
1194 WARN_ON_ONCE(!is_power_of_2(alignment) ||
1195 alignment > BPF_IMAGE_ALIGNMENT);
1196
1197 /* add 16 bytes for a random section of illegal instructions */
1198 size = round_up(proglen + sizeof(*ro_header) + 16, BPF_PROG_CHUNK_SIZE);
1199
1200 if (bpf_jit_charge_modmem(size))
1201 return NULL;
1202 ro_header = bpf_prog_pack_alloc(size, bpf_fill_ill_insns, was_classic);
1203 if (!ro_header) {
1204 bpf_jit_uncharge_modmem(size);
1205 return NULL;
1206 }
1207
1208 *rw_header = kvmalloc(size, GFP_KERNEL);
1209 if (!*rw_header) {
1210 bpf_prog_pack_free(ro_header, size);
1211 bpf_jit_uncharge_modmem(size);
1212 return NULL;
1213 }
1214
1215 /* Fill space with illegal/arch-dep instructions. */
1216 bpf_fill_ill_insns(*rw_header, size);
1217 (*rw_header)->size = size;
1218
1219 hole = min_t(unsigned int, size - (proglen + sizeof(*ro_header)),
1220 BPF_PROG_CHUNK_SIZE - sizeof(*ro_header));
1221 start = get_random_u32_below(hole) & ~(alignment - 1);
1222
1223 *image_ptr = &ro_header->image[start];
1224 *rw_image = &(*rw_header)->image[start];
1225
1226 return ro_header;
1227 }
1228
1229 /* Copy JITed text from rw_header to its final location, the ro_header. */
bpf_jit_binary_pack_finalize(struct bpf_binary_header * ro_header,struct bpf_binary_header * rw_header)1230 int bpf_jit_binary_pack_finalize(struct bpf_binary_header *ro_header,
1231 struct bpf_binary_header *rw_header)
1232 {
1233 void *ptr;
1234
1235 ptr = bpf_arch_text_copy(ro_header, rw_header, rw_header->size);
1236
1237 kvfree(rw_header);
1238
1239 if (IS_ERR(ptr)) {
1240 bpf_prog_pack_free(ro_header, ro_header->size);
1241 return PTR_ERR(ptr);
1242 }
1243 return 0;
1244 }
1245
1246 /* bpf_jit_binary_pack_free is called in two different scenarios:
1247 * 1) when the program is freed after;
1248 * 2) when the JIT engine fails (before bpf_jit_binary_pack_finalize).
1249 * For case 2), we need to free both the RO memory and the RW buffer.
1250 *
1251 * bpf_jit_binary_pack_free requires proper ro_header->size. However,
1252 * bpf_jit_binary_pack_alloc does not set it. Therefore, ro_header->size
1253 * must be set with either bpf_jit_binary_pack_finalize (normal path) or
1254 * bpf_arch_text_copy (when jit fails).
1255 */
bpf_jit_binary_pack_free(struct bpf_binary_header * ro_header,struct bpf_binary_header * rw_header)1256 void bpf_jit_binary_pack_free(struct bpf_binary_header *ro_header,
1257 struct bpf_binary_header *rw_header)
1258 {
1259 u32 size = ro_header->size;
1260
1261 bpf_prog_pack_free(ro_header, size);
1262 kvfree(rw_header);
1263 bpf_jit_uncharge_modmem(size);
1264 }
1265
1266 struct bpf_binary_header *
bpf_jit_binary_pack_hdr(const struct bpf_prog * fp)1267 bpf_jit_binary_pack_hdr(const struct bpf_prog *fp)
1268 {
1269 unsigned long real_start = (unsigned long)fp->bpf_func;
1270 unsigned long addr;
1271
1272 addr = real_start & BPF_PROG_CHUNK_MASK;
1273 return (void *)addr;
1274 }
1275
1276 static inline struct bpf_binary_header *
bpf_jit_binary_hdr(const struct bpf_prog * fp)1277 bpf_jit_binary_hdr(const struct bpf_prog *fp)
1278 {
1279 unsigned long real_start = (unsigned long)fp->bpf_func;
1280 unsigned long addr;
1281
1282 addr = real_start & PAGE_MASK;
1283 return (void *)addr;
1284 }
1285
1286 /* This symbol is only overridden by archs that have different
1287 * requirements than the usual eBPF JITs, f.e. when they only
1288 * implement cBPF JIT, do not set images read-only, etc.
1289 */
bpf_jit_free(struct bpf_prog * fp)1290 void __weak bpf_jit_free(struct bpf_prog *fp)
1291 {
1292 if (fp->jited) {
1293 struct bpf_binary_header *hdr = bpf_jit_binary_hdr(fp);
1294
1295 bpf_jit_binary_free(hdr);
1296 WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(fp));
1297 }
1298
1299 bpf_prog_unlock_free(fp);
1300 }
1301
bpf_jit_get_func_addr(const struct bpf_prog * prog,const struct bpf_insn * insn,bool extra_pass,u64 * func_addr,bool * func_addr_fixed)1302 int bpf_jit_get_func_addr(const struct bpf_prog *prog,
1303 const struct bpf_insn *insn, bool extra_pass,
1304 u64 *func_addr, bool *func_addr_fixed)
1305 {
1306 s16 off = insn->off;
1307 s32 imm = insn->imm;
1308 u8 *addr;
1309 int err;
1310
1311 *func_addr_fixed = insn->src_reg != BPF_PSEUDO_CALL;
1312 if (!*func_addr_fixed) {
1313 /* Place-holder address till the last pass has collected
1314 * all addresses for JITed subprograms in which case we
1315 * can pick them up from prog->aux.
1316 */
1317 if (!extra_pass)
1318 addr = NULL;
1319 else if (prog->aux->func &&
1320 off >= 0 && off < prog->aux->real_func_cnt)
1321 addr = (u8 *)prog->aux->func[off]->bpf_func;
1322 else
1323 return -EINVAL;
1324 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL &&
1325 bpf_jit_supports_far_kfunc_call()) {
1326 err = bpf_get_kfunc_addr(prog, insn->imm, insn->off, &addr);
1327 if (err)
1328 return err;
1329 } else {
1330 /* Address of a BPF helper call. Since part of the core
1331 * kernel, it's always at a fixed location. __bpf_call_base
1332 * and the helper with imm relative to it are both in core
1333 * kernel.
1334 */
1335 addr = (u8 *)__bpf_call_base + imm;
1336 }
1337
1338 *func_addr = (unsigned long)addr;
1339 return 0;
1340 }
1341
bpf_jit_get_prog_name(struct bpf_prog * prog)1342 const char *bpf_jit_get_prog_name(struct bpf_prog *prog)
1343 {
1344 if (prog->aux->ksym.prog)
1345 return prog->aux->ksym.name;
1346 return prog->aux->name;
1347 }
1348
bpf_jit_blind_insn(const struct bpf_insn * from,const struct bpf_insn * aux,struct bpf_insn * to_buff,bool emit_zext)1349 static int bpf_jit_blind_insn(const struct bpf_insn *from,
1350 const struct bpf_insn *aux,
1351 struct bpf_insn *to_buff,
1352 bool emit_zext)
1353 {
1354 struct bpf_insn *to = to_buff;
1355 u32 imm_rnd = get_random_u32();
1356 s16 off;
1357
1358 BUILD_BUG_ON(BPF_REG_PARAMS + 2 != MAX_BPF_JIT_REG);
1359 BUILD_BUG_ON(BPF_REG_AX + 1 != MAX_BPF_JIT_REG);
1360
1361 /* Constraints on AX register:
1362 *
1363 * AX register is inaccessible from user space. It is mapped in
1364 * all JITs, and used here for constant blinding rewrites. It is
1365 * typically "stateless" meaning its contents are only valid within
1366 * the executed instruction, but not across several instructions.
1367 * There are a few exceptions however which are further detailed
1368 * below.
1369 *
1370 * Constant blinding is only used by JITs, not in the interpreter.
1371 * The interpreter uses AX in some occasions as a local temporary
1372 * register e.g. in DIV or MOD instructions.
1373 *
1374 * In restricted circumstances, the verifier can also use the AX
1375 * register for rewrites as long as they do not interfere with
1376 * the above cases!
1377 */
1378 if (from->dst_reg == BPF_REG_AX || from->src_reg == BPF_REG_AX)
1379 goto out;
1380
1381 if (from->imm == 0 &&
1382 (from->code == (BPF_ALU | BPF_MOV | BPF_K) ||
1383 from->code == (BPF_ALU64 | BPF_MOV | BPF_K))) {
1384 *to++ = BPF_ALU64_REG(BPF_XOR, from->dst_reg, from->dst_reg);
1385 goto out;
1386 }
1387
1388 switch (from->code) {
1389 case BPF_ALU | BPF_ADD | BPF_K:
1390 case BPF_ALU | BPF_SUB | BPF_K:
1391 case BPF_ALU | BPF_AND | BPF_K:
1392 case BPF_ALU | BPF_OR | BPF_K:
1393 case BPF_ALU | BPF_XOR | BPF_K:
1394 case BPF_ALU | BPF_MUL | BPF_K:
1395 case BPF_ALU | BPF_MOV | BPF_K:
1396 case BPF_ALU | BPF_DIV | BPF_K:
1397 case BPF_ALU | BPF_MOD | BPF_K:
1398 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1399 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1400 *to++ = BPF_ALU32_REG_OFF(from->code, from->dst_reg, BPF_REG_AX, from->off);
1401 break;
1402
1403 case BPF_ALU64 | BPF_ADD | BPF_K:
1404 case BPF_ALU64 | BPF_SUB | BPF_K:
1405 case BPF_ALU64 | BPF_AND | BPF_K:
1406 case BPF_ALU64 | BPF_OR | BPF_K:
1407 case BPF_ALU64 | BPF_XOR | BPF_K:
1408 case BPF_ALU64 | BPF_MUL | BPF_K:
1409 case BPF_ALU64 | BPF_MOV | BPF_K:
1410 case BPF_ALU64 | BPF_DIV | BPF_K:
1411 case BPF_ALU64 | BPF_MOD | BPF_K:
1412 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1413 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1414 *to++ = BPF_ALU64_REG_OFF(from->code, from->dst_reg, BPF_REG_AX, from->off);
1415 break;
1416
1417 case BPF_JMP | BPF_JEQ | BPF_K:
1418 case BPF_JMP | BPF_JNE | BPF_K:
1419 case BPF_JMP | BPF_JGT | BPF_K:
1420 case BPF_JMP | BPF_JLT | BPF_K:
1421 case BPF_JMP | BPF_JGE | BPF_K:
1422 case BPF_JMP | BPF_JLE | BPF_K:
1423 case BPF_JMP | BPF_JSGT | BPF_K:
1424 case BPF_JMP | BPF_JSLT | BPF_K:
1425 case BPF_JMP | BPF_JSGE | BPF_K:
1426 case BPF_JMP | BPF_JSLE | BPF_K:
1427 case BPF_JMP | BPF_JSET | BPF_K:
1428 /* Accommodate for extra offset in case of a backjump. */
1429 off = from->off;
1430 if (off < 0)
1431 off -= 2;
1432 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1433 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1434 *to++ = BPF_JMP_REG(from->code, from->dst_reg, BPF_REG_AX, off);
1435 break;
1436
1437 case BPF_JMP32 | BPF_JEQ | BPF_K:
1438 case BPF_JMP32 | BPF_JNE | BPF_K:
1439 case BPF_JMP32 | BPF_JGT | BPF_K:
1440 case BPF_JMP32 | BPF_JLT | BPF_K:
1441 case BPF_JMP32 | BPF_JGE | BPF_K:
1442 case BPF_JMP32 | BPF_JLE | BPF_K:
1443 case BPF_JMP32 | BPF_JSGT | BPF_K:
1444 case BPF_JMP32 | BPF_JSLT | BPF_K:
1445 case BPF_JMP32 | BPF_JSGE | BPF_K:
1446 case BPF_JMP32 | BPF_JSLE | BPF_K:
1447 case BPF_JMP32 | BPF_JSET | BPF_K:
1448 /* Accommodate for extra offset in case of a backjump. */
1449 off = from->off;
1450 if (off < 0)
1451 off -= 2;
1452 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1453 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1454 *to++ = BPF_JMP32_REG(from->code, from->dst_reg, BPF_REG_AX,
1455 off);
1456 break;
1457
1458 case BPF_LD | BPF_IMM | BPF_DW:
1459 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[1].imm);
1460 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1461 *to++ = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
1462 *to++ = BPF_ALU64_REG(BPF_MOV, aux[0].dst_reg, BPF_REG_AX);
1463 break;
1464 case 0: /* Part 2 of BPF_LD | BPF_IMM | BPF_DW. */
1465 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[0].imm);
1466 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1467 if (emit_zext)
1468 *to++ = BPF_ZEXT_REG(BPF_REG_AX);
1469 *to++ = BPF_ALU64_REG(BPF_OR, aux[0].dst_reg, BPF_REG_AX);
1470 break;
1471
1472 case BPF_ST | BPF_MEM | BPF_DW:
1473 case BPF_ST | BPF_MEM | BPF_W:
1474 case BPF_ST | BPF_MEM | BPF_H:
1475 case BPF_ST | BPF_MEM | BPF_B:
1476 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1477 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1478 *to++ = BPF_STX_MEM(from->code, from->dst_reg, BPF_REG_AX, from->off);
1479 break;
1480
1481 case BPF_ST | BPF_PROBE_MEM32 | BPF_DW:
1482 case BPF_ST | BPF_PROBE_MEM32 | BPF_W:
1483 case BPF_ST | BPF_PROBE_MEM32 | BPF_H:
1484 case BPF_ST | BPF_PROBE_MEM32 | BPF_B:
1485 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^
1486 from->imm);
1487 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1488 /*
1489 * Cannot use BPF_STX_MEM() macro here as it
1490 * hardcodes BPF_MEM mode, losing PROBE_MEM32
1491 * and breaking arena addressing in the JIT.
1492 */
1493 *to++ = (struct bpf_insn) {
1494 .code = BPF_STX | BPF_PROBE_MEM32 |
1495 BPF_SIZE(from->code),
1496 .dst_reg = from->dst_reg,
1497 .src_reg = BPF_REG_AX,
1498 .off = from->off,
1499 };
1500 break;
1501 }
1502 out:
1503 return to - to_buff;
1504 }
1505
bpf_prog_clone_create(struct bpf_prog * fp_other,gfp_t gfp_extra_flags)1506 static struct bpf_prog *bpf_prog_clone_create(struct bpf_prog *fp_other,
1507 gfp_t gfp_extra_flags)
1508 {
1509 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
1510 struct bpf_prog *fp;
1511
1512 fp = __vmalloc(fp_other->pages * PAGE_SIZE, gfp_flags);
1513 if (fp != NULL) {
1514 /* aux->prog still points to the fp_other one, so
1515 * when promoting the clone to the real program,
1516 * this still needs to be adapted.
1517 */
1518 memcpy(fp, fp_other, fp_other->pages * PAGE_SIZE);
1519 }
1520
1521 return fp;
1522 }
1523
bpf_prog_clone_free(struct bpf_prog * fp)1524 static void bpf_prog_clone_free(struct bpf_prog *fp)
1525 {
1526 /* aux was stolen by the other clone, so we cannot free
1527 * it from this path! It will be freed eventually by the
1528 * other program on release.
1529 *
1530 * At this point, we don't need a deferred release since
1531 * clone is guaranteed to not be locked.
1532 */
1533 fp->aux = NULL;
1534 fp->stats = NULL;
1535 fp->active = NULL;
1536 __bpf_prog_free(fp);
1537 }
1538
bpf_jit_prog_release_other(struct bpf_prog * fp,struct bpf_prog * fp_other)1539 void bpf_jit_prog_release_other(struct bpf_prog *fp, struct bpf_prog *fp_other)
1540 {
1541 /* We have to repoint aux->prog to self, as we don't
1542 * know whether fp here is the clone or the original.
1543 */
1544 fp->aux->prog = fp;
1545 if (fp->aux->offload)
1546 fp->aux->offload->prog = fp;
1547 bpf_prog_clone_free(fp_other);
1548 }
1549
1550 /*
1551 * Now this function is used only to blind the main prog and must be invoked only when
1552 * bpf_prog_need_blind() returns true.
1553 */
bpf_jit_blind_constants(struct bpf_verifier_env * env,struct bpf_prog * prog)1554 struct bpf_prog *bpf_jit_blind_constants(struct bpf_verifier_env *env, struct bpf_prog *prog)
1555 {
1556 struct bpf_insn insn_buff[16], aux[2];
1557 struct bpf_prog *clone, *tmp;
1558 int insn_delta, insn_cnt;
1559 struct bpf_insn *insn;
1560 int i, rewritten;
1561
1562 if (WARN_ON_ONCE(env && env->prog != prog))
1563 return ERR_PTR(-EINVAL);
1564
1565 clone = bpf_prog_clone_create(prog, GFP_USER);
1566 if (!clone)
1567 return ERR_PTR(-ENOMEM);
1568
1569 /* make sure bpf_patch_insn_data() patches the correct prog */
1570 if (env)
1571 env->prog = clone;
1572
1573 insn_cnt = clone->len;
1574 insn = clone->insnsi;
1575
1576 for (i = 0; i < insn_cnt; i++, insn++) {
1577 if (bpf_pseudo_func(insn)) {
1578 /* ld_imm64 with an address of bpf subprog is not
1579 * a user controlled constant. Don't randomize it,
1580 * since it will conflict with jit_subprogs() logic.
1581 */
1582 insn++;
1583 i++;
1584 continue;
1585 }
1586
1587 /* We temporarily need to hold the original ld64 insn
1588 * so that we can still access the first part in the
1589 * second blinding run.
1590 */
1591 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW) &&
1592 insn[1].code == 0)
1593 memcpy(aux, insn, sizeof(aux));
1594
1595 rewritten = bpf_jit_blind_insn(insn, aux, insn_buff,
1596 clone->aux->verifier_zext);
1597 if (!rewritten)
1598 continue;
1599
1600 if (env)
1601 tmp = bpf_patch_insn_data(env, i, insn_buff, rewritten);
1602 else
1603 tmp = bpf_patch_insn_single(clone, i, insn_buff, rewritten);
1604
1605 if (IS_ERR_OR_NULL(tmp)) {
1606 if (env)
1607 /* restore the original prog */
1608 env->prog = prog;
1609 /* Patching may have repointed aux->prog during
1610 * realloc from the original one, so we need to
1611 * fix it up here on error.
1612 */
1613 bpf_jit_prog_release_other(prog, clone);
1614 return IS_ERR(tmp) ? tmp : ERR_PTR(-ENOMEM);
1615 }
1616
1617 clone = tmp;
1618 insn_delta = rewritten - 1;
1619
1620 if (env)
1621 env->prog = clone;
1622
1623 /* Walk new program and skip insns we just inserted. */
1624 insn = clone->insnsi + i + insn_delta;
1625 insn_cnt += insn_delta;
1626 i += insn_delta;
1627 }
1628
1629 clone->blinded = 1;
1630 return clone;
1631 }
1632
bpf_insn_is_indirect_target(const struct bpf_verifier_env * env,const struct bpf_prog * prog,int insn_idx)1633 bool bpf_insn_is_indirect_target(const struct bpf_verifier_env *env, const struct bpf_prog *prog,
1634 int insn_idx)
1635 {
1636 if (!env)
1637 return false;
1638 insn_idx += prog->aux->subprog_start;
1639 return env->insn_aux_data[insn_idx].indirect_target;
1640 }
1641
bpf_out_stack_arg_cnt(const struct bpf_verifier_env * env,const struct bpf_prog * prog)1642 u16 bpf_out_stack_arg_cnt(const struct bpf_verifier_env *env, const struct bpf_prog *prog)
1643 {
1644 const struct bpf_subprog_info *sub;
1645
1646 if (!env)
1647 return 0;
1648 sub = &env->subprog_info[prog->aux->func_idx];
1649 return sub->stack_arg_cnt - bpf_in_stack_arg_cnt(sub);
1650 }
1651 #endif /* CONFIG_BPF_JIT */
1652
1653 /* Base function for offset calculation. Needs to go into .text section,
1654 * therefore keeping it non-static as well; will also be used by JITs
1655 * anyway later on, so do not let the compiler omit it. This also needs
1656 * to go into kallsyms for correlation from e.g. bpftool, so naming
1657 * must not change.
1658 */
__bpf_call_base(u64 r1,u64 r2,u64 r3,u64 r4,u64 r5)1659 noinline u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
1660 {
1661 return 0;
1662 }
1663 EXPORT_SYMBOL_GPL(__bpf_call_base);
1664
1665 /* All UAPI available opcodes. */
1666 #define BPF_INSN_MAP(INSN_2, INSN_3) \
1667 /* 32 bit ALU operations. */ \
1668 /* Register based. */ \
1669 INSN_3(ALU, ADD, X), \
1670 INSN_3(ALU, SUB, X), \
1671 INSN_3(ALU, AND, X), \
1672 INSN_3(ALU, OR, X), \
1673 INSN_3(ALU, LSH, X), \
1674 INSN_3(ALU, RSH, X), \
1675 INSN_3(ALU, XOR, X), \
1676 INSN_3(ALU, MUL, X), \
1677 INSN_3(ALU, MOV, X), \
1678 INSN_3(ALU, ARSH, X), \
1679 INSN_3(ALU, DIV, X), \
1680 INSN_3(ALU, MOD, X), \
1681 INSN_2(ALU, NEG), \
1682 INSN_3(ALU, END, TO_BE), \
1683 INSN_3(ALU, END, TO_LE), \
1684 /* Immediate based. */ \
1685 INSN_3(ALU, ADD, K), \
1686 INSN_3(ALU, SUB, K), \
1687 INSN_3(ALU, AND, K), \
1688 INSN_3(ALU, OR, K), \
1689 INSN_3(ALU, LSH, K), \
1690 INSN_3(ALU, RSH, K), \
1691 INSN_3(ALU, XOR, K), \
1692 INSN_3(ALU, MUL, K), \
1693 INSN_3(ALU, MOV, K), \
1694 INSN_3(ALU, ARSH, K), \
1695 INSN_3(ALU, DIV, K), \
1696 INSN_3(ALU, MOD, K), \
1697 /* 64 bit ALU operations. */ \
1698 /* Register based. */ \
1699 INSN_3(ALU64, ADD, X), \
1700 INSN_3(ALU64, SUB, X), \
1701 INSN_3(ALU64, AND, X), \
1702 INSN_3(ALU64, OR, X), \
1703 INSN_3(ALU64, LSH, X), \
1704 INSN_3(ALU64, RSH, X), \
1705 INSN_3(ALU64, XOR, X), \
1706 INSN_3(ALU64, MUL, X), \
1707 INSN_3(ALU64, MOV, X), \
1708 INSN_3(ALU64, ARSH, X), \
1709 INSN_3(ALU64, DIV, X), \
1710 INSN_3(ALU64, MOD, X), \
1711 INSN_2(ALU64, NEG), \
1712 INSN_3(ALU64, END, TO_LE), \
1713 /* Immediate based. */ \
1714 INSN_3(ALU64, ADD, K), \
1715 INSN_3(ALU64, SUB, K), \
1716 INSN_3(ALU64, AND, K), \
1717 INSN_3(ALU64, OR, K), \
1718 INSN_3(ALU64, LSH, K), \
1719 INSN_3(ALU64, RSH, K), \
1720 INSN_3(ALU64, XOR, K), \
1721 INSN_3(ALU64, MUL, K), \
1722 INSN_3(ALU64, MOV, K), \
1723 INSN_3(ALU64, ARSH, K), \
1724 INSN_3(ALU64, DIV, K), \
1725 INSN_3(ALU64, MOD, K), \
1726 /* Call instruction. */ \
1727 INSN_2(JMP, CALL), \
1728 /* Exit instruction. */ \
1729 INSN_2(JMP, EXIT), \
1730 /* 32-bit Jump instructions. */ \
1731 /* Register based. */ \
1732 INSN_3(JMP32, JEQ, X), \
1733 INSN_3(JMP32, JNE, X), \
1734 INSN_3(JMP32, JGT, X), \
1735 INSN_3(JMP32, JLT, X), \
1736 INSN_3(JMP32, JGE, X), \
1737 INSN_3(JMP32, JLE, X), \
1738 INSN_3(JMP32, JSGT, X), \
1739 INSN_3(JMP32, JSLT, X), \
1740 INSN_3(JMP32, JSGE, X), \
1741 INSN_3(JMP32, JSLE, X), \
1742 INSN_3(JMP32, JSET, X), \
1743 /* Immediate based. */ \
1744 INSN_3(JMP32, JEQ, K), \
1745 INSN_3(JMP32, JNE, K), \
1746 INSN_3(JMP32, JGT, K), \
1747 INSN_3(JMP32, JLT, K), \
1748 INSN_3(JMP32, JGE, K), \
1749 INSN_3(JMP32, JLE, K), \
1750 INSN_3(JMP32, JSGT, K), \
1751 INSN_3(JMP32, JSLT, K), \
1752 INSN_3(JMP32, JSGE, K), \
1753 INSN_3(JMP32, JSLE, K), \
1754 INSN_3(JMP32, JSET, K), \
1755 /* Jump instructions. */ \
1756 /* Register based. */ \
1757 INSN_3(JMP, JEQ, X), \
1758 INSN_3(JMP, JNE, X), \
1759 INSN_3(JMP, JGT, X), \
1760 INSN_3(JMP, JLT, X), \
1761 INSN_3(JMP, JGE, X), \
1762 INSN_3(JMP, JLE, X), \
1763 INSN_3(JMP, JSGT, X), \
1764 INSN_3(JMP, JSLT, X), \
1765 INSN_3(JMP, JSGE, X), \
1766 INSN_3(JMP, JSLE, X), \
1767 INSN_3(JMP, JSET, X), \
1768 /* Immediate based. */ \
1769 INSN_3(JMP, JEQ, K), \
1770 INSN_3(JMP, JNE, K), \
1771 INSN_3(JMP, JGT, K), \
1772 INSN_3(JMP, JLT, K), \
1773 INSN_3(JMP, JGE, K), \
1774 INSN_3(JMP, JLE, K), \
1775 INSN_3(JMP, JSGT, K), \
1776 INSN_3(JMP, JSLT, K), \
1777 INSN_3(JMP, JSGE, K), \
1778 INSN_3(JMP, JSLE, K), \
1779 INSN_3(JMP, JSET, K), \
1780 INSN_2(JMP, JA), \
1781 INSN_2(JMP32, JA), \
1782 /* Atomic operations. */ \
1783 INSN_3(STX, ATOMIC, B), \
1784 INSN_3(STX, ATOMIC, H), \
1785 INSN_3(STX, ATOMIC, W), \
1786 INSN_3(STX, ATOMIC, DW), \
1787 /* Store instructions. */ \
1788 /* Register based. */ \
1789 INSN_3(STX, MEM, B), \
1790 INSN_3(STX, MEM, H), \
1791 INSN_3(STX, MEM, W), \
1792 INSN_3(STX, MEM, DW), \
1793 /* Immediate based. */ \
1794 INSN_3(ST, MEM, B), \
1795 INSN_3(ST, MEM, H), \
1796 INSN_3(ST, MEM, W), \
1797 INSN_3(ST, MEM, DW), \
1798 /* Load instructions. */ \
1799 /* Register based. */ \
1800 INSN_3(LDX, MEM, B), \
1801 INSN_3(LDX, MEM, H), \
1802 INSN_3(LDX, MEM, W), \
1803 INSN_3(LDX, MEM, DW), \
1804 INSN_3(LDX, MEMSX, B), \
1805 INSN_3(LDX, MEMSX, H), \
1806 INSN_3(LDX, MEMSX, W), \
1807 /* Immediate based. */ \
1808 INSN_3(LD, IMM, DW)
1809
bpf_opcode_in_insntable(u8 code)1810 bool bpf_opcode_in_insntable(u8 code)
1811 {
1812 #define BPF_INSN_2_TBL(x, y) [BPF_##x | BPF_##y] = true
1813 #define BPF_INSN_3_TBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = true
1814 static const bool public_insntable[256] = {
1815 [0 ... 255] = false,
1816 /* Now overwrite non-defaults ... */
1817 BPF_INSN_MAP(BPF_INSN_2_TBL, BPF_INSN_3_TBL),
1818 /* UAPI exposed, but rewritten opcodes. cBPF carry-over. */
1819 [BPF_LD | BPF_ABS | BPF_B] = true,
1820 [BPF_LD | BPF_ABS | BPF_H] = true,
1821 [BPF_LD | BPF_ABS | BPF_W] = true,
1822 [BPF_LD | BPF_IND | BPF_B] = true,
1823 [BPF_LD | BPF_IND | BPF_H] = true,
1824 [BPF_LD | BPF_IND | BPF_W] = true,
1825 [BPF_JMP | BPF_JA | BPF_X] = true,
1826 [BPF_JMP | BPF_JCOND] = true,
1827 };
1828 #undef BPF_INSN_3_TBL
1829 #undef BPF_INSN_2_TBL
1830 return public_insntable[code];
1831 }
1832
1833 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1834 /* Absolute value of s32 without undefined behavior for S32_MIN */
abs_s32(s32 x)1835 static u32 abs_s32(s32 x)
1836 {
1837 return x >= 0 ? (u32)x : -(u32)x;
1838 }
1839
1840 static u64 (*interpreters_args[])(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5,
1841 const struct bpf_insn *insn);
1842
1843 /**
1844 * ___bpf_prog_run - run eBPF program on a given context
1845 * @regs: is the array of MAX_BPF_EXT_REG eBPF pseudo-registers
1846 * @insn: is the array of eBPF instructions
1847 *
1848 * Decode and execute eBPF instructions.
1849 *
1850 * Return: whatever value is in %BPF_R0 at program exit
1851 */
___bpf_prog_run(u64 * regs,const struct bpf_insn * insn)1852 static u64 ___bpf_prog_run(u64 *regs, const struct bpf_insn *insn)
1853 {
1854 #define BPF_INSN_2_LBL(x, y) [BPF_##x | BPF_##y] = &&x##_##y
1855 #define BPF_INSN_3_LBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = &&x##_##y##_##z
1856 static const void * const jumptable[256] __annotate_jump_table = {
1857 [0 ... 255] = &&default_label,
1858 /* Now overwrite non-defaults ... */
1859 BPF_INSN_MAP(BPF_INSN_2_LBL, BPF_INSN_3_LBL),
1860 /* Non-UAPI available opcodes. */
1861 [BPF_JMP | BPF_CALL_ARGS] = &&JMP_CALL_ARGS,
1862 [BPF_JMP | BPF_TAIL_CALL] = &&JMP_TAIL_CALL,
1863 [BPF_ST | BPF_NOSPEC] = &&ST_NOSPEC,
1864 [BPF_LDX | BPF_PROBE_MEM | BPF_B] = &&LDX_PROBE_MEM_B,
1865 [BPF_LDX | BPF_PROBE_MEM | BPF_H] = &&LDX_PROBE_MEM_H,
1866 [BPF_LDX | BPF_PROBE_MEM | BPF_W] = &&LDX_PROBE_MEM_W,
1867 [BPF_LDX | BPF_PROBE_MEM | BPF_DW] = &&LDX_PROBE_MEM_DW,
1868 [BPF_LDX | BPF_PROBE_MEMSX | BPF_B] = &&LDX_PROBE_MEMSX_B,
1869 [BPF_LDX | BPF_PROBE_MEMSX | BPF_H] = &&LDX_PROBE_MEMSX_H,
1870 [BPF_LDX | BPF_PROBE_MEMSX | BPF_W] = &&LDX_PROBE_MEMSX_W,
1871 };
1872 #undef BPF_INSN_3_LBL
1873 #undef BPF_INSN_2_LBL
1874 u32 tail_call_cnt = 0;
1875
1876 #define CONT ({ insn++; goto select_insn; })
1877 #define CONT_JMP ({ insn++; goto select_insn; })
1878
1879 select_insn:
1880 goto *jumptable[insn->code];
1881
1882 /* Explicitly mask the register-based shift amounts with 63 or 31
1883 * to avoid undefined behavior. Normally this won't affect the
1884 * generated code, for example, in case of native 64 bit archs such
1885 * as x86-64 or arm64, the compiler is optimizing the AND away for
1886 * the interpreter. In case of JITs, each of the JIT backends compiles
1887 * the BPF shift operations to machine instructions which produce
1888 * implementation-defined results in such a case; the resulting
1889 * contents of the register may be arbitrary, but program behaviour
1890 * as a whole remains defined. In other words, in case of JIT backends,
1891 * the AND must /not/ be added to the emitted LSH/RSH/ARSH translation.
1892 */
1893 /* ALU (shifts) */
1894 #define SHT(OPCODE, OP) \
1895 ALU64_##OPCODE##_X: \
1896 DST = DST OP (SRC & 63); \
1897 CONT; \
1898 ALU_##OPCODE##_X: \
1899 DST = (u32) DST OP ((u32) SRC & 31); \
1900 CONT; \
1901 ALU64_##OPCODE##_K: \
1902 DST = DST OP IMM; \
1903 CONT; \
1904 ALU_##OPCODE##_K: \
1905 DST = (u32) DST OP (u32) IMM; \
1906 CONT;
1907 /* ALU (rest) */
1908 #define ALU(OPCODE, OP) \
1909 ALU64_##OPCODE##_X: \
1910 DST = DST OP SRC; \
1911 CONT; \
1912 ALU_##OPCODE##_X: \
1913 DST = (u32) DST OP (u32) SRC; \
1914 CONT; \
1915 ALU64_##OPCODE##_K: \
1916 DST = DST OP IMM; \
1917 CONT; \
1918 ALU_##OPCODE##_K: \
1919 DST = (u32) DST OP (u32) IMM; \
1920 CONT;
1921 ALU(ADD, +)
1922 ALU(SUB, -)
1923 ALU(AND, &)
1924 ALU(OR, |)
1925 ALU(XOR, ^)
1926 ALU(MUL, *)
1927 SHT(LSH, <<)
1928 SHT(RSH, >>)
1929 #undef SHT
1930 #undef ALU
1931 ALU_NEG:
1932 DST = (u32) -DST;
1933 CONT;
1934 ALU64_NEG:
1935 DST = -DST;
1936 CONT;
1937 ALU_MOV_X:
1938 switch (OFF) {
1939 case 0:
1940 DST = (u32) SRC;
1941 break;
1942 case 8:
1943 DST = (u32)(s8) SRC;
1944 break;
1945 case 16:
1946 DST = (u32)(s16) SRC;
1947 break;
1948 }
1949 CONT;
1950 ALU_MOV_K:
1951 DST = (u32) IMM;
1952 CONT;
1953 ALU64_MOV_X:
1954 switch (OFF) {
1955 case 0:
1956 DST = SRC;
1957 break;
1958 case 8:
1959 DST = (s8) SRC;
1960 break;
1961 case 16:
1962 DST = (s16) SRC;
1963 break;
1964 case 32:
1965 DST = (s32) SRC;
1966 break;
1967 }
1968 CONT;
1969 ALU64_MOV_K:
1970 DST = IMM;
1971 CONT;
1972 LD_IMM_DW:
1973 DST = (u64) (u32) insn[0].imm | ((u64) (u32) insn[1].imm) << 32;
1974 insn++;
1975 CONT;
1976 ALU_ARSH_X:
1977 DST = (u64) (u32) (((s32) DST) >> (SRC & 31));
1978 CONT;
1979 ALU_ARSH_K:
1980 DST = (u64) (u32) (((s32) DST) >> IMM);
1981 CONT;
1982 ALU64_ARSH_X:
1983 (*(s64 *) &DST) >>= (SRC & 63);
1984 CONT;
1985 ALU64_ARSH_K:
1986 (*(s64 *) &DST) >>= IMM;
1987 CONT;
1988 ALU64_MOD_X:
1989 switch (OFF) {
1990 case 0:
1991 div64_u64_rem(DST, SRC, &AX);
1992 DST = AX;
1993 break;
1994 case 1:
1995 AX = div64_s64(DST, SRC);
1996 DST = DST - AX * SRC;
1997 break;
1998 }
1999 CONT;
2000 ALU_MOD_X:
2001 switch (OFF) {
2002 case 0:
2003 AX = (u32) DST;
2004 DST = do_div(AX, (u32) SRC);
2005 break;
2006 case 1:
2007 AX = abs_s32((s32)DST);
2008 AX = do_div(AX, abs_s32((s32)SRC));
2009 if ((s32)DST < 0)
2010 DST = (u32)-AX;
2011 else
2012 DST = (u32)AX;
2013 break;
2014 }
2015 CONT;
2016 ALU64_MOD_K:
2017 switch (OFF) {
2018 case 0:
2019 div64_u64_rem(DST, IMM, &AX);
2020 DST = AX;
2021 break;
2022 case 1:
2023 AX = div64_s64(DST, IMM);
2024 DST = DST - AX * IMM;
2025 break;
2026 }
2027 CONT;
2028 ALU_MOD_K:
2029 switch (OFF) {
2030 case 0:
2031 AX = (u32) DST;
2032 DST = do_div(AX, (u32) IMM);
2033 break;
2034 case 1:
2035 AX = abs_s32((s32)DST);
2036 AX = do_div(AX, abs_s32((s32)IMM));
2037 if ((s32)DST < 0)
2038 DST = (u32)-AX;
2039 else
2040 DST = (u32)AX;
2041 break;
2042 }
2043 CONT;
2044 ALU64_DIV_X:
2045 switch (OFF) {
2046 case 0:
2047 DST = div64_u64(DST, SRC);
2048 break;
2049 case 1:
2050 DST = div64_s64(DST, SRC);
2051 break;
2052 }
2053 CONT;
2054 ALU_DIV_X:
2055 switch (OFF) {
2056 case 0:
2057 AX = (u32) DST;
2058 do_div(AX, (u32) SRC);
2059 DST = (u32) AX;
2060 break;
2061 case 1:
2062 AX = abs_s32((s32)DST);
2063 do_div(AX, abs_s32((s32)SRC));
2064 if (((s32)DST < 0) == ((s32)SRC < 0))
2065 DST = (u32)AX;
2066 else
2067 DST = (u32)-AX;
2068 break;
2069 }
2070 CONT;
2071 ALU64_DIV_K:
2072 switch (OFF) {
2073 case 0:
2074 DST = div64_u64(DST, IMM);
2075 break;
2076 case 1:
2077 DST = div64_s64(DST, IMM);
2078 break;
2079 }
2080 CONT;
2081 ALU_DIV_K:
2082 switch (OFF) {
2083 case 0:
2084 AX = (u32) DST;
2085 do_div(AX, (u32) IMM);
2086 DST = (u32) AX;
2087 break;
2088 case 1:
2089 AX = abs_s32((s32)DST);
2090 do_div(AX, abs_s32((s32)IMM));
2091 if (((s32)DST < 0) == ((s32)IMM < 0))
2092 DST = (u32)AX;
2093 else
2094 DST = (u32)-AX;
2095 break;
2096 }
2097 CONT;
2098 ALU_END_TO_BE:
2099 switch (IMM) {
2100 case 16:
2101 DST = (__force u16) cpu_to_be16(DST);
2102 break;
2103 case 32:
2104 DST = (__force u32) cpu_to_be32(DST);
2105 break;
2106 case 64:
2107 DST = (__force u64) cpu_to_be64(DST);
2108 break;
2109 }
2110 CONT;
2111 ALU_END_TO_LE:
2112 switch (IMM) {
2113 case 16:
2114 DST = (__force u16) cpu_to_le16(DST);
2115 break;
2116 case 32:
2117 DST = (__force u32) cpu_to_le32(DST);
2118 break;
2119 case 64:
2120 DST = (__force u64) cpu_to_le64(DST);
2121 break;
2122 }
2123 CONT;
2124 ALU64_END_TO_LE:
2125 switch (IMM) {
2126 case 16:
2127 DST = (__force u16) __swab16(DST);
2128 break;
2129 case 32:
2130 DST = (__force u32) __swab32(DST);
2131 break;
2132 case 64:
2133 DST = (__force u64) __swab64(DST);
2134 break;
2135 }
2136 CONT;
2137
2138 /* CALL */
2139 JMP_CALL:
2140 /* Function call scratches BPF_R1-BPF_R5 registers,
2141 * preserves BPF_R6-BPF_R9, and stores return value
2142 * into BPF_R0.
2143 */
2144 BPF_R0 = (__bpf_call_base + insn->imm)(BPF_R1, BPF_R2, BPF_R3,
2145 BPF_R4, BPF_R5);
2146 CONT;
2147
2148 JMP_CALL_ARGS:
2149 BPF_R0 = interpreters_args[insn->off](BPF_R1, BPF_R2, BPF_R3,
2150 BPF_R4, BPF_R5,
2151 insn + insn->imm + 1);
2152 CONT;
2153
2154 JMP_TAIL_CALL: {
2155 struct bpf_map *map = (struct bpf_map *) (unsigned long) BPF_R2;
2156 struct bpf_array *array = container_of(map, struct bpf_array, map);
2157 struct bpf_prog *prog;
2158 u32 index = BPF_R3;
2159
2160 if (unlikely(index >= array->map.max_entries))
2161 goto out;
2162
2163 if (unlikely(tail_call_cnt >= MAX_TAIL_CALL_CNT))
2164 goto out;
2165
2166 prog = READ_ONCE(array->ptrs[index]);
2167 if (!prog)
2168 goto out;
2169
2170 tail_call_cnt++;
2171
2172 /* ARG1 at this point is guaranteed to point to CTX from
2173 * the verifier side due to the fact that the tail call is
2174 * handled like a helper, that is, bpf_tail_call_proto,
2175 * where arg1_type is ARG_PTR_TO_CTX.
2176 */
2177 insn = prog->insnsi;
2178 goto select_insn;
2179 out:
2180 CONT;
2181 }
2182 JMP_JA:
2183 insn += insn->off;
2184 CONT;
2185 JMP32_JA:
2186 insn += insn->imm;
2187 CONT;
2188 JMP_EXIT:
2189 return BPF_R0;
2190 /* JMP */
2191 #define COND_JMP(SIGN, OPCODE, CMP_OP) \
2192 JMP_##OPCODE##_X: \
2193 if ((SIGN##64) DST CMP_OP (SIGN##64) SRC) { \
2194 insn += insn->off; \
2195 CONT_JMP; \
2196 } \
2197 CONT; \
2198 JMP32_##OPCODE##_X: \
2199 if ((SIGN##32) DST CMP_OP (SIGN##32) SRC) { \
2200 insn += insn->off; \
2201 CONT_JMP; \
2202 } \
2203 CONT; \
2204 JMP_##OPCODE##_K: \
2205 if ((SIGN##64) DST CMP_OP (SIGN##64) IMM) { \
2206 insn += insn->off; \
2207 CONT_JMP; \
2208 } \
2209 CONT; \
2210 JMP32_##OPCODE##_K: \
2211 if ((SIGN##32) DST CMP_OP (SIGN##32) IMM) { \
2212 insn += insn->off; \
2213 CONT_JMP; \
2214 } \
2215 CONT;
2216 COND_JMP(u, JEQ, ==)
2217 COND_JMP(u, JNE, !=)
2218 COND_JMP(u, JGT, >)
2219 COND_JMP(u, JLT, <)
2220 COND_JMP(u, JGE, >=)
2221 COND_JMP(u, JLE, <=)
2222 COND_JMP(u, JSET, &)
2223 COND_JMP(s, JSGT, >)
2224 COND_JMP(s, JSLT, <)
2225 COND_JMP(s, JSGE, >=)
2226 COND_JMP(s, JSLE, <=)
2227 #undef COND_JMP
2228 /* ST, STX and LDX*/
2229 ST_NOSPEC:
2230 /* Speculation barrier for mitigating Speculative Store Bypass,
2231 * Bounds-Check Bypass and Type Confusion. In case of arm64, we
2232 * rely on the firmware mitigation as controlled via the ssbd
2233 * kernel parameter. Whenever the mitigation is enabled, it
2234 * works for all of the kernel code with no need to provide any
2235 * additional instructions here. In case of x86, we use 'lfence'
2236 * insn for mitigation. We reuse preexisting logic from Spectre
2237 * v1 mitigation that happens to produce the required code on
2238 * x86 for v4 as well.
2239 */
2240 barrier_nospec();
2241 CONT;
2242 #define LDST(SIZEOP, SIZE) \
2243 STX_MEM_##SIZEOP: \
2244 *(SIZE *)(unsigned long) (DST + insn->off) = SRC; \
2245 CONT; \
2246 ST_MEM_##SIZEOP: \
2247 *(SIZE *)(unsigned long) (DST + insn->off) = IMM; \
2248 CONT; \
2249 LDX_MEM_##SIZEOP: \
2250 DST = *(SIZE *)(unsigned long) (SRC + insn->off); \
2251 CONT; \
2252 LDX_PROBE_MEM_##SIZEOP: \
2253 bpf_probe_read_kernel_common(&DST, sizeof(SIZE), \
2254 (const void *)(long) (SRC + insn->off)); \
2255 DST = *((SIZE *)&DST); \
2256 CONT;
2257
2258 LDST(B, u8)
2259 LDST(H, u16)
2260 LDST(W, u32)
2261 LDST(DW, u64)
2262 #undef LDST
2263
2264 #define LDSX(SIZEOP, SIZE) \
2265 LDX_MEMSX_##SIZEOP: \
2266 DST = *(SIZE *)(unsigned long) (SRC + insn->off); \
2267 CONT; \
2268 LDX_PROBE_MEMSX_##SIZEOP: \
2269 bpf_probe_read_kernel_common(&DST, sizeof(SIZE), \
2270 (const void *)(long) (SRC + insn->off)); \
2271 DST = *((SIZE *)&DST); \
2272 CONT;
2273
2274 LDSX(B, s8)
2275 LDSX(H, s16)
2276 LDSX(W, s32)
2277 #undef LDSX
2278
2279 #define ATOMIC_ALU_OP(BOP, KOP) \
2280 case BOP: \
2281 if (BPF_SIZE(insn->code) == BPF_W) \
2282 atomic_##KOP((u32) SRC, (atomic_t *)(unsigned long) \
2283 (DST + insn->off)); \
2284 else if (BPF_SIZE(insn->code) == BPF_DW) \
2285 atomic64_##KOP((u64) SRC, (atomic64_t *)(unsigned long) \
2286 (DST + insn->off)); \
2287 else \
2288 goto default_label; \
2289 break; \
2290 case BOP | BPF_FETCH: \
2291 if (BPF_SIZE(insn->code) == BPF_W) \
2292 SRC = (u32) atomic_fetch_##KOP( \
2293 (u32) SRC, \
2294 (atomic_t *)(unsigned long) (DST + insn->off)); \
2295 else if (BPF_SIZE(insn->code) == BPF_DW) \
2296 SRC = (u64) atomic64_fetch_##KOP( \
2297 (u64) SRC, \
2298 (atomic64_t *)(unsigned long) (DST + insn->off)); \
2299 else \
2300 goto default_label; \
2301 break;
2302
2303 STX_ATOMIC_DW:
2304 STX_ATOMIC_W:
2305 STX_ATOMIC_H:
2306 STX_ATOMIC_B:
2307 switch (IMM) {
2308 /* Atomic read-modify-write instructions support only W and DW
2309 * size modifiers.
2310 */
2311 ATOMIC_ALU_OP(BPF_ADD, add)
2312 ATOMIC_ALU_OP(BPF_AND, and)
2313 ATOMIC_ALU_OP(BPF_OR, or)
2314 ATOMIC_ALU_OP(BPF_XOR, xor)
2315 #undef ATOMIC_ALU_OP
2316
2317 case BPF_XCHG:
2318 if (BPF_SIZE(insn->code) == BPF_W)
2319 SRC = (u32) atomic_xchg(
2320 (atomic_t *)(unsigned long) (DST + insn->off),
2321 (u32) SRC);
2322 else if (BPF_SIZE(insn->code) == BPF_DW)
2323 SRC = (u64) atomic64_xchg(
2324 (atomic64_t *)(unsigned long) (DST + insn->off),
2325 (u64) SRC);
2326 else
2327 goto default_label;
2328 break;
2329 case BPF_CMPXCHG:
2330 if (BPF_SIZE(insn->code) == BPF_W)
2331 BPF_R0 = (u32) atomic_cmpxchg(
2332 (atomic_t *)(unsigned long) (DST + insn->off),
2333 (u32) BPF_R0, (u32) SRC);
2334 else if (BPF_SIZE(insn->code) == BPF_DW)
2335 BPF_R0 = (u64) atomic64_cmpxchg(
2336 (atomic64_t *)(unsigned long) (DST + insn->off),
2337 (u64) BPF_R0, (u64) SRC);
2338 else
2339 goto default_label;
2340 break;
2341 /* Atomic load and store instructions support all size
2342 * modifiers.
2343 */
2344 case BPF_LOAD_ACQ:
2345 switch (BPF_SIZE(insn->code)) {
2346 #define LOAD_ACQUIRE(SIZEOP, SIZE) \
2347 case BPF_##SIZEOP: \
2348 DST = (SIZE)smp_load_acquire( \
2349 (SIZE *)(unsigned long)(SRC + insn->off)); \
2350 break;
2351 LOAD_ACQUIRE(B, u8)
2352 LOAD_ACQUIRE(H, u16)
2353 LOAD_ACQUIRE(W, u32)
2354 #ifdef CONFIG_64BIT
2355 LOAD_ACQUIRE(DW, u64)
2356 #endif
2357 #undef LOAD_ACQUIRE
2358 default:
2359 goto default_label;
2360 }
2361 break;
2362 case BPF_STORE_REL:
2363 switch (BPF_SIZE(insn->code)) {
2364 #define STORE_RELEASE(SIZEOP, SIZE) \
2365 case BPF_##SIZEOP: \
2366 smp_store_release( \
2367 (SIZE *)(unsigned long)(DST + insn->off), (SIZE)SRC); \
2368 break;
2369 STORE_RELEASE(B, u8)
2370 STORE_RELEASE(H, u16)
2371 STORE_RELEASE(W, u32)
2372 #ifdef CONFIG_64BIT
2373 STORE_RELEASE(DW, u64)
2374 #endif
2375 #undef STORE_RELEASE
2376 default:
2377 goto default_label;
2378 }
2379 break;
2380
2381 default:
2382 goto default_label;
2383 }
2384 CONT;
2385
2386 default_label:
2387 /* If we ever reach this, we have a bug somewhere. Die hard here
2388 * instead of just returning 0; we could be somewhere in a subprog,
2389 * so execution could continue otherwise which we do /not/ want.
2390 *
2391 * Note, verifier whitelists all opcodes in bpf_opcode_in_insntable().
2392 */
2393 pr_warn("BPF interpreter: unknown opcode %02x (imm: 0x%x)\n",
2394 insn->code, insn->imm);
2395 BUG_ON(1);
2396 return 0;
2397 }
2398
2399 #define PROG_NAME(stack_size) __bpf_prog_run##stack_size
2400 #define DEFINE_BPF_PROG_RUN(stack_size) \
2401 static unsigned int PROG_NAME(stack_size)(const void *ctx, const struct bpf_insn *insn) \
2402 { \
2403 u64 stack[stack_size / sizeof(u64)]; \
2404 u64 regs[MAX_BPF_EXT_REG] = {}; \
2405 \
2406 kmsan_unpoison_memory(stack, sizeof(stack)); \
2407 FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
2408 ARG1 = (u64) (unsigned long) ctx; \
2409 return ___bpf_prog_run(regs, insn); \
2410 }
2411
2412 #define PROG_NAME_ARGS(stack_size) __bpf_prog_run_args##stack_size
2413 #define DEFINE_BPF_PROG_RUN_ARGS(stack_size) \
2414 static u64 PROG_NAME_ARGS(stack_size)(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, \
2415 const struct bpf_insn *insn) \
2416 { \
2417 u64 stack[stack_size / sizeof(u64)]; \
2418 u64 regs[MAX_BPF_EXT_REG]; \
2419 \
2420 kmsan_unpoison_memory(stack, sizeof(stack)); \
2421 FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
2422 BPF_R1 = r1; \
2423 BPF_R2 = r2; \
2424 BPF_R3 = r3; \
2425 BPF_R4 = r4; \
2426 BPF_R5 = r5; \
2427 return ___bpf_prog_run(regs, insn); \
2428 }
2429
2430 #define EVAL1(FN, X) FN(X)
2431 #define EVAL2(FN, X, Y...) FN(X) EVAL1(FN, Y)
2432 #define EVAL3(FN, X, Y...) FN(X) EVAL2(FN, Y)
2433 #define EVAL4(FN, X, Y...) FN(X) EVAL3(FN, Y)
2434 #define EVAL5(FN, X, Y...) FN(X) EVAL4(FN, Y)
2435 #define EVAL6(FN, X, Y...) FN(X) EVAL5(FN, Y)
2436
2437 EVAL6(DEFINE_BPF_PROG_RUN, 32, 64, 96, 128, 160, 192);
2438 EVAL6(DEFINE_BPF_PROG_RUN, 224, 256, 288, 320, 352, 384);
2439 EVAL4(DEFINE_BPF_PROG_RUN, 416, 448, 480, 512);
2440
2441 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 32, 64, 96, 128, 160, 192);
2442 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 224, 256, 288, 320, 352, 384);
2443 EVAL4(DEFINE_BPF_PROG_RUN_ARGS, 416, 448, 480, 512);
2444
2445 #define PROG_NAME_LIST(stack_size) PROG_NAME(stack_size),
2446
2447 static unsigned int (*interpreters[])(const void *ctx,
2448 const struct bpf_insn *insn) = {
2449 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
2450 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
2451 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
2452 };
2453 #undef PROG_NAME_LIST
2454 #define PROG_NAME_LIST(stack_size) PROG_NAME_ARGS(stack_size),
2455 static __maybe_unused
2456 u64 (*interpreters_args[])(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5,
2457 const struct bpf_insn *insn) = {
2458 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
2459 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
2460 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
2461 };
2462 #undef PROG_NAME_LIST
2463
2464 #ifdef CONFIG_BPF_SYSCALL
bpf_patch_call_args(struct bpf_insn * insn,u32 stack_depth)2465 int bpf_patch_call_args(struct bpf_insn *insn, u32 stack_depth)
2466 {
2467 stack_depth = max_t(u32, stack_depth, 1);
2468 /* Prevent out-of-bounds read to interpreters_args */
2469 if (stack_depth > MAX_BPF_STACK)
2470 return -EINVAL;
2471 insn->off = (round_up(stack_depth, 32) / 32) - 1;
2472 insn->code = BPF_JMP | BPF_CALL_ARGS;
2473 return 0;
2474 }
2475
bpf_call_args_imm(s16 idx)2476 s32 bpf_call_args_imm(s16 idx)
2477 {
2478 if (WARN_ON_ONCE(idx < 0 || idx >= ARRAY_SIZE(interpreters_args)))
2479 return 0;
2480 return BPF_CALL_IMM(interpreters_args[idx]);
2481 }
2482 #endif
2483 #endif
2484
__bpf_prog_ret0_warn(const void * ctx,const struct bpf_insn * insn)2485 static unsigned int __bpf_prog_ret0_warn(const void *ctx,
2486 const struct bpf_insn *insn)
2487 {
2488 /* If this handler ever gets executed, then BPF_JIT_ALWAYS_ON
2489 * is not working properly, so warn about it!
2490 */
2491 WARN_ON_ONCE(1);
2492 return 0;
2493 }
2494
__bpf_prog_map_compatible(struct bpf_map * map,const struct bpf_prog * fp)2495 static bool __bpf_prog_map_compatible(struct bpf_map *map,
2496 const struct bpf_prog *fp)
2497 {
2498 enum bpf_prog_type prog_type = resolve_prog_type(fp);
2499 struct bpf_prog_aux *aux = fp->aux;
2500 enum bpf_cgroup_storage_type i;
2501 bool ret = false;
2502 u64 cookie;
2503
2504 if (fp->kprobe_override)
2505 return ret;
2506
2507 spin_lock(&map->owner_lock);
2508 /* There's no owner yet where we could check for compatibility. */
2509 if (!map->owner) {
2510 map->owner = bpf_map_owner_alloc(map);
2511 if (!map->owner)
2512 goto err;
2513 map->owner->type = prog_type;
2514 map->owner->jited = fp->jited;
2515 map->owner->xdp_has_frags = aux->xdp_has_frags;
2516 map->owner->sleepable = fp->sleepable;
2517 map->owner->expected_attach_type = fp->expected_attach_type;
2518 map->owner->attach_func_proto = aux->attach_func_proto;
2519 for_each_cgroup_storage_type(i) {
2520 map->owner->storage_cookie[i] =
2521 aux->cgroup_storage[i] ?
2522 aux->cgroup_storage[i]->cookie : 0;
2523 }
2524 ret = true;
2525 } else {
2526 ret = map->owner->type == prog_type &&
2527 map->owner->jited == fp->jited &&
2528 map->owner->xdp_has_frags == aux->xdp_has_frags &&
2529 map->owner->sleepable == fp->sleepable;
2530 if (ret &&
2531 map->map_type == BPF_MAP_TYPE_PROG_ARRAY &&
2532 map->owner->expected_attach_type != fp->expected_attach_type)
2533 ret = false;
2534 for_each_cgroup_storage_type(i) {
2535 if (!ret)
2536 break;
2537 cookie = aux->cgroup_storage[i] ?
2538 aux->cgroup_storage[i]->cookie : 0;
2539 ret = map->owner->storage_cookie[i] == cookie ||
2540 (!cookie && !aux->tail_call_reachable);
2541 }
2542 if (ret &&
2543 map->owner->attach_func_proto != aux->attach_func_proto) {
2544 switch (prog_type) {
2545 case BPF_PROG_TYPE_TRACING:
2546 case BPF_PROG_TYPE_LSM:
2547 case BPF_PROG_TYPE_EXT:
2548 case BPF_PROG_TYPE_STRUCT_OPS:
2549 ret = false;
2550 break;
2551 default:
2552 break;
2553 }
2554 }
2555 }
2556 err:
2557 spin_unlock(&map->owner_lock);
2558 return ret;
2559 }
2560
bpf_prog_map_compatible(struct bpf_map * map,const struct bpf_prog * fp)2561 bool bpf_prog_map_compatible(struct bpf_map *map, const struct bpf_prog *fp)
2562 {
2563 /* XDP programs inserted into maps are not guaranteed to run on
2564 * a particular netdev (and can run outside driver context entirely
2565 * in the case of devmap and cpumap). Until device checks
2566 * are implemented, prohibit adding dev-bound programs to program maps.
2567 */
2568 if (bpf_prog_is_dev_bound(fp->aux))
2569 return false;
2570
2571 return __bpf_prog_map_compatible(map, fp);
2572 }
2573
bpf_check_tail_call(const struct bpf_prog * fp)2574 static int bpf_check_tail_call(const struct bpf_prog *fp)
2575 {
2576 struct bpf_prog_aux *aux = fp->aux;
2577 int i, ret = 0;
2578
2579 mutex_lock(&aux->used_maps_mutex);
2580 for (i = 0; i < aux->used_map_cnt; i++) {
2581 struct bpf_map *map = aux->used_maps[i];
2582
2583 if (!map_type_contains_progs(map))
2584 continue;
2585
2586 if (!__bpf_prog_map_compatible(map, fp)) {
2587 ret = -EINVAL;
2588 goto out;
2589 }
2590 }
2591
2592 out:
2593 mutex_unlock(&aux->used_maps_mutex);
2594 return ret;
2595 }
2596
bpf_prog_select_interpreter(struct bpf_prog * fp)2597 static bool bpf_prog_select_interpreter(struct bpf_prog *fp)
2598 {
2599 bool select_interpreter = false;
2600 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
2601 u32 stack_depth = max_t(u32, fp->aux->stack_depth, 1);
2602 u32 idx = (round_up(stack_depth, 32) / 32) - 1;
2603
2604 /* may_goto may cause stack size > 512, leading to idx out-of-bounds.
2605 * But for non-JITed programs, we don't need bpf_func, so no bounds
2606 * check needed.
2607 */
2608 if (idx < ARRAY_SIZE(interpreters)) {
2609 fp->bpf_func = interpreters[idx];
2610 select_interpreter = true;
2611 } else {
2612 fp->bpf_func = __bpf_prog_ret0_warn;
2613 }
2614 #else
2615 fp->bpf_func = __bpf_prog_ret0_warn;
2616 #endif
2617 return select_interpreter;
2618 }
2619
bpf_prog_jit_compile(struct bpf_verifier_env * env,struct bpf_prog * prog)2620 static struct bpf_prog *bpf_prog_jit_compile(struct bpf_verifier_env *env, struct bpf_prog *prog)
2621 {
2622 #ifdef CONFIG_BPF_JIT
2623 struct bpf_prog *orig_prog;
2624 struct bpf_insn_aux_data *orig_insn_aux;
2625
2626 if (!bpf_prog_need_blind(prog))
2627 return bpf_int_jit_compile(env, prog);
2628
2629 if (env) {
2630 /*
2631 * If env is not NULL, we are called from the end of bpf_check(), at this
2632 * point, only insn_aux_data is used after failure, so it should be restored
2633 * on failure.
2634 */
2635 orig_insn_aux = bpf_dup_insn_aux_data(env);
2636 if (!orig_insn_aux)
2637 return prog;
2638 }
2639
2640 orig_prog = prog;
2641 prog = bpf_jit_blind_constants(env, prog);
2642 /*
2643 * If blinding was requested and we failed during blinding, we must fall
2644 * back to the interpreter.
2645 */
2646 if (IS_ERR(prog))
2647 goto out_restore;
2648
2649 prog = bpf_int_jit_compile(env, prog);
2650 if (prog->jited) {
2651 bpf_jit_prog_release_other(prog, orig_prog);
2652 if (env)
2653 vfree(orig_insn_aux);
2654 return prog;
2655 }
2656
2657 bpf_jit_prog_release_other(orig_prog, prog);
2658
2659 out_restore:
2660 prog = orig_prog;
2661 if (env)
2662 bpf_restore_insn_aux_data(env, orig_insn_aux);
2663 #endif
2664 return prog;
2665 }
2666
__bpf_prog_select_runtime(struct bpf_verifier_env * env,struct bpf_prog * fp,int * err)2667 struct bpf_prog *__bpf_prog_select_runtime(struct bpf_verifier_env *env, struct bpf_prog *fp,
2668 int *err)
2669 {
2670 /* In case of BPF to BPF calls, verifier did all the prep
2671 * work with regards to JITing, etc.
2672 */
2673 bool jit_needed = false;
2674
2675 if (fp->bpf_func)
2676 goto finalize;
2677
2678 if (IS_ENABLED(CONFIG_BPF_JIT_ALWAYS_ON) ||
2679 bpf_prog_has_kfunc_call(fp))
2680 jit_needed = true;
2681
2682 if (!bpf_prog_select_interpreter(fp))
2683 jit_needed = true;
2684
2685 /* eBPF JITs can rewrite the program in case constant
2686 * blinding is active. However, in case of error during
2687 * blinding, bpf_int_jit_compile() must always return a
2688 * valid program, which in this case would simply not
2689 * be JITed, but falls back to the interpreter.
2690 */
2691 if (!bpf_prog_is_offloaded(fp->aux)) {
2692 *err = bpf_prog_alloc_jited_linfo(fp);
2693 if (*err)
2694 return fp;
2695
2696 fp = bpf_prog_jit_compile(env, fp);
2697 bpf_prog_jit_attempt_done(fp);
2698 if (!fp->jited && jit_needed) {
2699 *err = -ENOTSUPP;
2700 return fp;
2701 }
2702 } else {
2703 *err = bpf_prog_offload_compile(fp);
2704 if (*err)
2705 return fp;
2706 }
2707
2708 finalize:
2709 *err = bpf_prog_lock_ro(fp);
2710 if (*err)
2711 return fp;
2712
2713 /* The tail call compatibility check can only be done at
2714 * this late stage as we need to determine, if we deal
2715 * with JITed or non JITed program concatenations and not
2716 * all eBPF JITs might immediately support all features.
2717 */
2718 *err = bpf_check_tail_call(fp);
2719
2720 return fp;
2721 }
2722
2723 /**
2724 * bpf_prog_select_runtime - select exec runtime for BPF program
2725 * @fp: bpf_prog populated with BPF program
2726 * @err: pointer to error variable
2727 *
2728 * Try to JIT eBPF program, if JIT is not available, use interpreter.
2729 * The BPF program will be executed via bpf_prog_run() function.
2730 *
2731 * Return: the &fp argument along with &err set to 0 for success or
2732 * a negative errno code on failure
2733 */
bpf_prog_select_runtime(struct bpf_prog * fp,int * err)2734 struct bpf_prog *bpf_prog_select_runtime(struct bpf_prog *fp, int *err)
2735 {
2736 return __bpf_prog_select_runtime(NULL, fp, err);
2737 }
2738 EXPORT_SYMBOL_GPL(bpf_prog_select_runtime);
2739
__bpf_prog_ret1(const void * ctx,const struct bpf_insn * insn)2740 static unsigned int __bpf_prog_ret1(const void *ctx,
2741 const struct bpf_insn *insn)
2742 {
2743 return 1;
2744 }
2745
2746 static struct bpf_prog_dummy {
2747 struct bpf_prog prog;
2748 } dummy_bpf_prog = {
2749 .prog = {
2750 .bpf_func = __bpf_prog_ret1,
2751 },
2752 };
2753
2754 struct bpf_prog_array bpf_empty_prog_array = {
2755 .items = {
2756 { .prog = NULL },
2757 },
2758 };
2759 EXPORT_SYMBOL(bpf_empty_prog_array);
2760
bpf_prog_array_alloc(u32 prog_cnt,gfp_t flags)2761 struct bpf_prog_array *bpf_prog_array_alloc(u32 prog_cnt, gfp_t flags)
2762 {
2763 struct bpf_prog_array *p;
2764
2765 if (prog_cnt)
2766 p = kzalloc_flex(*p, items, prog_cnt + 1, flags);
2767 else
2768 p = &bpf_empty_prog_array;
2769
2770 return p;
2771 }
2772
bpf_prog_array_free(struct bpf_prog_array * progs)2773 void bpf_prog_array_free(struct bpf_prog_array *progs)
2774 {
2775 if (!progs || progs == &bpf_empty_prog_array)
2776 return;
2777 kfree_rcu(progs, rcu);
2778 }
2779
__bpf_prog_array_free_sleepable_cb(struct rcu_head * rcu)2780 static void __bpf_prog_array_free_sleepable_cb(struct rcu_head *rcu)
2781 {
2782 struct bpf_prog_array *progs;
2783
2784 /*
2785 * RCU Tasks Trace grace period implies RCU grace period, there is no
2786 * need to call kfree_rcu(), just call kfree() directly.
2787 */
2788 progs = container_of(rcu, struct bpf_prog_array, rcu);
2789 kfree(progs);
2790 }
2791
bpf_prog_array_free_sleepable(struct bpf_prog_array * progs)2792 void bpf_prog_array_free_sleepable(struct bpf_prog_array *progs)
2793 {
2794 if (!progs || progs == &bpf_empty_prog_array)
2795 return;
2796 call_rcu_tasks_trace(&progs->rcu, __bpf_prog_array_free_sleepable_cb);
2797 }
2798
bpf_prog_array_length(struct bpf_prog_array * array)2799 int bpf_prog_array_length(struct bpf_prog_array *array)
2800 {
2801 struct bpf_prog_array_item *item;
2802 u32 cnt = 0;
2803
2804 for (item = array->items; item->prog; item++)
2805 if (item->prog != &dummy_bpf_prog.prog)
2806 cnt++;
2807 return cnt;
2808 }
2809
bpf_prog_array_is_empty(struct bpf_prog_array * array)2810 bool bpf_prog_array_is_empty(struct bpf_prog_array *array)
2811 {
2812 struct bpf_prog_array_item *item;
2813
2814 for (item = array->items; item->prog; item++)
2815 if (item->prog != &dummy_bpf_prog.prog)
2816 return false;
2817 return true;
2818 }
2819
bpf_prog_array_copy_core(struct bpf_prog_array * array,u32 * prog_ids,u32 request_cnt)2820 static bool bpf_prog_array_copy_core(struct bpf_prog_array *array,
2821 u32 *prog_ids,
2822 u32 request_cnt)
2823 {
2824 struct bpf_prog_array_item *item;
2825 int i = 0;
2826
2827 for (item = array->items; item->prog; item++) {
2828 if (item->prog == &dummy_bpf_prog.prog)
2829 continue;
2830 prog_ids[i] = item->prog->aux->id;
2831 if (++i == request_cnt) {
2832 item++;
2833 break;
2834 }
2835 }
2836
2837 return !!(item->prog);
2838 }
2839
bpf_prog_array_copy_to_user(struct bpf_prog_array * array,__u32 __user * prog_ids,u32 cnt)2840 int bpf_prog_array_copy_to_user(struct bpf_prog_array *array,
2841 __u32 __user *prog_ids, u32 cnt)
2842 {
2843 unsigned long err = 0;
2844 bool nospc;
2845 u32 *ids;
2846
2847 /* users of this function are doing:
2848 * cnt = bpf_prog_array_length();
2849 * if (cnt > 0)
2850 * bpf_prog_array_copy_to_user(..., cnt);
2851 * so below kcalloc doesn't need extra cnt > 0 check.
2852 */
2853 ids = kcalloc(cnt, sizeof(u32), GFP_USER | __GFP_NOWARN);
2854 if (!ids)
2855 return -ENOMEM;
2856 nospc = bpf_prog_array_copy_core(array, ids, cnt);
2857 err = copy_to_user(prog_ids, ids, cnt * sizeof(u32));
2858 kfree(ids);
2859 if (err)
2860 return -EFAULT;
2861 if (nospc)
2862 return -ENOSPC;
2863 return 0;
2864 }
2865
bpf_prog_array_delete_safe(struct bpf_prog_array * array,struct bpf_prog * old_prog)2866 void bpf_prog_array_delete_safe(struct bpf_prog_array *array,
2867 struct bpf_prog *old_prog)
2868 {
2869 struct bpf_prog_array_item *item;
2870
2871 for (item = array->items; item->prog; item++)
2872 if (item->prog == old_prog) {
2873 WRITE_ONCE(item->prog, &dummy_bpf_prog.prog);
2874 break;
2875 }
2876 }
2877
2878 /**
2879 * bpf_prog_array_delete_safe_at() - Replaces the program at the given
2880 * index into the program array with
2881 * a dummy no-op program.
2882 * @array: a bpf_prog_array
2883 * @index: the index of the program to replace
2884 *
2885 * Skips over dummy programs, by not counting them, when calculating
2886 * the position of the program to replace.
2887 *
2888 * Return:
2889 * * 0 - Success
2890 * * -EINVAL - Invalid index value. Must be a non-negative integer.
2891 * * -ENOENT - Index out of range
2892 */
bpf_prog_array_delete_safe_at(struct bpf_prog_array * array,int index)2893 int bpf_prog_array_delete_safe_at(struct bpf_prog_array *array, int index)
2894 {
2895 return bpf_prog_array_update_at(array, index, &dummy_bpf_prog.prog);
2896 }
2897
2898 /**
2899 * bpf_prog_array_update_at() - Updates the program at the given index
2900 * into the program array.
2901 * @array: a bpf_prog_array
2902 * @index: the index of the program to update
2903 * @prog: the program to insert into the array
2904 *
2905 * Skips over dummy programs, by not counting them, when calculating
2906 * the position of the program to update.
2907 *
2908 * Return:
2909 * * 0 - Success
2910 * * -EINVAL - Invalid index value. Must be a non-negative integer.
2911 * * -ENOENT - Index out of range
2912 */
bpf_prog_array_update_at(struct bpf_prog_array * array,int index,struct bpf_prog * prog)2913 int bpf_prog_array_update_at(struct bpf_prog_array *array, int index,
2914 struct bpf_prog *prog)
2915 {
2916 struct bpf_prog_array_item *item;
2917
2918 if (unlikely(index < 0))
2919 return -EINVAL;
2920
2921 for (item = array->items; item->prog; item++) {
2922 if (item->prog == &dummy_bpf_prog.prog)
2923 continue;
2924 if (!index) {
2925 WRITE_ONCE(item->prog, prog);
2926 return 0;
2927 }
2928 index--;
2929 }
2930 return -ENOENT;
2931 }
2932
bpf_prog_array_copy(struct bpf_prog_array * old_array,struct bpf_prog * exclude_prog,struct bpf_prog * include_prog,u64 bpf_cookie,struct bpf_prog_array ** new_array)2933 int bpf_prog_array_copy(struct bpf_prog_array *old_array,
2934 struct bpf_prog *exclude_prog,
2935 struct bpf_prog *include_prog,
2936 u64 bpf_cookie,
2937 struct bpf_prog_array **new_array)
2938 {
2939 int new_prog_cnt, carry_prog_cnt = 0;
2940 struct bpf_prog_array_item *existing, *new;
2941 struct bpf_prog_array *array;
2942 bool found_exclude = false;
2943
2944 /* Figure out how many existing progs we need to carry over to
2945 * the new array.
2946 */
2947 if (old_array) {
2948 existing = old_array->items;
2949 for (; existing->prog; existing++) {
2950 if (existing->prog == exclude_prog) {
2951 found_exclude = true;
2952 continue;
2953 }
2954 if (existing->prog != &dummy_bpf_prog.prog)
2955 carry_prog_cnt++;
2956 if (existing->prog == include_prog)
2957 return -EEXIST;
2958 }
2959 }
2960
2961 if (exclude_prog && !found_exclude)
2962 return -ENOENT;
2963
2964 /* How many progs (not NULL) will be in the new array? */
2965 new_prog_cnt = carry_prog_cnt;
2966 if (include_prog)
2967 new_prog_cnt += 1;
2968
2969 /* Do we have any prog (not NULL) in the new array? */
2970 if (!new_prog_cnt) {
2971 *new_array = NULL;
2972 return 0;
2973 }
2974
2975 /* +1 as the end of prog_array is marked with NULL */
2976 array = bpf_prog_array_alloc(new_prog_cnt + 1, GFP_KERNEL);
2977 if (!array)
2978 return -ENOMEM;
2979 new = array->items;
2980
2981 /* Fill in the new prog array */
2982 if (carry_prog_cnt) {
2983 existing = old_array->items;
2984 for (; existing->prog; existing++) {
2985 if (existing->prog == exclude_prog ||
2986 existing->prog == &dummy_bpf_prog.prog)
2987 continue;
2988
2989 new->prog = existing->prog;
2990 new->bpf_cookie = existing->bpf_cookie;
2991 new++;
2992 }
2993 }
2994 if (include_prog) {
2995 new->prog = include_prog;
2996 new->bpf_cookie = bpf_cookie;
2997 new++;
2998 }
2999 new->prog = NULL;
3000 *new_array = array;
3001 return 0;
3002 }
3003
bpf_prog_array_copy_info(struct bpf_prog_array * array,u32 * prog_ids,u32 request_cnt,u32 * prog_cnt)3004 int bpf_prog_array_copy_info(struct bpf_prog_array *array,
3005 u32 *prog_ids, u32 request_cnt,
3006 u32 *prog_cnt)
3007 {
3008 u32 cnt = 0;
3009
3010 if (array)
3011 cnt = bpf_prog_array_length(array);
3012
3013 *prog_cnt = cnt;
3014
3015 /* return early if user requested only program count or nothing to copy */
3016 if (!request_cnt || !cnt)
3017 return 0;
3018
3019 /* this function is called under trace/bpf_trace.c: bpf_event_mutex */
3020 return bpf_prog_array_copy_core(array, prog_ids, request_cnt) ? -ENOSPC
3021 : 0;
3022 }
3023
__bpf_free_used_maps(struct bpf_prog_aux * aux,struct bpf_map ** used_maps,u32 len)3024 void __bpf_free_used_maps(struct bpf_prog_aux *aux,
3025 struct bpf_map **used_maps, u32 len)
3026 {
3027 struct bpf_map *map;
3028 bool sleepable;
3029 u32 i;
3030
3031 sleepable = aux->prog->sleepable;
3032 for (i = 0; i < len; i++) {
3033 map = used_maps[i];
3034 if (map->ops->map_poke_untrack)
3035 map->ops->map_poke_untrack(map, aux);
3036 if (sleepable)
3037 atomic64_dec(&map->sleepable_refcnt);
3038 bpf_map_put(map);
3039 }
3040 }
3041
bpf_free_used_maps(struct bpf_prog_aux * aux)3042 static void bpf_free_used_maps(struct bpf_prog_aux *aux)
3043 {
3044 __bpf_free_used_maps(aux, aux->used_maps, aux->used_map_cnt);
3045 kfree(aux->used_maps);
3046 }
3047
__bpf_free_used_btfs(struct btf_mod_pair * used_btfs,u32 len)3048 void __bpf_free_used_btfs(struct btf_mod_pair *used_btfs, u32 len)
3049 {
3050 #ifdef CONFIG_BPF_SYSCALL
3051 struct btf_mod_pair *btf_mod;
3052 u32 i;
3053
3054 for (i = 0; i < len; i++) {
3055 btf_mod = &used_btfs[i];
3056 if (btf_mod->module)
3057 module_put(btf_mod->module);
3058 btf_put(btf_mod->btf);
3059 }
3060 #endif
3061 }
3062
bpf_free_used_btfs(struct bpf_prog_aux * aux)3063 static void bpf_free_used_btfs(struct bpf_prog_aux *aux)
3064 {
3065 __bpf_free_used_btfs(aux->used_btfs, aux->used_btf_cnt);
3066 kfree(aux->used_btfs);
3067 }
3068
bpf_prog_free_deferred(struct work_struct * work)3069 static void bpf_prog_free_deferred(struct work_struct *work)
3070 {
3071 struct bpf_prog_aux *aux;
3072 int i;
3073
3074 aux = container_of(work, struct bpf_prog_aux, work);
3075 #ifdef CONFIG_BPF_SYSCALL
3076 bpf_free_kfunc_btf_tab(aux->kfunc_btf_tab);
3077 bpf_prog_stream_free(aux->prog);
3078 #endif
3079 #ifdef CONFIG_CGROUP_BPF
3080 if (aux->cgroup_atype != CGROUP_BPF_ATTACH_TYPE_INVALID)
3081 bpf_cgroup_atype_put(aux->cgroup_atype);
3082 #endif
3083 bpf_free_used_maps(aux);
3084 bpf_free_used_btfs(aux);
3085 bpf_prog_disassoc_struct_ops(aux->prog);
3086 if (bpf_prog_is_dev_bound(aux))
3087 bpf_prog_dev_bound_destroy(aux->prog);
3088 #ifdef CONFIG_PERF_EVENTS
3089 if (aux->prog->has_callchain_buf)
3090 put_callchain_buffers();
3091 #endif
3092 if (aux->dst_trampoline)
3093 bpf_trampoline_put(aux->dst_trampoline);
3094 for (i = 0; i < aux->real_func_cnt; i++) {
3095 /* We can just unlink the subprog poke descriptor table as
3096 * it was originally linked to the main program and is also
3097 * released along with it.
3098 */
3099 aux->func[i]->aux->poke_tab = NULL;
3100 bpf_jit_free(aux->func[i]);
3101 }
3102 if (aux->real_func_cnt) {
3103 kfree(aux->func);
3104 bpf_prog_unlock_free(aux->prog);
3105 } else {
3106 bpf_jit_free(aux->prog);
3107 }
3108 }
3109
bpf_prog_free(struct bpf_prog * fp)3110 void bpf_prog_free(struct bpf_prog *fp)
3111 {
3112 struct bpf_prog_aux *aux = fp->aux;
3113
3114 if (aux->dst_prog)
3115 bpf_prog_put(aux->dst_prog);
3116 bpf_token_put(aux->token);
3117 INIT_WORK(&aux->work, bpf_prog_free_deferred);
3118 schedule_work(&aux->work);
3119 }
3120 EXPORT_SYMBOL_GPL(bpf_prog_free);
3121
3122 /* RNG for unprivileged user space with separated state from prandom_u32(). */
3123 static DEFINE_PER_CPU(struct rnd_state, bpf_user_rnd_state);
3124
bpf_user_rnd_init_once(void)3125 void bpf_user_rnd_init_once(void)
3126 {
3127 prandom_init_once(&bpf_user_rnd_state);
3128 }
3129
BPF_CALL_0(bpf_user_rnd_u32)3130 BPF_CALL_0(bpf_user_rnd_u32)
3131 {
3132 /* Should someone ever have the rather unwise idea to use some
3133 * of the registers passed into this function, then note that
3134 * this function is called from native eBPF and classic-to-eBPF
3135 * transformations. Register assignments from both sides are
3136 * different, f.e. classic always sets fn(ctx, A, X) here.
3137 */
3138 struct rnd_state *state;
3139 u32 res;
3140
3141 state = &get_cpu_var(bpf_user_rnd_state);
3142 res = prandom_u32_state(state);
3143 put_cpu_var(bpf_user_rnd_state);
3144
3145 return res;
3146 }
3147
BPF_CALL_0(bpf_get_raw_cpu_id)3148 BPF_CALL_0(bpf_get_raw_cpu_id)
3149 {
3150 return raw_smp_processor_id();
3151 }
3152
3153 /* Weak definitions of helper functions in case we don't have bpf syscall. */
3154 const struct bpf_func_proto bpf_map_lookup_elem_proto __weak;
3155 const struct bpf_func_proto bpf_map_update_elem_proto __weak;
3156 const struct bpf_func_proto bpf_map_delete_elem_proto __weak;
3157 const struct bpf_func_proto bpf_map_push_elem_proto __weak;
3158 const struct bpf_func_proto bpf_map_pop_elem_proto __weak;
3159 const struct bpf_func_proto bpf_map_peek_elem_proto __weak;
3160 const struct bpf_func_proto bpf_map_lookup_percpu_elem_proto __weak;
3161 const struct bpf_func_proto bpf_spin_lock_proto __weak;
3162 const struct bpf_func_proto bpf_spin_unlock_proto __weak;
3163 const struct bpf_func_proto bpf_jiffies64_proto __weak;
3164
3165 const struct bpf_func_proto bpf_get_prandom_u32_proto __weak;
3166 const struct bpf_func_proto bpf_get_smp_processor_id_proto __weak;
3167 const struct bpf_func_proto bpf_get_numa_node_id_proto __weak;
3168 const struct bpf_func_proto bpf_ktime_get_ns_proto __weak;
3169 const struct bpf_func_proto bpf_ktime_get_boot_ns_proto __weak;
3170 const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto __weak;
3171 const struct bpf_func_proto bpf_ktime_get_tai_ns_proto __weak;
3172
3173 const struct bpf_func_proto bpf_get_current_pid_tgid_proto __weak;
3174 const struct bpf_func_proto bpf_get_current_uid_gid_proto __weak;
3175 const struct bpf_func_proto bpf_get_current_comm_proto __weak;
3176 const struct bpf_func_proto bpf_get_current_cgroup_id_proto __weak;
3177 const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto __weak;
3178 const struct bpf_func_proto bpf_get_local_storage_proto __weak;
3179 const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto __weak;
3180 const struct bpf_func_proto bpf_snprintf_btf_proto __weak;
3181 const struct bpf_func_proto bpf_seq_printf_btf_proto __weak;
3182 const struct bpf_func_proto bpf_set_retval_proto __weak;
3183 const struct bpf_func_proto bpf_get_retval_proto __weak;
3184
bpf_get_trace_printk_proto(void)3185 const struct bpf_func_proto * __weak bpf_get_trace_printk_proto(void)
3186 {
3187 return NULL;
3188 }
3189
bpf_get_trace_vprintk_proto(void)3190 const struct bpf_func_proto * __weak bpf_get_trace_vprintk_proto(void)
3191 {
3192 return NULL;
3193 }
3194
bpf_get_perf_event_read_value_proto(void)3195 const struct bpf_func_proto * __weak bpf_get_perf_event_read_value_proto(void)
3196 {
3197 return NULL;
3198 }
3199
3200 u64 __weak
bpf_event_output(struct bpf_map * map,u64 flags,void * meta,u64 meta_size,void * ctx,u64 ctx_size,bpf_ctx_copy_t ctx_copy)3201 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
3202 void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
3203 {
3204 return -ENOTSUPP;
3205 }
3206 EXPORT_SYMBOL_GPL(bpf_event_output);
3207
3208 /* Always built-in helper functions. */
3209 const struct bpf_func_proto bpf_tail_call_proto = {
3210 /* func is unused for tail_call, we set it to pass the
3211 * get_helper_proto check
3212 */
3213 .func = BPF_PTR_POISON,
3214 .gpl_only = false,
3215 .ret_type = RET_VOID,
3216 .arg1_type = ARG_PTR_TO_CTX,
3217 .arg2_type = ARG_CONST_MAP_PTR,
3218 .arg3_type = ARG_ANYTHING,
3219 };
3220
3221 /* Stub for JITs that only support cBPF. eBPF programs are interpreted.
3222 * It is encouraged to implement bpf_int_jit_compile() instead, so that
3223 * eBPF and implicitly also cBPF can get JITed!
3224 */
bpf_int_jit_compile(struct bpf_verifier_env * env,struct bpf_prog * prog)3225 struct bpf_prog * __weak bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_prog *prog)
3226 {
3227 return prog;
3228 }
3229
3230 /* Stub for JITs that support eBPF. All cBPF code gets transformed into
3231 * eBPF by the kernel and is later compiled by bpf_int_jit_compile().
3232 */
bpf_jit_compile(struct bpf_prog * prog)3233 void __weak bpf_jit_compile(struct bpf_prog *prog)
3234 {
3235 }
3236
bpf_helper_changes_pkt_data(enum bpf_func_id func_id)3237 bool __weak bpf_helper_changes_pkt_data(enum bpf_func_id func_id)
3238 {
3239 return false;
3240 }
3241
3242 /* Return TRUE if the JIT backend wants verifier to enable sub-register usage
3243 * analysis code and wants explicit zero extension inserted by verifier.
3244 * Otherwise, return FALSE.
3245 *
3246 * The verifier inserts an explicit zero extension after BPF_CMPXCHGs even if
3247 * you don't override this. JITs that don't want these extra insns can detect
3248 * them using insn_is_zext.
3249 */
bpf_jit_needs_zext(void)3250 bool __weak bpf_jit_needs_zext(void)
3251 {
3252 return false;
3253 }
3254
3255 /* By default, enable the verifier's mitigations against Spectre v1 and v4 for
3256 * all archs. The value returned must not change at runtime as there is
3257 * currently no support for reloading programs that were loaded without
3258 * mitigations.
3259 */
bpf_jit_bypass_spec_v1(void)3260 bool __weak bpf_jit_bypass_spec_v1(void)
3261 {
3262 return false;
3263 }
3264
bpf_jit_bypass_spec_v4(void)3265 bool __weak bpf_jit_bypass_spec_v4(void)
3266 {
3267 return false;
3268 }
3269
3270 /* Return true if the JIT inlines the call to the helper corresponding to
3271 * the imm.
3272 *
3273 * The verifier will not patch the insn->imm for the call to the helper if
3274 * this returns true.
3275 */
bpf_jit_inlines_helper_call(s32 imm)3276 bool __weak bpf_jit_inlines_helper_call(s32 imm)
3277 {
3278 return false;
3279 }
3280
3281 /* Return TRUE if the JIT backend supports mixing bpf2bpf and tailcalls. */
bpf_jit_supports_subprog_tailcalls(void)3282 bool __weak bpf_jit_supports_subprog_tailcalls(void)
3283 {
3284 return false;
3285 }
3286
bpf_jit_supports_percpu_insn(void)3287 bool __weak bpf_jit_supports_percpu_insn(void)
3288 {
3289 return false;
3290 }
3291
bpf_jit_supports_kfunc_call(void)3292 bool __weak bpf_jit_supports_kfunc_call(void)
3293 {
3294 return false;
3295 }
3296
bpf_jit_supports_stack_args(void)3297 bool __weak bpf_jit_supports_stack_args(void)
3298 {
3299 return false;
3300 }
3301
bpf_jit_supports_far_kfunc_call(void)3302 bool __weak bpf_jit_supports_far_kfunc_call(void)
3303 {
3304 return false;
3305 }
3306
bpf_jit_supports_arena(void)3307 bool __weak bpf_jit_supports_arena(void)
3308 {
3309 return false;
3310 }
3311
bpf_jit_supports_insn(struct bpf_insn * insn,bool in_arena)3312 bool __weak bpf_jit_supports_insn(struct bpf_insn *insn, bool in_arena)
3313 {
3314 return false;
3315 }
3316
bpf_jit_supports_fsession(void)3317 bool __weak bpf_jit_supports_fsession(void)
3318 {
3319 return false;
3320 }
3321
bpf_arch_uaddress_limit(void)3322 u64 __weak bpf_arch_uaddress_limit(void)
3323 {
3324 #if defined(CONFIG_64BIT) && defined(CONFIG_ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE)
3325 return TASK_SIZE;
3326 #else
3327 return 0;
3328 #endif
3329 }
3330
3331 /* Return TRUE if the JIT backend satisfies the following two conditions:
3332 * 1) JIT backend supports atomic_xchg() on pointer-sized words.
3333 * 2) Under the specific arch, the implementation of xchg() is the same
3334 * as atomic_xchg() on pointer-sized words.
3335 */
bpf_jit_supports_ptr_xchg(void)3336 bool __weak bpf_jit_supports_ptr_xchg(void)
3337 {
3338 return false;
3339 }
3340
3341 /* To execute LD_ABS/LD_IND instructions __bpf_prog_run() may call
3342 * skb_copy_bits(), so provide a weak definition of it for NET-less config.
3343 */
skb_copy_bits(const struct sk_buff * skb,int offset,void * to,int len)3344 int __weak skb_copy_bits(const struct sk_buff *skb, int offset, void *to,
3345 int len)
3346 {
3347 return -EFAULT;
3348 }
3349
bpf_arch_text_poke(void * ip,enum bpf_text_poke_type old_t,enum bpf_text_poke_type new_t,void * old_addr,void * new_addr)3350 int __weak bpf_arch_text_poke(void *ip, enum bpf_text_poke_type old_t,
3351 enum bpf_text_poke_type new_t, void *old_addr,
3352 void *new_addr)
3353 {
3354 return -ENOTSUPP;
3355 }
3356
bpf_arch_text_copy(void * dst,void * src,size_t len)3357 void * __weak bpf_arch_text_copy(void *dst, void *src, size_t len)
3358 {
3359 return ERR_PTR(-ENOTSUPP);
3360 }
3361
bpf_arch_text_invalidate(void * dst,size_t len)3362 int __weak bpf_arch_text_invalidate(void *dst, size_t len)
3363 {
3364 return -ENOTSUPP;
3365 }
3366
bpf_jit_supports_exceptions(void)3367 bool __weak bpf_jit_supports_exceptions(void)
3368 {
3369 return false;
3370 }
3371
bpf_jit_supports_private_stack(void)3372 bool __weak bpf_jit_supports_private_stack(void)
3373 {
3374 return false;
3375 }
3376
arch_bpf_stack_walk(bool (* consume_fn)(void * cookie,u64 ip,u64 sp,u64 bp),void * cookie)3377 void __weak arch_bpf_stack_walk(bool (*consume_fn)(void *cookie, u64 ip, u64 sp, u64 bp), void *cookie)
3378 {
3379 }
3380
bpf_jit_supports_timed_may_goto(void)3381 bool __weak bpf_jit_supports_timed_may_goto(void)
3382 {
3383 return false;
3384 }
3385
arch_bpf_timed_may_goto(void)3386 u64 __weak arch_bpf_timed_may_goto(void)
3387 {
3388 return 0;
3389 }
3390
bpf_prog_report_may_goto_violation(void)3391 static noinline void bpf_prog_report_may_goto_violation(void)
3392 {
3393 #ifdef CONFIG_BPF_SYSCALL
3394 struct bpf_stream_stage ss;
3395 struct bpf_prog *prog;
3396
3397 prog = bpf_prog_find_from_stack();
3398 if (!prog)
3399 return;
3400 bpf_stream_stage(ss, prog, BPF_STDERR, ({
3401 bpf_stream_printk(ss, "ERROR: Timeout detected for may_goto instruction\n");
3402 bpf_stream_dump_stack(ss);
3403 }));
3404 #endif
3405 }
3406
bpf_check_timed_may_goto(struct bpf_timed_may_goto * p)3407 u64 bpf_check_timed_may_goto(struct bpf_timed_may_goto *p)
3408 {
3409 u64 time = ktime_get_mono_fast_ns();
3410
3411 /* Populate the timestamp for this stack frame, and refresh count. */
3412 if (!p->timestamp) {
3413 p->timestamp = time;
3414 return BPF_MAX_TIMED_LOOPS;
3415 }
3416 /* Check if we've exhausted our time slice, and zero count. */
3417 if (unlikely(time - p->timestamp >= (NSEC_PER_SEC / 4))) {
3418 bpf_prog_report_may_goto_violation();
3419 return 0;
3420 }
3421 /* Refresh the count for the stack frame. */
3422 return BPF_MAX_TIMED_LOOPS;
3423 }
3424
3425 /* for configs without MMU or 32-bit */
3426 __weak const struct bpf_map_ops arena_map_ops;
bpf_arena_get_user_vm_start(struct bpf_arena * arena)3427 __weak u64 bpf_arena_get_user_vm_start(struct bpf_arena *arena)
3428 {
3429 return 0;
3430 }
bpf_arena_get_kern_vm_start(struct bpf_arena * arena)3431 __weak u64 bpf_arena_get_kern_vm_start(struct bpf_arena *arena)
3432 {
3433 return 0;
3434 }
3435
3436 #ifdef CONFIG_BPF_SYSCALL
bpf_arena_handle_page_fault(unsigned long addr,bool is_write,unsigned long fault_ip)3437 __weak bool bpf_arena_handle_page_fault(unsigned long addr, bool is_write,
3438 unsigned long fault_ip)
3439 {
3440 return false;
3441 }
3442
bpf_global_ma_init(void)3443 static int __init bpf_global_ma_init(void)
3444 {
3445 int ret;
3446
3447 ret = bpf_mem_alloc_init(&bpf_global_ma, 0, false);
3448 bpf_global_ma_set = !ret;
3449 return ret;
3450 }
3451 late_initcall(bpf_global_ma_init);
3452 #endif
3453
3454 DEFINE_STATIC_KEY_FALSE(bpf_stats_enabled_key);
3455 EXPORT_SYMBOL(bpf_stats_enabled_key);
3456
3457 /* All definitions of tracepoints related to BPF. */
3458 #define CREATE_TRACE_POINTS
3459 #include <linux/bpf_trace.h>
3460
3461 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_exception);
3462 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_bulk_tx);
3463
3464 #ifdef CONFIG_BPF_SYSCALL
3465
bpf_get_linfo_file_line(struct btf * btf,const struct bpf_line_info * linfo,const char ** filep,const char ** linep,int * nump)3466 void bpf_get_linfo_file_line(struct btf *btf, const struct bpf_line_info *linfo,
3467 const char **filep, const char **linep, int *nump)
3468 {
3469 /* Get base component of the file path. */
3470 if (filep) {
3471 *filep = btf_name_by_offset(btf, linfo->file_name_off);
3472 *filep = kbasename(*filep);
3473 }
3474
3475 /* Obtain the source line, and strip whitespace in prefix. */
3476 if (linep) {
3477 *linep = btf_name_by_offset(btf, linfo->line_off);
3478 while (isspace(**linep))
3479 *linep += 1;
3480 }
3481
3482 if (nump)
3483 *nump = BPF_LINE_INFO_LINE_NUM(linfo->line_col);
3484 }
3485
bpf_find_linfo(const struct bpf_prog * prog,u32 insn_off)3486 const struct bpf_line_info *bpf_find_linfo(const struct bpf_prog *prog, u32 insn_off)
3487 {
3488 const struct bpf_line_info *linfo;
3489 u32 nr_linfo;
3490 int l, r, m;
3491
3492 nr_linfo = prog->aux->nr_linfo;
3493 if (!nr_linfo || insn_off >= prog->len)
3494 return NULL;
3495
3496 linfo = prog->aux->linfo;
3497 /* Loop invariant: linfo[l].insn_off <= insns_off.
3498 * linfo[0].insn_off == 0 which always satisfies above condition.
3499 * Binary search is searching for rightmost linfo entry that satisfies
3500 * the above invariant, giving us the desired record that covers given
3501 * instruction offset.
3502 */
3503 l = 0;
3504 r = nr_linfo - 1;
3505 while (l < r) {
3506 /* (r - l + 1) / 2 means we break a tie to the right, so if:
3507 * l=1, r=2, linfo[l].insn_off <= insn_off, linfo[r].insn_off > insn_off,
3508 * then m=2, we see that linfo[m].insn_off > insn_off, and so
3509 * r becomes 1 and we exit the loop with correct l==1.
3510 * If the tie was broken to the left, m=1 would end us up in
3511 * an endless loop where l and m stay at 1 and r stays at 2.
3512 */
3513 m = l + (r - l + 1) / 2;
3514 if (linfo[m].insn_off <= insn_off)
3515 l = m;
3516 else
3517 r = m - 1;
3518 }
3519
3520 return &linfo[l];
3521 }
3522
bpf_prog_get_file_line(struct bpf_prog * prog,unsigned long ip,const char ** filep,const char ** linep,int * nump)3523 int bpf_prog_get_file_line(struct bpf_prog *prog, unsigned long ip, const char **filep,
3524 const char **linep, int *nump)
3525 {
3526 int idx = -1, insn_start, insn_end, len;
3527 struct bpf_line_info *linfo;
3528 void **jited_linfo;
3529 struct btf *btf;
3530 int nr_linfo;
3531
3532 btf = prog->aux->btf;
3533 linfo = prog->aux->linfo;
3534 jited_linfo = prog->aux->jited_linfo;
3535
3536 if (!btf || !linfo || !jited_linfo)
3537 return -EINVAL;
3538 len = prog->aux->func ? prog->aux->func[prog->aux->func_idx]->len : prog->len;
3539
3540 linfo = &prog->aux->linfo[prog->aux->linfo_idx];
3541 jited_linfo = &prog->aux->jited_linfo[prog->aux->linfo_idx];
3542
3543 insn_start = linfo[0].insn_off;
3544 insn_end = insn_start + len;
3545 nr_linfo = prog->aux->nr_linfo - prog->aux->linfo_idx;
3546
3547 for (int i = 0; i < nr_linfo &&
3548 linfo[i].insn_off >= insn_start && linfo[i].insn_off < insn_end; i++) {
3549 if (jited_linfo[i] >= (void *)ip)
3550 break;
3551 idx = i;
3552 }
3553
3554 if (idx == -1)
3555 return -ENOENT;
3556
3557 bpf_get_linfo_file_line(btf, &linfo[idx], filep, linep, nump);
3558 return 0;
3559 }
3560
3561 struct walk_stack_ctx {
3562 struct bpf_prog *prog;
3563 };
3564
find_from_stack_cb(void * cookie,u64 ip,u64 sp,u64 bp)3565 static bool find_from_stack_cb(void *cookie, u64 ip, u64 sp, u64 bp)
3566 {
3567 struct walk_stack_ctx *ctxp = cookie;
3568 struct bpf_prog *prog;
3569
3570 /*
3571 * The RCU read lock is held to safely traverse the latch tree, but we
3572 * don't need its protection when accessing the prog, since it has an
3573 * active stack frame on the current stack trace, and won't disappear.
3574 */
3575 rcu_read_lock();
3576 prog = bpf_prog_ksym_find(ip);
3577 rcu_read_unlock();
3578 if (!prog)
3579 return true;
3580 /* Make sure we return the main prog if we found a subprog */
3581 ctxp->prog = prog->aux->main_prog_aux->prog;
3582 return false;
3583 }
3584
bpf_prog_find_from_stack(void)3585 struct bpf_prog *bpf_prog_find_from_stack(void)
3586 {
3587 struct walk_stack_ctx ctx = {};
3588
3589 arch_bpf_stack_walk(find_from_stack_cb, &ctx);
3590 return ctx.prog;
3591 }
3592
3593 #endif
3594