xref: /linux/kernel/bpf/liveness.c (revision ceea9085f2d131987903d7965d3738168275bf4a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */
3 
4 #include <linux/bpf_verifier.h>
5 #include <linux/btf.h>
6 #include <linux/hashtable.h>
7 #include <linux/jhash.h>
8 #include <linux/slab.h>
9 #include <linux/sort.h>
10 
11 #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
12 
13 /*
14  * Stack liveness is tracked with a 4-byte (half register) granularity.
15  * Half-slot 0 covers [fp-4, fp), half-slot 1 covers [fp-8, fp-4), and so on,
16  * hence FRAME_HALF_SPIS - 1 is the deepest half-slot a frame can have.
17  */
18 #define FRAME_HALF_SPIS		(MAX_BPF_STACK_JIT / BPF_HALF_REG_SIZE)
19 #define FRAME_MAX_WORDS		BITS_TO_LONGS(FRAME_HALF_SPIS)
20 
21 /* Masks tracked for each instruction of a frame */
22 enum {
23 	FM_MAY_READ,	/* stack slots that may be read by this instruction */
24 	FM_MUST_WRITE,	/* stack slots written by this instruction */
25 	FM_LIVE_BEFORE,	/* stack slots that may be read by this insn and its successors */
26 	FM_MAY_WRITE,	/* stack slots that may be written by this instruction */
27 	FM_MASK_CNT,
28 };
29 
30 /*
31  * Per instruction stack masks for one frame of a function instance.
32  *
33  * Most frames use only a fraction of the stack budget, so instead of masks
34  * wide enough for every half-slot of the largest possible frame, all masks
35  * of one array share the width @words, and the marking functions widen the
36  * array as deeper half-slots are recorded. Mask @kind of the instruction at
37  * relative index @i is at &bits[(i * FM_MASK_CNT + kind) * words]. A
38  * half-slot at or past @words * BITS_PER_LONG is never read by this frame,
39  * hence never live. An instruction that may read the whole frame, such as a
40  * call passing a frame pointer to another subprog, widens the array to the
41  * program's stack budget, the deepest an accepted program can reach, so
42  * that the read cannot lose half-slots to a later widening.
43  */
44 struct frame_masks {
45 	u32 words;
46 	unsigned long bits[];
47 };
48 
49 /*
50  * A function instance keyed by (callsite, depth).
51  * Encapsulates read and write marks for each instruction in the function.
52  * Marks are tracked for each frame up to @depth.
53  */
54 struct func_instance {
55 	struct hlist_node hl_node;
56 	u32 callsite;		/* call insn that invoked this subprog (subprog_start for depth 0) */
57 	u32 depth;		/* call depth (0 = entry subprog) */
58 	u32 subprog;		/* subprog index */
59 	u32 subprog_start;	/* cached env->subprog_info[subprog].start */
60 	u32 insn_cnt;		/* cached number of insns in the function */
61 	/* Per frame, per instruction masks, frames allocated lazily. */
62 	struct frame_masks *frames[MAX_CALL_FRAMES];
63 	bool must_write_initialized;
64 };
65 
66 struct live_stack_query {
67 	struct func_instance *instances[MAX_CALL_FRAMES]; /* valid in range [0..curframe] */
68 	u32 callsites[MAX_CALL_FRAMES]; /* callsite[i] = insn calling frame i+1 */
69 	u32 curframe;
70 	u32 insn_idx;
71 };
72 
73 struct bpf_liveness {
74 	DECLARE_HASHTABLE(func_instances, 8);		/* maps (depth, callsite) to func_instance */
75 	struct live_stack_query live_stack_query;	/* cache to avoid repetitive ht lookups */
76 	u32 subprog_calls;				/* analyze_subprog() invocations */
77 };
78 
79 /*
80  * Hash/compare key for func_instance: (depth, callsite).
81  * For depth == 0 (entry subprog), @callsite is the subprog start insn.
82  * For depth > 0, @callsite is the call instruction index that invoked the subprog.
83  */
84 static u32 instance_hash(u32 callsite, u32 depth)
85 {
86 	u32 key[2] = { depth, callsite };
87 
88 	return jhash2(key, 2, 0);
89 }
90 
91 static struct func_instance *find_instance(struct bpf_verifier_env *env,
92 					   u32 callsite, u32 depth)
93 {
94 	struct bpf_liveness *liveness = env->liveness;
95 	struct func_instance *f;
96 	u32 key = instance_hash(callsite, depth);
97 
98 	hash_for_each_possible(liveness->func_instances, f, hl_node, key)
99 		if (f->depth == depth && f->callsite == callsite)
100 			return f;
101 	return NULL;
102 }
103 
104 static struct func_instance *call_instance(struct bpf_verifier_env *env,
105 					   struct func_instance *caller,
106 					   u32 callsite, int subprog)
107 {
108 	u32 depth = caller ? caller->depth + 1 : 0;
109 	u32 subprog_start = env->subprog_info[subprog].start;
110 	u32 lookup_key = depth > 0 ? callsite : subprog_start;
111 	struct func_instance *f;
112 	u32 hash;
113 
114 	f = find_instance(env, lookup_key, depth);
115 	if (f)
116 		return f;
117 
118 	f = kvzalloc_obj(*f, GFP_KERNEL_ACCOUNT);
119 	if (!f)
120 		return ERR_PTR(-ENOMEM);
121 	f->callsite = lookup_key;
122 	f->depth = depth;
123 	f->subprog = subprog;
124 	f->subprog_start = subprog_start;
125 	f->insn_cnt = (env->subprog_info + subprog + 1)->start - subprog_start;
126 	hash = instance_hash(lookup_key, depth);
127 	hash_add(env->liveness->func_instances, &f->hl_node, hash);
128 	return f;
129 }
130 
131 static struct func_instance *lookup_instance(struct bpf_verifier_env *env,
132 					     struct bpf_verifier_state *st,
133 					     u32 frameno)
134 {
135 	u32 callsite, subprog_start;
136 	struct func_instance *f;
137 	u32 key, depth;
138 
139 	subprog_start = env->subprog_info[st->frame[frameno]->subprogno].start;
140 	callsite = frameno > 0 ? st->frame[frameno]->callsite : subprog_start;
141 
142 	for (depth = frameno; ; depth--) {
143 		key = depth > 0 ? callsite : subprog_start;
144 		f = find_instance(env, key, depth);
145 		if (f || depth == 0)
146 			return f;
147 	}
148 }
149 
150 int bpf_stack_liveness_init(struct bpf_verifier_env *env)
151 {
152 	env->liveness = kvzalloc_obj(*env->liveness, GFP_KERNEL_ACCOUNT);
153 	if (!env->liveness)
154 		return -ENOMEM;
155 	hash_init(env->liveness->func_instances);
156 	return 0;
157 }
158 
159 void bpf_stack_liveness_free(struct bpf_verifier_env *env)
160 {
161 	struct func_instance *instance;
162 	struct hlist_node *tmp;
163 	int bkt, i;
164 
165 	if (!env->liveness)
166 		return;
167 	hash_for_each_safe(env->liveness->func_instances, bkt, tmp, instance, hl_node) {
168 		for (i = 0; i <= instance->depth; i++)
169 			kvfree(instance->frames[i]);
170 		kvfree(instance);
171 	}
172 	kvfree(env->liveness);
173 }
174 
175 /*
176  * Convert absolute instruction index @insn_idx to an index relative
177  * to start of the function corresponding to @instance.
178  */
179 static int relative_idx(struct func_instance *instance, u32 insn_idx)
180 {
181 	return insn_idx - instance->subprog_start;
182 }
183 
184 static u32 frame_mask_bits(struct frame_masks *fm)
185 {
186 	return fm->words * BITS_PER_LONG;
187 }
188 
189 static size_t frame_mask_words(struct func_instance *instance, u32 words)
190 {
191 	return (size_t)instance->insn_cnt * FM_MASK_CNT * words;
192 }
193 
194 /* Mask @kind of the instruction at relative index @rel */
195 static unsigned long *rel_mask(struct frame_masks *fm, u32 rel, u32 kind)
196 {
197 	return fm->bits + ((size_t)rel * FM_MASK_CNT + kind) * fm->words;
198 }
199 
200 /*
201  * Make sure @frame has a mask array at least @words wide, allocating it or
202  * copying the existing masks into the wider stride as needed.
203  * @words must be in range [1, FRAME_MAX_WORDS].
204  */
205 static struct frame_masks *widen_frame_masks(struct func_instance *instance,
206 					     u32 frame, u32 words)
207 {
208 	struct frame_masks *old = instance->frames[frame], *new;
209 	u32 i, kind;
210 
211 	if (old && old->words >= words)
212 		return old;
213 	new = kvzalloc_flex(*new, bits, frame_mask_words(instance, words), GFP_KERNEL_ACCOUNT);
214 	if (!new)
215 		return NULL;
216 	new->words = words;
217 	if (old) {
218 		for (i = 0; i < instance->insn_cnt; i++)
219 			for (kind = 0; kind < FM_MASK_CNT; kind++)
220 				memcpy(rel_mask(new, i, kind), rel_mask(old, i, kind),
221 				       old->words * sizeof(*old->bits));
222 		kvfree(old);
223 	}
224 	instance->frames[frame] = new;
225 	return new;
226 }
227 
228 /*
229  * Set the inclusive half-slot range [lo, hi] in mask @kind of @frame at @insn_idx.
230  * An empty range, including one with a negative @hi as computed for a write
231  * that does not fully cover any half-slot, marks nothing.
232  */
233 static int mark_stack_range(struct func_instance *instance, u32 frame, u32 insn_idx,
234 			    u32 kind, s32 lo, s32 hi)
235 {
236 	struct frame_masks *fm;
237 
238 	/*
239 	 * An access past the frame bottom is rejected by the main verifier
240 	 * pass later, liveness only has to avoid running off the masks.
241 	 */
242 	hi = min_t(s32, hi, FRAME_HALF_SPIS - 1);
243 	if (lo > hi)
244 		return 0;
245 	fm = widen_frame_masks(instance, frame, BITS_TO_LONGS(hi + 1));
246 	if (!fm)
247 		return -ENOMEM;
248 	bitmap_set(rel_mask(fm, relative_idx(instance, insn_idx), kind), lo, hi - lo + 1);
249 	return 0;
250 }
251 
252 /* Accumulate may_read for half-slots [lo, hi] of @frame at @insn_idx */
253 static int mark_stack_read(struct func_instance *instance, u32 frame, u32 insn_idx,
254 			   s32 lo, s32 hi)
255 {
256 	return mark_stack_range(instance, frame, insn_idx, FM_MAY_READ, lo, hi);
257 }
258 
259 /* Accumulate must_write for half-slots [lo, hi] of @frame at @insn_idx */
260 static int mark_stack_write(struct func_instance *instance, u32 frame, u32 insn_idx,
261 			    s32 lo, s32 hi)
262 {
263 	return mark_stack_range(instance, frame, insn_idx, FM_MUST_WRITE, lo, hi);
264 }
265 
266 static int mark_stack_may_write(struct func_instance *instance, u32 frame, u32 insn_idx,
267 				s32 lo, s32 hi)
268 {
269 	return mark_stack_range(instance, frame, insn_idx, FM_MAY_WRITE, lo, hi);
270 }
271 
272 /*
273  * Mark every half-slot of @frame as possibly read by @insn_idx. This widens
274  * the masks to the program's stack budget: a full read recorded at a narrower
275  * width would leave the bits added by a later widening clear and lose part of
276  * it. No verifier state holds a slot past the budget, so no liveness query
277  * reaches beyond it; an access past the budget in unreachable code may still
278  * widen a frame's masks further, which is harmless.
279  */
280 static int mark_stack_read_all(struct bpf_verifier_env *env, struct func_instance *instance,
281 			       u32 frame, u32 insn_idx)
282 {
283 	return mark_stack_read(instance, frame, insn_idx, 0,
284 			       env->stack_limit / BPF_HALF_REG_SIZE - 1);
285 }
286 
287 static int mark_stack_may_write_all(struct bpf_verifier_env *env, struct func_instance *instance,
288 				    u32 frame, u32 insn_idx)
289 {
290 	return mark_stack_may_write(instance, frame, insn_idx, 0,
291 				    env->stack_limit / BPF_HALF_REG_SIZE - 1);
292 }
293 
294 /* Accumulate @src, a mask @src_words wide, into @kind mask of @frame at @insn_idx */
295 static int mark_stack_mask(struct func_instance *instance, u32 frame, u32 insn_idx, u32 kind,
296 			   const unsigned long *src, u32 src_words)
297 {
298 	u32 nbits = src_words * BITS_PER_LONG;
299 	struct frame_masks *fm;
300 	unsigned long *dst;
301 	u32 last, w;
302 
303 	last = find_last_bit(src, nbits);
304 	if (last == nbits)
305 		return 0;
306 	fm = widen_frame_masks(instance, frame, BITS_TO_LONGS(last + 1));
307 	if (!fm)
308 		return -ENOMEM;
309 	dst = rel_mask(fm, relative_idx(instance, insn_idx), kind);
310 	/* @src has no bits set past @last, hence none past @fm->words either */
311 	src_words = min(src_words, fm->words);
312 	for (w = 0; w < src_words; w++)
313 		dst[w] |= src[w];
314 	return 0;
315 }
316 
317 static int mark_stack_read_mask(struct func_instance *instance, u32 frame, u32 insn_idx,
318 				const unsigned long *src, u32 src_words)
319 {
320 	return mark_stack_mask(instance, frame, insn_idx, FM_MAY_READ, src, src_words);
321 }
322 
323 int bpf_jmp_offset(struct bpf_insn *insn)
324 {
325 	u8 code = insn->code;
326 
327 	if (code == (BPF_JMP32 | BPF_JA))
328 		return insn->imm;
329 	return insn->off;
330 }
331 
332 __diag_push();
333 __diag_ignore_all("-Woverride-init", "Allow field initialization overrides for opcode_info_tbl");
334 
335 /*
336  * Returns an array of instructions succ, with succ->items[0], ...,
337  * succ->items[n-1] with successor instructions, where n=succ->cnt
338  */
339 inline struct bpf_iarray *
340 bpf_insn_successors(struct bpf_verifier_env *env, u32 idx)
341 {
342 	static const struct opcode_info {
343 		bool can_jump;
344 		bool can_fallthrough;
345 	} opcode_info_tbl[256] = {
346 		[0 ... 255] = {.can_jump = false, .can_fallthrough = true},
347 	#define _J(code, ...) \
348 		[BPF_JMP   | code] = __VA_ARGS__, \
349 		[BPF_JMP32 | code] = __VA_ARGS__
350 
351 		_J(BPF_EXIT,  {.can_jump = false, .can_fallthrough = false}),
352 		_J(BPF_JA,    {.can_jump = true,  .can_fallthrough = false}),
353 		_J(BPF_JEQ,   {.can_jump = true,  .can_fallthrough = true}),
354 		_J(BPF_JNE,   {.can_jump = true,  .can_fallthrough = true}),
355 		_J(BPF_JLT,   {.can_jump = true,  .can_fallthrough = true}),
356 		_J(BPF_JLE,   {.can_jump = true,  .can_fallthrough = true}),
357 		_J(BPF_JGT,   {.can_jump = true,  .can_fallthrough = true}),
358 		_J(BPF_JGE,   {.can_jump = true,  .can_fallthrough = true}),
359 		_J(BPF_JSGT,  {.can_jump = true,  .can_fallthrough = true}),
360 		_J(BPF_JSGE,  {.can_jump = true,  .can_fallthrough = true}),
361 		_J(BPF_JSLT,  {.can_jump = true,  .can_fallthrough = true}),
362 		_J(BPF_JSLE,  {.can_jump = true,  .can_fallthrough = true}),
363 		_J(BPF_JCOND, {.can_jump = true,  .can_fallthrough = true}),
364 		_J(BPF_JSET,  {.can_jump = true,  .can_fallthrough = true}),
365 	#undef _J
366 	};
367 	struct bpf_prog *prog = env->prog;
368 	struct bpf_insn *insn = &prog->insnsi[idx];
369 	const struct opcode_info *opcode_info;
370 	struct bpf_iarray *succ, *jt;
371 	int insn_sz;
372 
373 	/* pre-allocated array of size up to 2; reset cnt, as it may have been used already */
374 	succ = env->succ;
375 	succ->cnt = 0;
376 
377 	/* All gotox of a subprogram share its jump table, see compute_subprog_jts() */
378 	if (unlikely(insn_is_gotox(insn))) {
379 		jt = bpf_find_containing_subprog(env, idx)->jt;
380 		if (verifier_bug_if(!jt, env, "no jump table for gotox insn %u", idx))
381 			return succ;
382 		return jt;
383 	}
384 
385 	opcode_info = &opcode_info_tbl[BPF_CLASS(insn->code) | BPF_OP(insn->code)];
386 	insn_sz = bpf_is_ldimm64(insn) ? 2 : 1;
387 	if (opcode_info->can_fallthrough)
388 		succ->items[succ->cnt++] = idx + insn_sz;
389 
390 	if (opcode_info->can_jump)
391 		succ->items[succ->cnt++] = idx + bpf_jmp_offset(insn) + 1;
392 
393 	/*
394 	 * tail_call upon success and ld_{abs,ind} upon load failure return
395 	 * from the subprogram, which is a hidden edge to its exit. A subprogram
396 	 * without an exit insn has no exit to model.
397 	 */
398 	if (unlikely((bpf_helper_call(insn) && insn->imm == BPF_FUNC_tail_call) ||
399 		     (BPF_CLASS(insn->code) == BPF_LD &&
400 		      (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND)))) {
401 		u32 exit_idx = bpf_find_containing_subprog(env, idx)->exit_idx;
402 
403 		if (exit_idx != U32_MAX)
404 			succ->items[succ->cnt++] = exit_idx;
405 	}
406 
407 	return succ;
408 }
409 
410 __diag_pop();
411 
412 static inline bool update_insn(struct bpf_verifier_env *env,
413 			       struct func_instance *instance, u32 frame, u32 insn_idx)
414 {
415 	unsigned long new_after[FRAME_MAX_WORDS] = {};
416 	unsigned long *may_read, *must_write, *live_before;
417 	struct frame_masks *fm = instance->frames[frame];
418 	u32 rel = relative_idx(instance, insn_idx);
419 	struct bpf_iarray *succ;
420 	bool changed = false;
421 	u32 s, w;
422 
423 	succ = bpf_insn_successors(env, insn_idx);
424 	if (succ->cnt == 0)
425 		return false;
426 
427 	/* All instructions of one frame array share the same mask width */
428 	for (s = 0; s < succ->cnt; ++s) {
429 		unsigned long *succ_live;
430 
431 		succ_live = rel_mask(fm, relative_idx(instance, succ->items[s]), FM_LIVE_BEFORE);
432 		for (w = 0; w < fm->words; w++)
433 			new_after[w] |= succ_live[w];
434 	}
435 	may_read = rel_mask(fm, rel, FM_MAY_READ);
436 	must_write = rel_mask(fm, rel, FM_MUST_WRITE);
437 	live_before = rel_mask(fm, rel, FM_LIVE_BEFORE);
438 	/*
439 	 * New "live_before" is a union of all "live_before" of successors
440 	 * minus slots written by instruction plus slots read by instruction.
441 	 * new_before = (new_after & ~insn->must_write) | insn->may_read
442 	 */
443 	for (w = 0; w < fm->words; w++) {
444 		unsigned long new_before = (new_after[w] & ~must_write[w]) | may_read[w];
445 
446 		if (new_before != live_before[w]) {
447 			live_before[w] = new_before;
448 			changed = true;
449 		}
450 	}
451 	return changed;
452 }
453 
454 /* Fixed-point computation of @live_before marks */
455 static void update_instance(struct bpf_verifier_env *env, struct func_instance *instance)
456 {
457 	u32 i, frame, po_start, po_end;
458 	int *insn_postorder = env->cfg.insn_postorder;
459 	struct bpf_subprog_info *subprog;
460 	bool changed;
461 
462 	instance->must_write_initialized = true;
463 	subprog = &env->subprog_info[instance->subprog];
464 	po_start = subprog->postorder_start;
465 	po_end = (subprog + 1)->postorder_start;
466 	/* repeat until fixed point is reached */
467 	do {
468 		changed = false;
469 		for (frame = 0; frame <= instance->depth; frame++) {
470 			if (!instance->frames[frame])
471 				continue;
472 
473 			for (i = po_start; i < po_end; i++)
474 				changed |= update_insn(env, instance, frame, insn_postorder[i]);
475 		}
476 	} while (changed);
477 }
478 
479 static bool is_live_before(struct func_instance *instance, u32 insn_idx, u32 frameno, u32 half_spi)
480 {
481 	struct frame_masks *fm = instance->frames[frameno];
482 
483 	/* No recorded access reaches past the masks, so nothing there is live */
484 	if (!fm || half_spi >= frame_mask_bits(fm))
485 		return false;
486 	return test_bit(half_spi, rel_mask(fm, relative_idx(instance, insn_idx), FM_LIVE_BEFORE));
487 }
488 
489 int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
490 {
491 	struct live_stack_query *q = &env->liveness->live_stack_query;
492 	struct func_instance *instance;
493 	u32 frame;
494 
495 	memset(q, 0, sizeof(*q));
496 	for (frame = 0; frame <= st->curframe; frame++) {
497 		instance = lookup_instance(env, st, frame);
498 		if (IS_ERR_OR_NULL(instance))
499 			q->instances[frame] = NULL;
500 		else
501 			q->instances[frame] = instance;
502 		if (frame < st->curframe)
503 			q->callsites[frame] = st->frame[frame + 1]->callsite;
504 	}
505 	q->curframe = st->curframe;
506 	q->insn_idx = st->insn_idx;
507 	return 0;
508 }
509 
510 /*
511  * Stack slots of outer frames that the callee may read are accounted as read
512  * by the @callsite insn itself, i.e. they are live before @callsite and may be
513  * dead after it, when:
514  * - @callsite calls a callback, which may be called several times;
515  * - @callsite is callx. Its callee is not known when stack liveness is
516  *   computed, so there is no func instance for it at @callsite. While
517  *   the verifier is in the callee lookup_instance() finds its standalone
518  *   instance that knows nothing about outer frames. What the callee may read
519  *   there is recorded by record_call_access().
520  */
521 static bool callee_stack_access_at_callsite(struct bpf_verifier_env *env, u32 callsite)
522 {
523 	return bpf_calls_callback(env, callsite) ||
524 	       bpf_is_callx(&env->prog->insnsi[callsite]);
525 }
526 
527 bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_spi)
528 {
529 	/*
530 	 * Slot is alive if it is read before q->insn_idx in current func instance,
531 	 * or if for some outer func instance:
532 	 * - alive before callsite if callsite calls callback or is callx, otherwise
533 	 * - alive after callsite
534 	 */
535 	struct live_stack_query *q = &env->liveness->live_stack_query;
536 	struct func_instance *instance, *curframe_instance;
537 	u32 i, callsite, rel;
538 	int cur_delta, delta;
539 	bool alive = false;
540 
541 	curframe_instance = q->instances[q->curframe];
542 	if (!curframe_instance)
543 		return true;
544 	cur_delta = (int)curframe_instance->depth - (int)q->curframe;
545 	rel = frameno + cur_delta;
546 	if (rel <= curframe_instance->depth)
547 		alive = is_live_before(curframe_instance, q->insn_idx, rel, half_spi);
548 
549 	if (alive)
550 		return true;
551 
552 	for (i = frameno; i < q->curframe; i++) {
553 		instance = q->instances[i];
554 		if (!instance)
555 			return true;
556 		/* Map actual frameno to frame index within this instance */
557 		delta = (int)instance->depth - (int)i;
558 		rel = frameno + delta;
559 		if (rel > instance->depth)
560 			return true;
561 
562 		/* Get callsite from verifier state, not from instance callchain */
563 		callsite = q->callsites[i];
564 
565 		alive = callee_stack_access_at_callsite(env, callsite)
566 			? is_live_before(instance, callsite, rel, half_spi)
567 			: is_live_before(instance, callsite + 1, rel, half_spi);
568 		if (alive)
569 			return true;
570 	}
571 
572 	return false;
573 }
574 
575 static char *fmt_subprog(struct bpf_verifier_env *env, int subprog)
576 {
577 	const char *name = env->subprog_info[subprog].name;
578 
579 	snprintf(env->tmp_str_buf, sizeof(env->tmp_str_buf),
580 		 "subprog#%d%s%s", subprog, name ? " " : "", name ? name : "");
581 	return env->tmp_str_buf;
582 }
583 
584 static char *fmt_instance(struct bpf_verifier_env *env, struct func_instance *instance)
585 {
586 	snprintf(env->tmp_str_buf, sizeof(env->tmp_str_buf),
587 		 "(d%d,cs%d)", instance->depth, instance->callsite);
588 	return env->tmp_str_buf;
589 }
590 
591 static int spi_off(int spi)
592 {
593 	return -(spi + 1) * BPF_REG_SIZE;
594 }
595 
596 /*
597  * When both halves of an 8-byte SPI are set, print as "-8","-16",...
598  * When only one half is set, print as "-4h","-8h",...
599  * Runs of 3+ consecutive fully-set SPIs are collapsed: "fp0-8..-24"
600  */
601 static char *fmt_spis_mask(struct bpf_verifier_env *env, int frame, bool first,
602 			   const unsigned long *spis, u32 words)
603 {
604 	int buf_sz = sizeof(env->tmp_str_buf);
605 	int spi_cnt = words * BITS_PER_LONG / 2;
606 	char *buf = env->tmp_str_buf;
607 	int spi, n, run_start;
608 
609 	buf[0] = '\0';
610 
611 	for (spi = 0; spi < spi_cnt && buf_sz > 0; spi++) {
612 		bool lo = test_bit(spi * 2, spis);
613 		bool hi = test_bit(spi * 2 + 1, spis);
614 		const char *space = first ? "" : " ";
615 
616 		if (!lo && !hi)
617 			continue;
618 
619 		if (!lo || !hi) {
620 			/* half-spi */
621 			n = scnprintf(buf, buf_sz, "%sfp%d%d%s",
622 				      space, frame, spi_off(spi) + (lo ? STACK_SLOT_SZ : 0), "h");
623 		} else if (spi + 2 < spi_cnt &&
624 			   test_bit(spi * 2 + 2, spis) &&
625 			   test_bit(spi * 2 + 3, spis) &&
626 			   test_bit(spi * 2 + 4, spis) &&
627 			   test_bit(spi * 2 + 5, spis)) {
628 			/* 3+ consecutive full spis */
629 			run_start = spi;
630 			while (spi + 1 < spi_cnt &&
631 			       test_bit((spi + 1) * 2, spis) &&
632 			       test_bit((spi + 1) * 2 + 1, spis))
633 				spi++;
634 			n = scnprintf(buf, buf_sz, "%sfp%d%d..%d",
635 				      space, frame, spi_off(run_start), spi_off(spi));
636 		} else {
637 			/* just a full spi */
638 			n = scnprintf(buf, buf_sz, "%sfp%d%d", space, frame, spi_off(spi));
639 		}
640 		first = false;
641 		buf += n;
642 		buf_sz -= n;
643 	}
644 	return env->tmp_str_buf;
645 }
646 
647 /* Print mask @kind of the instruction at relative index @i for every frame, if any bit is set. */
648 static bool print_mask(struct bpf_verifier_env *env, struct func_instance *instance, int i,
649 		       const char *name, u32 kind)
650 {
651 	struct frame_masks *fm;
652 	bool printed = false;
653 	unsigned long *mask;
654 	int frame;
655 	u64 pos;
656 
657 	pos = env->log.end_pos;
658 	verbose(env, "%s", name);
659 	for (frame = instance->depth; frame >= 0; --frame) {
660 		fm = instance->frames[frame];
661 		if (!fm)
662 			continue;
663 		mask = rel_mask(fm, i, kind);
664 		if (bitmap_empty(mask, frame_mask_bits(fm)))
665 			continue;
666 		verbose(env, "%s", fmt_spis_mask(env, frame, !printed, mask, fm->words));
667 		printed = true;
668 	}
669 	if (!printed)
670 		bpf_vlog_reset(&env->log, pos);
671 	return printed;
672 }
673 
674 static void print_instance(struct bpf_verifier_env *env, struct func_instance *instance)
675 {
676 	int start = env->subprog_info[instance->subprog].start;
677 	struct bpf_insn *insns = env->prog->insnsi;
678 	int len = instance->insn_cnt;
679 	u64 pos, insn_pos;
680 	int insn_idx, i;
681 	bool printed;
682 
683 	if (!(env->log.level & BPF_LOG_LEVEL2))
684 		return;
685 
686 	verbose(env, "stack use/def %s ", fmt_subprog(env, instance->subprog));
687 	verbose(env, "%s:\n", fmt_instance(env, instance));
688 	for (i = 0; i < len; i++) {
689 		insn_idx = start + i;
690 		pos = env->log.end_pos;
691 		verbose(env, "%3d: ", insn_idx);
692 		bpf_verbose_insn(env, &insns[insn_idx]);
693 		insn_pos = env->log.end_pos;
694 		verbose(env, "%*c;", bpf_vlog_alignment(insn_pos - pos), ' ');
695 		printed = false;
696 		printed |= print_mask(env, instance, i, " use: ", FM_MAY_READ);
697 		printed |= print_mask(env, instance, i, " def: ", FM_MUST_WRITE);
698 		printed |= print_mask(env, instance, i, " may_def: ", FM_MAY_WRITE);
699 		if (!printed)
700 			bpf_vlog_reset(&env->log, insn_pos);
701 		verbose(env, "\n");
702 		if (bpf_is_ldimm64(&insns[insn_idx]))
703 			i++;
704 	}
705 }
706 
707 static int cmp_instances(const void *pa, const void *pb)
708 {
709 	struct func_instance *a = *(struct func_instance **)pa;
710 	struct func_instance *b = *(struct func_instance **)pb;
711 	int dcallsite = (int)a->callsite - b->callsite;
712 	int ddepth = (int)a->depth - b->depth;
713 
714 	if (dcallsite)
715 		return dcallsite;
716 	if (ddepth)
717 		return ddepth;
718 	return 0;
719 }
720 
721 /* OR the 8-byte slots touched by a half-slot (4-byte) mask into @slots. */
722 static void half_spis_to_slots(unsigned long *slots, const unsigned long *mask, u32 nbits)
723 {
724 	u32 slot;
725 
726 	for (slot = 0; slot < MAX_BPF_STACK_SLOTS && slot * 2 + 1 < nbits; slot++)
727 		if (test_bit(slot * 2, mask) || test_bit(slot * 2 + 1, mask))
728 			__set_bit(slot, slots);
729 }
730 
731 /*
732  * Precompute, for each instruction, the OR of may_write and live_before masks
733  * over its top frame across all func_instances reaching it, stash them in the
734  * insn_aux_data.
735  */
736 static void compute_may_write_masks(struct bpf_verifier_env *env)
737 {
738 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
739 	struct bpf_liveness *liveness = env->liveness;
740 	struct func_instance *instance;
741 	struct frame_masks *fm;
742 	u32 nbits;
743 	int bkt, i;
744 
745 	hash_for_each(liveness->func_instances, bkt, instance, hl_node) {
746 		fm = instance->frames[instance->depth];
747 		if (!fm)
748 			continue;
749 		nbits = frame_mask_bits(fm);
750 		for (i = 0; i < instance->insn_cnt; i++) {
751 			half_spis_to_slots(aux[instance->subprog_start + i].may_write_mask,
752 					   rel_mask(fm, i, FM_MAY_WRITE), nbits);
753 			half_spis_to_slots(aux[instance->subprog_start + i].live_stack_before,
754 					   rel_mask(fm, i, FM_LIVE_BEFORE), nbits);
755 		}
756 	}
757 }
758 
759 const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx)
760 {
761 	return env->insn_aux_data[insn_idx].may_write_mask;
762 }
763 
764 /* print use/def slots for all instances ordered by callsite first, then by depth */
765 static int print_instances(struct bpf_verifier_env *env)
766 {
767 	struct func_instance *instance, **sorted_instances;
768 	struct bpf_liveness *liveness = env->liveness;
769 	int i, bkt, cnt;
770 
771 	cnt = 0;
772 	hash_for_each(liveness->func_instances, bkt, instance, hl_node)
773 		cnt++;
774 	sorted_instances = kvmalloc_objs(*sorted_instances, cnt, GFP_KERNEL_ACCOUNT);
775 	if (!sorted_instances)
776 		return -ENOMEM;
777 	cnt = 0;
778 	hash_for_each(liveness->func_instances, bkt, instance, hl_node)
779 		sorted_instances[cnt++] = instance;
780 	sort(sorted_instances, cnt, sizeof(*sorted_instances), cmp_instances, NULL);
781 	for (i = 0; i < cnt; i++)
782 		print_instance(env, sorted_instances[i]);
783 	kvfree(sorted_instances);
784 	return 0;
785 }
786 
787 /*
788  * Per-register tracking state for compute_subprog_args().
789  * Tracks which frame's FP a value is derived from
790  * and the byte offset from that frame's FP.
791  *
792  * The .frame field forms a lattice with three levels of precision:
793  *
794  *   precise {frame=N, off=V}      -- known absolute frame index and byte offset
795  *        |
796  *   offset-imprecise {frame=N, cnt=0}
797  *        |                        -- known frame identity, unknown offset
798  *   fully-imprecise {frame=ARG_IMPRECISE, mask=bitmask}
799  *                                 -- unknown frame identity; .mask is a
800  *                                    bitmask of which frame indices might be
801  *                                    involved
802  *
803  * At CFG merge points, arg_track_join() moves down the lattice:
804  *   - same frame + same offset  -> precise
805  *   - same frame + different offset -> offset-imprecise
806  *   - different frames          -> fully-imprecise (bitmask OR)
807  *
808  * At memory access sites (LDX/STX/ST), offset-imprecise marks the known
809  * frame as fully read, while fully-imprecise iterates bits in the bitmask
810  * and routes each frame to its target.
811  */
812 #define MAX_ARG_OFFSETS 4
813 
814 struct arg_track {
815 	union {
816 		s16 off[MAX_ARG_OFFSETS]; /* byte offsets; off_cnt says how many */
817 		u16 mask;	/* arg bitmask when arg == ARG_IMPRECISE */
818 	};
819 	s8 frame;	/* absolute frame index, or enum arg_track_state */
820 	s8 off_cnt;	/* 0 = offset-imprecise, 1-4 = # of precise offsets */
821 };
822 
823 enum arg_track_state {
824 	ARG_NONE	= -1,	/* not derived from any argument */
825 	ARG_UNVISITED	= -2,	/* not yet reached by dataflow */
826 	ARG_IMPRECISE	= -3,	/* lost identity; .mask is arg bitmask */
827 };
828 
829 /*
830  * The tracker follows as many spill slots as a subprog addresses directly
831  * through R10, see subprog_spill_slots(). A frame's slots at a call site are
832  * kept in a snapshot for the callees that receive pointers into that frame.
833  */
834 struct spill_snapshot {
835 	u32 slots;
836 	struct arg_track at[];
837 };
838 
839 /*
840  * Combined register + stack arg tracking: R0-R10 at indices 0-10,
841  * outgoing stack arg slots at indices MAX_BPF_REG..MAX_BPF_REG+6.
842  */
843 #define MAX_AT_TRACK_REGS (MAX_BPF_REG + MAX_STACK_ARG_SLOTS)
844 
845 static int stack_arg_off_to_slot(s16 off)
846 {
847 	int aoff = off < 0 ? -off : off;
848 
849 	if (aoff / 8 > MAX_STACK_ARG_SLOTS)
850 		return -1;
851 	return aoff / 8 - 1;
852 }
853 
854 static bool arg_is_visited(const struct arg_track *at)
855 {
856 	return at->frame != ARG_UNVISITED;
857 }
858 
859 static bool arg_is_fp(const struct arg_track *at)
860 {
861 	return at->frame >= 0 || at->frame == ARG_IMPRECISE;
862 }
863 
864 static void verbose_arg_track(struct bpf_verifier_env *env, struct arg_track *at)
865 {
866 	int i;
867 
868 	switch (at->frame) {
869 	case ARG_NONE:      verbose(env, "_");                          break;
870 	case ARG_UNVISITED: verbose(env, "?");                          break;
871 	case ARG_IMPRECISE: verbose(env, "IMP%x", at->mask);            break;
872 	default:
873 		/* frame >= 0: absolute frame index */
874 		if (at->off_cnt == 0) {
875 			verbose(env, "fp%d ?", at->frame);
876 		} else {
877 			for (i = 0; i < at->off_cnt; i++) {
878 				if (i)
879 					verbose(env, "|");
880 				verbose(env, "fp%d%+d", at->frame, at->off[i]);
881 			}
882 		}
883 		break;
884 	}
885 }
886 
887 static bool arg_track_eq(const struct arg_track *a, const struct arg_track *b)
888 {
889 	int i;
890 
891 	if (a->frame != b->frame)
892 		return false;
893 	if (a->frame == ARG_IMPRECISE)
894 		return a->mask == b->mask;
895 	if (a->frame < 0)
896 		return true;
897 	if (a->off_cnt != b->off_cnt)
898 		return false;
899 	for (i = 0; i < a->off_cnt; i++)
900 		if (a->off[i] != b->off[i])
901 			return false;
902 	return true;
903 }
904 
905 static struct arg_track arg_single(s8 arg, s16 off)
906 {
907 	struct arg_track at = {};
908 
909 	at.frame = arg;
910 	at.off[0] = off;
911 	at.off_cnt = 1;
912 	return at;
913 }
914 
915 /*
916  * Merge two sorted offset arrays, deduplicate.
917  * Returns off_cnt=0 if the result exceeds MAX_ARG_OFFSETS.
918  * Both args must have the same frame and off_cnt > 0.
919  */
920 static struct arg_track arg_merge_offsets(struct arg_track a, struct arg_track b)
921 {
922 	struct arg_track result = { .frame = a.frame };
923 	struct arg_track imp = { .frame = a.frame };
924 	int i = 0, j = 0, k = 0;
925 
926 	while (i < a.off_cnt && j < b.off_cnt) {
927 		s16 v;
928 
929 		if (a.off[i] <= b.off[j]) {
930 			v = a.off[i++];
931 			if (v == b.off[j])
932 				j++;
933 		} else {
934 			v = b.off[j++];
935 		}
936 		if (k > 0 && result.off[k - 1] == v)
937 			continue;
938 		if (k >= MAX_ARG_OFFSETS)
939 			return imp;
940 		result.off[k++] = v;
941 	}
942 	while (i < a.off_cnt) {
943 		if (k >= MAX_ARG_OFFSETS)
944 			return imp;
945 		result.off[k++] = a.off[i++];
946 	}
947 	while (j < b.off_cnt) {
948 		if (k >= MAX_ARG_OFFSETS)
949 			return imp;
950 		result.off[k++] = b.off[j++];
951 	}
952 	result.off_cnt = k;
953 	return result;
954 }
955 
956 /*
957  * Merge two arg_tracks into ARG_IMPRECISE, collecting the frame
958  * bits from both operands. Precise frame indices (frame >= 0)
959  * contribute a single bit; existing ARG_IMPRECISE values
960  * contribute their full bitmask.
961  */
962 static struct arg_track arg_join_imprecise(struct arg_track a, struct arg_track b)
963 {
964 	u32 m = 0;
965 
966 	if (a.frame >= 0)
967 		m |= BIT(a.frame);
968 	else if (a.frame == ARG_IMPRECISE)
969 		m |= a.mask;
970 
971 	if (b.frame >= 0)
972 		m |= BIT(b.frame);
973 	else if (b.frame == ARG_IMPRECISE)
974 		m |= b.mask;
975 
976 	return (struct arg_track){ .mask = m, .frame = ARG_IMPRECISE };
977 }
978 
979 /* Join two arg_track values at merge points */
980 static struct arg_track __arg_track_join(struct arg_track a, struct arg_track b)
981 {
982 	if (!arg_is_visited(&b))
983 		return a;
984 	if (!arg_is_visited(&a))
985 		return b;
986 	if (a.frame == b.frame && a.frame >= 0) {
987 		/* Both offset-imprecise: stay imprecise */
988 		if (a.off_cnt == 0 || b.off_cnt == 0)
989 			return (struct arg_track){ .frame = a.frame };
990 		/* Merge offset sets; falls back to off_cnt=0 if >4 */
991 		return arg_merge_offsets(a, b);
992 	}
993 
994 	/*
995 	 * args are different, but one of them is known
996 	 * arg + none -> arg
997 	 * none + arg -> arg
998 	 *
999 	 * none + none -> none
1000 	 */
1001 	if (a.frame == ARG_NONE && b.frame == ARG_NONE)
1002 		return a;
1003 	if (a.frame >= 0 && b.frame == ARG_NONE) {
1004 		/*
1005 		 * When joining single fp-N add fake fp+0 to
1006 		 * keep stack_use and prevent stack_def
1007 		 */
1008 		if (a.off_cnt == 1)
1009 			return arg_merge_offsets(a, arg_single(a.frame, 0));
1010 		return a;
1011 	}
1012 	if (b.frame >= 0 && a.frame == ARG_NONE) {
1013 		if (b.off_cnt == 1)
1014 			return arg_merge_offsets(b, arg_single(b.frame, 0));
1015 		return b;
1016 	}
1017 
1018 	return arg_join_imprecise(a, b);
1019 }
1020 
1021 static bool arg_track_join(struct bpf_verifier_env *env, int idx, int target, int r,
1022 			   struct arg_track *in, struct arg_track out)
1023 {
1024 	struct arg_track old = *in;
1025 	struct arg_track new_val = __arg_track_join(old, out);
1026 
1027 	if (arg_track_eq(&new_val, &old))
1028 		return false;
1029 
1030 	*in = new_val;
1031 	if (!(env->log.level & BPF_LOG_LEVEL2) || !arg_is_visited(&old))
1032 		return true;
1033 
1034 	verbose(env, "arg JOIN insn %d -> %d ", idx, target);
1035 	if (r >= MAX_BPF_REG)
1036 		verbose(env, "sa%d: ", r - MAX_BPF_REG);
1037 	else if (r >= 0)
1038 		verbose(env, "r%d: ", r);
1039 	else
1040 		verbose(env, "fp%+d: ", r * 8);
1041 	verbose_arg_track(env, &old);
1042 	verbose(env, " + ");
1043 	verbose_arg_track(env, &out);
1044 	verbose(env, " => ");
1045 	verbose_arg_track(env, &new_val);
1046 	verbose(env, "\n");
1047 	return true;
1048 }
1049 
1050 /*
1051  * Compute the result when an ALU op destroys offset precision.
1052  * If a single arg is identifiable, preserve it with OFF_IMPRECISE.
1053  * If two different args are involved or one is already ARG_IMPRECISE,
1054  * the result is fully ARG_IMPRECISE.
1055  */
1056 static void arg_track_alu64(struct arg_track *dst, const struct arg_track *src)
1057 {
1058 	WARN_ON_ONCE(!arg_is_visited(dst));
1059 	WARN_ON_ONCE(!arg_is_visited(src));
1060 
1061 	if (dst->frame >= 0 && (src->frame == ARG_NONE || src->frame == dst->frame)) {
1062 		/*
1063 		 * rX += rY where rY is not arg derived
1064 		 * rX += rX
1065 		 */
1066 		dst->off_cnt = 0;
1067 		return;
1068 	}
1069 	if (src->frame >= 0 && dst->frame == ARG_NONE) {
1070 		/*
1071 		 * rX += rY where rX is not arg derived
1072 		 * rY identity leaks into rX
1073 		 */
1074 		dst->off_cnt = 0;
1075 		dst->frame = src->frame;
1076 		return;
1077 	}
1078 
1079 	if (dst->frame == ARG_NONE && src->frame == ARG_NONE)
1080 		return;
1081 
1082 	*dst = arg_join_imprecise(*dst, *src);
1083 }
1084 
1085 static bool arg_add(s16 off, s64 delta, s16 *out)
1086 {
1087 	s16 d = delta;
1088 
1089 	if (d != delta)
1090 		return true;
1091 	return check_add_overflow(off, d, out);
1092 }
1093 
1094 static void arg_padd(struct arg_track *at, s64 delta)
1095 {
1096 	int i;
1097 
1098 	if (at->off_cnt == 0)
1099 		return;
1100 	for (i = 0; i < at->off_cnt; i++) {
1101 		s16 new_off;
1102 
1103 		if (arg_add(at->off[i], delta, &new_off)) {
1104 			at->off_cnt = 0;
1105 			return;
1106 		}
1107 		at->off[i] = new_off;
1108 	}
1109 }
1110 
1111 /*
1112  * Slots the spill tracker may follow for a subprog of @len instructions
1113  * without its per-instruction tables costing more than they could for the
1114  * largest program while every frame stayed within MAX_BPF_STACK: as many
1115  * entries as 64 slots need for BPF_COMPLEXITY_LIMIT_INSNS instructions.
1116  */
1117 static u32 spill_slots_affordable(int len)
1118 {
1119 	u32 base = MAX_BPF_STACK / BPF_REG_SIZE;
1120 
1121 	return max_t(u32, base, base * BPF_COMPLEXITY_LIMIT_INSNS / len);
1122 }
1123 
1124 /*
1125  * Number of 8-byte spill slots to track for the instructions in [@start, @end):
1126  * the 64 slots of a MAX_BPF_STACK frame, which the tracker has always
1127  * followed, or the deepest 8-byte stack access made directly through R10 when
1128  * that reaches further, up to the program's stack budget. Spills and fills are
1129  * compiled as direct R10 accesses, so the count covers them whatever the frame
1130  * size; a fill through a derived pointer that reaches past it is treated as
1131  * imprecise, as one past the frame always was.
1132  */
1133 static u32 subprog_spill_slots(struct bpf_verifier_env *env, int start, int end)
1134 {
1135 	struct bpf_insn *insns = env->prog->insnsi;
1136 	int deepest = 0;
1137 
1138 	for (int i = start; i < end; i++) {
1139 		struct bpf_insn *insn = &insns[i];
1140 		u8 class = BPF_CLASS(insn->code);
1141 		u8 base;
1142 
1143 		if (BPF_SIZE(insn->code) != BPF_DW)
1144 			continue;
1145 		if (class == BPF_LDX)
1146 			base = insn->src_reg;
1147 		else if (class == BPF_STX || class == BPF_ST)
1148 			base = insn->dst_reg;
1149 		else
1150 			continue;
1151 		if (base == BPF_REG_FP && insn->off < 0)
1152 			deepest = max(deepest, -insn->off);
1153 	}
1154 	return clamp_t(u32, DIV_ROUND_UP(deepest, 8), MAX_BPF_STACK / BPF_REG_SIZE,
1155 		       env->stack_limit / BPF_REG_SIZE);
1156 }
1157 
1158 /*
1159  * Convert a byte offset from FP to one of the @nslots tracked stack slots.
1160  * Returns -1 if out of range or not 8-byte aligned.
1161  * Slot 0 = fp-8, slot 1 = fp-16, ..., slot 7 = fp-64, ....
1162  */
1163 static int fp_off_to_slot(s16 off, u32 nslots)
1164 {
1165 	if (off >= 0 || off < -(int)(nslots * 8))
1166 		return -1;
1167 	if (off % 8)
1168 		return -1;
1169 	return (-off) / 8 - 1;
1170 }
1171 
1172 static struct arg_track fill_from_stack(struct bpf_insn *insn,
1173 					struct arg_track *at_out, int reg,
1174 					struct arg_track *at_stack_out, u32 nslots,
1175 					int depth)
1176 {
1177 	struct arg_track imp = {
1178 		.mask = (1u << (depth + 1)) - 1,
1179 		.frame = ARG_IMPRECISE
1180 	};
1181 	struct arg_track result = { .frame = ARG_NONE };
1182 	int cnt, i;
1183 
1184 	if (reg == BPF_REG_FP) {
1185 		int slot = fp_off_to_slot(insn->off, nslots);
1186 
1187 		return slot >= 0 ? at_stack_out[slot] : imp;
1188 	}
1189 	cnt = at_out[reg].off_cnt;
1190 	if (cnt == 0)
1191 		return imp;
1192 
1193 	for (i = 0; i < cnt; i++) {
1194 		s16 fp_off, slot;
1195 
1196 		if (arg_add(at_out[reg].off[i], insn->off, &fp_off))
1197 			return imp;
1198 		slot = fp_off_to_slot(fp_off, nslots);
1199 		if (slot < 0)
1200 			return imp;
1201 		result = __arg_track_join(result, at_stack_out[slot]);
1202 	}
1203 	return result;
1204 }
1205 
1206 /*
1207  * Spill @val to all possible stack slots indicated by the FP offsets in @reg.
1208  * For an 8-byte store, single candidate slot gets @val. multi-slots are joined.
1209  * sub-8-byte store joins with ARG_NONE.
1210  * When exact offset is unknown conservatively add reg values to all slots in at_stack_out.
1211  */
1212 static void spill_to_stack(struct bpf_insn *insn, struct arg_track *at_out,
1213 			   int reg, struct arg_track *at_stack_out, u32 nslots,
1214 			   struct arg_track *val, u32 sz)
1215 {
1216 	struct arg_track none = { .frame = ARG_NONE };
1217 	struct arg_track new_val = sz == 8 ? *val : none;
1218 	int cnt, i;
1219 
1220 	if (reg == BPF_REG_FP) {
1221 		int slot = fp_off_to_slot(insn->off, nslots);
1222 
1223 		if (slot >= 0)
1224 			at_stack_out[slot] = new_val;
1225 		return;
1226 	}
1227 	cnt = at_out[reg].off_cnt;
1228 	if (cnt == 0) {
1229 		for (int slot = 0; slot < nslots; slot++)
1230 			at_stack_out[slot] = __arg_track_join(at_stack_out[slot], new_val);
1231 		return;
1232 	}
1233 	for (i = 0; i < cnt; i++) {
1234 		s16 fp_off;
1235 		int slot;
1236 
1237 		if (arg_add(at_out[reg].off[i], insn->off, &fp_off))
1238 			continue;
1239 		slot = fp_off_to_slot(fp_off, nslots);
1240 		if (slot < 0)
1241 			continue;
1242 		if (cnt == 1)
1243 			at_stack_out[slot] = new_val;
1244 		else
1245 			at_stack_out[slot] = __arg_track_join(at_stack_out[slot], new_val);
1246 	}
1247 }
1248 
1249 /*
1250  * Clear all tracked callee stack slots overlapping the byte range
1251  * [off, off+sz-1] where off is a negative FP-relative offset.
1252  */
1253 static void clear_overlapping_stack_slots(struct arg_track *at_stack, u32 nslots, s16 off,
1254 					  u32 sz, int cnt)
1255 {
1256 	struct arg_track none = { .frame = ARG_NONE };
1257 
1258 	if (cnt == 0) {
1259 		for (int i = 0; i < nslots; i++)
1260 			at_stack[i] = __arg_track_join(at_stack[i], none);
1261 		return;
1262 	}
1263 	for (int i = 0; i < nslots; i++) {
1264 		int slot_start = -((i + 1) * 8);
1265 		int slot_end = slot_start + 8;
1266 
1267 		if (slot_start < off + (int)sz && slot_end > off) {
1268 			if (cnt == 1)
1269 				at_stack[i] = none;
1270 			else
1271 				at_stack[i] = __arg_track_join(at_stack[i], none);
1272 		}
1273 	}
1274 }
1275 
1276 /*
1277  * Clear stack slots overlapping all possible FP offsets in @reg.
1278  */
1279 static void clear_stack_for_all_offs(struct bpf_insn *insn,
1280 				     struct arg_track *at_out, int reg,
1281 				     struct arg_track *at_stack_out, u32 nslots, u32 sz)
1282 {
1283 	int cnt, i;
1284 
1285 	if (reg == BPF_REG_FP) {
1286 		clear_overlapping_stack_slots(at_stack_out, nslots, insn->off, sz, 1);
1287 		return;
1288 	}
1289 	cnt = at_out[reg].off_cnt;
1290 	if (cnt == 0) {
1291 		clear_overlapping_stack_slots(at_stack_out, nslots, 0, sz, cnt);
1292 		return;
1293 	}
1294 	for (i = 0; i < cnt; i++) {
1295 		s16 fp_off;
1296 
1297 		if (arg_add(at_out[reg].off[i], insn->off, &fp_off)) {
1298 			clear_overlapping_stack_slots(at_stack_out, nslots, 0, sz, 0);
1299 			break;
1300 		}
1301 		clear_overlapping_stack_slots(at_stack_out, nslots, fp_off, sz, cnt);
1302 	}
1303 }
1304 
1305 static void arg_track_log(struct bpf_verifier_env *env, struct bpf_insn *insn, int idx,
1306 			  struct arg_track *at_in, struct arg_track *at_stack_in,
1307 			  struct arg_track *at_out, struct arg_track *at_stack_out, u32 nslots)
1308 {
1309 	bool printed = false;
1310 	int i;
1311 
1312 	if (!(env->log.level & BPF_LOG_LEVEL2))
1313 		return;
1314 	for (i = 0; i < MAX_BPF_REG; i++) {
1315 		if (arg_track_eq(&at_out[i], &at_in[i]))
1316 			continue;
1317 		if (!printed) {
1318 			verbose(env, "%3d: ", idx);
1319 			bpf_verbose_insn(env, insn);
1320 			printed = true;
1321 		}
1322 		verbose(env, "\tr%d: ", i); verbose_arg_track(env, &at_in[i]);
1323 		verbose(env, " -> "); verbose_arg_track(env, &at_out[i]);
1324 	}
1325 	/* Log outgoing stack arg slot transitions at indices MAX_BPF_REG..MAX_AT_TRACK_REGS-1 */
1326 	for (i = 0; i < MAX_STACK_ARG_SLOTS; i++) {
1327 		int ai = MAX_BPF_REG + i;
1328 
1329 		if (arg_track_eq(&at_out[ai], &at_in[ai]))
1330 			continue;
1331 		if (!printed) {
1332 			verbose(env, "%3d: ", idx);
1333 			bpf_verbose_insn(env, insn);
1334 			printed = true;
1335 		}
1336 		verbose(env, "\tsa%d: ", i); verbose_arg_track(env, &at_in[ai]);
1337 		verbose(env, " -> "); verbose_arg_track(env, &at_out[ai]);
1338 	}
1339 	for (i = 0; i < nslots; i++) {
1340 		if (arg_track_eq(&at_stack_out[i], &at_stack_in[i]))
1341 			continue;
1342 		if (!printed) {
1343 			verbose(env, "%3d: ", idx);
1344 			bpf_verbose_insn(env, insn);
1345 			printed = true;
1346 		}
1347 		verbose(env, "\tfp%+d: ", -(i + 1) * 8); verbose_arg_track(env, &at_stack_in[i]);
1348 		verbose(env, " -> "); verbose_arg_track(env, &at_stack_out[i]);
1349 	}
1350 	if (printed)
1351 		verbose(env, "\n");
1352 }
1353 
1354 static bool can_be_local_fp(int depth, int regno, struct arg_track *at)
1355 {
1356 	return regno == BPF_REG_FP || at->frame == depth ||
1357 	       (at->frame == ARG_IMPRECISE && (at->mask & BIT(depth)));
1358 }
1359 
1360 /*
1361  * Model 8-byte reads through @reg, including load-acquire
1362  * and the old value fetched by atomic operations.
1363  */
1364 static struct arg_track arg_track_deref(struct bpf_verifier_env *env, struct bpf_insn *insn,
1365 					struct arg_track *at_out, int reg,
1366 					struct arg_track *at_stack_out, u32 nslots,
1367 					int depth, u32 *callsites)
1368 {
1369 	struct arg_track *ptr = &at_out[reg];
1370 
1371 	if (can_be_local_fp(depth, reg, ptr))
1372 		return fill_from_stack(insn, at_out, reg, at_stack_out, nslots, depth);
1373 	if (ptr->frame >= 0 && ptr->frame < depth) {
1374 		struct spill_snapshot *parent = env->callsite_at_stack[callsites[ptr->frame]];
1375 
1376 		return fill_from_stack(insn, at_out, reg, parent->at, parent->slots, ptr->frame);
1377 	}
1378 	if (ptr->frame == ARG_IMPRECISE && !(ptr->mask & BIT(depth)) && ptr->mask)
1379 		return *ptr;
1380 	return (struct arg_track){ .frame = ARG_NONE };
1381 }
1382 
1383 /*
1384  * Pure dataflow transfer function for arg_track state.
1385  * Updates at_out[] based on how the instruction modifies registers.
1386  * Tracks spill/fill, but not other memory accesses.
1387  */
1388 static void arg_track_xfer(struct bpf_verifier_env *env, struct bpf_insn *insn,
1389 			   int insn_idx,
1390 			   struct arg_track *at_out, struct arg_track *at_stack_out, u32 nslots,
1391 			   const struct arg_track *at_stack_arg_entry,
1392 			   struct func_instance *instance,
1393 			   u32 *callsites)
1394 {
1395 	int depth = instance->depth;
1396 	u8 class = BPF_CLASS(insn->code);
1397 	u8 code = BPF_OP(insn->code);
1398 	struct arg_track *dst = &at_out[insn->dst_reg];
1399 	struct arg_track *src = &at_out[insn->src_reg];
1400 	struct arg_track none = { .frame = ARG_NONE };
1401 	int r, slot;
1402 
1403 	/* Handle stack arg stores and loads. */
1404 	if (is_stack_arg_st(insn) || is_stack_arg_stx(insn)) {
1405 		slot = stack_arg_off_to_slot(insn->off);
1406 		if (slot >= 0) {
1407 			if (is_stack_arg_stx(insn))
1408 				at_out[MAX_BPF_REG + slot] = at_out[insn->src_reg];
1409 			else
1410 				at_out[MAX_BPF_REG + slot] = none;
1411 		}
1412 	} else if (is_stack_arg_ldx(insn)) {
1413 		slot = stack_arg_off_to_slot(insn->off);
1414 		at_out[insn->dst_reg] = (slot >= 0) ? at_stack_arg_entry[slot] : none;
1415 	} else if (class == BPF_ALU64 && BPF_SRC(insn->code) == BPF_K) {
1416 		if (code == BPF_MOV) {
1417 			*dst = none;
1418 		} else if (dst->frame >= 0) {
1419 			if (code == BPF_ADD)
1420 				arg_padd(dst, insn->imm);
1421 			else if (code == BPF_SUB)
1422 				arg_padd(dst, -(s64)insn->imm);
1423 			else
1424 				/* Any other 64-bit alu on the pointer makes it imprecise */
1425 				dst->off_cnt = 0;
1426 		} /* else if dst->frame is imprecise it stays so */
1427 	} else if (class == BPF_ALU64 && BPF_SRC(insn->code) == BPF_X) {
1428 		if (code == BPF_MOV) {
1429 			if (insn->off == 0) {
1430 				*dst = *src;
1431 			} else {
1432 				/* addr_space_cast destroys a pointer */
1433 				*dst = none;
1434 			}
1435 		} else {
1436 			arg_track_alu64(dst, src);
1437 		}
1438 	} else if (class == BPF_ALU) {
1439 		/*
1440 		 * 32-bit alu destroys the pointer.
1441 		 * If src was a pointer it cannot leak into dst
1442 		 */
1443 		*dst = none;
1444 	} else if (class == BPF_JMP && code == BPF_CALL) {
1445 		/*
1446 		 * at_stack_out[slot] is not cleared by the helper and subprog calls.
1447 		 * The fill_from_stack() may return the stale spill — which is an FP-derived arg_track
1448 		 * (the value that was originally spilled there). The loaded register then carries
1449 		 * a phantom FP-derived identity that doesn't correspond to what's actually in the slot.
1450 		 * This phantom FP pointer propagates forward, and wherever it's subsequently used
1451 		 * (as a helper argument, another store, etc.), it sets stack liveness bits.
1452 		 * Those bits correspond to stack accesses that don't actually happen.
1453 		 * So the effect is over-reporting stack liveness — marking slots as live that aren't
1454 		 * actually accessed. The verifier preserves more state than necessary across calls,
1455 		 * which is conservative.
1456 		 *
1457 		 * helpers can scratch stack slots, but they won't make a valid pointer out of it.
1458 		 * subprogs are allowed to write into parent slots, but they cannot write
1459 		 * _any_ FP-derived pointer into it (either their own or parent's FP).
1460 		 */
1461 		for (r = BPF_REG_0; r <= BPF_REG_5; r++)
1462 			at_out[r] = none;
1463 	} else if (class == BPF_LDX) {
1464 		/* Only an 8-byte BPF_MEM load can be a fill, see arg_track_deref(). */
1465 		if (BPF_MODE(insn->code) == BPF_MEM && BPF_SIZE(insn->code) == BPF_DW)
1466 			*dst = arg_track_deref(env, insn, at_out, insn->src_reg,
1467 					       at_stack_out, nslots, depth, callsites);
1468 		else
1469 			*dst = none;
1470 	} else if (class == BPF_LD && BPF_MODE(insn->code) == BPF_IMM) {
1471 		*dst = none;
1472 	} else if (class == BPF_STX) {
1473 		u32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code));
1474 		bool dst_is_local_fp = can_be_local_fp(depth, insn->dst_reg, dst);
1475 		u8 mode = BPF_MODE(insn->code);
1476 
1477 		if (mode == BPF_MEM || (mode == BPF_ATOMIC && insn->imm == BPF_STORE_REL)) {
1478 			if (dst_is_local_fp)
1479 				spill_to_stack(insn, at_out, insn->dst_reg,
1480 					       at_stack_out, nslots, src, sz);
1481 		} else if (mode == BPF_ATOMIC && insn->imm == BPF_LOAD_ACQ) {
1482 			if (sz == 8)
1483 				*dst = arg_track_deref(env, insn, at_out, insn->src_reg,
1484 						       at_stack_out, nslots, depth, callsites);
1485 			else
1486 				*dst = none;
1487 		} else if (mode == BPF_ATOMIC) {
1488 			/* BPF_XCHG, BPF_CMPXCHG or BPF_{ADD,AND,OR,XOR} | [BPF_FETCH] */
1489 			struct arg_track old = none;
1490 
1491 			r = bpf_atomic_load_reg(insn);
1492 			if (r >= 0 && sz == 8)
1493 				old = arg_track_deref(env, insn, at_out, insn->dst_reg,
1494 						      at_stack_out, nslots, depth, callsites);
1495 			if (dst_is_local_fp)
1496 				clear_stack_for_all_offs(insn, at_out, insn->dst_reg,
1497 							 at_stack_out, nslots, sz);
1498 			if (r >= 0)
1499 				at_out[r] = old;
1500 		}
1501 	} else if (class == BPF_ST && BPF_MODE(insn->code) == BPF_MEM) {
1502 		u32 sz = bpf_size_to_bytes(BPF_SIZE(insn->code));
1503 		bool dst_is_local_fp = can_be_local_fp(depth, insn->dst_reg, dst);
1504 
1505 		/* BPF_ST to FP-derived dst: clear overlapping stack slots */
1506 		if (dst_is_local_fp)
1507 			clear_stack_for_all_offs(insn, at_out, insn->dst_reg,
1508 						 at_stack_out, nslots, sz);
1509 	}
1510 }
1511 
1512 /*
1513  * Record possible reads and writes for every touched half-slot. A definite
1514  * write requires full coverage, a known size, and a single possible offset.
1515  */
1516 static int record_stack_access_off(struct func_instance *instance, const struct arg_track *arg,
1517 				   s64 off_idx, struct arg_access_info info,
1518 				   u32 frame, u32 insn_idx)
1519 {
1520 	s64 fp_off = arg->off[off_idx];
1521 	s32 slot_hi, slot_lo;
1522 	int err;
1523 
1524 	if (fp_off >= 0)
1525 		/*
1526 		 * out of bounds stack access doesn't contribute
1527 		 * into actual stack liveness. It will be rejected
1528 		 * by the main verifier pass later.
1529 		 */
1530 		return 0;
1531 
1532 	/*
1533 	 * Read and may_write marks include partially covered slots.
1534 	 * An unknown access size may reach from fp_off to the frame top.
1535 	 */
1536 	slot_hi = (-fp_off - 1) / STACK_SLOT_SZ;
1537 	slot_lo = info.size == U32_MAX
1538 		  ? 0
1539 		  : max_t(s32, (-fp_off - info.size) / STACK_SLOT_SZ, 0);
1540 	if (info.may_read) {
1541 		err = mark_stack_read(instance, frame, insn_idx, slot_lo, slot_hi);
1542 		if (err)
1543 			return err;
1544 	}
1545 	if (info.may_write) {
1546 		err = mark_stack_may_write(instance, frame, insn_idx, slot_lo, slot_hi);
1547 		if (err)
1548 			return err;
1549 	}
1550 	if (info.must_write && info.size != U32_MAX && arg->off_cnt == 1) {
1551 		/* Mark only fully covered slots as def */
1552 		slot_hi = (-fp_off) / STACK_SLOT_SZ - 1;
1553 		slot_lo = max_t(s32, (-fp_off - info.size + STACK_SLOT_SZ - 1) / STACK_SLOT_SZ, 0);
1554 		return mark_stack_write(instance, frame, insn_idx, slot_lo, slot_hi);
1555 	}
1556 	return 0;
1557 }
1558 
1559 /* Record access through a pointer with a known frame and possibly known offsets. */
1560 static int record_stack_access(struct bpf_verifier_env *env,
1561 			       struct func_instance *instance,
1562 			       const struct arg_track *arg,
1563 			       struct arg_access_info info, u32 frame, u32 insn_idx)
1564 {
1565 	int i, err;
1566 
1567 	if (!info.size)
1568 		return 0;
1569 	if (arg->off_cnt == 0) {
1570 		if (info.may_read) {
1571 			err = mark_stack_read_all(env, instance, frame, insn_idx);
1572 			if (err)
1573 				return err;
1574 		}
1575 		if (info.may_write) {
1576 			err = mark_stack_may_write_all(env, instance, frame, insn_idx);
1577 			if (err)
1578 				return err;
1579 		}
1580 		return 0;
1581 	}
1582 	for (i = 0; i < arg->off_cnt; i++) {
1583 		err = record_stack_access_off(instance, arg, i, info, frame, insn_idx);
1584 		if (err)
1585 			return err;
1586 	}
1587 	return 0;
1588 }
1589 
1590 /* Record possible effects on every candidate frame of an imprecise pointer. */
1591 static int record_imprecise(struct bpf_verifier_env *env, struct func_instance *instance,
1592 			    struct arg_access_info info, u32 mask, u32 insn_idx)
1593 {
1594 	int depth = instance->depth;
1595 	int f, err;
1596 
1597 	for (f = 0; mask; f++, mask >>= 1) {
1598 		if (!(mask & 1))
1599 			continue;
1600 		if (f <= depth) {
1601 			if (info.may_read) {
1602 				err = mark_stack_read_all(env, instance, f, insn_idx);
1603 				if (err)
1604 					return err;
1605 			}
1606 			if (info.may_write) {
1607 				err = mark_stack_may_write_all(env, instance, f, insn_idx);
1608 				if (err)
1609 					return err;
1610 			}
1611 		}
1612 	}
1613 	return 0;
1614 }
1615 
1616 /* Record load/store access for a given 'at' state of 'insn'. */
1617 static int record_load_store_access(struct bpf_verifier_env *env,
1618 				    struct func_instance *instance,
1619 				    struct arg_track *at, int insn_idx)
1620 {
1621 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
1622 	struct arg_access_info info = {};
1623 	int depth = instance->depth;
1624 	u8 class = BPF_CLASS(insn->code);
1625 	bool read = false, write = false;
1626 	struct arg_track resolved, *ptr;
1627 	int oi;
1628 
1629 	/*
1630 	 * Stack arg insns use dst_reg/src_reg=BPF_REG_PARAMS(11). Since at[]
1631 	 * is extended to MAX_AT_TRACK_REGS, at[11] holds the arg_track for
1632 	 * outgoing stack arg slot 0 — not the pointer used for the memory
1633 	 * access. Skip so the slot's tracked value isn't confused with the
1634 	 * base register that record_stack_access() expects.
1635 	 */
1636 	if (is_stack_arg_stx(insn) || is_stack_arg_st(insn) || is_stack_arg_ldx(insn))
1637 		return 0;
1638 
1639 	switch (class) {
1640 	case BPF_LDX:
1641 		ptr = &at[insn->src_reg];
1642 		read = true;
1643 		break;
1644 	case BPF_STX:
1645 		if (BPF_MODE(insn->code) == BPF_ATOMIC) {
1646 			switch (insn->imm) {
1647 			case BPF_LOAD_ACQ:
1648 				ptr = &at[insn->src_reg];
1649 				read = true;
1650 				break;
1651 			case BPF_STORE_REL:
1652 				ptr = &at[insn->dst_reg];
1653 				write = true;
1654 				break;
1655 			default:
1656 				/* ADD/AND/OR/XOR(+FETCH), XCHG, CMPXCHG */
1657 				ptr = &at[insn->dst_reg];
1658 				read = true;
1659 				write = true;
1660 				break;
1661 			}
1662 		} else {
1663 			ptr = &at[insn->dst_reg];
1664 			write = true;
1665 		}
1666 		break;
1667 	case BPF_ST:
1668 		ptr = &at[insn->dst_reg];
1669 		write = true;
1670 		break;
1671 	default:
1672 		return 0;
1673 	}
1674 
1675 	/* Resolve offsets: fold insn->off into arg_track */
1676 	if (ptr->off_cnt > 0) {
1677 		resolved.off_cnt = ptr->off_cnt;
1678 		resolved.frame = ptr->frame;
1679 		for (oi = 0; oi < ptr->off_cnt; oi++) {
1680 			if (arg_add(ptr->off[oi], insn->off, &resolved.off[oi])) {
1681 				resolved.off_cnt = 0;
1682 				break;
1683 			}
1684 		}
1685 		ptr = &resolved;
1686 	}
1687 
1688 	info.may_read = read;
1689 	info.may_write = write;
1690 	info.must_write = write;
1691 	info.size = bpf_size_to_bytes(BPF_SIZE(insn->code));
1692 	if (ptr->frame >= 0 && ptr->frame <= depth)
1693 		return record_stack_access(env, instance, ptr, info, ptr->frame, insn_idx);
1694 	if (ptr->frame == ARG_IMPRECISE)
1695 		return record_imprecise(env, instance, info, ptr->mask, insn_idx);
1696 	/* ARG_NONE: not derived from any frame pointer, skip */
1697 	return 0;
1698 }
1699 
1700 static int record_arg_access(struct bpf_verifier_env *env,
1701 			     struct func_instance *instance,
1702 			     struct bpf_insn *insn,
1703 			     struct arg_track *at, int arg_idx,
1704 			     int insn_idx)
1705 {
1706 	struct arg_access_info info;
1707 	int depth = instance->depth;
1708 	int frame = at->frame;
1709 	int err = 0;
1710 
1711 	if (!arg_is_fp(at))
1712 		return 0;
1713 
1714 	if (bpf_helper_call(insn)) {
1715 		info = bpf_helper_stack_access_bytes(env, insn, arg_idx, insn_idx);
1716 	} else if (bpf_pseudo_kfunc_call(insn)) {
1717 		info = bpf_kfunc_stack_access_bytes(env, insn, arg_idx, insn_idx);
1718 	} else if (bpf_pseudo_call(insn)) {
1719 		info = bpf_global_subprog_stack_access_bytes(env, insn, arg_idx, insn_idx);
1720 	} else {
1721 		for (int f = 0; f <= depth; f++) {
1722 			err = mark_stack_read_all(env, instance, f, insn_idx);
1723 			if (err)
1724 				return err;
1725 			err = mark_stack_may_write_all(env, instance, f, insn_idx);
1726 			if (err)
1727 				return err;
1728 		}
1729 		return 0;
1730 	}
1731 	if (!info.size)
1732 		return 0;
1733 
1734 	if (frame >= 0 && frame <= depth)
1735 		err = record_stack_access(env, instance, at, info, frame, insn_idx);
1736 	else if (frame == ARG_IMPRECISE)
1737 		err = record_imprecise(env, instance, info, at->mask, insn_idx);
1738 	return err;
1739 }
1740 
1741 /* Record stack access for a given 'at' state of helper/kfunc/global subprog 'insn' */
1742 static int record_call_access(struct bpf_verifier_env *env,
1743 			      struct func_instance *instance,
1744 			      struct arg_track *at,
1745 			      int insn_idx)
1746 {
1747 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
1748 	struct bpf_call_summary cs;
1749 	int r, err, callee, arg_slot_cnt = 5;
1750 
1751 	if (bpf_pseudo_call(insn)) {
1752 		/*
1753 		 * analyze_subprog() handles static callees. For global callees,
1754 		 * derive effects from argument types so may_write marks remain
1755 		 * conservative under freplace.
1756 		 */
1757 		callee = bpf_find_subprog(env, insn_idx + insn->imm + 1);
1758 		if (callee < 0 || !bpf_subprog_is_global(env, callee))
1759 			return 0;
1760 		arg_slot_cnt = MAX_BPF_FUNC_ARGS;
1761 	} else if (bpf_is_callx(insn))
1762 		/*
1763 		 * The callee is not known statically. Assume that all arg
1764 		 * slots are passed and let record_arg_access() conservatively
1765 		 * mark the stack of all frames as read if any of them is
1766 		 * derived from a frame pointer.
1767 		 */
1768 		arg_slot_cnt = MAX_BPF_FUNC_REG_ARGS + MAX_STACK_ARG_SLOTS;
1769 	else if (bpf_get_call_summary(env, insn, &cs))
1770 		arg_slot_cnt = cs.arg_slot_cnt;
1771 
1772 	for (r = BPF_REG_1; r < BPF_REG_1 + min(arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS); r++) {
1773 		err = record_arg_access(env, instance, insn, &at[r], r - 1, insn_idx);
1774 		if (err)
1775 			return err;
1776 	}
1777 
1778 	for (r = 0; r < MAX_STACK_ARG_SLOTS && r < arg_slot_cnt - MAX_BPF_FUNC_REG_ARGS; r++) {
1779 		err = record_arg_access(env, instance, insn, &at[MAX_BPF_REG + r],
1780 					r + MAX_BPF_FUNC_REG_ARGS, insn_idx);
1781 		if (err)
1782 			return err;
1783 	}
1784 	return 0;
1785 }
1786 
1787 /*
1788  * For a calls_callback helper, find the callback subprog and determine
1789  * which caller register maps to which callback register for FP passthrough.
1790  */
1791 static int find_callback_subprog(struct bpf_verifier_env *env,
1792 				 struct bpf_insn *insn, int insn_idx,
1793 				 int *caller_reg, int *callee_reg)
1794 {
1795 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
1796 	int cb_reg = -1;
1797 
1798 	*caller_reg = -1;
1799 	*callee_reg = -1;
1800 
1801 	if (!bpf_helper_call(insn))
1802 		return -1;
1803 	switch (insn->imm) {
1804 	case BPF_FUNC_loop:
1805 		/* bpf_loop(nr, cb, ctx, flags): cb=R2, R3->cb R2 */
1806 		cb_reg = BPF_REG_2;
1807 		*caller_reg = BPF_REG_3;
1808 		*callee_reg = BPF_REG_2;
1809 		break;
1810 	case BPF_FUNC_for_each_map_elem:
1811 		/* for_each_map_elem(map, cb, ctx, flags): cb=R2, R3->cb R4 */
1812 		cb_reg = BPF_REG_2;
1813 		*caller_reg = BPF_REG_3;
1814 		*callee_reg = BPF_REG_4;
1815 		break;
1816 	case BPF_FUNC_find_vma:
1817 		/* find_vma(task, addr, cb, ctx, flags): cb=R3, R4->cb R3 */
1818 		cb_reg = BPF_REG_3;
1819 		*caller_reg = BPF_REG_4;
1820 		*callee_reg = BPF_REG_3;
1821 		break;
1822 	case BPF_FUNC_user_ringbuf_drain:
1823 		/* user_ringbuf_drain(map, cb, ctx, flags): cb=R2, R3->cb R2 */
1824 		cb_reg = BPF_REG_2;
1825 		*caller_reg = BPF_REG_3;
1826 		*callee_reg = BPF_REG_2;
1827 		break;
1828 	default:
1829 		return -1;
1830 	}
1831 
1832 	if (!(aux->const_reg_subprog_mask & BIT(cb_reg)))
1833 		return -2;
1834 
1835 	return aux->const_reg_vals[cb_reg];
1836 }
1837 
1838 /* Per-subprog intermediate state kept alive across analysis phases */
1839 struct subprog_at_info {
1840 	struct arg_track (*at_in)[MAX_AT_TRACK_REGS];
1841 	int len;
1842 };
1843 
1844 static void print_subprog_arg_access(struct bpf_verifier_env *env,
1845 				     int subprog,
1846 				     struct subprog_at_info *info,
1847 				     struct arg_track *at_stack_in, u32 nslots)
1848 {
1849 	struct bpf_insn *insns = env->prog->insnsi;
1850 	int start = env->subprog_info[subprog].start;
1851 	int len = info->len;
1852 	int i, r;
1853 
1854 	if (!(env->log.level & BPF_LOG_LEVEL2))
1855 		return;
1856 
1857 	verbose(env, "%s:\n", fmt_subprog(env, subprog));
1858 	for (i = 0; i < len; i++) {
1859 		int idx = start + i;
1860 		bool has_extra = false;
1861 		u8 cls = BPF_CLASS(insns[idx].code);
1862 		bool is_ldx_stx_call = cls == BPF_LDX || cls == BPF_STX ||
1863 				       (cls == BPF_JMP && BPF_OP(insns[idx].code) == BPF_CALL);
1864 
1865 		verbose(env, "%3d: ", idx);
1866 		bpf_verbose_insn(env, &insns[idx]);
1867 		verbose(env, "\n");
1868 
1869 		/* Collect what needs printing */
1870 		if (is_ldx_stx_call &&
1871 		    arg_is_visited(&info->at_in[i][0])) {
1872 			for (r = 0; r < MAX_BPF_REG - 1; r++)
1873 				if (arg_is_fp(&info->at_in[i][r]))
1874 					has_extra = true;
1875 			for (r = 0; r < MAX_STACK_ARG_SLOTS; r++)
1876 				if (arg_is_fp(&info->at_in[i][MAX_BPF_REG + r]))
1877 					has_extra = true;
1878 		}
1879 		if (is_ldx_stx_call) {
1880 			for (r = 0; r < nslots; r++)
1881 				if (arg_is_fp(&at_stack_in[(size_t)i * nslots + r]))
1882 					has_extra = true;
1883 		}
1884 
1885 		if (!has_extra) {
1886 			if (bpf_is_ldimm64(&insns[idx]))
1887 				i++;
1888 			continue;
1889 		}
1890 
1891 		bpf_vlog_reset(&env->log, env->log.end_pos - 1);
1892 		verbose(env, " //");
1893 
1894 		if (is_ldx_stx_call && info->at_in &&
1895 		    arg_is_visited(&info->at_in[i][0])) {
1896 			for (r = 0; r < MAX_BPF_REG - 1; r++) {
1897 				if (!arg_is_fp(&info->at_in[i][r]))
1898 					continue;
1899 				verbose(env, " r%d=", r);
1900 				verbose_arg_track(env, &info->at_in[i][r]);
1901 			}
1902 			for (r = 0; r < MAX_STACK_ARG_SLOTS; r++) {
1903 				if (!arg_is_fp(&info->at_in[i][MAX_BPF_REG + r]))
1904 					continue;
1905 				verbose(env, " sa%d=", r);
1906 				verbose_arg_track(env, &info->at_in[i][MAX_BPF_REG + r]);
1907 			}
1908 		}
1909 
1910 		if (is_ldx_stx_call) {
1911 			for (r = 0; r < nslots; r++) {
1912 				if (!arg_is_fp(&at_stack_in[(size_t)i * nslots + r]))
1913 					continue;
1914 				verbose(env, " fp%+d=", -(r + 1) * 8);
1915 				verbose_arg_track(env, &at_stack_in[(size_t)i * nslots + r]);
1916 			}
1917 		}
1918 
1919 		verbose(env, "\n");
1920 		if (bpf_is_ldimm64(&insns[idx]))
1921 			i++;
1922 	}
1923 }
1924 
1925 static void record_stack_ptrs(struct bpf_verifier_env *env, int idx, struct arg_track *at_in)
1926 {
1927 	u16 r, mask = 0;
1928 
1929 	for (r = 0; r < MAX_BPF_REG; r++)
1930 		if (arg_is_fp(&at_in[r]))
1931 			mask |= BIT(r);
1932 
1933 	env->insn_aux_data[idx].stack_ptrs |= mask;
1934 }
1935 
1936 /*
1937  * Compute arg tracking dataflow for a single subprog.
1938  * Runs forward fixed-point with arg_track_xfer(), then records
1939  * memory accesses in a single linear pass over converged state.
1940  *
1941  * @callee_entry: pre-populated entry state for R1-R5 and stack args
1942  *                NULL for main (subprog 0).
1943  * @info:         stores at_in, len for debug printing.
1944  */
1945 static int compute_subprog_args(struct bpf_verifier_env *env,
1946 				struct subprog_at_info *info,
1947 				struct arg_track *callee_entry,
1948 				struct func_instance *instance,
1949 				u32 *callsites)
1950 {
1951 	int subprog = instance->subprog;
1952 	struct bpf_insn *insns = env->prog->insnsi;
1953 	int depth = instance->depth;
1954 	int start = env->subprog_info[subprog].start;
1955 	int po_start = env->subprog_info[subprog].postorder_start;
1956 	int end = env->subprog_info[subprog + 1].start;
1957 	int po_end = env->subprog_info[subprog + 1].postorder_start;
1958 	int len = end - start;
1959 	u32 nslots = min(subprog_spill_slots(env, start, end), spill_slots_affordable(len));
1960 	struct arg_track (*at_in)[MAX_AT_TRACK_REGS] = NULL;
1961 	struct arg_track at_out[MAX_AT_TRACK_REGS];
1962 	struct arg_track *at_stack_in = NULL;
1963 	struct arg_track *at_stack_out = NULL;
1964 	struct arg_track at_stack_arg_entry[MAX_STACK_ARG_SLOTS];
1965 	struct arg_track unvisited = { .frame = ARG_UNVISITED };
1966 	struct arg_track none = { .frame = ARG_NONE };
1967 	bool changed;
1968 	int i, p, r, err = -ENOMEM;
1969 
1970 	at_in = kvmalloc_objs(*at_in, len, GFP_KERNEL_ACCOUNT);
1971 	if (!at_in)
1972 		goto err_free;
1973 
1974 	at_stack_in = kvmalloc_objs(*at_stack_in, (size_t)len * nslots, GFP_KERNEL_ACCOUNT);
1975 	if (!at_stack_in)
1976 		goto err_free;
1977 
1978 	at_stack_out = kvmalloc_objs(*at_stack_out, nslots, GFP_KERNEL_ACCOUNT);
1979 	if (!at_stack_out)
1980 		goto err_free;
1981 
1982 	for (i = 0; i < len; i++) {
1983 		for (r = 0; r < MAX_AT_TRACK_REGS; r++)
1984 			at_in[i][r] = unvisited;
1985 		for (r = 0; r < nslots; r++)
1986 			at_stack_in[(size_t)i * nslots + r] = unvisited;
1987 	}
1988 
1989 	for (r = 0; r < MAX_AT_TRACK_REGS; r++)
1990 		at_in[0][r] = none;
1991 
1992 	/* Entry: R10 is always precisely the current frame's FP */
1993 	at_in[0][BPF_REG_FP] = arg_single(depth, 0);
1994 
1995 	/* R1-R5: from caller or ARG_NONE for main */
1996 	if (callee_entry) {
1997 		for (r = BPF_REG_1; r <= BPF_REG_5; r++)
1998 			at_in[0][r] = callee_entry[r];
1999 	}
2000 
2001 	/* Entry: all stack slots are ARG_NONE */
2002 	for (r = 0; r < nslots; r++)
2003 		at_stack_in[r] = none;
2004 
2005 	/* Entry: incoming stack args from caller, or ARG_NONE for main */
2006 	for (r = 0; r < MAX_STACK_ARG_SLOTS; r++)
2007 		at_stack_arg_entry[r] = callee_entry ? callee_entry[MAX_BPF_REG + r] : none;
2008 
2009 	if (env->log.level & BPF_LOG_LEVEL2)
2010 		verbose(env, "subprog#%d: analyzing (depth %d)...\n", subprog, depth);
2011 
2012 	/* Forward fixed-point iteration in reverse post order */
2013 redo:
2014 	changed = false;
2015 	for (p = po_end - 1; p >= po_start; p--) {
2016 		int idx = env->cfg.insn_postorder[p];
2017 		int i = idx - start;
2018 		struct bpf_insn *insn = &insns[idx];
2019 		struct bpf_iarray *succ;
2020 
2021 		if (!arg_is_visited(&at_in[i][0]) && !arg_is_visited(&at_in[i][1]))
2022 			continue;
2023 
2024 		memcpy(at_out, at_in[i], sizeof(at_out));
2025 		memcpy(at_stack_out, &at_stack_in[(size_t)i * nslots], nslots * sizeof(*at_stack_out));
2026 
2027 		arg_track_xfer(env, insn, idx, at_out, at_stack_out, nslots,
2028 			       at_stack_arg_entry, instance, callsites);
2029 		arg_track_log(env, insn, idx, at_in[i], &at_stack_in[(size_t)i * nslots], at_out,
2030 			      at_stack_out, nslots);
2031 
2032 		/* Propagate to successors within this subprogram */
2033 		succ = bpf_insn_successors(env, idx);
2034 		for (int s = 0; s < succ->cnt; s++) {
2035 			int target = succ->items[s];
2036 			int ti;
2037 
2038 			/* Filter: stay within the subprogram's range */
2039 			if (target < start || target >= end)
2040 				continue;
2041 			ti = target - start;
2042 
2043 			for (r = 0; r < MAX_AT_TRACK_REGS; r++)
2044 				changed |= arg_track_join(env, idx, target, r,
2045 							  &at_in[ti][r], at_out[r]);
2046 
2047 			for (r = 0; r < nslots; r++)
2048 				changed |= arg_track_join(env, idx, target, -r - 1,
2049 							  &at_stack_in[(size_t)ti * nslots + r],
2050 							  at_stack_out[r]);
2051 		}
2052 	}
2053 	if (changed)
2054 		goto redo;
2055 
2056 	/* Record memory accesses using converged at_in (RPO skips dead code) */
2057 	for (p = po_end - 1; p >= po_start; p--) {
2058 		int idx = env->cfg.insn_postorder[p];
2059 		int i = idx - start;
2060 		struct bpf_insn *insn = &insns[idx];
2061 
2062 		err = record_load_store_access(env, instance, at_in[i], idx);
2063 		if (err)
2064 			goto err_free;
2065 
2066 		if (BPF_CLASS(insn->code) == BPF_JMP && BPF_OP(insn->code) == BPF_CALL) {
2067 			err = record_call_access(env, instance, at_in[i], idx);
2068 			if (err)
2069 				goto err_free;
2070 		}
2071 
2072 		if (bpf_pseudo_call(insn) || bpf_calls_callback(env, idx)) {
2073 			struct spill_snapshot *snap;
2074 
2075 			kvfree(env->callsite_at_stack[idx]);
2076 			env->callsite_at_stack[idx] = kvmalloc_flex(*snap, at, nslots, GFP_KERNEL_ACCOUNT);
2077 			snap = env->callsite_at_stack[idx];
2078 			if (!snap) {
2079 				err = -ENOMEM;
2080 				goto err_free;
2081 			}
2082 			snap->slots = nslots;
2083 			memcpy(snap->at, &at_stack_in[(size_t)i * nslots], nslots * sizeof(*snap->at));
2084 		}
2085 
2086 		record_stack_ptrs(env, idx, at_in[i]);
2087 	}
2088 
2089 	info->at_in = at_in;
2090 	at_in = NULL;
2091 	info->len = len;
2092 	print_subprog_arg_access(env, subprog, info, at_stack_in, nslots);
2093 	err = 0;
2094 
2095 err_free:
2096 	kvfree(at_stack_out);
2097 	kvfree(at_stack_in);
2098 	kvfree(at_in);
2099 	return err;
2100 }
2101 
2102 /* Return true if any of R1-R5 or stack args is derived from a frame pointer. */
2103 static bool has_fp_args(struct arg_track *args)
2104 {
2105 	for (int r = BPF_REG_1; r <= BPF_REG_5; r++)
2106 		if (arg_is_fp(&args[r]))
2107 			return true;
2108 	for (int r = 0; r < MAX_STACK_ARG_SLOTS; r++)
2109 		if (arg_is_fp(&args[MAX_BPF_REG + r]))
2110 			return true;
2111 	return false;
2112 }
2113 
2114 /*
2115  * Merge a freshly analyzed instance into the original.
2116  * may_read: union (any pass might read the slot).
2117  * may_write: union (slots written on ANY pass).
2118  * must_write: intersection (only slots written on ALL passes are guaranteed).
2119  * live_before is recomputed by a subsequent update_instance() on @dst.
2120  *
2121  * The two instances may have settled on different mask widths for the same
2122  * frame, so @dst is widened to cover @src first. A word only @dst has counts
2123  * as zero on the @src side: it unions into may_read as a no-op and intersects
2124  * must_write to empty.
2125  */
2126 static int merge_instances(struct func_instance *dst, struct func_instance *src)
2127 {
2128 	struct frame_masks *d, *s;
2129 	u32 f, i, w;
2130 
2131 	for (f = 0; f <= dst->depth; f++) {
2132 		s = src->frames[f];
2133 		d = dst->frames[f];
2134 		if (!s) {
2135 			/* This pass didn't touch frame f — must_write intersects with empty. */
2136 			if (d)
2137 				for (i = 0; i < dst->insn_cnt; i++)
2138 					bitmap_zero(rel_mask(d, i, FM_MUST_WRITE),
2139 						    frame_mask_bits(d));
2140 			continue;
2141 		}
2142 		if (!d) {
2143 			/* Previous pass didn't touch frame f — take src, zero must_write. */
2144 			dst->frames[f] = s;
2145 			src->frames[f] = NULL;
2146 			for (i = 0; i < dst->insn_cnt; i++)
2147 				bitmap_zero(rel_mask(s, i, FM_MUST_WRITE), frame_mask_bits(s));
2148 			continue;
2149 		}
2150 		d = widen_frame_masks(dst, f, s->words);
2151 		if (!d)
2152 			return -ENOMEM;
2153 		for (i = 0; i < dst->insn_cnt; i++) {
2154 			unsigned long *dst_read = rel_mask(d, i, FM_MAY_READ);
2155 			unsigned long *dst_write = rel_mask(d, i, FM_MUST_WRITE);
2156 			unsigned long *dst_may_write = rel_mask(d, i, FM_MAY_WRITE);
2157 			unsigned long *src_read = rel_mask(s, i, FM_MAY_READ);
2158 			unsigned long *src_write = rel_mask(s, i, FM_MUST_WRITE);
2159 			unsigned long *src_may_write = rel_mask(s, i, FM_MAY_WRITE);
2160 
2161 			for (w = 0; w < d->words; w++) {
2162 				dst_read[w] |= w < s->words ? src_read[w] : 0;
2163 				dst_write[w] &= w < s->words ? src_write[w] : 0;
2164 				dst_may_write[w] |= w < s->words ? src_may_write[w] : 0;
2165 			}
2166 		}
2167 	}
2168 	return 0;
2169 }
2170 
2171 /*
2172  * Fold a fully analyzed callee instance writes to upper frames as
2173  * may_write marks at callsite in caller's frames.
2174  */
2175 static int merge_may_write(struct func_instance *caller, struct func_instance *callee)
2176 {
2177 	DECLARE_BITMAP(acc, FRAME_HALF_SPIS);
2178 	u32 call_idx = callee->callsite;
2179 	struct frame_masks *fm;
2180 	u32 f, i, nbits;
2181 	int err;
2182 
2183 	for (f = 0; f < callee->depth; f++) {
2184 		fm = callee->frames[f];
2185 		if (!fm)
2186 			continue;
2187 		nbits = frame_mask_bits(fm);
2188 		bitmap_zero(acc, nbits);
2189 		for (i = 0; i < callee->insn_cnt; i++)
2190 			bitmap_or(acc, acc, rel_mask(fm, i, FM_MAY_WRITE), nbits);
2191 		if (bitmap_empty(acc, nbits))
2192 			continue;
2193 		err = mark_stack_mask(caller, f, call_idx, FM_MAY_WRITE, acc, fm->words);
2194 		if (err)
2195 			return err;
2196 	}
2197 	return 0;
2198 }
2199 
2200 static struct func_instance *fresh_instance(struct func_instance *src)
2201 {
2202 	struct func_instance *f;
2203 
2204 	f = kvzalloc_obj(*f, GFP_KERNEL_ACCOUNT);
2205 	if (!f)
2206 		return ERR_PTR(-ENOMEM);
2207 	f->callsite = src->callsite;
2208 	f->depth = src->depth;
2209 	f->subprog = src->subprog;
2210 	f->subprog_start = src->subprog_start;
2211 	f->insn_cnt = src->insn_cnt;
2212 	return f;
2213 }
2214 
2215 static void free_instance(struct func_instance *instance)
2216 {
2217 	int i;
2218 
2219 	for (i = 0; i <= instance->depth; i++)
2220 		kvfree(instance->frames[i]);
2221 	kvfree(instance);
2222 }
2223 
2224 /*
2225  * Recursively analyze a subprog with specific 'entry_args'.
2226  * Each callee is analyzed with the exact args from its call site.
2227  *
2228  * Args are recomputed for each call because the dataflow result at_in[]
2229  * depends on the entry args and frame depth. Consider: A->C->D and B->C->D
2230  * Callsites in A and B pass different args into C, so C is recomputed.
2231  * Then within C the same callsite passes different args into D.
2232  */
2233 static int analyze_subprog(struct bpf_verifier_env *env,
2234 			   struct arg_track *entry_args,
2235 			   struct subprog_at_info *info,
2236 			   struct func_instance *instance,
2237 			   u32 *callsites)
2238 {
2239 	int subprog = instance->subprog;
2240 	int depth = instance->depth;
2241 	struct bpf_insn *insns = env->prog->insnsi;
2242 	int start = env->subprog_info[subprog].start;
2243 	int po_start = env->subprog_info[subprog].postorder_start;
2244 	int po_end = env->subprog_info[subprog + 1].postorder_start;
2245 	struct func_instance *prev_instance = NULL;
2246 	int j, err;
2247 
2248 	if (++env->liveness->subprog_calls > 10000) {
2249 		verbose(env, "liveness analysis exceeded complexity limit (%d calls)\n",
2250 			env->liveness->subprog_calls);
2251 		return -E2BIG;
2252 	}
2253 
2254 	if (need_resched())
2255 		cond_resched();
2256 
2257 	/*
2258 	 * When an instance is reused (must_write_initialized == true),
2259 	 * record into a fresh instance and merge afterward.  This avoids
2260 	 * stale must_write marks for instructions not reached in this pass.
2261 	 */
2262 	if (instance->must_write_initialized) {
2263 		struct func_instance *fresh = fresh_instance(instance);
2264 
2265 		if (IS_ERR(fresh))
2266 			return PTR_ERR(fresh);
2267 		prev_instance = instance;
2268 		instance = fresh;
2269 	}
2270 
2271 	/* Free prior analysis if this subprog was already visited */
2272 	kvfree(info[subprog].at_in);
2273 	info[subprog].at_in = NULL;
2274 
2275 	err = compute_subprog_args(env, &info[subprog], entry_args, instance, callsites);
2276 	if (err)
2277 		goto out_free;
2278 
2279 	/* For each reachable call site in the subprog, recurse into callees */
2280 	for (int p = po_start; p < po_end; p++) {
2281 		int idx = env->cfg.insn_postorder[p];
2282 		struct arg_track callee_args[MAX_AT_TRACK_REGS] = {};
2283 		struct arg_track none = { .frame = ARG_NONE };
2284 		struct bpf_insn *insn = &insns[idx];
2285 		struct func_instance *callee_instance;
2286 		int callee, target;
2287 		int caller_reg, cb_callee_reg;
2288 
2289 		j = idx - start; /* relative index within this subprog */
2290 
2291 		if (bpf_pseudo_call(insn)) {
2292 			target = idx + insn->imm + 1;
2293 			callee = bpf_find_subprog(env, target);
2294 			/*
2295 			 * Global subprograms can be freplaced, so conservatively derive
2296 			 * their stack effects from their BTF signatures instead of
2297 			 * analyzing them in the context of their callers.
2298 			 */
2299 			if (callee < 0 || bpf_subprog_is_global(env, callee))
2300 				continue;
2301 
2302 			/* Build entry args: R1-R5 and stack args from at_in at call site */
2303 			for (int r = BPF_REG_1; r <= BPF_REG_5; r++)
2304 				callee_args[r] = info[subprog].at_in[j][r];
2305 			for (int r = 0; r < MAX_STACK_ARG_SLOTS; r++)
2306 				callee_args[MAX_BPF_REG + r] = info[subprog].at_in[j][MAX_BPF_REG + r];
2307 		} else if (bpf_calls_callback(env, idx)) {
2308 			callee = find_callback_subprog(env, insn, idx, &caller_reg, &cb_callee_reg);
2309 			if (callee == -2) {
2310 				/*
2311 				 * same bpf_loop() calls two different callbacks and passes
2312 				 * stack pointer to them
2313 				 */
2314 				if (info[subprog].at_in[j][caller_reg].frame == ARG_NONE)
2315 					continue;
2316 				for (int f = 0; f <= depth; f++) {
2317 					err = mark_stack_read_all(env, instance, f, idx);
2318 					if (err)
2319 						goto out_free;
2320 					err = mark_stack_may_write_all(env, instance, f, idx);
2321 					if (err)
2322 						goto out_free;
2323 				}
2324 				continue;
2325 			}
2326 			if (callee < 0)
2327 				continue;
2328 
2329 			for (int r = BPF_REG_1; r <= BPF_REG_5; r++)
2330 				callee_args[r] = none;
2331 			for (int r = 0; r < MAX_STACK_ARG_SLOTS; r++)
2332 				callee_args[MAX_BPF_REG + r] = none;
2333 			callee_args[cb_callee_reg] = info[subprog].at_in[j][caller_reg];
2334 		} else {
2335 			continue;
2336 		}
2337 
2338 		if (!has_fp_args(callee_args))
2339 			continue;
2340 
2341 		if (depth == MAX_CALL_FRAMES - 1) {
2342 			err = -EINVAL;
2343 			goto out_free;
2344 		}
2345 
2346 		callee_instance = call_instance(env, instance, idx, callee);
2347 		if (IS_ERR(callee_instance)) {
2348 			err = PTR_ERR(callee_instance);
2349 			goto out_free;
2350 		}
2351 		callsites[depth] = idx;
2352 		err = analyze_subprog(env, callee_args, info, callee_instance, callsites);
2353 		if (err)
2354 			goto out_free;
2355 
2356 		/* Pull callee's entry liveness back to caller's callsite */
2357 		{
2358 			u32 callee_start = callee_instance->subprog_start;
2359 			struct frame_masks *callee_fm;
2360 
2361 			for (int f = 0; f < callee_instance->depth; f++) {
2362 				callee_fm = callee_instance->frames[f];
2363 				if (!callee_fm)
2364 					continue;
2365 				err = mark_stack_read_mask(instance, f, idx,
2366 							   rel_mask(callee_fm,
2367 								    relative_idx(callee_instance,
2368 										 callee_start),
2369 								    FM_LIVE_BEFORE),
2370 							   callee_fm->words);
2371 				if (err)
2372 					goto out_free;
2373 			}
2374 		}
2375 
2376 		/* Summarize callee's writes to ancestor frames onto the callsite */
2377 		err = merge_may_write(instance, callee_instance);
2378 		if (err)
2379 			goto out_free;
2380 	}
2381 
2382 	if (prev_instance) {
2383 		err = merge_instances(prev_instance, instance);
2384 		free_instance(instance);
2385 		instance = prev_instance;
2386 		if (err)
2387 			return err;
2388 	}
2389 	update_instance(env, instance);
2390 	return 0;
2391 
2392 out_free:
2393 	if (prev_instance)
2394 		free_instance(instance);
2395 	return err;
2396 }
2397 
2398 int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env)
2399 {
2400 	u32 callsites[MAX_CALL_FRAMES] = {};
2401 	int insn_cnt = env->prog->len;
2402 	struct func_instance *instance;
2403 	struct subprog_at_info *info;
2404 	int k, err = 0;
2405 
2406 	info = kvzalloc_objs(*info, env->subprog_cnt, GFP_KERNEL_ACCOUNT);
2407 	if (!info)
2408 		return -ENOMEM;
2409 
2410 	env->callsite_at_stack = kvzalloc_objs(*env->callsite_at_stack, insn_cnt,
2411 					       GFP_KERNEL_ACCOUNT);
2412 	if (!env->callsite_at_stack) {
2413 		kvfree(info);
2414 		return -ENOMEM;
2415 	}
2416 
2417 	/*
2418 	 * Analyze every subprog in reverse topological order (callers
2419 	 * before callees) so that each subprog is analyzed before its
2420 	 * callees, allowing the recursive walk inside analyze_subprog()
2421 	 * to naturally reach callees that receive FP-derived args.
2422 	 *
2423 	 * Subprogs and callbacks that don't receive FP-derived arguments
2424 	 * cannot access ancestor stack frames are analyzed independently.
2425 	 * Async callbacks (timer, workqueue) are handled the same way.
2426 	 */
2427 	for (k = env->subprog_cnt - 1; k >= 0; k--) {
2428 		int sub = env->subprog_topo_order[k];
2429 
2430 		if (info[sub].at_in && !bpf_subprog_is_global(env, sub))
2431 			continue;
2432 		instance = call_instance(env, NULL, 0, sub);
2433 		if (IS_ERR(instance)) {
2434 			err = PTR_ERR(instance);
2435 			goto out;
2436 		}
2437 		err = analyze_subprog(env, NULL, info, instance, callsites);
2438 		if (err)
2439 			goto out;
2440 	}
2441 
2442 	compute_may_write_masks(env);
2443 
2444 	if (env->log.level & BPF_LOG_LEVEL2)
2445 		err = print_instances(env);
2446 
2447 out:
2448 	for (k = 0; k < insn_cnt; k++)
2449 		kvfree(env->callsite_at_stack[k]);
2450 	kvfree(env->callsite_at_stack);
2451 	env->callsite_at_stack = NULL;
2452 	for (k = 0; k < env->subprog_cnt; k++)
2453 		kvfree(info[k].at_in);
2454 	kvfree(info);
2455 	return err;
2456 }
2457 
2458 /* Each field is a register bitmask */
2459 struct insn_live_regs {
2460 	u32 use;	/* registers read by instruction */
2461 	u32 def;	/* registers written by instruction */
2462 	u32 in;		/* registers that may be alive before instruction */
2463 	u32 out;	/* registers that may be alive after instruction */
2464 };
2465 
2466 /* Bitmask with 1s for all caller saved registers */
2467 #define ALL_CALLER_SAVED_REGS ((1u << CALLER_SAVED_REGS) - 1)
2468 
2469 static inline u32 reg32_mask(u32 n) { return BIT(n); }
2470 static inline u32 reg64_mask(u32 n) { return BIT(n) | BIT(n + 16); }
2471 static inline u32 mask_widen(u32 m) { return m | (m << 16); }
2472 static inline u16 mask_lo(u32 m) { return (u16)m; }
2473 static inline u16 mask_hi(u32 m) { return (u16)(m >> 16); }
2474 
2475 /* Index of the subprogram called by pseudo call @insn */
2476 static int callee_subprog(struct bpf_verifier_env *env, const struct bpf_insn *insn)
2477 {
2478 	return bpf_find_subprog(env, insn - env->prog->insnsi + insn->imm + 1);
2479 }
2480 
2481 /* Compute info->{use,def} fields for the instruction */
2482 static void compute_insn_live_regs(struct bpf_verifier_env *env,
2483 				   struct bpf_insn *insn,
2484 				   struct insn_live_regs *info,
2485 				   bool ret_reg_pair)
2486 {
2487 	struct bpf_call_summary cs;
2488 	const u8 class = BPF_CLASS(insn->code);
2489 	const u8 code = BPF_OP(insn->code);
2490 	const u8 mode = BPF_MODE(insn->code);
2491 	const u8 size = BPF_SIZE(insn->code);
2492 	const u32 src = reg64_mask(insn->src_reg);
2493 	const u32 dst = reg64_mask(insn->dst_reg);
2494 	const u32 src32 = mask_lo(src);
2495 	const u32 dst32 = mask_lo(dst);
2496 	const u32 r0  = reg64_mask(0);
2497 	const u32 r2  = reg64_mask(BPF_REG_2);
2498 	int subprog, reg_args;
2499 	u32 def = 0;
2500 	u32 use = U32_MAX;
2501 
2502 	switch (class) {
2503 	case BPF_LD:
2504 		switch (mode) {
2505 		case BPF_IMM:
2506 			if (BPF_SIZE(insn->code) == BPF_DW) {
2507 				def = dst;
2508 				use = 0;
2509 			}
2510 			break;
2511 		case BPF_ABS:
2512 		case BPF_IND:
2513 			/* stick with defaults */
2514 			break;
2515 		}
2516 		break;
2517 	case BPF_LDX:
2518 		switch (mode) {
2519 		case BPF_MEM:
2520 			/* a narrow load still redefines the whole register */
2521 			def = dst;
2522 			use = src;
2523 			break;
2524 		case BPF_MEMSX:
2525 			/*
2526 			 * sign extension defines the whole register;
2527 			 * src holds a pointer, hence is used as 64-bit.
2528 			 */
2529 			def = dst;
2530 			use = src;
2531 			break;
2532 		}
2533 		break;
2534 	case BPF_ST:
2535 		switch (mode) {
2536 		case BPF_MEM:
2537 			def = 0;
2538 			use = dst;
2539 			break;
2540 		}
2541 		break;
2542 	case BPF_STX:
2543 		switch (mode) {
2544 		case BPF_MEM:
2545 			def = 0;
2546 			use = dst | (size == BPF_DW ? src : src32);
2547 			break;
2548 		case BPF_ATOMIC: {
2549 			/*
2550 			 * dst holds a pointer and is always used as 64-bit;
2551 			 * the value operand and r0 are read as 32-bit for BPF_W atomics.
2552 			 */
2553 			u32 srcv = size == BPF_DW ? src : src32;
2554 			u32 r0v  = size == BPF_DW ? r0 : mask_lo(r0);
2555 
2556 			switch (insn->imm) {
2557 			case BPF_CMPXCHG:
2558 				use = r0v | dst | srcv;
2559 				def = r0;
2560 				break;
2561 			case BPF_LOAD_ACQ:
2562 				def = dst;
2563 				use = src;
2564 				break;
2565 			case BPF_STORE_REL:
2566 				def = 0;
2567 				use = dst | srcv;
2568 				break;
2569 			default:
2570 				use = dst | srcv;
2571 				if (insn->imm & BPF_FETCH)
2572 					def = src;
2573 				else
2574 					def = 0;
2575 			}
2576 			break;
2577 		}
2578 		}
2579 		break;
2580 	case BPF_ALU:
2581 	case BPF_ALU64:
2582 		switch (code) {
2583 		case BPF_END:
2584 			use = dst;
2585 			def = dst;
2586 			break;
2587 		case BPF_MOV:
2588 			def = dst;
2589 			if (BPF_SRC(insn->code) == BPF_K)
2590 				use = 0;
2591 			else
2592 				use = class == BPF_ALU64 ? src : src32;
2593 			break;
2594 		default:
2595 			def = dst;
2596 			if (BPF_SRC(insn->code) == BPF_K)
2597 				use = class == BPF_ALU64 ? dst : dst32;
2598 			else
2599 				use = class == BPF_ALU64 ? (dst | src) : (dst32 | src32);
2600 		}
2601 		break;
2602 	case BPF_JMP:
2603 	case BPF_JMP32:
2604 		switch (code) {
2605 		case BPF_JA:
2606 			def = 0;
2607 			if (BPF_SRC(insn->code) == BPF_X)
2608 				use = dst;
2609 			else
2610 				use = 0;
2611 			break;
2612 		case BPF_JCOND:
2613 			def = 0;
2614 			use = 0;
2615 			break;
2616 		case BPF_EXIT:
2617 			def = 0;
2618 			use = ret_reg_pair ? (r0 | r2) : r0;
2619 			break;
2620 		case BPF_CALL:
2621 			def = ALL_CALLER_SAVED_REGS;
2622 			use = def & ~BIT(BPF_REG_0);
2623 			if (bpf_get_call_summary(env, insn, &cs)) {
2624 				use = GENMASK(min_t(u8, cs.arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS), 1);
2625 			} else if (bpf_pseudo_call(insn)) {
2626 				/* a static callee's reads are added in bpf_compute_live_registers() */
2627 				subprog = callee_subprog(env, insn);
2628 				if (bpf_subprog_is_global(env, subprog)) {
2629 					reg_args = min_t(u8, env->subprog_info[subprog].arg_slot_cnt, MAX_BPF_FUNC_REG_ARGS);
2630 					use = GENMASK(reg_args, 1);
2631 				} else {
2632 					use = 0;
2633 				}
2634 			}
2635 			def = mask_widen(def);
2636 			use = mask_widen(use);
2637 			/* callx reads the address of the callee from dst_reg */
2638 			if (bpf_is_callx(insn))
2639 				use |= dst;
2640 			break;
2641 		default:
2642 			def = 0;
2643 			use = class == BPF_JMP ? dst : dst32;
2644 			if (BPF_SRC(insn->code) == BPF_X)
2645 				use |= class == BPF_JMP ? src : src32;
2646 		}
2647 		break;
2648 	}
2649 
2650 	info->def = def;
2651 	info->use = use;
2652 }
2653 
2654 /* Compute may-live registers after each instruction in the program.
2655  * The register is live after the instruction I if it is read by some
2656  * instruction S following I during program execution and is not
2657  * overwritten between I and S.
2658  *
2659  * Store result in env->insn_aux_data[i].live_regs.
2660  */
2661 int bpf_compute_live_registers(struct bpf_verifier_env *env)
2662 {
2663 	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
2664 	struct bpf_insn *insns = env->prog->insnsi;
2665 	struct insn_live_regs *state;
2666 	int insn_cnt = env->prog->len;
2667 	int err = 0, i, subprog, start, end;
2668 	bool changed, ret_reg_pair;
2669 
2670 	/* Use the following algorithm:
2671 	 * - define the following:
2672 	 *   - I.use : a set of all registers read by instruction I;
2673 	 *   - I.def : a set of all registers written by instruction I;
2674 	 *   - I.in  : a set of all registers that may be alive before I execution;
2675 	 *   - I.out : a set of all registers that may be alive after I execution;
2676 	 *   - insn_successors(I): a set of instructions S that might immediately
2677 	 *                         follow I for some program execution;
2678 	 * - associate separate empty sets 'I.in' and 'I.out' with each instruction;
2679 	 * - visit each instruction in a postorder and update
2680 	 *   state[i].in, state[i].out as follows:
2681 	 *
2682 	 *       state[i].out = U [state[s].in for S in insn_successors(i)]
2683 	 *       state[i].in  = (state[i].out / state[i].def) U state[i].use
2684 	 *
2685 	 *   (where U stands for set union, / stands for set difference)
2686 	 * - repeat the computation while {in,out} fields changes for
2687 	 *   any instruction.
2688 	 */
2689 	state = kvzalloc_objs(*state, insn_cnt, GFP_KERNEL_ACCOUNT);
2690 	if (!state) {
2691 		err = -ENOMEM;
2692 		goto out;
2693 	}
2694 
2695 	for (subprog = 0; subprog < env->subprog_cnt; subprog++) {
2696 		start = env->subprog_info[subprog].start;
2697 		end = env->subprog_info[subprog + 1].start;
2698 		ret_reg_pair = bpf_ret_reg_pair(env, subprog);
2699 
2700 		for (i = start; i < end; ++i)
2701 			compute_insn_live_regs(env, &insns[i], &state[i], ret_reg_pair);
2702 	}
2703 
2704 	/* Forward pass: resolve stack access through FP-derived pointers */
2705 	err = bpf_compute_subprog_arg_access(env);
2706 	if (err)
2707 		goto out;
2708 
2709 	changed = true;
2710 	while (changed) {
2711 		changed = false;
2712 		for (i = 0; i < env->cfg.cur_postorder; ++i) {
2713 			int insn_idx = env->cfg.insn_postorder[i];
2714 			struct insn_live_regs *live = &state[insn_idx];
2715 			struct bpf_iarray *succ;
2716 			u32 new_out = 0;
2717 			u32 new_in = 0;
2718 			u32 use;
2719 
2720 			succ = bpf_insn_successors(env, insn_idx);
2721 			for (int s = 0; s < succ->cnt; ++s)
2722 				new_out |= state[succ->items[s]].in;
2723 			use = live->use;
2724 			/*
2725 			 * For a call to a static subprogram include the callee's
2726 			 * entry 'in' as computed so far.
2727 			 */
2728 			if (bpf_pseudo_call(&insns[insn_idx]) &&
2729 			    !bpf_subprog_is_global(env, callee_subprog(env, &insns[insn_idx])))
2730 				use |= state[insn_idx + insns[insn_idx].imm + 1].in &
2731 				       mask_widen(GENMASK(BPF_REG_5, BPF_REG_1));
2732 			new_in = (new_out & ~live->def) | use;
2733 			if (new_out != live->out || new_in != live->in) {
2734 				live->in = new_in;
2735 				live->out = new_out;
2736 				changed = true;
2737 			}
2738 		}
2739 	}
2740 
2741 	for (i = 0; i < insn_cnt; ++i) {
2742 		int def32 = bpf_insn_def32(env->prog, &insns[i]);
2743 		u32 out = state[i].out;
2744 		u32 in = state[i].in;
2745 
2746 		insn_aux[i].live_regs_before = mask_lo(in) | mask_hi(in);
2747 		/*
2748 		 * On architectures where 32-bit operations do not reset upper halves
2749 		 * of the registers, the verifier needs to zero extend a destination
2750 		 * register if an instruction defines a 32-bit subregister and the
2751 		 * upper half of that register is alive after the instruction.
2752 		 */
2753 		insn_aux[i].zext_dst = def32 >= 0 && (mask_hi(out) & BIT(def32));
2754 	}
2755 
2756 out:
2757 	kvfree(state);
2758 	return err;
2759 }
2760