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