blob: 705424f029f38664625bdf25eac1974bbe41d892 [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// 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/vmalloc.h>
24#include <linux/random.h>
25#include <linux/moduleloader.h>
26#include <linux/bpf.h>
27#include <linux/btf.h>
28#include <linux/frame.h>
29#include <linux/rbtree_latch.h>
30#include <linux/kallsyms.h>
31#include <linux/rcupdate.h>
32#include <linux/perf_event.h>
33#include <linux/nospec.h>
34
35#include <asm/barrier.h>
36#include <asm/unaligned.h>
37
38/* Registers */
39#define BPF_R0 regs[BPF_REG_0]
40#define BPF_R1 regs[BPF_REG_1]
41#define BPF_R2 regs[BPF_REG_2]
42#define BPF_R3 regs[BPF_REG_3]
43#define BPF_R4 regs[BPF_REG_4]
44#define BPF_R5 regs[BPF_REG_5]
45#define BPF_R6 regs[BPF_REG_6]
46#define BPF_R7 regs[BPF_REG_7]
47#define BPF_R8 regs[BPF_REG_8]
48#define BPF_R9 regs[BPF_REG_9]
49#define BPF_R10 regs[BPF_REG_10]
50
51/* Named registers */
52#define DST regs[insn->dst_reg]
53#define SRC regs[insn->src_reg]
54#define FP regs[BPF_REG_FP]
55#define AX regs[BPF_REG_AX]
56#define ARG1 regs[BPF_REG_ARG1]
57#define CTX regs[BPF_REG_CTX]
58#define IMM insn->imm
59
60/* No hurry in this branch
61 *
62 * Exported for the bpf jit load helper.
63 */
64void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, unsigned int size)
65{
66 u8 *ptr = NULL;
67
68 if (k >= SKF_NET_OFF) {
69 ptr = skb_network_header(skb) + k - SKF_NET_OFF;
70 } else if (k >= SKF_LL_OFF) {
71 if (unlikely(!skb_mac_header_was_set(skb)))
72 return NULL;
73 ptr = skb_mac_header(skb) + k - SKF_LL_OFF;
74 }
75 if (ptr >= skb->head && ptr + size <= skb_tail_pointer(skb))
76 return ptr;
77
78 return NULL;
79}
80
81struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)
82{
83 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
84 struct bpf_prog_aux *aux;
85 struct bpf_prog *fp;
86
87 size = round_up(size, PAGE_SIZE);
88 fp = __vmalloc(size, gfp_flags, PAGE_KERNEL);
89 if (fp == NULL)
90 return NULL;
91
92 aux = kzalloc(sizeof(*aux), GFP_KERNEL | gfp_extra_flags);
93 if (aux == NULL) {
94 vfree(fp);
95 return NULL;
96 }
97
98 fp->pages = size / PAGE_SIZE;
99 fp->aux = aux;
100 fp->aux->prog = fp;
101 fp->jit_requested = ebpf_jit_enabled();
102
103 INIT_LIST_HEAD_RCU(&fp->aux->ksym_lnode);
104
105 return fp;
106}
107
108struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags)
109{
110 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
111 struct bpf_prog *prog;
112 int cpu;
113
114 prog = bpf_prog_alloc_no_stats(size, gfp_extra_flags);
115 if (!prog)
116 return NULL;
117
118 prog->aux->stats = alloc_percpu_gfp(struct bpf_prog_stats, gfp_flags);
119 if (!prog->aux->stats) {
120 kfree(prog->aux);
121 vfree(prog);
122 return NULL;
123 }
124
125 for_each_possible_cpu(cpu) {
126 struct bpf_prog_stats *pstats;
127
128 pstats = per_cpu_ptr(prog->aux->stats, cpu);
129 u64_stats_init(&pstats->syncp);
130 }
131 return prog;
132}
133EXPORT_SYMBOL_GPL(bpf_prog_alloc);
134
135int bpf_prog_alloc_jited_linfo(struct bpf_prog *prog)
136{
137 if (!prog->aux->nr_linfo || !prog->jit_requested)
138 return 0;
139
140 prog->aux->jited_linfo = kcalloc(prog->aux->nr_linfo,
141 sizeof(*prog->aux->jited_linfo),
142 GFP_KERNEL | __GFP_NOWARN);
143 if (!prog->aux->jited_linfo)
144 return -ENOMEM;
145
146 return 0;
147}
148
149void bpf_prog_free_jited_linfo(struct bpf_prog *prog)
150{
151 kfree(prog->aux->jited_linfo);
152 prog->aux->jited_linfo = NULL;
153}
154
155void bpf_prog_free_unused_jited_linfo(struct bpf_prog *prog)
156{
157 if (prog->aux->jited_linfo && !prog->aux->jited_linfo[0])
158 bpf_prog_free_jited_linfo(prog);
159}
160
161/* The jit engine is responsible to provide an array
162 * for insn_off to the jited_off mapping (insn_to_jit_off).
163 *
164 * The idx to this array is the insn_off. Hence, the insn_off
165 * here is relative to the prog itself instead of the main prog.
166 * This array has one entry for each xlated bpf insn.
167 *
168 * jited_off is the byte off to the last byte of the jited insn.
169 *
170 * Hence, with
171 * insn_start:
172 * The first bpf insn off of the prog. The insn off
173 * here is relative to the main prog.
174 * e.g. if prog is a subprog, insn_start > 0
175 * linfo_idx:
176 * The prog's idx to prog->aux->linfo and jited_linfo
177 *
178 * jited_linfo[linfo_idx] = prog->bpf_func
179 *
180 * For i > linfo_idx,
181 *
182 * jited_linfo[i] = prog->bpf_func +
183 * insn_to_jit_off[linfo[i].insn_off - insn_start - 1]
184 */
185void bpf_prog_fill_jited_linfo(struct bpf_prog *prog,
186 const u32 *insn_to_jit_off)
187{
188 u32 linfo_idx, insn_start, insn_end, nr_linfo, i;
189 const struct bpf_line_info *linfo;
190 void **jited_linfo;
191
192 if (!prog->aux->jited_linfo)
193 /* Userspace did not provide linfo */
194 return;
195
196 linfo_idx = prog->aux->linfo_idx;
197 linfo = &prog->aux->linfo[linfo_idx];
198 insn_start = linfo[0].insn_off;
199 insn_end = insn_start + prog->len;
200
201 jited_linfo = &prog->aux->jited_linfo[linfo_idx];
202 jited_linfo[0] = prog->bpf_func;
203
204 nr_linfo = prog->aux->nr_linfo - linfo_idx;
205
206 for (i = 1; i < nr_linfo && linfo[i].insn_off < insn_end; i++)
207 /* The verifier ensures that linfo[i].insn_off is
208 * strictly increasing
209 */
210 jited_linfo[i] = prog->bpf_func +
211 insn_to_jit_off[linfo[i].insn_off - insn_start - 1];
212}
213
214void bpf_prog_free_linfo(struct bpf_prog *prog)
215{
216 bpf_prog_free_jited_linfo(prog);
217 kvfree(prog->aux->linfo);
218}
219
220struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
221 gfp_t gfp_extra_flags)
222{
223 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
224 struct bpf_prog *fp;
225 u32 pages, delta;
226 int ret;
227
228 BUG_ON(fp_old == NULL);
229
230 size = round_up(size, PAGE_SIZE);
231 pages = size / PAGE_SIZE;
232 if (pages <= fp_old->pages)
233 return fp_old;
234
235 delta = pages - fp_old->pages;
236 ret = __bpf_prog_charge(fp_old->aux->user, delta);
237 if (ret)
238 return NULL;
239
240 fp = __vmalloc(size, gfp_flags, PAGE_KERNEL);
241 if (fp == NULL) {
242 __bpf_prog_uncharge(fp_old->aux->user, delta);
243 } else {
244 memcpy(fp, fp_old, fp_old->pages * PAGE_SIZE);
245 fp->pages = pages;
246 fp->aux->prog = fp;
247
248 /* We keep fp->aux from fp_old around in the new
249 * reallocated structure.
250 */
251 fp_old->aux = NULL;
252 __bpf_prog_free(fp_old);
253 }
254
255 return fp;
256}
257
258void __bpf_prog_free(struct bpf_prog *fp)
259{
260 if (fp->aux) {
261 free_percpu(fp->aux->stats);
262 kfree(fp->aux);
263 }
264 vfree(fp);
265}
266
267int bpf_prog_calc_tag(struct bpf_prog *fp)
268{
269 const u32 bits_offset = SHA_MESSAGE_BYTES - sizeof(__be64);
270 u32 raw_size = bpf_prog_tag_scratch_size(fp);
271 u32 digest[SHA_DIGEST_WORDS];
272 u32 ws[SHA_WORKSPACE_WORDS];
273 u32 i, bsize, psize, blocks;
274 struct bpf_insn *dst;
275 bool was_ld_map;
276 u8 *raw, *todo;
277 __be32 *result;
278 __be64 *bits;
279
280 raw = vmalloc(raw_size);
281 if (!raw)
282 return -ENOMEM;
283
284 sha_init(digest);
285 memset(ws, 0, sizeof(ws));
286
287 /* We need to take out the map fd for the digest calculation
288 * since they are unstable from user space side.
289 */
290 dst = (void *)raw;
291 for (i = 0, was_ld_map = false; i < fp->len; i++) {
292 dst[i] = fp->insnsi[i];
293 if (!was_ld_map &&
294 dst[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
295 (dst[i].src_reg == BPF_PSEUDO_MAP_FD ||
296 dst[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
297 was_ld_map = true;
298 dst[i].imm = 0;
299 } else if (was_ld_map &&
300 dst[i].code == 0 &&
301 dst[i].dst_reg == 0 &&
302 dst[i].src_reg == 0 &&
303 dst[i].off == 0) {
304 was_ld_map = false;
305 dst[i].imm = 0;
306 } else {
307 was_ld_map = false;
308 }
309 }
310
311 psize = bpf_prog_insn_size(fp);
312 memset(&raw[psize], 0, raw_size - psize);
313 raw[psize++] = 0x80;
314
315 bsize = round_up(psize, SHA_MESSAGE_BYTES);
316 blocks = bsize / SHA_MESSAGE_BYTES;
317 todo = raw;
318 if (bsize - psize >= sizeof(__be64)) {
319 bits = (__be64 *)(todo + bsize - sizeof(__be64));
320 } else {
321 bits = (__be64 *)(todo + bsize + bits_offset);
322 blocks++;
323 }
324 *bits = cpu_to_be64((psize - 1) << 3);
325
326 while (blocks--) {
327 sha_transform(digest, todo, ws);
328 todo += SHA_MESSAGE_BYTES;
329 }
330
331 result = (__force __be32 *)digest;
332 for (i = 0; i < SHA_DIGEST_WORDS; i++)
333 result[i] = cpu_to_be32(digest[i]);
334 memcpy(fp->tag, result, sizeof(fp->tag));
335
336 vfree(raw);
337 return 0;
338}
339
340static int bpf_adj_delta_to_imm(struct bpf_insn *insn, u32 pos, s32 end_old,
341 s32 end_new, s32 curr, const bool probe_pass)
342{
343 const s64 imm_min = S32_MIN, imm_max = S32_MAX;
344 s32 delta = end_new - end_old;
345 s64 imm = insn->imm;
346
347 if (curr < pos && curr + imm + 1 >= end_old)
348 imm += delta;
349 else if (curr >= end_new && curr + imm + 1 < end_new)
350 imm -= delta;
351 if (imm < imm_min || imm > imm_max)
352 return -ERANGE;
353 if (!probe_pass)
354 insn->imm = imm;
355 return 0;
356}
357
358static int bpf_adj_delta_to_off(struct bpf_insn *insn, u32 pos, s32 end_old,
359 s32 end_new, s32 curr, const bool probe_pass)
360{
361 const s32 off_min = S16_MIN, off_max = S16_MAX;
362 s32 delta = end_new - end_old;
363 s32 off = insn->off;
364
365 if (curr < pos && curr + off + 1 >= end_old)
366 off += delta;
367 else if (curr >= end_new && curr + off + 1 < end_new)
368 off -= delta;
369 if (off < off_min || off > off_max)
370 return -ERANGE;
371 if (!probe_pass)
372 insn->off = off;
373 return 0;
374}
375
376static int bpf_adj_branches(struct bpf_prog *prog, u32 pos, s32 end_old,
377 s32 end_new, const bool probe_pass)
378{
379 u32 i, insn_cnt = prog->len + (probe_pass ? end_new - end_old : 0);
380 struct bpf_insn *insn = prog->insnsi;
381 int ret = 0;
382
383 for (i = 0; i < insn_cnt; i++, insn++) {
384 u8 code;
385
386 /* In the probing pass we still operate on the original,
387 * unpatched image in order to check overflows before we
388 * do any other adjustments. Therefore skip the patchlet.
389 */
390 if (probe_pass && i == pos) {
391 i = end_new;
392 insn = prog->insnsi + end_old;
393 }
394 code = insn->code;
395 if ((BPF_CLASS(code) != BPF_JMP &&
396 BPF_CLASS(code) != BPF_JMP32) ||
397 BPF_OP(code) == BPF_EXIT)
398 continue;
399 /* Adjust offset of jmps if we cross patch boundaries. */
400 if (BPF_OP(code) == BPF_CALL) {
401 if (insn->src_reg != BPF_PSEUDO_CALL)
402 continue;
403 ret = bpf_adj_delta_to_imm(insn, pos, end_old,
404 end_new, i, probe_pass);
405 } else {
406 ret = bpf_adj_delta_to_off(insn, pos, end_old,
407 end_new, i, probe_pass);
408 }
409 if (ret)
410 break;
411 }
412
413 return ret;
414}
415
416static void bpf_adj_linfo(struct bpf_prog *prog, u32 off, u32 delta)
417{
418 struct bpf_line_info *linfo;
419 u32 i, nr_linfo;
420
421 nr_linfo = prog->aux->nr_linfo;
422 if (!nr_linfo || !delta)
423 return;
424
425 linfo = prog->aux->linfo;
426
427 for (i = 0; i < nr_linfo; i++)
428 if (off < linfo[i].insn_off)
429 break;
430
431 /* Push all off < linfo[i].insn_off by delta */
432 for (; i < nr_linfo; i++)
433 linfo[i].insn_off += delta;
434}
435
436struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off,
437 const struct bpf_insn *patch, u32 len)
438{
439 u32 insn_adj_cnt, insn_rest, insn_delta = len - 1;
440 const u32 cnt_max = S16_MAX;
441 struct bpf_prog *prog_adj;
442 int err;
443
444 /* Since our patchlet doesn't expand the image, we're done. */
445 if (insn_delta == 0) {
446 memcpy(prog->insnsi + off, patch, sizeof(*patch));
447 return prog;
448 }
449
450 insn_adj_cnt = prog->len + insn_delta;
451
452 /* Reject anything that would potentially let the insn->off
453 * target overflow when we have excessive program expansions.
454 * We need to probe here before we do any reallocation where
455 * we afterwards may not fail anymore.
456 */
457 if (insn_adj_cnt > cnt_max &&
458 (err = bpf_adj_branches(prog, off, off + 1, off + len, true)))
459 return ERR_PTR(err);
460
461 /* Several new instructions need to be inserted. Make room
462 * for them. Likely, there's no need for a new allocation as
463 * last page could have large enough tailroom.
464 */
465 prog_adj = bpf_prog_realloc(prog, bpf_prog_size(insn_adj_cnt),
466 GFP_USER);
467 if (!prog_adj)
468 return ERR_PTR(-ENOMEM);
469
470 prog_adj->len = insn_adj_cnt;
471
472 /* Patching happens in 3 steps:
473 *
474 * 1) Move over tail of insnsi from next instruction onwards,
475 * so we can patch the single target insn with one or more
476 * new ones (patching is always from 1 to n insns, n > 0).
477 * 2) Inject new instructions at the target location.
478 * 3) Adjust branch offsets if necessary.
479 */
480 insn_rest = insn_adj_cnt - off - len;
481
482 memmove(prog_adj->insnsi + off + len, prog_adj->insnsi + off + 1,
483 sizeof(*patch) * insn_rest);
484 memcpy(prog_adj->insnsi + off, patch, sizeof(*patch) * len);
485
486 /* We are guaranteed to not fail at this point, otherwise
487 * the ship has sailed to reverse to the original state. An
488 * overflow cannot happen at this point.
489 */
490 BUG_ON(bpf_adj_branches(prog_adj, off, off + 1, off + len, false));
491
492 bpf_adj_linfo(prog_adj, off, insn_delta);
493
494 return prog_adj;
495}
496
497int bpf_remove_insns(struct bpf_prog *prog, u32 off, u32 cnt)
498{
499 int err;
500
501 /* Branch offsets can't overflow when program is shrinking, no need
502 * to call bpf_adj_branches(..., true) here
503 */
504 memmove(prog->insnsi + off, prog->insnsi + off + cnt,
505 sizeof(struct bpf_insn) * (prog->len - off - cnt));
506 prog->len -= cnt;
507
508 err = bpf_adj_branches(prog, off, off + cnt, off, false);
509 WARN_ON_ONCE(err);
510 return err;
511}
512
513static void bpf_prog_kallsyms_del_subprogs(struct bpf_prog *fp)
514{
515 int i;
516
517 for (i = 0; i < fp->aux->func_cnt; i++)
518 bpf_prog_kallsyms_del(fp->aux->func[i]);
519}
520
521void bpf_prog_kallsyms_del_all(struct bpf_prog *fp)
522{
523 bpf_prog_kallsyms_del_subprogs(fp);
524 bpf_prog_kallsyms_del(fp);
525}
526
527#ifdef CONFIG_BPF_JIT
528/* All BPF JIT sysctl knobs here. */
529int bpf_jit_enable __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_ALWAYS_ON);
530int bpf_jit_harden __read_mostly;
531int bpf_jit_kallsyms __read_mostly;
532long bpf_jit_limit __read_mostly;
533long bpf_jit_limit_max __read_mostly;
534
535static __always_inline void
536bpf_get_prog_addr_region(const struct bpf_prog *prog,
537 unsigned long *symbol_start,
538 unsigned long *symbol_end)
539{
540 const struct bpf_binary_header *hdr = bpf_jit_binary_hdr(prog);
541 unsigned long addr = (unsigned long)hdr;
542
543 WARN_ON_ONCE(!bpf_prog_ebpf_jited(prog));
544
545 *symbol_start = addr;
546 *symbol_end = addr + hdr->pages * PAGE_SIZE;
547}
548
549void bpf_get_prog_name(const struct bpf_prog *prog, char *sym)
550{
551 const char *end = sym + KSYM_NAME_LEN;
552 const struct btf_type *type;
553 const char *func_name;
554
555 BUILD_BUG_ON(sizeof("bpf_prog_") +
556 sizeof(prog->tag) * 2 +
557 /* name has been null terminated.
558 * We should need +1 for the '_' preceding
559 * the name. However, the null character
560 * is double counted between the name and the
561 * sizeof("bpf_prog_") above, so we omit
562 * the +1 here.
563 */
564 sizeof(prog->aux->name) > KSYM_NAME_LEN);
565
566 sym += snprintf(sym, KSYM_NAME_LEN, "bpf_prog_");
567 sym = bin2hex(sym, prog->tag, sizeof(prog->tag));
568
569 /* prog->aux->name will be ignored if full btf name is available */
570 if (prog->aux->func_info_cnt) {
571 type = btf_type_by_id(prog->aux->btf,
572 prog->aux->func_info[prog->aux->func_idx].type_id);
573 func_name = btf_name_by_offset(prog->aux->btf, type->name_off);
574 snprintf(sym, (size_t)(end - sym), "_%s", func_name);
575 return;
576 }
577
578 if (prog->aux->name[0])
579 snprintf(sym, (size_t)(end - sym), "_%s", prog->aux->name);
580 else
581 *sym = 0;
582}
583
584static __always_inline unsigned long
585bpf_get_prog_addr_start(struct latch_tree_node *n)
586{
587 unsigned long symbol_start, symbol_end;
588 const struct bpf_prog_aux *aux;
589
590 aux = container_of(n, struct bpf_prog_aux, ksym_tnode);
591 bpf_get_prog_addr_region(aux->prog, &symbol_start, &symbol_end);
592
593 return symbol_start;
594}
595
596static __always_inline bool bpf_tree_less(struct latch_tree_node *a,
597 struct latch_tree_node *b)
598{
599 return bpf_get_prog_addr_start(a) < bpf_get_prog_addr_start(b);
600}
601
602static __always_inline int bpf_tree_comp(void *key, struct latch_tree_node *n)
603{
604 unsigned long val = (unsigned long)key;
605 unsigned long symbol_start, symbol_end;
606 const struct bpf_prog_aux *aux;
607
608 aux = container_of(n, struct bpf_prog_aux, ksym_tnode);
609 bpf_get_prog_addr_region(aux->prog, &symbol_start, &symbol_end);
610
611 if (val < symbol_start)
612 return -1;
613 if (val >= symbol_end)
614 return 1;
615
616 return 0;
617}
618
619static const struct latch_tree_ops bpf_tree_ops = {
620 .less = bpf_tree_less,
621 .comp = bpf_tree_comp,
622};
623
624static DEFINE_SPINLOCK(bpf_lock);
625static LIST_HEAD(bpf_kallsyms);
626static struct latch_tree_root bpf_tree __cacheline_aligned;
627
628static void bpf_prog_ksym_node_add(struct bpf_prog_aux *aux)
629{
630 WARN_ON_ONCE(!list_empty(&aux->ksym_lnode));
631 list_add_tail_rcu(&aux->ksym_lnode, &bpf_kallsyms);
632 latch_tree_insert(&aux->ksym_tnode, &bpf_tree, &bpf_tree_ops);
633}
634
635static void bpf_prog_ksym_node_del(struct bpf_prog_aux *aux)
636{
637 if (list_empty(&aux->ksym_lnode))
638 return;
639
640 latch_tree_erase(&aux->ksym_tnode, &bpf_tree, &bpf_tree_ops);
641 list_del_rcu(&aux->ksym_lnode);
642}
643
644static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp)
645{
646 return fp->jited && !bpf_prog_was_classic(fp);
647}
648
649static bool bpf_prog_kallsyms_verify_off(const struct bpf_prog *fp)
650{
651 return list_empty(&fp->aux->ksym_lnode) ||
652 fp->aux->ksym_lnode.prev == LIST_POISON2;
653}
654
655void bpf_prog_kallsyms_add(struct bpf_prog *fp)
656{
657 if (!bpf_prog_kallsyms_candidate(fp) ||
658 !capable(CAP_SYS_ADMIN))
659 return;
660
661 spin_lock_bh(&bpf_lock);
662 bpf_prog_ksym_node_add(fp->aux);
663 spin_unlock_bh(&bpf_lock);
664}
665
666void bpf_prog_kallsyms_del(struct bpf_prog *fp)
667{
668 if (!bpf_prog_kallsyms_candidate(fp))
669 return;
670
671 spin_lock_bh(&bpf_lock);
672 bpf_prog_ksym_node_del(fp->aux);
673 spin_unlock_bh(&bpf_lock);
674}
675
676static struct bpf_prog *bpf_prog_kallsyms_find(unsigned long addr)
677{
678 struct latch_tree_node *n;
679
680 if (!bpf_jit_kallsyms_enabled())
681 return NULL;
682
683 n = latch_tree_find((void *)addr, &bpf_tree, &bpf_tree_ops);
684 return n ?
685 container_of(n, struct bpf_prog_aux, ksym_tnode)->prog :
686 NULL;
687}
688
689const char *__bpf_address_lookup(unsigned long addr, unsigned long *size,
690 unsigned long *off, char *sym)
691{
692 unsigned long symbol_start, symbol_end;
693 struct bpf_prog *prog;
694 char *ret = NULL;
695
696 rcu_read_lock();
697 prog = bpf_prog_kallsyms_find(addr);
698 if (prog) {
699 bpf_get_prog_addr_region(prog, &symbol_start, &symbol_end);
700 bpf_get_prog_name(prog, sym);
701
702 ret = sym;
703 if (size)
704 *size = symbol_end - symbol_start;
705 if (off)
706 *off = addr - symbol_start;
707 }
708 rcu_read_unlock();
709
710 return ret;
711}
712
713bool is_bpf_text_address(unsigned long addr)
714{
715 bool ret;
716
717 rcu_read_lock();
718 ret = bpf_prog_kallsyms_find(addr) != NULL;
719 rcu_read_unlock();
720
721 return ret;
722}
723
724int bpf_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
725 char *sym)
726{
727 struct bpf_prog_aux *aux;
728 unsigned int it = 0;
729 int ret = -ERANGE;
730
731 if (!bpf_jit_kallsyms_enabled())
732 return ret;
733
734 rcu_read_lock();
735 list_for_each_entry_rcu(aux, &bpf_kallsyms, ksym_lnode) {
736 if (it++ != symnum)
737 continue;
738
739 bpf_get_prog_name(aux->prog, sym);
740
741 *value = (unsigned long)aux->prog->bpf_func;
742 *type = BPF_SYM_ELF_TYPE;
743
744 ret = 0;
745 break;
746 }
747 rcu_read_unlock();
748
749 return ret;
750}
751
752static atomic_long_t bpf_jit_current;
753
754/* Can be overridden by an arch's JIT compiler if it has a custom,
755 * dedicated BPF backend memory area, or if neither of the two
756 * below apply.
757 */
758u64 __weak bpf_jit_alloc_exec_limit(void)
759{
760#if defined(MODULES_VADDR)
761 return MODULES_END - MODULES_VADDR;
762#else
763 return VMALLOC_END - VMALLOC_START;
764#endif
765}
766
767static int __init bpf_jit_charge_init(void)
768{
769 /* Only used as heuristic here to derive limit. */
770 bpf_jit_limit_max = bpf_jit_alloc_exec_limit();
771 bpf_jit_limit = min_t(u64, round_up(bpf_jit_limit_max >> 1,
772 PAGE_SIZE), LONG_MAX);
773 return 0;
774}
775pure_initcall(bpf_jit_charge_init);
776
777static int bpf_jit_charge_modmem(u32 pages)
778{
779 if (atomic_long_add_return(pages, &bpf_jit_current) >
780 (bpf_jit_limit >> PAGE_SHIFT)) {
781 if (!capable(CAP_SYS_ADMIN)) {
782 atomic_long_sub(pages, &bpf_jit_current);
783 return -EPERM;
784 }
785 }
786
787 return 0;
788}
789
790static void bpf_jit_uncharge_modmem(u32 pages)
791{
792 atomic_long_sub(pages, &bpf_jit_current);
793}
794
795void *__weak bpf_jit_alloc_exec(unsigned long size)
796{
797 return module_alloc(size);
798}
799
800void __weak bpf_jit_free_exec(void *addr)
801{
802 module_memfree(addr);
803}
804
805#if IS_ENABLED(CONFIG_BPF_JIT) && IS_ENABLED(CONFIG_CFI_CLANG)
806bool __weak arch_bpf_jit_check_func(const struct bpf_prog *prog)
807{
808 return true;
809}
810EXPORT_SYMBOL_GPL(arch_bpf_jit_check_func);
811#endif
812
813struct bpf_binary_header *
814bpf_jit_binary_alloc(unsigned int proglen, u8 **image_ptr,
815 unsigned int alignment,
816 bpf_jit_fill_hole_t bpf_fill_ill_insns)
817{
818 struct bpf_binary_header *hdr;
819 u32 size, hole, start, pages;
820
821 /* Most of BPF filters are really small, but if some of them
822 * fill a page, allow at least 128 extra bytes to insert a
823 * random section of illegal instructions.
824 */
825 size = round_up(proglen + sizeof(*hdr) + 128, PAGE_SIZE);
826 pages = size / PAGE_SIZE;
827
828 if (bpf_jit_charge_modmem(pages))
829 return NULL;
830 hdr = bpf_jit_alloc_exec(size);
831 if (!hdr) {
832 bpf_jit_uncharge_modmem(pages);
833 return NULL;
834 }
835
836 /* Fill space with illegal/arch-dep instructions. */
837 bpf_fill_ill_insns(hdr, size);
838
839 bpf_jit_set_header_magic(hdr);
840 hdr->pages = pages;
841 hole = min_t(unsigned int, size - (proglen + sizeof(*hdr)),
842 PAGE_SIZE - sizeof(*hdr));
843 start = (get_random_int() % hole) & ~(alignment - 1);
844
845 /* Leave a random number of instructions before BPF code. */
846 *image_ptr = &hdr->image[start];
847
848 return hdr;
849}
850
851void bpf_jit_binary_free(struct bpf_binary_header *hdr)
852{
853 u32 pages = hdr->pages;
854
855 bpf_jit_free_exec(hdr);
856 bpf_jit_uncharge_modmem(pages);
857}
858
859/* This symbol is only overridden by archs that have different
860 * requirements than the usual eBPF JITs, f.e. when they only
861 * implement cBPF JIT, do not set images read-only, etc.
862 */
863void __weak bpf_jit_free(struct bpf_prog *fp)
864{
865 if (fp->jited) {
866 struct bpf_binary_header *hdr = bpf_jit_binary_hdr(fp);
867
868 bpf_jit_binary_free(hdr);
869
870 WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(fp));
871 }
872
873 bpf_prog_unlock_free(fp);
874}
875
876int bpf_jit_get_func_addr(const struct bpf_prog *prog,
877 const struct bpf_insn *insn, bool extra_pass,
878 u64 *func_addr, bool *func_addr_fixed)
879{
880 s16 off = insn->off;
881 s32 imm = insn->imm;
882 u8 *addr;
883
884 *func_addr_fixed = insn->src_reg != BPF_PSEUDO_CALL;
885 if (!*func_addr_fixed) {
886 /* Place-holder address till the last pass has collected
887 * all addresses for JITed subprograms in which case we
888 * can pick them up from prog->aux.
889 */
890 if (!extra_pass)
891 addr = NULL;
892 else if (prog->aux->func &&
893 off >= 0 && off < prog->aux->func_cnt)
894 addr = (u8 *)prog->aux->func[off]->bpf_func;
895 else
896 return -EINVAL;
897 } else {
898 /* Address of a BPF helper call. Since part of the core
899 * kernel, it's always at a fixed location. __bpf_call_base
900 * and the helper with imm relative to it are both in core
901 * kernel.
902 */
903 addr = (u8 *)__bpf_call_base + imm;
904 }
905
906 *func_addr = (unsigned long)addr;
907 return 0;
908}
909
910static int bpf_jit_blind_insn(const struct bpf_insn *from,
911 const struct bpf_insn *aux,
912 struct bpf_insn *to_buff,
913 bool emit_zext)
914{
915 struct bpf_insn *to = to_buff;
916 u32 imm_rnd = get_random_int();
917 s16 off;
918
919 BUILD_BUG_ON(BPF_REG_AX + 1 != MAX_BPF_JIT_REG);
920 BUILD_BUG_ON(MAX_BPF_REG + 1 != MAX_BPF_JIT_REG);
921
922 /* Constraints on AX register:
923 *
924 * AX register is inaccessible from user space. It is mapped in
925 * all JITs, and used here for constant blinding rewrites. It is
926 * typically "stateless" meaning its contents are only valid within
927 * the executed instruction, but not across several instructions.
928 * There are a few exceptions however which are further detailed
929 * below.
930 *
931 * Constant blinding is only used by JITs, not in the interpreter.
932 * The interpreter uses AX in some occasions as a local temporary
933 * register e.g. in DIV or MOD instructions.
934 *
935 * In restricted circumstances, the verifier can also use the AX
936 * register for rewrites as long as they do not interfere with
937 * the above cases!
938 */
939 if (from->dst_reg == BPF_REG_AX || from->src_reg == BPF_REG_AX)
940 goto out;
941
942 if (from->imm == 0 &&
943 (from->code == (BPF_ALU | BPF_MOV | BPF_K) ||
944 from->code == (BPF_ALU64 | BPF_MOV | BPF_K))) {
945 *to++ = BPF_ALU64_REG(BPF_XOR, from->dst_reg, from->dst_reg);
946 goto out;
947 }
948
949 switch (from->code) {
950 case BPF_ALU | BPF_ADD | BPF_K:
951 case BPF_ALU | BPF_SUB | BPF_K:
952 case BPF_ALU | BPF_AND | BPF_K:
953 case BPF_ALU | BPF_OR | BPF_K:
954 case BPF_ALU | BPF_XOR | BPF_K:
955 case BPF_ALU | BPF_MUL | BPF_K:
956 case BPF_ALU | BPF_MOV | BPF_K:
957 case BPF_ALU | BPF_DIV | BPF_K:
958 case BPF_ALU | BPF_MOD | BPF_K:
959 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
960 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
961 *to++ = BPF_ALU32_REG(from->code, from->dst_reg, BPF_REG_AX);
962 break;
963
964 case BPF_ALU64 | BPF_ADD | BPF_K:
965 case BPF_ALU64 | BPF_SUB | BPF_K:
966 case BPF_ALU64 | BPF_AND | BPF_K:
967 case BPF_ALU64 | BPF_OR | BPF_K:
968 case BPF_ALU64 | BPF_XOR | BPF_K:
969 case BPF_ALU64 | BPF_MUL | BPF_K:
970 case BPF_ALU64 | BPF_MOV | BPF_K:
971 case BPF_ALU64 | BPF_DIV | BPF_K:
972 case BPF_ALU64 | BPF_MOD | BPF_K:
973 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
974 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
975 *to++ = BPF_ALU64_REG(from->code, from->dst_reg, BPF_REG_AX);
976 break;
977
978 case BPF_JMP | BPF_JEQ | BPF_K:
979 case BPF_JMP | BPF_JNE | BPF_K:
980 case BPF_JMP | BPF_JGT | BPF_K:
981 case BPF_JMP | BPF_JLT | BPF_K:
982 case BPF_JMP | BPF_JGE | BPF_K:
983 case BPF_JMP | BPF_JLE | BPF_K:
984 case BPF_JMP | BPF_JSGT | BPF_K:
985 case BPF_JMP | BPF_JSLT | BPF_K:
986 case BPF_JMP | BPF_JSGE | BPF_K:
987 case BPF_JMP | BPF_JSLE | BPF_K:
988 case BPF_JMP | BPF_JSET | BPF_K:
989 /* Accommodate for extra offset in case of a backjump. */
990 off = from->off;
991 if (off < 0)
992 off -= 2;
993 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
994 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
995 *to++ = BPF_JMP_REG(from->code, from->dst_reg, BPF_REG_AX, off);
996 break;
997
998 case BPF_JMP32 | BPF_JEQ | BPF_K:
999 case BPF_JMP32 | BPF_JNE | BPF_K:
1000 case BPF_JMP32 | BPF_JGT | BPF_K:
1001 case BPF_JMP32 | BPF_JLT | BPF_K:
1002 case BPF_JMP32 | BPF_JGE | BPF_K:
1003 case BPF_JMP32 | BPF_JLE | BPF_K:
1004 case BPF_JMP32 | BPF_JSGT | BPF_K:
1005 case BPF_JMP32 | BPF_JSLT | BPF_K:
1006 case BPF_JMP32 | BPF_JSGE | BPF_K:
1007 case BPF_JMP32 | BPF_JSLE | BPF_K:
1008 case BPF_JMP32 | BPF_JSET | BPF_K:
1009 /* Accommodate for extra offset in case of a backjump. */
1010 off = from->off;
1011 if (off < 0)
1012 off -= 2;
1013 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1014 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1015 *to++ = BPF_JMP32_REG(from->code, from->dst_reg, BPF_REG_AX,
1016 off);
1017 break;
1018
1019 case BPF_LD | BPF_IMM | BPF_DW:
1020 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[1].imm);
1021 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1022 *to++ = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
1023 *to++ = BPF_ALU64_REG(BPF_MOV, aux[0].dst_reg, BPF_REG_AX);
1024 break;
1025 case 0: /* Part 2 of BPF_LD | BPF_IMM | BPF_DW. */
1026 *to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[0].imm);
1027 *to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1028 if (emit_zext)
1029 *to++ = BPF_ZEXT_REG(BPF_REG_AX);
1030 *to++ = BPF_ALU64_REG(BPF_OR, aux[0].dst_reg, BPF_REG_AX);
1031 break;
1032
1033 case BPF_ST | BPF_MEM | BPF_DW:
1034 case BPF_ST | BPF_MEM | BPF_W:
1035 case BPF_ST | BPF_MEM | BPF_H:
1036 case BPF_ST | BPF_MEM | BPF_B:
1037 *to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1038 *to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1039 *to++ = BPF_STX_MEM(from->code, from->dst_reg, BPF_REG_AX, from->off);
1040 break;
1041 }
1042out:
1043 return to - to_buff;
1044}
1045
1046static struct bpf_prog *bpf_prog_clone_create(struct bpf_prog *fp_other,
1047 gfp_t gfp_extra_flags)
1048{
1049 gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
1050 struct bpf_prog *fp;
1051
1052 fp = __vmalloc(fp_other->pages * PAGE_SIZE, gfp_flags, PAGE_KERNEL);
1053 if (fp != NULL) {
1054 /* aux->prog still points to the fp_other one, so
1055 * when promoting the clone to the real program,
1056 * this still needs to be adapted.
1057 */
1058 memcpy(fp, fp_other, fp_other->pages * PAGE_SIZE);
1059 }
1060
1061 return fp;
1062}
1063
1064static void bpf_prog_clone_free(struct bpf_prog *fp)
1065{
1066 /* aux was stolen by the other clone, so we cannot free
1067 * it from this path! It will be freed eventually by the
1068 * other program on release.
1069 *
1070 * At this point, we don't need a deferred release since
1071 * clone is guaranteed to not be locked.
1072 */
1073 fp->aux = NULL;
1074 __bpf_prog_free(fp);
1075}
1076
1077void bpf_jit_prog_release_other(struct bpf_prog *fp, struct bpf_prog *fp_other)
1078{
1079 /* We have to repoint aux->prog to self, as we don't
1080 * know whether fp here is the clone or the original.
1081 */
1082 fp->aux->prog = fp;
1083 bpf_prog_clone_free(fp_other);
1084}
1085
1086struct bpf_prog *bpf_jit_blind_constants(struct bpf_prog *prog)
1087{
1088 struct bpf_insn insn_buff[16], aux[2];
1089 struct bpf_prog *clone, *tmp;
1090 int insn_delta, insn_cnt;
1091 struct bpf_insn *insn;
1092 int i, rewritten;
1093
1094 if (!bpf_jit_blinding_enabled(prog) || prog->blinded)
1095 return prog;
1096
1097 clone = bpf_prog_clone_create(prog, GFP_USER);
1098 if (!clone)
1099 return ERR_PTR(-ENOMEM);
1100
1101 insn_cnt = clone->len;
1102 insn = clone->insnsi;
1103
1104 for (i = 0; i < insn_cnt; i++, insn++) {
1105 /* We temporarily need to hold the original ld64 insn
1106 * so that we can still access the first part in the
1107 * second blinding run.
1108 */
1109 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW) &&
1110 insn[1].code == 0)
1111 memcpy(aux, insn, sizeof(aux));
1112
1113 rewritten = bpf_jit_blind_insn(insn, aux, insn_buff,
1114 clone->aux->verifier_zext);
1115 if (!rewritten)
1116 continue;
1117
1118 tmp = bpf_patch_insn_single(clone, i, insn_buff, rewritten);
1119 if (IS_ERR(tmp)) {
1120 /* Patching may have repointed aux->prog during
1121 * realloc from the original one, so we need to
1122 * fix it up here on error.
1123 */
1124 bpf_jit_prog_release_other(prog, clone);
1125 return tmp;
1126 }
1127
1128 clone = tmp;
1129 insn_delta = rewritten - 1;
1130
1131 /* Walk new program and skip insns we just inserted. */
1132 insn = clone->insnsi + i + insn_delta;
1133 insn_cnt += insn_delta;
1134 i += insn_delta;
1135 }
1136
1137 clone->blinded = 1;
1138 return clone;
1139}
1140#endif /* CONFIG_BPF_JIT */
1141
1142/* Base function for offset calculation. Needs to go into .text section,
1143 * therefore keeping it non-static as well; will also be used by JITs
1144 * anyway later on, so do not let the compiler omit it. This also needs
1145 * to go into kallsyms for correlation from e.g. bpftool, so naming
1146 * must not change.
1147 */
1148noinline u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
1149{
1150 return 0;
1151}
1152EXPORT_SYMBOL_GPL(__bpf_call_base);
1153
1154/* All UAPI available opcodes. */
1155#define BPF_INSN_MAP(INSN_2, INSN_3) \
1156 /* 32 bit ALU operations. */ \
1157 /* Register based. */ \
1158 INSN_3(ALU, ADD, X), \
1159 INSN_3(ALU, SUB, X), \
1160 INSN_3(ALU, AND, X), \
1161 INSN_3(ALU, OR, X), \
1162 INSN_3(ALU, LSH, X), \
1163 INSN_3(ALU, RSH, X), \
1164 INSN_3(ALU, XOR, X), \
1165 INSN_3(ALU, MUL, X), \
1166 INSN_3(ALU, MOV, X), \
1167 INSN_3(ALU, ARSH, X), \
1168 INSN_3(ALU, DIV, X), \
1169 INSN_3(ALU, MOD, X), \
1170 INSN_2(ALU, NEG), \
1171 INSN_3(ALU, END, TO_BE), \
1172 INSN_3(ALU, END, TO_LE), \
1173 /* Immediate based. */ \
1174 INSN_3(ALU, ADD, K), \
1175 INSN_3(ALU, SUB, K), \
1176 INSN_3(ALU, AND, K), \
1177 INSN_3(ALU, OR, K), \
1178 INSN_3(ALU, LSH, K), \
1179 INSN_3(ALU, RSH, K), \
1180 INSN_3(ALU, XOR, K), \
1181 INSN_3(ALU, MUL, K), \
1182 INSN_3(ALU, MOV, K), \
1183 INSN_3(ALU, ARSH, K), \
1184 INSN_3(ALU, DIV, K), \
1185 INSN_3(ALU, MOD, K), \
1186 /* 64 bit ALU operations. */ \
1187 /* Register based. */ \
1188 INSN_3(ALU64, ADD, X), \
1189 INSN_3(ALU64, SUB, X), \
1190 INSN_3(ALU64, AND, X), \
1191 INSN_3(ALU64, OR, X), \
1192 INSN_3(ALU64, LSH, X), \
1193 INSN_3(ALU64, RSH, X), \
1194 INSN_3(ALU64, XOR, X), \
1195 INSN_3(ALU64, MUL, X), \
1196 INSN_3(ALU64, MOV, X), \
1197 INSN_3(ALU64, ARSH, X), \
1198 INSN_3(ALU64, DIV, X), \
1199 INSN_3(ALU64, MOD, X), \
1200 INSN_2(ALU64, NEG), \
1201 /* Immediate based. */ \
1202 INSN_3(ALU64, ADD, K), \
1203 INSN_3(ALU64, SUB, K), \
1204 INSN_3(ALU64, AND, K), \
1205 INSN_3(ALU64, OR, K), \
1206 INSN_3(ALU64, LSH, K), \
1207 INSN_3(ALU64, RSH, K), \
1208 INSN_3(ALU64, XOR, K), \
1209 INSN_3(ALU64, MUL, K), \
1210 INSN_3(ALU64, MOV, K), \
1211 INSN_3(ALU64, ARSH, K), \
1212 INSN_3(ALU64, DIV, K), \
1213 INSN_3(ALU64, MOD, K), \
1214 /* Call instruction. */ \
1215 INSN_2(JMP, CALL), \
1216 /* Exit instruction. */ \
1217 INSN_2(JMP, EXIT), \
1218 /* 32-bit Jump instructions. */ \
1219 /* Register based. */ \
1220 INSN_3(JMP32, JEQ, X), \
1221 INSN_3(JMP32, JNE, X), \
1222 INSN_3(JMP32, JGT, X), \
1223 INSN_3(JMP32, JLT, X), \
1224 INSN_3(JMP32, JGE, X), \
1225 INSN_3(JMP32, JLE, X), \
1226 INSN_3(JMP32, JSGT, X), \
1227 INSN_3(JMP32, JSLT, X), \
1228 INSN_3(JMP32, JSGE, X), \
1229 INSN_3(JMP32, JSLE, X), \
1230 INSN_3(JMP32, JSET, X), \
1231 /* Immediate based. */ \
1232 INSN_3(JMP32, JEQ, K), \
1233 INSN_3(JMP32, JNE, K), \
1234 INSN_3(JMP32, JGT, K), \
1235 INSN_3(JMP32, JLT, K), \
1236 INSN_3(JMP32, JGE, K), \
1237 INSN_3(JMP32, JLE, K), \
1238 INSN_3(JMP32, JSGT, K), \
1239 INSN_3(JMP32, JSLT, K), \
1240 INSN_3(JMP32, JSGE, K), \
1241 INSN_3(JMP32, JSLE, K), \
1242 INSN_3(JMP32, JSET, K), \
1243 /* Jump instructions. */ \
1244 /* Register based. */ \
1245 INSN_3(JMP, JEQ, X), \
1246 INSN_3(JMP, JNE, X), \
1247 INSN_3(JMP, JGT, X), \
1248 INSN_3(JMP, JLT, X), \
1249 INSN_3(JMP, JGE, X), \
1250 INSN_3(JMP, JLE, X), \
1251 INSN_3(JMP, JSGT, X), \
1252 INSN_3(JMP, JSLT, X), \
1253 INSN_3(JMP, JSGE, X), \
1254 INSN_3(JMP, JSLE, X), \
1255 INSN_3(JMP, JSET, X), \
1256 /* Immediate based. */ \
1257 INSN_3(JMP, JEQ, K), \
1258 INSN_3(JMP, JNE, K), \
1259 INSN_3(JMP, JGT, K), \
1260 INSN_3(JMP, JLT, K), \
1261 INSN_3(JMP, JGE, K), \
1262 INSN_3(JMP, JLE, K), \
1263 INSN_3(JMP, JSGT, K), \
1264 INSN_3(JMP, JSLT, K), \
1265 INSN_3(JMP, JSGE, K), \
1266 INSN_3(JMP, JSLE, K), \
1267 INSN_3(JMP, JSET, K), \
1268 INSN_2(JMP, JA), \
1269 /* Store instructions. */ \
1270 /* Register based. */ \
1271 INSN_3(STX, MEM, B), \
1272 INSN_3(STX, MEM, H), \
1273 INSN_3(STX, MEM, W), \
1274 INSN_3(STX, MEM, DW), \
1275 INSN_3(STX, XADD, W), \
1276 INSN_3(STX, XADD, DW), \
1277 /* Immediate based. */ \
1278 INSN_3(ST, MEM, B), \
1279 INSN_3(ST, MEM, H), \
1280 INSN_3(ST, MEM, W), \
1281 INSN_3(ST, MEM, DW), \
1282 /* Load instructions. */ \
1283 /* Register based. */ \
1284 INSN_3(LDX, MEM, B), \
1285 INSN_3(LDX, MEM, H), \
1286 INSN_3(LDX, MEM, W), \
1287 INSN_3(LDX, MEM, DW), \
1288 /* Immediate based. */ \
1289 INSN_3(LD, IMM, DW)
1290
1291bool bpf_opcode_in_insntable(u8 code)
1292{
1293#define BPF_INSN_2_TBL(x, y) [BPF_##x | BPF_##y] = true
1294#define BPF_INSN_3_TBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = true
1295 static const bool public_insntable[256] = {
1296 [0 ... 255] = false,
1297 /* Now overwrite non-defaults ... */
1298 BPF_INSN_MAP(BPF_INSN_2_TBL, BPF_INSN_3_TBL),
1299 /* UAPI exposed, but rewritten opcodes. cBPF carry-over. */
1300 [BPF_LD | BPF_ABS | BPF_B] = true,
1301 [BPF_LD | BPF_ABS | BPF_H] = true,
1302 [BPF_LD | BPF_ABS | BPF_W] = true,
1303 [BPF_LD | BPF_IND | BPF_B] = true,
1304 [BPF_LD | BPF_IND | BPF_H] = true,
1305 [BPF_LD | BPF_IND | BPF_W] = true,
1306 };
1307#undef BPF_INSN_3_TBL
1308#undef BPF_INSN_2_TBL
1309 return public_insntable[code];
1310}
1311
1312#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1313/**
1314 * __bpf_prog_run - run eBPF program on a given context
1315 * @regs: is the array of MAX_BPF_EXT_REG eBPF pseudo-registers
1316 * @insn: is the array of eBPF instructions
1317 * @stack: is the eBPF storage stack
1318 *
1319 * Decode and execute eBPF instructions.
1320 */
1321static u64 ___bpf_prog_run(u64 *regs, const struct bpf_insn *insn, u64 *stack)
1322{
1323#define BPF_INSN_2_LBL(x, y) [BPF_##x | BPF_##y] = &&x##_##y
1324#define BPF_INSN_3_LBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = &&x##_##y##_##z
1325 static const void * const jumptable[256] __annotate_jump_table = {
1326 [0 ... 255] = &&default_label,
1327 /* Now overwrite non-defaults ... */
1328 BPF_INSN_MAP(BPF_INSN_2_LBL, BPF_INSN_3_LBL),
1329 /* Non-UAPI available opcodes. */
1330 [BPF_JMP | BPF_CALL_ARGS] = &&JMP_CALL_ARGS,
1331 [BPF_JMP | BPF_TAIL_CALL] = &&JMP_TAIL_CALL,
1332 [BPF_ST | BPF_NOSPEC] = &&ST_NOSPEC,
1333 };
1334#undef BPF_INSN_3_LBL
1335#undef BPF_INSN_2_LBL
1336 u32 tail_call_cnt = 0;
1337
1338#define CONT ({ insn++; goto select_insn; })
1339#define CONT_JMP ({ insn++; goto select_insn; })
1340
1341select_insn:
1342 goto *jumptable[insn->code];
1343
1344 /* Explicitly mask the register-based shift amounts with 63 or 31
1345 * to avoid undefined behavior. Normally this won't affect the
1346 * generated code, for example, in case of native 64 bit archs such
1347 * as x86-64 or arm64, the compiler is optimizing the AND away for
1348 * the interpreter. In case of JITs, each of the JIT backends compiles
1349 * the BPF shift operations to machine instructions which produce
1350 * implementation-defined results in such a case; the resulting
1351 * contents of the register may be arbitrary, but program behaviour
1352 * as a whole remains defined. In other words, in case of JIT backends,
1353 * the AND must /not/ be added to the emitted LSH/RSH/ARSH translation.
1354 */
1355 /* ALU (shifts) */
1356#define SHT(OPCODE, OP) \
1357 ALU64_##OPCODE##_X: \
1358 DST = DST OP (SRC & 63); \
1359 CONT; \
1360 ALU_##OPCODE##_X: \
1361 DST = (u32) DST OP ((u32) SRC & 31); \
1362 CONT; \
1363 ALU64_##OPCODE##_K: \
1364 DST = DST OP IMM; \
1365 CONT; \
1366 ALU_##OPCODE##_K: \
1367 DST = (u32) DST OP (u32) IMM; \
1368 CONT;
1369 /* ALU (rest) */
1370#define ALU(OPCODE, OP) \
1371 ALU64_##OPCODE##_X: \
1372 DST = DST OP SRC; \
1373 CONT; \
1374 ALU_##OPCODE##_X: \
1375 DST = (u32) DST OP (u32) SRC; \
1376 CONT; \
1377 ALU64_##OPCODE##_K: \
1378 DST = DST OP IMM; \
1379 CONT; \
1380 ALU_##OPCODE##_K: \
1381 DST = (u32) DST OP (u32) IMM; \
1382 CONT;
1383 ALU(ADD, +)
1384 ALU(SUB, -)
1385 ALU(AND, &)
1386 ALU(OR, |)
1387 ALU(XOR, ^)
1388 ALU(MUL, *)
1389 SHT(LSH, <<)
1390 SHT(RSH, >>)
1391#undef SHT
1392#undef ALU
1393 ALU_NEG:
1394 DST = (u32) -DST;
1395 CONT;
1396 ALU64_NEG:
1397 DST = -DST;
1398 CONT;
1399 ALU_MOV_X:
1400 DST = (u32) SRC;
1401 CONT;
1402 ALU_MOV_K:
1403 DST = (u32) IMM;
1404 CONT;
1405 ALU64_MOV_X:
1406 DST = SRC;
1407 CONT;
1408 ALU64_MOV_K:
1409 DST = IMM;
1410 CONT;
1411 LD_IMM_DW:
1412 DST = (u64) (u32) insn[0].imm | ((u64) (u32) insn[1].imm) << 32;
1413 insn++;
1414 CONT;
1415 ALU_ARSH_X:
1416 DST = (u64) (u32) (((s32) DST) >> (SRC & 31));
1417 CONT;
1418 ALU_ARSH_K:
1419 DST = (u64) (u32) (((s32) DST) >> IMM);
1420 CONT;
1421 ALU64_ARSH_X:
1422 (*(s64 *) &DST) >>= (SRC & 63);
1423 CONT;
1424 ALU64_ARSH_K:
1425 (*(s64 *) &DST) >>= IMM;
1426 CONT;
1427 ALU64_MOD_X:
1428 div64_u64_rem(DST, SRC, &AX);
1429 DST = AX;
1430 CONT;
1431 ALU_MOD_X:
1432 AX = (u32) DST;
1433 DST = do_div(AX, (u32) SRC);
1434 CONT;
1435 ALU64_MOD_K:
1436 div64_u64_rem(DST, IMM, &AX);
1437 DST = AX;
1438 CONT;
1439 ALU_MOD_K:
1440 AX = (u32) DST;
1441 DST = do_div(AX, (u32) IMM);
1442 CONT;
1443 ALU64_DIV_X:
1444 DST = div64_u64(DST, SRC);
1445 CONT;
1446 ALU_DIV_X:
1447 AX = (u32) DST;
1448 do_div(AX, (u32) SRC);
1449 DST = (u32) AX;
1450 CONT;
1451 ALU64_DIV_K:
1452 DST = div64_u64(DST, IMM);
1453 CONT;
1454 ALU_DIV_K:
1455 AX = (u32) DST;
1456 do_div(AX, (u32) IMM);
1457 DST = (u32) AX;
1458 CONT;
1459 ALU_END_TO_BE:
1460 switch (IMM) {
1461 case 16:
1462 DST = (__force u16) cpu_to_be16(DST);
1463 break;
1464 case 32:
1465 DST = (__force u32) cpu_to_be32(DST);
1466 break;
1467 case 64:
1468 DST = (__force u64) cpu_to_be64(DST);
1469 break;
1470 }
1471 CONT;
1472 ALU_END_TO_LE:
1473 switch (IMM) {
1474 case 16:
1475 DST = (__force u16) cpu_to_le16(DST);
1476 break;
1477 case 32:
1478 DST = (__force u32) cpu_to_le32(DST);
1479 break;
1480 case 64:
1481 DST = (__force u64) cpu_to_le64(DST);
1482 break;
1483 }
1484 CONT;
1485
1486 /* CALL */
1487 JMP_CALL:
1488 /* Function call scratches BPF_R1-BPF_R5 registers,
1489 * preserves BPF_R6-BPF_R9, and stores return value
1490 * into BPF_R0.
1491 */
1492 BPF_R0 = (__bpf_call_base + insn->imm)(BPF_R1, BPF_R2, BPF_R3,
1493 BPF_R4, BPF_R5);
1494 CONT;
1495
1496 JMP_CALL_ARGS:
1497 BPF_R0 = (__bpf_call_base_args + insn->imm)(BPF_R1, BPF_R2,
1498 BPF_R3, BPF_R4,
1499 BPF_R5,
1500 insn + insn->off + 1);
1501 CONT;
1502
1503 JMP_TAIL_CALL: {
1504 struct bpf_map *map = (struct bpf_map *) (unsigned long) BPF_R2;
1505 struct bpf_array *array = container_of(map, struct bpf_array, map);
1506 struct bpf_prog *prog;
1507 u32 index = BPF_R3;
1508
1509 if (unlikely(index >= array->map.max_entries))
1510 goto out;
1511 if (unlikely(tail_call_cnt > MAX_TAIL_CALL_CNT))
1512 goto out;
1513
1514 tail_call_cnt++;
1515
1516 prog = READ_ONCE(array->ptrs[index]);
1517 if (!prog)
1518 goto out;
1519
1520 /* ARG1 at this point is guaranteed to point to CTX from
1521 * the verifier side due to the fact that the tail call is
1522 * handeled like a helper, that is, bpf_tail_call_proto,
1523 * where arg1_type is ARG_PTR_TO_CTX.
1524 */
1525 insn = prog->insnsi;
1526 goto select_insn;
1527out:
1528 CONT;
1529 }
1530 JMP_JA:
1531 insn += insn->off;
1532 CONT;
1533 JMP_EXIT:
1534 return BPF_R0;
1535 /* JMP */
1536#define COND_JMP(SIGN, OPCODE, CMP_OP) \
1537 JMP_##OPCODE##_X: \
1538 if ((SIGN##64) DST CMP_OP (SIGN##64) SRC) { \
1539 insn += insn->off; \
1540 CONT_JMP; \
1541 } \
1542 CONT; \
1543 JMP32_##OPCODE##_X: \
1544 if ((SIGN##32) DST CMP_OP (SIGN##32) SRC) { \
1545 insn += insn->off; \
1546 CONT_JMP; \
1547 } \
1548 CONT; \
1549 JMP_##OPCODE##_K: \
1550 if ((SIGN##64) DST CMP_OP (SIGN##64) IMM) { \
1551 insn += insn->off; \
1552 CONT_JMP; \
1553 } \
1554 CONT; \
1555 JMP32_##OPCODE##_K: \
1556 if ((SIGN##32) DST CMP_OP (SIGN##32) IMM) { \
1557 insn += insn->off; \
1558 CONT_JMP; \
1559 } \
1560 CONT;
1561 COND_JMP(u, JEQ, ==)
1562 COND_JMP(u, JNE, !=)
1563 COND_JMP(u, JGT, >)
1564 COND_JMP(u, JLT, <)
1565 COND_JMP(u, JGE, >=)
1566 COND_JMP(u, JLE, <=)
1567 COND_JMP(u, JSET, &)
1568 COND_JMP(s, JSGT, >)
1569 COND_JMP(s, JSLT, <)
1570 COND_JMP(s, JSGE, >=)
1571 COND_JMP(s, JSLE, <=)
1572#undef COND_JMP
1573 /* ST, STX and LDX*/
1574 ST_NOSPEC:
1575 /* Speculation barrier for mitigating Speculative Store Bypass.
1576 * In case of arm64, we rely on the firmware mitigation as
1577 * controlled via the ssbd kernel parameter. Whenever the
1578 * mitigation is enabled, it works for all of the kernel code
1579 * with no need to provide any additional instructions here.
1580 * In case of x86, we use 'lfence' insn for mitigation. We
1581 * reuse preexisting logic from Spectre v1 mitigation that
1582 * happens to produce the required code on x86 for v4 as well.
1583 */
1584 barrier_nospec();
1585 CONT;
1586#define LDST(SIZEOP, SIZE) \
1587 STX_MEM_##SIZEOP: \
1588 *(SIZE *)(unsigned long) (DST + insn->off) = SRC; \
1589 CONT; \
1590 ST_MEM_##SIZEOP: \
1591 *(SIZE *)(unsigned long) (DST + insn->off) = IMM; \
1592 CONT; \
1593 LDX_MEM_##SIZEOP: \
1594 DST = *(SIZE *)(unsigned long) (SRC + insn->off); \
1595 CONT;
1596
1597 LDST(B, u8)
1598 LDST(H, u16)
1599 LDST(W, u32)
1600 LDST(DW, u64)
1601#undef LDST
1602 STX_XADD_W: /* lock xadd *(u32 *)(dst_reg + off16) += src_reg */
1603 atomic_add((u32) SRC, (atomic_t *)(unsigned long)
1604 (DST + insn->off));
1605 CONT;
1606 STX_XADD_DW: /* lock xadd *(u64 *)(dst_reg + off16) += src_reg */
1607 atomic64_add((u64) SRC, (atomic64_t *)(unsigned long)
1608 (DST + insn->off));
1609 CONT;
1610
1611 default_label:
1612 /* If we ever reach this, we have a bug somewhere. Die hard here
1613 * instead of just returning 0; we could be somewhere in a subprog,
1614 * so execution could continue otherwise which we do /not/ want.
1615 *
1616 * Note, verifier whitelists all opcodes in bpf_opcode_in_insntable().
1617 */
1618 pr_warn("BPF interpreter: unknown opcode %02x\n", insn->code);
1619 BUG_ON(1);
1620 return 0;
1621}
1622
1623#define PROG_NAME(stack_size) __bpf_prog_run##stack_size
1624#define DEFINE_BPF_PROG_RUN(stack_size) \
1625static unsigned int PROG_NAME(stack_size)(const void *ctx, const struct bpf_insn *insn) \
1626{ \
1627 u64 stack[stack_size / sizeof(u64)]; \
1628 u64 regs[MAX_BPF_EXT_REG]; \
1629\
1630 FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
1631 ARG1 = (u64) (unsigned long) ctx; \
1632 return ___bpf_prog_run(regs, insn, stack); \
1633}
1634
1635#define PROG_NAME_ARGS(stack_size) __bpf_prog_run_args##stack_size
1636#define DEFINE_BPF_PROG_RUN_ARGS(stack_size) \
1637static u64 PROG_NAME_ARGS(stack_size)(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, \
1638 const struct bpf_insn *insn) \
1639{ \
1640 u64 stack[stack_size / sizeof(u64)]; \
1641 u64 regs[MAX_BPF_EXT_REG]; \
1642\
1643 FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
1644 BPF_R1 = r1; \
1645 BPF_R2 = r2; \
1646 BPF_R3 = r3; \
1647 BPF_R4 = r4; \
1648 BPF_R5 = r5; \
1649 return ___bpf_prog_run(regs, insn, stack); \
1650}
1651
1652#define EVAL1(FN, X) FN(X)
1653#define EVAL2(FN, X, Y...) FN(X) EVAL1(FN, Y)
1654#define EVAL3(FN, X, Y...) FN(X) EVAL2(FN, Y)
1655#define EVAL4(FN, X, Y...) FN(X) EVAL3(FN, Y)
1656#define EVAL5(FN, X, Y...) FN(X) EVAL4(FN, Y)
1657#define EVAL6(FN, X, Y...) FN(X) EVAL5(FN, Y)
1658
1659EVAL6(DEFINE_BPF_PROG_RUN, 32, 64, 96, 128, 160, 192);
1660EVAL6(DEFINE_BPF_PROG_RUN, 224, 256, 288, 320, 352, 384);
1661EVAL4(DEFINE_BPF_PROG_RUN, 416, 448, 480, 512);
1662
1663EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 32, 64, 96, 128, 160, 192);
1664EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 224, 256, 288, 320, 352, 384);
1665EVAL4(DEFINE_BPF_PROG_RUN_ARGS, 416, 448, 480, 512);
1666
1667#define PROG_NAME_LIST(stack_size) PROG_NAME(stack_size),
1668
1669static unsigned int (*interpreters[])(const void *ctx,
1670 const struct bpf_insn *insn) = {
1671EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
1672EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
1673EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
1674};
1675#undef PROG_NAME_LIST
1676#define PROG_NAME_LIST(stack_size) PROG_NAME_ARGS(stack_size),
1677static u64 (*interpreters_args[])(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5,
1678 const struct bpf_insn *insn) = {
1679EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
1680EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
1681EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
1682};
1683#undef PROG_NAME_LIST
1684
1685void bpf_patch_call_args(struct bpf_insn *insn, u32 stack_depth)
1686{
1687 stack_depth = max_t(u32, stack_depth, 1);
1688 insn->off = (s16) insn->imm;
1689 insn->imm = interpreters_args[(round_up(stack_depth, 32) / 32) - 1] -
1690 __bpf_call_base_args;
1691 insn->code = BPF_JMP | BPF_CALL_ARGS;
1692}
1693
1694#else
1695static unsigned int __bpf_prog_ret0_warn(const void *ctx,
1696 const struct bpf_insn *insn)
1697{
1698 /* If this handler ever gets executed, then BPF_JIT_ALWAYS_ON
1699 * is not working properly, so warn about it!
1700 */
1701 WARN_ON_ONCE(1);
1702 return 0;
1703}
1704#endif
1705
1706bool bpf_prog_array_compatible(struct bpf_array *array,
1707 const struct bpf_prog *fp)
1708{
1709 if (fp->kprobe_override)
1710 return false;
1711
1712 if (!array->owner_prog_type) {
1713 /* There's no owner yet where we could check for
1714 * compatibility.
1715 */
1716 array->owner_prog_type = fp->type;
1717 array->owner_jited = fp->jited;
1718
1719 return true;
1720 }
1721
1722 return array->owner_prog_type == fp->type &&
1723 array->owner_jited == fp->jited;
1724}
1725
1726static int bpf_check_tail_call(const struct bpf_prog *fp)
1727{
1728 struct bpf_prog_aux *aux = fp->aux;
1729 int i;
1730
1731 for (i = 0; i < aux->used_map_cnt; i++) {
1732 struct bpf_map *map = aux->used_maps[i];
1733 struct bpf_array *array;
1734
1735 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1736 continue;
1737
1738 array = container_of(map, struct bpf_array, map);
1739 if (!bpf_prog_array_compatible(array, fp))
1740 return -EINVAL;
1741 }
1742
1743 return 0;
1744}
1745
1746static void bpf_prog_select_func(struct bpf_prog *fp)
1747{
1748#ifndef CONFIG_BPF_JIT_ALWAYS_ON
1749 u32 stack_depth = max_t(u32, fp->aux->stack_depth, 1);
1750
1751 fp->bpf_func = interpreters[(round_up(stack_depth, 32) / 32) - 1];
1752#else
1753 fp->bpf_func = __bpf_prog_ret0_warn;
1754#endif
1755}
1756
1757/**
1758 * bpf_prog_select_runtime - select exec runtime for BPF program
1759 * @fp: bpf_prog populated with internal BPF program
1760 * @err: pointer to error variable
1761 *
1762 * Try to JIT eBPF program, if JIT is not available, use interpreter.
1763 * The BPF program will be executed via BPF_PROG_RUN() macro.
1764 */
1765struct bpf_prog *bpf_prog_select_runtime(struct bpf_prog *fp, int *err)
1766{
1767 /* In case of BPF to BPF calls, verifier did all the prep
1768 * work with regards to JITing, etc.
1769 */
1770 if (fp->bpf_func)
1771 goto finalize;
1772
1773 bpf_prog_select_func(fp);
1774
1775 /* eBPF JITs can rewrite the program in case constant
1776 * blinding is active. However, in case of error during
1777 * blinding, bpf_int_jit_compile() must always return a
1778 * valid program, which in this case would simply not
1779 * be JITed, but falls back to the interpreter.
1780 */
1781 if (!bpf_prog_is_dev_bound(fp->aux)) {
1782 *err = bpf_prog_alloc_jited_linfo(fp);
1783 if (*err)
1784 return fp;
1785
1786 fp = bpf_int_jit_compile(fp);
1787 if (!fp->jited) {
1788 bpf_prog_free_jited_linfo(fp);
1789#ifdef CONFIG_BPF_JIT_ALWAYS_ON
1790 *err = -ENOTSUPP;
1791 return fp;
1792#endif
1793 } else {
1794 bpf_prog_free_unused_jited_linfo(fp);
1795 }
1796 } else {
1797 *err = bpf_prog_offload_compile(fp);
1798 if (*err)
1799 return fp;
1800 }
1801
1802finalize:
1803 bpf_prog_lock_ro(fp);
1804
1805 /* The tail call compatibility check can only be done at
1806 * this late stage as we need to determine, if we deal
1807 * with JITed or non JITed program concatenations and not
1808 * all eBPF JITs might immediately support all features.
1809 */
1810 *err = bpf_check_tail_call(fp);
1811
1812 return fp;
1813}
1814EXPORT_SYMBOL_GPL(bpf_prog_select_runtime);
1815
1816static unsigned int __bpf_prog_ret1(const void *ctx,
1817 const struct bpf_insn *insn)
1818{
1819 return 1;
1820}
1821
1822static struct bpf_prog_dummy {
1823 struct bpf_prog prog;
1824} dummy_bpf_prog = {
1825 .prog = {
1826 .bpf_func = __bpf_prog_ret1,
1827 },
1828};
1829
1830/* to avoid allocating empty bpf_prog_array for cgroups that
1831 * don't have bpf program attached use one global 'empty_prog_array'
1832 * It will not be modified the caller of bpf_prog_array_alloc()
1833 * (since caller requested prog_cnt == 0)
1834 * that pointer should be 'freed' by bpf_prog_array_free()
1835 */
1836static struct {
1837 struct bpf_prog_array hdr;
1838 struct bpf_prog *null_prog;
1839} empty_prog_array = {
1840 .null_prog = NULL,
1841};
1842
1843struct bpf_prog_array *bpf_prog_array_alloc(u32 prog_cnt, gfp_t flags)
1844{
1845 if (prog_cnt)
1846 return kzalloc(sizeof(struct bpf_prog_array) +
1847 sizeof(struct bpf_prog_array_item) *
1848 (prog_cnt + 1),
1849 flags);
1850
1851 return &empty_prog_array.hdr;
1852}
1853
1854void bpf_prog_array_free(struct bpf_prog_array *progs)
1855{
1856 if (!progs || progs == &empty_prog_array.hdr)
1857 return;
1858 kfree_rcu(progs, rcu);
1859}
1860
1861int bpf_prog_array_length(struct bpf_prog_array *array)
1862{
1863 struct bpf_prog_array_item *item;
1864 u32 cnt = 0;
1865
1866 for (item = array->items; item->prog; item++)
1867 if (item->prog != &dummy_bpf_prog.prog)
1868 cnt++;
1869 return cnt;
1870}
1871
1872bool bpf_prog_array_is_empty(struct bpf_prog_array *array)
1873{
1874 struct bpf_prog_array_item *item;
1875
1876 for (item = array->items; item->prog; item++)
1877 if (item->prog != &dummy_bpf_prog.prog)
1878 return false;
1879 return true;
1880}
1881
1882static bool bpf_prog_array_copy_core(struct bpf_prog_array *array,
1883 u32 *prog_ids,
1884 u32 request_cnt)
1885{
1886 struct bpf_prog_array_item *item;
1887 int i = 0;
1888
1889 for (item = array->items; item->prog; item++) {
1890 if (item->prog == &dummy_bpf_prog.prog)
1891 continue;
1892 prog_ids[i] = item->prog->aux->id;
1893 if (++i == request_cnt) {
1894 item++;
1895 break;
1896 }
1897 }
1898
1899 return !!(item->prog);
1900}
1901
1902int bpf_prog_array_copy_to_user(struct bpf_prog_array *array,
1903 __u32 __user *prog_ids, u32 cnt)
1904{
1905 unsigned long err = 0;
1906 bool nospc;
1907 u32 *ids;
1908
1909 /* users of this function are doing:
1910 * cnt = bpf_prog_array_length();
1911 * if (cnt > 0)
1912 * bpf_prog_array_copy_to_user(..., cnt);
1913 * so below kcalloc doesn't need extra cnt > 0 check.
1914 */
1915 ids = kcalloc(cnt, sizeof(u32), GFP_USER | __GFP_NOWARN);
1916 if (!ids)
1917 return -ENOMEM;
1918 nospc = bpf_prog_array_copy_core(array, ids, cnt);
1919 err = copy_to_user(prog_ids, ids, cnt * sizeof(u32));
1920 kfree(ids);
1921 if (err)
1922 return -EFAULT;
1923 if (nospc)
1924 return -ENOSPC;
1925 return 0;
1926}
1927
1928void bpf_prog_array_delete_safe(struct bpf_prog_array *array,
1929 struct bpf_prog *old_prog)
1930{
1931 struct bpf_prog_array_item *item;
1932
1933 for (item = array->items; item->prog; item++)
1934 if (item->prog == old_prog) {
1935 WRITE_ONCE(item->prog, &dummy_bpf_prog.prog);
1936 break;
1937 }
1938}
1939
1940int bpf_prog_array_copy(struct bpf_prog_array *old_array,
1941 struct bpf_prog *exclude_prog,
1942 struct bpf_prog *include_prog,
1943 struct bpf_prog_array **new_array)
1944{
1945 int new_prog_cnt, carry_prog_cnt = 0;
1946 struct bpf_prog_array_item *existing;
1947 struct bpf_prog_array *array;
1948 bool found_exclude = false;
1949 int new_prog_idx = 0;
1950
1951 /* Figure out how many existing progs we need to carry over to
1952 * the new array.
1953 */
1954 if (old_array) {
1955 existing = old_array->items;
1956 for (; existing->prog; existing++) {
1957 if (existing->prog == exclude_prog) {
1958 found_exclude = true;
1959 continue;
1960 }
1961 if (existing->prog != &dummy_bpf_prog.prog)
1962 carry_prog_cnt++;
1963 if (existing->prog == include_prog)
1964 return -EEXIST;
1965 }
1966 }
1967
1968 if (exclude_prog && !found_exclude)
1969 return -ENOENT;
1970
1971 /* How many progs (not NULL) will be in the new array? */
1972 new_prog_cnt = carry_prog_cnt;
1973 if (include_prog)
1974 new_prog_cnt += 1;
1975
1976 /* Do we have any prog (not NULL) in the new array? */
1977 if (!new_prog_cnt) {
1978 *new_array = NULL;
1979 return 0;
1980 }
1981
1982 /* +1 as the end of prog_array is marked with NULL */
1983 array = bpf_prog_array_alloc(new_prog_cnt + 1, GFP_KERNEL);
1984 if (!array)
1985 return -ENOMEM;
1986
1987 /* Fill in the new prog array */
1988 if (carry_prog_cnt) {
1989 existing = old_array->items;
1990 for (; existing->prog; existing++)
1991 if (existing->prog != exclude_prog &&
1992 existing->prog != &dummy_bpf_prog.prog) {
1993 array->items[new_prog_idx++].prog =
1994 existing->prog;
1995 }
1996 }
1997 if (include_prog)
1998 array->items[new_prog_idx++].prog = include_prog;
1999 array->items[new_prog_idx].prog = NULL;
2000 *new_array = array;
2001 return 0;
2002}
2003
2004int bpf_prog_array_copy_info(struct bpf_prog_array *array,
2005 u32 *prog_ids, u32 request_cnt,
2006 u32 *prog_cnt)
2007{
2008 u32 cnt = 0;
2009
2010 if (array)
2011 cnt = bpf_prog_array_length(array);
2012
2013 *prog_cnt = cnt;
2014
2015 /* return early if user requested only program count or nothing to copy */
2016 if (!request_cnt || !cnt)
2017 return 0;
2018
2019 /* this function is called under trace/bpf_trace.c: bpf_event_mutex */
2020 return bpf_prog_array_copy_core(array, prog_ids, request_cnt) ? -ENOSPC
2021 : 0;
2022}
2023
2024static void bpf_prog_free_deferred(struct work_struct *work)
2025{
2026 struct bpf_prog_aux *aux;
2027 int i;
2028
2029 aux = container_of(work, struct bpf_prog_aux, work);
2030 if (bpf_prog_is_dev_bound(aux))
2031 bpf_prog_offload_destroy(aux->prog);
2032#ifdef CONFIG_PERF_EVENTS
2033 if (aux->prog->has_callchain_buf)
2034 put_callchain_buffers();
2035#endif
2036 for (i = 0; i < aux->func_cnt; i++)
2037 bpf_jit_free(aux->func[i]);
2038 if (aux->func_cnt) {
2039 kfree(aux->func);
2040 bpf_prog_unlock_free(aux->prog);
2041 } else {
2042 bpf_jit_free(aux->prog);
2043 }
2044}
2045
2046/* Free internal BPF program */
2047void bpf_prog_free(struct bpf_prog *fp)
2048{
2049 struct bpf_prog_aux *aux = fp->aux;
2050
2051 INIT_WORK(&aux->work, bpf_prog_free_deferred);
2052 schedule_work(&aux->work);
2053}
2054EXPORT_SYMBOL_GPL(bpf_prog_free);
2055
2056/* RNG for unpriviledged user space with separated state from prandom_u32(). */
2057static DEFINE_PER_CPU(struct rnd_state, bpf_user_rnd_state);
2058
2059void bpf_user_rnd_init_once(void)
2060{
2061 prandom_init_once(&bpf_user_rnd_state);
2062}
2063
2064BPF_CALL_0(bpf_user_rnd_u32)
2065{
2066 /* Should someone ever have the rather unwise idea to use some
2067 * of the registers passed into this function, then note that
2068 * this function is called from native eBPF and classic-to-eBPF
2069 * transformations. Register assignments from both sides are
2070 * different, f.e. classic always sets fn(ctx, A, X) here.
2071 */
2072 struct rnd_state *state;
2073 u32 res;
2074
2075 state = &get_cpu_var(bpf_user_rnd_state);
2076 res = prandom_u32_state(state);
2077 put_cpu_var(bpf_user_rnd_state);
2078
2079 return res;
2080}
2081
2082/* Weak definitions of helper functions in case we don't have bpf syscall. */
2083const struct bpf_func_proto bpf_map_lookup_elem_proto __weak;
2084const struct bpf_func_proto bpf_map_update_elem_proto __weak;
2085const struct bpf_func_proto bpf_map_delete_elem_proto __weak;
2086const struct bpf_func_proto bpf_map_push_elem_proto __weak;
2087const struct bpf_func_proto bpf_map_pop_elem_proto __weak;
2088const struct bpf_func_proto bpf_map_peek_elem_proto __weak;
2089const struct bpf_func_proto bpf_spin_lock_proto __weak;
2090const struct bpf_func_proto bpf_spin_unlock_proto __weak;
2091
2092const struct bpf_func_proto bpf_get_prandom_u32_proto __weak;
2093const struct bpf_func_proto bpf_get_smp_processor_id_proto __weak;
2094const struct bpf_func_proto bpf_get_numa_node_id_proto __weak;
2095const struct bpf_func_proto bpf_ktime_get_ns_proto __weak;
2096const struct bpf_func_proto bpf_ktime_get_boot_ns_proto __weak;
2097
2098const struct bpf_func_proto bpf_get_current_pid_tgid_proto __weak;
2099const struct bpf_func_proto bpf_get_current_uid_gid_proto __weak;
2100const struct bpf_func_proto bpf_get_current_comm_proto __weak;
2101const struct bpf_func_proto bpf_get_current_cgroup_id_proto __weak;
2102const struct bpf_func_proto bpf_get_local_storage_proto __weak;
2103
2104const struct bpf_func_proto * __weak bpf_get_trace_printk_proto(void)
2105{
2106 return NULL;
2107}
2108
2109u64 __weak
2110bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
2111 void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
2112{
2113 return -ENOTSUPP;
2114}
2115EXPORT_SYMBOL_GPL(bpf_event_output);
2116
2117/* Always built-in helper functions. */
2118const struct bpf_func_proto bpf_tail_call_proto = {
2119 .func = NULL,
2120 .gpl_only = false,
2121 .ret_type = RET_VOID,
2122 .arg1_type = ARG_PTR_TO_CTX,
2123 .arg2_type = ARG_CONST_MAP_PTR,
2124 .arg3_type = ARG_ANYTHING,
2125};
2126
2127/* Stub for JITs that only support cBPF. eBPF programs are interpreted.
2128 * It is encouraged to implement bpf_int_jit_compile() instead, so that
2129 * eBPF and implicitly also cBPF can get JITed!
2130 */
2131struct bpf_prog * __weak bpf_int_jit_compile(struct bpf_prog *prog)
2132{
2133 return prog;
2134}
2135
2136/* Stub for JITs that support eBPF. All cBPF code gets transformed into
2137 * eBPF by the kernel and is later compiled by bpf_int_jit_compile().
2138 */
2139void __weak bpf_jit_compile(struct bpf_prog *prog)
2140{
2141}
2142
2143bool __weak bpf_helper_changes_pkt_data(void *func)
2144{
2145 return false;
2146}
2147
2148/* Return TRUE if the JIT backend wants verifier to enable sub-register usage
2149 * analysis code and wants explicit zero extension inserted by verifier.
2150 * Otherwise, return FALSE.
2151 */
2152bool __weak bpf_jit_needs_zext(void)
2153{
2154 return false;
2155}
2156
2157/* To execute LD_ABS/LD_IND instructions __bpf_prog_run() may call
2158 * skb_copy_bits(), so provide a weak definition of it for NET-less config.
2159 */
2160int __weak skb_copy_bits(const struct sk_buff *skb, int offset, void *to,
2161 int len)
2162{
2163 return -EFAULT;
2164}
2165
2166DEFINE_STATIC_KEY_FALSE(bpf_stats_enabled_key);
2167EXPORT_SYMBOL(bpf_stats_enabled_key);
2168
2169/* All definitions of tracepoints related to BPF. */
2170#define CREATE_TRACE_POINTS
2171#include <linux/bpf_trace.h>
2172
2173EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_exception);
2174EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_bulk_tx);