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