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