xref: /linux/kernel/bpf/core.c (revision b04df400c30235fa347313c9e2a0695549bd2c8e)
1 /*
2  * Linux Socket Filter - Kernel level socket filtering
3  *
4  * Based on the design of the Berkeley Packet Filter. The new
5  * internal format has been designed by PLUMgrid:
6  *
7  *	Copyright (c) 2011 - 2014 PLUMgrid, http://plumgrid.com
8  *
9  * Authors:
10  *
11  *	Jay Schulist <jschlst@samba.org>
12  *	Alexei Starovoitov <ast@plumgrid.com>
13  *	Daniel Borkmann <dborkman@redhat.com>
14  *
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License
17  * as published by the Free Software Foundation; either version
18  * 2 of the License, or (at your option) any later version.
19  *
20  * Andi Kleen - Fix a few bad bugs and races.
21  * Kris Katterjohn - Added many additional checks in bpf_check_classic()
22  */
23 
24 #include <linux/filter.h>
25 #include <linux/skbuff.h>
26 #include <linux/vmalloc.h>
27 #include <linux/random.h>
28 #include <linux/moduleloader.h>
29 #include <linux/bpf.h>
30 #include <linux/frame.h>
31 #include <linux/rbtree_latch.h>
32 #include <linux/kallsyms.h>
33 #include <linux/rcupdate.h>
34 #include <linux/perf_event.h>
35 
36 #include <asm/unaligned.h>
37 
38 /* Registers */
39 #define BPF_R0	regs[BPF_REG_0]
40 #define BPF_R1	regs[BPF_REG_1]
41 #define BPF_R2	regs[BPF_REG_2]
42 #define BPF_R3	regs[BPF_REG_3]
43 #define BPF_R4	regs[BPF_REG_4]
44 #define BPF_R5	regs[BPF_REG_5]
45 #define BPF_R6	regs[BPF_REG_6]
46 #define BPF_R7	regs[BPF_REG_7]
47 #define BPF_R8	regs[BPF_REG_8]
48 #define BPF_R9	regs[BPF_REG_9]
49 #define BPF_R10	regs[BPF_REG_10]
50 
51 /* Named registers */
52 #define DST	regs[insn->dst_reg]
53 #define SRC	regs[insn->src_reg]
54 #define FP	regs[BPF_REG_FP]
55 #define ARG1	regs[BPF_REG_ARG1]
56 #define CTX	regs[BPF_REG_CTX]
57 #define IMM	insn->imm
58 
59 /* No hurry in this branch
60  *
61  * Exported for the bpf jit load helper.
62  */
63 void *bpf_internal_load_pointer_neg_helper(const struct sk_buff *skb, int k, unsigned int size)
64 {
65 	u8 *ptr = NULL;
66 
67 	if (k >= SKF_NET_OFF)
68 		ptr = skb_network_header(skb) + k - SKF_NET_OFF;
69 	else if (k >= SKF_LL_OFF)
70 		ptr = skb_mac_header(skb) + k - SKF_LL_OFF;
71 
72 	if (ptr >= skb->head && ptr + size <= skb_tail_pointer(skb))
73 		return ptr;
74 
75 	return NULL;
76 }
77 
78 struct bpf_prog *bpf_prog_alloc(unsigned int size, gfp_t gfp_extra_flags)
79 {
80 	gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
81 	struct bpf_prog_aux *aux;
82 	struct bpf_prog *fp;
83 
84 	size = round_up(size, PAGE_SIZE);
85 	fp = __vmalloc(size, gfp_flags, PAGE_KERNEL);
86 	if (fp == NULL)
87 		return NULL;
88 
89 	aux = kzalloc(sizeof(*aux), GFP_KERNEL | gfp_extra_flags);
90 	if (aux == NULL) {
91 		vfree(fp);
92 		return NULL;
93 	}
94 
95 	fp->pages = size / PAGE_SIZE;
96 	fp->aux = aux;
97 	fp->aux->prog = fp;
98 	fp->jit_requested = ebpf_jit_enabled();
99 
100 	INIT_LIST_HEAD_RCU(&fp->aux->ksym_lnode);
101 
102 	return fp;
103 }
104 EXPORT_SYMBOL_GPL(bpf_prog_alloc);
105 
106 struct bpf_prog *bpf_prog_realloc(struct bpf_prog *fp_old, unsigned int size,
107 				  gfp_t gfp_extra_flags)
108 {
109 	gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
110 	struct bpf_prog *fp;
111 	u32 pages, delta;
112 	int ret;
113 
114 	BUG_ON(fp_old == NULL);
115 
116 	size = round_up(size, PAGE_SIZE);
117 	pages = size / PAGE_SIZE;
118 	if (pages <= fp_old->pages)
119 		return fp_old;
120 
121 	delta = pages - fp_old->pages;
122 	ret = __bpf_prog_charge(fp_old->aux->user, delta);
123 	if (ret)
124 		return NULL;
125 
126 	fp = __vmalloc(size, gfp_flags, PAGE_KERNEL);
127 	if (fp == NULL) {
128 		__bpf_prog_uncharge(fp_old->aux->user, delta);
129 	} else {
130 		memcpy(fp, fp_old, fp_old->pages * PAGE_SIZE);
131 		fp->pages = pages;
132 		fp->aux->prog = fp;
133 
134 		/* We keep fp->aux from fp_old around in the new
135 		 * reallocated structure.
136 		 */
137 		fp_old->aux = NULL;
138 		__bpf_prog_free(fp_old);
139 	}
140 
141 	return fp;
142 }
143 
144 void __bpf_prog_free(struct bpf_prog *fp)
145 {
146 	kfree(fp->aux);
147 	vfree(fp);
148 }
149 
150 int bpf_prog_calc_tag(struct bpf_prog *fp)
151 {
152 	const u32 bits_offset = SHA_MESSAGE_BYTES - sizeof(__be64);
153 	u32 raw_size = bpf_prog_tag_scratch_size(fp);
154 	u32 digest[SHA_DIGEST_WORDS];
155 	u32 ws[SHA_WORKSPACE_WORDS];
156 	u32 i, bsize, psize, blocks;
157 	struct bpf_insn *dst;
158 	bool was_ld_map;
159 	u8 *raw, *todo;
160 	__be32 *result;
161 	__be64 *bits;
162 
163 	raw = vmalloc(raw_size);
164 	if (!raw)
165 		return -ENOMEM;
166 
167 	sha_init(digest);
168 	memset(ws, 0, sizeof(ws));
169 
170 	/* We need to take out the map fd for the digest calculation
171 	 * since they are unstable from user space side.
172 	 */
173 	dst = (void *)raw;
174 	for (i = 0, was_ld_map = false; i < fp->len; i++) {
175 		dst[i] = fp->insnsi[i];
176 		if (!was_ld_map &&
177 		    dst[i].code == (BPF_LD | BPF_IMM | BPF_DW) &&
178 		    dst[i].src_reg == BPF_PSEUDO_MAP_FD) {
179 			was_ld_map = true;
180 			dst[i].imm = 0;
181 		} else if (was_ld_map &&
182 			   dst[i].code == 0 &&
183 			   dst[i].dst_reg == 0 &&
184 			   dst[i].src_reg == 0 &&
185 			   dst[i].off == 0) {
186 			was_ld_map = false;
187 			dst[i].imm = 0;
188 		} else {
189 			was_ld_map = false;
190 		}
191 	}
192 
193 	psize = bpf_prog_insn_size(fp);
194 	memset(&raw[psize], 0, raw_size - psize);
195 	raw[psize++] = 0x80;
196 
197 	bsize  = round_up(psize, SHA_MESSAGE_BYTES);
198 	blocks = bsize / SHA_MESSAGE_BYTES;
199 	todo   = raw;
200 	if (bsize - psize >= sizeof(__be64)) {
201 		bits = (__be64 *)(todo + bsize - sizeof(__be64));
202 	} else {
203 		bits = (__be64 *)(todo + bsize + bits_offset);
204 		blocks++;
205 	}
206 	*bits = cpu_to_be64((psize - 1) << 3);
207 
208 	while (blocks--) {
209 		sha_transform(digest, todo, ws);
210 		todo += SHA_MESSAGE_BYTES;
211 	}
212 
213 	result = (__force __be32 *)digest;
214 	for (i = 0; i < SHA_DIGEST_WORDS; i++)
215 		result[i] = cpu_to_be32(digest[i]);
216 	memcpy(fp->tag, result, sizeof(fp->tag));
217 
218 	vfree(raw);
219 	return 0;
220 }
221 
222 static void bpf_adj_branches(struct bpf_prog *prog, u32 pos, u32 delta)
223 {
224 	struct bpf_insn *insn = prog->insnsi;
225 	u32 i, insn_cnt = prog->len;
226 	bool pseudo_call;
227 	u8 code;
228 	int off;
229 
230 	for (i = 0; i < insn_cnt; i++, insn++) {
231 		code = insn->code;
232 		if (BPF_CLASS(code) != BPF_JMP)
233 			continue;
234 		if (BPF_OP(code) == BPF_EXIT)
235 			continue;
236 		if (BPF_OP(code) == BPF_CALL) {
237 			if (insn->src_reg == BPF_PSEUDO_CALL)
238 				pseudo_call = true;
239 			else
240 				continue;
241 		} else {
242 			pseudo_call = false;
243 		}
244 		off = pseudo_call ? insn->imm : insn->off;
245 
246 		/* Adjust offset of jmps if we cross boundaries. */
247 		if (i < pos && i + off + 1 > pos)
248 			off += delta;
249 		else if (i > pos + delta && i + off + 1 <= pos + delta)
250 			off -= delta;
251 
252 		if (pseudo_call)
253 			insn->imm = off;
254 		else
255 			insn->off = off;
256 	}
257 }
258 
259 struct bpf_prog *bpf_patch_insn_single(struct bpf_prog *prog, u32 off,
260 				       const struct bpf_insn *patch, u32 len)
261 {
262 	u32 insn_adj_cnt, insn_rest, insn_delta = len - 1;
263 	struct bpf_prog *prog_adj;
264 
265 	/* Since our patchlet doesn't expand the image, we're done. */
266 	if (insn_delta == 0) {
267 		memcpy(prog->insnsi + off, patch, sizeof(*patch));
268 		return prog;
269 	}
270 
271 	insn_adj_cnt = prog->len + insn_delta;
272 
273 	/* Several new instructions need to be inserted. Make room
274 	 * for them. Likely, there's no need for a new allocation as
275 	 * last page could have large enough tailroom.
276 	 */
277 	prog_adj = bpf_prog_realloc(prog, bpf_prog_size(insn_adj_cnt),
278 				    GFP_USER);
279 	if (!prog_adj)
280 		return NULL;
281 
282 	prog_adj->len = insn_adj_cnt;
283 
284 	/* Patching happens in 3 steps:
285 	 *
286 	 * 1) Move over tail of insnsi from next instruction onwards,
287 	 *    so we can patch the single target insn with one or more
288 	 *    new ones (patching is always from 1 to n insns, n > 0).
289 	 * 2) Inject new instructions at the target location.
290 	 * 3) Adjust branch offsets if necessary.
291 	 */
292 	insn_rest = insn_adj_cnt - off - len;
293 
294 	memmove(prog_adj->insnsi + off + len, prog_adj->insnsi + off + 1,
295 		sizeof(*patch) * insn_rest);
296 	memcpy(prog_adj->insnsi + off, patch, sizeof(*patch) * len);
297 
298 	bpf_adj_branches(prog_adj, off, insn_delta);
299 
300 	return prog_adj;
301 }
302 
303 #ifdef CONFIG_BPF_JIT
304 /* All BPF JIT sysctl knobs here. */
305 int bpf_jit_enable   __read_mostly = IS_BUILTIN(CONFIG_BPF_JIT_ALWAYS_ON);
306 int bpf_jit_harden   __read_mostly;
307 int bpf_jit_kallsyms __read_mostly;
308 
309 static __always_inline void
310 bpf_get_prog_addr_region(const struct bpf_prog *prog,
311 			 unsigned long *symbol_start,
312 			 unsigned long *symbol_end)
313 {
314 	const struct bpf_binary_header *hdr = bpf_jit_binary_hdr(prog);
315 	unsigned long addr = (unsigned long)hdr;
316 
317 	WARN_ON_ONCE(!bpf_prog_ebpf_jited(prog));
318 
319 	*symbol_start = addr;
320 	*symbol_end   = addr + hdr->pages * PAGE_SIZE;
321 }
322 
323 static void bpf_get_prog_name(const struct bpf_prog *prog, char *sym)
324 {
325 	const char *end = sym + KSYM_NAME_LEN;
326 
327 	BUILD_BUG_ON(sizeof("bpf_prog_") +
328 		     sizeof(prog->tag) * 2 +
329 		     /* name has been null terminated.
330 		      * We should need +1 for the '_' preceding
331 		      * the name.  However, the null character
332 		      * is double counted between the name and the
333 		      * sizeof("bpf_prog_") above, so we omit
334 		      * the +1 here.
335 		      */
336 		     sizeof(prog->aux->name) > KSYM_NAME_LEN);
337 
338 	sym += snprintf(sym, KSYM_NAME_LEN, "bpf_prog_");
339 	sym  = bin2hex(sym, prog->tag, sizeof(prog->tag));
340 	if (prog->aux->name[0])
341 		snprintf(sym, (size_t)(end - sym), "_%s", prog->aux->name);
342 	else
343 		*sym = 0;
344 }
345 
346 static __always_inline unsigned long
347 bpf_get_prog_addr_start(struct latch_tree_node *n)
348 {
349 	unsigned long symbol_start, symbol_end;
350 	const struct bpf_prog_aux *aux;
351 
352 	aux = container_of(n, struct bpf_prog_aux, ksym_tnode);
353 	bpf_get_prog_addr_region(aux->prog, &symbol_start, &symbol_end);
354 
355 	return symbol_start;
356 }
357 
358 static __always_inline bool bpf_tree_less(struct latch_tree_node *a,
359 					  struct latch_tree_node *b)
360 {
361 	return bpf_get_prog_addr_start(a) < bpf_get_prog_addr_start(b);
362 }
363 
364 static __always_inline int bpf_tree_comp(void *key, struct latch_tree_node *n)
365 {
366 	unsigned long val = (unsigned long)key;
367 	unsigned long symbol_start, symbol_end;
368 	const struct bpf_prog_aux *aux;
369 
370 	aux = container_of(n, struct bpf_prog_aux, ksym_tnode);
371 	bpf_get_prog_addr_region(aux->prog, &symbol_start, &symbol_end);
372 
373 	if (val < symbol_start)
374 		return -1;
375 	if (val >= symbol_end)
376 		return  1;
377 
378 	return 0;
379 }
380 
381 static const struct latch_tree_ops bpf_tree_ops = {
382 	.less	= bpf_tree_less,
383 	.comp	= bpf_tree_comp,
384 };
385 
386 static DEFINE_SPINLOCK(bpf_lock);
387 static LIST_HEAD(bpf_kallsyms);
388 static struct latch_tree_root bpf_tree __cacheline_aligned;
389 
390 static void bpf_prog_ksym_node_add(struct bpf_prog_aux *aux)
391 {
392 	WARN_ON_ONCE(!list_empty(&aux->ksym_lnode));
393 	list_add_tail_rcu(&aux->ksym_lnode, &bpf_kallsyms);
394 	latch_tree_insert(&aux->ksym_tnode, &bpf_tree, &bpf_tree_ops);
395 }
396 
397 static void bpf_prog_ksym_node_del(struct bpf_prog_aux *aux)
398 {
399 	if (list_empty(&aux->ksym_lnode))
400 		return;
401 
402 	latch_tree_erase(&aux->ksym_tnode, &bpf_tree, &bpf_tree_ops);
403 	list_del_rcu(&aux->ksym_lnode);
404 }
405 
406 static bool bpf_prog_kallsyms_candidate(const struct bpf_prog *fp)
407 {
408 	return fp->jited && !bpf_prog_was_classic(fp);
409 }
410 
411 static bool bpf_prog_kallsyms_verify_off(const struct bpf_prog *fp)
412 {
413 	return list_empty(&fp->aux->ksym_lnode) ||
414 	       fp->aux->ksym_lnode.prev == LIST_POISON2;
415 }
416 
417 void bpf_prog_kallsyms_add(struct bpf_prog *fp)
418 {
419 	if (!bpf_prog_kallsyms_candidate(fp) ||
420 	    !capable(CAP_SYS_ADMIN))
421 		return;
422 
423 	spin_lock_bh(&bpf_lock);
424 	bpf_prog_ksym_node_add(fp->aux);
425 	spin_unlock_bh(&bpf_lock);
426 }
427 
428 void bpf_prog_kallsyms_del(struct bpf_prog *fp)
429 {
430 	if (!bpf_prog_kallsyms_candidate(fp))
431 		return;
432 
433 	spin_lock_bh(&bpf_lock);
434 	bpf_prog_ksym_node_del(fp->aux);
435 	spin_unlock_bh(&bpf_lock);
436 }
437 
438 static struct bpf_prog *bpf_prog_kallsyms_find(unsigned long addr)
439 {
440 	struct latch_tree_node *n;
441 
442 	if (!bpf_jit_kallsyms_enabled())
443 		return NULL;
444 
445 	n = latch_tree_find((void *)addr, &bpf_tree, &bpf_tree_ops);
446 	return n ?
447 	       container_of(n, struct bpf_prog_aux, ksym_tnode)->prog :
448 	       NULL;
449 }
450 
451 const char *__bpf_address_lookup(unsigned long addr, unsigned long *size,
452 				 unsigned long *off, char *sym)
453 {
454 	unsigned long symbol_start, symbol_end;
455 	struct bpf_prog *prog;
456 	char *ret = NULL;
457 
458 	rcu_read_lock();
459 	prog = bpf_prog_kallsyms_find(addr);
460 	if (prog) {
461 		bpf_get_prog_addr_region(prog, &symbol_start, &symbol_end);
462 		bpf_get_prog_name(prog, sym);
463 
464 		ret = sym;
465 		if (size)
466 			*size = symbol_end - symbol_start;
467 		if (off)
468 			*off  = addr - symbol_start;
469 	}
470 	rcu_read_unlock();
471 
472 	return ret;
473 }
474 
475 bool is_bpf_text_address(unsigned long addr)
476 {
477 	bool ret;
478 
479 	rcu_read_lock();
480 	ret = bpf_prog_kallsyms_find(addr) != NULL;
481 	rcu_read_unlock();
482 
483 	return ret;
484 }
485 
486 int bpf_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
487 		    char *sym)
488 {
489 	unsigned long symbol_start, symbol_end;
490 	struct bpf_prog_aux *aux;
491 	unsigned int it = 0;
492 	int ret = -ERANGE;
493 
494 	if (!bpf_jit_kallsyms_enabled())
495 		return ret;
496 
497 	rcu_read_lock();
498 	list_for_each_entry_rcu(aux, &bpf_kallsyms, ksym_lnode) {
499 		if (it++ != symnum)
500 			continue;
501 
502 		bpf_get_prog_addr_region(aux->prog, &symbol_start, &symbol_end);
503 		bpf_get_prog_name(aux->prog, sym);
504 
505 		*value = symbol_start;
506 		*type  = BPF_SYM_ELF_TYPE;
507 
508 		ret = 0;
509 		break;
510 	}
511 	rcu_read_unlock();
512 
513 	return ret;
514 }
515 
516 struct bpf_binary_header *
517 bpf_jit_binary_alloc(unsigned int proglen, u8 **image_ptr,
518 		     unsigned int alignment,
519 		     bpf_jit_fill_hole_t bpf_fill_ill_insns)
520 {
521 	struct bpf_binary_header *hdr;
522 	unsigned int size, hole, start;
523 
524 	/* Most of BPF filters are really small, but if some of them
525 	 * fill a page, allow at least 128 extra bytes to insert a
526 	 * random section of illegal instructions.
527 	 */
528 	size = round_up(proglen + sizeof(*hdr) + 128, PAGE_SIZE);
529 	hdr = module_alloc(size);
530 	if (hdr == NULL)
531 		return NULL;
532 
533 	/* Fill space with illegal/arch-dep instructions. */
534 	bpf_fill_ill_insns(hdr, size);
535 
536 	hdr->pages = size / PAGE_SIZE;
537 	hole = min_t(unsigned int, size - (proglen + sizeof(*hdr)),
538 		     PAGE_SIZE - sizeof(*hdr));
539 	start = (get_random_int() % hole) & ~(alignment - 1);
540 
541 	/* Leave a random number of instructions before BPF code. */
542 	*image_ptr = &hdr->image[start];
543 
544 	return hdr;
545 }
546 
547 void bpf_jit_binary_free(struct bpf_binary_header *hdr)
548 {
549 	module_memfree(hdr);
550 }
551 
552 /* This symbol is only overridden by archs that have different
553  * requirements than the usual eBPF JITs, f.e. when they only
554  * implement cBPF JIT, do not set images read-only, etc.
555  */
556 void __weak bpf_jit_free(struct bpf_prog *fp)
557 {
558 	if (fp->jited) {
559 		struct bpf_binary_header *hdr = bpf_jit_binary_hdr(fp);
560 
561 		bpf_jit_binary_unlock_ro(hdr);
562 		bpf_jit_binary_free(hdr);
563 
564 		WARN_ON_ONCE(!bpf_prog_kallsyms_verify_off(fp));
565 	}
566 
567 	bpf_prog_unlock_free(fp);
568 }
569 
570 static int bpf_jit_blind_insn(const struct bpf_insn *from,
571 			      const struct bpf_insn *aux,
572 			      struct bpf_insn *to_buff)
573 {
574 	struct bpf_insn *to = to_buff;
575 	u32 imm_rnd = get_random_int();
576 	s16 off;
577 
578 	BUILD_BUG_ON(BPF_REG_AX  + 1 != MAX_BPF_JIT_REG);
579 	BUILD_BUG_ON(MAX_BPF_REG + 1 != MAX_BPF_JIT_REG);
580 
581 	if (from->imm == 0 &&
582 	    (from->code == (BPF_ALU   | BPF_MOV | BPF_K) ||
583 	     from->code == (BPF_ALU64 | BPF_MOV | BPF_K))) {
584 		*to++ = BPF_ALU64_REG(BPF_XOR, from->dst_reg, from->dst_reg);
585 		goto out;
586 	}
587 
588 	switch (from->code) {
589 	case BPF_ALU | BPF_ADD | BPF_K:
590 	case BPF_ALU | BPF_SUB | BPF_K:
591 	case BPF_ALU | BPF_AND | BPF_K:
592 	case BPF_ALU | BPF_OR  | BPF_K:
593 	case BPF_ALU | BPF_XOR | BPF_K:
594 	case BPF_ALU | BPF_MUL | BPF_K:
595 	case BPF_ALU | BPF_MOV | BPF_K:
596 	case BPF_ALU | BPF_DIV | BPF_K:
597 	case BPF_ALU | BPF_MOD | BPF_K:
598 		*to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
599 		*to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
600 		*to++ = BPF_ALU32_REG(from->code, from->dst_reg, BPF_REG_AX);
601 		break;
602 
603 	case BPF_ALU64 | BPF_ADD | BPF_K:
604 	case BPF_ALU64 | BPF_SUB | BPF_K:
605 	case BPF_ALU64 | BPF_AND | BPF_K:
606 	case BPF_ALU64 | BPF_OR  | BPF_K:
607 	case BPF_ALU64 | BPF_XOR | BPF_K:
608 	case BPF_ALU64 | BPF_MUL | BPF_K:
609 	case BPF_ALU64 | BPF_MOV | BPF_K:
610 	case BPF_ALU64 | BPF_DIV | BPF_K:
611 	case BPF_ALU64 | BPF_MOD | BPF_K:
612 		*to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
613 		*to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
614 		*to++ = BPF_ALU64_REG(from->code, from->dst_reg, BPF_REG_AX);
615 		break;
616 
617 	case BPF_JMP | BPF_JEQ  | BPF_K:
618 	case BPF_JMP | BPF_JNE  | BPF_K:
619 	case BPF_JMP | BPF_JGT  | BPF_K:
620 	case BPF_JMP | BPF_JLT  | BPF_K:
621 	case BPF_JMP | BPF_JGE  | BPF_K:
622 	case BPF_JMP | BPF_JLE  | BPF_K:
623 	case BPF_JMP | BPF_JSGT | BPF_K:
624 	case BPF_JMP | BPF_JSLT | BPF_K:
625 	case BPF_JMP | BPF_JSGE | BPF_K:
626 	case BPF_JMP | BPF_JSLE | BPF_K:
627 	case BPF_JMP | BPF_JSET | BPF_K:
628 		/* Accommodate for extra offset in case of a backjump. */
629 		off = from->off;
630 		if (off < 0)
631 			off -= 2;
632 		*to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
633 		*to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
634 		*to++ = BPF_JMP_REG(from->code, from->dst_reg, BPF_REG_AX, off);
635 		break;
636 
637 	case BPF_LD | BPF_IMM | BPF_DW:
638 		*to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[1].imm);
639 		*to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
640 		*to++ = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
641 		*to++ = BPF_ALU64_REG(BPF_MOV, aux[0].dst_reg, BPF_REG_AX);
642 		break;
643 	case 0: /* Part 2 of BPF_LD | BPF_IMM | BPF_DW. */
644 		*to++ = BPF_ALU32_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ aux[0].imm);
645 		*to++ = BPF_ALU32_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
646 		*to++ = BPF_ALU64_REG(BPF_OR,  aux[0].dst_reg, BPF_REG_AX);
647 		break;
648 
649 	case BPF_ST | BPF_MEM | BPF_DW:
650 	case BPF_ST | BPF_MEM | BPF_W:
651 	case BPF_ST | BPF_MEM | BPF_H:
652 	case BPF_ST | BPF_MEM | BPF_B:
653 		*to++ = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, imm_rnd ^ from->imm);
654 		*to++ = BPF_ALU64_IMM(BPF_XOR, BPF_REG_AX, imm_rnd);
655 		*to++ = BPF_STX_MEM(from->code, from->dst_reg, BPF_REG_AX, from->off);
656 		break;
657 	}
658 out:
659 	return to - to_buff;
660 }
661 
662 static struct bpf_prog *bpf_prog_clone_create(struct bpf_prog *fp_other,
663 					      gfp_t gfp_extra_flags)
664 {
665 	gfp_t gfp_flags = GFP_KERNEL | __GFP_ZERO | gfp_extra_flags;
666 	struct bpf_prog *fp;
667 
668 	fp = __vmalloc(fp_other->pages * PAGE_SIZE, gfp_flags, PAGE_KERNEL);
669 	if (fp != NULL) {
670 		/* aux->prog still points to the fp_other one, so
671 		 * when promoting the clone to the real program,
672 		 * this still needs to be adapted.
673 		 */
674 		memcpy(fp, fp_other, fp_other->pages * PAGE_SIZE);
675 	}
676 
677 	return fp;
678 }
679 
680 static void bpf_prog_clone_free(struct bpf_prog *fp)
681 {
682 	/* aux was stolen by the other clone, so we cannot free
683 	 * it from this path! It will be freed eventually by the
684 	 * other program on release.
685 	 *
686 	 * At this point, we don't need a deferred release since
687 	 * clone is guaranteed to not be locked.
688 	 */
689 	fp->aux = NULL;
690 	__bpf_prog_free(fp);
691 }
692 
693 void bpf_jit_prog_release_other(struct bpf_prog *fp, struct bpf_prog *fp_other)
694 {
695 	/* We have to repoint aux->prog to self, as we don't
696 	 * know whether fp here is the clone or the original.
697 	 */
698 	fp->aux->prog = fp;
699 	bpf_prog_clone_free(fp_other);
700 }
701 
702 struct bpf_prog *bpf_jit_blind_constants(struct bpf_prog *prog)
703 {
704 	struct bpf_insn insn_buff[16], aux[2];
705 	struct bpf_prog *clone, *tmp;
706 	int insn_delta, insn_cnt;
707 	struct bpf_insn *insn;
708 	int i, rewritten;
709 
710 	if (!bpf_jit_blinding_enabled(prog) || prog->blinded)
711 		return prog;
712 
713 	clone = bpf_prog_clone_create(prog, GFP_USER);
714 	if (!clone)
715 		return ERR_PTR(-ENOMEM);
716 
717 	insn_cnt = clone->len;
718 	insn = clone->insnsi;
719 
720 	for (i = 0; i < insn_cnt; i++, insn++) {
721 		/* We temporarily need to hold the original ld64 insn
722 		 * so that we can still access the first part in the
723 		 * second blinding run.
724 		 */
725 		if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW) &&
726 		    insn[1].code == 0)
727 			memcpy(aux, insn, sizeof(aux));
728 
729 		rewritten = bpf_jit_blind_insn(insn, aux, insn_buff);
730 		if (!rewritten)
731 			continue;
732 
733 		tmp = bpf_patch_insn_single(clone, i, insn_buff, rewritten);
734 		if (!tmp) {
735 			/* Patching may have repointed aux->prog during
736 			 * realloc from the original one, so we need to
737 			 * fix it up here on error.
738 			 */
739 			bpf_jit_prog_release_other(prog, clone);
740 			return ERR_PTR(-ENOMEM);
741 		}
742 
743 		clone = tmp;
744 		insn_delta = rewritten - 1;
745 
746 		/* Walk new program and skip insns we just inserted. */
747 		insn = clone->insnsi + i + insn_delta;
748 		insn_cnt += insn_delta;
749 		i        += insn_delta;
750 	}
751 
752 	clone->blinded = 1;
753 	return clone;
754 }
755 #endif /* CONFIG_BPF_JIT */
756 
757 /* Base function for offset calculation. Needs to go into .text section,
758  * therefore keeping it non-static as well; will also be used by JITs
759  * anyway later on, so do not let the compiler omit it. This also needs
760  * to go into kallsyms for correlation from e.g. bpftool, so naming
761  * must not change.
762  */
763 noinline u64 __bpf_call_base(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5)
764 {
765 	return 0;
766 }
767 EXPORT_SYMBOL_GPL(__bpf_call_base);
768 
769 /* All UAPI available opcodes. */
770 #define BPF_INSN_MAP(INSN_2, INSN_3)		\
771 	/* 32 bit ALU operations. */		\
772 	/*   Register based. */			\
773 	INSN_3(ALU, ADD, X),			\
774 	INSN_3(ALU, SUB, X),			\
775 	INSN_3(ALU, AND, X),			\
776 	INSN_3(ALU, OR,  X),			\
777 	INSN_3(ALU, LSH, X),			\
778 	INSN_3(ALU, RSH, X),			\
779 	INSN_3(ALU, XOR, X),			\
780 	INSN_3(ALU, MUL, X),			\
781 	INSN_3(ALU, MOV, X),			\
782 	INSN_3(ALU, DIV, X),			\
783 	INSN_3(ALU, MOD, X),			\
784 	INSN_2(ALU, NEG),			\
785 	INSN_3(ALU, END, TO_BE),		\
786 	INSN_3(ALU, END, TO_LE),		\
787 	/*   Immediate based. */		\
788 	INSN_3(ALU, ADD, K),			\
789 	INSN_3(ALU, SUB, K),			\
790 	INSN_3(ALU, AND, K),			\
791 	INSN_3(ALU, OR,  K),			\
792 	INSN_3(ALU, LSH, K),			\
793 	INSN_3(ALU, RSH, K),			\
794 	INSN_3(ALU, XOR, K),			\
795 	INSN_3(ALU, MUL, K),			\
796 	INSN_3(ALU, MOV, K),			\
797 	INSN_3(ALU, DIV, K),			\
798 	INSN_3(ALU, MOD, K),			\
799 	/* 64 bit ALU operations. */		\
800 	/*   Register based. */			\
801 	INSN_3(ALU64, ADD,  X),			\
802 	INSN_3(ALU64, SUB,  X),			\
803 	INSN_3(ALU64, AND,  X),			\
804 	INSN_3(ALU64, OR,   X),			\
805 	INSN_3(ALU64, LSH,  X),			\
806 	INSN_3(ALU64, RSH,  X),			\
807 	INSN_3(ALU64, XOR,  X),			\
808 	INSN_3(ALU64, MUL,  X),			\
809 	INSN_3(ALU64, MOV,  X),			\
810 	INSN_3(ALU64, ARSH, X),			\
811 	INSN_3(ALU64, DIV,  X),			\
812 	INSN_3(ALU64, MOD,  X),			\
813 	INSN_2(ALU64, NEG),			\
814 	/*   Immediate based. */		\
815 	INSN_3(ALU64, ADD,  K),			\
816 	INSN_3(ALU64, SUB,  K),			\
817 	INSN_3(ALU64, AND,  K),			\
818 	INSN_3(ALU64, OR,   K),			\
819 	INSN_3(ALU64, LSH,  K),			\
820 	INSN_3(ALU64, RSH,  K),			\
821 	INSN_3(ALU64, XOR,  K),			\
822 	INSN_3(ALU64, MUL,  K),			\
823 	INSN_3(ALU64, MOV,  K),			\
824 	INSN_3(ALU64, ARSH, K),			\
825 	INSN_3(ALU64, DIV,  K),			\
826 	INSN_3(ALU64, MOD,  K),			\
827 	/* Call instruction. */			\
828 	INSN_2(JMP, CALL),			\
829 	/* Exit instruction. */			\
830 	INSN_2(JMP, EXIT),			\
831 	/* Jump instructions. */		\
832 	/*   Register based. */			\
833 	INSN_3(JMP, JEQ,  X),			\
834 	INSN_3(JMP, JNE,  X),			\
835 	INSN_3(JMP, JGT,  X),			\
836 	INSN_3(JMP, JLT,  X),			\
837 	INSN_3(JMP, JGE,  X),			\
838 	INSN_3(JMP, JLE,  X),			\
839 	INSN_3(JMP, JSGT, X),			\
840 	INSN_3(JMP, JSLT, X),			\
841 	INSN_3(JMP, JSGE, X),			\
842 	INSN_3(JMP, JSLE, X),			\
843 	INSN_3(JMP, JSET, X),			\
844 	/*   Immediate based. */		\
845 	INSN_3(JMP, JEQ,  K),			\
846 	INSN_3(JMP, JNE,  K),			\
847 	INSN_3(JMP, JGT,  K),			\
848 	INSN_3(JMP, JLT,  K),			\
849 	INSN_3(JMP, JGE,  K),			\
850 	INSN_3(JMP, JLE,  K),			\
851 	INSN_3(JMP, JSGT, K),			\
852 	INSN_3(JMP, JSLT, K),			\
853 	INSN_3(JMP, JSGE, K),			\
854 	INSN_3(JMP, JSLE, K),			\
855 	INSN_3(JMP, JSET, K),			\
856 	INSN_2(JMP, JA),			\
857 	/* Store instructions. */		\
858 	/*   Register based. */			\
859 	INSN_3(STX, MEM,  B),			\
860 	INSN_3(STX, MEM,  H),			\
861 	INSN_3(STX, MEM,  W),			\
862 	INSN_3(STX, MEM,  DW),			\
863 	INSN_3(STX, XADD, W),			\
864 	INSN_3(STX, XADD, DW),			\
865 	/*   Immediate based. */		\
866 	INSN_3(ST, MEM, B),			\
867 	INSN_3(ST, MEM, H),			\
868 	INSN_3(ST, MEM, W),			\
869 	INSN_3(ST, MEM, DW),			\
870 	/* Load instructions. */		\
871 	/*   Register based. */			\
872 	INSN_3(LDX, MEM, B),			\
873 	INSN_3(LDX, MEM, H),			\
874 	INSN_3(LDX, MEM, W),			\
875 	INSN_3(LDX, MEM, DW),			\
876 	/*   Immediate based. */		\
877 	INSN_3(LD, IMM, DW)
878 
879 bool bpf_opcode_in_insntable(u8 code)
880 {
881 #define BPF_INSN_2_TBL(x, y)    [BPF_##x | BPF_##y] = true
882 #define BPF_INSN_3_TBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = true
883 	static const bool public_insntable[256] = {
884 		[0 ... 255] = false,
885 		/* Now overwrite non-defaults ... */
886 		BPF_INSN_MAP(BPF_INSN_2_TBL, BPF_INSN_3_TBL),
887 		/* UAPI exposed, but rewritten opcodes. cBPF carry-over. */
888 		[BPF_LD | BPF_ABS | BPF_B] = true,
889 		[BPF_LD | BPF_ABS | BPF_H] = true,
890 		[BPF_LD | BPF_ABS | BPF_W] = true,
891 		[BPF_LD | BPF_IND | BPF_B] = true,
892 		[BPF_LD | BPF_IND | BPF_H] = true,
893 		[BPF_LD | BPF_IND | BPF_W] = true,
894 	};
895 #undef BPF_INSN_3_TBL
896 #undef BPF_INSN_2_TBL
897 	return public_insntable[code];
898 }
899 
900 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
901 /**
902  *	__bpf_prog_run - run eBPF program on a given context
903  *	@ctx: is the data we are operating on
904  *	@insn: is the array of eBPF instructions
905  *
906  * Decode and execute eBPF instructions.
907  */
908 static u64 ___bpf_prog_run(u64 *regs, const struct bpf_insn *insn, u64 *stack)
909 {
910 	u64 tmp;
911 #define BPF_INSN_2_LBL(x, y)    [BPF_##x | BPF_##y] = &&x##_##y
912 #define BPF_INSN_3_LBL(x, y, z) [BPF_##x | BPF_##y | BPF_##z] = &&x##_##y##_##z
913 	static const void *jumptable[256] = {
914 		[0 ... 255] = &&default_label,
915 		/* Now overwrite non-defaults ... */
916 		BPF_INSN_MAP(BPF_INSN_2_LBL, BPF_INSN_3_LBL),
917 		/* Non-UAPI available opcodes. */
918 		[BPF_JMP | BPF_CALL_ARGS] = &&JMP_CALL_ARGS,
919 		[BPF_JMP | BPF_TAIL_CALL] = &&JMP_TAIL_CALL,
920 	};
921 #undef BPF_INSN_3_LBL
922 #undef BPF_INSN_2_LBL
923 	u32 tail_call_cnt = 0;
924 
925 #define CONT	 ({ insn++; goto select_insn; })
926 #define CONT_JMP ({ insn++; goto select_insn; })
927 
928 select_insn:
929 	goto *jumptable[insn->code];
930 
931 	/* ALU */
932 #define ALU(OPCODE, OP)			\
933 	ALU64_##OPCODE##_X:		\
934 		DST = DST OP SRC;	\
935 		CONT;			\
936 	ALU_##OPCODE##_X:		\
937 		DST = (u32) DST OP (u32) SRC;	\
938 		CONT;			\
939 	ALU64_##OPCODE##_K:		\
940 		DST = DST OP IMM;		\
941 		CONT;			\
942 	ALU_##OPCODE##_K:		\
943 		DST = (u32) DST OP (u32) IMM;	\
944 		CONT;
945 
946 	ALU(ADD,  +)
947 	ALU(SUB,  -)
948 	ALU(AND,  &)
949 	ALU(OR,   |)
950 	ALU(LSH, <<)
951 	ALU(RSH, >>)
952 	ALU(XOR,  ^)
953 	ALU(MUL,  *)
954 #undef ALU
955 	ALU_NEG:
956 		DST = (u32) -DST;
957 		CONT;
958 	ALU64_NEG:
959 		DST = -DST;
960 		CONT;
961 	ALU_MOV_X:
962 		DST = (u32) SRC;
963 		CONT;
964 	ALU_MOV_K:
965 		DST = (u32) IMM;
966 		CONT;
967 	ALU64_MOV_X:
968 		DST = SRC;
969 		CONT;
970 	ALU64_MOV_K:
971 		DST = IMM;
972 		CONT;
973 	LD_IMM_DW:
974 		DST = (u64) (u32) insn[0].imm | ((u64) (u32) insn[1].imm) << 32;
975 		insn++;
976 		CONT;
977 	ALU64_ARSH_X:
978 		(*(s64 *) &DST) >>= SRC;
979 		CONT;
980 	ALU64_ARSH_K:
981 		(*(s64 *) &DST) >>= IMM;
982 		CONT;
983 	ALU64_MOD_X:
984 		div64_u64_rem(DST, SRC, &tmp);
985 		DST = tmp;
986 		CONT;
987 	ALU_MOD_X:
988 		tmp = (u32) DST;
989 		DST = do_div(tmp, (u32) SRC);
990 		CONT;
991 	ALU64_MOD_K:
992 		div64_u64_rem(DST, IMM, &tmp);
993 		DST = tmp;
994 		CONT;
995 	ALU_MOD_K:
996 		tmp = (u32) DST;
997 		DST = do_div(tmp, (u32) IMM);
998 		CONT;
999 	ALU64_DIV_X:
1000 		DST = div64_u64(DST, SRC);
1001 		CONT;
1002 	ALU_DIV_X:
1003 		tmp = (u32) DST;
1004 		do_div(tmp, (u32) SRC);
1005 		DST = (u32) tmp;
1006 		CONT;
1007 	ALU64_DIV_K:
1008 		DST = div64_u64(DST, IMM);
1009 		CONT;
1010 	ALU_DIV_K:
1011 		tmp = (u32) DST;
1012 		do_div(tmp, (u32) IMM);
1013 		DST = (u32) tmp;
1014 		CONT;
1015 	ALU_END_TO_BE:
1016 		switch (IMM) {
1017 		case 16:
1018 			DST = (__force u16) cpu_to_be16(DST);
1019 			break;
1020 		case 32:
1021 			DST = (__force u32) cpu_to_be32(DST);
1022 			break;
1023 		case 64:
1024 			DST = (__force u64) cpu_to_be64(DST);
1025 			break;
1026 		}
1027 		CONT;
1028 	ALU_END_TO_LE:
1029 		switch (IMM) {
1030 		case 16:
1031 			DST = (__force u16) cpu_to_le16(DST);
1032 			break;
1033 		case 32:
1034 			DST = (__force u32) cpu_to_le32(DST);
1035 			break;
1036 		case 64:
1037 			DST = (__force u64) cpu_to_le64(DST);
1038 			break;
1039 		}
1040 		CONT;
1041 
1042 	/* CALL */
1043 	JMP_CALL:
1044 		/* Function call scratches BPF_R1-BPF_R5 registers,
1045 		 * preserves BPF_R6-BPF_R9, and stores return value
1046 		 * into BPF_R0.
1047 		 */
1048 		BPF_R0 = (__bpf_call_base + insn->imm)(BPF_R1, BPF_R2, BPF_R3,
1049 						       BPF_R4, BPF_R5);
1050 		CONT;
1051 
1052 	JMP_CALL_ARGS:
1053 		BPF_R0 = (__bpf_call_base_args + insn->imm)(BPF_R1, BPF_R2,
1054 							    BPF_R3, BPF_R4,
1055 							    BPF_R5,
1056 							    insn + insn->off + 1);
1057 		CONT;
1058 
1059 	JMP_TAIL_CALL: {
1060 		struct bpf_map *map = (struct bpf_map *) (unsigned long) BPF_R2;
1061 		struct bpf_array *array = container_of(map, struct bpf_array, map);
1062 		struct bpf_prog *prog;
1063 		u32 index = BPF_R3;
1064 
1065 		if (unlikely(index >= array->map.max_entries))
1066 			goto out;
1067 		if (unlikely(tail_call_cnt > MAX_TAIL_CALL_CNT))
1068 			goto out;
1069 
1070 		tail_call_cnt++;
1071 
1072 		prog = READ_ONCE(array->ptrs[index]);
1073 		if (!prog)
1074 			goto out;
1075 
1076 		/* ARG1 at this point is guaranteed to point to CTX from
1077 		 * the verifier side due to the fact that the tail call is
1078 		 * handeled like a helper, that is, bpf_tail_call_proto,
1079 		 * where arg1_type is ARG_PTR_TO_CTX.
1080 		 */
1081 		insn = prog->insnsi;
1082 		goto select_insn;
1083 out:
1084 		CONT;
1085 	}
1086 	/* JMP */
1087 	JMP_JA:
1088 		insn += insn->off;
1089 		CONT;
1090 	JMP_JEQ_X:
1091 		if (DST == SRC) {
1092 			insn += insn->off;
1093 			CONT_JMP;
1094 		}
1095 		CONT;
1096 	JMP_JEQ_K:
1097 		if (DST == IMM) {
1098 			insn += insn->off;
1099 			CONT_JMP;
1100 		}
1101 		CONT;
1102 	JMP_JNE_X:
1103 		if (DST != SRC) {
1104 			insn += insn->off;
1105 			CONT_JMP;
1106 		}
1107 		CONT;
1108 	JMP_JNE_K:
1109 		if (DST != IMM) {
1110 			insn += insn->off;
1111 			CONT_JMP;
1112 		}
1113 		CONT;
1114 	JMP_JGT_X:
1115 		if (DST > SRC) {
1116 			insn += insn->off;
1117 			CONT_JMP;
1118 		}
1119 		CONT;
1120 	JMP_JGT_K:
1121 		if (DST > IMM) {
1122 			insn += insn->off;
1123 			CONT_JMP;
1124 		}
1125 		CONT;
1126 	JMP_JLT_X:
1127 		if (DST < SRC) {
1128 			insn += insn->off;
1129 			CONT_JMP;
1130 		}
1131 		CONT;
1132 	JMP_JLT_K:
1133 		if (DST < IMM) {
1134 			insn += insn->off;
1135 			CONT_JMP;
1136 		}
1137 		CONT;
1138 	JMP_JGE_X:
1139 		if (DST >= SRC) {
1140 			insn += insn->off;
1141 			CONT_JMP;
1142 		}
1143 		CONT;
1144 	JMP_JGE_K:
1145 		if (DST >= IMM) {
1146 			insn += insn->off;
1147 			CONT_JMP;
1148 		}
1149 		CONT;
1150 	JMP_JLE_X:
1151 		if (DST <= SRC) {
1152 			insn += insn->off;
1153 			CONT_JMP;
1154 		}
1155 		CONT;
1156 	JMP_JLE_K:
1157 		if (DST <= IMM) {
1158 			insn += insn->off;
1159 			CONT_JMP;
1160 		}
1161 		CONT;
1162 	JMP_JSGT_X:
1163 		if (((s64) DST) > ((s64) SRC)) {
1164 			insn += insn->off;
1165 			CONT_JMP;
1166 		}
1167 		CONT;
1168 	JMP_JSGT_K:
1169 		if (((s64) DST) > ((s64) IMM)) {
1170 			insn += insn->off;
1171 			CONT_JMP;
1172 		}
1173 		CONT;
1174 	JMP_JSLT_X:
1175 		if (((s64) DST) < ((s64) SRC)) {
1176 			insn += insn->off;
1177 			CONT_JMP;
1178 		}
1179 		CONT;
1180 	JMP_JSLT_K:
1181 		if (((s64) DST) < ((s64) IMM)) {
1182 			insn += insn->off;
1183 			CONT_JMP;
1184 		}
1185 		CONT;
1186 	JMP_JSGE_X:
1187 		if (((s64) DST) >= ((s64) SRC)) {
1188 			insn += insn->off;
1189 			CONT_JMP;
1190 		}
1191 		CONT;
1192 	JMP_JSGE_K:
1193 		if (((s64) DST) >= ((s64) IMM)) {
1194 			insn += insn->off;
1195 			CONT_JMP;
1196 		}
1197 		CONT;
1198 	JMP_JSLE_X:
1199 		if (((s64) DST) <= ((s64) SRC)) {
1200 			insn += insn->off;
1201 			CONT_JMP;
1202 		}
1203 		CONT;
1204 	JMP_JSLE_K:
1205 		if (((s64) DST) <= ((s64) IMM)) {
1206 			insn += insn->off;
1207 			CONT_JMP;
1208 		}
1209 		CONT;
1210 	JMP_JSET_X:
1211 		if (DST & SRC) {
1212 			insn += insn->off;
1213 			CONT_JMP;
1214 		}
1215 		CONT;
1216 	JMP_JSET_K:
1217 		if (DST & IMM) {
1218 			insn += insn->off;
1219 			CONT_JMP;
1220 		}
1221 		CONT;
1222 	JMP_EXIT:
1223 		return BPF_R0;
1224 
1225 	/* STX and ST and LDX*/
1226 #define LDST(SIZEOP, SIZE)						\
1227 	STX_MEM_##SIZEOP:						\
1228 		*(SIZE *)(unsigned long) (DST + insn->off) = SRC;	\
1229 		CONT;							\
1230 	ST_MEM_##SIZEOP:						\
1231 		*(SIZE *)(unsigned long) (DST + insn->off) = IMM;	\
1232 		CONT;							\
1233 	LDX_MEM_##SIZEOP:						\
1234 		DST = *(SIZE *)(unsigned long) (SRC + insn->off);	\
1235 		CONT;
1236 
1237 	LDST(B,   u8)
1238 	LDST(H,  u16)
1239 	LDST(W,  u32)
1240 	LDST(DW, u64)
1241 #undef LDST
1242 	STX_XADD_W: /* lock xadd *(u32 *)(dst_reg + off16) += src_reg */
1243 		atomic_add((u32) SRC, (atomic_t *)(unsigned long)
1244 			   (DST + insn->off));
1245 		CONT;
1246 	STX_XADD_DW: /* lock xadd *(u64 *)(dst_reg + off16) += src_reg */
1247 		atomic64_add((u64) SRC, (atomic64_t *)(unsigned long)
1248 			     (DST + insn->off));
1249 		CONT;
1250 
1251 	default_label:
1252 		/* If we ever reach this, we have a bug somewhere. Die hard here
1253 		 * instead of just returning 0; we could be somewhere in a subprog,
1254 		 * so execution could continue otherwise which we do /not/ want.
1255 		 *
1256 		 * Note, verifier whitelists all opcodes in bpf_opcode_in_insntable().
1257 		 */
1258 		pr_warn("BPF interpreter: unknown opcode %02x\n", insn->code);
1259 		BUG_ON(1);
1260 		return 0;
1261 }
1262 STACK_FRAME_NON_STANDARD(___bpf_prog_run); /* jump table */
1263 
1264 #define PROG_NAME(stack_size) __bpf_prog_run##stack_size
1265 #define DEFINE_BPF_PROG_RUN(stack_size) \
1266 static unsigned int PROG_NAME(stack_size)(const void *ctx, const struct bpf_insn *insn) \
1267 { \
1268 	u64 stack[stack_size / sizeof(u64)]; \
1269 	u64 regs[MAX_BPF_REG]; \
1270 \
1271 	FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
1272 	ARG1 = (u64) (unsigned long) ctx; \
1273 	return ___bpf_prog_run(regs, insn, stack); \
1274 }
1275 
1276 #define PROG_NAME_ARGS(stack_size) __bpf_prog_run_args##stack_size
1277 #define DEFINE_BPF_PROG_RUN_ARGS(stack_size) \
1278 static u64 PROG_NAME_ARGS(stack_size)(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5, \
1279 				      const struct bpf_insn *insn) \
1280 { \
1281 	u64 stack[stack_size / sizeof(u64)]; \
1282 	u64 regs[MAX_BPF_REG]; \
1283 \
1284 	FP = (u64) (unsigned long) &stack[ARRAY_SIZE(stack)]; \
1285 	BPF_R1 = r1; \
1286 	BPF_R2 = r2; \
1287 	BPF_R3 = r3; \
1288 	BPF_R4 = r4; \
1289 	BPF_R5 = r5; \
1290 	return ___bpf_prog_run(regs, insn, stack); \
1291 }
1292 
1293 #define EVAL1(FN, X) FN(X)
1294 #define EVAL2(FN, X, Y...) FN(X) EVAL1(FN, Y)
1295 #define EVAL3(FN, X, Y...) FN(X) EVAL2(FN, Y)
1296 #define EVAL4(FN, X, Y...) FN(X) EVAL3(FN, Y)
1297 #define EVAL5(FN, X, Y...) FN(X) EVAL4(FN, Y)
1298 #define EVAL6(FN, X, Y...) FN(X) EVAL5(FN, Y)
1299 
1300 EVAL6(DEFINE_BPF_PROG_RUN, 32, 64, 96, 128, 160, 192);
1301 EVAL6(DEFINE_BPF_PROG_RUN, 224, 256, 288, 320, 352, 384);
1302 EVAL4(DEFINE_BPF_PROG_RUN, 416, 448, 480, 512);
1303 
1304 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 32, 64, 96, 128, 160, 192);
1305 EVAL6(DEFINE_BPF_PROG_RUN_ARGS, 224, 256, 288, 320, 352, 384);
1306 EVAL4(DEFINE_BPF_PROG_RUN_ARGS, 416, 448, 480, 512);
1307 
1308 #define PROG_NAME_LIST(stack_size) PROG_NAME(stack_size),
1309 
1310 static unsigned int (*interpreters[])(const void *ctx,
1311 				      const struct bpf_insn *insn) = {
1312 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
1313 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
1314 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
1315 };
1316 #undef PROG_NAME_LIST
1317 #define PROG_NAME_LIST(stack_size) PROG_NAME_ARGS(stack_size),
1318 static u64 (*interpreters_args[])(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5,
1319 				  const struct bpf_insn *insn) = {
1320 EVAL6(PROG_NAME_LIST, 32, 64, 96, 128, 160, 192)
1321 EVAL6(PROG_NAME_LIST, 224, 256, 288, 320, 352, 384)
1322 EVAL4(PROG_NAME_LIST, 416, 448, 480, 512)
1323 };
1324 #undef PROG_NAME_LIST
1325 
1326 void bpf_patch_call_args(struct bpf_insn *insn, u32 stack_depth)
1327 {
1328 	stack_depth = max_t(u32, stack_depth, 1);
1329 	insn->off = (s16) insn->imm;
1330 	insn->imm = interpreters_args[(round_up(stack_depth, 32) / 32) - 1] -
1331 		__bpf_call_base_args;
1332 	insn->code = BPF_JMP | BPF_CALL_ARGS;
1333 }
1334 
1335 #else
1336 static unsigned int __bpf_prog_ret0_warn(const void *ctx,
1337 					 const struct bpf_insn *insn)
1338 {
1339 	/* If this handler ever gets executed, then BPF_JIT_ALWAYS_ON
1340 	 * is not working properly, so warn about it!
1341 	 */
1342 	WARN_ON_ONCE(1);
1343 	return 0;
1344 }
1345 #endif
1346 
1347 bool bpf_prog_array_compatible(struct bpf_array *array,
1348 			       const struct bpf_prog *fp)
1349 {
1350 	if (fp->kprobe_override)
1351 		return false;
1352 
1353 	if (!array->owner_prog_type) {
1354 		/* There's no owner yet where we could check for
1355 		 * compatibility.
1356 		 */
1357 		array->owner_prog_type = fp->type;
1358 		array->owner_jited = fp->jited;
1359 
1360 		return true;
1361 	}
1362 
1363 	return array->owner_prog_type == fp->type &&
1364 	       array->owner_jited == fp->jited;
1365 }
1366 
1367 static int bpf_check_tail_call(const struct bpf_prog *fp)
1368 {
1369 	struct bpf_prog_aux *aux = fp->aux;
1370 	int i;
1371 
1372 	for (i = 0; i < aux->used_map_cnt; i++) {
1373 		struct bpf_map *map = aux->used_maps[i];
1374 		struct bpf_array *array;
1375 
1376 		if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY)
1377 			continue;
1378 
1379 		array = container_of(map, struct bpf_array, map);
1380 		if (!bpf_prog_array_compatible(array, fp))
1381 			return -EINVAL;
1382 	}
1383 
1384 	return 0;
1385 }
1386 
1387 /**
1388  *	bpf_prog_select_runtime - select exec runtime for BPF program
1389  *	@fp: bpf_prog populated with internal BPF program
1390  *	@err: pointer to error variable
1391  *
1392  * Try to JIT eBPF program, if JIT is not available, use interpreter.
1393  * The BPF program will be executed via BPF_PROG_RUN() macro.
1394  */
1395 struct bpf_prog *bpf_prog_select_runtime(struct bpf_prog *fp, int *err)
1396 {
1397 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1398 	u32 stack_depth = max_t(u32, fp->aux->stack_depth, 1);
1399 
1400 	fp->bpf_func = interpreters[(round_up(stack_depth, 32) / 32) - 1];
1401 #else
1402 	fp->bpf_func = __bpf_prog_ret0_warn;
1403 #endif
1404 
1405 	/* eBPF JITs can rewrite the program in case constant
1406 	 * blinding is active. However, in case of error during
1407 	 * blinding, bpf_int_jit_compile() must always return a
1408 	 * valid program, which in this case would simply not
1409 	 * be JITed, but falls back to the interpreter.
1410 	 */
1411 	if (!bpf_prog_is_dev_bound(fp->aux)) {
1412 		fp = bpf_int_jit_compile(fp);
1413 #ifdef CONFIG_BPF_JIT_ALWAYS_ON
1414 		if (!fp->jited) {
1415 			*err = -ENOTSUPP;
1416 			return fp;
1417 		}
1418 #endif
1419 	} else {
1420 		*err = bpf_prog_offload_compile(fp);
1421 		if (*err)
1422 			return fp;
1423 	}
1424 	bpf_prog_lock_ro(fp);
1425 
1426 	/* The tail call compatibility check can only be done at
1427 	 * this late stage as we need to determine, if we deal
1428 	 * with JITed or non JITed program concatenations and not
1429 	 * all eBPF JITs might immediately support all features.
1430 	 */
1431 	*err = bpf_check_tail_call(fp);
1432 
1433 	return fp;
1434 }
1435 EXPORT_SYMBOL_GPL(bpf_prog_select_runtime);
1436 
1437 static unsigned int __bpf_prog_ret1(const void *ctx,
1438 				    const struct bpf_insn *insn)
1439 {
1440 	return 1;
1441 }
1442 
1443 static struct bpf_prog_dummy {
1444 	struct bpf_prog prog;
1445 } dummy_bpf_prog = {
1446 	.prog = {
1447 		.bpf_func = __bpf_prog_ret1,
1448 	},
1449 };
1450 
1451 /* to avoid allocating empty bpf_prog_array for cgroups that
1452  * don't have bpf program attached use one global 'empty_prog_array'
1453  * It will not be modified the caller of bpf_prog_array_alloc()
1454  * (since caller requested prog_cnt == 0)
1455  * that pointer should be 'freed' by bpf_prog_array_free()
1456  */
1457 static struct {
1458 	struct bpf_prog_array hdr;
1459 	struct bpf_prog *null_prog;
1460 } empty_prog_array = {
1461 	.null_prog = NULL,
1462 };
1463 
1464 struct bpf_prog_array __rcu *bpf_prog_array_alloc(u32 prog_cnt, gfp_t flags)
1465 {
1466 	if (prog_cnt)
1467 		return kzalloc(sizeof(struct bpf_prog_array) +
1468 			       sizeof(struct bpf_prog *) * (prog_cnt + 1),
1469 			       flags);
1470 
1471 	return &empty_prog_array.hdr;
1472 }
1473 
1474 void bpf_prog_array_free(struct bpf_prog_array __rcu *progs)
1475 {
1476 	if (!progs ||
1477 	    progs == (struct bpf_prog_array __rcu *)&empty_prog_array.hdr)
1478 		return;
1479 	kfree_rcu(progs, rcu);
1480 }
1481 
1482 int bpf_prog_array_length(struct bpf_prog_array __rcu *progs)
1483 {
1484 	struct bpf_prog **prog;
1485 	u32 cnt = 0;
1486 
1487 	rcu_read_lock();
1488 	prog = rcu_dereference(progs)->progs;
1489 	for (; *prog; prog++)
1490 		if (*prog != &dummy_bpf_prog.prog)
1491 			cnt++;
1492 	rcu_read_unlock();
1493 	return cnt;
1494 }
1495 
1496 static bool bpf_prog_array_copy_core(struct bpf_prog **prog,
1497 				     u32 *prog_ids,
1498 				     u32 request_cnt)
1499 {
1500 	int i = 0;
1501 
1502 	for (; *prog; prog++) {
1503 		if (*prog == &dummy_bpf_prog.prog)
1504 			continue;
1505 		prog_ids[i] = (*prog)->aux->id;
1506 		if (++i == request_cnt) {
1507 			prog++;
1508 			break;
1509 		}
1510 	}
1511 
1512 	return !!(*prog);
1513 }
1514 
1515 int bpf_prog_array_copy_to_user(struct bpf_prog_array __rcu *progs,
1516 				__u32 __user *prog_ids, u32 cnt)
1517 {
1518 	struct bpf_prog **prog;
1519 	unsigned long err = 0;
1520 	bool nospc;
1521 	u32 *ids;
1522 
1523 	/* users of this function are doing:
1524 	 * cnt = bpf_prog_array_length();
1525 	 * if (cnt > 0)
1526 	 *     bpf_prog_array_copy_to_user(..., cnt);
1527 	 * so below kcalloc doesn't need extra cnt > 0 check, but
1528 	 * bpf_prog_array_length() releases rcu lock and
1529 	 * prog array could have been swapped with empty or larger array,
1530 	 * so always copy 'cnt' prog_ids to the user.
1531 	 * In a rare race the user will see zero prog_ids
1532 	 */
1533 	ids = kcalloc(cnt, sizeof(u32), GFP_USER | __GFP_NOWARN);
1534 	if (!ids)
1535 		return -ENOMEM;
1536 	rcu_read_lock();
1537 	prog = rcu_dereference(progs)->progs;
1538 	nospc = bpf_prog_array_copy_core(prog, ids, cnt);
1539 	rcu_read_unlock();
1540 	err = copy_to_user(prog_ids, ids, cnt * sizeof(u32));
1541 	kfree(ids);
1542 	if (err)
1543 		return -EFAULT;
1544 	if (nospc)
1545 		return -ENOSPC;
1546 	return 0;
1547 }
1548 
1549 void bpf_prog_array_delete_safe(struct bpf_prog_array __rcu *progs,
1550 				struct bpf_prog *old_prog)
1551 {
1552 	struct bpf_prog **prog = progs->progs;
1553 
1554 	for (; *prog; prog++)
1555 		if (*prog == old_prog) {
1556 			WRITE_ONCE(*prog, &dummy_bpf_prog.prog);
1557 			break;
1558 		}
1559 }
1560 
1561 int bpf_prog_array_copy(struct bpf_prog_array __rcu *old_array,
1562 			struct bpf_prog *exclude_prog,
1563 			struct bpf_prog *include_prog,
1564 			struct bpf_prog_array **new_array)
1565 {
1566 	int new_prog_cnt, carry_prog_cnt = 0;
1567 	struct bpf_prog **existing_prog;
1568 	struct bpf_prog_array *array;
1569 	int new_prog_idx = 0;
1570 
1571 	/* Figure out how many existing progs we need to carry over to
1572 	 * the new array.
1573 	 */
1574 	if (old_array) {
1575 		existing_prog = old_array->progs;
1576 		for (; *existing_prog; existing_prog++) {
1577 			if (*existing_prog != exclude_prog &&
1578 			    *existing_prog != &dummy_bpf_prog.prog)
1579 				carry_prog_cnt++;
1580 			if (*existing_prog == include_prog)
1581 				return -EEXIST;
1582 		}
1583 	}
1584 
1585 	/* How many progs (not NULL) will be in the new array? */
1586 	new_prog_cnt = carry_prog_cnt;
1587 	if (include_prog)
1588 		new_prog_cnt += 1;
1589 
1590 	/* Do we have any prog (not NULL) in the new array? */
1591 	if (!new_prog_cnt) {
1592 		*new_array = NULL;
1593 		return 0;
1594 	}
1595 
1596 	/* +1 as the end of prog_array is marked with NULL */
1597 	array = bpf_prog_array_alloc(new_prog_cnt + 1, GFP_KERNEL);
1598 	if (!array)
1599 		return -ENOMEM;
1600 
1601 	/* Fill in the new prog array */
1602 	if (carry_prog_cnt) {
1603 		existing_prog = old_array->progs;
1604 		for (; *existing_prog; existing_prog++)
1605 			if (*existing_prog != exclude_prog &&
1606 			    *existing_prog != &dummy_bpf_prog.prog)
1607 				array->progs[new_prog_idx++] = *existing_prog;
1608 	}
1609 	if (include_prog)
1610 		array->progs[new_prog_idx++] = include_prog;
1611 	array->progs[new_prog_idx] = NULL;
1612 	*new_array = array;
1613 	return 0;
1614 }
1615 
1616 int bpf_prog_array_copy_info(struct bpf_prog_array __rcu *array,
1617 			     u32 *prog_ids, u32 request_cnt,
1618 			     u32 *prog_cnt)
1619 {
1620 	struct bpf_prog **prog;
1621 	u32 cnt = 0;
1622 
1623 	if (array)
1624 		cnt = bpf_prog_array_length(array);
1625 
1626 	*prog_cnt = cnt;
1627 
1628 	/* return early if user requested only program count or nothing to copy */
1629 	if (!request_cnt || !cnt)
1630 		return 0;
1631 
1632 	/* this function is called under trace/bpf_trace.c: bpf_event_mutex */
1633 	prog = rcu_dereference_check(array, 1)->progs;
1634 	return bpf_prog_array_copy_core(prog, prog_ids, request_cnt) ? -ENOSPC
1635 								     : 0;
1636 }
1637 
1638 static void bpf_prog_free_deferred(struct work_struct *work)
1639 {
1640 	struct bpf_prog_aux *aux;
1641 	int i;
1642 
1643 	aux = container_of(work, struct bpf_prog_aux, work);
1644 	if (bpf_prog_is_dev_bound(aux))
1645 		bpf_prog_offload_destroy(aux->prog);
1646 #ifdef CONFIG_PERF_EVENTS
1647 	if (aux->prog->has_callchain_buf)
1648 		put_callchain_buffers();
1649 #endif
1650 	for (i = 0; i < aux->func_cnt; i++)
1651 		bpf_jit_free(aux->func[i]);
1652 	if (aux->func_cnt) {
1653 		kfree(aux->func);
1654 		bpf_prog_unlock_free(aux->prog);
1655 	} else {
1656 		bpf_jit_free(aux->prog);
1657 	}
1658 }
1659 
1660 /* Free internal BPF program */
1661 void bpf_prog_free(struct bpf_prog *fp)
1662 {
1663 	struct bpf_prog_aux *aux = fp->aux;
1664 
1665 	INIT_WORK(&aux->work, bpf_prog_free_deferred);
1666 	schedule_work(&aux->work);
1667 }
1668 EXPORT_SYMBOL_GPL(bpf_prog_free);
1669 
1670 /* RNG for unpriviledged user space with separated state from prandom_u32(). */
1671 static DEFINE_PER_CPU(struct rnd_state, bpf_user_rnd_state);
1672 
1673 void bpf_user_rnd_init_once(void)
1674 {
1675 	prandom_init_once(&bpf_user_rnd_state);
1676 }
1677 
1678 BPF_CALL_0(bpf_user_rnd_u32)
1679 {
1680 	/* Should someone ever have the rather unwise idea to use some
1681 	 * of the registers passed into this function, then note that
1682 	 * this function is called from native eBPF and classic-to-eBPF
1683 	 * transformations. Register assignments from both sides are
1684 	 * different, f.e. classic always sets fn(ctx, A, X) here.
1685 	 */
1686 	struct rnd_state *state;
1687 	u32 res;
1688 
1689 	state = &get_cpu_var(bpf_user_rnd_state);
1690 	res = prandom_u32_state(state);
1691 	put_cpu_var(bpf_user_rnd_state);
1692 
1693 	return res;
1694 }
1695 
1696 /* Weak definitions of helper functions in case we don't have bpf syscall. */
1697 const struct bpf_func_proto bpf_map_lookup_elem_proto __weak;
1698 const struct bpf_func_proto bpf_map_update_elem_proto __weak;
1699 const struct bpf_func_proto bpf_map_delete_elem_proto __weak;
1700 
1701 const struct bpf_func_proto bpf_get_prandom_u32_proto __weak;
1702 const struct bpf_func_proto bpf_get_smp_processor_id_proto __weak;
1703 const struct bpf_func_proto bpf_get_numa_node_id_proto __weak;
1704 const struct bpf_func_proto bpf_ktime_get_ns_proto __weak;
1705 
1706 const struct bpf_func_proto bpf_get_current_pid_tgid_proto __weak;
1707 const struct bpf_func_proto bpf_get_current_uid_gid_proto __weak;
1708 const struct bpf_func_proto bpf_get_current_comm_proto __weak;
1709 const struct bpf_func_proto bpf_sock_map_update_proto __weak;
1710 const struct bpf_func_proto bpf_sock_hash_update_proto __weak;
1711 
1712 const struct bpf_func_proto * __weak bpf_get_trace_printk_proto(void)
1713 {
1714 	return NULL;
1715 }
1716 
1717 u64 __weak
1718 bpf_event_output(struct bpf_map *map, u64 flags, void *meta, u64 meta_size,
1719 		 void *ctx, u64 ctx_size, bpf_ctx_copy_t ctx_copy)
1720 {
1721 	return -ENOTSUPP;
1722 }
1723 EXPORT_SYMBOL_GPL(bpf_event_output);
1724 
1725 /* Always built-in helper functions. */
1726 const struct bpf_func_proto bpf_tail_call_proto = {
1727 	.func		= NULL,
1728 	.gpl_only	= false,
1729 	.ret_type	= RET_VOID,
1730 	.arg1_type	= ARG_PTR_TO_CTX,
1731 	.arg2_type	= ARG_CONST_MAP_PTR,
1732 	.arg3_type	= ARG_ANYTHING,
1733 };
1734 
1735 /* Stub for JITs that only support cBPF. eBPF programs are interpreted.
1736  * It is encouraged to implement bpf_int_jit_compile() instead, so that
1737  * eBPF and implicitly also cBPF can get JITed!
1738  */
1739 struct bpf_prog * __weak bpf_int_jit_compile(struct bpf_prog *prog)
1740 {
1741 	return prog;
1742 }
1743 
1744 /* Stub for JITs that support eBPF. All cBPF code gets transformed into
1745  * eBPF by the kernel and is later compiled by bpf_int_jit_compile().
1746  */
1747 void __weak bpf_jit_compile(struct bpf_prog *prog)
1748 {
1749 }
1750 
1751 bool __weak bpf_helper_changes_pkt_data(void *func)
1752 {
1753 	return false;
1754 }
1755 
1756 /* To execute LD_ABS/LD_IND instructions __bpf_prog_run() may call
1757  * skb_copy_bits(), so provide a weak definition of it for NET-less config.
1758  */
1759 int __weak skb_copy_bits(const struct sk_buff *skb, int offset, void *to,
1760 			 int len)
1761 {
1762 	return -EFAULT;
1763 }
1764 
1765 /* All definitions of tracepoints related to BPF. */
1766 #define CREATE_TRACE_POINTS
1767 #include <linux/bpf_trace.h>
1768 
1769 EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_exception);
1770