xref: /linux/kernel/bpf/core.c (revision d8dc09a4db45e49cc1ee5170632833ec11fafa7e)
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/bpf_verifier.h>
36 #include <linux/nodemask.h>
37 
38 #include <asm/barrier.h>
39 #include <asm/unaligned.h>
40 
41 /* Registers */
42 #define BPF_R0	regs[BPF_REG_0]
43 #define BPF_R1	regs[BPF_REG_1]
44 #define BPF_R2	regs[BPF_REG_2]
45 #define BPF_R3	regs[BPF_REG_3]
46 #define BPF_R4	regs[BPF_REG_4]
47 #define BPF_R5	regs[BPF_REG_5]
48 #define BPF_R6	regs[BPF_REG_6]
49 #define BPF_R7	regs[BPF_REG_7]
50 #define BPF_R8	regs[BPF_REG_8]
51 #define BPF_R9	regs[BPF_REG_9]
52 #define BPF_R10	regs[BPF_REG_10]
53 
54 /* Named registers */
55 #define DST	regs[insn->dst_reg]
56 #define SRC	regs[insn->src_reg]
57 #define FP	regs[BPF_REG_FP]
58 #define AX	regs[BPF_REG_AX]
59 #define ARG1	regs[BPF_REG_ARG1]
60 #define CTX	regs[BPF_REG_CTX]
61 #define IMM	insn->imm
62 
63 /* No hurry in this branch
64  *
65  * Exported for the bpf jit load helper.
66  */
67 void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, unsigned int size)
68 {
69 	u8 *ptr = NULL;
70 
71 	if (k >= SKF_NET_OFF)
72 		ptr = skb_network_header(skb) + k - SKF_NET_OFF;
73 	else if (k >= SKF_LL_OFF)
74 		ptr = skb_mac_header(skb) + k - SKF_LL_OFF;
75 
76 	if (ptr >= skb->head && ptr + size <= skb_tail_pointer(skb))
77 		return ptr;
78 
79 	return NULL;
80 }
81 
82 struct bpf_prog *bpf_prog_alloc_no_stats(unsigned int size, gfp_t gfp_extra_flags)
83 {
84 	gfp_t gfp_flags = GFP_KERNEL_ACCOUNT | __GFP_ZERO | gfp_extra_flags;
85 	struct bpf_prog_aux *aux;
86 	struct bpf_prog *fp;
87 
88 	size = round_up(size, PAGE_SIZE);
89 	fp = __vmalloc(size, gfp_flags);
90 	if (fp == NULL)
91 		return NULL;
92 
93 	aux = kzalloc(sizeof(*aux), GFP_KERNEL_ACCOUNT | gfp_extra_flags);
94 	if (aux == NULL) {
95 		vfree(fp);
96 		return NULL;
97 	}
98 	fp->active = alloc_percpu_gfp(int, GFP_KERNEL_ACCOUNT | gfp_extra_flags);
99 	if (!fp->active) {
100 		vfree(fp);
101 		kfree(aux);
102 		return NULL;
103 	}
104 
105 	fp->pages = size / PAGE_SIZE;
106 	fp->aux = aux;
107 	fp->aux->prog = fp;
108 	fp->jit_requested = ebpf_jit_enabled();
109 	fp->blinding_requested = bpf_jit_blinding_enabled(fp);
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 
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 
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 
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  */
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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
540 bpf_prog_ksym_set_addr(struct bpf_prog *prog)
541 {
542 	WARN_ON_ONCE(!bpf_prog_ebpf_jited(prog));
543 
544 	prog->aux->ksym.start = (unsigned long) prog->bpf_func;
545 	prog->aux->ksym.end   = prog->aux->ksym.start + prog->jited_len;
546 }
547 
548 static void
549 bpf_prog_ksym_set_name(struct bpf_prog *prog)
550 {
551 	char *sym = prog->aux->ksym.name;
552 	const char *end = sym + KSYM_NAME_LEN;
553 	const struct btf_type *type;
554 	const char *func_name;
555 
556 	BUILD_BUG_ON(sizeof("bpf_prog_") +
557 		     sizeof(prog->tag) * 2 +
558 		     /* name has been null terminated.
559 		      * We should need +1 for the '_' preceding
560 		      * the name.  However, the null character
561 		      * is double counted between the name and the
562 		      * sizeof("bpf_prog_") above, so we omit
563 		      * the +1 here.
564 		      */
565 		     sizeof(prog->aux->name) > KSYM_NAME_LEN);
566 
567 	sym += snprintf(sym, KSYM_NAME_LEN, "bpf_prog_");
568 	sym  = bin2hex(sym, prog->tag, sizeof(prog->tag));
569 
570 	/* prog->aux->name will be ignored if full btf name is available */
571 	if (prog->aux->func_info_cnt) {
572 		type = btf_type_by_id(prog->aux->btf,
573 				      prog->aux->func_info[prog->aux->func_idx].type_id);
574 		func_name = btf_name_by_offset(prog->aux->btf, type->name_off);
575 		snprintf(sym, (size_t)(end - sym), "_%s", func_name);
576 		return;
577 	}
578 
579 	if (prog->aux->name[0])
580 		snprintf(sym, (size_t)(end - sym), "_%s", prog->aux->name);
581 	else
582 		*sym = 0;
583 }
584 
585 static unsigned long bpf_get_ksym_start(struct latch_tree_node *n)
586 {
587 	return container_of(n, struct bpf_ksym, tnode)->start;
588 }
589 
590 static __always_inline bool bpf_tree_less(struct latch_tree_node *a,
591 					  struct latch_tree_node *b)
592 {
593 	return bpf_get_ksym_start(a) < bpf_get_ksym_start(b);
594 }
595 
596 static __always_inline int bpf_tree_comp(void *key, struct latch_tree_node *n)
597 {
598 	unsigned long val = (unsigned long)key;
599 	const struct bpf_ksym *ksym;
600 
601 	ksym = container_of(n, struct bpf_ksym, tnode);
602 
603 	if (val < ksym->start)
604 		return -1;
605 	if (val >= ksym->end)
606 		return  1;
607 
608 	return 0;
609 }
610 
611 static const struct latch_tree_ops bpf_tree_ops = {
612 	.less	= bpf_tree_less,
613 	.comp	= bpf_tree_comp,
614 };
615 
616 static DEFINE_SPINLOCK(bpf_lock);
617 static LIST_HEAD(bpf_kallsyms);
618 static struct latch_tree_root bpf_tree __cacheline_aligned;
619 
620 void bpf_ksym_add(struct bpf_ksym *ksym)
621 {
622 	spin_lock_bh(&bpf_lock);
623 	WARN_ON_ONCE(!list_empty(&ksym->lnode));
624 	list_add_tail_rcu(&ksym->lnode, &bpf_kallsyms);
625 	latch_tree_insert(&ksym->tnode, &bpf_tree, &bpf_tree_ops);
626 	spin_unlock_bh(&bpf_lock);
627 }
628 
629 static void __bpf_ksym_del(struct bpf_ksym *ksym)
630 {
631 	if (list_empty(&ksym->lnode))
632 		return;
633 
634 	latch_tree_erase(&ksym->tnode, &bpf_tree, &bpf_tree_ops);
635 	list_del_rcu(&ksym->lnode);
636 }
637 
638 void bpf_ksym_del(struct bpf_ksym *ksym)
639 {
640 	spin_lock_bh(&bpf_lock);
641 	__bpf_ksym_del(ksym);
642 	spin_unlock_bh(&bpf_lock);
643 }
644 
645 static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp)
646 {
647 	return fp->jited && !bpf_prog_was_classic(fp);
648 }
649 
650 static bool bpf_prog_kallsyms_verify_off(const struct bpf_prog *fp)
651 {
652 	return list_empty(&fp->aux->ksym.lnode) ||
653 	       fp->aux->ksym.lnode.prev == LIST_POISON2;
654 }
655 
656 void bpf_prog_kallsyms_add(struct bpf_prog *fp)
657 {
658 	if (!bpf_prog_kallsyms_candidate(fp) ||
659 	    !bpf_capable())
660 		return;
661 
662 	bpf_prog_ksym_set_addr(fp);
663 	bpf_prog_ksym_set_name(fp);
664 	fp->aux->ksym.prog = true;
665 
666 	bpf_ksym_add(&fp->aux->ksym);
667 }
668 
669 void bpf_prog_kallsyms_del(struct bpf_prog *fp)
670 {
671 	if (!bpf_prog_kallsyms_candidate(fp))
672 		return;
673 
674 	bpf_ksym_del(&fp->aux->ksym);
675 }
676 
677 static struct bpf_ksym *bpf_ksym_find(unsigned long addr)
678 {
679 	struct latch_tree_node *n;
680 
681 	n = latch_tree_find((void *)addr, &bpf_tree, &bpf_tree_ops);
682 	return n ? container_of(n, struct bpf_ksym, tnode) : NULL;
683 }
684 
685 const char *__bpf_address_lookup(unsigned long addr, unsigned long *size,
686 				 unsigned long *off, char *sym)
687 {
688 	struct bpf_ksym *ksym;
689 	char *ret = NULL;
690 
691 	rcu_read_lock();
692 	ksym = bpf_ksym_find(addr);
693 	if (ksym) {
694 		unsigned long symbol_start = ksym->start;
695 		unsigned long symbol_end = ksym->end;
696 
697 		strncpy(sym, ksym->name, KSYM_NAME_LEN);
698 
699 		ret = sym;
700 		if (size)
701 			*size = symbol_end - symbol_start;
702 		if (off)
703 			*off  = addr - symbol_start;
704 	}
705 	rcu_read_unlock();
706 
707 	return ret;
708 }
709 
710 bool is_bpf_text_address(unsigned long addr)
711 {
712 	bool ret;
713 
714 	rcu_read_lock();
715 	ret = bpf_ksym_find(addr) != NULL;
716 	rcu_read_unlock();
717 
718 	return ret;
719 }
720 
721 static struct bpf_prog *bpf_prog_ksym_find(unsigned long addr)
722 {
723 	struct bpf_ksym *ksym = bpf_ksym_find(addr);
724 
725 	return ksym && ksym->prog ?
726 	       container_of(ksym, struct bpf_prog_aux, ksym)->prog :
727 	       NULL;
728 }
729 
730 const struct exception_table_entry *search_bpf_extables(unsigned long addr)
731 {
732 	const struct exception_table_entry *e = NULL;
733 	struct bpf_prog *prog;
734 
735 	rcu_read_lock();
736 	prog = bpf_prog_ksym_find(addr);
737 	if (!prog)
738 		goto out;
739 	if (!prog->aux->num_exentries)
740 		goto out;
741 
742 	e = search_extable(prog->aux->extable, prog->aux->num_exentries, addr);
743 out:
744 	rcu_read_unlock();
745 	return e;
746 }
747 
748 int bpf_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
749 		    char *sym)
750 {
751 	struct bpf_ksym *ksym;
752 	unsigned int it = 0;
753 	int ret = -ERANGE;
754 
755 	if (!bpf_jit_kallsyms_enabled())
756 		return ret;
757 
758 	rcu_read_lock();
759 	list_for_each_entry_rcu(ksym, &bpf_kallsyms, lnode) {
760 		if (it++ != symnum)
761 			continue;
762 
763 		strncpy(sym, ksym->name, KSYM_NAME_LEN);
764 
765 		*value = ksym->start;
766 		*type  = BPF_SYM_ELF_TYPE;
767 
768 		ret = 0;
769 		break;
770 	}
771 	rcu_read_unlock();
772 
773 	return ret;
774 }
775 
776 int bpf_jit_add_poke_descriptor(struct bpf_prog *prog,
777 				struct bpf_jit_poke_descriptor *poke)
778 {
779 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
780 	static const u32 poke_tab_max = 1024;
781 	u32 slot = prog->aux->size_poke_tab;
782 	u32 size = slot + 1;
783 
784 	if (size > poke_tab_max)
785 		return -ENOSPC;
786 	if (poke->tailcall_target || poke->tailcall_target_stable ||
787 	    poke->tailcall_bypass || poke->adj_off || poke->bypass_addr)
788 		return -EINVAL;
789 
790 	switch (poke->reason) {
791 	case BPF_POKE_REASON_TAIL_CALL:
792 		if (!poke->tail_call.map)
793 			return -EINVAL;
794 		break;
795 	default:
796 		return -EINVAL;
797 	}
798 
799 	tab = krealloc(tab, size * sizeof(*poke), GFP_KERNEL);
800 	if (!tab)
801 		return -ENOMEM;
802 
803 	memcpy(&tab[slot], poke, sizeof(*poke));
804 	prog->aux->size_poke_tab = size;
805 	prog->aux->poke_tab = tab;
806 
807 	return slot;
808 }
809 
810 /*
811  * BPF program pack allocator.
812  *
813  * Most BPF programs are pretty small. Allocating a hole page for each
814  * program is sometime a waste. Many small bpf program also adds pressure
815  * to instruction TLB. To solve this issue, we introduce a BPF program pack
816  * allocator. The prog_pack allocator uses HPAGE_PMD_SIZE page (2MB on x86)
817  * to host BPF programs.
818  */
819 #define BPF_PROG_CHUNK_SHIFT	6
820 #define BPF_PROG_CHUNK_SIZE	(1 << BPF_PROG_CHUNK_SHIFT)
821 #define BPF_PROG_CHUNK_MASK	(~(BPF_PROG_CHUNK_SIZE - 1))
822 
823 struct bpf_prog_pack {
824 	struct list_head list;
825 	void *ptr;
826 	unsigned long bitmap[];
827 };
828 
829 #define BPF_PROG_SIZE_TO_NBITS(size)	(round_up(size, BPF_PROG_CHUNK_SIZE) / BPF_PROG_CHUNK_SIZE)
830 
831 static size_t bpf_prog_pack_size = -1;
832 
833 static int bpf_prog_chunk_count(void)
834 {
835 	WARN_ON_ONCE(bpf_prog_pack_size == -1);
836 	return bpf_prog_pack_size / BPF_PROG_CHUNK_SIZE;
837 }
838 
839 static DEFINE_MUTEX(pack_mutex);
840 static LIST_HEAD(pack_list);
841 
842 static size_t select_bpf_prog_pack_size(void)
843 {
844 	size_t size;
845 	void *ptr;
846 
847 	size = PMD_SIZE * num_online_nodes();
848 	ptr = module_alloc(size);
849 
850 	/* Test whether we can get huge pages. If not just use PAGE_SIZE
851 	 * packs.
852 	 */
853 	if (!ptr || !is_vm_area_hugepages(ptr))
854 		size = PAGE_SIZE;
855 
856 	vfree(ptr);
857 	return size;
858 }
859 
860 static struct bpf_prog_pack *alloc_new_pack(void)
861 {
862 	struct bpf_prog_pack *pack;
863 
864 	pack = kzalloc(struct_size(pack, bitmap, BITS_TO_LONGS(bpf_prog_chunk_count())),
865 		       GFP_KERNEL);
866 	if (!pack)
867 		return NULL;
868 	pack->ptr = module_alloc(bpf_prog_pack_size);
869 	if (!pack->ptr) {
870 		kfree(pack);
871 		return NULL;
872 	}
873 	bitmap_zero(pack->bitmap, bpf_prog_pack_size / BPF_PROG_CHUNK_SIZE);
874 	list_add_tail(&pack->list, &pack_list);
875 
876 	set_vm_flush_reset_perms(pack->ptr);
877 	set_memory_ro((unsigned long)pack->ptr, bpf_prog_pack_size / PAGE_SIZE);
878 	set_memory_x((unsigned long)pack->ptr, bpf_prog_pack_size / PAGE_SIZE);
879 	return pack;
880 }
881 
882 static void *bpf_prog_pack_alloc(u32 size)
883 {
884 	unsigned int nbits = BPF_PROG_SIZE_TO_NBITS(size);
885 	struct bpf_prog_pack *pack;
886 	unsigned long pos;
887 	void *ptr = NULL;
888 
889 	mutex_lock(&pack_mutex);
890 	if (bpf_prog_pack_size == -1)
891 		bpf_prog_pack_size = select_bpf_prog_pack_size();
892 
893 	if (size > bpf_prog_pack_size) {
894 		size = round_up(size, PAGE_SIZE);
895 		ptr = module_alloc(size);
896 		if (ptr) {
897 			set_vm_flush_reset_perms(ptr);
898 			set_memory_ro((unsigned long)ptr, size / PAGE_SIZE);
899 			set_memory_x((unsigned long)ptr, size / PAGE_SIZE);
900 		}
901 		goto out;
902 	}
903 	list_for_each_entry(pack, &pack_list, list) {
904 		pos = bitmap_find_next_zero_area(pack->bitmap, bpf_prog_chunk_count(), 0,
905 						 nbits, 0);
906 		if (pos < bpf_prog_chunk_count())
907 			goto found_free_area;
908 	}
909 
910 	pack = alloc_new_pack();
911 	if (!pack)
912 		goto out;
913 
914 	pos = 0;
915 
916 found_free_area:
917 	bitmap_set(pack->bitmap, pos, nbits);
918 	ptr = (void *)(pack->ptr) + (pos << BPF_PROG_CHUNK_SHIFT);
919 
920 out:
921 	mutex_unlock(&pack_mutex);
922 	return ptr;
923 }
924 
925 static void bpf_prog_pack_free(struct bpf_binary_header *hdr)
926 {
927 	struct bpf_prog_pack *pack = NULL, *tmp;
928 	unsigned int nbits;
929 	unsigned long pos;
930 	void *pack_ptr;
931 
932 	mutex_lock(&pack_mutex);
933 	if (hdr->size > bpf_prog_pack_size) {
934 		module_memfree(hdr);
935 		goto out;
936 	}
937 
938 	pack_ptr = (void *)((unsigned long)hdr & ~(bpf_prog_pack_size - 1));
939 
940 	list_for_each_entry(tmp, &pack_list, list) {
941 		if (tmp->ptr == pack_ptr) {
942 			pack = tmp;
943 			break;
944 		}
945 	}
946 
947 	if (WARN_ONCE(!pack, "bpf_prog_pack bug\n"))
948 		goto out;
949 
950 	nbits = BPF_PROG_SIZE_TO_NBITS(hdr->size);
951 	pos = ((unsigned long)hdr - (unsigned long)pack_ptr) >> BPF_PROG_CHUNK_SHIFT;
952 
953 	bitmap_clear(pack->bitmap, pos, nbits);
954 	if (bitmap_find_next_zero_area(pack->bitmap, bpf_prog_chunk_count(), 0,
955 				       bpf_prog_chunk_count(), 0) == 0) {
956 		list_del(&pack->list);
957 		module_memfree(pack->ptr);
958 		kfree(pack);
959 	}
960 out:
961 	mutex_unlock(&pack_mutex);
962 }
963 
964 static atomic_long_t bpf_jit_current;
965 
966 /* Can be overridden by an arch's JIT compiler if it has a custom,
967  * dedicated BPF backend memory area, or if neither of the two
968  * below apply.
969  */
970 u64 __weak bpf_jit_alloc_exec_limit(void)
971 {
972 #if defined(MODULES_VADDR)
973 	return MODULES_END - MODULES_VADDR;
974 #else
975 	return VMALLOC_END - VMALLOC_START;
976 #endif
977 }
978 
979 static int __init bpf_jit_charge_init(void)
980 {
981 	/* Only used as heuristic here to derive limit. */
982 	bpf_jit_limit_max = bpf_jit_alloc_exec_limit();
983 	bpf_jit_limit = min_t(u64, round_up(bpf_jit_limit_max >> 2,
984 					    PAGE_SIZE), LONG_MAX);
985 	return 0;
986 }
987 pure_initcall(bpf_jit_charge_init);
988 
989 int bpf_jit_charge_modmem(u32 size)
990 {
991 	if (atomic_long_add_return(size, &bpf_jit_current) > bpf_jit_limit) {
992 		if (!bpf_capable()) {
993 			atomic_long_sub(size, &bpf_jit_current);
994 			return -EPERM;
995 		}
996 	}
997 
998 	return 0;
999 }
1000 
1001 void bpf_jit_uncharge_modmem(u32 size)
1002 {
1003 	atomic_long_sub(size, &bpf_jit_current);
1004 }
1005 
1006 void *__weak bpf_jit_alloc_exec(unsigned long size)
1007 {
1008 	return module_alloc(size);
1009 }
1010 
1011 void __weak bpf_jit_free_exec(void *addr)
1012 {
1013 	module_memfree(addr);
1014 }
1015 
1016 struct bpf_binary_header *
1017 bpf_jit_binary_alloc(unsigned int proglen, u8 **image_ptr,
1018 		     unsigned int alignment,
1019 		     bpf_jit_fill_hole_t bpf_fill_ill_insns)
1020 {
1021 	struct bpf_binary_header *hdr;
1022 	u32 size, hole, start;
1023 
1024 	WARN_ON_ONCE(!is_power_of_2(alignment) ||
1025 		     alignment > BPF_IMAGE_ALIGNMENT);
1026 
1027 	/* Most of BPF filters are really small, but if some of them
1028 	 * fill a page, allow at least 128 extra bytes to insert a
1029 	 * random section of illegal instructions.
1030 	 */
1031 	size = round_up(proglen + sizeof(*hdr) + 128, PAGE_SIZE);
1032 
1033 	if (bpf_jit_charge_modmem(size))
1034 		return NULL;
1035 	hdr = bpf_jit_alloc_exec(size);
1036 	if (!hdr) {
1037 		bpf_jit_uncharge_modmem(size);
1038 		return NULL;
1039 	}
1040 
1041 	/* Fill space with illegal/arch-dep instructions. */
1042 	bpf_fill_ill_insns(hdr, size);
1043 
1044 	hdr->size = size;
1045 	hole = min_t(unsigned int, size - (proglen + sizeof(*hdr)),
1046 		     PAGE_SIZE - sizeof(*hdr));
1047 	start = (get_random_int() % hole) & ~(alignment - 1);
1048 
1049 	/* Leave a random number of instructions before BPF code. */
1050 	*image_ptr = &hdr->image[start];
1051 
1052 	return hdr;
1053 }
1054 
1055 void bpf_jit_binary_free(struct bpf_binary_header *hdr)
1056 {
1057 	u32 size = hdr->size;
1058 
1059 	bpf_jit_free_exec(hdr);
1060 	bpf_jit_uncharge_modmem(size);
1061 }
1062 
1063 /* Allocate jit binary from bpf_prog_pack allocator.
1064  * Since the allocated memory is RO+X, the JIT engine cannot write directly
1065  * to the memory. To solve this problem, a RW buffer is also allocated at
1066  * as the same time. The JIT engine should calculate offsets based on the
1067  * RO memory address, but write JITed program to the RW buffer. Once the
1068  * JIT engine finishes, it calls bpf_jit_binary_pack_finalize, which copies
1069  * the JITed program to the RO memory.
1070  */
1071 struct bpf_binary_header *
1072 bpf_jit_binary_pack_alloc(unsigned int proglen, u8 **image_ptr,
1073 			  unsigned int alignment,
1074 			  struct bpf_binary_header **rw_header,
1075 			  u8 **rw_image,
1076 			  bpf_jit_fill_hole_t bpf_fill_ill_insns)
1077 {
1078 	struct bpf_binary_header *ro_header;
1079 	u32 size, hole, start;
1080 
1081 	WARN_ON_ONCE(!is_power_of_2(alignment) ||
1082 		     alignment > BPF_IMAGE_ALIGNMENT);
1083 
1084 	/* add 16 bytes for a random section of illegal instructions */
1085 	size = round_up(proglen + sizeof(*ro_header) + 16, BPF_PROG_CHUNK_SIZE);
1086 
1087 	if (bpf_jit_charge_modmem(size))
1088 		return NULL;
1089 	ro_header = bpf_prog_pack_alloc(size);
1090 	if (!ro_header) {
1091 		bpf_jit_uncharge_modmem(size);
1092 		return NULL;
1093 	}
1094 
1095 	*rw_header = kvmalloc(size, GFP_KERNEL);
1096 	if (!*rw_header) {
1097 		bpf_arch_text_copy(&ro_header->size, &size, sizeof(size));
1098 		bpf_prog_pack_free(ro_header);
1099 		bpf_jit_uncharge_modmem(size);
1100 		return NULL;
1101 	}
1102 
1103 	/* Fill space with illegal/arch-dep instructions. */
1104 	bpf_fill_ill_insns(*rw_header, size);
1105 	(*rw_header)->size = size;
1106 
1107 	hole = min_t(unsigned int, size - (proglen + sizeof(*ro_header)),
1108 		     BPF_PROG_CHUNK_SIZE - sizeof(*ro_header));
1109 	start = (get_random_int() % hole) & ~(alignment - 1);
1110 
1111 	*image_ptr = &ro_header->image[start];
1112 	*rw_image = &(*rw_header)->image[start];
1113 
1114 	return ro_header;
1115 }
1116 
1117 /* Copy JITed text from rw_header to its final location, the ro_header. */
1118 int bpf_jit_binary_pack_finalize(struct bpf_prog *prog,
1119 				 struct bpf_binary_header *ro_header,
1120 				 struct bpf_binary_header *rw_header)
1121 {
1122 	void *ptr;
1123 
1124 	ptr = bpf_arch_text_copy(ro_header, rw_header, rw_header->size);
1125 
1126 	kvfree(rw_header);
1127 
1128 	if (IS_ERR(ptr)) {
1129 		bpf_prog_pack_free(ro_header);
1130 		return PTR_ERR(ptr);
1131 	}
1132 	prog->aux->use_bpf_prog_pack = true;
1133 	return 0;
1134 }
1135 
1136 /* bpf_jit_binary_pack_free is called in two different scenarios:
1137  *   1) when the program is freed after;
1138  *   2) when the JIT engine fails (before bpf_jit_binary_pack_finalize).
1139  * For case 2), we need to free both the RO memory and the RW buffer.
1140  *
1141  * bpf_jit_binary_pack_free requires proper ro_header->size. However,
1142  * bpf_jit_binary_pack_alloc does not set it. Therefore, ro_header->size
1143  * must be set with either bpf_jit_binary_pack_finalize (normal path) or
1144  * bpf_arch_text_copy (when jit fails).
1145  */
1146 void bpf_jit_binary_pack_free(struct bpf_binary_header *ro_header,
1147 			      struct bpf_binary_header *rw_header)
1148 {
1149 	u32 size = ro_header->size;
1150 
1151 	bpf_prog_pack_free(ro_header);
1152 	kvfree(rw_header);
1153 	bpf_jit_uncharge_modmem(size);
1154 }
1155 
1156 static inline struct bpf_binary_header *
1157 bpf_jit_binary_hdr(const struct bpf_prog *fp)
1158 {
1159 	unsigned long real_start = (unsigned long)fp->bpf_func;
1160 	unsigned long addr;
1161 
1162 	if (fp->aux->use_bpf_prog_pack)
1163 		addr = real_start & BPF_PROG_CHUNK_MASK;
1164 	else
1165 		addr = real_start & PAGE_MASK;
1166 
1167 	return (void *)addr;
1168 }
1169 
1170 /* This symbol is only overridden by archs that have different
1171  * requirements than the usual eBPF JITs, f.e. when they only
1172  * implement cBPF JIT, do not set images read-only, etc.
1173  */
1174 void __weak bpf_jit_free(struct bpf_prog *fp)
1175 {
1176 	if (fp->jited) {
1177 		struct bpf_binary_header *hdr = bpf_jit_binary_hdr(fp);
1178 
1179 		if (fp->aux->use_bpf_prog_pack)
1180 			bpf_jit_binary_pack_free(hdr, NULL /* rw_buffer */);
1181 		else
1182 			bpf_jit_binary_free(hdr);
1183 
1184 		WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(fp));
1185 	}
1186 
1187 	bpf_prog_unlock_free(fp);
1188 }
1189 
1190 int bpf_jit_get_func_addr(const struct bpf_prog *prog,
1191 			  const struct bpf_insn *insn, bool extra_pass,
1192 			  u64 *func_addr, bool *func_addr_fixed)
1193 {
1194 	s16 off = insn->off;
1195 	s32 imm = insn->imm;
1196 	u8 *addr;
1197 
1198 	*func_addr_fixed = insn->src_reg != BPF_PSEUDO_CALL;
1199 	if (!*func_addr_fixed) {
1200 		/* Place-holder address till the last pass has collected
1201 		 * all addresses for JITed subprograms in which case we
1202 		 * can pick them up from prog->aux.
1203 		 */
1204 		if (!extra_pass)
1205 			addr = NULL;
1206 		else if (prog->aux->func &&
1207 			 off >= 0 && off < prog->aux->func_cnt)
1208 			addr = (u8 *)prog->aux->func[off]->bpf_func;
1209 		else
1210 			return -EINVAL;
1211 	} else {
1212 		/* Address of a BPF helper call. Since part of the core
1213 		 * kernel, it's always at a fixed location. __bpf_call_base
1214 		 * and the helper with imm relative to it are both in core
1215 		 * kernel.
1216 		 */
1217 		addr = (u8 *)__bpf_call_base + imm;
1218 	}
1219 
1220 	*func_addr = (unsigned long)addr;
1221 	return 0;
1222 }
1223 
1224 static int bpf_jit_blind_insn(const struct bpf_insn *from,
1225 			      const struct bpf_insn *aux,
1226 			      struct bpf_insn *to_buff,
1227 			      bool emit_zext)
1228 {
1229 	struct bpf_insn *to = to_buff;
1230 	u32 imm_rnd = get_random_int();
1231 	s16 off;
1232 
1233 	BUILD_BUG_ON(BPF_REG_AX  + 1 != MAX_BPF_JIT_REG);
1234 	BUILD_BUG_ON(MAX_BPF_REG + 1 != MAX_BPF_JIT_REG);
1235 
1236 	/* Constraints on AX register:
1237 	 *
1238 	 * AX register is inaccessible from user space. It is mapped in
1239 	 * all JITs, and used here for constant blinding rewrites. It is
1240 	 * typically "stateless" meaning its contents are only valid within
1241 	 * the executed instruction, but not across several instructions.
1242 	 * There are a few exceptions however which are further detailed
1243 	 * below.
1244 	 *
1245 	 * Constant blinding is only used by JITs, not in the interpreter.
1246 	 * The interpreter uses AX in some occasions as a local temporary
1247 	 * register e.g. in DIV or MOD instructions.
1248 	 *
1249 	 * In restricted circumstances, the verifier can also use the AX
1250 	 * register for rewrites as long as they do not interfere with
1251 	 * the above cases!
1252 	 */
1253 	if (from->dst_reg == BPF_REG_AX || from->src_reg == BPF_REG_AX)
1254 		goto out;
1255 
1256 	if (from->imm == 0 &&
1257 	    (from->code == (BPF_ALU   | BPF_MOV | BPF_K) ||
1258 	     from->code == (BPF_ALU64 | BPF_MOV | BPF_K))) {
1259 		*to++ = BPF_ALU64_REG(BPF_XOR, from->dst_reg, from->dst_reg);
1260 		goto out;
1261 	}
1262 
1263 	switch (from->code) {
1264 	case BPF_ALU | BPF_ADD | BPF_K:
1265 	case BPF_ALU | BPF_SUB | BPF_K:
1266 	case BPF_ALU | BPF_AND | BPF_K:
1267 	case BPF_ALU | BPF_OR  | BPF_K:
1268 	case BPF_ALU | BPF_XOR | BPF_K:
1269 	case BPF_ALU | BPF_MUL | BPF_K:
1270 	case BPF_ALU | BPF_MOV | BPF_K:
1271 	case BPF_ALU | BPF_DIV | BPF_K:
1272 	case BPF_ALU | BPF_MOD | BPF_K:
1273 		*to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1274 		*to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1275 		*to++ = BPF_ALU32_REG(from->code, from->dst_reg, BPF_REG_AX);
1276 		break;
1277 
1278 	case BPF_ALU64 | BPF_ADD | BPF_K:
1279 	case BPF_ALU64 | BPF_SUB | BPF_K:
1280 	case BPF_ALU64 | BPF_AND | BPF_K:
1281 	case BPF_ALU64 | BPF_OR  | BPF_K:
1282 	case BPF_ALU64 | BPF_XOR | BPF_K:
1283 	case BPF_ALU64 | BPF_MUL | BPF_K:
1284 	case BPF_ALU64 | BPF_MOV | BPF_K:
1285 	case BPF_ALU64 | BPF_DIV | BPF_K:
1286 	case BPF_ALU64 | BPF_MOD | BPF_K:
1287 		*to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1288 		*to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1289 		*to++ = BPF_ALU64_REG(from->code, from->dst_reg, BPF_REG_AX);
1290 		break;
1291 
1292 	case BPF_JMP | BPF_JEQ  | BPF_K:
1293 	case BPF_JMP | BPF_JNE  | BPF_K:
1294 	case BPF_JMP | BPF_JGT  | BPF_K:
1295 	case BPF_JMP | BPF_JLT  | BPF_K:
1296 	case BPF_JMP | BPF_JGE  | BPF_K:
1297 	case BPF_JMP | BPF_JLE  | BPF_K:
1298 	case BPF_JMP | BPF_JSGT | BPF_K:
1299 	case BPF_JMP | BPF_JSLT | BPF_K:
1300 	case BPF_JMP | BPF_JSGE | BPF_K:
1301 	case BPF_JMP | BPF_JSLE | BPF_K:
1302 	case BPF_JMP | BPF_JSET | BPF_K:
1303 		/* Accommodate for extra offset in case of a backjump. */
1304 		off = from->off;
1305 		if (off < 0)
1306 			off -= 2;
1307 		*to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1308 		*to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1309 		*to++ = BPF_JMP_REG(from->code, from->dst_reg, BPF_REG_AX, off);
1310 		break;
1311 
1312 	case BPF_JMP32 | BPF_JEQ  | BPF_K:
1313 	case BPF_JMP32 | BPF_JNE  | BPF_K:
1314 	case BPF_JMP32 | BPF_JGT  | BPF_K:
1315 	case BPF_JMP32 | BPF_JLT  | BPF_K:
1316 	case BPF_JMP32 | BPF_JGE  | BPF_K:
1317 	case BPF_JMP32 | BPF_JLE  | BPF_K:
1318 	case BPF_JMP32 | BPF_JSGT | BPF_K:
1319 	case BPF_JMP32 | BPF_JSLT | BPF_K:
1320 	case BPF_JMP32 | BPF_JSGE | BPF_K:
1321 	case BPF_JMP32 | BPF_JSLE | BPF_K:
1322 	case BPF_JMP32 | BPF_JSET | BPF_K:
1323 		/* Accommodate for extra offset in case of a backjump. */
1324 		off = from->off;
1325 		if (off < 0)
1326 			off -= 2;
1327 		*to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1328 		*to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1329 		*to++ = BPF_JMP32_REG(from->code, from->dst_reg, BPF_REG_AX,
1330 				      off);
1331 		break;
1332 
1333 	case BPF_LD | BPF_IMM | BPF_DW:
1334 		*to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[1].imm);
1335 		*to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1336 		*to++ = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
1337 		*to++ = BPF_ALU64_REG(BPF_MOV, aux[0].dst_reg, BPF_REG_AX);
1338 		break;
1339 	case 0: /* Part 2 of BPF_LD | BPF_IMM | BPF_DW. */
1340 		*to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[0].imm);
1341 		*to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1342 		if (emit_zext)
1343 			*to++ = BPF_ZEXT_REG(BPF_REG_AX);
1344 		*to++ = BPF_ALU64_REG(BPF_OR,  aux[0].dst_reg, BPF_REG_AX);
1345 		break;
1346 
1347 	case BPF_ST | BPF_MEM | BPF_DW:
1348 	case BPF_ST | BPF_MEM | BPF_W:
1349 	case BPF_ST | BPF_MEM | BPF_H:
1350 	case BPF_ST | BPF_MEM | BPF_B:
1351 		*to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
1352 		*to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
1353 		*to++ = BPF_STX_MEM(from->code, from->dst_reg, BPF_REG_AX, from->off);
1354 		break;
1355 	}
1356 out:
1357 	return to - to_buff;
1358 }
1359 
1360 static struct bpf_prog *bpf_prog_clone_create(struct bpf_prog *fp_other,
1361 					      gfp_t gfp_extra_flags)
1362 {
1363 	gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
1364 	struct bpf_prog *fp;
1365 
1366 	fp = __vmalloc(fp_other->pages * PAGE_SIZE, gfp_flags);
1367 	if (fp != NULL) {
1368 		/* aux->prog still points to the fp_other one, so
1369 		 * when promoting the clone to the real program,
1370 		 * this still needs to be adapted.
1371 		 */
1372 		memcpy(fp, fp_other, fp_other->pages * PAGE_SIZE);
1373 	}
1374 
1375 	return fp;
1376 }
1377 
1378 static void bpf_prog_clone_free(struct bpf_prog *fp)
1379 {
1380 	/* aux was stolen by the other clone, so we cannot free
1381 	 * it from this path! It will be freed eventually by the
1382 	 * other program on release.
1383 	 *
1384 	 * At this point, we don't need a deferred release since
1385 	 * clone is guaranteed to not be locked.
1386 	 */
1387 	fp->aux = NULL;
1388 	fp->stats = NULL;
1389 	fp->active = NULL;
1390 	__bpf_prog_free(fp);
1391 }
1392 
1393 void bpf_jit_prog_release_other(struct bpf_prog *fp, struct bpf_prog *fp_other)
1394 {
1395 	/* We have to repoint aux->prog to self, as we don't
1396 	 * know whether fp here is the clone or the original.
1397 	 */
1398 	fp->aux->prog = fp;
1399 	bpf_prog_clone_free(fp_other);
1400 }
1401 
1402 struct bpf_prog *bpf_jit_blind_constants(struct bpf_prog *prog)
1403 {
1404 	struct bpf_insn insn_buff[16], aux[2];
1405 	struct bpf_prog *clone, *tmp;
1406 	int insn_delta, insn_cnt;
1407 	struct bpf_insn *insn;
1408 	int i, rewritten;
1409 
1410 	if (!prog->blinding_requested || prog->blinded)
1411 		return prog;
1412 
1413 	clone = bpf_prog_clone_create(prog, GFP_USER);
1414 	if (!clone)
1415 		return ERR_PTR(-ENOMEM);
1416 
1417 	insn_cnt = clone->len;
1418 	insn = clone->insnsi;
1419 
1420 	for (i = 0; i < insn_cnt; i++, insn++) {
1421 		/* We temporarily need to hold the original ld64 insn
1422 		 * so that we can still access the first part in the
1423 		 * second blinding run.
1424 		 */
1425 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW) &&
1426 		    insn[1].code == 0)
1427 			memcpy(aux, insn, sizeof(aux));
1428 
1429 		rewritten = bpf_jit_blind_insn(insn, aux, insn_buff,
1430 						clone->aux->verifier_zext);
1431 		if (!rewritten)
1432 			continue;
1433 
1434 		tmp = bpf_patch_insn_single(clone, i, insn_buff, rewritten);
1435 		if (IS_ERR(tmp)) {
1436 			/* Patching may have repointed aux->prog during
1437 			 * realloc from the original one, so we need to
1438 			 * fix it up here on error.
1439 			 */
1440 			bpf_jit_prog_release_other(prog, clone);
1441 			return tmp;
1442 		}
1443 
1444 		clone = tmp;
1445 		insn_delta = rewritten - 1;
1446 
1447 		/* Walk new program and skip insns we just inserted. */
1448 		insn = clone->insnsi + i + insn_delta;
1449 		insn_cnt += insn_delta;
1450 		i        += insn_delta;
1451 	}
1452 
1453 	clone->blinded = 1;
1454 	return clone;
1455 }
1456 #endif /* CONFIG_BPF_JIT */
1457 
1458 /* Base function for offset calculation. Needs to go into .text section,
1459  * therefore keeping it non-static as well; will also be used by JITs
1460  * anyway later on, so do not let the compiler omit it. This also needs
1461  * to go into kallsyms for correlation from e.g. bpftool, so naming
1462  * must not change.
1463  */
1464 noinline u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
1465 {
1466 	return 0;
1467 }
1468 EXPORT_SYMBOL_GPL(__bpf_call_base);
1469 
1470 /* All UAPI available opcodes. */
1471 #define BPF_INSN_MAP(INSN_2, INSN_3)		\
1472 	/* 32 bit ALU operations. */		\
1473 	/*   Register based. */			\
1474 	INSN_3(ALU, ADD,  X),			\
1475 	INSN_3(ALU, SUB,  X),			\
1476 	INSN_3(ALU, AND,  X),			\
1477 	INSN_3(ALU, OR,   X),			\
1478 	INSN_3(ALU, LSH,  X),			\
1479 	INSN_3(ALU, RSH,  X),			\
1480 	INSN_3(ALU, XOR,  X),			\
1481 	INSN_3(ALU, MUL,  X),			\
1482 	INSN_3(ALU, MOV,  X),			\
1483 	INSN_3(ALU, ARSH, X),			\
1484 	INSN_3(ALU, DIV,  X),			\
1485 	INSN_3(ALU, MOD,  X),			\
1486 	INSN_2(ALU, NEG),			\
1487 	INSN_3(ALU, END, TO_BE),		\
1488 	INSN_3(ALU, END, TO_LE),		\
1489 	/*   Immediate based. */		\
1490 	INSN_3(ALU, ADD,  K),			\
1491 	INSN_3(ALU, SUB,  K),			\
1492 	INSN_3(ALU, AND,  K),			\
1493 	INSN_3(ALU, OR,   K),			\
1494 	INSN_3(ALU, LSH,  K),			\
1495 	INSN_3(ALU, RSH,  K),			\
1496 	INSN_3(ALU, XOR,  K),			\
1497 	INSN_3(ALU, MUL,  K),			\
1498 	INSN_3(ALU, MOV,  K),			\
1499 	INSN_3(ALU, ARSH, K),			\
1500 	INSN_3(ALU, DIV,  K),			\
1501 	INSN_3(ALU, MOD,  K),			\
1502 	/* 64 bit ALU operations. */		\
1503 	/*   Register based. */			\
1504 	INSN_3(ALU64, ADD,  X),			\
1505 	INSN_3(ALU64, SUB,  X),			\
1506 	INSN_3(ALU64, AND,  X),			\
1507 	INSN_3(ALU64, OR,   X),			\
1508 	INSN_3(ALU64, LSH,  X),			\
1509 	INSN_3(ALU64, RSH,  X),			\
1510 	INSN_3(ALU64, XOR,  X),			\
1511 	INSN_3(ALU64, MUL,  X),			\
1512 	INSN_3(ALU64, MOV,  X),			\
1513 	INSN_3(ALU64, ARSH, X),			\
1514 	INSN_3(ALU64, DIV,  X),			\
1515 	INSN_3(ALU64, MOD,  X),			\
1516 	INSN_2(ALU64, NEG),			\
1517 	/*   Immediate based. */		\
1518 	INSN_3(ALU64, ADD,  K),			\
1519 	INSN_3(ALU64, SUB,  K),			\
1520 	INSN_3(ALU64, AND,  K),			\
1521 	INSN_3(ALU64, OR,   K),			\
1522 	INSN_3(ALU64, LSH,  K),			\
1523 	INSN_3(ALU64, RSH,  K),			\
1524 	INSN_3(ALU64, XOR,  K),			\
1525 	INSN_3(ALU64, MUL,  K),			\
1526 	INSN_3(ALU64, MOV,  K),			\
1527 	INSN_3(ALU64, ARSH, K),			\
1528 	INSN_3(ALU64, DIV,  K),			\
1529 	INSN_3(ALU64, MOD,  K),			\
1530 	/* Call instruction. */			\
1531 	INSN_2(JMP, CALL),			\
1532 	/* Exit instruction. */			\
1533 	INSN_2(JMP, EXIT),			\
1534 	/* 32-bit Jump instructions. */		\
1535 	/*   Register based. */			\
1536 	INSN_3(JMP32, JEQ,  X),			\
1537 	INSN_3(JMP32, JNE,  X),			\
1538 	INSN_3(JMP32, JGT,  X),			\
1539 	INSN_3(JMP32, JLT,  X),			\
1540 	INSN_3(JMP32, JGE,  X),			\
1541 	INSN_3(JMP32, JLE,  X),			\
1542 	INSN_3(JMP32, JSGT, X),			\
1543 	INSN_3(JMP32, JSLT, X),			\
1544 	INSN_3(JMP32, JSGE, X),			\
1545 	INSN_3(JMP32, JSLE, X),			\
1546 	INSN_3(JMP32, JSET, X),			\
1547 	/*   Immediate based. */		\
1548 	INSN_3(JMP32, JEQ,  K),			\
1549 	INSN_3(JMP32, JNE,  K),			\
1550 	INSN_3(JMP32, JGT,  K),			\
1551 	INSN_3(JMP32, JLT,  K),			\
1552 	INSN_3(JMP32, JGE,  K),			\
1553 	INSN_3(JMP32, JLE,  K),			\
1554 	INSN_3(JMP32, JSGT, K),			\
1555 	INSN_3(JMP32, JSLT, K),			\
1556 	INSN_3(JMP32, JSGE, K),			\
1557 	INSN_3(JMP32, JSLE, K),			\
1558 	INSN_3(JMP32, JSET, K),			\
1559 	/* Jump instructions. */		\
1560 	/*   Register based. */			\
1561 	INSN_3(JMP, JEQ,  X),			\
1562 	INSN_3(JMP, JNE,  X),			\
1563 	INSN_3(JMP, JGT,  X),			\
1564 	INSN_3(JMP, JLT,  X),			\
1565 	INSN_3(JMP, JGE,  X),			\
1566 	INSN_3(JMP, JLE,  X),			\
1567 	INSN_3(JMP, JSGT, X),			\
1568 	INSN_3(JMP, JSLT, X),			\
1569 	INSN_3(JMP, JSGE, X),			\
1570 	INSN_3(JMP, JSLE, X),			\
1571 	INSN_3(JMP, JSET, X),			\
1572 	/*   Immediate based. */		\
1573 	INSN_3(JMP, JEQ,  K),			\
1574 	INSN_3(JMP, JNE,  K),			\
1575 	INSN_3(JMP, JGT,  K),			\
1576 	INSN_3(JMP, JLT,  K),			\
1577 	INSN_3(JMP, JGE,  K),			\
1578 	INSN_3(JMP, JLE,  K),			\
1579 	INSN_3(JMP, JSGT, K),			\
1580 	INSN_3(JMP, JSLT, K),			\
1581 	INSN_3(JMP, JSGE, K),			\
1582 	INSN_3(JMP, JSLE, K),			\
1583 	INSN_3(JMP, JSET, K),			\
1584 	INSN_2(JMP, JA),			\
1585 	/* Store instructions. */		\
1586 	/*   Register based. */			\
1587 	INSN_3(STX, MEM,  B),			\
1588 	INSN_3(STX, MEM,  H),			\
1589 	INSN_3(STX, MEM,  W),			\
1590 	INSN_3(STX, MEM,  DW),			\
1591 	INSN_3(STX, ATOMIC, W),			\
1592 	INSN_3(STX, ATOMIC, DW),		\
1593 	/*   Immediate based. */		\
1594 	INSN_3(ST, MEM, B),			\
1595 	INSN_3(ST, MEM, H),			\
1596 	INSN_3(ST, MEM, W),			\
1597 	INSN_3(ST, MEM, DW),			\
1598 	/* Load instructions. */		\
1599 	/*   Register based. */			\
1600 	INSN_3(LDX, MEM, B),			\
1601 	INSN_3(LDX, MEM, H),			\
1602 	INSN_3(LDX, MEM, W),			\
1603 	INSN_3(LDX, MEM, DW),			\
1604 	/*   Immediate based. */		\
1605 	INSN_3(LD, IMM, DW)
1606 
1607 bool bpf_opcode_in_insntable(u8 code)
1608 {
1609 #define BPF_INSN_2_TBL(x, y)    [BPF_##x | BPF_##y] = true
1610 #define BPF_INSN_3_TBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = true
1611 	static const bool public_insntable[256] = {
1612 		[0 ... 255] = false,
1613 		/* Now overwrite non-defaults ... */
1614 		BPF_INSN_MAP(BPF_INSN_2_TBL, BPF_INSN_3_TBL),
1615 		/* UAPI exposed, but rewritten opcodes. cBPF carry-over. */
1616 		[BPF_LD | BPF_ABS | BPF_B] = true,
1617 		[BPF_LD | BPF_ABS | BPF_H] = true,
1618 		[BPF_LD | BPF_ABS | BPF_W] = true,
1619 		[BPF_LD | BPF_IND | BPF_B] = true,
1620 		[BPF_LD | BPF_IND | BPF_H] = true,
1621 		[BPF_LD | BPF_IND | BPF_W] = true,
1622 	};
1623 #undef BPF_INSN_3_TBL
1624 #undef BPF_INSN_2_TBL
1625 	return public_insntable[code];
1626 }
1627 
1628 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1629 u64 __weak bpf_probe_read_kernel(void *dst, u32 size, const void *unsafe_ptr)
1630 {
1631 	memset(dst, 0, size);
1632 	return -EFAULT;
1633 }
1634 
1635 /**
1636  *	___bpf_prog_run - run eBPF program on a given context
1637  *	@regs: is the array of MAX_BPF_EXT_REG eBPF pseudo-registers
1638  *	@insn: is the array of eBPF instructions
1639  *
1640  * Decode and execute eBPF instructions.
1641  *
1642  * Return: whatever value is in %BPF_R0 at program exit
1643  */
1644 static u64 ___bpf_prog_run(u64 *regs, const struct bpf_insn *insn)
1645 {
1646 #define BPF_INSN_2_LBL(x, y)    [BPF_##x | BPF_##y] = &&x##_##y
1647 #define BPF_INSN_3_LBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = &&x##_##y##_##z
1648 	static const void * const jumptable[256] __annotate_jump_table = {
1649 		[0 ... 255] = &&default_label,
1650 		/* Now overwrite non-defaults ... */
1651 		BPF_INSN_MAP(BPF_INSN_2_LBL, BPF_INSN_3_LBL),
1652 		/* Non-UAPI available opcodes. */
1653 		[BPF_JMP | BPF_CALL_ARGS] = &&JMP_CALL_ARGS,
1654 		[BPF_JMP | BPF_TAIL_CALL] = &&JMP_TAIL_CALL,
1655 		[BPF_ST  | BPF_NOSPEC] = &&ST_NOSPEC,
1656 		[BPF_LDX | BPF_PROBE_MEM | BPF_B] = &&LDX_PROBE_MEM_B,
1657 		[BPF_LDX | BPF_PROBE_MEM | BPF_H] = &&LDX_PROBE_MEM_H,
1658 		[BPF_LDX | BPF_PROBE_MEM | BPF_W] = &&LDX_PROBE_MEM_W,
1659 		[BPF_LDX | BPF_PROBE_MEM | BPF_DW] = &&LDX_PROBE_MEM_DW,
1660 	};
1661 #undef BPF_INSN_3_LBL
1662 #undef BPF_INSN_2_LBL
1663 	u32 tail_call_cnt = 0;
1664 
1665 #define CONT	 ({ insn++; goto select_insn; })
1666 #define CONT_JMP ({ insn++; goto select_insn; })
1667 
1668 select_insn:
1669 	goto *jumptable[insn->code];
1670 
1671 	/* Explicitly mask the register-based shift amounts with 63 or 31
1672 	 * to avoid undefined behavior. Normally this won't affect the
1673 	 * generated code, for example, in case of native 64 bit archs such
1674 	 * as x86-64 or arm64, the compiler is optimizing the AND away for
1675 	 * the interpreter. In case of JITs, each of the JIT backends compiles
1676 	 * the BPF shift operations to machine instructions which produce
1677 	 * implementation-defined results in such a case; the resulting
1678 	 * contents of the register may be arbitrary, but program behaviour
1679 	 * as a whole remains defined. In other words, in case of JIT backends,
1680 	 * the AND must /not/ be added to the emitted LSH/RSH/ARSH translation.
1681 	 */
1682 	/* ALU (shifts) */
1683 #define SHT(OPCODE, OP)					\
1684 	ALU64_##OPCODE##_X:				\
1685 		DST = DST OP (SRC & 63);		\
1686 		CONT;					\
1687 	ALU_##OPCODE##_X:				\
1688 		DST = (u32) DST OP ((u32) SRC & 31);	\
1689 		CONT;					\
1690 	ALU64_##OPCODE##_K:				\
1691 		DST = DST OP IMM;			\
1692 		CONT;					\
1693 	ALU_##OPCODE##_K:				\
1694 		DST = (u32) DST OP (u32) IMM;		\
1695 		CONT;
1696 	/* ALU (rest) */
1697 #define ALU(OPCODE, OP)					\
1698 	ALU64_##OPCODE##_X:				\
1699 		DST = DST OP SRC;			\
1700 		CONT;					\
1701 	ALU_##OPCODE##_X:				\
1702 		DST = (u32) DST OP (u32) SRC;		\
1703 		CONT;					\
1704 	ALU64_##OPCODE##_K:				\
1705 		DST = DST OP IMM;			\
1706 		CONT;					\
1707 	ALU_##OPCODE##_K:				\
1708 		DST = (u32) DST OP (u32) IMM;		\
1709 		CONT;
1710 	ALU(ADD,  +)
1711 	ALU(SUB,  -)
1712 	ALU(AND,  &)
1713 	ALU(OR,   |)
1714 	ALU(XOR,  ^)
1715 	ALU(MUL,  *)
1716 	SHT(LSH, <<)
1717 	SHT(RSH, >>)
1718 #undef SHT
1719 #undef ALU
1720 	ALU_NEG:
1721 		DST = (u32) -DST;
1722 		CONT;
1723 	ALU64_NEG:
1724 		DST = -DST;
1725 		CONT;
1726 	ALU_MOV_X:
1727 		DST = (u32) SRC;
1728 		CONT;
1729 	ALU_MOV_K:
1730 		DST = (u32) IMM;
1731 		CONT;
1732 	ALU64_MOV_X:
1733 		DST = SRC;
1734 		CONT;
1735 	ALU64_MOV_K:
1736 		DST = IMM;
1737 		CONT;
1738 	LD_IMM_DW:
1739 		DST = (u64) (u32) insn[0].imm | ((u64) (u32) insn[1].imm) << 32;
1740 		insn++;
1741 		CONT;
1742 	ALU_ARSH_X:
1743 		DST = (u64) (u32) (((s32) DST) >> (SRC & 31));
1744 		CONT;
1745 	ALU_ARSH_K:
1746 		DST = (u64) (u32) (((s32) DST) >> IMM);
1747 		CONT;
1748 	ALU64_ARSH_X:
1749 		(*(s64 *) &DST) >>= (SRC & 63);
1750 		CONT;
1751 	ALU64_ARSH_K:
1752 		(*(s64 *) &DST) >>= IMM;
1753 		CONT;
1754 	ALU64_MOD_X:
1755 		div64_u64_rem(DST, SRC, &AX);
1756 		DST = AX;
1757 		CONT;
1758 	ALU_MOD_X:
1759 		AX = (u32) DST;
1760 		DST = do_div(AX, (u32) SRC);
1761 		CONT;
1762 	ALU64_MOD_K:
1763 		div64_u64_rem(DST, IMM, &AX);
1764 		DST = AX;
1765 		CONT;
1766 	ALU_MOD_K:
1767 		AX = (u32) DST;
1768 		DST = do_div(AX, (u32) IMM);
1769 		CONT;
1770 	ALU64_DIV_X:
1771 		DST = div64_u64(DST, SRC);
1772 		CONT;
1773 	ALU_DIV_X:
1774 		AX = (u32) DST;
1775 		do_div(AX, (u32) SRC);
1776 		DST = (u32) AX;
1777 		CONT;
1778 	ALU64_DIV_K:
1779 		DST = div64_u64(DST, IMM);
1780 		CONT;
1781 	ALU_DIV_K:
1782 		AX = (u32) DST;
1783 		do_div(AX, (u32) IMM);
1784 		DST = (u32) AX;
1785 		CONT;
1786 	ALU_END_TO_BE:
1787 		switch (IMM) {
1788 		case 16:
1789 			DST = (__force u16) cpu_to_be16(DST);
1790 			break;
1791 		case 32:
1792 			DST = (__force u32) cpu_to_be32(DST);
1793 			break;
1794 		case 64:
1795 			DST = (__force u64) cpu_to_be64(DST);
1796 			break;
1797 		}
1798 		CONT;
1799 	ALU_END_TO_LE:
1800 		switch (IMM) {
1801 		case 16:
1802 			DST = (__force u16) cpu_to_le16(DST);
1803 			break;
1804 		case 32:
1805 			DST = (__force u32) cpu_to_le32(DST);
1806 			break;
1807 		case 64:
1808 			DST = (__force u64) cpu_to_le64(DST);
1809 			break;
1810 		}
1811 		CONT;
1812 
1813 	/* CALL */
1814 	JMP_CALL:
1815 		/* Function call scratches BPF_R1-BPF_R5 registers,
1816 		 * preserves BPF_R6-BPF_R9, and stores return value
1817 		 * into BPF_R0.
1818 		 */
1819 		BPF_R0 = (__bpf_call_base + insn->imm)(BPF_R1, BPF_R2, BPF_R3,
1820 						       BPF_R4, BPF_R5);
1821 		CONT;
1822 
1823 	JMP_CALL_ARGS:
1824 		BPF_R0 = (__bpf_call_base_args + insn->imm)(BPF_R1, BPF_R2,
1825 							    BPF_R3, BPF_R4,
1826 							    BPF_R5,
1827 							    insn + insn->off + 1);
1828 		CONT;
1829 
1830 	JMP_TAIL_CALL: {
1831 		struct bpf_map *map = (struct bpf_map *) (unsigned long) BPF_R2;
1832 		struct bpf_array *array = container_of(map, struct bpf_array, map);
1833 		struct bpf_prog *prog;
1834 		u32 index = BPF_R3;
1835 
1836 		if (unlikely(index >= array->map.max_entries))
1837 			goto out;
1838 
1839 		if (unlikely(tail_call_cnt >= MAX_TAIL_CALL_CNT))
1840 			goto out;
1841 
1842 		tail_call_cnt++;
1843 
1844 		prog = READ_ONCE(array->ptrs[index]);
1845 		if (!prog)
1846 			goto out;
1847 
1848 		/* ARG1 at this point is guaranteed to point to CTX from
1849 		 * the verifier side due to the fact that the tail call is
1850 		 * handled like a helper, that is, bpf_tail_call_proto,
1851 		 * where arg1_type is ARG_PTR_TO_CTX.
1852 		 */
1853 		insn = prog->insnsi;
1854 		goto select_insn;
1855 out:
1856 		CONT;
1857 	}
1858 	JMP_JA:
1859 		insn += insn->off;
1860 		CONT;
1861 	JMP_EXIT:
1862 		return BPF_R0;
1863 	/* JMP */
1864 #define COND_JMP(SIGN, OPCODE, CMP_OP)				\
1865 	JMP_##OPCODE##_X:					\
1866 		if ((SIGN##64) DST CMP_OP (SIGN##64) SRC) {	\
1867 			insn += insn->off;			\
1868 			CONT_JMP;				\
1869 		}						\
1870 		CONT;						\
1871 	JMP32_##OPCODE##_X:					\
1872 		if ((SIGN##32) DST CMP_OP (SIGN##32) SRC) {	\
1873 			insn += insn->off;			\
1874 			CONT_JMP;				\
1875 		}						\
1876 		CONT;						\
1877 	JMP_##OPCODE##_K:					\
1878 		if ((SIGN##64) DST CMP_OP (SIGN##64) IMM) {	\
1879 			insn += insn->off;			\
1880 			CONT_JMP;				\
1881 		}						\
1882 		CONT;						\
1883 	JMP32_##OPCODE##_K:					\
1884 		if ((SIGN##32) DST CMP_OP (SIGN##32) IMM) {	\
1885 			insn += insn->off;			\
1886 			CONT_JMP;				\
1887 		}						\
1888 		CONT;
1889 	COND_JMP(u, JEQ, ==)
1890 	COND_JMP(u, JNE, !=)
1891 	COND_JMP(u, JGT, >)
1892 	COND_JMP(u, JLT, <)
1893 	COND_JMP(u, JGE, >=)
1894 	COND_JMP(u, JLE, <=)
1895 	COND_JMP(u, JSET, &)
1896 	COND_JMP(s, JSGT, >)
1897 	COND_JMP(s, JSLT, <)
1898 	COND_JMP(s, JSGE, >=)
1899 	COND_JMP(s, JSLE, <=)
1900 #undef COND_JMP
1901 	/* ST, STX and LDX*/
1902 	ST_NOSPEC:
1903 		/* Speculation barrier for mitigating Speculative Store Bypass.
1904 		 * In case of arm64, we rely on the firmware mitigation as
1905 		 * controlled via the ssbd kernel parameter. Whenever the
1906 		 * mitigation is enabled, it works for all of the kernel code
1907 		 * with no need to provide any additional instructions here.
1908 		 * In case of x86, we use 'lfence' insn for mitigation. We
1909 		 * reuse preexisting logic from Spectre v1 mitigation that
1910 		 * happens to produce the required code on x86 for v4 as well.
1911 		 */
1912 #ifdef CONFIG_X86
1913 		barrier_nospec();
1914 #endif
1915 		CONT;
1916 #define LDST(SIZEOP, SIZE)						\
1917 	STX_MEM_##SIZEOP:						\
1918 		*(SIZE *)(unsigned long) (DST + insn->off) = SRC;	\
1919 		CONT;							\
1920 	ST_MEM_##SIZEOP:						\
1921 		*(SIZE *)(unsigned long) (DST + insn->off) = IMM;	\
1922 		CONT;							\
1923 	LDX_MEM_##SIZEOP:						\
1924 		DST = *(SIZE *)(unsigned long) (SRC + insn->off);	\
1925 		CONT;
1926 
1927 	LDST(B,   u8)
1928 	LDST(H,  u16)
1929 	LDST(W,  u32)
1930 	LDST(DW, u64)
1931 #undef LDST
1932 #define LDX_PROBE(SIZEOP, SIZE)							\
1933 	LDX_PROBE_MEM_##SIZEOP:							\
1934 		bpf_probe_read_kernel(&DST, SIZE, (const void *)(long) (SRC + insn->off));	\
1935 		CONT;
1936 	LDX_PROBE(B,  1)
1937 	LDX_PROBE(H,  2)
1938 	LDX_PROBE(W,  4)
1939 	LDX_PROBE(DW, 8)
1940 #undef LDX_PROBE
1941 
1942 #define ATOMIC_ALU_OP(BOP, KOP)						\
1943 		case BOP:						\
1944 			if (BPF_SIZE(insn->code) == BPF_W)		\
1945 				atomic_##KOP((u32) SRC, (atomic_t *)(unsigned long) \
1946 					     (DST + insn->off));	\
1947 			else						\
1948 				atomic64_##KOP((u64) SRC, (atomic64_t *)(unsigned long) \
1949 					       (DST + insn->off));	\
1950 			break;						\
1951 		case BOP | BPF_FETCH:					\
1952 			if (BPF_SIZE(insn->code) == BPF_W)		\
1953 				SRC = (u32) atomic_fetch_##KOP(		\
1954 					(u32) SRC,			\
1955 					(atomic_t *)(unsigned long) (DST + insn->off)); \
1956 			else						\
1957 				SRC = (u64) atomic64_fetch_##KOP(	\
1958 					(u64) SRC,			\
1959 					(atomic64_t *)(unsigned long) (DST + insn->off)); \
1960 			break;
1961 
1962 	STX_ATOMIC_DW:
1963 	STX_ATOMIC_W:
1964 		switch (IMM) {
1965 		ATOMIC_ALU_OP(BPF_ADD, add)
1966 		ATOMIC_ALU_OP(BPF_AND, and)
1967 		ATOMIC_ALU_OP(BPF_OR, or)
1968 		ATOMIC_ALU_OP(BPF_XOR, xor)
1969 #undef ATOMIC_ALU_OP
1970 
1971 		case BPF_XCHG:
1972 			if (BPF_SIZE(insn->code) == BPF_W)
1973 				SRC = (u32) atomic_xchg(
1974 					(atomic_t *)(unsigned long) (DST + insn->off),
1975 					(u32) SRC);
1976 			else
1977 				SRC = (u64) atomic64_xchg(
1978 					(atomic64_t *)(unsigned long) (DST + insn->off),
1979 					(u64) SRC);
1980 			break;
1981 		case BPF_CMPXCHG:
1982 			if (BPF_SIZE(insn->code) == BPF_W)
1983 				BPF_R0 = (u32) atomic_cmpxchg(
1984 					(atomic_t *)(unsigned long) (DST + insn->off),
1985 					(u32) BPF_R0, (u32) SRC);
1986 			else
1987 				BPF_R0 = (u64) atomic64_cmpxchg(
1988 					(atomic64_t *)(unsigned long) (DST + insn->off),
1989 					(u64) BPF_R0, (u64) SRC);
1990 			break;
1991 
1992 		default:
1993 			goto default_label;
1994 		}
1995 		CONT;
1996 
1997 	default_label:
1998 		/* If we ever reach this, we have a bug somewhere. Die hard here
1999 		 * instead of just returning 0; we could be somewhere in a subprog,
2000 		 * so execution could continue otherwise which we do /not/ want.
2001 		 *
2002 		 * Note, verifier whitelists all opcodes in bpf_opcode_in_insntable().
2003 		 */
2004 		pr_warn("BPF interpreter: unknown opcode %02x (imm: 0x%x)\n",
2005 			insn->code, insn->imm);
2006 		BUG_ON(1);
2007 		return 0;
2008 }
2009 
2010 #define PROG_NAME(stack_size) __bpf_prog_run##stack_size
2011 #define DEFINE_BPF_PROG_RUN(stack_size) \
2012 static unsigned int PROG_NAME(stack_size)(const void *ctx, const struct bpf_insn *insn) \
2013 { \
2014 	u64 stack[stack_size / sizeof(u64)]; \
2015 	u64 regs[MAX_BPF_EXT_REG]; \
2016 \
2017 	FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
2018 	ARG1 = (u64) (unsigned long) ctx; \
2019 	return ___bpf_prog_run(regs, insn); \
2020 }
2021 
2022 #define PROG_NAME_ARGS(stack_size) __bpf_prog_run_args##stack_size
2023 #define DEFINE_BPF_PROG_RUN_ARGS(stack_size) \
2024 static u64 PROG_NAME_ARGS(stack_size)(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, \
2025 				      const struct bpf_insn *insn) \
2026 { \
2027 	u64 stack[stack_size / sizeof(u64)]; \
2028 	u64 regs[MAX_BPF_EXT_REG]; \
2029 \
2030 	FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
2031 	BPF_R1 = r1; \
2032 	BPF_R2 = r2; \
2033 	BPF_R3 = r3; \
2034 	BPF_R4 = r4; \
2035 	BPF_R5 = r5; \
2036 	return ___bpf_prog_run(regs, insn); \
2037 }
2038 
2039 #define EVAL1(FN, X) FN(X)
2040 #define EVAL2(FN, X, Y...) FN(X) EVAL1(FN, Y)
2041 #define EVAL3(FN, X, Y...) FN(X) EVAL2(FN, Y)
2042 #define EVAL4(FN, X, Y...) FN(X) EVAL3(FN, Y)
2043 #define EVAL5(FN, X, Y...) FN(X) EVAL4(FN, Y)
2044 #define EVAL6(FN, X, Y...) FN(X) EVAL5(FN, Y)
2045 
2046 EVAL6(DEFINE_BPF_PROG_RUN, 32, 64, 96, 128, 160, 192);
2047 EVAL6(DEFINE_BPF_PROG_RUN, 224, 256, 288, 320, 352, 384);
2048 EVAL4(DEFINE_BPF_PROG_RUN, 416, 448, 480, 512);
2049 
2050 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 32, 64, 96, 128, 160, 192);
2051 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 224, 256, 288, 320, 352, 384);
2052 EVAL4(DEFINE_BPF_PROG_RUN_ARGS, 416, 448, 480, 512);
2053 
2054 #define PROG_NAME_LIST(stack_size) PROG_NAME(stack_size),
2055 
2056 static unsigned int (*interpreters[])(const void *ctx,
2057 				      const struct bpf_insn *insn) = {
2058 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
2059 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
2060 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
2061 };
2062 #undef PROG_NAME_LIST
2063 #define PROG_NAME_LIST(stack_size) PROG_NAME_ARGS(stack_size),
2064 static u64 (*interpreters_args[])(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5,
2065 				  const struct bpf_insn *insn) = {
2066 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
2067 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
2068 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
2069 };
2070 #undef PROG_NAME_LIST
2071 
2072 void bpf_patch_call_args(struct bpf_insn *insn, u32 stack_depth)
2073 {
2074 	stack_depth = max_t(u32, stack_depth, 1);
2075 	insn->off = (s16) insn->imm;
2076 	insn->imm = interpreters_args[(round_up(stack_depth, 32) / 32) - 1] -
2077 		__bpf_call_base_args;
2078 	insn->code = BPF_JMP | BPF_CALL_ARGS;
2079 }
2080 
2081 #else
2082 static unsigned int __bpf_prog_ret0_warn(const void *ctx,
2083 					 const struct bpf_insn *insn)
2084 {
2085 	/* If this handler ever gets executed, then BPF_JIT_ALWAYS_ON
2086 	 * is not working properly, so warn about it!
2087 	 */
2088 	WARN_ON_ONCE(1);
2089 	return 0;
2090 }
2091 #endif
2092 
2093 bool bpf_prog_map_compatible(struct bpf_map *map,
2094 			     const struct bpf_prog *fp)
2095 {
2096 	bool ret;
2097 
2098 	if (fp->kprobe_override)
2099 		return false;
2100 
2101 	spin_lock(&map->owner.lock);
2102 	if (!map->owner.type) {
2103 		/* There's no owner yet where we could check for
2104 		 * compatibility.
2105 		 */
2106 		map->owner.type  = fp->type;
2107 		map->owner.jited = fp->jited;
2108 		map->owner.xdp_has_frags = fp->aux->xdp_has_frags;
2109 		ret = true;
2110 	} else {
2111 		ret = map->owner.type  == fp->type &&
2112 		      map->owner.jited == fp->jited &&
2113 		      map->owner.xdp_has_frags == fp->aux->xdp_has_frags;
2114 	}
2115 	spin_unlock(&map->owner.lock);
2116 
2117 	return ret;
2118 }
2119 
2120 static int bpf_check_tail_call(const struct bpf_prog *fp)
2121 {
2122 	struct bpf_prog_aux *aux = fp->aux;
2123 	int i, ret = 0;
2124 
2125 	mutex_lock(&aux->used_maps_mutex);
2126 	for (i = 0; i < aux->used_map_cnt; i++) {
2127 		struct bpf_map *map = aux->used_maps[i];
2128 
2129 		if (!map_type_contains_progs(map))
2130 			continue;
2131 
2132 		if (!bpf_prog_map_compatible(map, fp)) {
2133 			ret = -EINVAL;
2134 			goto out;
2135 		}
2136 	}
2137 
2138 out:
2139 	mutex_unlock(&aux->used_maps_mutex);
2140 	return ret;
2141 }
2142 
2143 static void bpf_prog_select_func(struct bpf_prog *fp)
2144 {
2145 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
2146 	u32 stack_depth = max_t(u32, fp->aux->stack_depth, 1);
2147 
2148 	fp->bpf_func = interpreters[(round_up(stack_depth, 32) / 32) - 1];
2149 #else
2150 	fp->bpf_func = __bpf_prog_ret0_warn;
2151 #endif
2152 }
2153 
2154 /**
2155  *	bpf_prog_select_runtime - select exec runtime for BPF program
2156  *	@fp: bpf_prog populated with BPF program
2157  *	@err: pointer to error variable
2158  *
2159  * Try to JIT eBPF program, if JIT is not available, use interpreter.
2160  * The BPF program will be executed via bpf_prog_run() function.
2161  *
2162  * Return: the &fp argument along with &err set to 0 for success or
2163  * a negative errno code on failure
2164  */
2165 struct bpf_prog *bpf_prog_select_runtime(struct bpf_prog *fp, int *err)
2166 {
2167 	/* In case of BPF to BPF calls, verifier did all the prep
2168 	 * work with regards to JITing, etc.
2169 	 */
2170 	bool jit_needed = false;
2171 
2172 	if (fp->bpf_func)
2173 		goto finalize;
2174 
2175 	if (IS_ENABLED(CONFIG_BPF_JIT_ALWAYS_ON) ||
2176 	    bpf_prog_has_kfunc_call(fp))
2177 		jit_needed = true;
2178 
2179 	bpf_prog_select_func(fp);
2180 
2181 	/* eBPF JITs can rewrite the program in case constant
2182 	 * blinding is active. However, in case of error during
2183 	 * blinding, bpf_int_jit_compile() must always return a
2184 	 * valid program, which in this case would simply not
2185 	 * be JITed, but falls back to the interpreter.
2186 	 */
2187 	if (!bpf_prog_is_dev_bound(fp->aux)) {
2188 		*err = bpf_prog_alloc_jited_linfo(fp);
2189 		if (*err)
2190 			return fp;
2191 
2192 		fp = bpf_int_jit_compile(fp);
2193 		bpf_prog_jit_attempt_done(fp);
2194 		if (!fp->jited && jit_needed) {
2195 			*err = -ENOTSUPP;
2196 			return fp;
2197 		}
2198 	} else {
2199 		*err = bpf_prog_offload_compile(fp);
2200 		if (*err)
2201 			return fp;
2202 	}
2203 
2204 finalize:
2205 	bpf_prog_lock_ro(fp);
2206 
2207 	/* The tail call compatibility check can only be done at
2208 	 * this late stage as we need to determine, if we deal
2209 	 * with JITed or non JITed program concatenations and not
2210 	 * all eBPF JITs might immediately support all features.
2211 	 */
2212 	*err = bpf_check_tail_call(fp);
2213 
2214 	return fp;
2215 }
2216 EXPORT_SYMBOL_GPL(bpf_prog_select_runtime);
2217 
2218 static unsigned int __bpf_prog_ret1(const void *ctx,
2219 				    const struct bpf_insn *insn)
2220 {
2221 	return 1;
2222 }
2223 
2224 static struct bpf_prog_dummy {
2225 	struct bpf_prog prog;
2226 } dummy_bpf_prog = {
2227 	.prog = {
2228 		.bpf_func = __bpf_prog_ret1,
2229 	},
2230 };
2231 
2232 struct bpf_empty_prog_array bpf_empty_prog_array = {
2233 	.null_prog = NULL,
2234 };
2235 EXPORT_SYMBOL(bpf_empty_prog_array);
2236 
2237 struct bpf_prog_array *bpf_prog_array_alloc(u32 prog_cnt, gfp_t flags)
2238 {
2239 	if (prog_cnt)
2240 		return kzalloc(sizeof(struct bpf_prog_array) +
2241 			       sizeof(struct bpf_prog_array_item) *
2242 			       (prog_cnt + 1),
2243 			       flags);
2244 
2245 	return &bpf_empty_prog_array.hdr;
2246 }
2247 
2248 void bpf_prog_array_free(struct bpf_prog_array *progs)
2249 {
2250 	if (!progs || progs == &bpf_empty_prog_array.hdr)
2251 		return;
2252 	kfree_rcu(progs, rcu);
2253 }
2254 
2255 int bpf_prog_array_length(struct bpf_prog_array *array)
2256 {
2257 	struct bpf_prog_array_item *item;
2258 	u32 cnt = 0;
2259 
2260 	for (item = array->items; item->prog; item++)
2261 		if (item->prog != &dummy_bpf_prog.prog)
2262 			cnt++;
2263 	return cnt;
2264 }
2265 
2266 bool bpf_prog_array_is_empty(struct bpf_prog_array *array)
2267 {
2268 	struct bpf_prog_array_item *item;
2269 
2270 	for (item = array->items; item->prog; item++)
2271 		if (item->prog != &dummy_bpf_prog.prog)
2272 			return false;
2273 	return true;
2274 }
2275 
2276 static bool bpf_prog_array_copy_core(struct bpf_prog_array *array,
2277 				     u32 *prog_ids,
2278 				     u32 request_cnt)
2279 {
2280 	struct bpf_prog_array_item *item;
2281 	int i = 0;
2282 
2283 	for (item = array->items; item->prog; item++) {
2284 		if (item->prog == &dummy_bpf_prog.prog)
2285 			continue;
2286 		prog_ids[i] = item->prog->aux->id;
2287 		if (++i == request_cnt) {
2288 			item++;
2289 			break;
2290 		}
2291 	}
2292 
2293 	return !!(item->prog);
2294 }
2295 
2296 int bpf_prog_array_copy_to_user(struct bpf_prog_array *array,
2297 				__u32 __user *prog_ids, u32 cnt)
2298 {
2299 	unsigned long err = 0;
2300 	bool nospc;
2301 	u32 *ids;
2302 
2303 	/* users of this function are doing:
2304 	 * cnt = bpf_prog_array_length();
2305 	 * if (cnt > 0)
2306 	 *     bpf_prog_array_copy_to_user(..., cnt);
2307 	 * so below kcalloc doesn't need extra cnt > 0 check.
2308 	 */
2309 	ids = kcalloc(cnt, sizeof(u32), GFP_USER | __GFP_NOWARN);
2310 	if (!ids)
2311 		return -ENOMEM;
2312 	nospc = bpf_prog_array_copy_core(array, ids, cnt);
2313 	err = copy_to_user(prog_ids, ids, cnt * sizeof(u32));
2314 	kfree(ids);
2315 	if (err)
2316 		return -EFAULT;
2317 	if (nospc)
2318 		return -ENOSPC;
2319 	return 0;
2320 }
2321 
2322 void bpf_prog_array_delete_safe(struct bpf_prog_array *array,
2323 				struct bpf_prog *old_prog)
2324 {
2325 	struct bpf_prog_array_item *item;
2326 
2327 	for (item = array->items; item->prog; item++)
2328 		if (item->prog == old_prog) {
2329 			WRITE_ONCE(item->prog, &dummy_bpf_prog.prog);
2330 			break;
2331 		}
2332 }
2333 
2334 /**
2335  * bpf_prog_array_delete_safe_at() - Replaces the program at the given
2336  *                                   index into the program array with
2337  *                                   a dummy no-op program.
2338  * @array: a bpf_prog_array
2339  * @index: the index of the program to replace
2340  *
2341  * Skips over dummy programs, by not counting them, when calculating
2342  * the position of the program to replace.
2343  *
2344  * Return:
2345  * * 0		- Success
2346  * * -EINVAL	- Invalid index value. Must be a non-negative integer.
2347  * * -ENOENT	- Index out of range
2348  */
2349 int bpf_prog_array_delete_safe_at(struct bpf_prog_array *array, int index)
2350 {
2351 	return bpf_prog_array_update_at(array, index, &dummy_bpf_prog.prog);
2352 }
2353 
2354 /**
2355  * bpf_prog_array_update_at() - Updates the program at the given index
2356  *                              into the program array.
2357  * @array: a bpf_prog_array
2358  * @index: the index of the program to update
2359  * @prog: the program to insert into the array
2360  *
2361  * Skips over dummy programs, by not counting them, when calculating
2362  * the position of the program to update.
2363  *
2364  * Return:
2365  * * 0		- Success
2366  * * -EINVAL	- Invalid index value. Must be a non-negative integer.
2367  * * -ENOENT	- Index out of range
2368  */
2369 int bpf_prog_array_update_at(struct bpf_prog_array *array, int index,
2370 			     struct bpf_prog *prog)
2371 {
2372 	struct bpf_prog_array_item *item;
2373 
2374 	if (unlikely(index < 0))
2375 		return -EINVAL;
2376 
2377 	for (item = array->items; item->prog; item++) {
2378 		if (item->prog == &dummy_bpf_prog.prog)
2379 			continue;
2380 		if (!index) {
2381 			WRITE_ONCE(item->prog, prog);
2382 			return 0;
2383 		}
2384 		index--;
2385 	}
2386 	return -ENOENT;
2387 }
2388 
2389 int bpf_prog_array_copy(struct bpf_prog_array *old_array,
2390 			struct bpf_prog *exclude_prog,
2391 			struct bpf_prog *include_prog,
2392 			u64 bpf_cookie,
2393 			struct bpf_prog_array **new_array)
2394 {
2395 	int new_prog_cnt, carry_prog_cnt = 0;
2396 	struct bpf_prog_array_item *existing, *new;
2397 	struct bpf_prog_array *array;
2398 	bool found_exclude = false;
2399 
2400 	/* Figure out how many existing progs we need to carry over to
2401 	 * the new array.
2402 	 */
2403 	if (old_array) {
2404 		existing = old_array->items;
2405 		for (; existing->prog; existing++) {
2406 			if (existing->prog == exclude_prog) {
2407 				found_exclude = true;
2408 				continue;
2409 			}
2410 			if (existing->prog != &dummy_bpf_prog.prog)
2411 				carry_prog_cnt++;
2412 			if (existing->prog == include_prog)
2413 				return -EEXIST;
2414 		}
2415 	}
2416 
2417 	if (exclude_prog && !found_exclude)
2418 		return -ENOENT;
2419 
2420 	/* How many progs (not NULL) will be in the new array? */
2421 	new_prog_cnt = carry_prog_cnt;
2422 	if (include_prog)
2423 		new_prog_cnt += 1;
2424 
2425 	/* Do we have any prog (not NULL) in the new array? */
2426 	if (!new_prog_cnt) {
2427 		*new_array = NULL;
2428 		return 0;
2429 	}
2430 
2431 	/* +1 as the end of prog_array is marked with NULL */
2432 	array = bpf_prog_array_alloc(new_prog_cnt + 1, GFP_KERNEL);
2433 	if (!array)
2434 		return -ENOMEM;
2435 	new = array->items;
2436 
2437 	/* Fill in the new prog array */
2438 	if (carry_prog_cnt) {
2439 		existing = old_array->items;
2440 		for (; existing->prog; existing++) {
2441 			if (existing->prog == exclude_prog ||
2442 			    existing->prog == &dummy_bpf_prog.prog)
2443 				continue;
2444 
2445 			new->prog = existing->prog;
2446 			new->bpf_cookie = existing->bpf_cookie;
2447 			new++;
2448 		}
2449 	}
2450 	if (include_prog) {
2451 		new->prog = include_prog;
2452 		new->bpf_cookie = bpf_cookie;
2453 		new++;
2454 	}
2455 	new->prog = NULL;
2456 	*new_array = array;
2457 	return 0;
2458 }
2459 
2460 int bpf_prog_array_copy_info(struct bpf_prog_array *array,
2461 			     u32 *prog_ids, u32 request_cnt,
2462 			     u32 *prog_cnt)
2463 {
2464 	u32 cnt = 0;
2465 
2466 	if (array)
2467 		cnt = bpf_prog_array_length(array);
2468 
2469 	*prog_cnt = cnt;
2470 
2471 	/* return early if user requested only program count or nothing to copy */
2472 	if (!request_cnt || !cnt)
2473 		return 0;
2474 
2475 	/* this function is called under trace/bpf_trace.c: bpf_event_mutex */
2476 	return bpf_prog_array_copy_core(array, prog_ids, request_cnt) ? -ENOSPC
2477 								     : 0;
2478 }
2479 
2480 void __bpf_free_used_maps(struct bpf_prog_aux *aux,
2481 			  struct bpf_map **used_maps, u32 len)
2482 {
2483 	struct bpf_map *map;
2484 	u32 i;
2485 
2486 	for (i = 0; i < len; i++) {
2487 		map = used_maps[i];
2488 		if (map->ops->map_poke_untrack)
2489 			map->ops->map_poke_untrack(map, aux);
2490 		bpf_map_put(map);
2491 	}
2492 }
2493 
2494 static void bpf_free_used_maps(struct bpf_prog_aux *aux)
2495 {
2496 	__bpf_free_used_maps(aux, aux->used_maps, aux->used_map_cnt);
2497 	kfree(aux->used_maps);
2498 }
2499 
2500 void __bpf_free_used_btfs(struct bpf_prog_aux *aux,
2501 			  struct btf_mod_pair *used_btfs, u32 len)
2502 {
2503 #ifdef CONFIG_BPF_SYSCALL
2504 	struct btf_mod_pair *btf_mod;
2505 	u32 i;
2506 
2507 	for (i = 0; i < len; i++) {
2508 		btf_mod = &used_btfs[i];
2509 		if (btf_mod->module)
2510 			module_put(btf_mod->module);
2511 		btf_put(btf_mod->btf);
2512 	}
2513 #endif
2514 }
2515 
2516 static void bpf_free_used_btfs(struct bpf_prog_aux *aux)
2517 {
2518 	__bpf_free_used_btfs(aux, aux->used_btfs, aux->used_btf_cnt);
2519 	kfree(aux->used_btfs);
2520 }
2521 
2522 static void bpf_prog_free_deferred(struct work_struct *work)
2523 {
2524 	struct bpf_prog_aux *aux;
2525 	int i;
2526 
2527 	aux = container_of(work, struct bpf_prog_aux, work);
2528 #ifdef CONFIG_BPF_SYSCALL
2529 	bpf_free_kfunc_btf_tab(aux->kfunc_btf_tab);
2530 #endif
2531 	bpf_free_used_maps(aux);
2532 	bpf_free_used_btfs(aux);
2533 	if (bpf_prog_is_dev_bound(aux))
2534 		bpf_prog_offload_destroy(aux->prog);
2535 #ifdef CONFIG_PERF_EVENTS
2536 	if (aux->prog->has_callchain_buf)
2537 		put_callchain_buffers();
2538 #endif
2539 	if (aux->dst_trampoline)
2540 		bpf_trampoline_put(aux->dst_trampoline);
2541 	for (i = 0; i < aux->func_cnt; i++) {
2542 		/* We can just unlink the subprog poke descriptor table as
2543 		 * it was originally linked to the main program and is also
2544 		 * released along with it.
2545 		 */
2546 		aux->func[i]->aux->poke_tab = NULL;
2547 		bpf_jit_free(aux->func[i]);
2548 	}
2549 	if (aux->func_cnt) {
2550 		kfree(aux->func);
2551 		bpf_prog_unlock_free(aux->prog);
2552 	} else {
2553 		bpf_jit_free(aux->prog);
2554 	}
2555 }
2556 
2557 void bpf_prog_free(struct bpf_prog *fp)
2558 {
2559 	struct bpf_prog_aux *aux = fp->aux;
2560 
2561 	if (aux->dst_prog)
2562 		bpf_prog_put(aux->dst_prog);
2563 	INIT_WORK(&aux->work, bpf_prog_free_deferred);
2564 	schedule_work(&aux->work);
2565 }
2566 EXPORT_SYMBOL_GPL(bpf_prog_free);
2567 
2568 /* RNG for unpriviledged user space with separated state from prandom_u32(). */
2569 static DEFINE_PER_CPU(struct rnd_state, bpf_user_rnd_state);
2570 
2571 void bpf_user_rnd_init_once(void)
2572 {
2573 	prandom_init_once(&bpf_user_rnd_state);
2574 }
2575 
2576 BPF_CALL_0(bpf_user_rnd_u32)
2577 {
2578 	/* Should someone ever have the rather unwise idea to use some
2579 	 * of the registers passed into this function, then note that
2580 	 * this function is called from native eBPF and classic-to-eBPF
2581 	 * transformations. Register assignments from both sides are
2582 	 * different, f.e. classic always sets fn(ctx, A, X) here.
2583 	 */
2584 	struct rnd_state *state;
2585 	u32 res;
2586 
2587 	state = &get_cpu_var(bpf_user_rnd_state);
2588 	res = prandom_u32_state(state);
2589 	put_cpu_var(bpf_user_rnd_state);
2590 
2591 	return res;
2592 }
2593 
2594 BPF_CALL_0(bpf_get_raw_cpu_id)
2595 {
2596 	return raw_smp_processor_id();
2597 }
2598 
2599 /* Weak definitions of helper functions in case we don't have bpf syscall. */
2600 const struct bpf_func_proto bpf_map_lookup_elem_proto __weak;
2601 const struct bpf_func_proto bpf_map_update_elem_proto __weak;
2602 const struct bpf_func_proto bpf_map_delete_elem_proto __weak;
2603 const struct bpf_func_proto bpf_map_push_elem_proto __weak;
2604 const struct bpf_func_proto bpf_map_pop_elem_proto __weak;
2605 const struct bpf_func_proto bpf_map_peek_elem_proto __weak;
2606 const struct bpf_func_proto bpf_spin_lock_proto __weak;
2607 const struct bpf_func_proto bpf_spin_unlock_proto __weak;
2608 const struct bpf_func_proto bpf_jiffies64_proto __weak;
2609 
2610 const struct bpf_func_proto bpf_get_prandom_u32_proto __weak;
2611 const struct bpf_func_proto bpf_get_smp_processor_id_proto __weak;
2612 const struct bpf_func_proto bpf_get_numa_node_id_proto __weak;
2613 const struct bpf_func_proto bpf_ktime_get_ns_proto __weak;
2614 const struct bpf_func_proto bpf_ktime_get_boot_ns_proto __weak;
2615 const struct bpf_func_proto bpf_ktime_get_coarse_ns_proto __weak;
2616 
2617 const struct bpf_func_proto bpf_get_current_pid_tgid_proto __weak;
2618 const struct bpf_func_proto bpf_get_current_uid_gid_proto __weak;
2619 const struct bpf_func_proto bpf_get_current_comm_proto __weak;
2620 const struct bpf_func_proto bpf_get_current_cgroup_id_proto __weak;
2621 const struct bpf_func_proto bpf_get_current_ancestor_cgroup_id_proto __weak;
2622 const struct bpf_func_proto bpf_get_local_storage_proto __weak;
2623 const struct bpf_func_proto bpf_get_ns_current_pid_tgid_proto __weak;
2624 const struct bpf_func_proto bpf_snprintf_btf_proto __weak;
2625 const struct bpf_func_proto bpf_seq_printf_btf_proto __weak;
2626 
2627 const struct bpf_func_proto * __weak bpf_get_trace_printk_proto(void)
2628 {
2629 	return NULL;
2630 }
2631 
2632 const struct bpf_func_proto * __weak bpf_get_trace_vprintk_proto(void)
2633 {
2634 	return NULL;
2635 }
2636 
2637 u64 __weak
2638 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
2639 		 void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
2640 {
2641 	return -ENOTSUPP;
2642 }
2643 EXPORT_SYMBOL_GPL(bpf_event_output);
2644 
2645 /* Always built-in helper functions. */
2646 const struct bpf_func_proto bpf_tail_call_proto = {
2647 	.func		= NULL,
2648 	.gpl_only	= false,
2649 	.ret_type	= RET_VOID,
2650 	.arg1_type	= ARG_PTR_TO_CTX,
2651 	.arg2_type	= ARG_CONST_MAP_PTR,
2652 	.arg3_type	= ARG_ANYTHING,
2653 };
2654 
2655 /* Stub for JITs that only support cBPF. eBPF programs are interpreted.
2656  * It is encouraged to implement bpf_int_jit_compile() instead, so that
2657  * eBPF and implicitly also cBPF can get JITed!
2658  */
2659 struct bpf_prog * __weak bpf_int_jit_compile(struct bpf_prog *prog)
2660 {
2661 	return prog;
2662 }
2663 
2664 /* Stub for JITs that support eBPF. All cBPF code gets transformed into
2665  * eBPF by the kernel and is later compiled by bpf_int_jit_compile().
2666  */
2667 void __weak bpf_jit_compile(struct bpf_prog *prog)
2668 {
2669 }
2670 
2671 bool __weak bpf_helper_changes_pkt_data(void *func)
2672 {
2673 	return false;
2674 }
2675 
2676 /* Return TRUE if the JIT backend wants verifier to enable sub-register usage
2677  * analysis code and wants explicit zero extension inserted by verifier.
2678  * Otherwise, return FALSE.
2679  *
2680  * The verifier inserts an explicit zero extension after BPF_CMPXCHGs even if
2681  * you don't override this. JITs that don't want these extra insns can detect
2682  * them using insn_is_zext.
2683  */
2684 bool __weak bpf_jit_needs_zext(void)
2685 {
2686 	return false;
2687 }
2688 
2689 bool __weak bpf_jit_supports_kfunc_call(void)
2690 {
2691 	return false;
2692 }
2693 
2694 /* To execute LD_ABS/LD_IND instructions __bpf_prog_run() may call
2695  * skb_copy_bits(), so provide a weak definition of it for NET-less config.
2696  */
2697 int __weak skb_copy_bits(const struct sk_buff *skb, int offset, void *to,
2698 			 int len)
2699 {
2700 	return -EFAULT;
2701 }
2702 
2703 int __weak bpf_arch_text_poke(void *ip, enum bpf_text_poke_type t,
2704 			      void *addr1, void *addr2)
2705 {
2706 	return -ENOTSUPP;
2707 }
2708 
2709 void * __weak bpf_arch_text_copy(void *dst, void *src, size_t len)
2710 {
2711 	return ERR_PTR(-ENOTSUPP);
2712 }
2713 
2714 DEFINE_STATIC_KEY_FALSE(bpf_stats_enabled_key);
2715 EXPORT_SYMBOL(bpf_stats_enabled_key);
2716 
2717 /* All definitions of tracepoints related to BPF. */
2718 #define CREATE_TRACE_POINTS
2719 #include <linux/bpf_trace.h>
2720 
2721 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_exception);
2722 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_bulk_tx);
2723