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