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