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