xref: /linux/kernel/bpf/fixups.c (revision 1879b5e505de97e250bb2d7e6914fbdf4032e15b)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
3 #include <linux/bpf.h>
4 #include <linux/btf.h>
5 #include <linux/bpf_verifier.h>
6 #include <linux/filter.h>
7 #include <linux/vmalloc.h>
8 #include <linux/perf_event.h>
9 #include <linux/sched/signal.h>
10 #include <net/xdp.h>
11 #include "disasm.h"
12 
13 #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
14 
15 /*
16  * Matches BPF_PROBE_ATOMIC too: bpf_convert_ctx_accesses() rewrites arena
17  * atomics before bpf_opt_subreg_zext_lo32_rnd_hi32() runs.
18  */
19 static bool is_cmpxchg_insn(const struct bpf_insn *insn)
20 {
21 	return BPF_CLASS(insn->code) == BPF_STX &&
22 	       (BPF_MODE(insn->code) == BPF_ATOMIC ||
23 		BPF_MODE(insn->code) == BPF_PROBE_ATOMIC) &&
24 	       insn->imm == BPF_CMPXCHG;
25 }
26 
27 /* Returns true if 'insn' is an address space cast instruction translated as BPF_ALU op */
28 static bool is_addr_space_cast32(struct bpf_prog *prog, const struct bpf_insn *insn)
29 {
30 	struct bpf_map *arena = (struct bpf_map *)prog->aux->arena;
31 
32 	if (insn->code != (BPF_ALU64 | BPF_MOV | BPF_X) || insn->off != BPF_ADDR_SPACE_CAST)
33 		return false;
34 
35 	/* cast from as(1) to as(0) */
36 	if (insn->imm == 1)
37 		return true;
38 
39 	/* cast from as(0) to as(1) */
40 	if (insn->imm == 1 << 16)
41 		return arena && arena->map_flags & BPF_F_NO_USER_CONV;
42 
43 	/* non-BPF_F_NO_USER_CONV cast from as(0) to as(1) should be handled by JIT */
44 	return false;
45 }
46 
47 /* Return the regno defined by the insn, or -1. */
48 static int insn_def_regno(const struct bpf_insn *insn)
49 {
50 	switch (BPF_CLASS(insn->code)) {
51 	case BPF_JMP:
52 	case BPF_JMP32:
53 	case BPF_ST:
54 		return -1;
55 	case BPF_STX:
56 		return bpf_atomic_load_reg(insn);
57 	default:
58 		return insn->dst_reg;
59 	}
60 }
61 
62 /*
63  * For use only in combination with insn_def_regno() >= 0.
64  * Returns TRUE if the destination register operates on 64-bit,
65  * otherwise return FALSE.
66  */
67 static bool bpf_is_reg64(struct bpf_prog *prog, struct bpf_insn *insn)
68 {
69 	u8 class = BPF_CLASS(insn->code);
70 	u8 mode = BPF_MODE(insn->code);
71 	u8 size = BPF_SIZE(insn->code);
72 	u8 op = BPF_OP(insn->code);
73 	bool mode_mem;
74 
75 	/* subregister endiness swap */
76 	if ((class == BPF_ALU || class == BPF_ALU64) && op == BPF_END && insn->imm != 64)
77 		return false;
78 
79 	/* w0 += 1 */
80 	if (class == BPF_ALU && op != BPF_END)
81 		return false;
82 
83 	/* address space casts converted to BPF_ALU, see bpf_do_misc_fixups() */
84 	if (is_addr_space_cast32(prog, insn))
85 		return false;
86 
87 	/* non 64-bit, non signed extended loads */
88 	mode_mem = mode == BPF_MEM || mode == BPF_PROBE_MEM || mode == BPF_PROBE_MEM32;
89 	if (class == BPF_LDX && mode_mem && size != BPF_DW)
90 		return false;
91 
92 	/* atomics, see insn_def_regno() */
93 	if (class == BPF_STX && size != BPF_DW)
94 		return false;
95 
96 	/* both LD_IND and LD_ABS return 32-bit data. */
97 	if (class == BPF_LD && (mode == BPF_IND || mode == BPF_ABS))
98 		return false;
99 
100 	/* Conservatively return true at default. */
101 	return true;
102 }
103 
104 /*
105  * Return the 32-bit subregister defined by INSN, or -1 if INSN does not
106  * explicitly define a 32-bit value.
107  */
108 int bpf_insn_def32(struct bpf_prog *prog, struct bpf_insn *insn)
109 {
110 	int dst_reg = insn_def_regno(insn);
111 
112 	if (dst_reg < 0 || bpf_is_reg64(prog, insn))
113 		return -1;
114 
115 	return dst_reg;
116 }
117 
118 const struct btf_func_model *
119 bpf_jit_find_kfunc_model(const struct bpf_prog *prog,
120 			 const struct bpf_insn *insn)
121 {
122 	const struct bpf_kfunc_desc *res;
123 	struct bpf_kfunc_desc_tab *tab;
124 
125 	tab = prog->aux->kfunc_tab;
126 	if (insn->off < 0 || insn->off >= tab->nr_descs)
127 		return NULL;
128 
129 	res = &tab->descs[insn->off];
130 	if (bpf_jit_supports_far_kfunc_call()) {
131 		if (res->func_id != insn->imm)
132 			return NULL;
133 	} else if ((s32)BPF_CALL_IMM(res->addr) != insn->imm) {
134 		return NULL;
135 	}
136 
137 	return &res->func_model;
138 }
139 
140 static int add_kfunc_in_insns(struct bpf_verifier_env *env,
141 			      struct bpf_insn *insn, int cnt)
142 {
143 	int i, ret;
144 
145 	for (i = 0; i < cnt; i++, insn++) {
146 		if (bpf_pseudo_kfunc_call(insn)) {
147 			ret = bpf_add_kfunc_call(env, insn->imm, insn->off);
148 			if (ret < 0)
149 				return ret;
150 		}
151 	}
152 	return 0;
153 }
154 
155 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
156 static int get_callee_stack_depth(struct bpf_verifier_env *env,
157 				  const struct bpf_insn *insn, int idx)
158 {
159 	int start = idx + insn->imm + 1, subprog;
160 
161 	subprog = bpf_find_subprog(env, start);
162 	if (verifier_bug_if(subprog < 0, env, "get stack depth: no program at insn %d", start))
163 		return -EFAULT;
164 	return env->subprog_info[subprog].stack_depth;
165 }
166 #endif
167 
168 enum bpf_patch_mode {
169 	BPF_PATCH_KEEP_TARGET,	/* targets of 'off' keep naming 'off', the first new insn */
170 	BPF_PATCH_MOVE_TARGET,	/* targets of 'off' follow the original insn to 'off + len - 1' */
171 };
172 
173 /* single env->prog->insni[off] instruction was replaced with the range
174  * insni[off, off + cnt).  Adjust corresponding insn_aux_data by copying
175  * [0, off) and [off, end) to new locations, so the patched range stays zero
176  */
177 static void adjust_insn_aux_data(struct bpf_verifier_env *env,
178 				 struct bpf_prog *new_prog, u32 off, u32 cnt,
179 				 struct bpf_insn *original_insn,
180 				 enum bpf_patch_mode mode)
181 {
182 	struct bpf_insn_aux_data *data = env->insn_aux_data;
183 	struct bpf_insn *insn = new_prog->insnsi;
184 	u32 old_seen = data[off].seen;
185 	u32 prog_len;
186 	int i;
187 
188 	/* aux info at OFF always needs adjustment, no matter fast path
189 	 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the
190 	 * original insn at old prog.
191 	 */
192 	data[off].zext_dst = bpf_insn_def32(new_prog, insn + off + cnt - 1) >= 0;
193 
194 	if (cnt == 1) {
195 		/*
196 		 * A non-memory accessing insn could have been replaced by a
197 		 * memory accessing insn, systematically mark it for non-stack
198 		 * access
199 		 */
200 		data[off].non_stack_access = bpf_is_mem_insn(insn + off);
201 		return;
202 	}
203 	prog_len = new_prog->len;
204 	env->insn_aux_data_len = prog_len;
205 
206 	memmove(data + off + cnt - 1, data + off,
207 		sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1));
208 	memset(data + off, 0, sizeof(struct bpf_insn_aux_data) * (cnt - 1));
209 	for (i = off; i < off + cnt - 1; i++) {
210 		/* Expand insni[off]'s seen count to the patched range. */
211 		data[i].seen = old_seen;
212 		data[i].zext_dst = bpf_insn_def32(new_prog, insn + i) >= 0;
213 		/*
214 		 * In BPF_PATCH_MOVE_TARGET mode the original insn is the last
215 		 * slot by construction.
216 		 */
217 		if (mode == BPF_PATCH_KEEP_TARGET &&
218 		    !memcmp(insn + i, original_insn, sizeof(struct bpf_insn))) {
219 			data[i].non_stack_access =
220 				data[off + cnt - 1].non_stack_access;
221 			data[off + cnt - 1].non_stack_access = false;
222 		} else if (bpf_is_mem_insn(insn + i)) {
223 			data[i].non_stack_access = true;
224 		}
225 	}
226 
227 	/*
228 	 * Last slot instruction could be a newly generated
229 	 * BPF_ST/BPF_LDX/BPF_STX, systematically mark it for non-stack access
230 	 * if it is not the original instruction, otherwise keep the
231 	 * original marking
232 	 */
233 	if (bpf_is_mem_insn(insn + off + cnt - 1) &&
234 	    memcmp(insn + off + cnt - 1, original_insn, sizeof(struct bpf_insn)))
235 		data[off + cnt - 1].non_stack_access = true;
236 
237 	/*
238 	 * The indirect_target flag of the original instruction was moved to the last of the
239 	 * new instructions by the above memmove and memset, but the indirect jump target is
240 	 * actually the first instruction, so move it back. This also matches with the behavior
241 	 * of bpf_insn_array_adjust(), which preserves xlated_off to point to the first new
242 	 * instruction. For BPF_PATCH_MOVE_TARGET the original instruction is the last one,
243 	 * so the flag already sits where needed.
244 	 */
245 	if (mode == BPF_PATCH_KEEP_TARGET && data[off + cnt - 1].indirect_target) {
246 		data[off].indirect_target = 1;
247 		data[off + cnt - 1].indirect_target = 0;
248 	}
249 }
250 
251 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len)
252 {
253 	int i;
254 
255 	if (len == 1)
256 		return;
257 	/* NOTE: fake 'exit' subprog should be updated as well. */
258 	for (i = 0; i <= env->subprog_cnt; i++) {
259 		if (env->subprog_info[i].start <= off)
260 			continue;
261 		env->subprog_info[i].start += len - 1;
262 	}
263 }
264 
265 static void adjust_insn_arrays(struct bpf_verifier_env *env, u32 first, u32 len)
266 {
267 	int i;
268 
269 	if (len == 1)
270 		return;
271 
272 	for (i = 0; i < env->insn_array_map_cnt; i++)
273 		bpf_insn_array_adjust(env->insn_array_maps[i], first, len);
274 }
275 
276 static void adjust_insn_arrays_after_remove(struct bpf_verifier_env *env, u32 off, u32 len)
277 {
278 	int i;
279 
280 	for (i = 0; i < env->insn_array_map_cnt; i++)
281 		bpf_insn_array_adjust_after_remove(env->insn_array_maps[i], off, len);
282 }
283 
284 static void adjust_poke_descs(struct bpf_prog *prog, u32 first, u32 len)
285 {
286 	struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab;
287 	int i, sz = prog->aux->size_poke_tab;
288 	struct bpf_jit_poke_descriptor *desc;
289 
290 	for (i = 0; i < sz; i++) {
291 		desc = &tab[i];
292 		if (desc->insn_idx < first)
293 			continue;
294 		desc->insn_idx += len - 1;
295 	}
296 }
297 
298 /*
299  * Some post-verification instruction rewriting passes require an
300  * O(prog->len) operation per instruction. Keep their shared primitives
301  * killable and preemptible.
302  */
303 static bool bpf_rewrite_must_abort(void)
304 {
305 	if (fatal_signal_pending(current))
306 		return true;
307 	cond_resched();
308 	return false;
309 }
310 
311 static struct bpf_prog *__bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
312 					      const struct bpf_insn *patch, u32 len,
313 					      enum bpf_patch_mode mode)
314 {
315 	struct bpf_prog *new_prog;
316 	struct bpf_insn_aux_data *new_data = NULL;
317 	/* The first slot whose targets move. */
318 	u32 first = mode == BPF_PATCH_MOVE_TARGET ? off : off + 1;
319 	struct bpf_insn original_insn;
320 
321 	if (bpf_rewrite_must_abort())
322 		return NULL;
323 
324 	if (len > 1) {
325 		new_data = vrealloc(env->insn_aux_data,
326 				    array_size(env->prog->len + len - 1,
327 					       sizeof(struct bpf_insn_aux_data)),
328 				    GFP_KERNEL_ACCOUNT | __GFP_ZERO);
329 		if (!new_data)
330 			return NULL;
331 
332 		env->insn_aux_data = new_data;
333 	}
334 
335 	memcpy(&original_insn, env->prog->insnsi + off, sizeof(struct bpf_insn));
336 	new_prog = bpf_patch_insn_single(env->prog, off, patch, len);
337 	if (IS_ERR(new_prog)) {
338 		if (PTR_ERR(new_prog) == -ERANGE)
339 			verbose(env,
340 				"insn %d cannot be patched due to 16-bit range\n",
341 				env->insn_aux_data[off].orig_idx);
342 		return NULL;
343 	}
344 	adjust_insn_aux_data(env, new_prog, off, len, &original_insn, mode);
345 	adjust_subprog_starts(env, off, len);
346 	adjust_insn_arrays(env, first, len);
347 	bpf_adjust_func_ptrs(env, off, len);
348 	adjust_poke_descs(new_prog, first, len);
349 	return new_prog;
350 }
351 
352 struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off,
353 				     const struct bpf_insn *patch, u32 len)
354 {
355 	return __bpf_patch_insn_data(env, off, patch, len, BPF_PATCH_KEEP_TARGET);
356 }
357 
358 /*
359  * insn was moved down by delta insns inside its own patch. Operands relative
360  * to the pc that point in front of the old position did not move with it.
361  */
362 static int bpf_adj_moved_insn(struct bpf_insn *insn, u32 delta)
363 {
364 	u8 class = BPF_CLASS(insn->code), op = BPF_OP(insn->code);
365 	s64 off = insn->imm, off_min = S32_MIN;
366 	bool is_imm = true;
367 
368 	if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) {
369 		/* subprog that started at the old position starts with the patch */
370 		if (off >= 0)
371 			return 0;
372 	} else if ((class == BPF_JMP || class == BPF_JMP32) &&
373 		   op != BPF_CALL && op != BPF_EXIT) {
374 		if (insn->code != (BPF_JMP32 | BPF_JA)) {
375 			off = insn->off;
376 			off_min = S16_MIN;
377 			is_imm = false;
378 		}
379 		/* jump to itself stays */
380 		if (off >= -1)
381 			return 0;
382 	} else {
383 		return 0;
384 	}
385 
386 	off -= delta;
387 	if (off < off_min)
388 		return -ERANGE;
389 	if (is_imm)
390 		insn->imm = off;
391 	else
392 		insn->off = off;
393 	return 0;
394 }
395 
396 /*
397  * For all jmp insns in a given 'prog' that point to 'tgt_idx' insn adjust the
398  * jump offset by 'delta'.
399  */
400 static int adjust_jmp_off(struct bpf_prog *prog, u32 tgt_idx, u32 delta)
401 {
402 	struct bpf_insn *insn = prog->insnsi;
403 	u32 insn_cnt = prog->len, i;
404 	s32 imm;
405 	s16 off;
406 
407 	for (i = 0; i < insn_cnt; i++, insn++) {
408 		u8 code = insn->code;
409 
410 		if (tgt_idx <= i && i < tgt_idx + delta)
411 			continue;
412 
413 		if ((BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) ||
414 		    BPF_OP(code) == BPF_CALL || BPF_OP(code) == BPF_EXIT)
415 			continue;
416 
417 		if (insn->code == (BPF_JMP32 | BPF_JA)) {
418 			if (i + 1 + insn->imm != tgt_idx)
419 				continue;
420 			if (check_add_overflow(insn->imm, delta, &imm))
421 				return -ERANGE;
422 			insn->imm = imm;
423 		} else {
424 			if (i + 1 + insn->off != tgt_idx)
425 				continue;
426 			if (check_add_overflow(insn->off, delta, &off))
427 				return -ERANGE;
428 			insn->off = off;
429 		}
430 	}
431 	return 0;
432 }
433 
434 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env,
435 					      u32 off, u32 cnt)
436 {
437 	int i, j;
438 
439 	/* find first prog starting at or after off (first to remove) */
440 	for (i = 0; i < env->subprog_cnt; i++)
441 		if (env->subprog_info[i].start >= off)
442 			break;
443 	/* find first prog starting at or after off + cnt (first to stay) */
444 	for (j = i; j < env->subprog_cnt; j++)
445 		if (env->subprog_info[j].start >= off + cnt)
446 			break;
447 	/* if j doesn't start exactly at off + cnt, we are just removing
448 	 * the front of previous prog
449 	 */
450 	if (env->subprog_info[j].start != off + cnt)
451 		j--;
452 
453 	if (j > i) {
454 		struct bpf_prog_aux *aux = env->prog->aux;
455 		int move;
456 
457 		/* move fake 'exit' subprog as well */
458 		move = env->subprog_cnt + 1 - j;
459 
460 		memmove(env->subprog_info + i,
461 			env->subprog_info + j,
462 			sizeof(*env->subprog_info) * move);
463 		env->subprog_cnt -= j - i;
464 
465 		/* remove func_info and its aux */
466 		if (aux->func_info) {
467 			move = aux->func_info_cnt - j;
468 
469 			memmove(aux->func_info + i,
470 				aux->func_info + j,
471 				sizeof(*aux->func_info) * move);
472 			if (aux->func_info_aux)
473 				memmove(aux->func_info_aux + i,
474 					aux->func_info_aux + j,
475 					sizeof(*aux->func_info_aux) * move);
476 			aux->func_info_cnt -= j - i;
477 			/* func_info->insn_off is set after all code rewrites,
478 			 * in adjust_btf_func() - no need to adjust
479 			 */
480 		}
481 		/* The exception callback is live, so it cannot sit inside the removed range. */
482 		if (env->exception_callback_subprog >= j)
483 			env->exception_callback_subprog -= j - i;
484 	} else {
485 		/* convert i from "first prog to remove" to "first to adjust" */
486 		if (env->subprog_info[i].start == off)
487 			i++;
488 	}
489 
490 	/* update fake 'exit' subprog as well */
491 	for (; i <= env->subprog_cnt; i++)
492 		env->subprog_info[i].start -= cnt;
493 
494 	return 0;
495 }
496 
497 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off,
498 				      u32 cnt)
499 {
500 	struct bpf_prog *prog = env->prog;
501 	u32 i, l_off, l_cnt, nr_linfo;
502 	struct bpf_line_info *linfo;
503 
504 	nr_linfo = prog->aux->nr_linfo;
505 	if (!nr_linfo)
506 		return 0;
507 
508 	linfo = prog->aux->linfo;
509 
510 	/* find first line info to remove, count lines to be removed */
511 	for (i = 0; i < nr_linfo; i++)
512 		if (linfo[i].insn_off >= off)
513 			break;
514 
515 	l_off = i;
516 	l_cnt = 0;
517 	for (; i < nr_linfo; i++)
518 		if (linfo[i].insn_off < off + cnt)
519 			l_cnt++;
520 		else
521 			break;
522 
523 	/* First live insn doesn't match first live linfo, it needs to "inherit"
524 	 * last removed linfo.  prog is already modified, so prog->len == off
525 	 * means no live instructions after (tail of the program was removed).
526 	 */
527 	if (prog->len != off && l_cnt &&
528 	    (i == nr_linfo || linfo[i].insn_off != off + cnt)) {
529 		l_cnt--;
530 		linfo[--i].insn_off = off + cnt;
531 	}
532 
533 	/* remove the line info which refer to the removed instructions */
534 	if (l_cnt) {
535 		memmove(linfo + l_off, linfo + i,
536 			sizeof(*linfo) * (nr_linfo - i));
537 
538 		prog->aux->nr_linfo -= l_cnt;
539 		nr_linfo = prog->aux->nr_linfo;
540 	}
541 
542 	/* pull all linfo[i].insn_off >= off + cnt in by cnt */
543 	for (i = l_off; i < nr_linfo; i++)
544 		linfo[i].insn_off -= cnt;
545 
546 	/* fix up all subprogs (incl. 'exit') which start >= off */
547 	for (i = 0; i <= env->subprog_cnt; i++)
548 		if (env->subprog_info[i].linfo_idx > l_off) {
549 			/* program may have started in the removed region but
550 			 * may not be fully removed
551 			 */
552 			if (env->subprog_info[i].linfo_idx >= l_off + l_cnt)
553 				env->subprog_info[i].linfo_idx -= l_cnt;
554 			else
555 				env->subprog_info[i].linfo_idx = l_off;
556 		}
557 
558 	return 0;
559 }
560 
561 /* Clean up dynamically allocated fields of aux data for instructions [start, ...] */
562 void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
563 {
564 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
565 	int end = start + len;
566 	int i;
567 
568 	for (i = start; i < end; i++) {
569 		if (aux_data[i].loop) {
570 			kvfree(aux_data[i].loop->exits);
571 			kvfree(aux_data[i].loop);
572 			aux_data[i].loop = NULL;
573 		}
574 	}
575 }
576 
577 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt)
578 {
579 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
580 	unsigned int orig_prog_len = env->prog->len;
581 	int err;
582 
583 	if (bpf_rewrite_must_abort())
584 		return -EINTR;
585 
586 	if (bpf_prog_is_offloaded(env->prog->aux))
587 		bpf_prog_offload_remove_insns(env, off, cnt);
588 
589 	bpf_clear_insn_aux_data(env, off, cnt);
590 
591 	err = bpf_remove_insns(env->prog, off, cnt);
592 	if (err)
593 		return err;
594 
595 	/* before subprogs are adjusted, since it looks at them */
596 	bpf_adjust_func_ptrs_after_remove(env, off, cnt);
597 
598 	err = adjust_subprog_starts_after_remove(env, off, cnt);
599 	if (err)
600 		return err;
601 
602 	err = bpf_adj_linfo_after_remove(env, off, cnt);
603 	if (err)
604 		return err;
605 
606 	adjust_insn_arrays_after_remove(env, off, cnt);
607 
608 	memmove(aux_data + off,	aux_data + off + cnt,
609 		sizeof(*aux_data) * (orig_prog_len - off - cnt));
610 	env->insn_aux_data_len -= cnt;
611 
612 	return 0;
613 }
614 
615 static const struct bpf_insn NOP = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
616 static const struct bpf_insn MAY_GOTO_0 = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0);
617 
618 bool bpf_insn_is_cond_jump(u8 code)
619 {
620 	u8 op;
621 
622 	op = BPF_OP(code);
623 	if (BPF_CLASS(code) == BPF_JMP32)
624 		return op != BPF_JA;
625 
626 	if (BPF_CLASS(code) != BPF_JMP)
627 		return false;
628 
629 	return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL;
630 }
631 
632 void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
633 {
634 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
635 	struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0);
636 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
637 	struct bpf_insn *insn = env->prog->insnsi;
638 	const int insn_cnt = env->prog->len;
639 	int i;
640 
641 	for (i = 0; i < insn_cnt; i++, insn++) {
642 		if (!bpf_insn_is_cond_jump(insn->code))
643 			continue;
644 
645 		if (bpf_is_unwind_goto(insn) && aux_data[i + 1 + insn->off].seen) {
646 			/*
647 			 * The callee never exits. Its unwind_exit needs
648 			 * unwind_goto all the same, and the cpu predicts that it
649 			 * returns to what follows. Don't let the removal of dead
650 			 * code put something else there.
651 			 */
652 			if (!aux_data[i + 1].seen) {
653 				memcpy(insn + 1, &trap, sizeof(trap));
654 				aux_data[i + 1].seen = env->pass_cnt;
655 			}
656 			continue;
657 		}
658 
659 		if (!aux_data[i + 1].seen)
660 			ja.off = insn->off;
661 		else if (!aux_data[i + 1 + insn->off].seen)
662 			ja.off = 0;
663 		else
664 			continue;
665 
666 		if (bpf_prog_is_offloaded(env->prog->aux))
667 			bpf_prog_offload_replace_insn(env, i, &ja);
668 
669 		memcpy(insn, &ja, sizeof(ja));
670 	}
671 }
672 
673 /*
674  * The address of a function might be taken by the code that is not dead,
675  * while the function itself is dead code, since nothing calls it. Keep the first
676  * instruction of such function, so that the address remains valid and differs
677  * from the addresses of other functions. Make it a trap like
678  * sanitize_dead_code() does.
679  */
680 static void keep_funcs_with_addr_taken(struct bpf_verifier_env *env)
681 {
682 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
683 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
684 	struct bpf_insn *insn = env->prog->insnsi;
685 	int insn_cnt = env->prog->len;
686 	int i, t;
687 
688 	for (i = 0; i < insn_cnt; i++) {
689 		if (!aux_data[i].seen || !bpf_pseudo_func(insn + i))
690 			continue;
691 		t = i + insn[i].imm + 1;
692 		if (aux_data[t].seen)
693 			continue;
694 		memcpy(insn + t, &trap, sizeof(trap));
695 		aux_data[t].zext_dst = false;
696 		aux_data[t].seen = env->pass_cnt;
697 	}
698 }
699 
700 int bpf_opt_remove_dead_code(struct bpf_verifier_env *env)
701 {
702 	struct bpf_insn_aux_data *aux_data = env->insn_aux_data;
703 	int insn_cnt = env->prog->len;
704 	int i, err;
705 
706 	keep_funcs_with_addr_taken(env);
707 
708 	for (i = 0; i < insn_cnt; i++) {
709 		int j;
710 
711 		j = 0;
712 		while (i + j < insn_cnt && !aux_data[i + j].seen)
713 			j++;
714 		if (!j)
715 			continue;
716 
717 		err = verifier_remove_insns(env, i, j);
718 		if (err)
719 			return err;
720 		insn_cnt = env->prog->len;
721 	}
722 
723 	return 0;
724 }
725 
726 int bpf_opt_remove_nops(struct bpf_verifier_env *env)
727 {
728 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
729 	struct bpf_insn *insn = env->prog->insnsi;
730 	int insn_cnt = env->prog->len;
731 	bool is_may_goto_0, is_ja;
732 	int i, err;
733 
734 	for (i = 0; i < insn_cnt; i++) {
735 		is_may_goto_0 = !memcmp(&insn[i], &MAY_GOTO_0, sizeof(MAY_GOTO_0));
736 		is_ja = !memcmp(&insn[i], &NOP, sizeof(NOP));
737 
738 		if (!is_may_goto_0 && !is_ja)
739 			continue;
740 		if (aux[i].indirect_target)
741 			continue;
742 
743 		err = verifier_remove_insns(env, i, 1);
744 		if (err)
745 			return err;
746 		insn_cnt--;
747 		/* Go back one insn to catch may_goto +1; may_goto +0 sequence */
748 		i -= (is_may_goto_0 && i > 0) ? 2 : 1;
749 	}
750 
751 	return 0;
752 }
753 
754 int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
755 					 const union bpf_attr *attr)
756 {
757 	struct bpf_insn *patch;
758 	/* use env->insn_buf as two independent buffers */
759 	struct bpf_insn *zext_patch = env->insn_buf;
760 	struct bpf_insn *rnd_hi32_patch = &env->insn_buf[2];
761 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
762 	int i, patch_len, delta = 0, len = env->prog->len;
763 	struct bpf_insn *insns = env->prog->insnsi;
764 	struct bpf_prog *new_prog;
765 	bool rnd_hi32;
766 
767 	rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32;
768 	zext_patch[1] = BPF_ZEXT_REG(0);
769 	rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0);
770 	rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32);
771 	rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX);
772 	for (i = 0; i < len; i++) {
773 		int adj_idx = i + delta;
774 		struct bpf_insn insn;
775 		int load_reg;
776 
777 		insn = insns[adj_idx];
778 		load_reg = insn_def_regno(&insn);
779 		if (!aux[adj_idx].zext_dst) {
780 			u8 code, class;
781 			u32 imm_rnd;
782 
783 			if (!rnd_hi32)
784 				continue;
785 
786 			code = insn.code;
787 			class = BPF_CLASS(code);
788 			if (load_reg == -1)
789 				continue;
790 
791 			if (bpf_is_reg64(env->prog, &insn)) {
792 				if (class == BPF_LD &&
793 				    BPF_MODE(code) == BPF_IMM)
794 					i++;
795 				continue;
796 			}
797 
798 			/* ctx load could be transformed into wider load. */
799 			if (class == BPF_LDX &&
800 			    aux[adj_idx].ptr_type == PTR_TO_CTX)
801 				continue;
802 
803 			imm_rnd = get_random_u32();
804 			rnd_hi32_patch[0] = insn;
805 			rnd_hi32_patch[1].imm = imm_rnd;
806 			rnd_hi32_patch[3].dst_reg = load_reg;
807 			patch = rnd_hi32_patch;
808 			patch_len = 4;
809 			goto apply_patch_buffer;
810 		}
811 
812 		/* Add in an zero-extend instruction if a) the JIT has requested
813 		 * it or b) it's a CMPXCHG.
814 		 *
815 		 * The latter is because: BPF_CMPXCHG always loads a value into
816 		 * R0, therefore always zero-extends. However some archs'
817 		 * equivalent instruction only does this load when the
818 		 * comparison is successful. This detail of CMPXCHG is
819 		 * orthogonal to the general zero-extension behaviour of the
820 		 * CPU, so it's treated independently of bpf_jit_needs_zext.
821 		 */
822 		if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn))
823 			continue;
824 
825 		/* Zero-extension is done by the caller. */
826 		if (bpf_pseudo_kfunc_call(&insn))
827 			continue;
828 
829 		if (verifier_bug_if(load_reg == -1, env,
830 				    "zext_dst is set, but no reg is defined"))
831 			return -EFAULT;
832 
833 		zext_patch[0] = insn;
834 		zext_patch[1].dst_reg = load_reg;
835 		zext_patch[1].src_reg = load_reg;
836 		patch = zext_patch;
837 		patch_len = 2;
838 apply_patch_buffer:
839 		new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len);
840 		if (!new_prog)
841 			return -ENOMEM;
842 		env->prog = new_prog;
843 		insns = new_prog->insnsi;
844 		aux = env->insn_aux_data;
845 		delta += patch_len - 1;
846 	}
847 
848 	return 0;
849 }
850 
851 /*
852  * The prologue takes the context from R1, and it can clobber R2-R5. An
853  * extension gets the arguments of the function that it replaces.
854  */
855 static bool ext_prog_takes_prologue(const struct bpf_verifier_env *env)
856 {
857 	const struct bpf_subprog_info *sub = &env->subprog_info[0];
858 	int i, cnt = min_t(int, sub->arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS);
859 
860 	if (!cnt || sub->args[0].arg_type != ARG_PTR_TO_CTX)
861 		return false;
862 
863 	for (i = 1; i < cnt; i++)
864 		if (sub->args[i].arg_type != ARG_SCALAR)
865 			return false;
866 
867 	return true;
868 }
869 
870 /* convert load instructions that access fields of a context type into a
871  * sequence of instructions that access fields of the underlying structure:
872  *     struct __sk_buff    -> struct sk_buff
873  *     struct bpf_sock_ops -> struct sock
874  */
875 /*
876  * A load through an __arena pointer member of a kernel struct reads the kernel
877  * address of arena memory. Append the conversion to the arena pointer form,
878  * (u32)(kaddr - kern_vm_start), that the struct_ops trampoline applies to
879  * __arena arguments. A __nullable member keeps NULL as NULL, tested on the
880  * full kernel address, and so does a probed load, which reads as 0 when it
881  * faults. Returns the number of insns in @buf, 0 when the insn loads no such
882  * member, or an error when it does so on some paths only.
883  */
884 static int arena_member_fixup(struct bpf_verifier_env *env, int idx, struct bpf_insn *insn,
885 			      struct bpf_insn *buf)
886 {
887 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[idx];
888 	int cnt = 0;
889 	u32 base;
890 
891 	if (!aux->arena_member)
892 		return 0;
893 	if (aux->non_arena_load) {
894 		verbose(env, "an insn loads an arena pointer member on one path and something else on another\n");
895 		return -EINVAL;
896 	}
897 
898 	base = bpf_arena_get_kern_vm_start(env->prog->aux->arena);
899 	buf[cnt++] = *insn;
900 	if (aux->arena_member_nullable || BPF_MODE(insn->code) == BPF_PROBE_MEM)
901 		buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, insn->dst_reg, 0, 1);
902 	buf[cnt++] = BPF_ALU32_IMM(BPF_SUB, insn->dst_reg, (s32)base);
903 	return cnt;
904 }
905 
906 int bpf_convert_ctx_accesses(struct bpf_verifier_env *env)
907 {
908 	struct bpf_subprog_info *subprogs = env->subprog_info;
909 	const struct bpf_verifier_ops *ops = env->ops;
910 	int i, cnt, size, ctx_field_size, ret, delta = 0, epilogue_cnt = 0;
911 	const int insn_cnt = env->prog->len;
912 	struct bpf_insn *epilogue_buf = env->epilogue_buf;
913 	struct bpf_insn *insn_buf = env->insn_buf;
914 	bool nospec, nospec_next = false;
915 	struct bpf_insn *insn;
916 	u32 target_size, size_default, off;
917 	struct bpf_prog *new_prog;
918 	enum bpf_access_type type;
919 	bool is_narrower_load;
920 	int epilogue_idx = 0;
921 
922 	if (ops->gen_epilogue) {
923 		epilogue_cnt = ops->gen_epilogue(epilogue_buf, env->prog,
924 						 -(subprogs[0].stack_depth + 8));
925 		if (epilogue_cnt >= INSN_BUF_SIZE) {
926 			verifier_bug(env, "epilogue is too long");
927 			return -EFAULT;
928 		} else if (epilogue_cnt) {
929 			/* Save the ARG_PTR_TO_CTX for the epilogue to use */
930 			cnt = 0;
931 			subprogs[0].stack_depth += 8;
932 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_1,
933 						      -subprogs[0].stack_depth);
934 			insn_buf[cnt++] = env->prog->insnsi[0];
935 			new_prog = __bpf_patch_insn_data(env, 0, insn_buf, cnt,
936 							 BPF_PATCH_MOVE_TARGET);
937 			if (!new_prog)
938 				return -ENOMEM;
939 			env->prog = new_prog;
940 			delta += cnt - 1;
941 
942 			ret = add_kfunc_in_insns(env, epilogue_buf, epilogue_cnt - 1);
943 			if (ret < 0)
944 				return ret;
945 		}
946 	}
947 
948 	if (ops->gen_prologue || env->seen_direct_write) {
949 		if (!ops->gen_prologue) {
950 			verifier_bug(env, "gen_prologue is null");
951 			return -EFAULT;
952 		}
953 		cnt = ops->gen_prologue(insn_buf, env->seen_direct_write,
954 					env->prog);
955 		if (cnt >= INSN_BUF_SIZE) {
956 			verifier_bug(env, "prologue is too long");
957 			return -EFAULT;
958 		} else if (cnt) {
959 			if (env->prog->type == BPF_PROG_TYPE_EXT &&
960 			    !ext_prog_takes_prologue(env)) {
961 				verbose(env,
962 					"Extension writing packet data must take ctx and scalars only\n");
963 				return -EINVAL;
964 			}
965 			if (env->prog->type == BPF_PROG_TYPE_EXT &&
966 			    bpf_check_ext_prologue(&env->log,
967 						   env->prog->aux->dst_prog,
968 						   env->prog->aux->attach_btf_id))
969 				return -EINVAL;
970 			env->prog->aux->has_prologue = true;
971 			new_prog = __bpf_patch_insn_data(env, 0, insn_buf, cnt,
972 							 BPF_PATCH_MOVE_TARGET);
973 			if (!new_prog)
974 				return -ENOMEM;
975 
976 			env->prog = new_prog;
977 			delta += cnt - 1;
978 
979 			ret = add_kfunc_in_insns(env, insn_buf, cnt - 1);
980 			if (ret < 0)
981 				return ret;
982 		}
983 	}
984 
985 	if (delta)
986 		WARN_ON(adjust_jmp_off(env->prog, 0, delta));
987 
988 	if (bpf_prog_is_offloaded(env->prog->aux))
989 		return 0;
990 
991 	insn = env->prog->insnsi + delta;
992 
993 	for (i = 0; i < insn_cnt; i++, insn++) {
994 		bpf_convert_ctx_access_t convert_ctx_access;
995 		enum bpf_reg_type ptr_type;
996 		u8 mode;
997 
998 		/* A call or an atomic gets its nospec in front of the next insn */
999 		nospec = env->insn_aux_data[i + delta].nospec;
1000 		WARN_ON_ONCE(nospec && env->insn_aux_data[i + delta].alu_state);
1001 		nospec |= nospec_next;
1002 		nospec_next = env->insn_aux_data[i + delta].nospec_result;
1003 
1004 		if (nospec) {
1005 			struct bpf_insn *patch = insn_buf;
1006 
1007 			*patch++ = BPF_ST_NOSPEC();
1008 			*patch = *insn;
1009 			ret = bpf_adj_moved_insn(patch++, 1);
1010 			if (ret) {
1011 				verbose(env, "insn %d cannot be patched due to 16-bit range\n",
1012 					env->insn_aux_data[i + delta].orig_idx);
1013 				return ret;
1014 			}
1015 			cnt = patch - insn_buf;
1016 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
1017 			if (!new_prog)
1018 				return -ENOMEM;
1019 
1020 			delta    += cnt - 1;
1021 			env->prog = new_prog;
1022 			insn      = new_prog->insnsi + i + delta;
1023 			/* This can not be easily merged with the
1024 			 * nospec_result-case, because an insn may require a
1025 			 * nospec before and after itself. Therefore also do not
1026 			 * 'continue' here but potentially apply further
1027 			 * patching to insn. *insn should equal patch[1] now.
1028 			 */
1029 		}
1030 
1031 		if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) ||
1032 		    insn->code == (BPF_LDX | BPF_MEM | BPF_H) ||
1033 		    insn->code == (BPF_LDX | BPF_MEM | BPF_W) ||
1034 		    insn->code == (BPF_LDX | BPF_MEM | BPF_DW) ||
1035 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) ||
1036 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) ||
1037 		    insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) {
1038 			type = BPF_READ;
1039 		} else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) ||
1040 			   insn->code == (BPF_STX | BPF_MEM | BPF_H) ||
1041 			   insn->code == (BPF_STX | BPF_MEM | BPF_W) ||
1042 			   insn->code == (BPF_STX | BPF_MEM | BPF_DW) ||
1043 			   insn->code == (BPF_ST | BPF_MEM | BPF_B) ||
1044 			   insn->code == (BPF_ST | BPF_MEM | BPF_H) ||
1045 			   insn->code == (BPF_ST | BPF_MEM | BPF_W) ||
1046 			   insn->code == (BPF_ST | BPF_MEM | BPF_DW)) {
1047 			type = BPF_WRITE;
1048 		} else if ((insn->code == (BPF_STX | BPF_ATOMIC | BPF_B) ||
1049 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_H) ||
1050 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_W) ||
1051 			    insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW)) &&
1052 			   env->insn_aux_data[i + delta].ptr_type == PTR_TO_ARENA) {
1053 			insn->code = BPF_STX | BPF_PROBE_ATOMIC | BPF_SIZE(insn->code);
1054 			env->prog->aux->num_exentries++;
1055 			continue;
1056 		} else if (insn->code == (BPF_STX | BPF_ATOMIC | BPF_DW) &&
1057 			   insn->imm == BPF_LOAD_ACQ &&
1058 			   env->insn_aux_data[i + delta].arena_member) {
1059 			/* an acquire load of an __arena member is rewritten like a plain load */
1060 			cnt = arena_member_fixup(env, i + delta, insn, insn_buf);
1061 			if (cnt < 0)
1062 				return cnt;
1063 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
1064 			if (!new_prog)
1065 				return -ENOMEM;
1066 
1067 			delta    += cnt - 1;
1068 			env->prog = new_prog;
1069 			insn      = new_prog->insnsi + i + delta;
1070 			continue;
1071 		} else if (insn->code == (BPF_JMP | BPF_EXIT) &&
1072 			   epilogue_cnt &&
1073 			   i + delta < subprogs[1].start) {
1074 			/* Generate epilogue for the main prog */
1075 			if (epilogue_idx) {
1076 				/* jump back to the earlier generated epilogue */
1077 				insn_buf[0] = BPF_JMP32_A(epilogue_idx - i - delta - 1);
1078 				cnt = 1;
1079 			} else {
1080 				memcpy(insn_buf, epilogue_buf,
1081 				       epilogue_cnt * sizeof(*epilogue_buf));
1082 				cnt = epilogue_cnt;
1083 				/* epilogue_idx cannot be 0. It must have at
1084 				 * least one ctx ptr saving insn before the
1085 				 * epilogue.
1086 				 */
1087 				epilogue_idx = i + delta;
1088 			}
1089 			goto patch_insn_buf;
1090 		} else {
1091 			continue;
1092 		}
1093 
1094 		if (type == BPF_WRITE &&
1095 		    env->insn_aux_data[i + delta].nospec_result) {
1096 			/* nospec_result is only used to mitigate Spectre v4 and
1097 			 * to limit verification-time for Spectre v1.
1098 			 */
1099 			struct bpf_insn *patch = insn_buf;
1100 
1101 			*patch++ = *insn;
1102 			*patch++ = BPF_ST_NOSPEC();
1103 			cnt = patch - insn_buf;
1104 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
1105 			if (!new_prog)
1106 				return -ENOMEM;
1107 
1108 			delta    += cnt - 1;
1109 			env->prog = new_prog;
1110 			insn      = new_prog->insnsi + i + delta;
1111 			nospec_next = false;
1112 			continue;
1113 		}
1114 
1115 		ptr_type = env->insn_aux_data[i + delta].ptr_type;
1116 		switch ((int)ptr_type) {
1117 		case PTR_TO_CTX:
1118 			if (!ops->convert_ctx_access)
1119 				continue;
1120 			convert_ctx_access = ops->convert_ctx_access;
1121 			break;
1122 		case PTR_TO_SOCKET:
1123 		case PTR_TO_SOCK_COMMON:
1124 			convert_ctx_access = bpf_sock_convert_ctx_access;
1125 			break;
1126 		case PTR_TO_TCP_SOCK:
1127 			convert_ctx_access = bpf_tcp_sock_convert_ctx_access;
1128 			break;
1129 		case PTR_TO_XDP_SOCK:
1130 			convert_ctx_access = bpf_xdp_sock_convert_ctx_access;
1131 			break;
1132 		case PTR_TO_ARENA:
1133 			if (BPF_MODE(insn->code) == BPF_MEMSX) {
1134 				if (!bpf_jit_supports_insn(insn, true)) {
1135 					verbose(env, "sign extending loads from arena are not supported yet\n");
1136 					return -EOPNOTSUPP;
1137 				}
1138 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32SX | BPF_SIZE(insn->code);
1139 			} else {
1140 				insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code);
1141 			}
1142 			env->prog->aux->num_exentries++;
1143 			continue;
1144 		default:
1145 			/*
1146 			 * A pointer which may fault on a dereference must not
1147 			 * be loaded from without fault protection, hence turn
1148 			 * the BPF_LDX into a BPF_PROBE_MEM one so that a bad
1149 			 * address is handled rather than panicking the kernel.
1150 			 * A store through one is rejected earlier, there is no
1151 			 * probed counterpart to rewrite it into.
1152 			 */
1153 			if (bpf_is_ptr_to_mem_or_btf_id(ptr_type) &&
1154 			    bpf_may_fault_on_deref(ptr_type) &&
1155 			    type == BPF_READ) {
1156 				if (BPF_MODE(insn->code) == BPF_MEM)
1157 					insn->code = BPF_LDX | BPF_PROBE_MEM |
1158 						     BPF_SIZE(insn->code);
1159 				else
1160 					insn->code = BPF_LDX | BPF_PROBE_MEMSX |
1161 						     BPF_SIZE(insn->code);
1162 				env->prog->aux->num_exentries++;
1163 			} else if (verifier_bug_if(bpf_may_fault_on_deref(ptr_type), env,
1164 						   "access to a fault prone pointer is not rewritten as a probed one")) {
1165 				return -EFAULT;
1166 			}
1167 
1168 			cnt = arena_member_fixup(env, i + delta, insn, insn_buf);
1169 			if (cnt < 0)
1170 				return cnt;
1171 			if (!cnt)
1172 				continue;
1173 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
1174 			if (!new_prog)
1175 				return -ENOMEM;
1176 
1177 			delta    += cnt - 1;
1178 			env->prog = new_prog;
1179 			insn      = new_prog->insnsi + i + delta;
1180 			continue;
1181 		}
1182 
1183 		ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size;
1184 		size = BPF_LDST_BYTES(insn);
1185 		mode = BPF_MODE(insn->code);
1186 
1187 		/* If the read access is a narrower load of the field,
1188 		 * convert to a 4/8-byte load, to minimum program type specific
1189 		 * convert_ctx_access changes. If conversion is successful,
1190 		 * we will apply proper mask to the result.
1191 		 */
1192 		is_narrower_load = size < ctx_field_size;
1193 		size_default = bpf_ctx_off_adjust_machine(ctx_field_size);
1194 		off = insn->off;
1195 		if (is_narrower_load) {
1196 			u8 size_code;
1197 
1198 			if (type == BPF_WRITE) {
1199 				verifier_bug(env, "narrow ctx access misconfigured");
1200 				return -EFAULT;
1201 			}
1202 
1203 			size_code = BPF_H;
1204 			if (ctx_field_size == 4)
1205 				size_code = BPF_W;
1206 			else if (ctx_field_size == 8)
1207 				size_code = BPF_DW;
1208 
1209 			insn->off = off & ~(size_default - 1);
1210 			insn->code = BPF_LDX | BPF_MEM | size_code;
1211 		}
1212 
1213 		target_size = 0;
1214 		cnt = convert_ctx_access(type, insn, insn_buf, env->prog,
1215 					 &target_size);
1216 		if (cnt == 0 || cnt >= INSN_BUF_SIZE ||
1217 		    (ctx_field_size && !target_size)) {
1218 			verifier_bug(env, "error during ctx access conversion (%d)", cnt);
1219 			return -EFAULT;
1220 		}
1221 
1222 		if (is_narrower_load && size < target_size) {
1223 			u8 shift = bpf_ctx_narrow_access_offset(
1224 				off, size, size_default) * 8;
1225 			if (shift && cnt + 1 >= INSN_BUF_SIZE) {
1226 				verifier_bug(env, "narrow ctx load misconfigured");
1227 				return -EFAULT;
1228 			}
1229 			if (ctx_field_size <= 4) {
1230 				if (shift)
1231 					insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH,
1232 									insn->dst_reg,
1233 									shift);
1234 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
1235 								(1 << size * 8) - 1);
1236 			} else {
1237 				if (shift)
1238 					insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH,
1239 									insn->dst_reg,
1240 									shift);
1241 				insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg,
1242 								(1ULL << size * 8) - 1);
1243 			}
1244 		}
1245 		if (mode == BPF_MEMSX)
1246 			insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X,
1247 						       insn->dst_reg, insn->dst_reg,
1248 						       size * 8, 0);
1249 
1250 patch_insn_buf:
1251 		new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
1252 		if (!new_prog)
1253 			return -ENOMEM;
1254 
1255 		delta += cnt - 1;
1256 
1257 		/* keep walking new program and skip insns we just inserted */
1258 		env->prog = new_prog;
1259 		insn      = new_prog->insnsi + i + delta;
1260 	}
1261 
1262 	return 0;
1263 }
1264 
1265 static u32 *bpf_dup_subprog_starts(struct bpf_verifier_env *env)
1266 {
1267 	u32 *starts = NULL;
1268 
1269 	starts = kvmalloc_objs(u32, env->subprog_cnt, GFP_KERNEL_ACCOUNT);
1270 	if (starts) {
1271 		for (int i = 0; i < env->subprog_cnt; i++)
1272 			starts[i] = env->subprog_info[i].start;
1273 	}
1274 	return starts;
1275 }
1276 
1277 static void bpf_restore_subprog_starts(struct bpf_verifier_env *env, u32 *orig_starts)
1278 {
1279 	for (int i = 0; i < env->subprog_cnt; i++)
1280 		env->subprog_info[i].start = orig_starts[i];
1281 	/* restore the start of fake 'exit' subprog as well */
1282 	env->subprog_info[env->subprog_cnt].start = env->prog->len;
1283 }
1284 
1285 /*
1286  * Replace the offsets of functions with their addresses in the maps of
1287  * the program, see resolve_func_ptrs() in verifier.c. The program must be
1288  * the only user of such map. From now on no other program can use it, see
1289  * bpf_map_claim().
1290  */
1291 static int resolve_func_ptrs(struct bpf_verifier_env *env, struct bpf_prog *prog,
1292 			     struct bpf_prog **func)
1293 {
1294 	unsigned long me = (unsigned long)prog->aux;
1295 	struct bpf_func_ptr *ptr;
1296 	int i, err, subprog;
1297 	u64 addr, new, *slot;
1298 
1299 	for (i = 0; i < env->func_ptr_cnt; i++) {
1300 		ptr = &env->func_ptrs[i];
1301 
1302 		/* pointers are sorted by map */
1303 		if ((!i || ptr->map != ptr[-1].map) &&
1304 		    cmpxchg(&ptr->map->user, me, me | BPF_MAP_USER_PATCHED) != me) {
1305 			verbose(env, "map '%s' is used by another program\n", ptr->map->name);
1306 			return -EBUSY;
1307 		}
1308 
1309 		/* it's the address of the value of the map whatever the offset is */
1310 		err = ptr->map->ops->map_direct_value_addr(ptr->map, &addr, 0);
1311 		if (verifier_bug_if(err, env, "no value of map '%s'", ptr->map->name))
1312 			return -EFAULT;
1313 		slot = (u64 *)(unsigned long)(addr + ptr->map_off);
1314 
1315 		/*
1316 		 * The function that is dead code is removed and the pointer is
1317 		 * NULL. The program may read it, but callx of it is dead code
1318 		 * too, see check_func_callx().
1319 		 */
1320 		new = 0;
1321 		if (ptr->xlated_off != BPF_FUNC_PTR_DELETED) {
1322 			subprog = bpf_find_subprog(env, ptr->xlated_off);
1323 			if (verifier_bug_if(!func || subprog <= 0, env, "no function at insn %u",
1324 					    ptr->xlated_off))
1325 				return -EFAULT;
1326 			new = (unsigned long)func[subprog]->bpf_func;
1327 		}
1328 
1329 		/* the map is frozen and nothing else uses it */
1330 		if (verifier_bug_if(*slot != (u64)ptr->orig_off * sizeof(struct bpf_insn), env,
1331 				    "map '%s' offset %u changed", ptr->map->name, ptr->map_off))
1332 			return -EFAULT;
1333 		WRITE_ONCE(*slot, new);
1334 	}
1335 	return 0;
1336 }
1337 
1338 static int jit_subprogs(struct bpf_verifier_env *env)
1339 {
1340 	struct bpf_prog *prog = env->prog, **func, *tmp;
1341 	int i, j, subprog_start, subprog_end = 0, len, subprog;
1342 	struct bpf_map *map_ptr;
1343 	struct bpf_insn *insn;
1344 	void *old_bpf_func;
1345 	int err, num_exentries;
1346 
1347 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
1348 		if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn))
1349 			continue;
1350 
1351 		/* Upon error here we cannot fall back to interpreter but
1352 		 * need a hard reject of the program. Thus -EFAULT is
1353 		 * propagated in any case.
1354 		 */
1355 		subprog = bpf_find_subprog(env, i + insn->imm + 1);
1356 		if (verifier_bug_if(subprog < 0, env, "No program to jit at insn %d",
1357 				    i + insn->imm + 1))
1358 			return -EFAULT;
1359 		/* temporarily remember subprog id inside insn instead of
1360 		 * aux_data, since next loop will split up all insns into funcs
1361 		 */
1362 		insn->off = subprog;
1363 		/* remember original imm in case JIT fails and fallback
1364 		 * to interpreter will be needed
1365 		 */
1366 		env->insn_aux_data[i].call_imm = insn->imm;
1367 		/* point imm to __bpf_call_base+1 from JITs point of view */
1368 		insn->imm = 1;
1369 		if (bpf_pseudo_func(insn)) {
1370 #if defined(MODULES_VADDR)
1371 			u64 addr = MODULES_VADDR;
1372 #else
1373 			u64 addr = VMALLOC_START;
1374 #endif
1375 			/* jit (e.g. x86_64) may emit fewer instructions
1376 			 * if it learns a u32 imm is the same as a u64 imm.
1377 			 * Set close enough to possible prog address.
1378 			 */
1379 			insn[0].imm = (u32)addr;
1380 			insn[1].imm = addr >> 32;
1381 		}
1382 	}
1383 
1384 	err = bpf_prog_alloc_jited_linfo(prog);
1385 	if (err)
1386 		goto out_undo_insn;
1387 
1388 	err = -ENOMEM;
1389 	func = kzalloc_objs(prog, env->subprog_cnt);
1390 	if (!func)
1391 		goto out_undo_insn;
1392 
1393 	for (i = 0; i < env->subprog_cnt; i++) {
1394 		subprog_start = subprog_end;
1395 		subprog_end = env->subprog_info[i + 1].start;
1396 
1397 		len = subprog_end - subprog_start;
1398 		/* bpf_prog_run() doesn't call subprogs directly,
1399 		 * hence main prog stats include the runtime of subprogs.
1400 		 * subprogs don't have IDs and not reachable via prog_get_next_id
1401 		 * func[i]->stats will never be accessed and stays NULL
1402 		 */
1403 		func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER);
1404 		if (!func[i])
1405 			goto out_free;
1406 		memcpy(func[i]->insnsi, &prog->insnsi[subprog_start],
1407 		       len * sizeof(struct bpf_insn));
1408 		func[i]->type = prog->type;
1409 		func[i]->len = len;
1410 		if (bpf_prog_calc_tag(func[i]))
1411 			goto out_free;
1412 		func[i]->is_func = 1;
1413 		func[i]->sleepable = prog->sleepable;
1414 		func[i]->blinded = prog->blinded;
1415 		func[i]->aux->func_idx = i;
1416 		/* Below members will be freed only at prog->aux */
1417 		func[i]->aux->btf = prog->aux->btf;
1418 		func[i]->aux->subprog_start = subprog_start;
1419 		func[i]->aux->func_info = prog->aux->func_info;
1420 		func[i]->aux->func_info_cnt = prog->aux->func_info_cnt;
1421 		func[i]->aux->poke_tab = prog->aux->poke_tab;
1422 		func[i]->aux->size_poke_tab = prog->aux->size_poke_tab;
1423 		func[i]->aux->main_prog_aux = prog->aux;
1424 
1425 		for (j = 0; j < prog->aux->size_poke_tab; j++) {
1426 			struct bpf_jit_poke_descriptor *poke;
1427 
1428 			poke = &prog->aux->poke_tab[j];
1429 			if (poke->insn_idx < subprog_end &&
1430 			    poke->insn_idx >= subprog_start)
1431 				poke->aux = func[i]->aux;
1432 		}
1433 
1434 		func[i]->aux->name[0] = 'F';
1435 		func[i]->aux->stack_depth = env->subprog_info[i].stack_depth;
1436 		if (env->subprog_info[i].priv_stack_mode == PRIV_STACK_ADAPTIVE)
1437 			func[i]->aux->jits_use_priv_stack = true;
1438 
1439 		func[i]->jit_requested = 1;
1440 		func[i]->blinding_requested = prog->blinding_requested;
1441 		func[i]->aux->kfunc_tab = prog->aux->kfunc_tab;
1442 		func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab;
1443 		func[i]->aux->linfo = prog->aux->linfo;
1444 		func[i]->aux->nr_linfo = prog->aux->nr_linfo;
1445 		func[i]->aux->jited_linfo = prog->aux->jited_linfo;
1446 		func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx;
1447 		func[i]->aux->arena = prog->aux->arena;
1448 		func[i]->aux->uses_arena_insns = bpf_prog_has_arena_insns(func[i]);
1449 		func[i]->aux->used_maps = env->used_maps;
1450 		func[i]->aux->used_map_cnt = env->used_map_cnt;
1451 		num_exentries = 0;
1452 		insn = func[i]->insnsi;
1453 		for (j = 0; j < func[i]->len; j++, insn++) {
1454 			if (BPF_CLASS(insn->code) == BPF_LDX &&
1455 			    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
1456 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32 ||
1457 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32SX ||
1458 			     BPF_MODE(insn->code) == BPF_PROBE_MEMSX))
1459 				num_exentries++;
1460 			if ((BPF_CLASS(insn->code) == BPF_STX ||
1461 			     BPF_CLASS(insn->code) == BPF_ST) &&
1462 			     BPF_MODE(insn->code) == BPF_PROBE_MEM32)
1463 				num_exentries++;
1464 			if (BPF_CLASS(insn->code) == BPF_STX &&
1465 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
1466 				num_exentries++;
1467 			if (bpf_is_unwind_goto(insn))
1468 				num_exentries++;
1469 		}
1470 		func[i]->aux->num_exentries = num_exentries;
1471 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
1472 		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
1473 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
1474 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
1475 		func[i]->aux->can_unwind = env->subprog_info[i].can_unwind;
1476 		func[i]->aux->token = prog->aux->token;
1477 		if (!i)
1478 			func[i]->aux->exception_boundary = env->seen_exception;
1479 		func[i] = bpf_int_jit_compile(env, func[i]);
1480 		if (!func[i]->jited) {
1481 			err = -ENOTSUPP;
1482 			goto out_free;
1483 		}
1484 		cond_resched();
1485 	}
1486 
1487 	/* at this point all bpf functions were successfully JITed
1488 	 * now populate all bpf_calls with correct addresses and
1489 	 * run last pass of JIT
1490 	 */
1491 	for (i = 0; i < env->subprog_cnt; i++) {
1492 		insn = func[i]->insnsi;
1493 		for (j = 0; j < func[i]->len; j++, insn++) {
1494 			if (bpf_pseudo_func(insn)) {
1495 				subprog = insn->off;
1496 				insn[0].imm = (u32)(long)func[subprog]->bpf_func;
1497 				insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32;
1498 				continue;
1499 			}
1500 			if (!bpf_pseudo_call(insn))
1501 				continue;
1502 			subprog = insn->off;
1503 			insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func);
1504 		}
1505 
1506 		/* we use the aux data to keep a list of the start addresses
1507 		 * of the JITed images for each function in the program
1508 		 *
1509 		 * for some architectures, such as powerpc64, the imm field
1510 		 * might not be large enough to hold the offset of the start
1511 		 * address of the callee's JITed image from __bpf_call_base
1512 		 *
1513 		 * in such cases, we can lookup the start address of a callee
1514 		 * by using its subprog id, available from the off field of
1515 		 * the call instruction, as an index for this list
1516 		 */
1517 		func[i]->aux->func = func;
1518 		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
1519 		func[i]->aux->real_func_cnt = env->subprog_cnt;
1520 	}
1521 	for (i = 0; i < env->subprog_cnt; i++) {
1522 		old_bpf_func = func[i]->bpf_func;
1523 		tmp = bpf_int_jit_compile(env, func[i]);
1524 		if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) {
1525 			verbose(env, "JIT doesn't support bpf-to-bpf calls\n");
1526 			err = -ENOTSUPP;
1527 			goto out_free;
1528 		}
1529 		cond_resched();
1530 	}
1531 
1532 	/* the addresses of all functions are final */
1533 	err = resolve_func_ptrs(env, prog, func);
1534 	if (err)
1535 		goto out_free;
1536 
1537 	/*
1538 	 * Cleanup func[i]->aux fields which aren't required
1539 	 * or can become invalid in future
1540 	 */
1541 	for (i = 0; i < env->subprog_cnt; i++) {
1542 		func[i]->aux->used_maps = NULL;
1543 		func[i]->aux->used_map_cnt = 0;
1544 	}
1545 
1546 	/* finally lock prog and jit images for all functions and
1547 	 * populate kallsysm. Begin at the first subprogram, since
1548 	 * bpf_prog_load will add the kallsyms for the main program.
1549 	 */
1550 	for (i = 1; i < env->subprog_cnt; i++) {
1551 		err = bpf_prog_lock_ro(func[i]);
1552 		if (err)
1553 			goto out_free;
1554 	}
1555 
1556 	for (i = 1; i < env->subprog_cnt; i++)
1557 		bpf_prog_kallsyms_add(func[i]);
1558 
1559 	/* Last step: make now unused interpreter insns from main
1560 	 * prog consistent for later dump requests, so they can
1561 	 * later look the same as if they were interpreted only.
1562 	 */
1563 	for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
1564 		if (bpf_pseudo_func(insn)) {
1565 			insn[0].imm = env->insn_aux_data[i].call_imm;
1566 			insn[1].imm = insn->off;
1567 			insn->off = 0;
1568 			continue;
1569 		}
1570 		if (!bpf_pseudo_call(insn))
1571 			continue;
1572 		insn->imm = env->insn_aux_data[i].call_imm;
1573 		subprog = bpf_find_subprog(env, i + insn->imm + 1);
1574 		insn->off = subprog;
1575 	}
1576 
1577 	prog->jited = 1;
1578 	prog->bpf_func = func[0]->bpf_func;
1579 	prog->jited_len = func[0]->jited_len;
1580 	prog->aux->extable = func[0]->aux->extable;
1581 	prog->aux->num_exentries = func[0]->aux->num_exentries;
1582 	prog->aux->ksym.fp_start = func[0]->aux->ksym.fp_start;
1583 	prog->aux->ksym.fp_end = func[0]->aux->ksym.fp_end;
1584 	prog->aux->ksym.fp_ret = func[0]->aux->ksym.fp_ret;
1585 	prog->aux->func = func;
1586 	prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
1587 	prog->aux->real_func_cnt = env->subprog_cnt;
1588 	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
1589 	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
1590 	prog->aux->stack_arg_sp_adjust = func[0]->aux->stack_arg_sp_adjust;
1591 	bpf_prog_jit_attempt_done(prog);
1592 	return 0;
1593 out_free:
1594 	/* We failed JIT'ing, so at this point we need to unregister poke
1595 	 * descriptors from subprogs, so that kernel is not attempting to
1596 	 * patch it anymore as we're freeing the subprog JIT memory.
1597 	 */
1598 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
1599 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
1600 		map_ptr->ops->map_poke_untrack(map_ptr, prog->aux);
1601 	}
1602 	/* At this point we're guaranteed that poke descriptors are not
1603 	 * live anymore. We can just unlink its descriptor table as it's
1604 	 * released with the main prog.
1605 	 */
1606 	for (i = 0; i < env->subprog_cnt; i++) {
1607 		if (!func[i])
1608 			continue;
1609 		func[i]->aux->poke_tab = NULL;
1610 		bpf_jit_free(func[i]);
1611 	}
1612 	kfree(func);
1613 out_undo_insn:
1614 	bpf_prog_jit_attempt_done(prog);
1615 	return err;
1616 }
1617 
1618 int bpf_jit_subprogs(struct bpf_verifier_env *env)
1619 {
1620 	int err, i;
1621 	bool blinded = false;
1622 	struct bpf_insn *insn;
1623 	struct bpf_prog *prog, *orig_prog;
1624 	u32 *orig_subprog_starts;
1625 
1626 	/* all functions that the maps point to are removed as dead code */
1627 	if (env->subprog_cnt <= 1)
1628 		return resolve_func_ptrs(env, env->prog, NULL);
1629 
1630 	prog = orig_prog = env->prog;
1631 	if (bpf_prog_need_blind(prog)) {
1632 		orig_subprog_starts = bpf_dup_subprog_starts(env);
1633 		if (!orig_subprog_starts) {
1634 			err = -ENOMEM;
1635 			goto out_cleanup;
1636 		}
1637 		prog = bpf_jit_blind_constants(env, prog);
1638 		if (IS_ERR(prog)) {
1639 			err = PTR_ERR(prog);
1640 			prog = orig_prog;
1641 			goto out_restore;
1642 		}
1643 		blinded = true;
1644 	}
1645 
1646 	err = jit_subprogs(env);
1647 	if (err)
1648 		goto out_jit_err;
1649 
1650 	if (blinded) {
1651 		bpf_jit_prog_release_other(prog, orig_prog);
1652 		kvfree(orig_subprog_starts);
1653 	}
1654 
1655 	return 0;
1656 
1657 out_jit_err:
1658 	if (blinded) {
1659 		bpf_jit_prog_release_other(orig_prog, prog);
1660 		/* roll back to the clean original prog */
1661 		prog = env->prog = orig_prog;
1662 		goto out_restore;
1663 	} else {
1664 		if (err != -EFAULT) {
1665 			/*
1666 			 * We will fall back to interpreter mode when err is not -EFAULT, before
1667 			 * that, insn->off and insn->imm should be restored to their original
1668 			 * values since they were modified by jit_subprogs.
1669 			 */
1670 			for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) {
1671 				if (!bpf_pseudo_call(insn))
1672 					continue;
1673 				insn->off = 0;
1674 				insn->imm = env->insn_aux_data[i].call_imm;
1675 			}
1676 		}
1677 		goto out_cleanup;
1678 	}
1679 
1680 out_restore:
1681 	bpf_restore_subprog_starts(env, orig_subprog_starts);
1682 	kvfree(orig_subprog_starts);
1683 out_cleanup:
1684 	/* cleanup main prog to be interpreted */
1685 	prog->jit_requested = 0;
1686 	prog->blinding_requested = 0;
1687 	return err;
1688 }
1689 
1690 int bpf_fixup_call_args(struct bpf_verifier_env *env)
1691 {
1692 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1693 	struct bpf_prog *prog = env->prog;
1694 	struct bpf_insn *insn = prog->insnsi;
1695 	int depth;
1696 #endif
1697 	int i, err = 0;
1698 
1699 	for (i = 0; i < env->subprog_cnt; i++) {
1700 		struct bpf_subprog_info *subprog = &env->subprog_info[i];
1701 		u16 outgoing = subprog->stack_arg_cnt - bpf_in_stack_arg_cnt(subprog);
1702 
1703 		if (subprog->max_out_stack_arg_cnt > outgoing) {
1704 			verbose(env,
1705 				"func#%d writes %u stack arg slots, but calls only require %u\n",
1706 				i, subprog->max_out_stack_arg_cnt, outgoing);
1707 			return -EINVAL;
1708 		}
1709 	}
1710 
1711 	if (env->prog->jit_requested &&
1712 	    !bpf_prog_is_offloaded(env->prog->aux)) {
1713 		err = bpf_jit_subprogs(env);
1714 		if (err == 0)
1715 			return 0;
1716 		if (err == -EFAULT || err == -EINTR)
1717 			return err;
1718 	}
1719 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
1720 	if (prog->jit_required) {
1721 		verbose(env, "program requires BPF JIT compiler but it is not available\n");
1722 		return -EINVAL;
1723 	}
1724 	for (i = 0; i < env->subprog_cnt; i++) {
1725 		if (bpf_in_stack_arg_cnt(&env->subprog_info[i])) {
1726 			verbose(env, "stack args are not supported in non-JITed programs\n");
1727 			return -EINVAL;
1728 		}
1729 	}
1730 	if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) {
1731 		/* When JIT fails the progs with bpf2bpf calls and tail_calls
1732 		 * have to be rejected, since interpreter doesn't support them yet.
1733 		 */
1734 		verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n");
1735 		return -EINVAL;
1736 	}
1737 	for (i = 0; i < prog->len; i++, insn++) {
1738 		if (bpf_pseudo_func(insn)) {
1739 			/* When JIT fails the progs with callback calls
1740 			 * have to be rejected, since interpreter doesn't support them yet.
1741 			 */
1742 			verbose(env, "callbacks are not allowed in non-JITed programs\n");
1743 			return -EINVAL;
1744 		}
1745 
1746 		if (!bpf_pseudo_call(insn))
1747 			continue;
1748 		depth = get_callee_stack_depth(env, insn, i);
1749 		if (depth < 0)
1750 			return depth;
1751 		err = bpf_patch_call_args(insn, depth);
1752 		if (err) {
1753 			verbose(env, "stack depth %d exceeds interpreter stack depth limit\n",
1754 				depth);
1755 			return err;
1756 		}
1757 	}
1758 	err = 0;
1759 #endif
1760 	return err;
1761 }
1762 
1763 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */
1764 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
1765 {
1766 	struct bpf_subprog_info *info = env->subprog_info;
1767 	int cnt = env->subprog_cnt;
1768 	struct bpf_prog *prog;
1769 
1770 	/* We only reserve one slot for hidden subprogs in subprog_info. */
1771 	if (env->hidden_subprog_cnt) {
1772 		verifier_bug(env, "only one hidden subprog supported");
1773 		return -EFAULT;
1774 	}
1775 	/* We're not patching any existing instruction, just appending the new
1776 	 * ones for the hidden subprog. Hence all of the adjustment operations
1777 	 * in bpf_patch_insn_data are no-ops.
1778 	 */
1779 	prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len);
1780 	if (!prog)
1781 		return -ENOMEM;
1782 	env->prog = prog;
1783 	info[cnt + 1].start = info[cnt].start;
1784 	info[cnt].start = prog->len - len + 1;
1785 	/* The patch ends with the exit. */
1786 	info[cnt].exit_idx = prog->len - 1;
1787 	env->subprog_cnt++;
1788 	env->hidden_subprog_cnt++;
1789 	return 0;
1790 }
1791 
1792 /*
1793  * Expand may_goto: load the count from the stack, jump to the target of
1794  * may_goto when it is zero, then the tail that updates the count.
1795  * Use gotol when the target is too far for 16-bit offset of a conditional jump.
1796  */
1797 static int may_goto_expand(struct bpf_insn *insn_buf, int off, int stack_off,
1798 			   const struct bpf_insn *tail, int tail_cnt)
1799 {
1800 	int cnt = 0;
1801 
1802 	/* Forward jump has to step over the tail */
1803 	off = off >= 0 ? off + tail_cnt : off - 1;
1804 
1805 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off);
1806 	if (off == (s16)off) {
1807 		insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, off);
1808 	} else {
1809 		insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 1);
1810 		insn_buf[cnt++] = BPF_JMP32_A(off >= 0 ? off : off - 1);
1811 	}
1812 	memcpy(insn_buf + cnt, tail, tail_cnt * sizeof(*tail));
1813 	return cnt + tail_cnt;
1814 }
1815 
1816 /*
1817  * Timed may_goto. All may_goto of a prog use one count and one timestamp: per-cpu memory of the
1818  * prog, set in the first insns of the main prog, and by the callers of async callbacks.
1819  * @reg holds the address. It is a register that is dead at the may_goto, or R0 that is saved at
1820  * @save_off in the stack.
1821  */
1822 static int may_goto_expand_timed(struct bpf_insn *insn_buf, int off,
1823 				 struct bpf_timed_may_goto __percpu *tmg, int reg, int save_off)
1824 {
1825 	struct bpf_insn ld_tmg[] = { BPF_LD_IMM64(reg, (__force unsigned long)tmg) };
1826 	int cnt = 0, jmp, tail_cnt = save_off ? 6 : 5;
1827 
1828 	if (save_off)
1829 		insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, reg, save_off);
1830 	insn_buf[cnt++] = ld_tmg[0];
1831 	insn_buf[cnt++] = ld_tmg[1];
1832 	insn_buf[cnt++] = BPF_MOV64_PERCPU_REG(reg, reg);
1833 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, reg, 0);
1834 	if (save_off) {
1835 		insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
1836 		insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_10, save_off);
1837 		jmp = cnt++;
1838 		insn_buf[jmp] = BPF_JMP32_A(off >= 0 ? off + tail_cnt : off - jmp);
1839 	} else {
1840 		jmp = cnt;
1841 		off = off >= 0 ? off + tail_cnt : off - jmp;
1842 		if (off == (s16)off) {
1843 			insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, off);
1844 		} else {
1845 			insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 1);
1846 			insn_buf[cnt++] = BPF_JMP32_A(off >= 0 ? off : off - 1);
1847 		}
1848 	}
1849 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1);
1850 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 2);
1851 	/* AX is the argument and the return value */
1852 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_AX, reg);
1853 	insn_buf[cnt++] = BPF_EMIT_CALL(arch_bpf_timed_may_goto);
1854 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, reg, BPF_REG_AX, 0);
1855 	if (save_off)
1856 		insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_10, save_off);
1857 	return cnt;
1858 }
1859 
1860 /* Do various post-verification rewrites in a single program pass.
1861  * These rewrites simplify JIT and interpreter implementations.
1862  */
1863 int bpf_do_misc_fixups(struct bpf_verifier_env *env)
1864 {
1865 	struct bpf_prog *prog = env->prog;
1866 	enum bpf_attach_type eatype = prog->expected_attach_type;
1867 	enum bpf_prog_type prog_type = resolve_prog_type(prog);
1868 	struct bpf_insn *insn = prog->insnsi;
1869 	const struct bpf_func_proto *fn;
1870 	const int insn_cnt = prog->len;
1871 	const struct bpf_map_ops *ops;
1872 	struct bpf_insn_aux_data *aux;
1873 	struct bpf_insn *insn_buf = env->insn_buf;
1874 	struct bpf_prog *new_prog;
1875 	struct bpf_map *map_ptr;
1876 	int i, ret, cnt, delta = 0, cur_subprog = 0;
1877 	struct bpf_subprog_info *subprogs = env->subprog_info;
1878 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
1879 	u16 stack_depth_extra = 0;
1880 	/* arch_bpf_timed_may_goto() takes and returns AX in a cpu register: for JITs only */
1881 	bool timed_may_goto = prog->jit_requested && bpf_jit_supports_timed_may_goto();
1882 	struct bpf_timed_may_goto __percpu *tmg = NULL;
1883 
1884 	if (env->seen_exception && !env->exception_callback_subprog) {
1885 		struct bpf_insn *patch = insn_buf;
1886 
1887 		*patch++ = env->prog->insnsi[insn_cnt - 1];
1888 		*patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
1889 		*patch++ = BPF_EXIT_INSN();
1890 		ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
1891 		if (ret < 0)
1892 			return ret;
1893 		prog = env->prog;
1894 		insn = prog->insnsi;
1895 
1896 		env->exception_callback_subprog = env->subprog_cnt - 1;
1897 		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
1898 		bpf_mark_subprog_exc_cb(env, env->exception_callback_subprog);
1899 	}
1900 
1901 	for (i = 0; i < insn_cnt;) {
1902 		if (is_addr_space_cast32(env->prog, insn)) {
1903 			/* convert to 32-bit mov that clears upper 32-bit */
1904 			insn->code = BPF_ALU | BPF_MOV | BPF_X;
1905 			/* clear off and imm, so it's a normal 'wX = wY' from JIT pov */
1906 			insn->off = 0;
1907 			insn->imm = 0;
1908 			goto next_insn;
1909 		}
1910 
1911 		if (env->insn_aux_data[i + delta].needs_zext)
1912 			/* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */
1913 			insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code);
1914 
1915 		/* Make sdiv/smod divide-by-minus-one exceptions impossible. */
1916 		if ((insn->code == (BPF_ALU64 | BPF_MOD | BPF_K) ||
1917 		     insn->code == (BPF_ALU64 | BPF_DIV | BPF_K) ||
1918 		     insn->code == (BPF_ALU | BPF_MOD | BPF_K) ||
1919 		     insn->code == (BPF_ALU | BPF_DIV | BPF_K)) &&
1920 		    insn->off == 1 && insn->imm == -1) {
1921 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
1922 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
1923 			struct bpf_insn *patch = insn_buf;
1924 
1925 			if (isdiv)
1926 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
1927 							BPF_NEG | BPF_K, insn->dst_reg,
1928 							0, 0, 0);
1929 			else
1930 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
1931 
1932 			cnt = patch - insn_buf;
1933 
1934 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
1935 			if (!new_prog)
1936 				return -ENOMEM;
1937 
1938 			delta    += cnt - 1;
1939 			env->prog = prog = new_prog;
1940 			insn      = new_prog->insnsi + i + delta;
1941 			goto next_insn;
1942 		}
1943 
1944 		/* Make divide-by-zero and divide-by-minus-one exceptions impossible. */
1945 		if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) ||
1946 		    insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) ||
1947 		    insn->code == (BPF_ALU | BPF_MOD | BPF_X) ||
1948 		    insn->code == (BPF_ALU | BPF_DIV | BPF_X)) {
1949 			bool is64 = BPF_CLASS(insn->code) == BPF_ALU64;
1950 			bool isdiv = BPF_OP(insn->code) == BPF_DIV;
1951 			bool is_sdiv = isdiv && insn->off == 1;
1952 			bool is_smod = !isdiv && insn->off == 1;
1953 			struct bpf_insn *patch = insn_buf;
1954 
1955 			if (is_sdiv) {
1956 				/* [R,W]x sdiv 0 -> 0
1957 				 * LLONG_MIN sdiv -1 -> LLONG_MIN
1958 				 * INT_MIN sdiv -1 -> INT_MIN
1959 				 */
1960 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
1961 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
1962 							BPF_ADD | BPF_K, BPF_REG_AX,
1963 							0, 0, 1);
1964 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
1965 							BPF_JGT | BPF_K, BPF_REG_AX,
1966 							0, 4, 1);
1967 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
1968 							BPF_JEQ | BPF_K, BPF_REG_AX,
1969 							0, 1, 0);
1970 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
1971 							BPF_MOV | BPF_K, insn->dst_reg,
1972 							0, 0, 0);
1973 				/* BPF_NEG(LLONG_MIN) == -LLONG_MIN == LLONG_MIN */
1974 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
1975 							BPF_NEG | BPF_K, insn->dst_reg,
1976 							0, 0, 0);
1977 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
1978 				*patch++ = *insn;
1979 				cnt = patch - insn_buf;
1980 			} else if (is_smod) {
1981 				/* [R,W]x mod 0 -> [R,W]x */
1982 				/* [R,W]x mod -1 -> 0 */
1983 				*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
1984 				*patch++ = BPF_RAW_INSN((is64 ? BPF_ALU64 : BPF_ALU) |
1985 							BPF_ADD | BPF_K, BPF_REG_AX,
1986 							0, 0, 1);
1987 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
1988 							BPF_JGT | BPF_K, BPF_REG_AX,
1989 							0, 3, 1);
1990 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
1991 							BPF_JEQ | BPF_K, BPF_REG_AX,
1992 							0, 3 + (is64 ? 0 : 1), 1);
1993 				*patch++ = BPF_MOV32_IMM(insn->dst_reg, 0);
1994 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
1995 				*patch++ = *insn;
1996 
1997 				if (!is64) {
1998 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
1999 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
2000 				}
2001 				cnt = patch - insn_buf;
2002 			} else if (isdiv) {
2003 				/* [R,W]x div 0 -> 0 */
2004 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
2005 							BPF_JNE | BPF_K, insn->src_reg,
2006 							0, 2, 0);
2007 				*patch++ = BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg);
2008 				*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
2009 				*patch++ = *insn;
2010 				cnt = patch - insn_buf;
2011 			} else {
2012 				/* [R,W]x mod 0 -> [R,W]x */
2013 				*patch++ = BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) |
2014 							BPF_JEQ | BPF_K, insn->src_reg,
2015 							0, 1 + (is64 ? 0 : 1), 0);
2016 				*patch++ = *insn;
2017 
2018 				if (!is64) {
2019 					*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
2020 					*patch++ = BPF_MOV32_REG(insn->dst_reg, insn->dst_reg);
2021 				}
2022 				cnt = patch - insn_buf;
2023 			}
2024 
2025 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2026 			if (!new_prog)
2027 				return -ENOMEM;
2028 
2029 			delta    += cnt - 1;
2030 			env->prog = prog = new_prog;
2031 			insn      = new_prog->insnsi + i + delta;
2032 			goto next_insn;
2033 		}
2034 
2035 		/* Make it impossible to de-reference a userspace address */
2036 		if (BPF_CLASS(insn->code) == BPF_LDX &&
2037 		    (BPF_MODE(insn->code) == BPF_PROBE_MEM ||
2038 		     BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) {
2039 			struct bpf_insn *patch = insn_buf;
2040 			u64 uaddress_limit = bpf_arch_uaddress_limit();
2041 
2042 			if (!uaddress_limit)
2043 				goto next_insn;
2044 
2045 			*patch++ = BPF_MOV64_REG(BPF_REG_AX, insn->src_reg);
2046 			if (insn->off)
2047 				*patch++ = BPF_ALU64_IMM(BPF_ADD, BPF_REG_AX, insn->off);
2048 			*patch++ = BPF_ALU64_IMM(BPF_RSH, BPF_REG_AX, 32);
2049 			*patch++ = BPF_JMP_IMM(BPF_JLE, BPF_REG_AX, uaddress_limit >> 32, 2);
2050 			*patch++ = *insn;
2051 			*patch++ = BPF_JMP_IMM(BPF_JA, 0, 0, 1);
2052 			*patch++ = BPF_MOV64_IMM(insn->dst_reg, 0);
2053 
2054 			cnt = patch - insn_buf;
2055 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2056 			if (!new_prog)
2057 				return -ENOMEM;
2058 
2059 			delta    += cnt - 1;
2060 			env->prog = prog = new_prog;
2061 			insn      = new_prog->insnsi + i + delta;
2062 			goto next_insn;
2063 		}
2064 
2065 		/* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */
2066 		if (BPF_CLASS(insn->code) == BPF_LD &&
2067 		    (BPF_MODE(insn->code) == BPF_ABS ||
2068 		     BPF_MODE(insn->code) == BPF_IND)) {
2069 			cnt = env->ops->gen_ld_abs(insn, insn_buf);
2070 			if (cnt == 0 || cnt >= INSN_BUF_SIZE) {
2071 				verifier_bug(env, "%d insns generated for ld_abs", cnt);
2072 				return -EFAULT;
2073 			}
2074 
2075 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2076 			if (!new_prog)
2077 				return -ENOMEM;
2078 
2079 			delta    += cnt - 1;
2080 			env->prog = prog = new_prog;
2081 			insn      = new_prog->insnsi + i + delta;
2082 			goto next_insn;
2083 		}
2084 
2085 		/* Rewrite pointer arithmetic to mitigate speculation attacks. */
2086 		if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) ||
2087 		    insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) {
2088 			const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X;
2089 			const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X;
2090 			struct bpf_insn *patch = insn_buf;
2091 			bool issrc, isneg, isimm;
2092 			u32 off_reg;
2093 
2094 			aux = &env->insn_aux_data[i + delta];
2095 			if (!aux->alu_state ||
2096 			    aux->alu_state == BPF_ALU_NON_POINTER)
2097 				goto next_insn;
2098 
2099 			isneg = aux->alu_state & BPF_ALU_NEG_VALUE;
2100 			issrc = (aux->alu_state & BPF_ALU_SANITIZE) ==
2101 				BPF_ALU_SANITIZE_SRC;
2102 			isimm = aux->alu_state & BPF_ALU_IMMEDIATE;
2103 
2104 			off_reg = issrc ? insn->src_reg : insn->dst_reg;
2105 			if (isimm) {
2106 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
2107 			} else {
2108 				if (isneg)
2109 					*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
2110 				*patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit);
2111 				*patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg);
2112 				*patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg);
2113 				*patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0);
2114 				*patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63);
2115 				*patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg);
2116 			}
2117 			if (!issrc)
2118 				*patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg);
2119 			insn->src_reg = BPF_REG_AX;
2120 			if (isneg)
2121 				insn->code = insn->code == code_add ?
2122 					     code_sub : code_add;
2123 			*patch++ = *insn;
2124 			if (issrc && isneg && !isimm)
2125 				*patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1);
2126 			cnt = patch - insn_buf;
2127 
2128 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2129 			if (!new_prog)
2130 				return -ENOMEM;
2131 
2132 			delta    += cnt - 1;
2133 			env->prog = prog = new_prog;
2134 			insn      = new_prog->insnsi + i + delta;
2135 			goto next_insn;
2136 		}
2137 
2138 		if (bpf_is_may_goto_insn(insn) && timed_may_goto) {
2139 			u16 live = env->insn_aux_data[i + delta].live_regs_before;
2140 			int reg, save_off = 0;
2141 
2142 			/* a register that is dead here holds the address of the count */
2143 			for (reg = BPF_REG_0; reg <= BPF_REG_9; reg++)
2144 				if (!(live & BIT(reg)))
2145 					break;
2146 			if (reg > BPF_REG_9) {
2147 				reg = BPF_REG_0;
2148 				save_off = -stack_depth - 8;
2149 				stack_depth_extra = 8;
2150 			}
2151 			if (!tmg) {
2152 				tmg = alloc_percpu_gfp(struct bpf_timed_may_goto,
2153 						       GFP_KERNEL_ACCOUNT);
2154 				if (!tmg)
2155 					return -ENOMEM;
2156 				prog->aux->timed_may_goto = tmg;
2157 			}
2158 			prog->jit_required = 1;
2159 			cnt = may_goto_expand_timed(insn_buf, insn->off, tmg, reg, save_off);
2160 
2161 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2162 			if (!new_prog)
2163 				return -ENOMEM;
2164 
2165 			delta += cnt - 1;
2166 			env->prog = prog = new_prog;
2167 			insn = new_prog->insnsi + i + delta;
2168 			goto next_insn;
2169 		} else if (bpf_is_may_goto_insn(insn)) {
2170 			int stack_off = -stack_depth - 8;
2171 			struct bpf_insn tail[] = {
2172 				BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1),
2173 				BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off),
2174 			};
2175 
2176 			stack_depth_extra = 8;
2177 			cnt = may_goto_expand(insn_buf, insn->off, stack_off,
2178 					      tail, ARRAY_SIZE(tail));
2179 
2180 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2181 			if (!new_prog)
2182 				return -ENOMEM;
2183 
2184 			delta += cnt - 1;
2185 			env->prog = prog = new_prog;
2186 			insn = new_prog->insnsi + i + delta;
2187 			goto next_insn;
2188 		}
2189 
2190 		if (bpf_jit_supports_percpu_insn() &&
2191 		    insn->code == (BPF_LD | BPF_IMM | BPF_DW) &&
2192 		    (insn->src_reg == BPF_PSEUDO_MAP_VALUE ||
2193 		     insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE)) {
2194 			struct bpf_map *map;
2195 
2196 			aux = &env->insn_aux_data[i + delta];
2197 			map = env->used_maps[aux->map_index];
2198 			if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY)
2199 				goto next_insn;
2200 
2201 			prog->jit_required = true;
2202 
2203 			/*
2204 			 * We are *skipping* first half of ld_imm64 insn
2205 			 * with 'i++;', patching over second half of it
2206 			 * with that same half + mov64_percpu_reg insn.
2207 			 * All because bpf_patch_insn_data() can only
2208 			 * replace one 8-byte insn, which does not work
2209 			 * well for ld_imm64 insn.
2210 			 */
2211 
2212 			insn_buf[0] = insn[1];
2213 			insn_buf[1] = BPF_MOV64_PERCPU_REG(insn->dst_reg, insn->dst_reg);
2214 			cnt = 2;
2215 
2216 			i++;
2217 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2218 			if (!new_prog)
2219 				return -ENOMEM;
2220 
2221 			delta    += cnt - 1;
2222 			env->prog = prog = new_prog;
2223 			insn      = new_prog->insnsi + i + delta;
2224 			goto next_insn;
2225 		}
2226 
2227 		if (insn->code != (BPF_JMP | BPF_CALL))
2228 			goto next_insn;
2229 		if (insn->src_reg == BPF_PSEUDO_CALL)
2230 			goto next_insn;
2231 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
2232 			ret = bpf_fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt);
2233 			if (ret)
2234 				return ret;
2235 			if (cnt == 0)
2236 				goto next_insn;
2237 
2238 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2239 			if (!new_prog)
2240 				return -ENOMEM;
2241 
2242 			delta	 += cnt - 1;
2243 			env->prog = prog = new_prog;
2244 			insn	  = new_prog->insnsi + i + delta;
2245 			goto next_insn;
2246 		}
2247 
2248 		/* Skip inlining the helper call if the JIT does it. */
2249 		if (bpf_jit_inlines_helper_call(insn->imm)) {
2250 			prog->jit_required = 1;
2251 			goto next_insn;
2252 		}
2253 
2254 		if (insn->imm == BPF_FUNC_get_route_realm)
2255 			prog->dst_needed = 1;
2256 		if (insn->imm == BPF_FUNC_get_prandom_u32)
2257 			bpf_user_rnd_init_once();
2258 		if (insn->imm == BPF_FUNC_override_return)
2259 			prog->kprobe_override = 1;
2260 		if (insn->imm == BPF_FUNC_tail_call) {
2261 			/* If we tail call into other programs, we
2262 			 * cannot make any assumptions since they can
2263 			 * be replaced dynamically during runtime in
2264 			 * the program array.
2265 			 */
2266 			prog->cb_access = 1;
2267 			prog->call_get_func_ip = 1;
2268 			if (prog_type == BPF_PROG_TYPE_TRACING &&
2269 			    (eatype == BPF_TRACE_FSESSION || eatype == BPF_TRACE_FSESSION_MULTI))
2270 				prog->call_session_cookie = 1;
2271 			if (!bpf_allow_tail_call_in_subprogs(env))
2272 				prog->aux->stack_depth = MAX_BPF_STACK;
2273 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
2274 			prog->aux->max_rdonly_access = U32_MAX;
2275 			prog->aux->max_rdwr_access = U32_MAX;
2276 			if (prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE)
2277 				prog->aux->max_tp_access = U32_MAX;
2278 
2279 			/* mark bpf_tail_call as different opcode to avoid
2280 			 * conditional branch in the interpreter for every normal
2281 			 * call and to prevent accidental JITing by JIT compiler
2282 			 * that doesn't support bpf_tail_call yet
2283 			 */
2284 			insn->imm = 0;
2285 			insn->code = BPF_JMP | BPF_TAIL_CALL;
2286 
2287 			aux = &env->insn_aux_data[i + delta];
2288 			if (env->bpf_capable && !prog->blinding_requested &&
2289 			    prog->jit_requested &&
2290 			    !bpf_map_key_poisoned(aux) &&
2291 			    !bpf_map_ptr_poisoned(aux) &&
2292 			    !bpf_map_ptr_unpriv(aux)) {
2293 				struct bpf_jit_poke_descriptor desc = {
2294 					.reason = BPF_POKE_REASON_TAIL_CALL,
2295 					.tail_call.map = aux->map_ptr_state.map_ptr,
2296 					.tail_call.key = bpf_map_key_immediate(aux),
2297 					.insn_idx = i + delta,
2298 				};
2299 
2300 				ret = bpf_jit_add_poke_descriptor(prog, &desc);
2301 				if (ret < 0) {
2302 					verbose(env, "adding tail call poke descriptor failed\n");
2303 					return ret;
2304 				}
2305 
2306 				insn->imm = ret + 1;
2307 				goto next_insn;
2308 			}
2309 
2310 			if (!bpf_map_ptr_unpriv(aux))
2311 				goto next_insn;
2312 
2313 			/* instead of changing every JIT dealing with tail_call
2314 			 * emit two extra insns:
2315 			 * if (index >= max_entries) goto out;
2316 			 * index &= array->index_mask;
2317 			 * to avoid out-of-bounds cpu speculation
2318 			 */
2319 			if (bpf_map_ptr_poisoned(aux)) {
2320 				verbose(env, "tail_call abusing map_ptr\n");
2321 				return -EINVAL;
2322 			}
2323 
2324 			map_ptr = aux->map_ptr_state.map_ptr;
2325 			insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3,
2326 						  map_ptr->max_entries, 2);
2327 			insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3,
2328 						    container_of(map_ptr,
2329 								 struct bpf_array,
2330 								 map)->index_mask);
2331 			insn_buf[2] = *insn;
2332 			cnt = 3;
2333 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2334 			if (!new_prog)
2335 				return -ENOMEM;
2336 
2337 			delta    += cnt - 1;
2338 			env->prog = prog = new_prog;
2339 			insn      = new_prog->insnsi + i + delta;
2340 			goto next_insn;
2341 		}
2342 
2343 		aux = &env->insn_aux_data[i + delta];
2344 		if (aux->arg_prog) {
2345 			/* The verifier will process callback_fn as many times as necessary
2346 			 * with different maps and the register states prepared by
2347 			 * set_timer_callback_state will be accurate.
2348 			 *
2349 			 * The following use case is valid:
2350 			 *   map1 is shared by prog1, prog2, prog3.
2351 			 *   prog1 calls bpf_timer_init for some map1 elements
2352 			 *   prog2 calls bpf_timer_set_callback for some map1 elements.
2353 			 *     Those that were not bpf_timer_init-ed will return -EINVAL.
2354 			 *   prog3 calls bpf_timer_start for some map1 elements.
2355 			 *     Those that were not both bpf_timer_init-ed and
2356 			 *     bpf_timer_set_callback-ed will return -EINVAL.
2357 			 */
2358 			struct bpf_insn ld_addrs[2] = {
2359 				BPF_LD_IMM64(aux->arg_prog, (long)prog->aux),
2360 			};
2361 
2362 			insn_buf[0] = ld_addrs[0];
2363 			insn_buf[1] = ld_addrs[1];
2364 			insn_buf[2] = *insn;
2365 			cnt = 3;
2366 
2367 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2368 			if (!new_prog)
2369 				return -ENOMEM;
2370 
2371 			delta    += cnt - 1;
2372 			env->prog = prog = new_prog;
2373 			insn      = new_prog->insnsi + i + delta;
2374 			goto patch_call_imm;
2375 		}
2376 
2377 		/* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */
2378 		if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) {
2379 			/* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data,
2380 			 * bpf_mem_alloc() returns a ptr to the percpu data ptr.
2381 			 */
2382 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0);
2383 			insn_buf[1] = *insn;
2384 			cnt = 2;
2385 
2386 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2387 			if (!new_prog)
2388 				return -ENOMEM;
2389 
2390 			delta += cnt - 1;
2391 			env->prog = prog = new_prog;
2392 			insn = new_prog->insnsi + i + delta;
2393 			goto patch_call_imm;
2394 		}
2395 
2396 		/* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup
2397 		 * and other inlining handlers are currently limited to 64 bit
2398 		 * only.
2399 		 */
2400 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
2401 		    (insn->imm == BPF_FUNC_map_lookup_elem ||
2402 		     insn->imm == BPF_FUNC_map_update_elem ||
2403 		     insn->imm == BPF_FUNC_map_delete_elem ||
2404 		     insn->imm == BPF_FUNC_map_push_elem   ||
2405 		     insn->imm == BPF_FUNC_map_pop_elem    ||
2406 		     insn->imm == BPF_FUNC_map_peek_elem   ||
2407 		     insn->imm == BPF_FUNC_redirect_map    ||
2408 		     insn->imm == BPF_FUNC_for_each_map_elem ||
2409 		     insn->imm == BPF_FUNC_map_lookup_percpu_elem)) {
2410 			aux = &env->insn_aux_data[i + delta];
2411 			if (bpf_map_ptr_poisoned(aux))
2412 				goto patch_call_imm;
2413 
2414 			map_ptr = aux->map_ptr_state.map_ptr;
2415 			ops = map_ptr->ops;
2416 			if (insn->imm == BPF_FUNC_map_lookup_elem &&
2417 			    ops->map_gen_lookup) {
2418 				cnt = ops->map_gen_lookup(map_ptr, insn_buf);
2419 				if (cnt == -EOPNOTSUPP)
2420 					goto patch_map_ops_generic;
2421 				if (cnt <= 0 || cnt >= INSN_BUF_SIZE) {
2422 					verifier_bug(env, "%d insns generated for map lookup", cnt);
2423 					return -EFAULT;
2424 				}
2425 
2426 				if (bpf_map_is_percpu_map(map_ptr->map_type))
2427 					prog->jit_required = true;
2428 
2429 				new_prog = bpf_patch_insn_data(env, i + delta,
2430 							       insn_buf, cnt);
2431 				if (!new_prog)
2432 					return -ENOMEM;
2433 
2434 				delta    += cnt - 1;
2435 				env->prog = prog = new_prog;
2436 				insn      = new_prog->insnsi + i + delta;
2437 				goto next_insn;
2438 			}
2439 
2440 			BUILD_BUG_ON(!__same_type(ops->map_lookup_elem,
2441 				     (void *(*)(struct bpf_map *map, void *key))NULL));
2442 			BUILD_BUG_ON(!__same_type(ops->map_delete_elem,
2443 				     (long (*)(struct bpf_map *map, void *key))NULL));
2444 			BUILD_BUG_ON(!__same_type(ops->map_update_elem,
2445 				     (long (*)(struct bpf_map *map, void *key, void *value,
2446 					      u64 flags))NULL));
2447 			BUILD_BUG_ON(!__same_type(ops->map_push_elem,
2448 				     (long (*)(struct bpf_map *map, void *value,
2449 					      u64 flags))NULL));
2450 			BUILD_BUG_ON(!__same_type(ops->map_pop_elem,
2451 				     (long (*)(struct bpf_map *map, void *value))NULL));
2452 			BUILD_BUG_ON(!__same_type(ops->map_peek_elem,
2453 				     (long (*)(struct bpf_map *map, void *value))NULL));
2454 			BUILD_BUG_ON(!__same_type(ops->map_redirect,
2455 				     (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL));
2456 			BUILD_BUG_ON(!__same_type(ops->map_for_each_callback,
2457 				     (long (*)(struct bpf_map *map,
2458 					      bpf_callback_t callback_fn,
2459 					      void *callback_ctx,
2460 					      u64 flags))NULL));
2461 			BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem,
2462 				     (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL));
2463 
2464 patch_map_ops_generic:
2465 			switch (insn->imm) {
2466 			case BPF_FUNC_map_lookup_elem:
2467 				insn->imm = BPF_CALL_IMM(ops->map_lookup_elem);
2468 				goto next_insn;
2469 			case BPF_FUNC_map_update_elem:
2470 				insn->imm = BPF_CALL_IMM(ops->map_update_elem);
2471 				goto next_insn;
2472 			case BPF_FUNC_map_delete_elem:
2473 				insn->imm = BPF_CALL_IMM(ops->map_delete_elem);
2474 				goto next_insn;
2475 			case BPF_FUNC_map_push_elem:
2476 				insn->imm = BPF_CALL_IMM(ops->map_push_elem);
2477 				goto next_insn;
2478 			case BPF_FUNC_map_pop_elem:
2479 				insn->imm = BPF_CALL_IMM(ops->map_pop_elem);
2480 				goto next_insn;
2481 			case BPF_FUNC_map_peek_elem:
2482 				insn->imm = BPF_CALL_IMM(ops->map_peek_elem);
2483 				goto next_insn;
2484 			case BPF_FUNC_redirect_map:
2485 				insn->imm = BPF_CALL_IMM(ops->map_redirect);
2486 				goto next_insn;
2487 			case BPF_FUNC_for_each_map_elem:
2488 				insn->imm = BPF_CALL_IMM(ops->map_for_each_callback);
2489 				goto next_insn;
2490 			case BPF_FUNC_map_lookup_percpu_elem:
2491 				insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem);
2492 				goto next_insn;
2493 			}
2494 
2495 			goto patch_call_imm;
2496 		}
2497 
2498 		/* Implement bpf_jiffies64 inline. */
2499 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
2500 		    insn->imm == BPF_FUNC_jiffies64) {
2501 			struct bpf_insn ld_jiffies_addr[2] = {
2502 				BPF_LD_IMM64(BPF_REG_0,
2503 					     (unsigned long)&jiffies),
2504 			};
2505 
2506 			insn_buf[0] = ld_jiffies_addr[0];
2507 			insn_buf[1] = ld_jiffies_addr[1];
2508 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0,
2509 						  BPF_REG_0, 0);
2510 			cnt = 3;
2511 
2512 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf,
2513 						       cnt);
2514 			if (!new_prog)
2515 				return -ENOMEM;
2516 
2517 			delta    += cnt - 1;
2518 			env->prog = prog = new_prog;
2519 			insn      = new_prog->insnsi + i + delta;
2520 			goto next_insn;
2521 		}
2522 
2523 #if defined(CONFIG_X86_64) && !defined(CONFIG_UML)
2524 		/* Implement bpf_get_smp_processor_id() inline. */
2525 		if (insn->imm == BPF_FUNC_get_smp_processor_id &&
2526 		    bpf_verifier_inlines_helper_call(env, insn->imm)) {
2527 			/* BPF_FUNC_get_smp_processor_id inlining is an
2528 			 * optimization, so if cpu_number is ever
2529 			 * changed in some incompatible and hard to support
2530 			 * way, it's fine to back out this inlining logic
2531 			 */
2532 #ifdef CONFIG_SMP
2533 			prog->jit_required = true;
2534 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&cpu_number);
2535 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
2536 			insn_buf[2] = BPF_LDX_MEM(BPF_W, BPF_REG_0, BPF_REG_0, 0);
2537 			cnt = 3;
2538 #else
2539 			insn_buf[0] = BPF_ALU32_REG(BPF_XOR, BPF_REG_0, BPF_REG_0);
2540 			cnt = 1;
2541 #endif
2542 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2543 			if (!new_prog)
2544 				return -ENOMEM;
2545 
2546 			delta    += cnt - 1;
2547 			env->prog = prog = new_prog;
2548 			insn      = new_prog->insnsi + i + delta;
2549 			goto next_insn;
2550 		}
2551 
2552 		/* Implement bpf_get_current_task() and bpf_get_current_task_btf() inline. */
2553 		if ((insn->imm == BPF_FUNC_get_current_task || insn->imm == BPF_FUNC_get_current_task_btf) &&
2554 		    bpf_verifier_inlines_helper_call(env, insn->imm)) {
2555 			prog->jit_required = true;
2556 			insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, (u32)(unsigned long)&current_task);
2557 			insn_buf[1] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
2558 			insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0, 0);
2559 			cnt = 3;
2560 
2561 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2562 			if (!new_prog)
2563 				return -ENOMEM;
2564 
2565 			delta    += cnt - 1;
2566 			env->prog = prog = new_prog;
2567 			insn      = new_prog->insnsi + i + delta;
2568 			goto next_insn;
2569 		}
2570 #endif
2571 		/* Implement bpf_get_func_arg inline. */
2572 		if (prog_type == BPF_PROG_TYPE_TRACING &&
2573 		    insn->imm == BPF_FUNC_get_func_arg) {
2574 			if (eatype == BPF_TRACE_RAW_TP) {
2575 				int nr_args = btf_type_vlen(prog->aux->attach_func_proto);
2576 
2577 				/* skip 'void *__data' in btf_trace_##name() and save to reg0 */
2578 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, nr_args - 1);
2579 				cnt = 1;
2580 			} else {
2581 				/* Load nr_args from ctx - 8 */
2582 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
2583 				insn_buf[1] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
2584 				cnt = 2;
2585 			}
2586 			insn_buf[cnt++] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
2587 			insn_buf[cnt++] = BPF_ALU32_IMM(BPF_LSH, BPF_REG_2, 3);
2588 			insn_buf[cnt++] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
2589 			insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
2590 			insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
2591 			insn_buf[cnt++] = BPF_MOV64_IMM(BPF_REG_0, 0);
2592 			insn_buf[cnt++] = BPF_JMP_A(1);
2593 			insn_buf[cnt++] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
2594 
2595 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2596 			if (!new_prog)
2597 				return -ENOMEM;
2598 
2599 			delta    += cnt - 1;
2600 			env->prog = prog = new_prog;
2601 			insn      = new_prog->insnsi + i + delta;
2602 			goto next_insn;
2603 		}
2604 
2605 		/* Implement bpf_get_func_ret inline. */
2606 		if (prog_type == BPF_PROG_TYPE_TRACING &&
2607 		    insn->imm == BPF_FUNC_get_func_ret) {
2608 			if (eatype == BPF_TRACE_FEXIT ||
2609 			    eatype == BPF_TRACE_FSESSION ||
2610 			    eatype == BPF_TRACE_FEXIT_MULTI ||
2611 			    eatype == BPF_TRACE_FSESSION_MULTI ||
2612 			    eatype == BPF_MODIFY_RETURN) {
2613 				/* Load nr_args from ctx - 8 */
2614 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
2615 				insn_buf[1] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
2616 				insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3);
2617 				insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1);
2618 				insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
2619 				insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0);
2620 				insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0);
2621 				cnt = 7;
2622 			} else {
2623 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP);
2624 				cnt = 1;
2625 			}
2626 
2627 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2628 			if (!new_prog)
2629 				return -ENOMEM;
2630 
2631 			delta    += cnt - 1;
2632 			env->prog = prog = new_prog;
2633 			insn      = new_prog->insnsi + i + delta;
2634 			goto next_insn;
2635 		}
2636 
2637 		/* Implement get_func_arg_cnt inline. */
2638 		if (prog_type == BPF_PROG_TYPE_TRACING &&
2639 		    insn->imm == BPF_FUNC_get_func_arg_cnt) {
2640 			if (eatype == BPF_TRACE_RAW_TP) {
2641 				int nr_args = btf_type_vlen(prog->aux->attach_func_proto);
2642 
2643 				/* skip 'void *__data' in btf_trace_##name() and save to reg0 */
2644 				insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, nr_args - 1);
2645 				cnt = 1;
2646 			} else {
2647 				/* Load nr_args from ctx - 8 */
2648 				insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
2649 				insn_buf[1] = BPF_ALU64_IMM(BPF_AND, BPF_REG_0, 0xFF);
2650 				cnt = 2;
2651 			}
2652 
2653 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2654 			if (!new_prog)
2655 				return -ENOMEM;
2656 
2657 			delta    += cnt - 1;
2658 			env->prog = prog = new_prog;
2659 			insn      = new_prog->insnsi + i + delta;
2660 			goto next_insn;
2661 		}
2662 
2663 		/* Implement bpf_get_func_ip inline. */
2664 		if (prog_type == BPF_PROG_TYPE_TRACING &&
2665 		    insn->imm == BPF_FUNC_get_func_ip) {
2666 			/* Load IP address from ctx - 16 */
2667 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16);
2668 
2669 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1);
2670 			if (!new_prog)
2671 				return -ENOMEM;
2672 
2673 			env->prog = prog = new_prog;
2674 			insn      = new_prog->insnsi + i + delta;
2675 			goto next_insn;
2676 		}
2677 
2678 		/* Implement bpf_get_branch_snapshot inline. */
2679 		if (IS_ENABLED(CONFIG_PERF_EVENTS) &&
2680 		    prog->jit_requested && BITS_PER_LONG == 64 &&
2681 		    insn->imm == BPF_FUNC_get_branch_snapshot) {
2682 			/* We are dealing with the following func protos:
2683 			 * u64 bpf_get_branch_snapshot(void *buf, u32 size, u64 flags);
2684 			 * int perf_snapshot_branch_stack(struct perf_branch_entry *entries, u32 cnt);
2685 			 */
2686 			const u32 br_entry_size = sizeof(struct perf_branch_entry);
2687 
2688 			/* struct perf_branch_entry is part of UAPI and is
2689 			 * used as an array element, so extremely unlikely to
2690 			 * ever grow or shrink
2691 			 */
2692 			BUILD_BUG_ON(br_entry_size != 24);
2693 
2694 			/* if (unlikely(flags)) return -EINVAL */
2695 			insn_buf[0] = BPF_JMP_IMM(BPF_JNE, BPF_REG_3, 0, 7);
2696 
2697 			/* Transform size (bytes) into number of entries (cnt = size / 24).
2698 			 * But to avoid expensive division instruction, we implement
2699 			 * divide-by-3 through multiplication, followed by further
2700 			 * division by 8 through 3-bit right shift.
2701 			 * Refer to book "Hacker's Delight, 2nd ed." by Henry S. Warren, Jr.,
2702 			 * p. 227, chapter "Unsigned Division by 3" for details and proofs.
2703 			 *
2704 			 * N / 3 <=> M * N / 2^33, where M = (2^33 + 1) / 3 = 0xaaaaaaab.
2705 			 */
2706 			insn_buf[1] = BPF_MOV32_IMM(BPF_REG_0, 0xaaaaaaab);
2707 			insn_buf[2] = BPF_ALU64_REG(BPF_MUL, BPF_REG_2, BPF_REG_0);
2708 			insn_buf[3] = BPF_ALU64_IMM(BPF_RSH, BPF_REG_2, 36);
2709 
2710 			/* call perf_snapshot_branch_stack implementation */
2711 			insn_buf[4] = BPF_EMIT_CALL(static_call_query(perf_snapshot_branch_stack));
2712 			/* if (entry_cnt == 0) return -ENOENT */
2713 			insn_buf[5] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 4);
2714 			/* return entry_cnt * sizeof(struct perf_branch_entry) */
2715 			insn_buf[6] = BPF_ALU32_IMM(BPF_MUL, BPF_REG_0, br_entry_size);
2716 			insn_buf[7] = BPF_JMP_A(3);
2717 			/* return -EINVAL; */
2718 			insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL);
2719 			insn_buf[9] = BPF_JMP_A(1);
2720 			/* return -ENOENT; */
2721 			insn_buf[10] = BPF_MOV64_IMM(BPF_REG_0, -ENOENT);
2722 			cnt = 11;
2723 
2724 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2725 			if (!new_prog)
2726 				return -ENOMEM;
2727 
2728 			delta    += cnt - 1;
2729 			env->prog = prog = new_prog;
2730 			insn      = new_prog->insnsi + i + delta;
2731 			goto next_insn;
2732 		}
2733 
2734 		/* Implement bpf_kptr_xchg inline */
2735 		if (prog->jit_requested && BITS_PER_LONG == 64 &&
2736 		    insn->imm == BPF_FUNC_kptr_xchg &&
2737 		    bpf_jit_supports_ptr_xchg()) {
2738 			insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2);
2739 			insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0);
2740 			cnt = 2;
2741 
2742 			new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt);
2743 			if (!new_prog)
2744 				return -ENOMEM;
2745 
2746 			delta    += cnt - 1;
2747 			env->prog = prog = new_prog;
2748 			insn      = new_prog->insnsi + i + delta;
2749 			goto next_insn;
2750 		}
2751 patch_call_imm:
2752 		fn = env->ops->get_func_proto(insn->imm, env->prog);
2753 		/* all functions that have prototype and verifier allowed
2754 		 * programs to call them, must be real in-kernel functions
2755 		 */
2756 		if (!fn->func) {
2757 			verifier_bug(env,
2758 				     "not inlined functions %s#%d is missing func",
2759 				     func_id_name(insn->imm), insn->imm);
2760 			return -EFAULT;
2761 		}
2762 		insn->imm = BPF_CALL_IMM(fn->func);
2763 next_insn:
2764 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
2765 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
2766 			subprogs[cur_subprog].stack_extra = stack_depth_extra;
2767 
2768 			stack_depth = subprogs[cur_subprog].stack_depth;
2769 			if (stack_depth > MAX_BPF_STACK && !prog->jit_requested) {
2770 				verbose(env, "stack size %d(extra %d) is too large\n",
2771 					stack_depth, stack_depth_extra);
2772 				return -EINVAL;
2773 			}
2774 			cur_subprog++;
2775 			stack_depth = subprogs[cur_subprog].stack_depth;
2776 			stack_depth_extra = 0;
2777 		}
2778 		i++;
2779 		insn++;
2780 	}
2781 
2782 	env->prog->aux->stack_depth = subprogs[0].stack_depth;
2783 	for (i = 0; i < env->subprog_cnt; i++) {
2784 		int subprog_start = subprogs[i].start;
2785 		int stack_slots = subprogs[i].stack_extra / 8;
2786 		/* an invocation begins, see bpf_timed_may_goto_save() for async callbacks */
2787 		bool main_prog = tmg && !i;
2788 		/* only a helper calls it, in a loop that ends when it returns 1 */
2789 		bool loop_cb = tmg && i && subprogs[i].is_loop_cb && !subprogs[i].is_called &&
2790 			       !subprogs[i].is_async_cb;
2791 		int cnt = 0;
2792 
2793 		if (timed_may_goto ? !main_prog && !loop_cb : !stack_slots)
2794 			continue;
2795 		if (stack_slots > 1) {
2796 			verifier_bug(env, "stack_slots supports may_goto only");
2797 			return -EFAULT;
2798 		}
2799 
2800 		stack_depth = subprogs[i].stack_depth;
2801 		if (timed_may_goto) {
2802 			struct bpf_insn ld_tmg[] = {
2803 				BPF_LD_IMM64(BPF_REG_0, (__force unsigned long)tmg)
2804 			};
2805 			int count_off = offsetof(struct bpf_timed_may_goto, count);
2806 			int timestamp_off = offsetof(struct bpf_timed_may_goto, timestamp);
2807 			int owner_off = offsetof(struct bpf_timed_may_goto, owner);
2808 
2809 			/* R0 has nothing at the entry */
2810 			insn_buf[cnt++] = ld_tmg[0];
2811 			insn_buf[cnt++] = ld_tmg[1];
2812 			insn_buf[cnt++] = BPF_MOV64_PERCPU_REG(BPF_REG_0, BPF_REG_0);
2813 			if (main_prog) {
2814 				insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_0, count_off,
2815 							     BPF_MAX_TIMED_LOOPS);
2816 				insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_0, timestamp_off, 0);
2817 				insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_0, owner_off, 0);
2818 			} else {
2819 				/*
2820 				 * The time is up, but the helper would call the function again and
2821 				 * again. End its loop. The verifier has seen that: the loop can end
2822 				 * after each call.
2823 				 */
2824 				insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0,
2825 							      count_off);
2826 				insn_buf[cnt++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_0, 0, 2);
2827 				insn_buf[cnt++] = BPF_MOV64_IMM(BPF_REG_0, 1);
2828 				insn_buf[cnt++] = BPF_EXIT_INSN();
2829 			}
2830 		} else {
2831 			/* Add ST insn to subprog prologue to init extra stack */
2832 			insn_buf[cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, -stack_depth,
2833 						     BPF_MAX_LOOPS);
2834 		}
2835 		/* Copy first actual insn to preserve it */
2836 		insn_buf[cnt] = env->prog->insnsi[subprog_start];
2837 		ret = bpf_adj_moved_insn(&insn_buf[cnt], cnt);
2838 		if (ret) {
2839 			verbose(env, "insn %d cannot be patched due to 16-bit range\n",
2840 				env->insn_aux_data[subprog_start].orig_idx);
2841 			return ret;
2842 		}
2843 		cnt++;
2844 
2845 		new_prog = __bpf_patch_insn_data(env, subprog_start, insn_buf, cnt,
2846 						 BPF_PATCH_MOVE_TARGET);
2847 		if (!new_prog)
2848 			return -ENOMEM;
2849 		env->prog = prog = new_prog;
2850 		/*
2851 		 * If may_goto is a first insn of a prog there could be a jmp
2852 		 * insn that points to it, hence adjust all such jmps to point
2853 		 * to insn after BPF_ST that inits may_goto count.
2854 		 * Adjustment will succeed because bpf_patch_insn_data() didn't fail.
2855 		 */
2856 		WARN_ON(adjust_jmp_off(env->prog, subprog_start, cnt - 1));
2857 	}
2858 
2859 	/* Since poke tab is now finalized, publish aux to tracker. */
2860 	for (i = 0; i < prog->aux->size_poke_tab; i++) {
2861 		map_ptr = prog->aux->poke_tab[i].tail_call.map;
2862 		if (!map_ptr->ops->map_poke_track ||
2863 		    !map_ptr->ops->map_poke_untrack ||
2864 		    !map_ptr->ops->map_poke_run) {
2865 			verifier_bug(env, "poke tab is misconfigured");
2866 			return -EFAULT;
2867 		}
2868 
2869 		ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux);
2870 		if (ret < 0) {
2871 			verbose(env, "tracking tail call prog failed\n");
2872 			return ret;
2873 		}
2874 	}
2875 
2876 	return 0;
2877 }
2878 
2879 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env,
2880 					int position,
2881 					s32 stack_base,
2882 					u32 callback_subprogno,
2883 					u32 *total_cnt)
2884 {
2885 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
2886 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
2887 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
2888 	int reg_loop_max = BPF_REG_6;
2889 	int reg_loop_cnt = BPF_REG_7;
2890 	int reg_loop_ctx = BPF_REG_8;
2891 
2892 	struct bpf_insn *insn_buf = env->insn_buf;
2893 	struct bpf_prog *new_prog;
2894 	u32 callback_start;
2895 	u32 call_insn_offset;
2896 	s32 callback_offset;
2897 	u32 cnt = 0;
2898 
2899 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
2900 	 * be careful to modify this code in sync.
2901 	 */
2902 
2903 	/* Return error and jump to the end of the patch if
2904 	 * expected number of iterations is too big.
2905 	 */
2906 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
2907 	insn_buf[cnt++] = BPF_MOV32_IMM(BPF_REG_0, -E2BIG);
2908 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
2909 	/* spill R6, R7, R8 to use these as loop vars */
2910 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
2911 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
2912 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset);
2913 	/* initialize loop vars */
2914 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_max, BPF_REG_1);
2915 	insn_buf[cnt++] = BPF_MOV32_IMM(reg_loop_cnt, 0);
2916 	insn_buf[cnt++] = BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3);
2917 	/* loop header,
2918 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
2919 	 */
2920 	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
2921 	/* callback call,
2922 	 * correct callback offset would be set after patching
2923 	 */
2924 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
2925 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
2926 	insn_buf[cnt++] = BPF_CALL_REL(0);
2927 	/* increment loop counter */
2928 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
2929 	/* jump to loop header if callback returned 0 */
2930 	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
2931 	/* return value of bpf_loop,
2932 	 * set R0 to the number of iterations
2933 	 */
2934 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt);
2935 	/* restore original values of R6, R7, R8 */
2936 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
2937 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
2938 	insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
2939 
2940 	*total_cnt = cnt;
2941 	new_prog = bpf_patch_insn_data(env, position, insn_buf, cnt);
2942 	if (!new_prog)
2943 		return new_prog;
2944 
2945 	/* callback start is known only after patching */
2946 	callback_start = env->subprog_info[callback_subprogno].start;
2947 	/* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */
2948 	call_insn_offset = position + 12;
2949 	callback_offset = callback_start - call_insn_offset - 1;
2950 	new_prog->insnsi[call_insn_offset].imm = callback_offset;
2951 
2952 	return new_prog;
2953 }
2954 
2955 static bool is_bpf_loop_call(struct bpf_insn *insn)
2956 {
2957 	return insn->code == (BPF_JMP | BPF_CALL) &&
2958 		insn->src_reg == 0 &&
2959 		insn->imm == BPF_FUNC_loop;
2960 }
2961 
2962 /* For all sub-programs in the program (including main) check
2963  * insn_aux_data to see if there are bpf_loop calls that require
2964  * inlining. If such calls are found the calls are replaced with a
2965  * sequence of instructions produced by `inline_bpf_loop` function and
2966  * subprog stack_depth is increased by the size of 3 registers.
2967  * This stack space is used to spill values of the R6, R7, R8.  These
2968  * registers are used to store the loop bound, counter and context
2969  * variables.
2970  */
2971 int bpf_optimize_bpf_loop(struct bpf_verifier_env *env)
2972 {
2973 	struct bpf_subprog_info *subprogs = env->subprog_info;
2974 	int i, cur_subprog = 0, cnt, delta = 0;
2975 	struct bpf_insn *insn = env->prog->insnsi;
2976 	int insn_cnt = env->prog->len;
2977 	u16 stack_depth = subprogs[cur_subprog].stack_depth;
2978 	u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
2979 	u16 stack_depth_extra = 0;
2980 
2981 	for (i = 0; i < insn_cnt; i++, insn++) {
2982 		struct bpf_loop_inline_state *inline_state =
2983 			&env->insn_aux_data[i + delta].loop_inline_state;
2984 
2985 		if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) {
2986 			struct bpf_prog *new_prog;
2987 
2988 			stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup;
2989 			new_prog = inline_bpf_loop(env,
2990 						   i + delta,
2991 						   -(stack_depth + stack_depth_extra),
2992 						   inline_state->callback_subprogno,
2993 						   &cnt);
2994 			if (!new_prog)
2995 				return -ENOMEM;
2996 
2997 			delta     += cnt - 1;
2998 			env->prog  = new_prog;
2999 			insn       = new_prog->insnsi + i + delta;
3000 		}
3001 
3002 		if (subprogs[cur_subprog + 1].start == i + delta + 1) {
3003 			subprogs[cur_subprog].stack_depth += stack_depth_extra;
3004 			cur_subprog++;
3005 			stack_depth = subprogs[cur_subprog].stack_depth;
3006 			stack_depth_roundup = round_up(stack_depth, 8) - stack_depth;
3007 			stack_depth_extra = 0;
3008 		}
3009 	}
3010 
3011 	env->prog->aux->stack_depth = env->subprog_info[0].stack_depth;
3012 
3013 	return 0;
3014 }
3015 
3016 /* Remove unnecessary spill/fill pairs, members of fastcall pattern,
3017  * adjust subprograms stack depth when possible.
3018  */
3019 int bpf_remove_fastcall_spills_fills(struct bpf_verifier_env *env)
3020 {
3021 	struct bpf_subprog_info *subprog = env->subprog_info;
3022 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
3023 	struct bpf_insn *insn = env->prog->insnsi;
3024 	int insn_cnt = env->prog->len;
3025 	u32 spills_num;
3026 	bool modified = false;
3027 	int i, j;
3028 
3029 	for (i = 0; i < insn_cnt; i++, insn++) {
3030 		if (aux[i].fastcall_spills_num > 0) {
3031 			spills_num = aux[i].fastcall_spills_num;
3032 			/* NOPs would be removed by opt_remove_nops() */
3033 			for (j = 1; j <= spills_num; ++j) {
3034 				*(insn - j) = NOP;
3035 				*(insn + j) = NOP;
3036 			}
3037 			modified = true;
3038 		}
3039 		if ((subprog + 1)->start == i + 1) {
3040 			if (modified && !subprog->keep_fastcall_stack)
3041 				subprog->stack_depth = -subprog->fastcall_stack_off;
3042 			subprog++;
3043 			modified = false;
3044 		}
3045 	}
3046 
3047 	return 0;
3048 }
3049