• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/random.h>
25 #include <linux/moduleloader.h>
26 #include <linux/bpf.h>
27 #include <linux/btf.h>
28 #include <linux/objtool.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/nospec.h>
36 
37 #include <asm/barrier.h>
38 #include <asm/unaligned.h>
39 
40 /* Registers */
41 #define BPF_R0	regs[BPF_REG_0]
42 #define BPF_R1	regs[BPF_REG_1]
43 #define BPF_R2	regs[BPF_REG_2]
44 #define BPF_R3	regs[BPF_REG_3]
45 #define BPF_R4	regs[BPF_REG_4]
46 #define BPF_R5	regs[BPF_REG_5]
47 #define BPF_R6	regs[BPF_REG_6]
48 #define BPF_R7	regs[BPF_REG_7]
49 #define BPF_R8	regs[BPF_REG_8]
50 #define BPF_R9	regs[BPF_REG_9]
51 #define BPF_R10	regs[BPF_REG_10]
52 
53 /* Named registers */
54 #define DST	regs[insn->dst_reg]
55 #define SRC	regs[insn->src_reg]
56 #define FP	regs[BPF_REG_FP]
57 #define AX	regs[BPF_REG_AX]
58 #define ARG1	regs[BPF_REG_ARG1]
59 #define CTX	regs[BPF_REG_CTX]
60 #define IMM	insn->imm
61 
62 /* No hurry in this branch
63  *
64  * Exported for the bpf jit load helper.
65  */
bpf_internal_load_pointer_neg_helper(const struct sk_buff * skb,int k,unsigned int size)66 void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, unsigned int size)
67 {
68 	u8 *ptr = NULL;
69 
70 	if (k >= SKF_NET_OFF) {
71 		ptr = skb_network_header(skb) + k - SKF_NET_OFF;
72 	} else if (k >= SKF_LL_OFF) {
73 		if (unlikely(!skb_mac_header_was_set(skb)))
74 			return NULL;
75 		ptr = skb_mac_header(skb) + k - SKF_LL_OFF;
76 	}
77 	if (ptr >= skb->head && ptr + size <= skb_tail_pointer(skb))
78 		return ptr;
79 
80 	return NULL;
81 }
82 
bpf_prog_alloc_no_stats(unsigned int size,gfp_t gfp_extra_flags)83 struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)
84 {
85 	gfp_t gfp_flags = GFP_KERNEL_ACCOUNT | __GFP_ZERO | gfp_extra_flags;
86 	struct bpf_prog_aux *aux;
87 	struct bpf_prog *fp;
88 
89 	size = round_up(size, PAGE_SIZE);
90 	fp = __vmalloc(size, gfp_flags);
91 	if (fp == NULL)
92 		return NULL;
93 
94 	aux = kzalloc(sizeof(*aux), GFP_KERNEL_ACCOUNT | gfp_extra_flags);
95 	if (aux == NULL) {
96 		vfree(fp);
97 		return NULL;
98 	}
99 	fp->active = alloc_percpu_gfp(int, GFP_KERNEL_ACCOUNT | gfp_extra_flags);
100 	if (!fp->active) {
101 		vfree(fp);
102 		kfree(aux);
103 		return NULL;
104 	}
105 
106 	fp->pages = size / PAGE_SIZE;
107 	fp->aux = aux;
108 	fp->aux->prog = fp;
109 	fp->jit_requested = ebpf_jit_enabled();
110 
111 	INIT_LIST_HEAD_RCU(&fp->aux->ksym.lnode);
112 	mutex_init(&fp->aux->used_maps_mutex);
113 	mutex_init(&fp->aux->dst_mutex);
114 
115 	return fp;
116 }
117 
bpf_prog_alloc(unsigned int size,gfp_t gfp_extra_flags)118 struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags)
119 {
120 	gfp_t gfp_flags = GFP_KERNEL_ACCOUNT | __GFP_ZERO | gfp_extra_flags;
121 	struct bpf_prog *prog;
122 	int cpu;
123 
124 	prog = bpf_prog_alloc_no_stats(size, gfp_extra_flags);
125 	if (!prog)
126 		return NULL;
127 
128 	prog->stats = alloc_percpu_gfp(struct bpf_prog_stats, gfp_flags);
129 	if (!prog->stats) {
130 		free_percpu(prog->active);
131 		kfree(prog->aux);
132 		vfree(prog);
133 		return NULL;
134 	}
135 
136 	for_each_possible_cpu(cpu) {
137 		struct bpf_prog_stats *pstats;
138 
139 		pstats = per_cpu_ptr(prog->stats, cpu);
140 		u64_stats_init(&pstats->syncp);
141 	}
142 	return prog;
143 }
144 EXPORT_SYMBOL_GPL(bpf_prog_alloc);
145 
bpf_prog_alloc_jited_linfo(struct bpf_prog * prog)146 int bpf_prog_alloc_jited_linfo(struct bpf_prog *prog)
147 {
148 	if (!prog->aux->nr_linfo || !prog->jit_requested)
149 		return 0;
150 
151 	prog->aux->jited_linfo = kvcalloc(prog->aux->nr_linfo,
152 					  sizeof(*prog->aux->jited_linfo),
153 					  GFP_KERNEL_ACCOUNT | __GFP_NOWARN);
154 	if (!prog->aux->jited_linfo)
155 		return -ENOMEM;
156 
157 	return 0;
158 }
159 
bpf_prog_jit_attempt_done(struct bpf_prog * prog)160 void bpf_prog_jit_attempt_done(struct bpf_prog *prog)
161 {
162 	if (prog->aux->jited_linfo &&
163 	    (!prog->jited || !prog->aux->jited_linfo[0])) {
164 		kvfree(prog->aux->jited_linfo);
165 		prog->aux->jited_linfo = NULL;
166 	}
167 
168 	kfree(prog->aux->kfunc_tab);
169 	prog->aux->kfunc_tab = NULL;
170 }
171 
172 /* The jit engine is responsible to provide an array
173  * for insn_off to the jited_off mapping (insn_to_jit_off).
174  *
175  * The idx to this array is the insn_off.  Hence, the insn_off
176  * here is relative to the prog itself instead of the main prog.
177  * This array has one entry for each xlated bpf insn.
178  *
179  * jited_off is the byte off to the last byte of the jited insn.
180  *
181  * Hence, with
182  * insn_start:
183  *      The first bpf insn off of the prog.  The insn off
184  *      here is relative to the main prog.
185  *      e.g. if prog is a subprog, insn_start > 0
186  * linfo_idx:
187  *      The prog's idx to prog->aux->linfo and jited_linfo
188  *
189  * jited_linfo[linfo_idx] = prog->bpf_func
190  *
191  * For i > linfo_idx,
192  *
193  * jited_linfo[i] = prog->bpf_func +
194  *	insn_to_jit_off[linfo[i].insn_off - insn_start - 1]
195  */
bpf_prog_fill_jited_linfo(struct bpf_prog * prog,const u32 * insn_to_jit_off)196 void bpf_prog_fill_jited_linfo(struct bpf_prog *prog,
197 			       const u32 *insn_to_jit_off)
198 {
199 	u32 linfo_idx, insn_start, insn_end, nr_linfo, i;
200 	const struct bpf_line_info *linfo;
201 	void **jited_linfo;
202 
203 	if (!prog->aux->jited_linfo)
204 		/* Userspace did not provide linfo */
205 		return;
206 
207 	linfo_idx = prog->aux->linfo_idx;
208 	linfo = &prog->aux->linfo[linfo_idx];
209 	insn_start = linfo[0].insn_off;
210 	insn_end = insn_start + prog->len;
211 
212 	jited_linfo = &prog->aux->jited_linfo[linfo_idx];
213 	jited_linfo[0] = prog->bpf_func;
214 
215 	nr_linfo = prog->aux->nr_linfo - linfo_idx;
216 
217 	for (i = 1; i < nr_linfo && linfo[i].insn_off < insn_end; i++)
218 		/* The verifier ensures that linfo[i].insn_off is
219 		 * strictly increasing
220 		 */
221 		jited_linfo[i] = prog->bpf_func +
222 			insn_to_jit_off[linfo[i].insn_off - insn_start - 1];
223 }
224 
bpf_prog_realloc(struct bpf_prog * fp_old,unsigned int size,gfp_t gfp_extra_flags)225 struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
226 				  gfp_t gfp_extra_flags)
227 {
228 	gfp_t gfp_flags = GFP_KERNEL_ACCOUNT | __GFP_ZERO | gfp_extra_flags;
229 	struct bpf_prog *fp;
230 	u32 pages;
231 
232 	size = round_up(size, PAGE_SIZE);
233 	pages = size / PAGE_SIZE;
234 	if (pages <= fp_old->pages)
235 		return fp_old;
236 
237 	fp = __vmalloc(size, gfp_flags);
238 	if (fp) {
239 		memcpy(fp, fp_old, fp_old->pages * PAGE_SIZE);
240 		fp->pages = pages;
241 		fp->aux->prog = fp;
242 
243 		/* We keep fp->aux from fp_old around in the new
244 		 * reallocated structure.
245 		 */
246 		fp_old->aux = NULL;
247 		fp_old->stats = NULL;
248 		fp_old->active = NULL;
249 		__bpf_prog_free(fp_old);
250 	}
251 
252 	return fp;
253 }
254 
__bpf_prog_free(struct bpf_prog * fp)255 void __bpf_prog_free(struct bpf_prog *fp)
256 {
257 	if (fp->aux) {
258 		mutex_destroy(&fp->aux->used_maps_mutex);
259 		mutex_destroy(&fp->aux->dst_mutex);
260 		kfree(fp->aux->poke_tab);
261 		kfree(fp->aux);
262 	}
263 	free_percpu(fp->stats);
264 	free_percpu(fp->active);
265 	vfree(fp);
266 }
267 
bpf_prog_calc_tag(struct bpf_prog * fp)268 int bpf_prog_calc_tag(struct bpf_prog *fp)
269 {
270 	const u32 bits_offset = SHA1_BLOCK_SIZE - sizeof(__be64);
271 	u32 raw_size = bpf_prog_tag_scratch_size(fp);
272 	u32 digest[SHA1_DIGEST_WORDS];
273 	u32 ws[SHA1_WORKSPACE_WORDS];
274 	u32 i, bsize, psize, blocks;
275 	struct bpf_insn *dst;
276 	bool was_ld_map;
277 	u8 *raw, *todo;
278 	__be32 *result;
279 	__be64 *bits;
280 
281 	raw = vmalloc(raw_size);
282 	if (!raw)
283 		return -ENOMEM;
284 
285 	sha1_init(digest);
286 	memset(ws, 0, sizeof(ws));
287 
288 	/* We need to take out the map fd for the digest calculation
289 	 * since they are unstable from user space side.
290 	 */
291 	dst = (void *)raw;
292 	for (i = 0, was_ld_map = false; i < fp->len; i++) {
293 		dst[i] = fp->insnsi[i];
294 		if (!was_ld_map &&
295 		    dst[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
296 		    (dst[i].src_reg == BPF_PSEUDO_MAP_FD ||
297 		     dst[i].src_reg == BPF_PSEUDO_MAP_VALUE)) {
298 			was_ld_map = true;
299 			dst[i].imm = 0;
300 		} else if (was_ld_map &&
301 			   dst[i].code == 0 &&
302 			   dst[i].dst_reg == 0 &&
303 			   dst[i].src_reg == 0 &&
304 			   dst[i].off == 0) {
305 			was_ld_map = false;
306 			dst[i].imm = 0;
307 		} else {
308 			was_ld_map = false;
309 		}
310 	}
311 
312 	psize = bpf_prog_insn_size(fp);
313 	memset(&raw[psize], 0, raw_size - psize);
314 	raw[psize++] = 0x80;
315 
316 	bsize  = round_up(psize, SHA1_BLOCK_SIZE);
317 	blocks = bsize / SHA1_BLOCK_SIZE;
318 	todo   = raw;
319 	if (bsize - psize >= sizeof(__be64)) {
320 		bits = (__be64 *)(todo + bsize - sizeof(__be64));
321 	} else {
322 		bits = (__be64 *)(todo + bsize + bits_offset);
323 		blocks++;
324 	}
325 	*bits = cpu_to_be64((psize - 1) << 3);
326 
327 	while (blocks--) {
328 		sha1_transform(digest, todo, ws);
329 		todo += SHA1_BLOCK_SIZE;
330 	}
331 
332 	result = (__force __be32 *)digest;
333 	for (i = 0; i < SHA1_DIGEST_WORDS; i++)
334 		result[i] = cpu_to_be32(digest[i]);
335 	memcpy(fp->tag, result, sizeof(fp->tag));
336 
337 	vfree(raw);
338 	return 0;
339 }
340 
bpf_adj_delta_to_imm(struct bpf_insn * insn,u32 pos,s32 end_old,s32 end_new,s32 curr,const bool probe_pass)341 static int bpf_adj_delta_to_imm(struct bpf_insn *insn, u32 pos, s32 end_old,
342 				s32 end_new, s32 curr, const bool probe_pass)
343 {
344 	const s64 imm_min = S32_MIN, imm_max = S32_MAX;
345 	s32 delta = end_new - end_old;
346 	s64 imm = insn->imm;
347 
348 	if (curr < pos && curr + imm + 1 >= end_old)
349 		imm += delta;
350 	else if (curr >= end_new && curr + imm + 1 < end_new)
351 		imm -= delta;
352 	if (imm < imm_min || imm > imm_max)
353 		return -ERANGE;
354 	if (!probe_pass)
355 		insn->imm = imm;
356 	return 0;
357 }
358 
bpf_adj_delta_to_off(struct bpf_insn * insn,u32 pos,s32 end_old,s32 end_new,s32 curr,const bool probe_pass)359 static int bpf_adj_delta_to_off(struct bpf_insn *insn, u32 pos, s32 end_old,
360 				s32 end_new, s32 curr, const bool probe_pass)
361 {
362 	const s32 off_min = S16_MIN, off_max = S16_MAX;
363 	s32 delta = end_new - end_old;
364 	s32 off = insn->off;
365 
366 	if (curr < pos && curr + off + 1 >= end_old)
367 		off += delta;
368 	else if (curr >= end_new && curr + off + 1 < end_new)
369 		off -= delta;
370 	if (off < off_min || off > off_max)
371 		return -ERANGE;
372 	if (!probe_pass)
373 		insn->off = off;
374 	return 0;
375 }
376 
bpf_adj_branches(struct bpf_prog * prog,u32 pos,s32 end_old,s32 end_new,const bool probe_pass)377 static int bpf_adj_branches(struct bpf_prog *prog, u32 pos, s32 end_old,
378 			    s32 end_new, const bool probe_pass)
379 {
380 	u32 i, insn_cnt = prog->len + (probe_pass ? end_new - end_old : 0);
381 	struct bpf_insn *insn = prog->insnsi;
382 	int ret = 0;
383 
384 	for (i = 0; i < insn_cnt; i++, insn++) {
385 		u8 code;
386 
387 		/* In the probing pass we still operate on the original,
388 		 * unpatched image in order to check overflows before we
389 		 * do any other adjustments. Therefore skip the patchlet.
390 		 */
391 		if (probe_pass && i == pos) {
392 			i = end_new;
393 			insn = prog->insnsi + end_old;
394 		}
395 		if (bpf_pseudo_func(insn)) {
396 			ret = bpf_adj_delta_to_imm(insn, pos, end_old,
397 						   end_new, i, probe_pass);
398 			if (ret)
399 				return ret;
400 			continue;
401 		}
402 		code = insn->code;
403 		if ((BPF_CLASS(code) != BPF_JMP &&
404 		     BPF_CLASS(code) != BPF_JMP32) ||
405 		    BPF_OP(code) == BPF_EXIT)
406 			continue;
407 		/* Adjust offset of jmps if we cross patch boundaries. */
408 		if (BPF_OP(code) == BPF_CALL) {
409 			if (insn->src_reg != BPF_PSEUDO_CALL)
410 				continue;
411 			ret = bpf_adj_delta_to_imm(insn, pos, end_old,
412 						   end_new, i, probe_pass);
413 		} else {
414 			ret = bpf_adj_delta_to_off(insn, pos, end_old,
415 						   end_new, i, probe_pass);
416 		}
417 		if (ret)
418 			break;
419 	}
420 
421 	return ret;
422 }
423 
bpf_adj_linfo(struct bpf_prog * prog,u32 off,u32 delta)424 static void bpf_adj_linfo(struct bpf_prog *prog, u32 off, u32 delta)
425 {
426 	struct bpf_line_info *linfo;
427 	u32 i, nr_linfo;
428 
429 	nr_linfo = prog->aux->nr_linfo;
430 	if (!nr_linfo || !delta)
431 		return;
432 
433 	linfo = prog->aux->linfo;
434 
435 	for (i = 0; i < nr_linfo; i++)
436 		if (off < linfo[i].insn_off)
437 			break;
438 
439 	/* Push all off < linfo[i].insn_off by delta */
440 	for (; i < nr_linfo; i++)
441 		linfo[i].insn_off += delta;
442 }
443 
bpf_patch_insn_single(struct bpf_prog * prog,u32 off,const struct bpf_insn * patch,u32 len)444 struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off,
445 				       const struct bpf_insn *patch, u32 len)
446 {
447 	u32 insn_adj_cnt, insn_rest, insn_delta = len - 1;
448 	const u32 cnt_max = S16_MAX;
449 	struct bpf_prog *prog_adj;
450 	int err;
451 
452 	/* Since our patchlet doesn't expand the image, we're done. */
453 	if (insn_delta == 0) {
454 		memcpy(prog->insnsi + off, patch, sizeof(*patch));
455 		return prog;
456 	}
457 
458 	insn_adj_cnt = prog->len + insn_delta;
459 
460 	/* Reject anything that would potentially let the insn->off
461 	 * target overflow when we have excessive program expansions.
462 	 * We need to probe here before we do any reallocation where
463 	 * we afterwards may not fail anymore.
464 	 */
465 	if (insn_adj_cnt > cnt_max &&
466 	    (err = bpf_adj_branches(prog, off, off + 1, off + len, true)))
467 		return ERR_PTR(err);
468 
469 	/* Several new instructions need to be inserted. Make room
470 	 * for them. Likely, there's no need for a new allocation as
471 	 * last page could have large enough tailroom.
472 	 */
473 	prog_adj = bpf_prog_realloc(prog, bpf_prog_size(insn_adj_cnt),
474 				    GFP_USER);
475 	if (!prog_adj)
476 		return ERR_PTR(-ENOMEM);
477 
478 	prog_adj->len = insn_adj_cnt;
479 
480 	/* Patching happens in 3 steps:
481 	 *
482 	 * 1) Move over tail of insnsi from next instruction onwards,
483 	 *    so we can patch the single target insn with one or more
484 	 *    new ones (patching is always from 1 to n insns, n > 0).
485 	 * 2) Inject new instructions at the target location.
486 	 * 3) Adjust branch offsets if necessary.
487 	 */
488 	insn_rest = insn_adj_cnt - off - len;
489 
490 	memmove(prog_adj->insnsi + off + len, prog_adj->insnsi + off + 1,
491 		sizeof(*patch) * insn_rest);
492 	memcpy(prog_adj->insnsi + off, patch, sizeof(*patch) * len);
493 
494 	/* We are guaranteed to not fail at this point, otherwise
495 	 * the ship has sailed to reverse to the original state. An
496 	 * overflow cannot happen at this point.
497 	 */
498 	BUG_ON(bpf_adj_branches(prog_adj, off, off + 1, off + len, false));
499 
500 	bpf_adj_linfo(prog_adj, off, insn_delta);
501 
502 	return prog_adj;
503 }
504 
bpf_remove_insns(struct bpf_prog * prog,u32 off,u32 cnt)505 int bpf_remove_insns(struct bpf_prog *prog, u32 off, u32 cnt)
506 {
507 	/* Branch offsets can't overflow when program is shrinking, no need
508 	 * to call bpf_adj_branches(..., true) here
509 	 */
510 	memmove(prog->insnsi + off, prog->insnsi + off + cnt,
511 		sizeof(struct bpf_insn) * (prog->len - off - cnt));
512 	prog->len -= cnt;
513 
514 	return WARN_ON_ONCE(bpf_adj_branches(prog, off, off + cnt, off, false));
515 }
516 
bpf_prog_kallsyms_del_subprogs(struct bpf_prog * fp)517 static void bpf_prog_kallsyms_del_subprogs(struct bpf_prog *fp)
518 {
519 	int i;
520 
521 	for (i = 0; i < fp->aux->func_cnt; i++)
522 		bpf_prog_kallsyms_del(fp->aux->func[i]);
523 }
524 
bpf_prog_kallsyms_del_all(struct bpf_prog * fp)525 void bpf_prog_kallsyms_del_all(struct bpf_prog *fp)
526 {
527 	bpf_prog_kallsyms_del_subprogs(fp);
528 	bpf_prog_kallsyms_del(fp);
529 }
530 
531 #ifdef CONFIG_BPF_JIT
532 /* All BPF JIT sysctl knobs here. */
533 int bpf_jit_enable   __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_DEFAULT_ON);
534 int bpf_jit_kallsyms __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_DEFAULT_ON);
535 int bpf_jit_harden   __read_mostly;
536 long bpf_jit_limit   __read_mostly;
537 long bpf_jit_limit_max __read_mostly;
538 
539 static void
bpf_prog_ksym_set_addr(struct bpf_prog * prog)540 bpf_prog_ksym_set_addr(struct bpf_prog *prog)
541 {
542 	const struct bpf_binary_header *hdr = bpf_jit_binary_hdr(prog);
543 	unsigned long addr = (unsigned long)hdr;
544 
545 	WARN_ON_ONCE(!bpf_prog_ebpf_jited(prog));
546 
547 	prog->aux->ksym.start = (unsigned long) prog->bpf_func;
548 	prog->aux->ksym.end   = addr + hdr->pages * PAGE_SIZE;
549 }
550 
551 static void
bpf_prog_ksym_set_name(struct bpf_prog * prog)552 bpf_prog_ksym_set_name(struct bpf_prog *prog)
553 {
554 	char *sym = prog->aux->ksym.name;
555 	const char *end = sym + KSYM_NAME_LEN;
556 	const struct btf_type *type;
557 	const char *func_name;
558 
559 	BUILD_BUG_ON(sizeof("bpf_prog_") +
560 		     sizeof(prog->tag) * 2 +
561 		     /* name has been null terminated.
562 		      * We should need +1 for the '_' preceding
563 		      * the name.  However, the null character
564 		      * is double counted between the name and the
565 		      * sizeof("bpf_prog_") above, so we omit
566 		      * the +1 here.
567 		      */
568 		     sizeof(prog->aux->name) > KSYM_NAME_LEN);
569 
570 	sym += snprintf(sym, KSYM_NAME_LEN, "bpf_prog_");
571 	sym  = bin2hex(sym, prog->tag, sizeof(prog->tag));
572 
573 	/* prog->aux->name will be ignored if full btf name is available */
574 	if (prog->aux->func_info_cnt) {
575 		type = btf_type_by_id(prog->aux->btf,
576 				      prog->aux->func_info[prog->aux->func_idx].type_id);
577 		func_name = btf_name_by_offset(prog->aux->btf, type->name_off);
578 		snprintf(sym, (size_t)(end - sym), "_%s", func_name);
579 		return;
580 	}
581 
582 	if (prog->aux->name[0])
583 		snprintf(sym, (size_t)(end - sym), "_%s", prog->aux->name);
584 	else
585 		*sym = 0;
586 }
587 
bpf_get_ksym_start(struct latch_tree_node * n)588 static unsigned long bpf_get_ksym_start(struct latch_tree_node *n)
589 {
590 	return container_of(n, struct bpf_ksym, tnode)->start;
591 }
592 
bpf_tree_less(struct latch_tree_node * a,struct latch_tree_node * b)593 static __always_inline bool bpf_tree_less(struct latch_tree_node *a,
594 					  struct latch_tree_node *b)
595 {
596 	return bpf_get_ksym_start(a) < bpf_get_ksym_start(b);
597 }
598 
bpf_tree_comp(void * key,struct latch_tree_node * n)599 static __always_inline int bpf_tree_comp(void *key, struct latch_tree_node *n)
600 {
601 	unsigned long val = (unsigned long)key;
602 	const struct bpf_ksym *ksym;
603 
604 	ksym = container_of(n, struct bpf_ksym, tnode);
605 
606 	if (val < ksym->start)
607 		return -1;
608 	/* Ensure that we detect return addresses as part of the program, when
609 	 * the final instruction is a call for a program part of the stack
610 	 * trace. Therefore, do val > ksym->end instead of val >= ksym->end.
611 	 */
612 	if (val > ksym->end)
613 		return  1;
614 
615 	return 0;
616 }
617 
618 static const struct latch_tree_ops bpf_tree_ops = {
619 	.less	= bpf_tree_less,
620 	.comp	= bpf_tree_comp,
621 };
622 
623 static DEFINE_SPINLOCK(bpf_lock);
624 static LIST_HEAD(bpf_kallsyms);
625 static struct latch_tree_root bpf_tree __cacheline_aligned;
626 
bpf_ksym_add(struct bpf_ksym * ksym)627 void bpf_ksym_add(struct bpf_ksym *ksym)
628 {
629 	spin_lock_bh(&bpf_lock);
630 	WARN_ON_ONCE(!list_empty(&ksym->lnode));
631 	list_add_tail_rcu(&ksym->lnode, &bpf_kallsyms);
632 	latch_tree_insert(&ksym->tnode, &bpf_tree, &bpf_tree_ops);
633 	spin_unlock_bh(&bpf_lock);
634 }
635 
__bpf_ksym_del(struct bpf_ksym * ksym)636 static void __bpf_ksym_del(struct bpf_ksym *ksym)
637 {
638 	if (list_empty(&ksym->lnode))
639 		return;
640 
641 	latch_tree_erase(&ksym->tnode, &bpf_tree, &bpf_tree_ops);
642 	list_del_rcu(&ksym->lnode);
643 }
644 
bpf_ksym_del(struct bpf_ksym * ksym)645 void bpf_ksym_del(struct bpf_ksym *ksym)
646 {
647 	spin_lock_bh(&bpf_lock);
648 	__bpf_ksym_del(ksym);
649 	spin_unlock_bh(&bpf_lock);
650 }
651 
bpf_prog_kallsyms_candidate(const struct bpf_prog * fp)652 static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp)
653 {
654 	return fp->jited && !bpf_prog_was_classic(fp);
655 }
656 
bpf_prog_kallsyms_verify_off(const struct bpf_prog * fp)657 static bool bpf_prog_kallsyms_verify_off(const struct bpf_prog *fp)
658 {
659 	return list_empty(&fp->aux->ksym.lnode) ||
660 	       fp->aux->ksym.lnode.prev == LIST_POISON2;
661 }
662 
bpf_prog_kallsyms_add(struct bpf_prog * fp)663 void bpf_prog_kallsyms_add(struct bpf_prog *fp)
664 {
665 	if (!bpf_prog_kallsyms_candidate(fp) ||
666 	    !bpf_capable())
667 		return;
668 
669 	bpf_prog_ksym_set_addr(fp);
670 	bpf_prog_ksym_set_name(fp);
671 	fp->aux->ksym.prog = true;
672 
673 	bpf_ksym_add(&fp->aux->ksym);
674 }
675 
bpf_prog_kallsyms_del(struct bpf_prog * fp)676 void bpf_prog_kallsyms_del(struct bpf_prog *fp)
677 {
678 	if (!bpf_prog_kallsyms_candidate(fp))
679 		return;
680 
681 	bpf_ksym_del(&fp->aux->ksym);
682 }
683 
bpf_ksym_find(unsigned long addr)684 static struct bpf_ksym *bpf_ksym_find(unsigned long addr)
685 {
686 	struct latch_tree_node *n;
687 
688 	n = latch_tree_find((void *)addr, &bpf_tree, &bpf_tree_ops);
689 	return n ? container_of(n, struct bpf_ksym, tnode) : NULL;
690 }
691 
__bpf_address_lookup(unsigned long addr,unsigned long * size,unsigned long * off,char * sym)692 const char *__bpf_address_lookup(unsigned long addr, unsigned long *size,
693 				 unsigned long *off, char *sym)
694 {
695 	struct bpf_ksym *ksym;
696 	char *ret = NULL;
697 
698 	rcu_read_lock();
699 	ksym = bpf_ksym_find(addr);
700 	if (ksym) {
701 		unsigned long symbol_start = ksym->start;
702 		unsigned long symbol_end = ksym->end;
703 
704 		strncpy(sym, ksym->name, KSYM_NAME_LEN);
705 
706 		ret = sym;
707 		if (size)
708 			*size = symbol_end - symbol_start;
709 		if (off)
710 			*off  = addr - symbol_start;
711 	}
712 	rcu_read_unlock();
713 
714 	return ret;
715 }
716 
is_bpf_text_address(unsigned long addr)717 bool is_bpf_text_address(unsigned long addr)
718 {
719 	bool ret;
720 
721 	rcu_read_lock();
722 	ret = bpf_ksym_find(addr) != NULL;
723 	rcu_read_unlock();
724 
725 	return ret;
726 }
727 
bpf_prog_ksym_find(unsigned long addr)728 static struct bpf_prog *bpf_prog_ksym_find(unsigned long addr)
729 {
730 	struct bpf_ksym *ksym = bpf_ksym_find(addr);
731 
732 	return ksym && ksym->prog ?
733 	       container_of(ksym, struct bpf_prog_aux, ksym)->prog :
734 	       NULL;
735 }
736 
search_bpf_extables(unsigned long addr)737 const struct exception_table_entry *search_bpf_extables(unsigned long addr)
738 {
739 	const struct exception_table_entry *e = NULL;
740 	struct bpf_prog *prog;
741 
742 	rcu_read_lock();
743 	prog = bpf_prog_ksym_find(addr);
744 	if (!prog)
745 		goto out;
746 	if (!prog->aux->num_exentries)
747 		goto out;
748 
749 	e = search_extable(prog->aux->extable, prog->aux->num_exentries, addr);
750 out:
751 	rcu_read_unlock();
752 	return e;
753 }
754 
bpf_get_kallsym(unsigned int symnum,unsigned long * value,char * type,char * sym)755 int bpf_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
756 		    char *sym)
757 {
758 	struct bpf_ksym *ksym;
759 	unsigned int it = 0;
760 	int ret = -ERANGE;
761 
762 	if (!bpf_jit_kallsyms_enabled())
763 		return ret;
764 
765 	rcu_read_lock();
766 	list_for_each_entry_rcu(ksym, &bpf_kallsyms, lnode) {
767 		if (it++ != symnum)
768 			continue;
769 
770 		strncpy(sym, ksym->name, KSYM_NAME_LEN);
771 
772 		*value = ksym->start;
773 		*type  = BPF_SYM_ELF_TYPE;
774 
775 		ret = 0;
776 		break;
777 	}
778 	rcu_read_unlock();
779 
780 	return ret;
781 }
782 
bpf_jit_add_poke_descriptor(struct bpf_prog * prog,struct bpf_jit_poke_descriptor * poke)783 int bpf_jit_add_poke_descriptor(struct bpf_prog *prog,
784 				struct bpf_jit_poke_descriptor *poke)
785 {
786 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
787 	static const u32 poke_tab_max = 1024;
788 	u32 slot = prog->aux->size_poke_tab;
789 	u32 size = slot + 1;
790 
791 	if (size > poke_tab_max)
792 		return -ENOSPC;
793 	if (poke->tailcall_target || poke->tailcall_target_stable ||
794 	    poke->tailcall_bypass || poke->adj_off || poke->bypass_addr)
795 		return -EINVAL;
796 
797 	switch (poke->reason) {
798 	case BPF_POKE_REASON_TAIL_CALL:
799 		if (!poke->tail_call.map)
800 			return -EINVAL;
801 		break;
802 	default:
803 		return -EINVAL;
804 	}
805 
806 	tab = krealloc(tab, size * sizeof(*poke), GFP_KERNEL);
807 	if (!tab)
808 		return -ENOMEM;
809 
810 	memcpy(&tab[slot], poke, sizeof(*poke));
811 	prog->aux->size_poke_tab = size;
812 	prog->aux->poke_tab = tab;
813 
814 	return slot;
815 }
816 
817 static atomic_long_t bpf_jit_current;
818 
819 /* Can be overridden by an arch's JIT compiler if it has a custom,
820  * dedicated BPF backend memory area, or if neither of the two
821  * below apply.
822  */
bpf_jit_alloc_exec_limit(void)823 u64 __weak bpf_jit_alloc_exec_limit(void)
824 {
825 #if defined(MODULES_VADDR)
826 	return MODULES_END - MODULES_VADDR;
827 #else
828 	return VMALLOC_END - VMALLOC_START;
829 #endif
830 }
831 
bpf_jit_charge_init(void)832 static int __init bpf_jit_charge_init(void)
833 {
834 	/* Only used as heuristic here to derive limit. */
835 	bpf_jit_limit_max = bpf_jit_alloc_exec_limit();
836 	bpf_jit_limit = min_t(u64, round_up(bpf_jit_limit_max >> 1,
837 					    PAGE_SIZE), LONG_MAX);
838 	return 0;
839 }
840 pure_initcall(bpf_jit_charge_init);
841 
bpf_jit_charge_modmem(u32 pages)842 int bpf_jit_charge_modmem(u32 pages)
843 {
844 	if (atomic_long_add_return(pages, &bpf_jit_current) >
845 	    (bpf_jit_limit >> PAGE_SHIFT)) {
846 		if (!bpf_capable()) {
847 			atomic_long_sub(pages, &bpf_jit_current);
848 			return -EPERM;
849 		}
850 	}
851 
852 	return 0;
853 }
854 
bpf_jit_uncharge_modmem(u32 pages)855 void bpf_jit_uncharge_modmem(u32 pages)
856 {
857 	atomic_long_sub(pages, &bpf_jit_current);
858 }
859 
bpf_jit_alloc_exec(unsigned long size)860 void *__weak bpf_jit_alloc_exec(unsigned long size)
861 {
862 	return module_alloc(size);
863 }
864 
bpf_jit_free_exec(void * addr)865 void __weak bpf_jit_free_exec(void *addr)
866 {
867 	module_memfree(addr);
868 }
869 
870 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)871 bpf_jit_binary_alloc(unsigned int proglen, u8 **image_ptr,
872 		     unsigned int alignment,
873 		     bpf_jit_fill_hole_t bpf_fill_ill_insns)
874 {
875 	struct bpf_binary_header *hdr;
876 	u32 size, hole, start, pages;
877 
878 	WARN_ON_ONCE(!is_power_of_2(alignment) ||
879 		     alignment > BPF_IMAGE_ALIGNMENT);
880 
881 	/* Most of BPF filters are really small, but if some of them
882 	 * fill a page, allow at least 128 extra bytes to insert a
883 	 * random section of illegal instructions.
884 	 */
885 	size = round_up(proglen + sizeof(*hdr) + 128, PAGE_SIZE);
886 	pages = size / PAGE_SIZE;
887 
888 	if (bpf_jit_charge_modmem(pages))
889 		return NULL;
890 	hdr = bpf_jit_alloc_exec(size);
891 	if (!hdr) {
892 		bpf_jit_uncharge_modmem(pages);
893 		return NULL;
894 	}
895 
896 	/* Fill space with illegal/arch-dep instructions. */
897 	bpf_fill_ill_insns(hdr, size);
898 
899 	hdr->pages = pages;
900 	hole = min_t(unsigned int, size - (proglen + sizeof(*hdr)),
901 		     PAGE_SIZE - sizeof(*hdr));
902 	start = (get_random_int() % hole) & ~(alignment - 1);
903 
904 	/* Leave a random number of instructions before BPF code. */
905 	*image_ptr = &hdr->image[start];
906 
907 	return hdr;
908 }
909 
bpf_jit_binary_free(struct bpf_binary_header * hdr)910 void bpf_jit_binary_free(struct bpf_binary_header *hdr)
911 {
912 	u32 pages = hdr->pages;
913 
914 	bpf_jit_free_exec(hdr);
915 	bpf_jit_uncharge_modmem(pages);
916 }
917 
918 /* This symbol is only overridden by archs that have different
919  * requirements than the usual eBPF JITs, f.e. when they only
920  * implement cBPF JIT, do not set images read-only, etc.
921  */
bpf_jit_free(struct bpf_prog * fp)922 void __weak bpf_jit_free(struct bpf_prog *fp)
923 {
924 	if (fp->jited) {
925 		struct bpf_binary_header *hdr = bpf_jit_binary_hdr(fp);
926 
927 		bpf_jit_binary_free(hdr);
928 
929 		WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(fp));
930 	}
931 
932 	bpf_prog_unlock_free(fp);
933 }
934 
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)935 int bpf_jit_get_func_addr(const struct bpf_prog *prog,
936 			  const struct bpf_insn *insn, bool extra_pass,
937 			  u64 *func_addr, bool *func_addr_fixed)
938 {
939 	s16 off = insn->off;
940 	s32 imm = insn->imm;
941 	u8 *addr;
942 
943 	*func_addr_fixed = insn->src_reg != BPF_PSEUDO_CALL;
944 	if (!*func_addr_fixed) {
945 		/* Place-holder address till the last pass has collected
946 		 * all addresses for JITed subprograms in which case we
947 		 * can pick them up from prog->aux.
948 		 */
949 		if (!extra_pass)
950 			addr = NULL;
951 		else if (prog->aux->func &&
952 			 off >= 0 && off < prog->aux->func_cnt)
953 			addr = (u8 *)prog->aux->func[off]->bpf_func;
954 		else
955 			return -EINVAL;
956 	} else {
957 		/* Address of a BPF helper call. Since part of the core
958 		 * kernel, it's always at a fixed location. __bpf_call_base
959 		 * and the helper with imm relative to it are both in core
960 		 * kernel.
961 		 */
962 		addr = (u8 *)__bpf_call_base + imm;
963 	}
964 
965 	*func_addr = (unsigned long)addr;
966 	return 0;
967 }
968 
bpf_jit_blind_insn(const struct bpf_insn * from,const struct bpf_insn * aux,struct bpf_insn * to_buff,bool emit_zext)969 static int bpf_jit_blind_insn(const struct bpf_insn *from,
970 			      const struct bpf_insn *aux,
971 			      struct bpf_insn *to_buff,
972 			      bool emit_zext)
973 {
974 	struct bpf_insn *to = to_buff;
975 	u32 imm_rnd = get_random_int();
976 	s16 off;
977 
978 	BUILD_BUG_ON(BPF_REG_AX  + 1 != MAX_BPF_JIT_REG);
979 	BUILD_BUG_ON(MAX_BPF_REG + 1 != MAX_BPF_JIT_REG);
980 
981 	/* Constraints on AX register:
982 	 *
983 	 * AX register is inaccessible from user space. It is mapped in
984 	 * all JITs, and used here for constant blinding rewrites. It is
985 	 * typically "stateless" meaning its contents are only valid within
986 	 * the executed instruction, but not across several instructions.
987 	 * There are a few exceptions however which are further detailed
988 	 * below.
989 	 *
990 	 * Constant blinding is only used by JITs, not in the interpreter.
991 	 * The interpreter uses AX in some occasions as a local temporary
992 	 * register e.g. in DIV or MOD instructions.
993 	 *
994 	 * In restricted circumstances, the verifier can also use the AX
995 	 * register for rewrites as long as they do not interfere with
996 	 * the above cases!
997 	 */
998 	if (from->dst_reg == BPF_REG_AX || from->src_reg == BPF_REG_AX)
999 		goto out;
1000 
1001 	if (from->imm == 0 &&
1002 	    (from->code == (BPF_ALU   | BPF_MOV | BPF_K) ||
1003 	     from->code == (BPF_ALU64 | BPF_MOV | BPF_K))) {
1004 		*to++ = BPF_ALU64_REG(BPF_XOR, from->dst_reg, from->dst_reg);
1005 		goto out;
1006 	}
1007 
1008 	switch (from->code) {
1009 	case BPF_ALU | BPF_ADD | BPF_K:
1010 	case BPF_ALU | BPF_SUB | BPF_K:
1011 	case BPF_ALU | BPF_AND | BPF_K:
1012 	case BPF_ALU | BPF_OR  | BPF_K:
1013 	case BPF_ALU | BPF_XOR | BPF_K:
1014 	case BPF_ALU | BPF_MUL | BPF_K:
1015 	case BPF_ALU | BPF_MOV | BPF_K:
1016 	case BPF_ALU | BPF_DIV | BPF_K:
1017 	case BPF_ALU | BPF_MOD | BPF_K:
1018 		*to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1019 		*to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1020 		*to++ = BPF_ALU32_REG(from->code, from->dst_reg, BPF_REG_AX);
1021 		break;
1022 
1023 	case BPF_ALU64 | BPF_ADD | BPF_K:
1024 	case BPF_ALU64 | BPF_SUB | BPF_K:
1025 	case BPF_ALU64 | BPF_AND | BPF_K:
1026 	case BPF_ALU64 | BPF_OR  | BPF_K:
1027 	case BPF_ALU64 | BPF_XOR | BPF_K:
1028 	case BPF_ALU64 | BPF_MUL | BPF_K:
1029 	case BPF_ALU64 | BPF_MOV | BPF_K:
1030 	case BPF_ALU64 | BPF_DIV | BPF_K:
1031 	case BPF_ALU64 | BPF_MOD | BPF_K:
1032 		*to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1033 		*to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1034 		*to++ = BPF_ALU64_REG(from->code, from->dst_reg, BPF_REG_AX);
1035 		break;
1036 
1037 	case BPF_JMP | BPF_JEQ  | BPF_K:
1038 	case BPF_JMP | BPF_JNE  | BPF_K:
1039 	case BPF_JMP | BPF_JGT  | BPF_K:
1040 	case BPF_JMP | BPF_JLT  | BPF_K:
1041 	case BPF_JMP | BPF_JGE  | BPF_K:
1042 	case BPF_JMP | BPF_JLE  | BPF_K:
1043 	case BPF_JMP | BPF_JSGT | BPF_K:
1044 	case BPF_JMP | BPF_JSLT | BPF_K:
1045 	case BPF_JMP | BPF_JSGE | BPF_K:
1046 	case BPF_JMP | BPF_JSLE | BPF_K:
1047 	case BPF_JMP | BPF_JSET | BPF_K:
1048 		/* Accommodate for extra offset in case of a backjump. */
1049 		off = from->off;
1050 		if (off < 0)
1051 			off -= 2;
1052 		*to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1053 		*to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1054 		*to++ = BPF_JMP_REG(from->code, from->dst_reg, BPF_REG_AX, off);
1055 		break;
1056 
1057 	case BPF_JMP32 | BPF_JEQ  | BPF_K:
1058 	case BPF_JMP32 | BPF_JNE  | BPF_K:
1059 	case BPF_JMP32 | BPF_JGT  | BPF_K:
1060 	case BPF_JMP32 | BPF_JLT  | BPF_K:
1061 	case BPF_JMP32 | BPF_JGE  | BPF_K:
1062 	case BPF_JMP32 | BPF_JLE  | BPF_K:
1063 	case BPF_JMP32 | BPF_JSGT | BPF_K:
1064 	case BPF_JMP32 | BPF_JSLT | BPF_K:
1065 	case BPF_JMP32 | BPF_JSGE | BPF_K:
1066 	case BPF_JMP32 | BPF_JSLE | BPF_K:
1067 	case BPF_JMP32 | BPF_JSET | BPF_K:
1068 		/* Accommodate for extra offset in case of a backjump. */
1069 		off = from->off;
1070 		if (off < 0)
1071 			off -= 2;
1072 		*to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1073 		*to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1074 		*to++ = BPF_JMP32_REG(from->code, from->dst_reg, BPF_REG_AX,
1075 				      off);
1076 		break;
1077 
1078 	case BPF_LD | BPF_IMM | BPF_DW:
1079 		*to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[1].imm);
1080 		*to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1081 		*to++ = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
1082 		*to++ = BPF_ALU64_REG(BPF_MOV, aux[0].dst_reg, BPF_REG_AX);
1083 		break;
1084 	case 0: /* Part 2 of BPF_LD | BPF_IMM | BPF_DW. */
1085 		*to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[0].imm);
1086 		*to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1087 		if (emit_zext)
1088 			*to++ = BPF_ZEXT_REG(BPF_REG_AX);
1089 		*to++ = BPF_ALU64_REG(BPF_OR,  aux[0].dst_reg, BPF_REG_AX);
1090 		break;
1091 
1092 	case BPF_ST | BPF_MEM | BPF_DW:
1093 	case BPF_ST | BPF_MEM | BPF_W:
1094 	case BPF_ST | BPF_MEM | BPF_H:
1095 	case BPF_ST | BPF_MEM | BPF_B:
1096 		*to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1097 		*to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1098 		*to++ = BPF_STX_MEM(from->code, from->dst_reg, BPF_REG_AX, from->off);
1099 		break;
1100 	}
1101 out:
1102 	return to - to_buff;
1103 }
1104 
bpf_prog_clone_create(struct bpf_prog * fp_other,gfp_t gfp_extra_flags)1105 static struct bpf_prog *bpf_prog_clone_create(struct bpf_prog *fp_other,
1106 					      gfp_t gfp_extra_flags)
1107 {
1108 	gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
1109 	struct bpf_prog *fp;
1110 
1111 	fp = __vmalloc(fp_other->pages * PAGE_SIZE, gfp_flags);
1112 	if (fp != NULL) {
1113 		/* aux->prog still points to the fp_other one, so
1114 		 * when promoting the clone to the real program,
1115 		 * this still needs to be adapted.
1116 		 */
1117 		memcpy(fp, fp_other, fp_other->pages * PAGE_SIZE);
1118 	}
1119 
1120 	return fp;
1121 }
1122 
bpf_prog_clone_free(struct bpf_prog * fp)1123 static void bpf_prog_clone_free(struct bpf_prog *fp)
1124 {
1125 	/* aux was stolen by the other clone, so we cannot free
1126 	 * it from this path! It will be freed eventually by the
1127 	 * other program on release.
1128 	 *
1129 	 * At this point, we don't need a deferred release since
1130 	 * clone is guaranteed to not be locked.
1131 	 */
1132 	fp->aux = NULL;
1133 	fp->stats = NULL;
1134 	fp->active = NULL;
1135 	__bpf_prog_free(fp);
1136 }
1137 
bpf_jit_prog_release_other(struct bpf_prog * fp,struct bpf_prog * fp_other)1138 void bpf_jit_prog_release_other(struct bpf_prog *fp, struct bpf_prog *fp_other)
1139 {
1140 	/* We have to repoint aux->prog to self, as we don't
1141 	 * know whether fp here is the clone or the original.
1142 	 */
1143 	fp->aux->prog = fp;
1144 	bpf_prog_clone_free(fp_other);
1145 }
1146 
bpf_jit_blind_constants(struct bpf_prog * prog)1147 struct bpf_prog *bpf_jit_blind_constants(struct bpf_prog *prog)
1148 {
1149 	struct bpf_insn insn_buff[16], aux[2];
1150 	struct bpf_prog *clone, *tmp;
1151 	int insn_delta, insn_cnt;
1152 	struct bpf_insn *insn;
1153 	int i, rewritten;
1154 
1155 	if (!bpf_jit_blinding_enabled(prog) || prog->blinded)
1156 		return prog;
1157 
1158 	clone = bpf_prog_clone_create(prog, GFP_USER);
1159 	if (!clone)
1160 		return ERR_PTR(-ENOMEM);
1161 
1162 	insn_cnt = clone->len;
1163 	insn = clone->insnsi;
1164 
1165 	for (i = 0; i < insn_cnt; i++, insn++) {
1166 		/* We temporarily need to hold the original ld64 insn
1167 		 * so that we can still access the first part in the
1168 		 * second blinding run.
1169 		 */
1170 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW) &&
1171 		    insn[1].code == 0)
1172 			memcpy(aux, insn, sizeof(aux));
1173 
1174 		rewritten = bpf_jit_blind_insn(insn, aux, insn_buff,
1175 						clone->aux->verifier_zext);
1176 		if (!rewritten)
1177 			continue;
1178 
1179 		tmp = bpf_patch_insn_single(clone, i, insn_buff, rewritten);
1180 		if (IS_ERR(tmp)) {
1181 			/* Patching may have repointed aux->prog during
1182 			 * realloc from the original one, so we need to
1183 			 * fix it up here on error.
1184 			 */
1185 			bpf_jit_prog_release_other(prog, clone);
1186 			return tmp;
1187 		}
1188 
1189 		clone = tmp;
1190 		insn_delta = rewritten - 1;
1191 
1192 		/* Walk new program and skip insns we just inserted. */
1193 		insn = clone->insnsi + i + insn_delta;
1194 		insn_cnt += insn_delta;
1195 		i        += insn_delta;
1196 	}
1197 
1198 	clone->blinded = 1;
1199 	return clone;
1200 }
1201 #endif /* CONFIG_BPF_JIT */
1202 
1203 /* Base function for offset calculation. Needs to go into .text section,
1204  * therefore keeping it non-static as well; will also be used by JITs
1205  * anyway later on, so do not let the compiler omit it. This also needs
1206  * to go into kallsyms for correlation from e.g. bpftool, so naming
1207  * must not change.
1208  */
__bpf_call_base(u64 r1,u64 r2,u64 r3,u64 r4,u64 r5)1209 noinline u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
1210 {
1211 	return 0;
1212 }
1213 EXPORT_SYMBOL_GPL(__bpf_call_base);
1214 
1215 /* All UAPI available opcodes. */
1216 #define BPF_INSN_MAP(INSN_2, INSN_3)		\
1217 	/* 32 bit ALU operations. */		\
1218 	/*   Register based. */			\
1219 	INSN_3(ALU, ADD,  X),			\
1220 	INSN_3(ALU, SUB,  X),			\
1221 	INSN_3(ALU, AND,  X),			\
1222 	INSN_3(ALU, OR,   X),			\
1223 	INSN_3(ALU, LSH,  X),			\
1224 	INSN_3(ALU, RSH,  X),			\
1225 	INSN_3(ALU, XOR,  X),			\
1226 	INSN_3(ALU, MUL,  X),			\
1227 	INSN_3(ALU, MOV,  X),			\
1228 	INSN_3(ALU, ARSH, X),			\
1229 	INSN_3(ALU, DIV,  X),			\
1230 	INSN_3(ALU, MOD,  X),			\
1231 	INSN_2(ALU, NEG),			\
1232 	INSN_3(ALU, END, TO_BE),		\
1233 	INSN_3(ALU, END, TO_LE),		\
1234 	/*   Immediate based. */		\
1235 	INSN_3(ALU, ADD,  K),			\
1236 	INSN_3(ALU, SUB,  K),			\
1237 	INSN_3(ALU, AND,  K),			\
1238 	INSN_3(ALU, OR,   K),			\
1239 	INSN_3(ALU, LSH,  K),			\
1240 	INSN_3(ALU, RSH,  K),			\
1241 	INSN_3(ALU, XOR,  K),			\
1242 	INSN_3(ALU, MUL,  K),			\
1243 	INSN_3(ALU, MOV,  K),			\
1244 	INSN_3(ALU, ARSH, K),			\
1245 	INSN_3(ALU, DIV,  K),			\
1246 	INSN_3(ALU, MOD,  K),			\
1247 	/* 64 bit ALU operations. */		\
1248 	/*   Register based. */			\
1249 	INSN_3(ALU64, ADD,  X),			\
1250 	INSN_3(ALU64, SUB,  X),			\
1251 	INSN_3(ALU64, AND,  X),			\
1252 	INSN_3(ALU64, OR,   X),			\
1253 	INSN_3(ALU64, LSH,  X),			\
1254 	INSN_3(ALU64, RSH,  X),			\
1255 	INSN_3(ALU64, XOR,  X),			\
1256 	INSN_3(ALU64, MUL,  X),			\
1257 	INSN_3(ALU64, MOV,  X),			\
1258 	INSN_3(ALU64, ARSH, X),			\
1259 	INSN_3(ALU64, DIV,  X),			\
1260 	INSN_3(ALU64, MOD,  X),			\
1261 	INSN_2(ALU64, NEG),			\
1262 	/*   Immediate based. */		\
1263 	INSN_3(ALU64, ADD,  K),			\
1264 	INSN_3(ALU64, SUB,  K),			\
1265 	INSN_3(ALU64, AND,  K),			\
1266 	INSN_3(ALU64, OR,   K),			\
1267 	INSN_3(ALU64, LSH,  K),			\
1268 	INSN_3(ALU64, RSH,  K),			\
1269 	INSN_3(ALU64, XOR,  K),			\
1270 	INSN_3(ALU64, MUL,  K),			\
1271 	INSN_3(ALU64, MOV,  K),			\
1272 	INSN_3(ALU64, ARSH, K),			\
1273 	INSN_3(ALU64, DIV,  K),			\
1274 	INSN_3(ALU64, MOD,  K),			\
1275 	/* Call instruction. */			\
1276 	INSN_2(JMP, CALL),			\
1277 	/* Exit instruction. */			\
1278 	INSN_2(JMP, EXIT),			\
1279 	/* 32-bit Jump instructions. */		\
1280 	/*   Register based. */			\
1281 	INSN_3(JMP32, JEQ,  X),			\
1282 	INSN_3(JMP32, JNE,  X),			\
1283 	INSN_3(JMP32, JGT,  X),			\
1284 	INSN_3(JMP32, JLT,  X),			\
1285 	INSN_3(JMP32, JGE,  X),			\
1286 	INSN_3(JMP32, JLE,  X),			\
1287 	INSN_3(JMP32, JSGT, X),			\
1288 	INSN_3(JMP32, JSLT, X),			\
1289 	INSN_3(JMP32, JSGE, X),			\
1290 	INSN_3(JMP32, JSLE, X),			\
1291 	INSN_3(JMP32, JSET, X),			\
1292 	/*   Immediate based. */		\
1293 	INSN_3(JMP32, JEQ,  K),			\
1294 	INSN_3(JMP32, JNE,  K),			\
1295 	INSN_3(JMP32, JGT,  K),			\
1296 	INSN_3(JMP32, JLT,  K),			\
1297 	INSN_3(JMP32, JGE,  K),			\
1298 	INSN_3(JMP32, JLE,  K),			\
1299 	INSN_3(JMP32, JSGT, K),			\
1300 	INSN_3(JMP32, JSLT, K),			\
1301 	INSN_3(JMP32, JSGE, K),			\
1302 	INSN_3(JMP32, JSLE, K),			\
1303 	INSN_3(JMP32, JSET, K),			\
1304 	/* Jump instructions. */		\
1305 	/*   Register based. */			\
1306 	INSN_3(JMP, JEQ,  X),			\
1307 	INSN_3(JMP, JNE,  X),			\
1308 	INSN_3(JMP, JGT,  X),			\
1309 	INSN_3(JMP, JLT,  X),			\
1310 	INSN_3(JMP, JGE,  X),			\
1311 	INSN_3(JMP, JLE,  X),			\
1312 	INSN_3(JMP, JSGT, X),			\
1313 	INSN_3(JMP, JSLT, X),			\
1314 	INSN_3(JMP, JSGE, X),			\
1315 	INSN_3(JMP, JSLE, X),			\
1316 	INSN_3(JMP, JSET, X),			\
1317 	/*   Immediate based. */		\
1318 	INSN_3(JMP, JEQ,  K),			\
1319 	INSN_3(JMP, JNE,  K),			\
1320 	INSN_3(JMP, JGT,  K),			\
1321 	INSN_3(JMP, JLT,  K),			\
1322 	INSN_3(JMP, JGE,  K),			\
1323 	INSN_3(JMP, JLE,  K),			\
1324 	INSN_3(JMP, JSGT, K),			\
1325 	INSN_3(JMP, JSLT, K),			\
1326 	INSN_3(JMP, JSGE, K),			\
1327 	INSN_3(JMP, JSLE, K),			\
1328 	INSN_3(JMP, JSET, K),			\
1329 	INSN_2(JMP, JA),			\
1330 	/* Store instructions. */		\
1331 	/*   Register based. */			\
1332 	INSN_3(STX, MEM,  B),			\
1333 	INSN_3(STX, MEM,  H),			\
1334 	INSN_3(STX, MEM,  W),			\
1335 	INSN_3(STX, MEM,  DW),			\
1336 	INSN_3(STX, ATOMIC, W),			\
1337 	INSN_3(STX, ATOMIC, DW),		\
1338 	/*   Immediate based. */		\
1339 	INSN_3(ST, MEM, B),			\
1340 	INSN_3(ST, MEM, H),			\
1341 	INSN_3(ST, MEM, W),			\
1342 	INSN_3(ST, MEM, DW),			\
1343 	/* Load instructions. */		\
1344 	/*   Register based. */			\
1345 	INSN_3(LDX, MEM, B),			\
1346 	INSN_3(LDX, MEM, H),			\
1347 	INSN_3(LDX, MEM, W),			\
1348 	INSN_3(LDX, MEM, DW),			\
1349 	/*   Immediate based. */		\
1350 	INSN_3(LD, IMM, DW)
1351 
bpf_opcode_in_insntable(u8 code)1352 bool bpf_opcode_in_insntable(u8 code)
1353 {
1354 #define BPF_INSN_2_TBL(x, y)    [BPF_##x | BPF_##y] = true
1355 #define BPF_INSN_3_TBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = true
1356 	static const bool public_insntable[256] = {
1357 		[0 ... 255] = false,
1358 		/* Now overwrite non-defaults ... */
1359 		BPF_INSN_MAP(BPF_INSN_2_TBL, BPF_INSN_3_TBL),
1360 		/* UAPI exposed, but rewritten opcodes. cBPF carry-over. */
1361 		[BPF_LD | BPF_ABS | BPF_B] = true,
1362 		[BPF_LD | BPF_ABS | BPF_H] = true,
1363 		[BPF_LD | BPF_ABS | BPF_W] = true,
1364 		[BPF_LD | BPF_IND | BPF_B] = true,
1365 		[BPF_LD | BPF_IND | BPF_H] = true,
1366 		[BPF_LD | BPF_IND | BPF_W] = true,
1367 	};
1368 #undef BPF_INSN_3_TBL
1369 #undef BPF_INSN_2_TBL
1370 	return public_insntable[code];
1371 }
1372 
1373 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
bpf_probe_read_kernel(void * dst,u32 size,const void * unsafe_ptr)1374 u64 __weak bpf_probe_read_kernel(void *dst, u32 size, const void *unsafe_ptr)
1375 {
1376 	memset(dst, 0, size);
1377 	return -EFAULT;
1378 }
1379 
1380 /**
1381  *	___bpf_prog_run - run eBPF program on a given context
1382  *	@regs: is the array of MAX_BPF_EXT_REG eBPF pseudo-registers
1383  *	@insn: is the array of eBPF instructions
1384  *
1385  * Decode and execute eBPF instructions.
1386  *
1387  * Return: whatever value is in %BPF_R0 at program exit
1388  */
___bpf_prog_run(u64 * regs,const struct bpf_insn * insn)1389 static u64 ___bpf_prog_run(u64 *regs, const struct bpf_insn *insn)
1390 {
1391 #define BPF_INSN_2_LBL(x, y)    [BPF_##x | BPF_##y] = &&x##_##y
1392 #define BPF_INSN_3_LBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = &&x##_##y##_##z
1393 	static const void * const jumptable[256] __annotate_jump_table = {
1394 		[0 ... 255] = &&default_label,
1395 		/* Now overwrite non-defaults ... */
1396 		BPF_INSN_MAP(BPF_INSN_2_LBL, BPF_INSN_3_LBL),
1397 		/* Non-UAPI available opcodes. */
1398 		[BPF_JMP | BPF_CALL_ARGS] = &&JMP_CALL_ARGS,
1399 		[BPF_JMP | BPF_TAIL_CALL] = &&JMP_TAIL_CALL,
1400 		[BPF_ST  | BPF_NOSPEC] = &&ST_NOSPEC,
1401 		[BPF_LDX | BPF_PROBE_MEM | BPF_B] = &&LDX_PROBE_MEM_B,
1402 		[BPF_LDX | BPF_PROBE_MEM | BPF_H] = &&LDX_PROBE_MEM_H,
1403 		[BPF_LDX | BPF_PROBE_MEM | BPF_W] = &&LDX_PROBE_MEM_W,
1404 		[BPF_LDX | BPF_PROBE_MEM | BPF_DW] = &&LDX_PROBE_MEM_DW,
1405 	};
1406 #undef BPF_INSN_3_LBL
1407 #undef BPF_INSN_2_LBL
1408 	u32 tail_call_cnt = 0;
1409 
1410 #define CONT	 ({ insn++; goto select_insn; })
1411 #define CONT_JMP ({ insn++; goto select_insn; })
1412 
1413 select_insn:
1414 	goto *jumptable[insn->code];
1415 
1416 	/* Explicitly mask the register-based shift amounts with 63 or 31
1417 	 * to avoid undefined behavior. Normally this won't affect the
1418 	 * generated code, for example, in case of native 64 bit archs such
1419 	 * as x86-64 or arm64, the compiler is optimizing the AND away for
1420 	 * the interpreter. In case of JITs, each of the JIT backends compiles
1421 	 * the BPF shift operations to machine instructions which produce
1422 	 * implementation-defined results in such a case; the resulting
1423 	 * contents of the register may be arbitrary, but program behaviour
1424 	 * as a whole remains defined. In other words, in case of JIT backends,
1425 	 * the AND must /not/ be added to the emitted LSH/RSH/ARSH translation.
1426 	 */
1427 	/* ALU (shifts) */
1428 #define SHT(OPCODE, OP)					\
1429 	ALU64_##OPCODE##_X:				\
1430 		DST = DST OP (SRC & 63);		\
1431 		CONT;					\
1432 	ALU_##OPCODE##_X:				\
1433 		DST = (u32) DST OP ((u32) SRC & 31);	\
1434 		CONT;					\
1435 	ALU64_##OPCODE##_K:				\
1436 		DST = DST OP IMM;			\
1437 		CONT;					\
1438 	ALU_##OPCODE##_K:				\
1439 		DST = (u32) DST OP (u32) IMM;		\
1440 		CONT;
1441 	/* ALU (rest) */
1442 #define ALU(OPCODE, OP)					\
1443 	ALU64_##OPCODE##_X:				\
1444 		DST = DST OP SRC;			\
1445 		CONT;					\
1446 	ALU_##OPCODE##_X:				\
1447 		DST = (u32) DST OP (u32) SRC;		\
1448 		CONT;					\
1449 	ALU64_##OPCODE##_K:				\
1450 		DST = DST OP IMM;			\
1451 		CONT;					\
1452 	ALU_##OPCODE##_K:				\
1453 		DST = (u32) DST OP (u32) IMM;		\
1454 		CONT;
1455 	ALU(ADD,  +)
1456 	ALU(SUB,  -)
1457 	ALU(AND,  &)
1458 	ALU(OR,   |)
1459 	ALU(XOR,  ^)
1460 	ALU(MUL,  *)
1461 	SHT(LSH, <<)
1462 	SHT(RSH, >>)
1463 #undef SHT
1464 #undef ALU
1465 	ALU_NEG:
1466 		DST = (u32) -DST;
1467 		CONT;
1468 	ALU64_NEG:
1469 		DST = -DST;
1470 		CONT;
1471 	ALU_MOV_X:
1472 		DST = (u32) SRC;
1473 		CONT;
1474 	ALU_MOV_K:
1475 		DST = (u32) IMM;
1476 		CONT;
1477 	ALU64_MOV_X:
1478 		DST = SRC;
1479 		CONT;
1480 	ALU64_MOV_K:
1481 		DST = IMM;
1482 		CONT;
1483 	LD_IMM_DW:
1484 		DST = (u64) (u32) insn[0].imm | ((u64) (u32) insn[1].imm) << 32;
1485 		insn++;
1486 		CONT;
1487 	ALU_ARSH_X:
1488 		DST = (u64) (u32) (((s32) DST) >> (SRC & 31));
1489 		CONT;
1490 	ALU_ARSH_K:
1491 		DST = (u64) (u32) (((s32) DST) >> IMM);
1492 		CONT;
1493 	ALU64_ARSH_X:
1494 		(*(s64 *) &DST) >>= (SRC & 63);
1495 		CONT;
1496 	ALU64_ARSH_K:
1497 		(*(s64 *) &DST) >>= IMM;
1498 		CONT;
1499 	ALU64_MOD_X:
1500 		div64_u64_rem(DST, SRC, &AX);
1501 		DST = AX;
1502 		CONT;
1503 	ALU_MOD_X:
1504 		AX = (u32) DST;
1505 		DST = do_div(AX, (u32) SRC);
1506 		CONT;
1507 	ALU64_MOD_K:
1508 		div64_u64_rem(DST, IMM, &AX);
1509 		DST = AX;
1510 		CONT;
1511 	ALU_MOD_K:
1512 		AX = (u32) DST;
1513 		DST = do_div(AX, (u32) IMM);
1514 		CONT;
1515 	ALU64_DIV_X:
1516 		DST = div64_u64(DST, SRC);
1517 		CONT;
1518 	ALU_DIV_X:
1519 		AX = (u32) DST;
1520 		do_div(AX, (u32) SRC);
1521 		DST = (u32) AX;
1522 		CONT;
1523 	ALU64_DIV_K:
1524 		DST = div64_u64(DST, IMM);
1525 		CONT;
1526 	ALU_DIV_K:
1527 		AX = (u32) DST;
1528 		do_div(AX, (u32) IMM);
1529 		DST = (u32) AX;
1530 		CONT;
1531 	ALU_END_TO_BE:
1532 		switch (IMM) {
1533 		case 16:
1534 			DST = (__force u16) cpu_to_be16(DST);
1535 			break;
1536 		case 32:
1537 			DST = (__force u32) cpu_to_be32(DST);
1538 			break;
1539 		case 64:
1540 			DST = (__force u64) cpu_to_be64(DST);
1541 			break;
1542 		}
1543 		CONT;
1544 	ALU_END_TO_LE:
1545 		switch (IMM) {
1546 		case 16:
1547 			DST = (__force u16) cpu_to_le16(DST);
1548 			break;
1549 		case 32:
1550 			DST = (__force u32) cpu_to_le32(DST);
1551 			break;
1552 		case 64:
1553 			DST = (__force u64) cpu_to_le64(DST);
1554 			break;
1555 		}
1556 		CONT;
1557 
1558 	/* CALL */
1559 	JMP_CALL:
1560 		/* Function call scratches BPF_R1-BPF_R5 registers,
1561 		 * preserves BPF_R6-BPF_R9, and stores return value
1562 		 * into BPF_R0.
1563 		 */
1564 		BPF_R0 = (__bpf_call_base + insn->imm)(BPF_R1, BPF_R2, BPF_R3,
1565 						       BPF_R4, BPF_R5);
1566 		CONT;
1567 
1568 	JMP_CALL_ARGS:
1569 		BPF_R0 = (__bpf_call_base_args + insn->imm)(BPF_R1, BPF_R2,
1570 							    BPF_R3, BPF_R4,
1571 							    BPF_R5,
1572 							    insn + insn->off + 1);
1573 		CONT;
1574 
1575 	JMP_TAIL_CALL: {
1576 		struct bpf_map *map = (struct bpf_map *) (unsigned long) BPF_R2;
1577 		struct bpf_array *array = container_of(map, struct bpf_array, map);
1578 		struct bpf_prog *prog;
1579 		u32 index = BPF_R3;
1580 
1581 		if (unlikely(index >= array->map.max_entries))
1582 			goto out;
1583 		if (unlikely(tail_call_cnt > MAX_TAIL_CALL_CNT))
1584 			goto out;
1585 
1586 		tail_call_cnt++;
1587 
1588 		prog = READ_ONCE(array->ptrs[index]);
1589 		if (!prog)
1590 			goto out;
1591 
1592 		/* ARG1 at this point is guaranteed to point to CTX from
1593 		 * the verifier side due to the fact that the tail call is
1594 		 * handled like a helper, that is, bpf_tail_call_proto,
1595 		 * where arg1_type is ARG_PTR_TO_CTX.
1596 		 */
1597 		insn = prog->insnsi;
1598 		goto select_insn;
1599 out:
1600 		CONT;
1601 	}
1602 	JMP_JA:
1603 		insn += insn->off;
1604 		CONT;
1605 	JMP_EXIT:
1606 		return BPF_R0;
1607 	/* JMP */
1608 #define COND_JMP(SIGN, OPCODE, CMP_OP)				\
1609 	JMP_##OPCODE##_X:					\
1610 		if ((SIGN##64) DST CMP_OP (SIGN##64) SRC) {	\
1611 			insn += insn->off;			\
1612 			CONT_JMP;				\
1613 		}						\
1614 		CONT;						\
1615 	JMP32_##OPCODE##_X:					\
1616 		if ((SIGN##32) DST CMP_OP (SIGN##32) SRC) {	\
1617 			insn += insn->off;			\
1618 			CONT_JMP;				\
1619 		}						\
1620 		CONT;						\
1621 	JMP_##OPCODE##_K:					\
1622 		if ((SIGN##64) DST CMP_OP (SIGN##64) IMM) {	\
1623 			insn += insn->off;			\
1624 			CONT_JMP;				\
1625 		}						\
1626 		CONT;						\
1627 	JMP32_##OPCODE##_K:					\
1628 		if ((SIGN##32) DST CMP_OP (SIGN##32) IMM) {	\
1629 			insn += insn->off;			\
1630 			CONT_JMP;				\
1631 		}						\
1632 		CONT;
1633 	COND_JMP(u, JEQ, ==)
1634 	COND_JMP(u, JNE, !=)
1635 	COND_JMP(u, JGT, >)
1636 	COND_JMP(u, JLT, <)
1637 	COND_JMP(u, JGE, >=)
1638 	COND_JMP(u, JLE, <=)
1639 	COND_JMP(u, JSET, &)
1640 	COND_JMP(s, JSGT, >)
1641 	COND_JMP(s, JSLT, <)
1642 	COND_JMP(s, JSGE, >=)
1643 	COND_JMP(s, JSLE, <=)
1644 #undef COND_JMP
1645 	/* ST, STX and LDX*/
1646 	ST_NOSPEC:
1647 		/* Speculation barrier for mitigating Speculative Store Bypass.
1648 		 * In case of arm64, we rely on the firmware mitigation as
1649 		 * controlled via the ssbd kernel parameter. Whenever the
1650 		 * mitigation is enabled, it works for all of the kernel code
1651 		 * with no need to provide any additional instructions here.
1652 		 * In case of x86, we use 'lfence' insn for mitigation. We
1653 		 * reuse preexisting logic from Spectre v1 mitigation that
1654 		 * happens to produce the required code on x86 for v4 as well.
1655 		 */
1656 		barrier_nospec();
1657 		CONT;
1658 #define LDST(SIZEOP, SIZE)						\
1659 	STX_MEM_##SIZEOP:						\
1660 		*(SIZE *)(unsigned long) (DST + insn->off) = SRC;	\
1661 		CONT;							\
1662 	ST_MEM_##SIZEOP:						\
1663 		*(SIZE *)(unsigned long) (DST + insn->off) = IMM;	\
1664 		CONT;							\
1665 	LDX_MEM_##SIZEOP:						\
1666 		DST = *(SIZE *)(unsigned long) (SRC + insn->off);	\
1667 		CONT;							\
1668 	LDX_PROBE_MEM_##SIZEOP:						\
1669 		bpf_probe_read_kernel(&DST, sizeof(SIZE),		\
1670 				      (const void *)(long) (SRC + insn->off));	\
1671 		DST = *((SIZE *)&DST);					\
1672 		CONT;
1673 
1674 	LDST(B,   u8)
1675 	LDST(H,  u16)
1676 	LDST(W,  u32)
1677 	LDST(DW, u64)
1678 #undef LDST
1679 
1680 #define ATOMIC_ALU_OP(BOP, KOP)						\
1681 		case BOP:						\
1682 			if (BPF_SIZE(insn->code) == BPF_W)		\
1683 				atomic_##KOP((u32) SRC, (atomic_t *)(unsigned long) \
1684 					     (DST + insn->off));	\
1685 			else						\
1686 				atomic64_##KOP((u64) SRC, (atomic64_t *)(unsigned long) \
1687 					       (DST + insn->off));	\
1688 			break;						\
1689 		case BOP | BPF_FETCH:					\
1690 			if (BPF_SIZE(insn->code) == BPF_W)		\
1691 				SRC = (u32) atomic_fetch_##KOP(		\
1692 					(u32) SRC,			\
1693 					(atomic_t *)(unsigned long) (DST + insn->off)); \
1694 			else						\
1695 				SRC = (u64) atomic64_fetch_##KOP(	\
1696 					(u64) SRC,			\
1697 					(atomic64_t *)(unsigned long) (DST + insn->off)); \
1698 			break;
1699 
1700 	STX_ATOMIC_DW:
1701 	STX_ATOMIC_W:
1702 		switch (IMM) {
1703 		ATOMIC_ALU_OP(BPF_ADD, add)
1704 		ATOMIC_ALU_OP(BPF_AND, and)
1705 		ATOMIC_ALU_OP(BPF_OR, or)
1706 		ATOMIC_ALU_OP(BPF_XOR, xor)
1707 #undef ATOMIC_ALU_OP
1708 
1709 		case BPF_XCHG:
1710 			if (BPF_SIZE(insn->code) == BPF_W)
1711 				SRC = (u32) atomic_xchg(
1712 					(atomic_t *)(unsigned long) (DST + insn->off),
1713 					(u32) SRC);
1714 			else
1715 				SRC = (u64) atomic64_xchg(
1716 					(atomic64_t *)(unsigned long) (DST + insn->off),
1717 					(u64) SRC);
1718 			break;
1719 		case BPF_CMPXCHG:
1720 			if (BPF_SIZE(insn->code) == BPF_W)
1721 				BPF_R0 = (u32) atomic_cmpxchg(
1722 					(atomic_t *)(unsigned long) (DST + insn->off),
1723 					(u32) BPF_R0, (u32) SRC);
1724 			else
1725 				BPF_R0 = (u64) atomic64_cmpxchg(
1726 					(atomic64_t *)(unsigned long) (DST + insn->off),
1727 					(u64) BPF_R0, (u64) SRC);
1728 			break;
1729 
1730 		default:
1731 			goto default_label;
1732 		}
1733 		CONT;
1734 
1735 	default_label:
1736 		/* If we ever reach this, we have a bug somewhere. Die hard here
1737 		 * instead of just returning 0; we could be somewhere in a subprog,
1738 		 * so execution could continue otherwise which we do /not/ want.
1739 		 *
1740 		 * Note, verifier whitelists all opcodes in bpf_opcode_in_insntable().
1741 		 */
1742 		pr_warn("BPF interpreter: unknown opcode %02x (imm: 0x%x)\n",
1743 			insn->code, insn->imm);
1744 		BUG_ON(1);
1745 		return 0;
1746 }
1747 
1748 #define PROG_NAME(stack_size) __bpf_prog_run##stack_size
1749 #define DEFINE_BPF_PROG_RUN(stack_size) \
1750 static unsigned int PROG_NAME(stack_size)(const void *ctx, const struct bpf_insn *insn) \
1751 { \
1752 	u64 stack[stack_size / sizeof(u64)]; \
1753 	u64 regs[MAX_BPF_EXT_REG]; \
1754 \
1755 	FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
1756 	ARG1 = (u64) (unsigned long) ctx; \
1757 	return ___bpf_prog_run(regs, insn); \
1758 }
1759 
1760 #define PROG_NAME_ARGS(stack_size) __bpf_prog_run_args##stack_size
1761 #define DEFINE_BPF_PROG_RUN_ARGS(stack_size) \
1762 static u64 PROG_NAME_ARGS(stack_size)(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, \
1763 				      const struct bpf_insn *insn) \
1764 { \
1765 	u64 stack[stack_size / sizeof(u64)]; \
1766 	u64 regs[MAX_BPF_EXT_REG]; \
1767 \
1768 	FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
1769 	BPF_R1 = r1; \
1770 	BPF_R2 = r2; \
1771 	BPF_R3 = r3; \
1772 	BPF_R4 = r4; \
1773 	BPF_R5 = r5; \
1774 	return ___bpf_prog_run(regs, insn); \
1775 }
1776 
1777 #define EVAL1(FN, X) FN(X)
1778 #define EVAL2(FN, X, Y...) FN(X) EVAL1(FN, Y)
1779 #define EVAL3(FN, X, Y...) FN(X) EVAL2(FN, Y)
1780 #define EVAL4(FN, X, Y...) FN(X) EVAL3(FN, Y)
1781 #define EVAL5(FN, X, Y...) FN(X) EVAL4(FN, Y)
1782 #define EVAL6(FN, X, Y...) FN(X) EVAL5(FN, Y)
1783 
1784 EVAL6(DEFINE_BPF_PROG_RUN, 32, 64, 96, 128, 160, 192);
1785 EVAL6(DEFINE_BPF_PROG_RUN, 224, 256, 288, 320, 352, 384);
1786 EVAL4(DEFINE_BPF_PROG_RUN, 416, 448, 480, 512);
1787 
1788 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 32, 64, 96, 128, 160, 192);
1789 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 224, 256, 288, 320, 352, 384);
1790 EVAL4(DEFINE_BPF_PROG_RUN_ARGS, 416, 448, 480, 512);
1791 
1792 #define PROG_NAME_LIST(stack_size) PROG_NAME(stack_size),
1793 
1794 static unsigned int (*interpreters[])(const void *ctx,
1795 				      const struct bpf_insn *insn) = {
1796 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
1797 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
1798 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
1799 };
1800 #undef PROG_NAME_LIST
1801 #define PROG_NAME_LIST(stack_size) PROG_NAME_ARGS(stack_size),
1802 static u64 (*interpreters_args[])(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5,
1803 				  const struct bpf_insn *insn) = {
1804 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
1805 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
1806 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
1807 };
1808 #undef PROG_NAME_LIST
1809 
bpf_patch_call_args(struct bpf_insn * insn,u32 stack_depth)1810 void bpf_patch_call_args(struct bpf_insn *insn, u32 stack_depth)
1811 {
1812 	stack_depth = max_t(u32, stack_depth, 1);
1813 	insn->off = (s16) insn->imm;
1814 	insn->imm = interpreters_args[(round_up(stack_depth, 32) / 32) - 1] -
1815 		__bpf_call_base_args;
1816 	insn->code = BPF_JMP | BPF_CALL_ARGS;
1817 }
1818 
1819 #else
__bpf_prog_ret0_warn(const void * ctx,const struct bpf_insn * insn)1820 static unsigned int __bpf_prog_ret0_warn(const void *ctx,
1821 					 const struct bpf_insn *insn)
1822 {
1823 	/* If this handler ever gets executed, then BPF_JIT_ALWAYS_ON
1824 	 * is not working properly, so warn about it!
1825 	 */
1826 	WARN_ON_ONCE(1);
1827 	return 0;
1828 }
1829 #endif
1830 
bpf_prog_array_compatible(struct bpf_array * array,const struct bpf_prog * fp)1831 bool bpf_prog_array_compatible(struct bpf_array *array,
1832 			       const struct bpf_prog *fp)
1833 {
1834 	bool ret;
1835 
1836 	if (fp->kprobe_override)
1837 		return false;
1838 
1839 	spin_lock(&array->aux->owner.lock);
1840 
1841 	if (!array->aux->owner.type) {
1842 		/* There's no owner yet where we could check for
1843 		 * compatibility.
1844 		 */
1845 		array->aux->owner.type  = fp->type;
1846 		array->aux->owner.jited = fp->jited;
1847 		ret = true;
1848 	} else {
1849 		ret = array->aux->owner.type  == fp->type &&
1850 		      array->aux->owner.jited == fp->jited;
1851 	}
1852 	spin_unlock(&array->aux->owner.lock);
1853 	return ret;
1854 }
1855 
bpf_check_tail_call(const struct bpf_prog * fp)1856 static int bpf_check_tail_call(const struct bpf_prog *fp)
1857 {
1858 	struct bpf_prog_aux *aux = fp->aux;
1859 	int i, ret = 0;
1860 
1861 	mutex_lock(&aux->used_maps_mutex);
1862 	for (i = 0; i < aux->used_map_cnt; i++) {
1863 		struct bpf_map *map = aux->used_maps[i];
1864 		struct bpf_array *array;
1865 
1866 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1867 			continue;
1868 
1869 		array = container_of(map, struct bpf_array, map);
1870 		if (!bpf_prog_array_compatible(array, fp)) {
1871 			ret = -EINVAL;
1872 			goto out;
1873 		}
1874 	}
1875 
1876 out:
1877 	mutex_unlock(&aux->used_maps_mutex);
1878 	return ret;
1879 }
1880 
bpf_prog_select_func(struct bpf_prog * fp)1881 static void bpf_prog_select_func(struct bpf_prog *fp)
1882 {
1883 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1884 	u32 stack_depth = max_t(u32, fp->aux->stack_depth, 1);
1885 
1886 	fp->bpf_func = interpreters[(round_up(stack_depth, 32) / 32) - 1];
1887 #else
1888 	fp->bpf_func = __bpf_prog_ret0_warn;
1889 #endif
1890 }
1891 
1892 /**
1893  *	bpf_prog_select_runtime - select exec runtime for BPF program
1894  *	@fp: bpf_prog populated with internal BPF program
1895  *	@err: pointer to error variable
1896  *
1897  * Try to JIT eBPF program, if JIT is not available, use interpreter.
1898  * The BPF program will be executed via bpf_prog_run() function.
1899  *
1900  * Return: the &fp argument along with &err set to 0 for success or
1901  * a negative errno code on failure
1902  */
bpf_prog_select_runtime(struct bpf_prog * fp,int * err)1903 struct bpf_prog *bpf_prog_select_runtime(struct bpf_prog *fp, int *err)
1904 {
1905 	/* In case of BPF to BPF calls, verifier did all the prep
1906 	 * work with regards to JITing, etc.
1907 	 */
1908 	bool jit_needed = false;
1909 
1910 	if (fp->bpf_func)
1911 		goto finalize;
1912 
1913 	if (IS_ENABLED(CONFIG_BPF_JIT_ALWAYS_ON) ||
1914 	    bpf_prog_has_kfunc_call(fp))
1915 		jit_needed = true;
1916 
1917 	bpf_prog_select_func(fp);
1918 
1919 	/* eBPF JITs can rewrite the program in case constant
1920 	 * blinding is active. However, in case of error during
1921 	 * blinding, bpf_int_jit_compile() must always return a
1922 	 * valid program, which in this case would simply not
1923 	 * be JITed, but falls back to the interpreter.
1924 	 */
1925 	if (!bpf_prog_is_dev_bound(fp->aux)) {
1926 		*err = bpf_prog_alloc_jited_linfo(fp);
1927 		if (*err)
1928 			return fp;
1929 
1930 		fp = bpf_int_jit_compile(fp);
1931 		bpf_prog_jit_attempt_done(fp);
1932 		if (!fp->jited && jit_needed) {
1933 			*err = -ENOTSUPP;
1934 			return fp;
1935 		}
1936 	} else {
1937 		*err = bpf_prog_offload_compile(fp);
1938 		if (*err)
1939 			return fp;
1940 	}
1941 
1942 finalize:
1943 	bpf_prog_lock_ro(fp);
1944 
1945 	/* The tail call compatibility check can only be done at
1946 	 * this late stage as we need to determine, if we deal
1947 	 * with JITed or non JITed program concatenations and not
1948 	 * all eBPF JITs might immediately support all features.
1949 	 */
1950 	*err = bpf_check_tail_call(fp);
1951 
1952 	return fp;
1953 }
1954 EXPORT_SYMBOL_GPL(bpf_prog_select_runtime);
1955 
__bpf_prog_ret1(const void * ctx,const struct bpf_insn * insn)1956 static unsigned int __bpf_prog_ret1(const void *ctx,
1957 				    const struct bpf_insn *insn)
1958 {
1959 	return 1;
1960 }
1961 
1962 static struct bpf_prog_dummy {
1963 	struct bpf_prog prog;
1964 } dummy_bpf_prog = {
1965 	.prog = {
1966 		.bpf_func = __bpf_prog_ret1,
1967 	},
1968 };
1969 
1970 /* to avoid allocating empty bpf_prog_array for cgroups that
1971  * don't have bpf program attached use one global 'empty_prog_array'
1972  * It will not be modified the caller of bpf_prog_array_alloc()
1973  * (since caller requested prog_cnt == 0)
1974  * that pointer should be 'freed' by bpf_prog_array_free()
1975  */
1976 static struct {
1977 	struct bpf_prog_array hdr;
1978 	struct bpf_prog *null_prog;
1979 } empty_prog_array = {
1980 	.null_prog = NULL,
1981 };
1982 
bpf_prog_array_alloc(u32 prog_cnt,gfp_t flags)1983 struct bpf_prog_array *bpf_prog_array_alloc(u32 prog_cnt, gfp_t flags)
1984 {
1985 	if (prog_cnt)
1986 		return kzalloc(sizeof(struct bpf_prog_array) +
1987 			       sizeof(struct bpf_prog_array_item) *
1988 			       (prog_cnt + 1),
1989 			       flags);
1990 
1991 	return &empty_prog_array.hdr;
1992 }
1993 
bpf_prog_array_free(struct bpf_prog_array * progs)1994 void bpf_prog_array_free(struct bpf_prog_array *progs)
1995 {
1996 	if (!progs || progs == &empty_prog_array.hdr)
1997 		return;
1998 	kfree_rcu(progs, rcu);
1999 }
2000 
bpf_prog_array_length(struct bpf_prog_array * array)2001 int bpf_prog_array_length(struct bpf_prog_array *array)
2002 {
2003 	struct bpf_prog_array_item *item;
2004 	u32 cnt = 0;
2005 
2006 	for (item = array->items; item->prog; item++)
2007 		if (item->prog != &dummy_bpf_prog.prog)
2008 			cnt++;
2009 	return cnt;
2010 }
2011 
bpf_prog_array_is_empty(struct bpf_prog_array * array)2012 bool bpf_prog_array_is_empty(struct bpf_prog_array *array)
2013 {
2014 	struct bpf_prog_array_item *item;
2015 
2016 	for (item = array->items; item->prog; item++)
2017 		if (item->prog != &dummy_bpf_prog.prog)
2018 			return false;
2019 	return true;
2020 }
2021 
bpf_prog_array_copy_core(struct bpf_prog_array * array,u32 * prog_ids,u32 request_cnt)2022 static bool bpf_prog_array_copy_core(struct bpf_prog_array *array,
2023 				     u32 *prog_ids,
2024 				     u32 request_cnt)
2025 {
2026 	struct bpf_prog_array_item *item;
2027 	int i = 0;
2028 
2029 	for (item = array->items; item->prog; item++) {
2030 		if (item->prog == &dummy_bpf_prog.prog)
2031 			continue;
2032 		prog_ids[i] = item->prog->aux->id;
2033 		if (++i == request_cnt) {
2034 			item++;
2035 			break;
2036 		}
2037 	}
2038 
2039 	return !!(item->prog);
2040 }
2041 
bpf_prog_array_copy_to_user(struct bpf_prog_array * array,__u32 __user * prog_ids,u32 cnt)2042 int bpf_prog_array_copy_to_user(struct bpf_prog_array *array,
2043 				__u32 __user *prog_ids, u32 cnt)
2044 {
2045 	unsigned long err = 0;
2046 	bool nospc;
2047 	u32 *ids;
2048 
2049 	/* users of this function are doing:
2050 	 * cnt = bpf_prog_array_length();
2051 	 * if (cnt > 0)
2052 	 *     bpf_prog_array_copy_to_user(..., cnt);
2053 	 * so below kcalloc doesn't need extra cnt > 0 check.
2054 	 */
2055 	ids = kcalloc(cnt, sizeof(u32), GFP_USER | __GFP_NOWARN);
2056 	if (!ids)
2057 		return -ENOMEM;
2058 	nospc = bpf_prog_array_copy_core(array, ids, cnt);
2059 	err = copy_to_user(prog_ids, ids, cnt * sizeof(u32));
2060 	kfree(ids);
2061 	if (err)
2062 		return -EFAULT;
2063 	if (nospc)
2064 		return -ENOSPC;
2065 	return 0;
2066 }
2067 
bpf_prog_array_delete_safe(struct bpf_prog_array * array,struct bpf_prog * old_prog)2068 void bpf_prog_array_delete_safe(struct bpf_prog_array *array,
2069 				struct bpf_prog *old_prog)
2070 {
2071 	struct bpf_prog_array_item *item;
2072 
2073 	for (item = array->items; item->prog; item++)
2074 		if (item->prog == old_prog) {
2075 			WRITE_ONCE(item->prog, &dummy_bpf_prog.prog);
2076 			break;
2077 		}
2078 }
2079 
2080 /**
2081  * bpf_prog_array_delete_safe_at() - Replaces the program at the given
2082  *                                   index into the program array with
2083  *                                   a dummy no-op program.
2084  * @array: a bpf_prog_array
2085  * @index: the index of the program to replace
2086  *
2087  * Skips over dummy programs, by not counting them, when calculating
2088  * the position of the program to replace.
2089  *
2090  * Return:
2091  * * 0		- Success
2092  * * -EINVAL	- Invalid index value. Must be a non-negative integer.
2093  * * -ENOENT	- Index out of range
2094  */
bpf_prog_array_delete_safe_at(struct bpf_prog_array * array,int index)2095 int bpf_prog_array_delete_safe_at(struct bpf_prog_array *array, int index)
2096 {
2097 	return bpf_prog_array_update_at(array, index, &dummy_bpf_prog.prog);
2098 }
2099 
2100 /**
2101  * bpf_prog_array_update_at() - Updates the program at the given index
2102  *                              into the program array.
2103  * @array: a bpf_prog_array
2104  * @index: the index of the program to update
2105  * @prog: the program to insert into the array
2106  *
2107  * Skips over dummy programs, by not counting them, when calculating
2108  * the position of the program to update.
2109  *
2110  * Return:
2111  * * 0		- Success
2112  * * -EINVAL	- Invalid index value. Must be a non-negative integer.
2113  * * -ENOENT	- Index out of range
2114  */
bpf_prog_array_update_at(struct bpf_prog_array * array,int index,struct bpf_prog * prog)2115 int bpf_prog_array_update_at(struct bpf_prog_array *array, int index,
2116 			     struct bpf_prog *prog)
2117 {
2118 	struct bpf_prog_array_item *item;
2119 
2120 	if (unlikely(index < 0))
2121 		return -EINVAL;
2122 
2123 	for (item = array->items; item->prog; item++) {
2124 		if (item->prog == &dummy_bpf_prog.prog)
2125 			continue;
2126 		if (!index) {
2127 			WRITE_ONCE(item->prog, prog);
2128 			return 0;
2129 		}
2130 		index--;
2131 	}
2132 	return -ENOENT;
2133 }
2134 
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)2135 int bpf_prog_array_copy(struct bpf_prog_array *old_array,
2136 			struct bpf_prog *exclude_prog,
2137 			struct bpf_prog *include_prog,
2138 			u64 bpf_cookie,
2139 			struct bpf_prog_array **new_array)
2140 {
2141 	int new_prog_cnt, carry_prog_cnt = 0;
2142 	struct bpf_prog_array_item *existing, *new;
2143 	struct bpf_prog_array *array;
2144 	bool found_exclude = false;
2145 
2146 	/* Figure out how many existing progs we need to carry over to
2147 	 * the new array.
2148 	 */
2149 	if (old_array) {
2150 		existing = old_array->items;
2151 		for (; existing->prog; existing++) {
2152 			if (existing->prog == exclude_prog) {
2153 				found_exclude = true;
2154 				continue;
2155 			}
2156 			if (existing->prog != &dummy_bpf_prog.prog)
2157 				carry_prog_cnt++;
2158 			if (existing->prog == include_prog)
2159 				return -EEXIST;
2160 		}
2161 	}
2162 
2163 	if (exclude_prog && !found_exclude)
2164 		return -ENOENT;
2165 
2166 	/* How many progs (not NULL) will be in the new array? */
2167 	new_prog_cnt = carry_prog_cnt;
2168 	if (include_prog)
2169 		new_prog_cnt += 1;
2170 
2171 	/* Do we have any prog (not NULL) in the new array? */
2172 	if (!new_prog_cnt) {
2173 		*new_array = NULL;
2174 		return 0;
2175 	}
2176 
2177 	/* +1 as the end of prog_array is marked with NULL */
2178 	array = bpf_prog_array_alloc(new_prog_cnt + 1, GFP_KERNEL);
2179 	if (!array)
2180 		return -ENOMEM;
2181 	new = array->items;
2182 
2183 	/* Fill in the new prog array */
2184 	if (carry_prog_cnt) {
2185 		existing = old_array->items;
2186 		for (; existing->prog; existing++) {
2187 			if (existing->prog == exclude_prog ||
2188 			    existing->prog == &dummy_bpf_prog.prog)
2189 				continue;
2190 
2191 			new->prog = existing->prog;
2192 			new->bpf_cookie = existing->bpf_cookie;
2193 			new++;
2194 		}
2195 	}
2196 	if (include_prog) {
2197 		new->prog = include_prog;
2198 		new->bpf_cookie = bpf_cookie;
2199 		new++;
2200 	}
2201 	new->prog = NULL;
2202 	*new_array = array;
2203 	return 0;
2204 }
2205 
bpf_prog_array_copy_info(struct bpf_prog_array * array,u32 * prog_ids,u32 request_cnt,u32 * prog_cnt)2206 int bpf_prog_array_copy_info(struct bpf_prog_array *array,
2207 			     u32 *prog_ids, u32 request_cnt,
2208 			     u32 *prog_cnt)
2209 {
2210 	u32 cnt = 0;
2211 
2212 	if (array)
2213 		cnt = bpf_prog_array_length(array);
2214 
2215 	*prog_cnt = cnt;
2216 
2217 	/* return early if user requested only program count or nothing to copy */
2218 	if (!request_cnt || !cnt)
2219 		return 0;
2220 
2221 	/* this function is called under trace/bpf_trace.c: bpf_event_mutex */
2222 	return bpf_prog_array_copy_core(array, prog_ids, request_cnt) ? -ENOSPC
2223 								     : 0;
2224 }
2225 
__bpf_free_used_maps(struct bpf_prog_aux * aux,struct bpf_map ** used_maps,u32 len)2226 void __bpf_free_used_maps(struct bpf_prog_aux *aux,
2227 			  struct bpf_map **used_maps, u32 len)
2228 {
2229 	struct bpf_map *map;
2230 	u32 i;
2231 
2232 	for (i = 0; i < len; i++) {
2233 		map = used_maps[i];
2234 		if (map->ops->map_poke_untrack)
2235 			map->ops->map_poke_untrack(map, aux);
2236 		bpf_map_put(map);
2237 	}
2238 }
2239 
bpf_free_used_maps(struct bpf_prog_aux * aux)2240 static void bpf_free_used_maps(struct bpf_prog_aux *aux)
2241 {
2242 	__bpf_free_used_maps(aux, aux->used_maps, aux->used_map_cnt);
2243 	kfree(aux->used_maps);
2244 }
2245 
__bpf_free_used_btfs(struct bpf_prog_aux * aux,struct btf_mod_pair * used_btfs,u32 len)2246 void __bpf_free_used_btfs(struct bpf_prog_aux *aux,
2247 			  struct btf_mod_pair *used_btfs, u32 len)
2248 {
2249 #ifdef CONFIG_BPF_SYSCALL
2250 	struct btf_mod_pair *btf_mod;
2251 	u32 i;
2252 
2253 	for (i = 0; i < len; i++) {
2254 		btf_mod = &used_btfs[i];
2255 		if (btf_mod->module)
2256 			module_put(btf_mod->module);
2257 		btf_put(btf_mod->btf);
2258 	}
2259 #endif
2260 }
2261 
bpf_free_used_btfs(struct bpf_prog_aux * aux)2262 static void bpf_free_used_btfs(struct bpf_prog_aux *aux)
2263 {
2264 	__bpf_free_used_btfs(aux, aux->used_btfs, aux->used_btf_cnt);
2265 	kfree(aux->used_btfs);
2266 }
2267 
bpf_prog_free_deferred(struct work_struct * work)2268 static void bpf_prog_free_deferred(struct work_struct *work)
2269 {
2270 	struct bpf_prog_aux *aux;
2271 	int i;
2272 
2273 	aux = container_of(work, struct bpf_prog_aux, work);
2274 	bpf_free_used_maps(aux);
2275 	bpf_free_used_btfs(aux);
2276 	if (bpf_prog_is_dev_bound(aux))
2277 		bpf_prog_offload_destroy(aux->prog);
2278 #ifdef CONFIG_PERF_EVENTS
2279 	if (aux->prog->has_callchain_buf)
2280 		put_callchain_buffers();
2281 #endif
2282 	if (aux->dst_trampoline)
2283 		bpf_trampoline_put(aux->dst_trampoline);
2284 	for (i = 0; i < aux->func_cnt; i++) {
2285 		/* We can just unlink the subprog poke descriptor table as
2286 		 * it was originally linked to the main program and is also
2287 		 * released along with it.
2288 		 */
2289 		aux->func[i]->aux->poke_tab = NULL;
2290 		bpf_jit_free(aux->func[i]);
2291 	}
2292 	if (aux->func_cnt) {
2293 		kfree(aux->func);
2294 		bpf_prog_unlock_free(aux->prog);
2295 	} else {
2296 		bpf_jit_free(aux->prog);
2297 	}
2298 }
2299 
2300 /* Free internal BPF program */
bpf_prog_free(struct bpf_prog * fp)2301 void bpf_prog_free(struct bpf_prog *fp)
2302 {
2303 	struct bpf_prog_aux *aux = fp->aux;
2304 
2305 	if (aux->dst_prog)
2306 		bpf_prog_put(aux->dst_prog);
2307 	INIT_WORK(&aux->work, bpf_prog_free_deferred);
2308 	schedule_work(&aux->work);
2309 }
2310 EXPORT_SYMBOL_GPL(bpf_prog_free);
2311 
2312 /* RNG for unpriviledged user space with separated state from prandom_u32(). */
2313 static DEFINE_PER_CPU(struct rnd_state, bpf_user_rnd_state);
2314 
bpf_user_rnd_init_once(void)2315 void bpf_user_rnd_init_once(void)
2316 {
2317 	prandom_init_once(&bpf_user_rnd_state);
2318 }
2319 
BPF_CALL_0(bpf_user_rnd_u32)2320 BPF_CALL_0(bpf_user_rnd_u32)
2321 {
2322 	/* Should someone ever have the rather unwise idea to use some
2323 	 * of the registers passed into this function, then note that
2324 	 * this function is called from native eBPF and classic-to-eBPF
2325 	 * transformations. Register assignments from both sides are
2326 	 * different, f.e. classic always sets fn(ctx, A, X) here.
2327 	 */
2328 	struct rnd_state *state;
2329 	u32 res;
2330 
2331 	state = &get_cpu_var(bpf_user_rnd_state);
2332 	res = prandom_u32_state(state);
2333 	put_cpu_var(bpf_user_rnd_state);
2334 
2335 	return res;
2336 }
2337 
BPF_CALL_0(bpf_get_raw_cpu_id)2338 BPF_CALL_0(bpf_get_raw_cpu_id)
2339 {
2340 	return raw_smp_processor_id();
2341 }
2342 
2343 /* Weak definitions of helper functions in case we don't have bpf syscall. */
2344 const struct bpf_func_proto bpf_map_lookup_elem_proto __weak;
2345 const struct bpf_func_proto bpf_map_update_elem_proto __weak;
2346 const struct bpf_func_proto bpf_map_delete_elem_proto __weak;
2347 const struct bpf_func_proto bpf_map_push_elem_proto __weak;
2348 const struct bpf_func_proto bpf_map_pop_elem_proto __weak;
2349 const struct bpf_func_proto bpf_map_peek_elem_proto __weak;
2350 const struct bpf_func_proto bpf_spin_lock_proto __weak;
2351 const struct bpf_func_proto bpf_spin_unlock_proto __weak;
2352 const struct bpf_func_proto bpf_jiffies64_proto __weak;
2353 
2354 const struct bpf_func_proto bpf_get_prandom_u32_proto __weak;
2355 const struct bpf_func_proto bpf_get_smp_processor_id_proto __weak;
2356 const struct bpf_func_proto bpf_get_numa_node_id_proto __weak;
2357 const struct bpf_func_proto bpf_ktime_get_ns_proto __weak;
2358 const struct bpf_func_proto bpf_ktime_get_boot_ns_proto __weak;
2359 const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto __weak;
2360 
2361 const struct bpf_func_proto bpf_get_current_pid_tgid_proto __weak;
2362 const struct bpf_func_proto bpf_get_current_uid_gid_proto __weak;
2363 const struct bpf_func_proto bpf_get_current_comm_proto __weak;
2364 const struct bpf_func_proto bpf_get_current_cgroup_id_proto __weak;
2365 const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto __weak;
2366 const struct bpf_func_proto bpf_get_local_storage_proto __weak;
2367 const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto __weak;
2368 const struct bpf_func_proto bpf_snprintf_btf_proto __weak;
2369 const struct bpf_func_proto bpf_seq_printf_btf_proto __weak;
2370 
bpf_get_trace_printk_proto(void)2371 const struct bpf_func_proto * __weak bpf_get_trace_printk_proto(void)
2372 {
2373 	return NULL;
2374 }
2375 
2376 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)2377 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
2378 		 void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
2379 {
2380 	return -ENOTSUPP;
2381 }
2382 EXPORT_SYMBOL_GPL(bpf_event_output);
2383 
2384 /* Always built-in helper functions. */
2385 const struct bpf_func_proto bpf_tail_call_proto = {
2386 	.func		= NULL,
2387 	.gpl_only	= false,
2388 	.ret_type	= RET_VOID,
2389 	.arg1_type	= ARG_PTR_TO_CTX,
2390 	.arg2_type	= ARG_CONST_MAP_PTR,
2391 	.arg3_type	= ARG_ANYTHING,
2392 };
2393 
2394 /* Stub for JITs that only support cBPF. eBPF programs are interpreted.
2395  * It is encouraged to implement bpf_int_jit_compile() instead, so that
2396  * eBPF and implicitly also cBPF can get JITed!
2397  */
bpf_int_jit_compile(struct bpf_prog * prog)2398 struct bpf_prog * __weak bpf_int_jit_compile(struct bpf_prog *prog)
2399 {
2400 	return prog;
2401 }
2402 
2403 /* Stub for JITs that support eBPF. All cBPF code gets transformed into
2404  * eBPF by the kernel and is later compiled by bpf_int_jit_compile().
2405  */
bpf_jit_compile(struct bpf_prog * prog)2406 void __weak bpf_jit_compile(struct bpf_prog *prog)
2407 {
2408 }
2409 
bpf_helper_changes_pkt_data(void * func)2410 bool __weak bpf_helper_changes_pkt_data(void *func)
2411 {
2412 	return false;
2413 }
2414 
2415 /* Return TRUE if the JIT backend wants verifier to enable sub-register usage
2416  * analysis code and wants explicit zero extension inserted by verifier.
2417  * Otherwise, return FALSE.
2418  *
2419  * The verifier inserts an explicit zero extension after BPF_CMPXCHGs even if
2420  * you don't override this. JITs that don't want these extra insns can detect
2421  * them using insn_is_zext.
2422  */
bpf_jit_needs_zext(void)2423 bool __weak bpf_jit_needs_zext(void)
2424 {
2425 	return false;
2426 }
2427 
bpf_jit_supports_kfunc_call(void)2428 bool __weak bpf_jit_supports_kfunc_call(void)
2429 {
2430 	return false;
2431 }
2432 
2433 /* To execute LD_ABS/LD_IND instructions __bpf_prog_run() may call
2434  * skb_copy_bits(), so provide a weak definition of it for NET-less config.
2435  */
skb_copy_bits(const struct sk_buff * skb,int offset,void * to,int len)2436 int __weak skb_copy_bits(const struct sk_buff *skb, int offset, void *to,
2437 			 int len)
2438 {
2439 	return -EFAULT;
2440 }
2441 
bpf_arch_text_poke(void * ip,enum bpf_text_poke_type t,void * addr1,void * addr2)2442 int __weak bpf_arch_text_poke(void *ip, enum bpf_text_poke_type t,
2443 			      void *addr1, void *addr2)
2444 {
2445 	return -ENOTSUPP;
2446 }
2447 
2448 DEFINE_STATIC_KEY_FALSE(bpf_stats_enabled_key);
2449 EXPORT_SYMBOL(bpf_stats_enabled_key);
2450 
2451 /* All definitions of tracepoints related to BPF. */
2452 #define CREATE_TRACE_POINTS
2453 #include <linux/bpf_trace.h>
2454 
2455 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_exception);
2456 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_bulk_tx);
2457