Skip to contentSkip to conversation

Redesign Verification Errors

PATCH Superseded Kumar Kartikeya Dwivedi 5 participants 40 messages Jul 13 – Jul 17

Subsystems (2)

v3 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

Kumar Kartikeya Dwivedi

author maintainer
#0 lore raw

v3 cover Redesign Verification Errors

TL;DR: This set reworks verifier error messages to include source and instruction annotations, together with more causal context, making failures easier to understand and more actionable when debugging and repairing BPF programs.

Changelog:
----------
v2 -> v3
v2: https://lore.kernel.org/bpf/[email protected]

* Address various comments from Eduard and Sashiko.
* Move instruction context from a separate gutter into a new section following source context, since surrounding source lines and BPF instructions do not map one-to-one.
* Fix active-path branch reconstruction when switching to queued states, and expand register histories to follow value lineage across spills, fills, stack reads, helper/kfunc clobbers, and dynptr invalidation.
* Misc improvements and refinements.

v1 -> v2
v1: https://lore.kernel.org/bpf/[email protected]

* Reworked diagnostic history from per-verifier-state log to active path log with positions saved and reset when verifier search backtracks. (Eduard)
* Moved reusable diagnostic formatting storage into struct bpf_diag under struct bpf_verifier_env, and removed large per-report scratch buffers from verifier stack frames. (Eduard)
* Added stack-slot events so diagnostics follow ordinary stack spill/fill value flow and invalidations in register-scoped histories. (Eduard)
* Reused existing source and BTF formatting helpers for diagnostics, including bpf_get_linfo_file_line() and btf_type_snprintf_show_name(). (Eduard)
* Fixed diagnostic edge cases around signed offset text, BPF_MAX_VAR_OFF reporting, negative-offset clamping, poisoned stack reads, and borrowed-reference invalidations. (Eduard)
* Fixed various miscellaneous diagnostic bugs. (Sashiko)
* Misc improvements and refinements.

--

Motivation
~~~~~~~~~~

The verifier log is the primary interface through which the verifier communicates to the user its verdict on whether a program was accepted or rejected.

To aid the debugging of rejection decisions, the verifier also reports the symbolic state of the program at each instruction, across every explored path of the BPF program. Such detailed information is critical to introspect the correctness of verification decisions, and provide insight into why a given program may have failed to load in the kernel.

A constant pain point in the BPF ecosystem throughout the years has been the difficulty of debugging verification errors. The human-readable error messages produced in response to a failure in satisfying safety-related constraints are often terse, context-dependent, or insufficient for understanding why a given error may have happened. Users must fall back to the verbose instruction-by-instruction breakdown of how the symbolic state evolved to surface the root cause. For programs with a huge log volume due to high verification complexity, such logs quickly become inscrutable.

All of this has made life difficult for users lacking an understanding of how the verifier works, and the various heuristics and idiosyncrasies used by it. In some cases, even seasoned BPF experts spend significant time reverse engineering why a program may have failed, and have to reach into the verifier's source code to form a complete picture of the verification process.

Such a steep learning curve and cognitive burden also hurts the speed of BPF development, as the verifier sits right in the middle of the user's iteration loop while they make use of BPF to solve any given problem. Expertise in debugging verifier errors does not scale in terms of teams deploying these programs in production across a diverse set of kernels.

Overall, this leads to a poorer developer experience, causes visible user dissatisfaction, and remains a drag on wider BPF adoption. With some of the more recent developments where users increasingly leverage AI tooling [0] to author their code, this bottleneck becomes even more critical to address, since it throttles the much faster iteration loop of AI agents.

[0]: https://lwn.net/Articles/1075067

Approach
~~~~~~~~

This series starts moving selected failures from terse terminal messages toward diagnostics that carry the relevant context for a verification failure. The existing verbose log remains the low-level trace. For selected failures, the new report is emitted after this trace and answers the immediate debugging questions:

- what verifier rule failed,
- why the current state does not satisfy it,
- where the failing instruction maps to source,
- which earlier branch or state event made this path fail,
- what kind of source change would satisfy the verifier.

The series adds a text-only diagnostics framework under kernel/bpf and uses it to augment selected verifier errors. Existing verbose(env, ...) messages are kept, so current selftest expectations and existing log consumers continue to see the legacy text. The new report has a uniform outer shape:

Verification failed: <category>: <problem>

Reason:
exact reason for the verification failure, with details

At:
source and instruction annotation

Causal path:
compressed branch and verifier-state events relevant for debugging

Suggestion:
speculation on potential fixes to repair the program

The outer shape is shared, but report construction is category-specific.

The categories are intentionally broad and reviewable. This revision covers representative cases in Register Type Safety, Memory Safety, Resource Lifetime Safety, Call Type Safety, Execution Context Safety, Program Structure, Policy, Verifier Limit, and Verifier Internal errors. It does not attempt to convert every verbose(env, ...) site for now. Additional verbose-only errors can be moved into the same framework incrementally.

The following excerpts are copied from this current run on this branch:

  ./test_progs -j1 \
    -a cpumask/test_populate_invalid_destination,\
    cpumask/test_alloc_no_release,\
    verifier_helper_value_access/via_variable_no_max_check_1,\
    verifier_sock/invalidate_pkt_pointers_from_global_func \
    -vv

They show the old terminal error and the exact new diagnostic report, including the source and instruction annotations.

Call Type Safety, cpumask/test_populate_invalid_destination:

Legacy:
R1 type=scalar expected=fp

Diagnostic:

    Verification failed: Call Type Safety: Invalid call argument

    Reason:
      The first argument (R1) to bpf_cpumask_populate does not satisfy the verifier contract: the kfunc
      expects 24 bytes of memory for (struct bpf_cpumask), but it is an integer scalar and not
      verifier-known memory.

    At:
      test_populate_invalid_destination @ cpumask_failure.c:234:8
      Source context:
          232 | ...
          233 | ...
      >>> 234 |         ret = bpf_cpumask_populate(invalid, &bits, sizeof(bits));
              |         ^-- error: invalid first argument (R1) for bpf_cpumask_populate
          235 |         if (!ret)
          236 |                 err = 2;
      Instruction context:
           2 | (b7) r1 = 1193046
           3 | (b7) r3 = 8
      >>>  4 | (85) call bpf_cpumask_populate#62860
           5 | (56) if w0 != 0x0 goto pc+4
           6 | (18) r1 = 0xffffc9000028e000

    Causal path:
      test_populate_invalid_destination @ cpumask_failure.c:234:8
      Source context:
          232 | ...
          233 | ...
      >>> 234 |         ret = bpf_cpumask_populate(invalid, &bits, sizeof(bits));
              |         ^-- update: R1 changed from context pointer at offset 0 to integer scalar value
              |             1193046
          235 |         if (!ret)
          236 |                 err = 2;
      Instruction context:
           0 | (bf) r2 = r10
           1 | (07) r2 += -8
      >>>  2 | (b7) r1 = 1193046
           3 | (b7) r3 = 8
           4 | (85) call bpf_cpumask_populate#62860

    Suggestion:
      Pass stack, map, context, or other verifier-known memory of the expected type and size, not an
      integer cast to a pointer.

Register Type Safety, verifier_sock/invalidate_pkt_pointers_from_global_func:

Legacy:
R7 invalid mem access 'scalar'

Diagnostic:

    Verification failed: Register Type Safety: Invalid dereference

    Reason:
      R7 is an integer scalar here, not a pointer to memory.

    At:
      invalidate_pkt_pointers_from_global_func @ verifier_sock.c:1067:5
      Source context:
          1065 | ...
          1066 |         skb_pull_data1(sk, 0);
      >>> 1067 |         *p = 42; /* this is unsafe */
               |         ^-- error: invalid dereference of R7 (an integer scalar)
          1068 | ...
          1069 | }
      Instruction context:
           8 | (85) call pc+4
           9 | (b4) w1 = 42
      >>> 10 | (63) *(u32 *)(r7 +0) = r1
          11 | (bc) w0 = w6
          12 | (95) exit

    Causal path:
      invalidate_pkt_pointers_from_global_func @ verifier_sock.c:1062:29
      Source context:
          1060 | int invalidate_pkt_pointers_from_global_func(struct __sk_buff *sk)
          1061 | ...
      >>> 1062 |         int *p = (void *)(long)sk->data;
               |         ^-- update: R7 changed from uninitialized value to pkt at offset 0
          1063 | ...
          1064 |         if ((void *)(p + 1) > (void *)(long)sk->data_end)
      Instruction context:
           0 | (b4) w6 = 2
           1 | (61) r2 = *(u32 *)(r1 +80)
      >>>  2 | (61) r7 = *(u32 *)(r1 +76)
           3 | (bf) r3 = r7
           4 | (07) r3 += 4

      invalidate_pkt_pointers_from_global_func @ verifier_sock.c:1064:22
      Source context:
          1062 |         int *p = (void *)(long)sk->data;
          1063 | ...
      >>> 1064 |         if ((void *)(p + 1) > (void *)(long)sk->data_end)
               |         ^-- branch: took the false branch of this conditional, goto not followed
          1065 | ...
          1066 |         skb_pull_data1(sk, 0);
      Instruction context:
           3 | (bf) r3 = r7
           4 | (07) r3 += 4
      >>>  5 | (2d) if r3 > r2 goto pc+5
           6 | (b4) w6 = 0
           7 | (b4) w2 = 0

      invalidate_pkt_pointers_from_global_func @ verifier_sock.c:1066:2
      Source context:
          1064 |         if ((void *)(p + 1) > (void *)(long)sk->data_end)
          1065 | ...
      >>> 1066 |         skb_pull_data1(sk, 0);
               |         ^-- invalidated: R7: packet data may have moved; previous value was pkt at
               |             offset 0
          1067 |         *p = 42; /* this is unsafe */
          1068 | ...
      Instruction context:
           6 | (b4) w6 = 0
           7 | (b4) w2 = 0
      >>>  8 | (85) call pc+4
           9 | (b4) w1 = 42
          10 | (63) *(u32 *)(r7 +0) = r1

    Suggestion:
      Preserve a pointer-valued register where needed, or reload and revalidate the pointer after scalar
      arithmetic, helper calls, or other operations that can invalidate it.

Memory Safety, verifier_helper_value_access/via_variable_no_max_check_1:

Legacy:
R1 unbounded memory access, make sure to bounds check any such access

Diagnostic:

    Verification failed: Memory Safety: Access outside bounds

    Reason:
      The verifier cannot prove offset + access_size <= object_size. Here, the maximal bound for a
      memory access is 4294967295 and exceeds maximum allowed offset of 536870912. R1 is map_value;
      offset is variable: known bits 0x0, unknown mask 0xffffffff; signed range [0, 4294967295],
      unsigned range [0, 4294967295]; access_size is 1; object_size is 48.

    At:
      via_variable_no_max_check_1 @ verifier_helper_value_access.c:627:2
      Source context:
          625 | ...
          626 | ...
      >>> 627 |         asm volatile ("                                 \
              |         ^-- error: access may be outside object bounds
          628 | ...
          629 | ...
      Instruction context:
          11 | (b7) r2 = 1
          12 | (b7) r3 = 0
      >>> 13 | (85) call bpf_probe_read_kernel#113
          14 | (95) exit

    Causal path:
      via_variable_no_max_check_1 @ verifier_helper_value_access.c:627:2
      Source context:
          625 | ...
          626 | ...
      >>> 627 |         asm volatile ("                                 \
              |         ^-- update: R0 changed from uninitialized value to nullable map value from
              |             map_hash_48b at offset 0
          628 | ...
          629 | ...
      Instruction context:
           4 | (18) r1 = 0xffff88810a3ea000
      >>>  6 | (85) call bpf_map_lookup_elem#1
           7 | (15) if r0 == 0x0 goto pc+6
           8 | (bf) r1 = r0

      via_variable_no_max_check_1 @ verifier_helper_value_access.c:627:2
      Source context:
          625 | ...
          626 | ...
      >>> 627 |         asm volatile ("                                 \
              |         ^-- branch: took the false branch of this conditional, goto not followed
          628 | ...
          629 | ...
      Instruction context:
           6 | (85) call bpf_map_lookup_elem#1
      >>>  7 | (15) if r0 == 0x0 goto pc+6
           8 | (bf) r1 = r0
           9 | (61) r3 = *(u32 *)(r0 +0)

      via_variable_no_max_check_1 @ verifier_helper_value_access.c:627:2
      Source context:
          625 | ...
          626 | ...
      >>> 627 |         asm volatile ("                                 \
              |         ^-- update: R1 changed from uninitialized value to map value from map_hash_48b
              |             at offset 0
          628 | ...
          629 | ...
      Instruction context:
           6 | (85) call bpf_map_lookup_elem#1
           7 | (15) if r0 == 0x0 goto pc+6
      >>>  8 | (bf) r1 = r0
           9 | (61) r3 = *(u32 *)(r0 +0)
          10 | (0f) r1 += r3

      via_variable_no_max_check_1 @ verifier_helper_value_access.c:627:2
      Source context:
          625 | ...
          626 | ...
      >>> 627 |         asm volatile ("                                 \
              |         ^-- update: R1 changed from map value from map_hash_48b at offset 0 to map value
              |             from map_hash_48b with variable offset: known bits 0x0, unknown mask
              |             0xffffffff, signed range [0, 4294967295], unsigned range [0, 4294967295]
          628 | ...
          629 | ...
      Instruction context:
           8 | (bf) r1 = r0
           9 | (61) r3 = *(u32 *)(r0 +0)
      >>> 10 | (0f) r1 += r3
          11 | (b7) r2 = 1
          12 | (b7) r3 = 0

    Suggestion:
      Add or adjust a bounds check that proves offset + access_size stays within the object.

Resource Lifetime Safety, cpumask/test_alloc_no_release:

Legacy:
Unreleased reference id=2 alloc_insn=0
BPF_EXIT instruction in main prog would lead to reference leak

Diagnostic:

    Verification failed: Resource Lifetime Safety: Unreleased resource

    Reason:
      Owned resource (id=2) was acquired at instruction 0 and still needs to be released before this
      exit path.

    At:
      test_alloc_no_release @ cpumask_failure.c:36:5
      Source context:
          34 | ...
          35 | ...
      >>> 36 | int BPF_PROG(test_alloc_no_release, struct task_struct *task, u64 clone_flags)
             | ^-- error: owned resource (id=2) still needs release
          37 | ...
          38 | ...
      Instruction context:
          19 | (7b) *(u64 *)(r10 -8) = r6
          20 | (b4) w0 = 0
      >>> 21 | (95) exit

    Causal path:
      test_alloc_no_release @ cpumask_common.h:78:12
      Source context:
          76 | ...
          77 | ...
      >>> 78 |         cpumask = bpf_cpumask_create();
             |         ^-- acquired: owned resource (id=2)
          79 |         if (!cpumask) {
          80 |                 err = 1;
      Instruction context:
      >>>  0 | (85) call bpf_cpumask_create#62851
           1 | (bf) r6 = r0
           2 | (55) if r6 != 0x0 goto pc+5

      test_alloc_no_release @ cpumask_common.h:79:6
      Source context:
          77 | ...
          78 |         cpumask = bpf_cpumask_create();
      >>> 79 |         if (!cpumask) {
             |         ^-- branch: took the true branch of this conditional, goto followed
          80 |                 err = 1;
          81 | ...
      Instruction context:
           0 | (85) call bpf_cpumask_create#62851
           1 | (bf) r6 = r0
      >>>  2 | (55) if r6 != 0x0 goto pc+5
           3 | (18) r1 = 0xffffc90000252000

      test_alloc_no_release @ cpumask_common.h:84:6
      Source context:
          82 | ...
          83 | ...
      >>> 84 |         if (!bpf_cpumask_empty(cast(cpumask))) {
             |         ^-- branch: took the true branch of this conditional, goto followed
          85 |                 err = 2;
          86 |                 bpf_cpumask_release(cpumask);
      Instruction context:
           9 | (85) call bpf_cpumask_empty#62852
          10 | (54) w0 &= 1
      >>> 11 | (56) if w0 != 0x0 goto pc+7
          12 | (18) r1 = 0xffffc90000252000

    Suggestion:
      Release or transfer ownership of the acquired resource on every path before the program exits.

Patch layout:

- Patches 1-2 add the common infrastructure: report sections, diagnostic categories, source-line lookup, and separate source and instruction context blocks.
- Patches 3-7 add growable environment-owned diagnostic history. The history follows the active verifier path and is pruned when backtracking; it records branch outcomes, material register changes, reference lifetime events, and execution-context events so reports can explain the path and causal state transitions that led to the failure.
- Patches 8-16 add the first category-specific reports. These patches hook selected verifier failure sites and choose the evidence that is useful for that error class.
- Patch 17 gates diagnostic collection and rendering on verifier log level, so stats-only loads do not collect the extra path history. The overhead is limited to verbose log mode through this change.

Evaluation
~~~~~~~~~~

To quantitatively assess diagnostic quality beyond subjective human feedback, we use AI models (called over APIs) and veristat metrics to compare results.

Models are used as a way to measure repair utility of the extra diagnostics over a fixed test set. Each prompt contains only a sanitized source snippet and either the legacy verifier log or the new diagnostic log. To avoid leaking the answer through the test itself, comments, annotations, and other source hints that describe the intended failure were removed. The model is not given internet access, repository access, test execution, verifier access, or the expected fix. The expected causes and intended repairs are kept outside the prompt. Under those constraints, correctness, exact repair rate, output size, reasoning tokens, cost, and wall time provide a proxy for whether the additional verifier context makes the failure easier to understand and turn into a source-level fix.

Verifier cost is assessed by forcing the collection of diagnostics information during normal verification. By default, this information is collected and processed only when verbose logs are enabled, but forcing it even without a verbose log helps us measure the CPU time and memory cost of the extra data.

Both evaluations are covered in the sections below.

Repair Quality
--------------

Repair quality is measured by asking API-only models to propose source fixes from a sanitized source snippet and verifier log. The criterion is score >= 3 on a 0-4 local grading scale, where 3 means a likely fix with incomplete detail and 4 means an actionable source-level fix. Score 4 is reported separately as the exact repair rate. The reported model set contains 596 completed API responses: 298 diagnostic and 298 legacy.

Main results (details available in Appendix):

  Metric                              Diagnostic   Legacy       Delta
  ----------------------------------  -----------  -----------  --------
  Answers                             298          298
  Success rate                        97.0%        97.3%        -0.3 pp
  Exact repair rate                   82.2%        72.1%        +10.1 pp
  Mean score                          3.79         3.69         +0.10
  Solver cost                         $8.93        $10.37       -13.8%
  Mean output tokens per answer       1662         1975         -15.8%
  Mean reasoning tokens per answer    951          1080         -11.9%
  Mean wall time per answer           37.3s        44.1s        -15.4%

Diagnostic prompts carry more input context. The resulting answers are still shorter and cheaper. In this run, diagnostics do not materially change the coarse success rate, but they increase exact repairs by 10.1 percentage points while reducing cost, output tokens, reasoning tokens, and wall time.

Verifier cost
-------------

Verifier cost is measured with veristat over the BPF selftest programs selected by tools/testing/selftests/bpf/veristat.cfg, with five repetitions per configuration. With diagnostics gated by log level, wall time and verifier duration stay close to baseline. Forcing diagnostics on for every verifier run adds modest overhead on this workload.

memory.peak is measured with cgroup v2 memory accounting for each program load. The table reports the mean wall time, the mean summed verifier duration, and the mean of the per-repetition maximum memory.peak values.

  Configuration                 Wall time mean   Verifier duration    memory.peak
  ----------------------------  --------------   -----------------    -----------
  bpf-next baseline                 25.78s            9.86s              142 MiB
  diagnostics, gated                26.64s           10.16s              144 MiB
  diagnostics, forced on            28.01s           11.00s              148 MiB

TODO
~~~~

Known follow-up work:

- Convert more verbose-only verifier errors into category-specific reports.
- Integrate loop-convergence failure summarization from Eduard.
- Report candidate kfuncs/helpers for releasing owned resources.
- Explore association of source variables with verifier registers where debug info permits it.
- Refine suggestions per category and, where useful, link diagnostics to maintained documentation.
- Bring verifier warnings into the same reporting framework.

Appendix: AI repair details
~~~~~~~~~~~~~~~~~~~~~~~~~~~

The 20 verifier-failing selftest cases are:

  Case     Diff    Category                    Selftest selector
  -------  ------  --------------------------  ---------------------------------------------
  case-001 easy    Call Type Safety            cpumask/test_populate_invalid_destination
  case-002 easy    Resource Lifetime Safety    cpumask/test_alloc_no_release
  case-003 easy    Register Type Safety        verifier_spill_fill/check_corrupted_spill_fill
  case-004 easy    Register Type Safety        test_global_funcs/global_func12
  case-005 easy    Execution Context Safety    preempt_lock/preempt_sleepable_helper
  case-006 easy    Policy                      verifier_helper_restricted/in_bpf_prog_type_kprobe_1
  case-007 medium  Memory Safety               dynptr/dynptr_slice_var_len1
  case-008 medium  Call Type Safety            dynptr/test_dynptr_skb_small_buff
  case-009 medium  Call Type Safety            task_kfunc/task_kfunc_acquire_untrusted
  case-010 medium  Register Type Safety        test_global_funcs/global_func6
  case-011 medium  Resource Lifetime Safety    dynptr/ringbuf_missing_release2
  case-012 medium  Execution Context Safety    irq/irq_sleepable_helper_global_subprog
  case-013 medium  Verifier Limit              test_global_funcs/global_func1
  case-014 hard    Memory Safety               verifier_helper_value_access/via_variable_no_max_check_1
  case-015 hard    Register Type Safety        verifier_sock/invalidate_pkt_pointers_from_global_func
  case-016 hard    Resource Lifetime Safety    verifier_ref_tracking/check_free_in_one_subbranch
  case-017 hard    Resource Lifetime Safety    irq/irq_restore_ooo
  case-018 hard    Resource Lifetime Safety    res_spin_lock_failure/res_spin_lock_ooo_unlock
  case-019 hard    Program Structure           verifier_loops1/bounded_recursion
  case-020 hard    Verifier Limit              verifier_liveness_exp/liveness_exponential_complexity

The grading scale is:

- 4: identifies the verifier cause and gives an actionable source-level fix.
- 3: gives a likely fix, but with incomplete explanation or detail.
- 2: identifies part of the issue, but not enough to fix confidently.
- 1: gives only a broad verifier-area answer, or a wrong/insufficient fix.
- 0: does not identify the intended verifier failure.

Detailed effort metrics for the model set:

  Metric                   Variant      Mean      Median       P99
  -----------------------  ----------  --------  --------  --------
  Cost per answer          diagnostic   $0.030    $0.019    $0.203
  Cost per answer          legacy       $0.035    $0.018    $0.223
  Input tokens             diagnostic     1391      1220      4048
  Input tokens             legacy         1052       805      3655
  Output tokens            diagnostic     1662       954      8680
  Output tokens            legacy         1975      1034      9912
  Reasoning tokens         diagnostic      951       208      8108
  Reasoning tokens         legacy         1080       228      6322
  Wall time                diagnostic    37.3s     18.3s    222.7s
  Wall time                legacy        44.1s     19.8s    255.5s

Per-model results for diagnostic prompts:

  Model profile                              Ans  Succ   Exact  Mean  Cost     OutK  ReasK  Wall
  -----------------------------------------  ---  -----  -----  ----  -------  ----  -----  -----
  anthropic-haiku-4.5-default                 20   90.0   80.0  3.70  $0.087   11.4    0.0   5.0s
  anthropic-opus-4.8-high                     20  100.0   90.0  3.90  $0.819   25.5    0.0  15.5s
  anthropic-opus-4.8-medium                   20   95.0   90.0  3.85  $0.870   27.5    0.0  12.7s
  anthropic-sonnet-4.6-high                   20   95.0   80.0  3.75  $0.824   48.9    0.0  21.6s
  anthropic-sonnet-4.6-medium                 20  100.0   65.0  3.65  $0.278   12.4    0.0   6.6s
  openai-gpt-5.3-codex-high                   20  100.0   80.0  3.80  $0.601   39.8   33.9  25.0s
  openai-gpt-5.3-codex-medium                 20   95.0   85.0  3.80  $0.287   17.5   11.4  13.5s
  openai-gpt-5.5-high                         20  100.0   90.0  3.90  $2.356   74.4   65.2  56.8s
  openai-gpt-5.5-low                          20  100.0   90.0  3.90  $0.686   18.7    8.5  21.3s
  openai-gpt-5.5-medium                       19  100.0   84.2  3.84  $1.353   41.1   31.8  37.4s
  openai-gpt-5.5-none                         20   95.0   90.0  3.85  $0.457   11.1    0.0  10.4s
  openrouter-deepseek-r1-0528                 20  100.0   75.0  3.75  $0.145   61.5   53.8  98.3s
  openrouter-deepseek-v3.2                    19  100.0   78.9  3.79  $0.028   64.2   58.1  87.3s
  openrouter-glm-5.1-high                     20   95.0   80.0  3.75  $0.113   28.8   20.7  19.3s
  openrouter-qwen3-coder                      20   90.0   75.0  3.65  $0.028   12.4    0.0   7.1s

Per-model results for legacy prompts:

  Model profile                              Ans  Succ   Exact  Mean  Cost     OutK  ReasK  Wall
  -----------------------------------------  ---  -----  -----  ----  -------  ----  -----  -----
  anthropic-haiku-4.5-default                 20   90.0   45.0  3.35  $0.081   11.6    0.0   5.0s
  anthropic-opus-4.8-high                     20   90.0   70.0  3.60  $1.192   42.2    0.0  17.5s
  anthropic-opus-4.8-medium                   20   95.0   85.0  3.80  $1.001   34.5    0.0  13.4s
  anthropic-sonnet-4.6-high                   20  100.0   75.0  3.75  $1.181   74.1    0.0  24.4s
  anthropic-sonnet-4.6-medium                 20   95.0   65.0  3.60  $0.420   23.4    0.0  12.3s
  openai-gpt-5.3-codex-high                   20  100.0   85.0  3.85  $0.562   37.8   31.6  27.1s
  openai-gpt-5.3-codex-medium                 20  100.0   75.0  3.75  $0.318   20.3   13.7  13.6s
  openai-gpt-5.5-high                         19  100.0   78.9  3.79  $2.613   84.0   75.4  98.1s
  openai-gpt-5.5-low                          20  100.0   75.0  3.75  $0.664   19.0    9.7  21.7s
  openai-gpt-5.5-medium                       20  100.0   75.0  3.75  $1.602   50.2   41.0  56.1s
  openai-gpt-5.5-none                         20   95.0   85.0  3.80  $0.416   10.7    0.0  10.9s
  openrouter-deepseek-r1-0528                 20   95.0   70.0  3.65  $0.149   64.6   57.5  92.5s
  openrouter-deepseek-v3.2                    20  100.0   60.0  3.60  $0.030   74.3   67.8  98.3s
  openrouter-glm-5.1-high                     19  100.0   63.2  3.63  $0.115   32.1   24.9  30.4s
  openrouter-qwen3-coder                      20  100.0   75.0  3.75  $0.022    9.5    0.0   5.4s

Kumar Kartikeya Dwivedi (17):
bpf: Add verifier diagnostics report helpers
bpf: Add source and instruction diagnostic context
bpf: Add verifier diagnostic event log
bpf: Prune verifier diagnostics when switching paths
bpf: Track verifier register diagnostic events
bpf: Track verifier reference diagnostic events
bpf: Track verifier context diagnostic events
bpf: Report Register Type Safety errors
bpf: Report Memory Safety bounds errors
bpf: Report Resource Lifetime reference leaks
bpf: Report Call Type Safety argument errors
bpf: Report Execution Context Safety errors
bpf: Report Program Structure CFG errors
bpf: Report Policy helper and kfunc errors
bpf: Report Verifier Limit errors
bpf: Report Verifier Internal errors
bpf: Gate verifier diagnostics on log level

 include/linux/bpf.h          |   15 +-
 include/linux/bpf_verifier.h |   26 +-
 include/linux/btf.h          |    1 +
 kernel/bpf/Makefile          |    2 +-
 kernel/bpf/btf.c             |   10 +
 kernel/bpf/cfg.c             |   55 +
 kernel/bpf/core.c            |   36 +-
 kernel/bpf/diagnostics.c     | 2492 ++++++++++++++++++++++++++++++++++
 kernel/bpf/diagnostics.h     |  188 +++
 kernel/bpf/liveness.c        |    7 +
 kernel/bpf/log.c             |   11 -
 kernel/bpf/verifier.c        | 1555 +++++++++++++++++++--
 12 files changed, 4229 insertions(+), 169 deletions(-)
 create mode 100644 kernel/bpf/diagnostics.c
 create mode 100644 kernel/bpf/diagnostics.h

base-commit: 9a3a07d06e7d74f4aecc51396c771149336ac55d

Signature · 1 line
2.53.0
author maintainer
#1 lore raw

PATCH v3 1/17 bpf: Add verifier diagnostics report helpers

Add a small diagnostics renderer for verifier reports and wire it into the BPF build. The initial helpers emit the common text structure: a failure header plus reusable report sections.

Wrap report prose at 100 columns so Reason and Suggestion text stays readable without changing source or instruction gutters.

Gate the helpers on normal verifier log output from the start, so BPF_LOG_STATS-only loads do not collect or render diagnostics.

---
 kernel/bpf/Makefile      |   2 +-
 kernel/bpf/diagnostics.c | 157 +++++++++++++++++++++++++++++++++++++++
 kernel/bpf/diagnostics.h |  16 ++++
 3 files changed, 174 insertions(+), 1 deletion(-)
 create mode 100644 kernel/bpf/diagnostics.c
 create mode 100644 kernel/bpf/diagnostics.h
kernel/bpf/Makefile +1 -1
index 4dc41bf5780c..90255d80e5be 100644
@@ -6,7 +6,7 @@ cflags-nogcse-$(CONFIG_X86)$(CONFIG_CC_IS_GCC) := -fno-gcse
 endif
 CFLAGS_core.o += -Wno-override-init $(cflags-nogcse-yy)
 
-obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o cnum.o log.o token.o liveness.o const_fold.o
+obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o cnum.o log.o token.o liveness.o const_fold.o diagnostics.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_iter.o
 obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o
 obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o
kernel/bpf/diagnostics.c new file +157 -0

157 lines not on this page · raw message

kernel/bpf/diagnostics.h new file +16 -0
new file mode 100644
index 000000000000..be7ad5142726
@@ -0,0 +1,16 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#ifndef __BPF_DIAGNOSTICS_H
+#define __BPF_DIAGNOSTICS_H
+
+#include <linux/compiler_attributes.h>
+#include <linux/types.h>
+
+struct bpf_verifier_env;
+
+bool bpf_diag_enabled(const struct bpf_verifier_env *env);
+void bpf_diag_report_header(struct bpf_verifier_env *env, const char *category,
+			    const char *problem);
+
+#endif /* __BPF_DIAGNOSTICS_H */
Signature · 1 line
2.53.0
#2 lore raw

Re: [PATCH bpf-next v3 01/17] bpf: Add verifier diagnostics report helpers

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] The static functions `diag_report_reason` and `diag_report_suggestion` (and their dependent static…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] The static functions diag_report_reason and diag_report_suggestion (and their dependent static functions like diag_report_section, diag_vprint_indented, etc.) are defined but never used in kernel/bpf/diagnostics.c. Additionally, several CATEGORY_* macros are defined locally in the .c file instead of the header, making them inaccessible to external callers. --

--- Patch [1]: [PATCH bpf-next v3 01/17] bpf: Add verifier diagnostics report helpers --- commit 1babdf2fc54b5272d1520095320e5a3cddaa9347
Author: Kumar Kartikeya Dwivedi <[email protected]>

bpf: Add verifier diagnostics report helpers

Add a small diagnostics renderer for verifier reports and wire it into the BPF build. The initial helpers emit the common text structure: a failure header plus reusable report sections.

Quoted 16 lines
kernel/bpf/diagnostics.c new file +10 -0
new file mode 100644
index 0000000000000..6d28a3481cfa5
@@ -0,0 +1,157 @@
+// SPDX-License-Identifier: GPL-2.0-only
+// Copyright (c) 2026 Meta Platforms, Inc. and affiliates.
+
+#include <linux/bpf_verifier.h>
+#include <linux/ctype.h>
+#include <linux/slab.h>
+#include <linux/stdarg.h>
+#include <linux/string.h>
+
+#include "diagnostics.h"

kernel/bpf/diagnostics.c line 20

Quoted 10 lines
kernel/bpf/diagnostics.c new file +10 -0
+
+#define CATEGORY_MEMORY_SAFETY "Memory Safety"
+#define CATEGORY_REGISTER_TYPE_SAFETY "Register Type Safety"
+#define CATEGORY_CALL_TYPE_SAFETY "Call Type Safety"
+#define CATEGORY_RESOURCE_LIFETIME_SAFETY "Resource Lifetime Safety"
+#define CATEGORY_EXECUTION_CONTEXT_SAFETY "Execution Context Safety"
+#define CATEGORY_PROGRAM_STRUCTURE "Program Structure"
+#define CATEGORY_POLICY "Policy"
+#define CATEGORY_VERIFIER_LIMIT "Verifier Limit"
+#define CATEGORY_VERIFIER_INTERNAL_ERROR "Verifier Internal Error"

[Severity: Low]
Should these CATEGORY_* macros be exported in the diagnostics.h header? Since they define the expected categories for bpf_diag_report_header(), keeping them local to this .c file prevents other subsystems from accessing them when calling the API.

[ ... ]

Quoted 18 lines
kernel/bpf/diagnostics.c new file +18 -0
+static void diag_report_reason(struct bpf_verifier_env *env, const char *fmt, ...)
+{
+	va_list args;
+
+	if (!bpf_diag_enabled(env))
+		return;
+
+	diag_report_section(env, "Reason");
+
+	va_start(args, fmt);
+	diag_vprint_indented(env, fmt, args);
+	va_end(args);
+}
+
+static void diag_report_suggestion(struct bpf_verifier_env *env, const char *fmt, ...)
+{
+	va_list args;
+

kernel/bpf/diagnostics.c line 157

Quoted 10 lines
kernel/bpf/diagnostics.c new file +10 -0
+	if (!bpf_diag_enabled(env))
+		return;
+
+	diag_report_section(env, "Suggestion");
+
+	va_start(args, fmt);
+	diag_vprint_indented(env, fmt, args);
+	va_end(args);
+	diag_log(env, "\n");
+}

[Severity: Low]
Will these static functions trigger -Wunused-function compiler warnings? Since diag_report_reason() and diag_report_suggestion() are defined but never called or exported in this patch, they could break the build when CONFIG_WERROR=y is enabled.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#3 lore raw

PATCH v3 2/17 bpf: Add source and instruction diagnostic context

In reply to Kumar Kartikeya Dwivedi

Teach verifier diagnostics to annotate an instruction with BTF source line information and nearby BPF instructions. The renderer keeps source text in a fixed-width lane and prints instructions in a stable right-hand gutter.

Wrap annotation text under the source line so long error labels remain readable while the source and instruction lanes keep their fixed layout.

Keeping source and instruction context in one commit preserves the visual layout contract that later diagnostic reports rely on.

---
 include/linux/bpf.h          |  15 +-
 include/linux/bpf_verifier.h |   4 +
 include/linux/btf.h          |   1 +
 kernel/bpf/btf.c             |  10 +
 kernel/bpf/core.c            |  36 +--
 kernel/bpf/diagnostics.c     | 464 +++++++++++++++++++++++++++++++++++
 kernel/bpf/diagnostics.h     |   9 +
 kernel/bpf/verifier.c        |  32 ++-
 8 files changed, 541 insertions(+), 30 deletions(-)
include/linux/bpf.h +13 -2
index 31181e0c2b80..9bf3eda75ed3 100644
@@ -4142,8 +4142,19 @@ static inline bool bpf_is_subprog(const struct bpf_prog *prog)
 }
 
 const struct bpf_line_info *bpf_find_linfo(const struct bpf_prog *prog, u32 insn_off);
-void bpf_get_linfo_file_line(struct btf *btf, const struct bpf_line_info *linfo,
-			     const char **filep, const char **linep, int *nump);
+#define BPF_LINFO_LINE_TRIM 1
+struct bpf_linfo_source {
+	const char *file;
+	const char *line;
+	u32 file_name_off;
+	int line_num;
+	int line_col;
+};
+
+void bpf_get_linfo_source(struct btf *btf, const struct bpf_line_info *linfo,
+			  struct bpf_linfo_source *src, u32 flags);
+void bpf_get_linfo_file_line(struct btf *btf, const struct bpf_line_info *linfo, const char **filep,
+			     const char **linep, int *nump, u32 flags);
 int bpf_prog_get_file_line(struct bpf_prog *prog, unsigned long ip, const char **filep,
 			   const char **linep, int *nump);
 struct bpf_prog *bpf_prog_find_from_stack(void);
include/linux/bpf_verifier.h +4 -0
index 317e99b9acc0..3ff27863e34d 100644
@@ -835,6 +835,7 @@ static inline u16 bpf_in_stack_arg_cnt(const struct bpf_subprog_info *sub)
 	return 0;
 }
 
+struct bpf_diag;
 struct bpf_verifier_env;
 
 struct backtrack_state {
@@ -951,6 +952,7 @@ struct bpf_verifier_env {
 	struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */
 	const struct bpf_line_info *prev_linfo;
 	struct bpf_verifier_log log;
+	struct bpf_diag *diag;
 	struct bpf_subprog_info subprog_info[BPF_MAX_SUBPROGS + 2]; /* max + 2 for the fake and exception subprogs */
 	/* subprog indices sorted in topological order: leaves first, callers last */
 	int subprog_topo_order[BPF_MAX_SUBPROGS + 2];
@@ -1425,8 +1427,10 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifie
 void print_insn_state(struct bpf_verifier_env *env, const struct bpf_verifier_state *vstate,
 		      u32 frameno);
 u32 bpf_vlog_alignment(u32 pos);
+const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn);
 
 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off);
+const char *bpf_verifier_subprog_name(const struct bpf_verifier_env *env, int subprog);
 int bpf_jmp_offset(struct bpf_insn *insn);
 struct bpf_iarray *bpf_insn_successors(struct bpf_verifier_env *env, u32 idx);
 void bpf_fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask);
include/linux/btf.h +1 -0
index 240401d9b25b..90e865d116b8 100644
@@ -213,6 +213,7 @@ int btf_type_seq_show_flags(const struct btf *btf, u32 type_id, void *obj,
  */
 int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
 			   char *buf, int len, u64 flags);
+int btf_type_snprintf_show_name(const struct btf *btf, u32 type_id, char *buf, int len);
 
 int btf_get_fd_by_id(u32 id);
 u32 btf_obj_id(const struct btf *btf);
kernel/bpf/btf.c +10 -0
index 8c04c340f499..abe8f6a9f361 100644
@@ -8297,6 +8297,16 @@ int btf_type_snprintf_show(const struct btf *btf, u32 type_id, void *obj,
 	return ssnprintf.len;
 }
 
+int btf_type_snprintf_show_name(const struct btf *btf, u32 type_id, char *buf, int len)
+{
+	struct btf_show show = {
+		.btf = btf,
+		.state.type_id = type_id,
+	};
+
+	return snprintf(buf, len, "%s", btf_show_name(&show));
+}
+
 #ifdef CONFIG_PROC_FS
 static void bpf_btf_show_fdinfo(struct seq_file *m, struct file *filp)
 {
kernel/bpf/core.c +21 -15
index 47fe047ad30b..b35721ab3712 100644
@@ -3460,24 +3460,30 @@ EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_bulk_tx);
 
 #ifdef CONFIG_BPF_SYSCALL
 
-void bpf_get_linfo_file_line(struct btf *btf, const struct bpf_line_info *linfo,
-			     const char **filep, const char **linep, int *nump)
+void bpf_get_linfo_source(struct btf *btf, const struct bpf_line_info *linfo,
+			  struct bpf_linfo_source *src, u32 flags)
 {
-	/* Get base component of the file path. */
-	if (filep) {
-		*filep = btf_name_by_offset(btf, linfo->file_name_off);
-		*filep = kbasename(*filep);
-	}
+	src->file = kbasename(btf_name_by_offset(btf, linfo->file_name_off));
+	src->line = btf_name_by_offset(btf, linfo->line_off);
+	while ((flags & BPF_LINFO_LINE_TRIM) && isspace(*src->line))
+		src->line++;
+	src->file_name_off = linfo->file_name_off;
+	src->line_num = BPF_LINE_INFO_LINE_NUM(linfo->line_col);
+	src->line_col = BPF_LINE_INFO_LINE_COL(linfo->line_col);
+}
 
-	/* Obtain the source line, and strip whitespace in prefix. */
-	if (linep) {
-		*linep = btf_name_by_offset(btf, linfo->line_off);
-		while (isspace(**linep))
-			*linep += 1;
-	}
+void bpf_get_linfo_file_line(struct btf *btf, const struct bpf_line_info *linfo, const char **filep,
+			     const char **linep, int *nump, u32 flags)
+{
+	struct bpf_linfo_source src;
 
+	bpf_get_linfo_source(btf, linfo, &src, flags);
+	if (filep)
+		*filep = src.file;
+	if (linep)
+		*linep = src.line;
 	if (nump)
-		*nump = BPF_LINE_INFO_LINE_NUM(linfo->line_col);
+		*nump = src.line_num;
 }
 
 const struct bpf_line_info *bpf_find_linfo(const struct bpf_prog *prog, u32 insn_off)
@@ -3551,7 +3557,7 @@ int bpf_prog_get_file_line(struct bpf_prog *prog, unsigned long ip, const char *
 	if (idx == -1)
 		return -ENOENT;
 
-	bpf_get_linfo_file_line(btf, &linfo[idx], filep, linep, nump);
+	bpf_get_linfo_file_line(btf, &linfo[idx], filep, linep, nump, BPF_LINFO_LINE_TRIM);
 	return 0;
 }
 
kernel/bpf/diagnostics.c +464 -0

497 lines not on this page · raw message

kernel/bpf/diagnostics.h +9 -0
index be7ad5142726..d852386bf5f2 100644
@@ -10,7 +10,16 @@
 struct bpf_verifier_env;
 
 bool bpf_diag_enabled(const struct bpf_verifier_env *env);
+int bpf_diag_init(struct bpf_verifier_env *env);
+char *bpf_diag_scratch_buf(struct bpf_verifier_env *env, unsigned int slot, size_t *size);
+const char *bpf_diag_scratch_strcpy(struct bpf_verifier_env *env, unsigned int slot,
+				    const char *str);
+const char *bpf_diag_scratch_printf(struct bpf_verifier_env *env, unsigned int slot,
+				    const char *fmt, ...) __printf(3, 4);
+void bpf_diag_free(struct bpf_verifier_env *env);
 void bpf_diag_report_header(struct bpf_verifier_env *env, const char *category,
 			    const char *problem);
+void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const char *label,
+			    const char *fmt, ...) __printf(4, 5);
 
 #endif /* __BPF_DIAGNOSTICS_H */
kernel/bpf/verifier.c +19 -13
index 03e2202cca13..4f127c8db134 100644
@@ -34,6 +34,7 @@
 #include <linux/trace_events.h>
 #include <linux/kallsyms.h>
 
+#include "diagnostics.h"
 #include "disasm.h"
 
 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = {
@@ -425,7 +426,7 @@ static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog)
 	return btf_type_is_void(type);
 }
 
-static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
+const char *bpf_verifier_subprog_name(const struct bpf_verifier_env *env, int subprog)
 {
 	struct bpf_func_info *info;
 
@@ -3014,8 +3015,8 @@ static int sort_subprogs_topo(struct bpf_verifier_env *env)
 					if (bpf_pseudo_func(&insn[idx]))
 						continue;
 					verbose(env, "recursive call from %s() to %s()\n",
-						subprog_name(env, cur),
-						subprog_name(env, callee));
+						bpf_verifier_subprog_name(env, cur),
+						bpf_verifier_subprog_name(env, callee));
 					ret = -EINVAL;
 					goto out;
 				}
@@ -3035,8 +3036,8 @@ static int sort_subprogs_topo(struct bpf_verifier_env *env)
 
 	if (env->log.level & BPF_LOG_LEVEL2)
 		for (i = 0; i < cnt; i++)
-			verbose(env, "topo_order[%d] = %s\n",
-				i, subprog_name(env, env->subprog_topo_order[i]));
+			verbose(env, "topo_order[%d] = %s\n", i,
+				bpf_verifier_subprog_name(env, env->subprog_topo_order[i]));
 out:
 	kvfree(dfs_stack);
 	kvfree(color);
@@ -3290,7 +3291,7 @@ static void linked_regs_unpack(u64 val, struct linked_regs *s)
 	}
 }
 
-static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
+const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn)
 {
 	const struct btf_type *func;
 	struct btf *desc_btf;
@@ -3309,9 +3310,9 @@ static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn)
 void bpf_verbose_insn(struct bpf_verifier_env *env, struct bpf_insn *insn)
 {
 	const struct bpf_insn_cbs cbs = {
-		.cb_call	= disasm_kfunc_name,
-		.cb_print	= verbose,
-		.private_data	= env,
+		.cb_call = bpf_disasm_kfunc_name,
+		.cb_print = verbose,
+		.private_data = env,
 	};
 
 	print_bpf_insn(&cbs, insn, env->allow_ptr_leaks);
@@ -9439,7 +9440,7 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	if (err == -EFAULT)
 		return err;
 	if (bpf_subprog_is_global(env, subprog)) {
-		const char *sub_name = subprog_name(env, subprog);
+		const char *sub_name = bpf_verifier_subprog_name(env, subprog);
 
 		if (env->cur_state->active_locks) {
 			verbose(env, "global function calls are not allowed while holding a lock,\n"
@@ -18515,7 +18516,7 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog)
 
 	regs = state->frame[state->curframe]->regs;
 	if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) {
-		const char *sub_name = subprog_name(env, subprog);
+		const char *sub_name = bpf_verifier_subprog_name(env, subprog);
 		struct bpf_subprog_arg_info *arg;
 		struct bpf_reg_state *reg;
 
@@ -18685,8 +18686,9 @@ static int do_check_subprogs(struct bpf_verifier_env *env)
 		if (ret) {
 			return ret;
 		} else if (env->log.level & BPF_LOG_LEVEL) {
-			verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n",
-				i, subprog_name(env, i));
+			verbose(env,
+				"Func#%d ('%s') is safe for any args that match its prototype\n", i,
+				bpf_verifier_subprog_name(env, i));
 		}
 
 		/* We verified new global subprog, it might have called some
@@ -20081,6 +20083,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	ret = bpf_vlog_init(&env->log, attr_log->level, attr_log->ubuf, attr_log->size);
 	if (ret)
 		goto err_free_env;
+	ret = bpf_diag_init(env);
+	if (ret)
+		goto err_prep;
 	if (env->signature) {
 		ret = bpf_prog_calc_tag(env->prog);
 		if (ret < 0)
@@ -20362,6 +20367,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	kvfree(env->scc_info);
 	kvfree(env->succ);
 	kvfree(env->gotox_tmp_buf);
+	bpf_diag_free(env);
 	kvfree(env);
 	return ret;
 }
Signature · 1 line
2.53.0
maintainer
#4 lore raw

Re: [PATCH bpf-next v3 02/17] bpf: Add source and instruction diagnostic context

On Mon, 2026-07-13 at 17:38 +0200, Kumar Kartikeya Dwivedi wrote:

More nits, since you asked for nits :)

...

Quoted 5 lines
kernel/bpf/core.c +0 -0
index 47fe047ad30b..b35721ab3712 100644
@@ -3460,24 +3460,30 @@ EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_bulk_tx);

...

kernel/bpf/core.c EXPORT_TRACEPOINT_SYMBOL_GPL(xdp_bulk_tx); · line 3476

Quoted 2 lines
kernel/bpf/core.c +2 -0
+void bpf_get_linfo_file_line(struct btf *btf, const struct bpf_line_info *linfo, const char **filep,
+			     const char **linep, int *nump, u32 flags)

Nit: it would be better to just move the callers to use
struct bpf_linfo_source.

...

Quoted 25 lines
kernel/bpf/diagnostics.c +4 -0
index 6d28a3481cfa..49106115621d 100644
@@ -1,12 +1,16 @@
 // SPDX-License-Identifier: GPL-2.0-only
 // Copyright (c) 2026 Meta Platforms, Inc. and affiliates.
 
+#include <linux/bpf.h>
 #include <linux/bpf_verifier.h>
+#include <linux/btf.h>
 #include <linux/ctype.h>
+#include <linux/kernel.h>
 #include <linux/slab.h>
 #include <linux/stdarg.h>
 #include <linux/string.h>
 
+#include "disasm.h"
 #include "diagnostics.h"
 
 #define CATEGORY_MEMORY_SAFETY "Memory Safety"
@@ -21,12 +25,136 @@
 
 #define BPF_DIAG_TEXT_WIDTH 100
 #define BPF_DIAG_TEXT_INDENT "  "

kernel/bpf/diagnostics.c line 37

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+#define BPF_DIAG_MSG_LEN 512
+#define BPF_DIAG_CONTEXT 2
+#define BPF_DIAG_CONTEXT_CNT (1 + BPF_DIAG_CONTEXT * 2)
+#define BPF_DIAG_SOURCE_LANE_WIDTH 88
+#define BPF_DIAG_TAB_WIDTH 8
+#define BPF_DIAG_REG_DESC_LEN 512
+#define BPF_DIAG_REG_TMP_LEN 192
+#define BPF_DIAG_SCRATCH_STR_CNT 3
+#define BPF_DIAG_SCRATCH_STR_LEN 256
+#define BPF_DIAG_TEXT_LEN 160
           ^^^^^^^^^

Let's drop the BPF_DIAG_ here.
In general, there a lot of places in this file with bpf_diag_ prefix that can be dropped to improve readability. E.g. struct definitions below, some of the utility functions, etc.

kernel/bpf/diagnostics.c line 44

Quoted 7 lines
kernel/bpf/diagnostics.c +7 -0
+
+struct bpf_diag_source_line {
+	const char *line;
+	int line_num;
+};
+
+struct bpf_diag_insn {

Nit: bpf_diag_insn -> disasm_line

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+	char text[BPF_DIAG_TEXT_LEN];
+	int idx;
+	bool valid;
+};
+
+struct bpf_diag_insn_buf {
+	char *buf;
+	size_t size;
+	size_t len;
+};

kernel/bpf/diagnostics.c line 64

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+
+struct bpf_diag_insn_ctx {
+	struct bpf_verifier_env *env;
+	struct bpf_diag_insn_buf buf;
+};
+
+struct bpf_diag_scratch {
+	char str[BPF_DIAG_SCRATCH_STR_CNT][BPF_DIAG_SCRATCH_STR_LEN];
+	struct bpf_linfo_source source;
+	struct bpf_diag_source_line source_lines[BPF_DIAG_CONTEXT_CNT];

Nit: drop the 'struct bpf_diag_source_line' and use 'bpf_linfo_source',
just to keep things simpler?

Quoted 24 lines
kernel/bpf/diagnostics.c +18 -0
+	struct bpf_diag_insn insns[BPF_DIAG_CONTEXT_CNT];
+};
+
+struct bpf_diag {
+	struct bpf_diag_scratch scratch;
+};
 
 bool bpf_diag_enabled(const struct bpf_verifier_env *env)
 {
 	return env->log.level & BPF_LOG_LEVEL;
 }
 
+static struct bpf_diag *diag_env(struct bpf_verifier_env *env)
+{
+	return env->diag;
+}
+
+int bpf_diag_init(struct bpf_verifier_env *env)
+{
+	if (!bpf_diag_enabled(env))
+		return 0;
+
+	env->diag = kzalloc_obj(struct bpf_diag, GFP_KERNEL_ACCOUNT);
+	return env->diag ? 0 : -ENOMEM;

kernel/bpf/diagnostics.c line 98

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+}
+
+static struct bpf_diag_scratch *diag_scratch(struct bpf_verifier_env *env)
+{
+	struct bpf_diag *diag = diag_env(env);
+
+	return diag ? &diag->scratch : NULL;
+}
+
+char *bpf_diag_scratch_buf(struct bpf_verifier_env *env, unsigned int slot, size_t *size)
                                                            ^^^^^^^^^^^^^^^^^

Still think that manual slot number management here is inconvenient. Can do some kind of &scratch->str[scartch->next_slot++] and avoid the 'slot' parameter.

The 'size' parameter is used inconsistently, at some callsites a local variable is passed, at some callsites BPF_DIAG_SCRATCH_STR_LEN is used directly.

Quoted 12 lines
kernel/bpf/diagnostics.c +12 -0
+{
+	struct bpf_diag_scratch *scratch = diag_scratch(env);
+	char *buf = NULL;
+	size_t buf_size = 0;
+
+	if (!scratch)
+		goto out;
+
+	if ((unsigned int)slot >= BPF_DIAG_SCRATCH_STR_CNT)
+		goto out;
+
+	buf = scratch->str[slot];

kernel/bpf/diagnostics.c line 120

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+	buf_size = sizeof(scratch->str[slot]);
+
+out:
+	if (size)
+		*size = buf_size;
+	return buf;
+}
+
+const char *bpf_diag_scratch_strcpy(struct bpf_verifier_env *env, unsigned int slot,
+				    const char *str)

There are no users.

Quoted 12 lines
kernel/bpf/diagnostics.c +12 -0
+{
+	size_t size;
+	char *buf = bpf_diag_scratch_buf(env, slot, &size);
+
+	if (!buf)
+		return "";
+	strscpy(buf, str ?: "", size);
+	return buf;
+}
+
+const char *bpf_diag_scratch_printf(struct bpf_verifier_env *env, unsigned int slot,
+				    const char *fmt, ...)

...

Quoted 1 line

+static const char *diag_func_name(struct bpf_verifier_env *env, u32 insn_idx)

Nit: I'd inline this function, would be less code in the end.

kernel/bpf/diagnostics.c static void diag_vprint_indented(struct bpf_verifier_env *env, const char *fmt, · line 244

Quoted 5 lines
kernel/bpf/diagnostics.c +5 -0
+{
+	const struct bpf_subprog_info *subprog;
+	int subprogno;
+
+	subprog = bpf_find_containing_subprog(env, insn_idx);

^^^^^^^^^^^^^^^^^^^^^^^^^^^
there is bpf_find_subprog() that returns index directly

kernel/bpf/diagnostics.c static void diag_vprint_indented(struct bpf_verifier_env *env, const char *fmt, · line 254

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+	if (!subprog)
+		return NULL;
+
+	subprogno = subprog - env->subprog_info;
+	return bpf_verifier_subprog_name(env, subprogno);
+}
+
+static bool diag_fill_source(struct bpf_verifier_env *env, const struct bpf_line_info *linfo,
+			     struct bpf_linfo_source *src)
+{

Nit: I'd inline this function.

Quoted 18 lines
kernel/bpf/diagnostics.c +18 -0
+	if (!env->prog->aux->btf)
+		return false;
+
+	bpf_get_linfo_source(env->prog->aux->btf, linfo, src, 0);
+	return src->file && *src->file && src->line && *src->line;
+}
+
+static bool diag_get_source(struct bpf_verifier_env *env, u32 insn_idx,
+			    struct bpf_linfo_source *src)
+{
+	const struct bpf_line_info *linfo;
+
+	linfo = bpf_find_linfo(env->prog, insn_idx);
+	if (!linfo)
+		return false;
+
+	return diag_fill_source(env, linfo, src);
+}

...

kernel/bpf/diagnostics.c static void diag_vprint_indented(struct bpf_verifier_env *env, const char *fmt, · line 438

Quoted 2 lines
kernel/bpf/diagnostics.c +2 -0
+static void diag_print_source_line(struct bpf_verifier_env *env, const char *source_prefix,
+				   int source_line_width, const struct bpf_diag_source_line *line)

Nit: and here, there is a single small caller now

Quoted 20 lines
kernel/bpf/diagnostics.c +20 -0
+{
+	size_t source_lane_size;
+	char *source_lane;
+
+	source_lane = bpf_diag_scratch_buf(env, 0, &source_lane_size);
+	diag_format_source_lane(source_lane, source_lane_size, source_prefix, source_line_width,
+				line->line_num, line->line);
+	diag_write(env, "  %s\n", source_lane);
+}
+
+static void diag_print_insn_line(struct bpf_verifier_env *env,
+				 const struct bpf_diag_insn *diag_insn, int focus_insn_idx,
+				 int insn_width)
+{
+	if (!diag_insn->valid)
+		return;
+	diag_write(env, "  %s%*d | %s\n", diag_insn->idx == focus_insn_idx ? ">>> " : "    ",
+		   insn_width, diag_insn->idx, diag_insn->text);
+}
+

...

Quoted 3 lines
kernel/bpf/diagnostics.c +3 -0
+void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const char *label,
+			    const char *fmt, ...)
+{

...

kernel/bpf/diagnostics.c static void diag_report_suggestion(struct bpf_verifier_env *env, const char *fmt · line 605

Quoted 5 lines
kernel/bpf/diagnostics.c +5 -0
+	/*
+	 * Source lines and BPF instructions are independent context windows.
+	 * Only their focused entries describe the same location, so render
+	 * separate blocks instead of pairing neighboring rows.
+	 */

This is a remnant from the prompt.

Quoted 16 lines
kernel/bpf/diagnostics.c +16 -0
+	diag_write(env, "  Source context:\n");
+	for (i = 0; i < BPF_DIAG_CONTEXT_CNT; i++) {
+		const char *source_prefix;
+
+		source_prefix = source_lines[i].line_num == src->line_num ? ">>> " : "    ";
+		diag_print_source_line(env, source_prefix, width, &source_lines[i]);
+		if (source_lines[i].line_num == src->line_num)
+			diag_print_source_annotation(env, width, indent, label, msg);
+	}
+	diag_write(env, "  Instruction context:\n");
+	for (i = 0; i < BPF_DIAG_CONTEXT_CNT; i++)
+		diag_print_insn_line(env, &diag_insn[i], insn_idx, insn_width);
+
+out_free_msg:
+	kfree(msg);
+}

...

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index 03e2202cca13..4f127c8db134 100644

...

kernel/bpf/verifier.c static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog) · line 429

Quoted 6 lines
kernel/bpf/verifier.c +1 -1
@@ -425,7 +426,7 @@ static bool subprog_returns_void(struct bpf_verifier_env *env, int subprog)
 	return btf_type_is_void(type);
 }
 
-static const char *subprog_name(const struct bpf_verifier_env *env, int subprog)
+const char *bpf_verifier_subprog_name(const struct bpf_verifier_env *env, int subprog)

bpf_verifier_subprog_name -> bpf_subprog_name

Quoted 3 lines
kernel/bpf/verifier.c +0 -0
 {
 	struct bpf_func_info *info;
 

...

maintainer
#5 lore raw

Re: [PATCH bpf-next v3 02/17] bpf: Add source and instruction diagnostic context

Quoted 1 line · Eduard Zingerman

On Mon, 2026-07-13 at 17:38 +0200, Kumar Kartikeya Dwivedi wrote:

...

Quoted 5 lines

kernel/bpf/diagnostics.c line 54

Quoted 5 lines
kernel/bpf/diagnostics.c +5 -0
+struct bpf_diag_insn_buf {
+	char *buf;
+	size_t size;
+	size_t len;
+};

One more nit, Claude reminded me that there is struct seq_buf, which is exactly this + a set of primitives including printf. On top of that, seq_buf can be used to manage bump allocation in diag_fmt_alloc(), as in [1].

[1] https://github.com/kernel-patches/bpf/commit/5e719a70cc454ef093aa689d13a0e502cb004962

...

author maintainer
#6 lore raw

PATCH v3 3/17 bpf: Add verifier diagnostic event log

In reply to Kumar Kartikeya Dwivedi

Add an environment-owned diagnostic history for verifier reports. Event payloads keep the user-facing branch history shape, while storage lives in bpf_verifier_env and follows the active verifier path.

Grow the event array as entries are appended and keep saved positions as array indices. Later patches can truncate back to those positions when verifier search backtracks. Add the branch event renderer now, while leaving branch recording to the follow-up patch that wires active-path pruning.

---
 kernel/bpf/diagnostics.c | 184 +++++++++++++++++++++++++++++++++++----
 kernel/bpf/diagnostics.h |   4 +
 kernel/bpf/verifier.c    |  20 ++++-
 3 files changed, 190 insertions(+), 18 deletions(-)
kernel/bpf/diagnostics.c +168 -16
index 49106115621d..ed19220aca9a 100644
@@ -36,6 +36,22 @@
 #define BPF_DIAG_SCRATCH_STR_LEN 256
 #define BPF_DIAG_TEXT_LEN 160
 
+enum bpf_diag_history_kind {
+	BPF_DIAG_HISTORY_BRANCH,
+};
+
+struct bpf_diag_history_event {
+	u32 insn_idx;
+	u8 kind;
+	union {
+		struct {
+			bool cond_true;
+		} branch;
+	};
+};
+
+static void diag_print_history(struct bpf_verifier_env *env);
+
 struct bpf_diag_source_line {
 	const char *line;
 	int line_num;
@@ -58,6 +74,13 @@ struct bpf_diag_insn_ctx {
 	struct bpf_diag_insn_buf buf;
 };
 
+struct bpf_diag_log {
+	struct bpf_diag_history_event *events;
+	u32 cnt;
+	u32 cap;
+	int error;
+};
+
 struct bpf_diag_scratch {
 	char str[BPF_DIAG_SCRATCH_STR_CNT][BPF_DIAG_SCRATCH_STR_LEN];
 	struct bpf_linfo_source source;
@@ -66,6 +89,7 @@ struct bpf_diag_scratch {
 };
 
 struct bpf_diag {
+	struct bpf_diag_log log;
 	struct bpf_diag_scratch scratch;
 };
 
@@ -144,6 +168,51 @@ const char *bpf_diag_scratch_printf(struct bpf_verifier_env *env, unsigned int s
 	return buf;
 }
 
+static void diag_write(struct bpf_verifier_env *env, const char *fmt, ...)
+{
+	va_list args;
+
+	if (!bpf_diag_enabled(env))
+		return;
+
+	va_start(args, fmt);
+	bpf_verifier_vlog(&env->log, fmt, args);
+	va_end(args);
+}
+
+static struct bpf_diag_log *diag_event_log(struct bpf_verifier_env *env)
+{
+	struct bpf_diag *diag = diag_env(env);
+
+	return diag ? &diag->log : NULL;
+}
+
+u32 bpf_diag_event_log_pos(struct bpf_verifier_env *env)
+{
+	struct bpf_diag *diag = diag_env(env);
+
+	if (!diag)
+		return 0;
+	return diag->log.cnt;
+}
+
+void bpf_diag_event_log_reset(struct bpf_verifier_env *env, u32 pos)
+{
+	struct bpf_diag *diag = env->diag;
+	struct bpf_diag_log *log;
+	u32 end;
+
+	if (!diag)
+		return;
+
+	log = &diag->log;
+	end = log->cnt;
+	if (WARN_ON_ONCE(pos > end))
+		pos = end;
+
+	log->cnt = pos;
+}
+
 void bpf_diag_free(struct bpf_verifier_env *env)
 {
 	struct bpf_diag *diag = env->diag;
@@ -151,20 +220,55 @@ void bpf_diag_free(struct bpf_verifier_env *env)
 	if (!diag)
 		return;
 
+	kfree(diag->log.events);
 	kfree(diag);
 	env->diag = NULL;
 }
 
-static void diag_log(struct bpf_verifier_env *env, const char *fmt, ...)
+static const struct bpf_diag_history_event *diag_history_event(const struct bpf_diag_log *log,
+							       u32 idx)
 {
-	va_list args;
+	return &log->events[idx];
+}
 
-	if (!bpf_diag_enabled(env))
-		return;
+static int diag_append_history(struct bpf_verifier_env *env,
+			       const struct bpf_diag_history_event *event)
+{
+	struct bpf_diag_history_event *events;
+	struct bpf_diag_log *log;
+	u32 cap;
 
-	va_start(args, fmt);
-	bpf_verifier_vlog(&env->log, fmt, args);
-	va_end(args);
+	log = diag_event_log(env);
+	if (!log)
+		return 0;
+	if (log->error)
+		return log->error;
+
+	if (log->cnt < log->cap) {
+		log->events[log->cnt++] = *event;
+		return 0;
+	}
+
+	cap = log->cap ? log->cap * 2 : 64;
+	if (cap < log->cap) {
+		log->error = -EOVERFLOW;
+		return log->error;
+	}
+
+	events = krealloc_array(log->events, cap, sizeof(*events), GFP_KERNEL_ACCOUNT);
+	if (!events) {
+		log->error = -ENOMEM;
+		return log->error;
+	}
+	log->events = events;
+	log->cap = cap;
+	log->events[log->cnt++] = *event;
+	return 0;
+}
+
+int bpf_diag_error(const struct bpf_verifier_env *env)
+{
+	return env->diag ? env->diag->log.error : 0;
 }
 
 static void diag_print_wrapped_prefixed(struct bpf_verifier_env *env, const char *first_prefix,
@@ -190,7 +294,7 @@ static void diag_print_wrapped_prefixed(struct bpf_verifier_env *env, const char
 		if (line[len] && line[len] != '\n' && line[len] != ' ' && last_space > 0)
 			len = last_space;
 
-		diag_log(env, "%s%.*s\n", prefix, len, line);
+		diag_write(env, "%s%.*s\n", prefix, len, line);
 
 		text = line + len;
 		while (*text == ' ')
@@ -216,7 +320,7 @@ static void diag_vprint_indented(struct bpf_verifier_env *env, const char *fmt,
 
 	buf = kvasprintf(GFP_KERNEL_ACCOUNT, fmt, args);
 	if (!buf) {
-		diag_log(env, "%s<failed to allocate diagnostic text>\n", BPF_DIAG_TEXT_INDENT);
+		diag_write(env, "%s<failed to allocate diagnostic text>\n", BPF_DIAG_TEXT_INDENT);
 		return;
 	}
 
@@ -467,12 +571,12 @@ void bpf_diag_report_header(struct bpf_verifier_env *env, const char *category,
 	problem = problem ?: "";
 
 	if (!problem[0]) {
-		diag_log(env, "\nVerification failed: %s\n", category);
+		diag_write(env, "\nVerification failed: %s\n", category);
 		return;
 	}
 
 	first = toupper(problem[0]);
-	diag_log(env, "\nVerification failed: %s: %c%s\n", category, first, problem + 1);
+	diag_write(env, "\nVerification failed: %s: %c%s\n", category, first, problem + 1);
 }
 
 static void diag_report_reason(struct bpf_verifier_env *env, const char *fmt, ...) __printf(2, 3);
@@ -484,7 +588,7 @@ static void diag_report_section(struct bpf_verifier_env *env, const char *title)
 	if (!bpf_diag_enabled(env))
 		return;
 
-	diag_log(env, "\n%s:\n", title);
+	diag_write(env, "\n%s:\n", title);
 }
 
 static void diag_report_reason(struct bpf_verifier_env *env, const char *fmt, ...)
@@ -513,7 +617,7 @@ static void diag_report_suggestion(struct bpf_verifier_env *env, const char *fmt
 	va_start(args, fmt);
 	diag_vprint_indented(env, fmt, args);
 	va_end(args);
-	diag_log(env, "\n");
+	diag_write(env, "\n");
 }
 
 static void diag_print_source_annotation(struct bpf_verifier_env *env, int line_width, int indent,
@@ -574,16 +678,16 @@ void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const ch
 	memset(diag_insn, 0, sizeof(scratch->insns));
 
 	if (!diag_get_source(env, insn_idx, src)) {
-		diag_log(env, "  insn %u\n", insn_idx);
+		diag_write(env, "  insn %u\n", insn_idx);
 		diag_print_source_annotation(env, 0, 0, label, msg);
 		goto out_free_msg;
 	}
 
 	func = diag_func_name(env, insn_idx);
 	if (func && *func)
-		diag_log(env, "  %s @ %s:%d:%d\n", func, src->file, src->line_num, src->line_col);
+		diag_write(env, "  %s @ %s:%d:%d\n", func, src->file, src->line_num, src->line_col);
 	else
-		diag_log(env, "  %s:%d:%d\n", src->file, src->line_num, src->line_col);
+		diag_write(env, "  %s:%d:%d\n", src->file, src->line_num, src->line_col);
 
 	start_line = src->line_num - BPF_DIAG_CONTEXT;
 	end_line = src->line_num + BPF_DIAG_CONTEXT;
@@ -619,3 +723,51 @@ void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const ch
 out_free_msg:
 	kfree(msg);
 }
+
+int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true)
+{
+	struct bpf_diag_history_event event = {
+		.insn_idx = insn_idx,
+		.kind = BPF_DIAG_HISTORY_BRANCH,
+		.branch.cond_true = cond_true,
+	};
+
+	return diag_append_history(env, &event);
+}
+
+static void diag_print_history(struct bpf_verifier_env *env)
+{
+	const struct bpf_diag_history_event *event;
+	const struct bpf_diag_log *log;
+	bool printed = false;
+	u32 i;
+
+	diag_report_section(env, "Causal path");
+
+	if (!env->diag) {
+		diag_write(env, "  no recorded diagnostic events on this path\n");
+		return;
+	}
+	log = &env->diag->log;
+
+	for (i = 0; i < log->cnt; i++) {
+		event = diag_history_event(log, i);
+
+		switch (event->kind) {
+		case BPF_DIAG_HISTORY_BRANCH:
+			if (printed)
+				diag_write(env, "\n");
+			bpf_diag_report_source(env, event->insn_idx, "branch",
+					       "took the %s branch of this conditional, goto %s",
+					       event->branch.cond_true ? "true" : "false",
+					       event->branch.cond_true ? "followed" : "not followed");
+			printed = true;
+			break;
+		default:
+			break;
+		}
+	}
+
+	if (!printed)
+		diag_write(env, "  no retained diagnostic events on this path\n");
+}
kernel/bpf/diagnostics.h +4 -0
index d852386bf5f2..e32ac64dd23c 100644
@@ -16,10 +16,14 @@ const char *bpf_diag_scratch_strcpy(struct bpf_verifier_env *env, unsigned int s
 				    const char *str);
 const char *bpf_diag_scratch_printf(struct bpf_verifier_env *env, unsigned int slot,
 				    const char *fmt, ...) __printf(3, 4);
+u32 bpf_diag_event_log_pos(struct bpf_verifier_env *env);
+void bpf_diag_event_log_reset(struct bpf_verifier_env *env, u32 pos);
+int bpf_diag_error(const struct bpf_verifier_env *env);
 void bpf_diag_free(struct bpf_verifier_env *env);
 void bpf_diag_report_header(struct bpf_verifier_env *env, const char *category,
 			    const char *problem);
 void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const char *label,
 			    const char *fmt, ...) __printf(4, 5);
+int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true);
 
 #endif /* __BPF_DIAGNOSTICS_H */
kernel/bpf/verifier.c +18 -2
index 4f127c8db134..d0d399b879e5 100644
@@ -16135,6 +16135,9 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 		}
 		if (env->log.level & BPF_LOG_LEVEL)
 			print_insn_state(env, this_branch, this_branch->curframe);
+		err = bpf_diag_record_branch(env, *insn_idx, true);
+		if (err)
+			return err;
 		*insn_idx += insn->off;
 		return 0;
 	} else if (pred == 0) {
@@ -16150,7 +16153,7 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 		}
 		if (env->log.level & BPF_LOG_LEVEL)
 			print_insn_state(env, this_branch, this_branch->curframe);
-		return 0;
+		return bpf_diag_record_branch(env, *insn_idx, false);
 	}
 
 	/* Push scalar registers sharing same ID to jump history,
@@ -16182,6 +16185,9 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 	other_branch_regs[insn->dst_reg] = env->true_reg1;
 	if (BPF_SRC(insn->code) == BPF_X)
 		other_branch_regs[insn->src_reg] = env->true_reg2;
+	err = bpf_diag_record_branch(env, *insn_idx, false);
+	if (err)
+		return err;
 
 	if (BPF_SRC(insn->code) == BPF_X &&
 	    src_reg->type == SCALAR_VALUE && src_reg->id &&
@@ -17437,6 +17443,10 @@ static int do_check(struct bpf_verifier_env *env)
 		/* reset current history entry on each new instruction */
 		env->cur_hist_ent = NULL;
 
+		err = bpf_diag_error(env);
+		if (err)
+			return err;
+
 		env->prev_insn_idx = prev_insn_idx;
 		if (env->insn_idx >= insn_cnt) {
 			verbose(env, "invalid insn idx %d insn_cnt %d\n",
@@ -17547,6 +17557,12 @@ static int do_check(struct bpf_verifier_env *env)
 			goto process_bpf_exit;
 
 		err = do_check_insn(env, &do_print_state);
+		if (err >= 0) {
+			int diag_err = bpf_diag_error(env);
+
+			if (diag_err)
+				return diag_err;
+		}
 		if (error_recoverable_with_nospec(err) && state->speculative) {
 			/* Prevent this speculative path from ever reaching the
 			 * insn that would have been unsafe to execute.
@@ -17604,7 +17620,7 @@ static int do_check(struct bpf_verifier_env *env)
 		}
 	}
 
-	return 0;
+	return bpf_diag_error(env);
 }
 
 static int find_btf_percpu_datasec(struct btf *btf)
Signature · 1 line
2.53.0
#7 lore raw

Re: [PATCH bpf-next v3 03/17] bpf: Add verifier diagnostic event log

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] Unbounded growth of diagnostic event log causes `-ENOMEM` verification failures for valid BPF…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Unbounded growth of diagnostic event log causes -ENOMEM verification failures for valid BPF programs due to memory fragmentation.
- [Low] Unused static function diag_print_history causes build failure with -Werror.
--

--- Patch [3]: [PATCH bpf-next v3 03/17] bpf: Add verifier diagnostic event log --- commit 84f2d0d4f3731edb22773c28c7395e2076557ddb
Author: Kumar Kartikeya Dwivedi <[email protected]>

bpf: Add verifier diagnostic event log

This commit adds an environment-owned diagnostic history for verifier reports to track branch events. The event array grows as entries are appended, saving positions for future truncation when the verifier backtracks.

Quoted 4 lines
kernel/bpf/diagnostics.c +0 -0
index 49106115621db..ed19220aca9a9 100644

[ ... ]

kernel/bpf/diagnostics.c void bpf_diag_free(struct bpf_verifier_env *env) · line 258

Quoted 7 lines
kernel/bpf/diagnostics.c +7 -0
+	cap = log->cap ? log->cap * 2 : 64;
+	if (cap < log->cap) {
+		log->error = -EOVERFLOW;
+		return log->error;
+	}
+
+	events = krealloc_array(log->events, cap, sizeof(*events), GFP_KERNEL_ACCOUNT);

[Severity: High]
The bpf_diag_record_branch function is called for every evaluated conditional jump without corresponding truncation during verifier backtracking, which records all explored paths instead of just the active causal path.

For complex programs approaching the one million instruction limit, the log can grow to several megabytes.

Since krealloc_array requires physically contiguous memory, these large allocations are highly likely to fail due to memory fragmentation.

Could this unbounded reallocation cause memory allocation failures for valid BPF programs?

Quoted 4 lines
kernel/bpf/diagnostics.c +4 -0
+	if (!events) {
+		log->error = -ENOMEM;
+		return log->error;
+	}

[ ... ]

kernel/bpf/diagnostics.c void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const ch · line 739

Quoted 2 lines
kernel/bpf/diagnostics.c +2 -0
+static void diag_print_history(struct bpf_verifier_env *env)
+{

[Severity: Low]
It appears this is defined but never called in this patch.

This triggers a compiler warning for an unused function and breaks the build when the kernel is compiled with warnings as errors.

Is this static function currently used anywhere in the file?

Quoted 4 lines
kernel/bpf/diagnostics.c +4 -0
+	const struct bpf_diag_history_event *event;
+	const struct bpf_diag_log *log;
+	bool printed = false;
+	u32 i;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
maintainer
#8 lore raw

Re: [PATCH bpf-next v3 03/17] bpf: Add verifier diagnostic event log

In reply to Kumar Kartikeya Dwivedi

On Mon, 2026-07-13 at 17:38 +0200, Kumar Kartikeya Dwivedi wrote:

...

Quoted 8 lines
kernel/bpf/diagnostics.c +0 -0
index 49106115621d..ed19220aca9a 100644
@@ -36,6 +36,22 @@
  #define BPF_DIAG_SCRATCH_STR_LEN 256
  #define BPF_DIAG_TEXT_LEN 160

kernel/bpf/diagnostics.c line 45

Quoted 7 lines
kernel/bpf/diagnostics.c +7 -0
+enum bpf_diag_history_kind {
+	BPF_DIAG_HISTORY_BRANCH,
+};
+
+struct bpf_diag_history_event {
+	u32 insn_idx;
+	u8 kind;

In the patch #5 you have this as:

	u32 insn_idx:24;
	u8 kind:8;

Let's keep it like that from the beginning.

Quoted 6 lines
kernel/bpf/diagnostics.c +6 -0
+	union {
+		struct {
+			bool cond_true;
+		} branch;
+	};
+};

...

Quoted 5 lines
kernel/bpf/diagnostics.c +0 -0
@@ -144,6 +168,51 @@ const char *bpf_diag_scratch_printf(struct bpf_verifier_env *env, unsigned int s
  	return buf;
  }


+static void diag_write(struct bpf_verifier_env *env, const char *fmt, ...)

This supersedes diag_log(), let's not add diag_log in a first place.

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+{
+	va_list args;
+
+	if (!bpf_diag_enabled(env))
+		return;
+
+	va_start(args, fmt);
+	bpf_verifier_vlog(&env->log, fmt, args);
+	va_end(args);
+}

...

Quoted 22 lines
kernel/bpf/diagnostics.c +0 -0
@@ -619,3 +723,51 @@ void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const ch

 out_free_msg:
  kfree(msg);
 }

kernel/bpf/diagnostics.c +18 -0
+
+int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true)
+{
+	struct bpf_diag_history_event event = {
+		.insn_idx = insn_idx,
+		.kind = BPF_DIAG_HISTORY_BRANCH,
+		.branch.cond_true = cond_true,
+	};
+
+	return diag_append_history(env, &event);
+}
+
+static void diag_print_history(struct bpf_verifier_env *env)
+{
+	const struct bpf_diag_history_event *event;
+	const struct bpf_diag_log *log;
+	bool printed = false;
+	u32 i;

kernel/bpf/diagnostics.c void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const ch · line 753

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+
+	diag_report_section(env, "Causal path");
+
+	if (!env->diag) {
+		diag_write(env, "  no recorded diagnostic events on this path\n");
+		return;
+	}
+	log = &env->diag->log;
+
+	for (i = 0; i < log->cnt; i++) {
             ^^^^^

As far as I understand, when the complete patch-set is applied the start index for branch history events is zero as well. Do we want to cap the amount of printed events by e.g. 10/50/100 or some reasonable amount?

Quoted 20 lines
kernel/bpf/diagnostics.c +20 -0
+		event = diag_history_event(log, i);
+
+		switch (event->kind) {
+		case BPF_DIAG_HISTORY_BRANCH:
+			if (printed)
+				diag_write(env, "\n");
+			bpf_diag_report_source(env, event->insn_idx, "branch",
+					       "took the %s branch of this conditional, goto %s",
+					       event->branch.cond_true ? "true" : "false",
+					       event->branch.cond_true ? "followed" : "not followed");
+			printed = true;
+			break;
+		default:
+			break;
+		}
+	}
+
+	if (!printed)
+		diag_write(env, "  no retained diagnostic events on this path\n");
+}

...

kernel/bpf/verifier.c static int check_cond_jmp_op(struct bpf_verifier_env *env, · line 16140

Quoted 11 lines
kernel/bpf/verifier.c +3 -0
index 4f127c8db134..d0d399b879e5 100644
@@ -16135,6 +16135,9 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
  		}
  		if (env->log.level & BPF_LOG_LEVEL)
  			print_insn_state(env, this_branch, this_branch->curframe);
+		err = bpf_diag_record_branch(env, *insn_idx, true);
+		if (err)
+			return err;

I'd try to avoid having spreading these calls across the code-base. How about checking prev_insn_idx and insn_idx in the do_check() in the same block where the following happens:

		if (bpf_is_jmp_point(env, env->insn_idx)) {
			err = bpf_push_jmp_history(env, state, 0, 0, 0, 0);
			if (err)
				return err;
		}

?

Quoted 3 lines
kernel/bpf/verifier.c +0 -0
  		*insn_idx += insn->off;
  		return 0;
  	} else if (pred == 0) {

...

kernel/bpf/verifier.c static int do_check(struct bpf_verifier_env *env) · line 17449

Quoted 8 lines
kernel/bpf/verifier.c +0 -0
@@ -17437,6 +17443,10 @@ static int do_check(struct bpf_verifier_env *env)
  		/* reset current history entry on each new instruction */
  		env->cur_hist_ent = NULL;

kernel/bpf/verifier.c +4 -0
+		err = bpf_diag_error(env);
+		if (err)
+			return err;
+

Let's not do this and propagate errors properly instead, would that lead to a big diff?

Quoted 3 lines

  env->prev_insn_idx = prev_insn_idx;
  if (env->insn_idx >= insn_cnt) {
  verbose(env, "invalid insn idx %d insn_cnt %d\n",

...

maintainer
#9 lore raw

Re: [PATCH bpf-next v3 03/17] bpf: Add verifier diagnostic event log

Quoted 1 line · Eduard Zingerman

On Mon, 2026-07-13 at 17:38 +0200, Kumar Kartikeya Dwivedi wrote:

...

Quoted 17 lines
Quoted 6 lines
kernel/bpf/diagnostics.c +6 -0
+static void diag_print_history(struct bpf_verifier_env *env)
+{
+	const struct bpf_diag_history_event *event;
+	const struct bpf_diag_log *log;
+	bool printed = false;
+	u32 i;

kernel/bpf/diagnostics.c void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const ch · line 753

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+
+	diag_report_section(env, "Causal path");
+
+	if (!env->diag) {
+		diag_write(env, "  no recorded diagnostic events on this path\n");
+		return;
+	}
+	log = &env->diag->log;
+
+	for (i = 0; i < log->cnt; i++) {
             ^^^^^
Quoted 4 lines

As far as I understand, when the complete patch-set is applied the start index for branch history events is zero as well. Do we want to cap the amount of printed events by e.g. 10/50/100 or some reasonable amount?

So, I was curious how performant the current version is, so I added
[1] as a stress test and used 'veristat -vl7 pyperf600.bpf.o' as guinea pig. Conclusion is that printing all accumulated events is very slow, 6s to collect level 2 log on master vs ~5m with this patch-set. Perf report is obvious in a hindsight:

- 35.50% veristat [kernel.kallsyms] [k] strrchr
- strrchr
- 35.49% bpf_get_linfo_source
- bpf_diag_report_source
+ 35.49% diag_print_history
- 20.77% veristat [kernel.kallsyms] [k] bpf_get_linfo_source
bpf_get_linfo_source
- bpf_diag_report_source
+ 20.77% diag_print_history
- 17.80% veristat [kernel.kallsyms] [k] bpf_diag_report_source
- bpf_diag_report_source
+ 17.80% diag_print_history

  +    5.58%  veristat  [kernel.kallsyms]     [k] btf_name_by_offset
  +    2.75%  veristat  [kernel.kallsyms]     [k] x86_pmu_enable_event

So we either need to limit the amount of events printed or work on more efficient algorithm for source line search (build a whole index in one go?) / cashing.

[1] https://github.com/kernel-patches/bpf/commit/99c06ed1d51826dbfdba115c71fc691696bfcbac

Quoted 20 lines
Quoted 20 lines
kernel/bpf/diagnostics.c +20 -0
+		event = diag_history_event(log, i);
+
+		switch (event->kind) {
+		case BPF_DIAG_HISTORY_BRANCH:
+			if (printed)
+				diag_write(env, "\n");
+			bpf_diag_report_source(env, event->insn_idx, "branch",
+					       "took the %s branch of this conditional, goto %s",
+					       event->branch.cond_true ? "true" : "false",
+					       event->branch.cond_true ? "followed" : "not followed");
+			printed = true;
+			break;
+		default:
+			break;
+		}
+	}
+
+	if (!printed)
+		diag_write(env, "  no retained diagnostic events on this path\n");
+}

...

maintainer
#10 lore raw

Re: [PATCH bpf-next v3 03/17] bpf: Add verifier diagnostic event log

In reply to Kumar Kartikeya Dwivedi

On Mon, 2026-07-13 at 17:38 +0200, Kumar Kartikeya Dwivedi wrote:

...

Quoted 18 lines
kernel/bpf/diagnostics.c +14 -3
+static int diag_append_history(struct bpf_verifier_env *env,
+			       const struct bpf_diag_history_event *event)
+{
+	struct bpf_diag_history_event *events;
+	struct bpf_diag_log *log;
+	u32 cap;
 
-	va_start(args, fmt);
-	bpf_verifier_vlog(&env->log, fmt, args);
-	va_end(args);
+	log = diag_event_log(env);
+	if (!log)
+		return 0;
+	if (log->error)
+		return log->error;
+
+	if (log->cnt < log->cap) {
+		log->events[log->cnt++] = *event;

kernel/bpf/diagnostics.c void bpf_diag_free(struct bpf_verifier_env *env) · line 258

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+		return 0;
+	}
+
+	cap = log->cap ? log->cap * 2 : 64;
+	if (cap < log->cap) {
+		log->error = -EOVERFLOW;
+		return log->error;
+	}
+
+	events = krealloc_array(log->events, cap, sizeof(*events), GFP_KERNEL_ACCOUNT);

This needs to be kvrealloc, otherwise it can't handle pyperf600.bpf.o.

[1] https://github.com/kernel-patches/bpf/commit/ecb6671190348b56eecc3b10339df4b162de1529

Quoted 9 lines
kernel/bpf/diagnostics.c +9 -0
+	if (!events) {
+		log->error = -ENOMEM;
+		return log->error;
+	}
+	log->events = events;
+	log->cap = cap;
+	log->events[log->cnt++] = *event;
+	return 0;
+}

...

author maintainer
#11 lore raw

PATCH v3 4/17 bpf: Prune verifier diagnostics when switching paths

In reply to Kumar Kartikeya Dwivedi

Save the diagnostic event-log position with each verifier stack entry and reset the environment-owned stream together with the normal verifier log when a queued state is popped. Also reset the diagnostic stream after successful subprogram verification even when level-2 logging preserves the normal verifier log.

Record branch outcomes as true or false. Later reports use those events to show the path that reached a verifier error. For queued branches, save the queued outcome with the verifier stack entry and append it when that state is popped; record the active branch immediately before continuing.

---
 kernel/bpf/verifier.c | 46 +++++++++++++++++++++++++++++++++++--------
 1 file changed, 38 insertions(+), 8 deletions(-)
kernel/bpf/verifier.c +38 -8
index d0d399b879e5..648adf3b7aaa 100644
@@ -189,11 +189,15 @@ struct bpf_verifier_stack_elem {
 	 * and after processing instruction 'prev_insn_idx'
 	 */
 	struct bpf_verifier_state st;
+	/* Only conditional-branch states have a queued diagnostic branch. */
+	u8 diag_branch_valid : 1;
+	u8 diag_branch_cond_true : 1;
 	int insn_idx;
 	int prev_insn_idx;
 	struct bpf_verifier_stack_elem *next;
 	/* length of verifier log at the time this state was pushed on stack */
 	u32 log_pos;
+	u32 diag_log_pos;
 };
 
 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ	8192
@@ -1706,8 +1710,8 @@ void bpf_free_backedges(struct bpf_scc_visit *visit)
 	visit->backedges = NULL;
 }
 
-static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
-		     int *insn_idx, bool pop_log)
+static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, int *insn_idx, bool pop_log,
+		     bool activate_diag_branch)
 {
 	struct bpf_verifier_state *cur = env->cur_state;
 	struct bpf_verifier_stack_elem *elem, *head = env->head;
@@ -1723,6 +1727,12 @@ static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
 	}
 	if (pop_log)
 		bpf_vlog_reset(&env->log, head->log_pos);
+	bpf_diag_event_log_reset(env, head->diag_log_pos);
+	if (activate_diag_branch && head->diag_branch_valid) {
+		err = bpf_diag_record_branch(env, head->prev_insn_idx, head->diag_branch_cond_true);
+		if (err)
+			return err;
+	}
 	if (insn_idx)
 		*insn_idx = head->insn_idx;
 	if (prev_insn_idx)
@@ -1763,6 +1773,7 @@ static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
 	elem->prev_insn_idx = prev_insn_idx;
 	elem->next = env->head;
 	elem->log_pos = env->log.end_pos;
+	elem->diag_log_pos = bpf_diag_event_log_pos(env);
 	env->head = elem;
 	env->stack_size++;
 	err = bpf_copy_verifier_state(&elem->st, cur);
@@ -1789,6 +1800,20 @@ static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env,
 	return &elem->st;
 }
 
+static struct bpf_verifier_state *push_stack_with_branch_diag(struct bpf_verifier_env *env,
+							      int insn_idx, int prev_insn_idx,
+							      bool speculative, bool cond_true)
+{
+	struct bpf_verifier_state *st;
+
+	st = push_stack(env, insn_idx, prev_insn_idx, speculative);
+	if (!IS_ERR(st)) {
+		env->head->diag_branch_valid = true;
+		env->head->diag_branch_cond_true = cond_true;
+	}
+	return st;
+}
+
 static const char *reg_arg_name(struct bpf_verifier_env *env, argno_t argno)
 {
 	char *buf = env->tmp_arg_name;
@@ -2287,6 +2312,7 @@ static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env,
 	elem->prev_insn_idx = prev_insn_idx;
 	elem->next = env->head;
 	elem->log_pos = env->log.end_pos;
+	elem->diag_log_pos = bpf_diag_event_log_pos(env);
 	env->head = elem;
 	env->stack_size++;
 	if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) {
@@ -16171,7 +16197,8 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 			return err;
 	}
 
-	other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, false);
+	other_branch =
+		push_stack_with_branch_diag(env, *insn_idx + insn->off + 1, *insn_idx, false, true);
 	if (IS_ERR(other_branch))
 		return PTR_ERR(other_branch);
 	other_branch_regs = other_branch->frame[other_branch->curframe]->regs;
@@ -17607,8 +17634,7 @@ static int do_check(struct bpf_verifier_env *env)
 			err = bpf_update_branch_counts(env, env->cur_state);
 			if (err)
 				return err;
-			err = pop_stack(env, &prev_insn_idx, &env->insn_idx,
-					pop_log);
+			err = pop_stack(env, &prev_insn_idx, &env->insn_idx, pop_log, true);
 			if (err < 0) {
 				if (err != -ENOENT)
 					return err;
@@ -18464,7 +18490,8 @@ static void free_states(struct bpf_verifier_env *env)
 
 	bpf_free_verifier_state(env->cur_state, true);
 	env->cur_state = NULL;
-	while (!pop_stack(env, NULL, NULL, false));
+	while (!pop_stack(env, NULL, NULL, false, false))
+		;
 
 	list_for_each_safe(pos, tmp, &env->free_list) {
 		sl = container_of(pos, struct bpf_verifier_state_list, node);
@@ -18643,8 +18670,11 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog)
 
 	ret = do_check(env);
 out:
-	if (!ret && pop_log)
-		bpf_vlog_reset(&env->log, 0);
+	if (!ret) {
+		if (pop_log)
+			bpf_vlog_reset(&env->log, 0);
+		bpf_diag_event_log_reset(env, 0);
+	}
 	free_states(env);
 	return ret;
 }
Signature · 1 line
2.53.0
#12 lore raw

Re: [PATCH bpf-next v3 04/17] bpf: Prune verifier diagnostics when switching paths

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [High] Unconditional truncation of the diagnostic event log in `pop_stack()` destroys the diagnostic…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [High] Unconditional truncation of the diagnostic event log in pop_stack() destroys the diagnostic trace when the verifier encounters an error.
- [Low] The commit message inaccurately claims to add logic to record the active branch, but this logic was already introduced in a preceding patch. --

--- Patch [4]: [PATCH bpf-next v3 04/17] bpf: Prune verifier diagnostics when switching paths --- commit 59e4455992c872528b5e207bc7864d38d2ea193e
Author: Kumar Kartikeya Dwivedi <[email protected]>

bpf: Prune verifier diagnostics when switching paths

This commit saves the diagnostic event-log position with each verifier stack entry and resets it when a queued state is popped or after a successful subprogram verification. It also queues diagnostic outcomes for branches and appends them when states are popped.

Quoted 4 lines

Record branch outcomes as true or false. Later reports use those events to show the path that reached a verifier error. For queued branches, save the queued outcome with the verifier stack entry and append it when that state is popped; record the active branch immediately before continuing.

[Severity: Low]
This isn't a bug, but the commit message states it adds logic to "record the active branch immediately before continuing". However, looking at the code, it appears this logic was already introduced in a preceding patch and is not actually part of this commit's diff in check_cond_jmp_op(). Should the commit message be updated to reflect only the changes made here?

Quoted 3 lines
kernel/bpf/verifier.c +0 -0

[ ... ]

Quoted 12 lines
kernel/bpf/verifier.c +2 -2
@@ -1706,8 +1710,8 @@ void bpf_free_backedges(struct bpf_scc_visit *visit)
 	visit->backedges = NULL;
 }
 
-static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
-		     int *insn_idx, bool pop_log)
+static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, int *insn_idx, bool pop_log,
+		     bool activate_diag_branch)
 {
 	struct bpf_verifier_state *cur = env->cur_state;
 	struct bpf_verifier_stack_elem *elem, *head = env->head;

kernel/bpf/verifier.c static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, · line 1730

Quoted 4 lines
kernel/bpf/verifier.c +1 -0
@@ -1723,6 +1727,12 @@ static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx,
 	}
 	if (pop_log)
 		bpf_vlog_reset(&env->log, head->log_pos);
+	bpf_diag_event_log_reset(env, head->diag_log_pos);

[Severity: High]
When a program fails verification, do_check() returns a negative error, causing do_check_common() to call free_states().

free_states() loops over the remaining states, calling pop_stack() with false for both pop_log and activate_diag_branch:

kernel/bpf/verifier.c:free_states() {
    ...
    while (!pop_stack(env, NULL, NULL, false, false))
        ;
    ...
}

Because bpf_diag_event_log_reset() is called unconditionally here in pop_stack(), won't this truncate or completely destroy the diagnostic trace during error cleanup?

If the log is rolled back to the length it had when each unvisited state was queued, does this result in an empty or useless diagnostic output for users trying to debug verifier failures? Should this reset also be conditional?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
maintainer
#13 lore raw

Re: [PATCH bpf-next v3 04/17] bpf: Prune verifier diagnostics when switching paths

In reply to Kumar Kartikeya Dwivedi

On Mon, 2026-07-13 at 17:38 +0200, Kumar Kartikeya Dwivedi wrote:

...

Quoted 8 lines
kernel/bpf/verifier.c +0 -0
index d0d399b879e5..648adf3b7aaa 100644
@@ -189,11 +189,15 @@ struct bpf_verifier_stack_elem {
  	 * and after processing instruction 'prev_insn_idx'
  	 */
  	struct bpf_verifier_state st;

kernel/bpf/verifier.c struct bpf_verifier_stack_elem { · line 201

Quoted 10 lines
kernel/bpf/verifier.c +4 -0
+	/* Only conditional-branch states have a queued diagnostic branch. */
+	u8 diag_branch_valid : 1;
+	u8 diag_branch_cond_true : 1;
  	int insn_idx;
  	int prev_insn_idx;
  	struct bpf_verifier_stack_elem *next;
  	/* length of verifier log at the time this state was pushed on stack */
  	u32 log_pos;
+	u32 diag_log_pos;
  };

Assuming the bpf_diag_record_branch() is called in do_check():

		if (bpf_is_jmp_point(env, env->insn_idx)) {
			err = bpf_push_jmp_history(env, state, 0, 0, 0, 0);
			if (err)
				return err;
			if (prev is jmp) {
                        	if ((err = bpf_diag_record_branch()))
                                	return err;
                        }
		}

This patch would be reduced to diag_log_pos management.

...

author maintainer
#14 lore raw

PATCH v3 5/17 bpf: Track verifier register diagnostic events

In reply to Kumar Kartikeya Dwivedi

Record material register and outgoing stack argument changes so diagnostics can explain how a value reached its current type, bounds, or unreadable state.

Store old and new register types, scalar ranges, tnum value and mask, map and BTF type identity, and basic operand metadata in the environment-owned diagnostic event stream.

Record invalidations when packet data moves, references are released, or borrowed references leave their protected region. Register-scoped history starts at the latest matching modification and then shows later branch outcomes.

Also record fixed stack spills and overwrites, and tag register fills from stack so register-scoped history can follow value flow through spilled stack slots.

---
 include/linux/bpf_verifier.h |  12 +
 kernel/bpf/diagnostics.c     | 713 ++++++++++++++++++++++++++++++++++-
 kernel/bpf/diagnostics.h     |  81 ++++
 kernel/bpf/log.c             |  11 -
 kernel/bpf/verifier.c        | 363 ++++++++++++++++--
 5 files changed, 1126 insertions(+), 54 deletions(-)
include/linux/bpf_verifier.h +12 -0
index 3ff27863e34d..625ea3e394a2 100644
@@ -1343,6 +1343,18 @@ static inline bool type_is_non_owning_ref(u32 type)
 	return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF;
 }
 
+static inline bool type_is_map_ptr(enum bpf_reg_type type)
+{
+	switch (base_type(type)) {
+	case CONST_PTR_TO_MAP:
+	case PTR_TO_MAP_KEY:
+	case PTR_TO_MAP_VALUE:
+		return true;
+	default:
+		return false;
+	}
+}
+
 static inline bool type_is_pkt_pointer(enum bpf_reg_type type)
 {
 	type = base_type(type);
kernel/bpf/diagnostics.c +696 -17

801 lines not on this page · raw message

kernel/bpf/diagnostics.h +81 -0

101 lines not on this page · raw message

kernel/bpf/log.c +0 -11
index b740fa73ee26..589770ca3d3a 100644
@@ -615,17 +615,6 @@ static void print_scalar_ranges(struct bpf_verifier_env *env,
 	}
 }
 
-static bool type_is_map_ptr(enum bpf_reg_type t) {
-	switch (base_type(t)) {
-	case CONST_PTR_TO_MAP:
-	case PTR_TO_MAP_KEY:
-	case PTR_TO_MAP_VALUE:
-		return true;
-	default:
-		return false;
-	}
-}
-
 /*
  * _a stands for append, was shortened to avoid multiline statements below.
  * This macro is used to output a comma separated list of attributes.
kernel/bpf/verifier.c +337 -26

533 lines not on this page · raw message

Signature · 1 line
2.53.0
#15 lore raw

Re: [PATCH bpf-next v3 05/17] bpf: Track verifier register diagnostic events

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Missing diagnostic history for R0 return values on alternate verification branches pushed during…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Missing diagnostic history for R0 return values on alternate verification branches pushed during iterator kfunc evaluation. --

--- Patch [5]: [PATCH bpf-next v3 05/17] bpf: Track verifier register diagnostic events --- commit 89ba11918f62e11a29a14afb1bb19f115cbbdd40
Author: Kumar Kartikeya Dwivedi <[email protected]>

bpf: Track verifier register diagnostic events

This commit adds diagnostic tracking for the BPF verifier to explain how a register or stack value reached its current state. It records register and stack modifications, invalidations, and causal history in a diagnostic event stream.

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index 648adf3b7aaa1..4a468299f05e9 100644

[ ... ]

kernel/bpf/verifier.c static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, · line 13692

Quoted 9 lines
kernel/bpf/verifier.c +2 -0
@@ -13392,6 +13685,8 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 			return err;
 	}
 
+	bpf_diag_record_call_ret(env, insn_idx, regs);
+
 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
 		env->prog->call_session_cookie = true;
 

[Severity: Medium]
Will this miss diagnostic history for R0 return values on alternate verification branches pushed during iterator kfunc evaluation?

When an iterator next kfunc (e.g., bpf_iter_num_next) is evaluated, process_iter_next_call() pushes the alternate verification branch via push_stack(), which snapshots the diagnostic log position.

The current branch then proceeds to call bpf_diag_record_call_ret() here, adding the R0 modification to its log. When the pushed branch resumes, its log is reset to the snapshot taken before this bpf_diag_record_call_ret() call, permanently skipping the event on that path.

Could this result in a confused developer seeing that R0 was invalidated as a caller-saved register, but not seeing the subsequent function return assignment?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
maintainer
#16 lore raw

Re: [PATCH bpf-next v3 05/17] bpf: Track verifier register diagnostic events

In reply to Kumar Kartikeya Dwivedi

On Mon, 2026-07-13 at 17:38 +0200, Kumar Kartikeya Dwivedi wrote:

...

Quoted 4 lines
kernel/bpf/diagnostics.c +0 -0
index ed19220aca9a..1a45ec926c71 100644

...

Quoted 27 lines
kernel/bpf/diagnostics.c +1 -0
@@ -34,23 +35,64 @@
  #define BPF_DIAG_REG_TMP_LEN 192
  #define BPF_DIAG_SCRATCH_STR_CNT 3
  #define BPF_DIAG_SCRATCH_STR_LEN 256
+#define BPF_DIAG_SCRATCH_REG_CNT CALLER_SAVED_REGS
  #define BPF_DIAG_TEXT_LEN 160

kernel/bpf/diagnostics.c +9 -0
+struct bpf_diag_reg_snapshot {
+	u32 type;
+	u32 btf_id;
+	const struct bpf_map *map_ptr;
+	const struct btf *btf;
+	struct tnum var_off;
+	struct cnum64 r64;
+};
+

 enum bpf_diag_history_kind {
  BPF_DIAG_HISTORY_BRANCH,

kernel/bpf/diagnostics.c +6 -0
+	BPF_DIAG_HISTORY_MOD,
+};
+
+struct bpf_diag_event_hdr {
+	u32 insn_idx : 24;
+	u32 kind : 8;

 };

 struct bpf_diag_history_event {

kernel/bpf/diagnostics.c line 45

Quoted 2 lines
kernel/bpf/diagnostics.c +0 -2
-	u32 insn_idx;
-	u8 kind;

Let's keep this as a single common part instead of bpf_diag_event_hdr (again, the prefixes are completely unnecessary). Every event in the series relies on such header, so there is no need to keep it spread across struct and a union.

Quoted 19 lines

  union {
  struct {

kernel/bpf/diagnostics.c +5 -0
+			u32 insn_idx : 24;
+			u32 kind : 8;
+		};
+		struct {
+			struct bpf_diag_event_hdr hdr;

  bool cond_true;
  } branch;

kernel/bpf/diagnostics.c +8 -0
+		struct {
+			struct bpf_diag_event_hdr hdr;
+			struct bpf_diag_mod_target target;
+			struct bpf_diag_mod_target origin;
+			struct bpf_diag_reg_snapshot old, new;
+			u8 reason;
+			bool origin_valid;
+		} mod;

  };
 };

...

Quoted 5 lines
kernel/bpf/diagnostics.c +1 -0
@@ -81,11 +123,27 @@ struct bpf_diag_log {
 	int error;
 };
 
+struct bpf_diag_reg_fmt {

kernel/bpf/diagnostics.c struct bpf_diag_log { · line 136

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+	char old_buf[BPF_DIAG_REG_DESC_LEN];
+	char new_buf[BPF_DIAG_REG_DESC_LEN];
+	char offset_desc[BPF_DIAG_REG_DESC_LEN];
+	char btf_type[BPF_DIAG_REG_TMP_LEN];
+	char range[BPF_DIAG_REG_TMP_LEN];
+	char smin_buf[32];
+	char smax_buf[32];
+	char umin_buf[32];
+	char umax_buf[32];
+};

The amount of scratch buffers of various kind is a bit high throughout the series, wdyt about the following unification for the string scratch buffers handling:

https://github.com/kernel-patches/bpf/commit/078fbf9471c1f9d59c61877afd5b9a8e7f189462

?

I played with bump allocator for strings but it does not show much difference compared to plain kasprintf(). At least not with current hot points (more on this separately).

kernel/bpf/diagnostics.c struct bpf_diag_log { · line 145

Quoted 9 lines
kernel/bpf/diagnostics.c +4 -0
+
  struct bpf_diag_scratch {
  	char str[BPF_DIAG_SCRATCH_STR_CNT][BPF_DIAG_SCRATCH_STR_LEN];
+	struct bpf_reg_state regs[BPF_DIAG_SCRATCH_REG_CNT];
  	struct bpf_linfo_source source;
  	struct bpf_diag_source_line source_lines[BPF_DIAG_CONTEXT_CNT];
  	struct bpf_diag_insn insns[BPF_DIAG_CONTEXT_CNT];
+	unsigned long *history_bitmap;
+	u32 history_bitmap_nbits;

Instead of maintaining a standalone bitmap, one can dedicate a bit in the event entry itself.

Quoted 2 lines
kernel/bpf/diagnostics.c +1 -0
+	struct bpf_diag_reg_fmt reg_fmt;
  };

...

Quoted 5 lines
kernel/bpf/diagnostics.c +0 -0
@@ -311,6 +379,36 @@ static void diag_print_wrapped_text(struct bpf_verifier_env *env, const char *te
  	diag_print_wrapped_prefixed(env, BPF_DIAG_TEXT_INDENT, BPF_DIAG_TEXT_INDENT, text);
  }


+void bpf_diag_format_btf_type(char *buf, size_t size, const struct btf *btf, u32 type_id)

All callers are internal for diagnostics.c

Quoted 8 lines
kernel/bpf/diagnostics.c +8 -0
+{
+	size_t len;
+	int ret;
+
+	buf[0] = '\0';
+	ret = btf_type_snprintf_show_name(btf, type_id, buf, size);
+	if (ret < 0 || !buf[0]) {
+		scnprintf(buf, size, "BTF type ID %u", type_id);

kernel/bpf/diagnostics.c static void diag_print_wrapped_text(struct bpf_verifier_env *env, const char *te · line 400

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+		return;
+	}
+
+	len = strlen(buf);
+	if (len && buf[len - 1] == '{')
+		buf[len - 1] = '\0';
+}
+
+const char *bpf_diag_format_btf_type_scratch(struct bpf_verifier_env *env, unsigned int slot,
+					     const struct btf *btf, u32 type_id)

There are no callers for this function.

Quoted 15 lines
kernel/bpf/diagnostics.c +11 -0
+{
+	size_t size;
+	char *buf = bpf_diag_scratch_buf(env, slot, &size);
+
+	if (!buf)
+		return "";
+
+	bpf_diag_format_btf_type(buf, size, btf, type_id);
+	return buf;
+}
+

 static void diag_vprint_indented(struct bpf_verifier_env *env, const char *fmt, va_list args) {
  char *buf;

kernel/bpf/diagnostics.c +0 -0
@@ -727,47 +825,628 @@ void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const ch

...

kernel/bpf/diagnostics.c void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const ch · line 863

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+static bool diag_snapshot_eq(const struct bpf_diag_reg_snapshot *old,
+			     const struct bpf_diag_reg_snapshot *new)
+{
+	return old->type == new->type && old->map_ptr == new->map_ptr && old->btf == new->btf &&
+	       old->btf_id == new->btf_id && old->var_off.value == new->var_off.value &&
+	       old->var_off.mask == new->var_off.mask && old->r64.base == new->r64.base &&
+	       old->r64.size == new->r64.size;
+}
+
+static bool diag_mod_snapshot_eq(const struct bpf_diag_history_event *event)

This wrapper is useless.

Quoted 23 lines
kernel/bpf/diagnostics.c +23 -0
+{
+	return diag_snapshot_eq(&event->mod.old, &event->mod.new);
+}
+
+static bool diag_mod_insn_origin(struct bpf_verifier_env *env, u32 insn_idx,
+				 const struct bpf_diag_mod_target *target,
+				 struct bpf_diag_mod_target *origin)
+{
+	const struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
+	u8 class = BPF_CLASS(insn->code);
+	u32 frameno;
+
+	if (target->kind == BPF_DIAG_MOD_TARGET_REG && (class == BPF_ALU || class == BPF_ALU64) &&
+	    BPF_OP(insn->code) == BPF_MOV && BPF_SRC(insn->code) == BPF_X) {
+		*origin = bpf_diag_reg_target(target->frameno, insn->src_reg);
+		return true;
+	}
+
+	if ((target->kind != BPF_DIAG_MOD_TARGET_STACK_ARG &&
+	     target->kind != BPF_DIAG_MOD_TARGET_STACK_SLOT) ||
+	    class != BPF_STX)
+		return false;
+

kernel/bpf/diagnostics.c void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const ch · line 896

Quoted 10 lines
kernel/bpf/diagnostics.c +10 -0
+	frameno = env->cur_state->frame[env->cur_state->curframe]->frameno;
+	*origin = bpf_diag_reg_target(frameno, insn->src_reg);
+	return true;
+}
+
+void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
+			 struct bpf_diag_mod_target target, enum bpf_diag_mod_reason reason,
+			 const struct bpf_reg_state *old_reg, const struct bpf_reg_state *new_reg,
+			 const struct bpf_diag_mod_target *origin)
+{

I need to reflect some more on the rest of the patch, it appears that this record_mod function should be integrated with existing mark_{reg,stack}_scratched calls:
- extended with some additional parameters, like frameno
- possibly reordered, such that at the callsite the old register state is saved and after do_check_insn() is complete the old and new states pair is fed into bpf_diag_record_mod().
But I need to think some more.

...

maintainer
#17 lore raw

Re: [PATCH bpf-next v3 05/17] bpf: Track verifier register diagnostic events

In reply to Kumar Kartikeya Dwivedi

On Mon, 2026-07-13 at 17:38 +0200, Kumar Kartikeya Dwivedi wrote:

...

Quoted 34 lines
kernel/bpf/diagnostics.c +33 -0
+void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
+			 struct bpf_diag_mod_target target, enum bpf_diag_mod_reason reason,
+			 const struct bpf_reg_state *old_reg, const struct bpf_reg_state *new_reg,
+			 const struct bpf_diag_mod_target *origin)
+{
+	struct bpf_diag_history_event event = {
+		.mod = {
+			.hdr = {
+				.insn_idx = insn_idx,
+				.kind = BPF_DIAG_HISTORY_MOD,
+			},
+			.target = target,
+			.reason = reason,
+		},
+	};
+
+	if (old_reg && new_reg) {
+		diag_snapshot_reg(&event.mod.old, old_reg);
+		diag_snapshot_reg(&event.mod.new, new_reg);
+		if ((reason == BPF_DIAG_MOD_WRITE || reason == BPF_DIAG_MOD_SPILL) &&
+		    diag_mod_snapshot_eq(&event))
+			return;
+	}
+	if (origin) {
+		event.mod.origin = *origin;
+		event.mod.origin_valid = true;
+	} else {
+		event.mod.origin_valid =
+			diag_mod_insn_origin(env, insn_idx, &target, &event.mod.origin);
+	}
+
+	diag_append_history(env, &event);
+}

...

Quoted 11 lines
kernel/bpf/verifier.c +3 -0
index 648adf3b7aaa..4a468299f05e 100644
@@ -1834,6 +1834,50 @@ static const int caller_saved[CALLER_SAVED_REGS] = {
 	BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5
 };
 
+static void bpf_diag_save_caller_saved_regs(struct bpf_verifier_env *env,
+					    struct bpf_reg_state *regs)
+{

...

Quoted 5 lines
kernel/bpf/verifier.c +5 -0
+}
+
+static void bpf_diag_record_caller_saved_invals(struct bpf_verifier_env *env, u32 insn_idx,
+						struct bpf_reg_state *regs)
+{

...

Quoted 5 lines
kernel/bpf/verifier.c +5 -0
+}
+
+static void bpf_diag_record_call_ret(struct bpf_verifier_env *env, u32 insn_idx,
+				     struct bpf_reg_state *regs)
+{

...

Quoted 12 lines
kernel/bpf/verifier.c +5 -0
+}
+
 /* This helper doesn't clear reg->id */
 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm)
 {
@@ -3448,6 +3492,22 @@ static void assign_scalar_id_before_mov(struct bpf_verifier_env *env,
 		src_reg->id = ++env->id_gen;
 }
 
+static int bpf_diag_stack_slot(const struct bpf_func_state *state,
+			       const struct bpf_stack_state *stack)
+{

...

Quoted 10 lines
kernel/bpf/verifier.c +3 -0
+}
+
 static void save_register_state(struct bpf_verifier_env *env,
 				struct bpf_func_state *state,
 				int spi, struct bpf_reg_state *reg,
@@ -3525,8 +3585,14 @@ static int check_stack_write_fixed_off(struct bpf_verifier_env *env,
 	int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err;
 	struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
 	struct bpf_reg_state *reg = NULL;
+	struct bpf_reg_state *old_spill;

kernel/bpf/verifier.c static int check_stack_write_fixed_off(struct bpf_verifier_env *env, · line 3598

Quoted 10 lines
kernel/bpf/verifier.c +5 -0
 	int insn_flags = INSN_F_STACK_ACCESS;
 	int hist_spi = spi, hist_frame = state->frameno;
+	bool old_was_spill = bpf_is_spilled_reg(&state->stack[spi]);
+
+	old_spill = bpf_diag_reg_scratch(env, 0);
+	if (old_spill)
+		*old_spill = state->stack[spi].spilled_ptr;
 
 	/* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0,
 	 * so it's aligned access and [off, off + size) are within stack limits

I think that changes in the verifier.c are too invasive and callsites for bpf_diag_record_mod() clutter the code too much. Please consider changes as in [1]:
- Expand the API to be used from verifier.c with begin()/end() primitives taking/using a snapshot of a register being modified.
- Derive target/origin descriptor from the register pointer.
- Avoid stashing caller saved registers in a scratch buffer, as these are set to NOT_INIT and the effect can be recorded right away.

[1] https://github.com/kernel-patches/bpf/commit/a89d27ea45c15a199f8e376535519306469a1f06

[...]

author maintainer
#18 lore raw

PATCH v3 6/17 bpf: Track verifier reference diagnostic events

In reply to Kumar Kartikeya Dwivedi

Add reference acquire and release events to diagnostic history so Resource Lifetime Safety reports can show the lifetime of a specific reference id along the path.

Record acquisitions after the verifier assigns the reference id. Record releases only after release_reference_nomark() succeeds, including the kptr_xchg RCU conversion path and owning-to-non-owning conversion path that consume an owning reference.

---
 kernel/bpf/diagnostics.c | 63 ++++++++++++++++++++++++++++++++++++++++
 kernel/bpf/diagnostics.h |  2 ++
 kernel/bpf/verifier.c    | 32 +++++++++++++++-----
 3 files changed, 90 insertions(+), 7 deletions(-)
kernel/bpf/diagnostics.c +63 -0
index 1a45ec926c71..4c1fbabf98d1 100644
@@ -50,6 +50,8 @@ struct bpf_diag_reg_snapshot {
 enum bpf_diag_history_kind {
 	BPF_DIAG_HISTORY_BRANCH,
 	BPF_DIAG_HISTORY_MOD,
+	BPF_DIAG_HISTORY_REF_ACQUIRE,
+	BPF_DIAG_HISTORY_REF_RELEASE,
 };
 
 struct bpf_diag_event_hdr {
@@ -75,6 +77,10 @@ struct bpf_diag_history_event {
 			u8 reason;
 			bool origin_valid;
 		} mod;
+		struct {
+			struct bpf_diag_event_hdr hdr;
+			u32 ref_id;
+		} ref;
 	};
 };
 
@@ -82,6 +88,7 @@ enum bpf_diag_history_scope {
 	BPF_DIAG_HISTORY_SCOPE_ALL,
 	BPF_DIAG_HISTORY_SCOPE_REG,
 	BPF_DIAG_HISTORY_SCOPE_STACK_ARG,
+	BPF_DIAG_HISTORY_SCOPE_REF,
 };
 
 struct bpf_diag_history_opts {
@@ -89,6 +96,7 @@ struct bpf_diag_history_opts {
 	u32 frameno;
 	int regno;
 	int stack_arg_slot;
+	u32 ref_id;
 };
 
 static void diag_print_history(struct bpf_verifier_env *env,
@@ -923,6 +931,31 @@ void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
 	diag_append_history(env, &event);
 }
 
+static void diag_record_ref(struct bpf_verifier_env *env, u32 insn_idx, u8 kind, u32 ref_id)
+{
+	struct bpf_diag_history_event event = {
+		.ref = {
+			.hdr = {
+				.insn_idx = insn_idx,
+				.kind = kind,
+			},
+			.ref_id = ref_id,
+		},
+	};
+
+	diag_append_history(env, &event);
+}
+
+void bpf_diag_record_ref_acquire(struct bpf_verifier_env *env, u32 insn_idx, u32 ref_id)
+{
+	diag_record_ref(env, insn_idx, BPF_DIAG_HISTORY_REF_ACQUIRE, ref_id);
+}
+
+void bpf_diag_record_ref_release(struct bpf_verifier_env *env, u32 insn_idx, u32 ref_id)
+{
+	diag_record_ref(env, insn_idx, BPF_DIAG_HISTORY_REF_RELEASE, ref_id);
+}
+
 struct bpf_diag_history_filter {
 	const struct bpf_diag_history_opts *opts;
 	unsigned long *lineage;
@@ -1074,11 +1107,23 @@ static int diag_history_start_idx(const struct bpf_diag_log *log,
 				  const struct bpf_diag_history_filter *filter)
 {
 	const struct bpf_diag_history_opts *opts = filter->opts;
+	int i;
 
 	if (!opts || opts->scope == BPF_DIAG_HISTORY_SCOPE_ALL)
 		return 0;
 	if (filter->lineage_valid)
 		return filter->lineage_start;
+	if (opts->scope != BPF_DIAG_HISTORY_SCOPE_REF)
+		return 0;
+
+	for (i = log->cnt; i > 0; i--) {
+		const struct bpf_diag_history_event *event;
+
+		event = diag_history_event(log, i - 1);
+		if (event->kind == BPF_DIAG_HISTORY_REF_ACQUIRE &&
+		    event->ref.ref_id == opts->ref_id)
+			return i - 1;
+	}
 
 	return 0;
 }
@@ -1096,6 +1141,10 @@ static bool diag_history_event_visible(const struct bpf_diag_history_event *even
 		return true;
 	case BPF_DIAG_HISTORY_MOD:
 		return filter->lineage_valid && test_bit(idx, filter->lineage);
+	case BPF_DIAG_HISTORY_REF_ACQUIRE:
+	case BPF_DIAG_HISTORY_REF_RELEASE:
+		return opts->scope == BPF_DIAG_HISTORY_SCOPE_REF &&
+		       event->ref.ref_id == opts->ref_id;
 	default:
 		return false;
 	}
@@ -1383,6 +1432,16 @@ static void diag_print_mod(struct bpf_verifier_env *env, const struct bpf_diag_h
 			       fmt->old_buf, fmt->new_buf);
 }
 
+static void diag_print_ref_event(struct bpf_verifier_env *env,
+				 const struct bpf_diag_history_event *event)
+{
+	const char *label;
+
+	label = event->kind == BPF_DIAG_HISTORY_REF_ACQUIRE ? "acquired" : "released";
+	bpf_diag_report_source(env, event->insn_idx, label, "owned resource (id=%u)",
+			       event->ref.ref_id);
+}
+
 static void diag_print_history(struct bpf_verifier_env *env,
 			       const struct bpf_diag_history_opts *opts)
 {
@@ -1442,6 +1501,10 @@ static void diag_print_history(struct bpf_verifier_env *env,
 		case BPF_DIAG_HISTORY_MOD:
 			diag_print_mod(env, event);
 			break;
+		case BPF_DIAG_HISTORY_REF_ACQUIRE:
+		case BPF_DIAG_HISTORY_REF_RELEASE:
+			diag_print_ref_event(env, event);
+			break;
 		default:
 			break;
 		}
kernel/bpf/diagnostics.h +2 -0
index 440142b09e7a..13b6f5c8f8da 100644
@@ -106,5 +106,7 @@ void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
 			 struct bpf_diag_mod_target target, enum bpf_diag_mod_reason reason,
 			 const struct bpf_reg_state *old_reg, const struct bpf_reg_state *new_reg,
 			 const struct bpf_diag_mod_target *origin);
+void bpf_diag_record_ref_acquire(struct bpf_verifier_env *env, u32 insn_idx, u32 ref_id);
+void bpf_diag_record_ref_release(struct bpf_verifier_env *env, u32 insn_idx, u32 ref_id);
 
 #endif /* __BPF_DIAGNOSTICS_H */
kernel/bpf/verifier.c +25 -7
index 4a468299f05e..24bbeee3396e 100644
@@ -208,7 +208,8 @@ struct bpf_verifier_stack_elem {
 #define BPF_PRIV_STACK_MIN_SIZE		64
 
 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id);
-static int release_reference_nomark(struct bpf_verifier_state *state, int id);
+static int __release_reference_nomark(struct bpf_verifier_state *state, int id);
+static int release_reference_nomark(struct bpf_verifier_env *env, int id);
 static int release_reference(struct bpf_verifier_env *env, int id);
 static void invalidate_non_owning_refs(struct bpf_verifier_env *env);
 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env);
@@ -1442,6 +1443,7 @@ static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int par
 	s->type = REF_TYPE_PTR;
 	s->id = ++env->id_gen;
 	s->parent_id = parent_id;
+	bpf_diag_record_ref_acquire(env, insn_idx, s->id);
 	return s->id;
 }
 
@@ -9232,7 +9234,7 @@ static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range
 		reg->range = AT_PKT_END;
 }
 
-static int release_reference_nomark(struct bpf_verifier_state *state, int id)
+static int __release_reference_nomark(struct bpf_verifier_state *state, int id)
 {
 	int i;
 
@@ -9247,6 +9249,16 @@ static int release_reference_nomark(struct bpf_verifier_state *state, int id)
 	return -EINVAL;
 }
 
+static int release_reference_nomark(struct bpf_verifier_env *env, int id)
+{
+	int err;
+
+	err = __release_reference_nomark(env->cur_state, id);
+	if (!err)
+		bpf_diag_record_ref_release(env, env->insn_idx, id);
+	return err;
+}
+
 static int idstack_push(struct bpf_idmap *idmap, u32 id)
 {
 	int i;
@@ -9289,8 +9301,10 @@ static int release_reference(struct bpf_verifier_env *env, int id)
 	if (err)
 		return err;
 
-	if (find_reference_state(vstate, id))
-		WARN_ON_ONCE(release_reference_nomark(vstate, id));
+	if (find_reference_state(vstate, id)) {
+		err = release_reference_nomark(env, id);
+		WARN_ON_ONCE(err);
+	}
 
 	while ((id = idstack_pop(idstack))) {
 		/*
@@ -9423,7 +9437,9 @@ static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id)
 	struct bpf_reg_state *reg;
 	int err;
 
-	err = release_reference_nomark(env->cur_state, id);
+	err = release_reference_nomark(env, id);
+	if (err)
+		return err;
 
 	bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({
 		if (reg->id != id)
@@ -11906,8 +11922,10 @@ static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id)
 {
 	struct bpf_func_state *unused;
 	struct bpf_reg_state *reg;
+	int err;
 
-	WARN_ON_ONCE(release_reference_nomark(env->cur_state, id));
+	err = release_reference_nomark(env, id);
+	WARN_ON_ONCE(err);
 
 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
 		if (reg->id == id) {
@@ -16135,7 +16153,7 @@ static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
 		 * No one could have freed the reference state before
 		 * doing the NULL check.
 		 */
-		WARN_ON_ONCE(release_reference_nomark(vstate, id));
+		WARN_ON_ONCE(__release_reference_nomark(vstate, id));
 
 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
 		mark_ptr_or_null_reg(state, reg, id, is_null);
Signature · 1 line
2.53.0
author maintainer
#19 lore raw

PATCH v3 7/17 bpf: Track verifier context diagnostic events

In reply to Kumar Kartikeya Dwivedi

Record verifier context transitions in the diagnostic history so later reports can anchor causal paths to the critical section that made an operation invalid.

This covers lock, IRQ, RCU, and preempt regions without adding any new verifier error reports. Category-specific commits decide where those recorded events should be rendered.

Use context depth when selecting scoped history so nested regions anchor at the outer active region, and fall back to the earliest retained event when the matching entry was pruned.

---
 kernel/bpf/diagnostics.c | 106 ++++++++++++++++++++++++++++++++++++++-
 kernel/bpf/diagnostics.h |  18 +++++++
 kernel/bpf/verifier.c    |  31 +++++++++---
 3 files changed, 148 insertions(+), 7 deletions(-)
kernel/bpf/diagnostics.c +105 -1
index 4c1fbabf98d1..bd06974efd7b 100644
@@ -52,6 +52,7 @@ enum bpf_diag_history_kind {
 	BPF_DIAG_HISTORY_MOD,
 	BPF_DIAG_HISTORY_REF_ACQUIRE,
 	BPF_DIAG_HISTORY_REF_RELEASE,
+	BPF_DIAG_HISTORY_CONTEXT,
 };
 
 struct bpf_diag_event_hdr {
@@ -81,6 +82,12 @@ struct bpf_diag_history_event {
 			struct bpf_diag_event_hdr hdr;
 			u32 ref_id;
 		} ref;
+		struct {
+			struct bpf_diag_event_hdr hdr;
+			u32 depth;
+			u8 kind;
+			bool enter;
+		} ctx;
 	};
 };
 
@@ -89,6 +96,7 @@ enum bpf_diag_history_scope {
 	BPF_DIAG_HISTORY_SCOPE_REG,
 	BPF_DIAG_HISTORY_SCOPE_STACK_ARG,
 	BPF_DIAG_HISTORY_SCOPE_REF,
+	BPF_DIAG_HISTORY_SCOPE_CONTEXT,
 };
 
 struct bpf_diag_history_opts {
@@ -97,6 +105,8 @@ struct bpf_diag_history_opts {
 	int regno;
 	int stack_arg_slot;
 	u32 ref_id;
+	enum bpf_diag_context_kind ctx_kind;
+	u32 ctx_depth;
 };
 
 static void diag_print_history(struct bpf_verifier_env *env,
@@ -288,6 +298,19 @@ void bpf_diag_event_log_reset(struct bpf_verifier_env *env, u32 pos)
 	log->cnt = pos;
 }
 
+u32 bpf_diag_irq_depth(const struct bpf_verifier_state *state)
+{
+	u32 depth = 0;
+	int i;
+
+	for (i = 0; i < state->acquired_refs; i++) {
+		if (state->refs[i].type == REF_TYPE_IRQ)
+			depth++;
+	}
+
+	return depth;
+}
+
 void bpf_diag_free(struct bpf_verifier_env *env)
 {
 	struct bpf_diag *diag = env->diag;
@@ -956,6 +979,54 @@ void bpf_diag_record_ref_release(struct bpf_verifier_env *env, u32 insn_idx, u32
 	diag_record_ref(env, insn_idx, BPF_DIAG_HISTORY_REF_RELEASE, ref_id);
 }
 
+void bpf_diag_record_context(struct bpf_verifier_env *env, u32 insn_idx,
+			     enum bpf_diag_context_event_kind ctx_kind, bool enter, u32 depth)
+{
+	/*
+	 * Keep leave events so context rendering can stop at a depth-zero exit
+	 * and show nested-region depth accurately for the active path.
+	 */
+	struct bpf_diag_history_event event = {
+		.ctx = {
+			.hdr = {
+				.insn_idx = insn_idx,
+				.kind = BPF_DIAG_HISTORY_CONTEXT,
+			},
+			.kind = ctx_kind,
+			.enter = enter,
+			.depth = depth,
+		},
+	};
+
+	diag_append_history(env, &event);
+}
+
+static int diag_history_context_start_idx(const struct bpf_diag_log *log,
+					  const struct bpf_diag_history_opts *opts)
+{
+	int i;
+
+	if (!opts->ctx_depth)
+		return 0;
+
+	/* Find the most recent outermost entry, or a depth-zero exit. */
+	for (i = log->cnt; i > 0; i--) {
+		const struct bpf_diag_history_event *event;
+
+		event = diag_history_event(log, i - 1);
+
+		if (event->kind != BPF_DIAG_HISTORY_CONTEXT || event->ctx.kind != opts->ctx_kind)
+			continue;
+
+		if (event->ctx.enter && event->ctx.depth == 1)
+			return i - 1;
+		if (!event->ctx.enter && event->ctx.depth == 0)
+			return 0;
+	}
+
+	return 0;
+}
+
 struct bpf_diag_history_filter {
 	const struct bpf_diag_history_opts *opts;
 	unsigned long *lineage;
@@ -1111,6 +1182,8 @@ static int diag_history_start_idx(const struct bpf_diag_log *log,
 
 	if (!opts || opts->scope == BPF_DIAG_HISTORY_SCOPE_ALL)
 		return 0;
+	if (opts->scope == BPF_DIAG_HISTORY_SCOPE_CONTEXT)
+		return diag_history_context_start_idx(log, opts);
 	if (filter->lineage_valid)
 		return filter->lineage_start;
 	if (opts->scope != BPF_DIAG_HISTORY_SCOPE_REF)
@@ -1134,7 +1207,7 @@ static bool diag_history_event_visible(const struct bpf_diag_history_event *even
 	const struct bpf_diag_history_opts *opts = filter->opts;
 
 	if (!opts || opts->scope == BPF_DIAG_HISTORY_SCOPE_ALL)
-		return true;
+		return event->kind != BPF_DIAG_HISTORY_CONTEXT;
 
 	switch (event->kind) {
 	case BPF_DIAG_HISTORY_BRANCH:
@@ -1145,6 +1218,9 @@ static bool diag_history_event_visible(const struct bpf_diag_history_event *even
 	case BPF_DIAG_HISTORY_REF_RELEASE:
 		return opts->scope == BPF_DIAG_HISTORY_SCOPE_REF &&
 		       event->ref.ref_id == opts->ref_id;
+	case BPF_DIAG_HISTORY_CONTEXT:
+		return opts->scope == BPF_DIAG_HISTORY_SCOPE_CONTEXT &&
+		       event->ctx.kind == opts->ctx_kind;
 	default:
 		return false;
 	}
@@ -1442,6 +1518,31 @@ static void diag_print_ref_event(struct bpf_verifier_env *env,
 			       event->ref.ref_id);
 }
 
+static const char *diag_context_name(enum bpf_diag_context_kind kind)
+{
+	switch (kind) {
+	case BPF_DIAG_CONTEXT_RCU:
+		return "RCU read lock region";
+	case BPF_DIAG_CONTEXT_PREEMPT:
+		return "non-preemptible region";
+	case BPF_DIAG_CONTEXT_IRQ:
+		return "IRQ-disabled region";
+	case BPF_DIAG_CONTEXT_LOCK:
+		return "lock region";
+	case BPF_DIAG_CONTEXT_NONE:
+	default:
+		return "context";
+	}
+}
+
+static void diag_print_context_event(struct bpf_verifier_env *env,
+				     const struct bpf_diag_history_event *event)
+{
+	bpf_diag_report_source(env, event->insn_idx, "context", "%s %s; depth is now %u",
+			       event->ctx.enter ? "entered" : "left",
+			       diag_context_name(event->ctx.kind), event->ctx.depth);
+}
+
 static void diag_print_history(struct bpf_verifier_env *env,
 			       const struct bpf_diag_history_opts *opts)
 {
@@ -1505,6 +1606,9 @@ static void diag_print_history(struct bpf_verifier_env *env,
 		case BPF_DIAG_HISTORY_REF_RELEASE:
 			diag_print_ref_event(env, event);
 			break;
+		case BPF_DIAG_HISTORY_CONTEXT:
+			diag_print_context_event(env, event);
+			break;
 		default:
 			break;
 		}
kernel/bpf/diagnostics.h +18 -0
index 13b6f5c8f8da..931d880b7eda 100644
@@ -9,6 +9,7 @@
 
 struct bpf_reg_state;
 struct bpf_verifier_env;
+struct bpf_verifier_state;
 struct btf;
 
 void bpf_diag_format_btf_type(char *buf, size_t size, const struct btf *btf, u32 type_id);
@@ -83,6 +84,20 @@ static inline struct bpf_diag_mod_target bpf_diag_stack_range_target(u32 frameno
 	};
 }
 
+enum bpf_diag_context_kind {
+	BPF_DIAG_CONTEXT_NONE,
+	BPF_DIAG_CONTEXT_RCU,
+	BPF_DIAG_CONTEXT_PREEMPT,
+	BPF_DIAG_CONTEXT_IRQ,
+	BPF_DIAG_CONTEXT_LOCK,
+};
+
+enum bpf_diag_context_event_kind {
+	BPF_DIAG_CONTEXT_EVENT_RCU = BPF_DIAG_CONTEXT_RCU,
+	BPF_DIAG_CONTEXT_EVENT_PREEMPT = BPF_DIAG_CONTEXT_PREEMPT,
+	BPF_DIAG_CONTEXT_EVENT_IRQ = BPF_DIAG_CONTEXT_IRQ,
+	BPF_DIAG_CONTEXT_EVENT_LOCK = BPF_DIAG_CONTEXT_LOCK,
+};
 bool bpf_diag_enabled(const struct bpf_verifier_env *env);
 int bpf_diag_init(struct bpf_verifier_env *env);
 char *bpf_diag_scratch_buf(struct bpf_verifier_env *env, unsigned int slot, size_t *size);
@@ -96,6 +111,7 @@ const char *bpf_diag_format_btf_type_scratch(struct bpf_verifier_env *env, unsig
 u32 bpf_diag_event_log_pos(struct bpf_verifier_env *env);
 void bpf_diag_event_log_reset(struct bpf_verifier_env *env, u32 pos);
 int bpf_diag_error(const struct bpf_verifier_env *env);
+u32 bpf_diag_irq_depth(const struct bpf_verifier_state *state);
 void bpf_diag_free(struct bpf_verifier_env *env);
 void bpf_diag_report_header(struct bpf_verifier_env *env, const char *category,
 			    const char *problem);
@@ -108,5 +124,7 @@ void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
 			 const struct bpf_diag_mod_target *origin);
 void bpf_diag_record_ref_acquire(struct bpf_verifier_env *env, u32 insn_idx, u32 ref_id);
 void bpf_diag_record_ref_release(struct bpf_verifier_env *env, u32 insn_idx, u32 ref_id);
+void bpf_diag_record_context(struct bpf_verifier_env *env, u32 insn_idx,
+			     enum bpf_diag_context_event_kind ctx_kind, bool enter, u32 depth);
 
 #endif /* __BPF_DIAGNOSTICS_H */
kernel/bpf/verifier.c +25 -6
index 24bbeee3396e..4cc4f1cc01c0 100644
@@ -1069,7 +1069,7 @@ static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_s
 }
 
 static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx);
-static int release_irq_state(struct bpf_verifier_state *state, int id);
+static int release_irq_state(struct bpf_verifier_env *env, int id);
 
 static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
 				     struct bpf_kfunc_call_arg_meta *meta,
@@ -1128,7 +1128,7 @@ static int unmark_stack_slot_irq_flag(struct bpf_verifier_env *env, struct bpf_r
 		return -EINVAL;
 	}
 
-	err = release_irq_state(env->cur_state, st->id);
+	err = release_irq_state(env, st->id);
 	WARN_ON_ONCE(err && err != -EACCES);
 	if (err) {
 		int insn_idx = 0;
@@ -1463,6 +1463,8 @@ static int acquire_lock_state(struct bpf_verifier_env *env, int insn_idx, enum r
 	state->active_locks++;
 	state->active_lock_id = id;
 	state->active_lock_ptr = ptr;
+	bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_EVENT_LOCK, true,
+				state->active_locks);
 	return 0;
 }
 
@@ -1478,6 +1480,8 @@ static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
 	s->id = ++env->id_gen;
 
 	state->active_irq_id = s->id;
+	bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_EVENT_IRQ, true,
+				bpf_diag_irq_depth(state));
 	return s->id;
 }
 
@@ -1519,8 +1523,9 @@ static bool reg_is_referenced(struct bpf_verifier_env *env, const struct bpf_reg
 	return find_reference_state(env->cur_state, reg->id);
 }
 
-static int release_lock_state(struct bpf_verifier_state *state, int type, int id, void *ptr)
+static int release_lock_state(struct bpf_verifier_env *env, int type, int id, void *ptr)
 {
+	struct bpf_verifier_state *state = env->cur_state;
 	void *prev_ptr = NULL;
 	u32 prev_id = 0;
 	int i;
@@ -1533,6 +1538,8 @@ static int release_lock_state(struct bpf_verifier_state *state, int type, int id
 			/* Reassign active lock (id, ptr). */
 			state->active_lock_id = prev_id;
 			state->active_lock_ptr = prev_ptr;
+			bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_EVENT_LOCK,
+						false, state->active_locks);
 			return 0;
 		}
 		if (state->refs[i].type & REF_TYPE_LOCK_MASK) {
@@ -1543,8 +1550,9 @@ static int release_lock_state(struct bpf_verifier_state *state, int type, int id
 	return -EINVAL;
 }
 
-static int release_irq_state(struct bpf_verifier_state *state, int id)
+static int release_irq_state(struct bpf_verifier_env *env, int id)
 {
+	struct bpf_verifier_state *state = env->cur_state;
 	u32 prev_id = 0;
 	int i;
 
@@ -1557,6 +1565,8 @@ static int release_irq_state(struct bpf_verifier_state *state, int id)
 		if (state->refs[i].id == id) {
 			release_reference_state(state, i);
 			state->active_irq_id = prev_id;
+			bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_EVENT_IRQ,
+						false, bpf_diag_irq_depth(state));
 			return 0;
 		} else {
 			prev_id = state->refs[i].id;
@@ -7345,7 +7355,7 @@ static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state
 			verbose(env, "%s_unlock cannot be out of order\n", lock_str);
 			return -EINVAL;
 		}
-		if (release_lock_state(cur, type, reg->id, ptr)) {
+		if (release_lock_state(env, type, reg->id, ptr)) {
 			verbose(env, "%s_unlock of different lock\n", lock_str);
 			return -EINVAL;
 		}
@@ -13466,21 +13476,30 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 
 	if (rcu_lock) {
 		env->cur_state->active_rcu_locks++;
+		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_EVENT_RCU, true,
+					env->cur_state->active_rcu_locks);
 	} else if (rcu_unlock) {
 		if (env->cur_state->active_rcu_locks == 0) {
 			verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name);
 			return -EINVAL;
 		}
-		if (--env->cur_state->active_rcu_locks == 0)
+		env->cur_state->active_rcu_locks--;
+		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_EVENT_RCU, false,
+					env->cur_state->active_rcu_locks);
+		if (env->cur_state->active_rcu_locks == 0)
 			invalidate_rcu_protected_refs(env);
 	} else if (preempt_disable) {
 		env->cur_state->active_preempt_locks++;
+		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_EVENT_PREEMPT, true,
+					env->cur_state->active_preempt_locks);
 	} else if (preempt_enable) {
 		if (env->cur_state->active_preempt_locks == 0) {
 			verbose(env, "unmatched attempt to enable preemption (kernel function %s)\n", func_name);
 			return -EINVAL;
 		}
 		env->cur_state->active_preempt_locks--;
+		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_EVENT_PREEMPT, false,
+					env->cur_state->active_preempt_locks);
 	}
 
 	if (sleepable && !in_sleepable_context(env)) {
Signature · 1 line
2.53.0
author maintainer
#20 lore raw

PATCH v3 8/17 bpf: Report Register Type Safety errors

In reply to Kumar Kartikeya Dwivedi

Augment selected register-state verifier failures with Register Type Safety reports. The existing verbose verifier messages remain in place; the new reports add reason, source context, causal path, and suggestions.

Cover invalid pointer dereferences, unreadable registers, missing outgoing stack arguments for bpf2bpf and kfunc calls, and rejected pointer arithmetic. Use scoped diagnostic history so reports start from the latest relevant value change and then show later branch outcomes.

---
 kernel/bpf/diagnostics.c | 249 +++++++++++++++++++++++++++++++++++++++
 kernel/bpf/diagnostics.h |  19 +++
 kernel/bpf/verifier.c    | 160 ++++++++++++++++++++++---
 3 files changed, 412 insertions(+), 16 deletions(-)
kernel/bpf/diagnostics.c +249 -0
index bd06974efd7b..0fa61882ee69 100644
@@ -853,6 +853,255 @@ void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const ch
 	kfree(msg);
 }
 
+static u32 diag_current_frameno(const struct bpf_verifier_env *env)
+{
+	return env->cur_state->frame[env->cur_state->curframe]->frameno;
+}
+
+void bpf_diag_report_register_type(struct bpf_verifier_env *env, u32 insn_idx, int regno,
+				   const char *problem, const char *reason, const char *suggestion)
+{
+	struct bpf_diag_history_opts opts = {
+		.scope = BPF_DIAG_HISTORY_SCOPE_REG,
+		.frameno = diag_current_frameno(env),
+		.regno = regno,
+	};
+
+	bpf_diag_report_header(env, CATEGORY_REGISTER_TYPE_SAFETY, problem);
+	diag_report_reason(env, "%s", reason);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "%s", problem);
+
+	if (regno >= 0)
+		diag_print_history(env, &opts);
+
+	diag_report_suggestion(env, "%s", suggestion);
+}
+
+const char *bpf_diag_reg_type_plain(struct bpf_verifier_env *env, enum bpf_reg_type type)
+{
+	switch (base_type(type)) {
+	case NOT_INIT:
+		return "an uninitialized value";
+	case SCALAR_VALUE:
+		return "an integer scalar";
+	case PTR_TO_CTX:
+		return "a context pointer";
+	case PTR_TO_STACK:
+		return "a stack pointer";
+	case PTR_TO_MAP_VALUE:
+		if (type_may_be_null(type))
+			return "a nullable map value pointer";
+		return "a map value pointer";
+	case PTR_TO_MEM:
+		if (type_may_be_null(type))
+			return "a nullable memory pointer";
+		return "a memory pointer";
+	case PTR_TO_BTF_ID:
+		if (type_may_be_null(type))
+			return "a nullable kernel object pointer";
+		if (type_is_non_owning_ref(type))
+			return "a borrowed allocated object pointer";
+		if (type_is_ptr_alloc_obj(type))
+			return "an owned allocated object pointer";
+		if (type_flag(type) & PTR_UNTRUSTED)
+			return "an untrusted kernel object pointer";
+		return "a kernel object pointer";
+	default:
+		return reg_type_str(env, type);
+	}
+}
+
+static const char *diag_arg_ordinal(int argno)
+{
+	switch (argno) {
+	case 1:
+		return "first";
+	case 2:
+		return "second";
+	case 3:
+		return "third";
+	case 4:
+		return "fourth";
+	case 5:
+		return "fifth";
+	case 6:
+		return "sixth";
+	case 7:
+		return "seventh";
+	case 8:
+		return "eighth";
+	case 9:
+		return "ninth";
+	case 10:
+		return "tenth";
+	case 11:
+		return "eleventh";
+	case 12:
+		return "twelfth";
+	default:
+		return NULL;
+	}
+}
+
+void bpf_diag_report_invalid_deref(struct bpf_verifier_env *env, u32 insn_idx, int regno,
+				   const char *reg_name, const struct bpf_reg_state *reg,
+				   enum bpf_diag_invalid_deref_kind kind, s64 offset)
+{
+	struct bpf_diag_history_opts opts = {
+		.scope = BPF_DIAG_HISTORY_SCOPE_REG,
+		.frameno = diag_current_frameno(env),
+		.regno = regno,
+	};
+	const char *type_name = bpf_diag_reg_type_plain(env, reg->type);
+
+	bpf_diag_report_header(env, CATEGORY_REGISTER_TYPE_SAFETY, "invalid dereference");
+
+	switch (kind) {
+	case BPF_DIAG_DEREF_SCALAR:
+		diag_report_reason(env, "%s is an integer scalar here, not a pointer to memory.",
+				   reg_name);
+		break;
+	case BPF_DIAG_DEREF_NULLABLE_PTR:
+		diag_report_reason(env,
+				   "%s may be NULL here (%s). The program could dereference NULL "
+				   "on this path, so the verifier cannot prove this access is "
+				   "safe.",
+				   reg_name, type_name);
+		break;
+	case BPF_DIAG_DEREF_MODIFIED_PTR:
+		diag_report_reason(env,
+				   "%s has offset %lld here, but this pointer type must be "
+				   "dereferenced in its original form.",
+				   reg_name, offset);
+		break;
+	case BPF_DIAG_DEREF_INVALID_PTR:
+	default:
+		diag_report_reason(env,
+				   "%s has type %s here, which is not valid for this memory "
+				   "access.",
+				   reg_name, type_name);
+		break;
+	}
+
+	diag_report_section(env, "At");
+	if (kind == BPF_DIAG_DEREF_MODIFIED_PTR)
+		bpf_diag_report_source(env, insn_idx, "error",
+				       "dereference requires the original %s pointer", type_name);
+	else
+		bpf_diag_report_source(env, insn_idx, "error", "invalid dereference of %s (%s)",
+				       reg_name, type_name);
+
+	if (regno >= 0)
+		diag_print_history(env, &opts);
+
+	switch (kind) {
+	case BPF_DIAG_DEREF_NULLABLE_PTR:
+		diag_report_suggestion(env, "Add a NULL check before the access and dereference "
+					    "the pointer only on the non-NULL path.");
+		break;
+	case BPF_DIAG_DEREF_MODIFIED_PTR:
+		diag_report_suggestion(env, "Preserve the original pointer in another register, or "
+					    "use only offsets this pointer type permits before "
+					    "dereferencing it.");
+		break;
+	case BPF_DIAG_DEREF_SCALAR:
+	case BPF_DIAG_DEREF_INVALID_PTR:
+	default:
+		diag_report_suggestion(env, "Preserve a pointer-valued register where needed, or "
+					    "reload and revalidate the pointer after scalar "
+					    "arithmetic, helper calls, or other operations that "
+					    "can invalidate it.");
+		break;
+	}
+}
+
+void bpf_diag_report_unreadable_reg(struct bpf_verifier_env *env, u32 insn_idx, int regno)
+{
+	struct bpf_diag_history_opts opts = {
+		.scope = BPF_DIAG_HISTORY_SCOPE_REG,
+		.frameno = diag_current_frameno(env),
+		.regno = regno,
+	};
+
+	bpf_diag_report_header(env, CATEGORY_REGISTER_TYPE_SAFETY, "unreadable register");
+	diag_report_reason(env,
+			   "R%d is not readable here. A previous operation may have invalidated "
+			   "this register, so the verifier cannot use it as an input.",
+			   regno);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "R%d is not readable", regno);
+
+	if (regno >= 0)
+		diag_print_history(env, &opts);
+
+	diag_report_suggestion(env, "Avoid using the register after it is invalidated, or reload "
+				    "and revalidate a fresh pointer before this instruction.");
+}
+
+static int diag_stack_argno(u8 slot)
+{
+	return MAX_BPF_FUNC_REG_ARGS + slot + 1;
+}
+
+static void diag_format_stack_arg(char *buf, size_t size, u8 slot, const char *arg_name)
+{
+	int argno = diag_stack_argno(slot);
+	const char *ordinal = diag_arg_ordinal(argno);
+
+	if (ordinal && arg_name)
+		scnprintf(buf, size, "outgoing stack argument %u (%s argument, %s)", slot + 1,
+			  ordinal, arg_name);
+	else if (ordinal)
+		scnprintf(buf, size, "outgoing stack argument %u (%s argument)", slot + 1, ordinal);
+	else if (arg_name)
+		scnprintf(buf, size, "outgoing stack argument %u (%s)", slot + 1, arg_name);
+	else
+		scnprintf(buf, size, "outgoing stack argument %u", slot + 1);
+}
+
+void bpf_diag_report_stack_arg_uninit(struct bpf_verifier_env *env, u32 insn_idx, int nargs,
+				      int stack_arg_slot, const char *callee_name,
+				      const char *arg_name)
+{
+	struct bpf_diag_history_opts opts = {
+		.scope = BPF_DIAG_HISTORY_SCOPE_STACK_ARG,
+		.frameno = diag_current_frameno(env),
+		.stack_arg_slot = stack_arg_slot,
+	};
+	const char *arg_buf;
+
+	arg_buf = bpf_diag_scratch_buf(env, 1, NULL);
+	if (arg_buf)
+		diag_format_stack_arg((char *)arg_buf, BPF_DIAG_SCRATCH_STR_LEN, stack_arg_slot,
+				      arg_name);
+	else
+		arg_buf = "";
+	bpf_diag_report_header(env, CATEGORY_REGISTER_TYPE_SAFETY, "missing stack argument");
+	if (callee_name && *callee_name)
+		diag_report_reason(env,
+				   "Function %s expects %d arguments, but %s is not initialized at "
+				   "this call.",
+				   callee_name, nargs, arg_buf);
+	else
+		diag_report_reason(env,
+				   "The callee expects %d arguments, but %s is not initialized at "
+				   "this call.",
+				   nargs, arg_buf);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "%s is not initialized", arg_buf);
+
+	if (stack_arg_slot >= 0)
+		diag_print_history(env, &opts);
+
+	diag_report_suggestion(env, "Write the outgoing stack argument after any operation that "
+				    "may invalidate stored pointer values, and before making this "
+				    "call.");
+}
+
 int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true)
 {
 	struct bpf_diag_history_event event = {
kernel/bpf/diagnostics.h +19 -0
index 931d880b7eda..28bc234cfe56 100644
@@ -4,6 +4,7 @@
 #ifndef __BPF_DIAGNOSTICS_H
 #define __BPF_DIAGNOSTICS_H
 
+#include <linux/bpf.h>
 #include <linux/compiler_attributes.h>
 #include <linux/types.h>
 
@@ -98,6 +99,14 @@ enum bpf_diag_context_event_kind {
 	BPF_DIAG_CONTEXT_EVENT_IRQ = BPF_DIAG_CONTEXT_IRQ,
 	BPF_DIAG_CONTEXT_EVENT_LOCK = BPF_DIAG_CONTEXT_LOCK,
 };
+
+enum bpf_diag_invalid_deref_kind {
+	BPF_DIAG_DEREF_SCALAR,
+	BPF_DIAG_DEREF_NULLABLE_PTR,
+	BPF_DIAG_DEREF_MODIFIED_PTR,
+	BPF_DIAG_DEREF_INVALID_PTR,
+};
+
 bool bpf_diag_enabled(const struct bpf_verifier_env *env);
 int bpf_diag_init(struct bpf_verifier_env *env);
 char *bpf_diag_scratch_buf(struct bpf_verifier_env *env, unsigned int slot, size_t *size);
@@ -108,6 +117,7 @@ const char *bpf_diag_scratch_printf(struct bpf_verifier_env *env, unsigned int s
 				    const char *fmt, ...) __printf(3, 4);
 const char *bpf_diag_format_btf_type_scratch(struct bpf_verifier_env *env, unsigned int slot,
 					     const struct btf *btf, u32 type_id);
+const char *bpf_diag_reg_type_plain(struct bpf_verifier_env *env, enum bpf_reg_type type);
 u32 bpf_diag_event_log_pos(struct bpf_verifier_env *env);
 void bpf_diag_event_log_reset(struct bpf_verifier_env *env, u32 pos);
 int bpf_diag_error(const struct bpf_verifier_env *env);
@@ -117,6 +127,15 @@ void bpf_diag_report_header(struct bpf_verifier_env *env, const char *category,
 			    const char *problem);
 void bpf_diag_report_source(struct bpf_verifier_env *env, u32 insn_idx, const char *label,
 			    const char *fmt, ...) __printf(4, 5);
+void bpf_diag_report_register_type(struct bpf_verifier_env *env, u32 insn_idx, int regno,
+				   const char *problem, const char *reason, const char *suggestion);
+void bpf_diag_report_invalid_deref(struct bpf_verifier_env *env, u32 insn_idx, int regno,
+				   const char *reg_name, const struct bpf_reg_state *reg,
+				   enum bpf_diag_invalid_deref_kind kind, s64 offset);
+void bpf_diag_report_unreadable_reg(struct bpf_verifier_env *env, u32 insn_idx, int regno);
+void bpf_diag_report_stack_arg_uninit(struct bpf_verifier_env *env, u32 insn_idx, int nargs,
+				      int stack_arg_slot, const char *callee_name,
+				      const char *arg_name);
 int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true);
 void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
 			 struct bpf_diag_mod_target target, enum bpf_diag_mod_reason reason,
kernel/bpf/verifier.c +144 -16

306 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#21 lore raw

PATCH v3 9/17 bpf: Report Memory Safety bounds errors

In reply to Kumar Kartikeya Dwivedi

Augment selected memory-range verifier failures with Memory Safety reports while preserving the existing terse verifier messages for compatibility.

Cover stack spill corruption, uninitialized stack reads, variable stack helper accesses, and check_mem_region_access() range-proof failures. The bounds report spells out the required offset + access_size <= object_size proof with concrete values and uses scoped diagnostic history for causal context.

---
 kernel/bpf/diagnostics.c | 100 ++++++++++++++++++++++++++++++++++++++
 kernel/bpf/diagnostics.h |   6 +++
 kernel/bpf/verifier.c    | 102 +++++++++++++++++++++++++++++++++++----
 3 files changed, 199 insertions(+), 9 deletions(-)
kernel/bpf/diagnostics.c +100 -0
index 0fa61882ee69..d4588b19aac9 100644
@@ -7,6 +7,7 @@
 #include <linux/btf.h>
 #include <linux/ctype.h>
 #include <linux/kernel.h>
+#include <linux/overflow.h>
 #include <linux/slab.h>
 #include <linux/stdarg.h>
 #include <linux/string.h>
@@ -1102,6 +1103,18 @@ void bpf_diag_report_stack_arg_uninit(struct bpf_verifier_env *env, u32 insn_idx
 				    "call.");
 }
 
+void bpf_diag_report_memory(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
+			    const char *reason, const char *suggestion)
+{
+	bpf_diag_report_header(env, CATEGORY_MEMORY_SAFETY, problem);
+	diag_report_reason(env, "%s", reason);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "%s", problem);
+
+	diag_report_suggestion(env, "%s", suggestion);
+}
+
 int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true)
 {
 	struct bpf_diag_history_event event = {
@@ -1544,6 +1557,93 @@ static void diag_format_scalar_range(struct bpf_diag_reg_fmt *fmt, char *buf, si
 		  fmt->smax_buf, fmt->umin_buf, fmt->umax_buf);
 }
 
+void bpf_diag_format_s64_sum(char *buf, size_t size, s64 value, int addend)
+{
+	s64 sum;
+
+	if (check_add_overflow(value, (s64)addend, &sum)) {
+		if (addend < 0)
+			scnprintf(buf, size, "%lld plus %d (below S64_MIN)", value, addend);
+		else
+			scnprintf(buf, size, "%lld plus %d (above S64_MAX)", value, addend);
+		return;
+	}
+
+	scnprintf(buf, size, "%lld", sum);
+}
+
+static void diag_format_access_offset(struct bpf_verifier_env *env, char *buf, size_t size, int off,
+				      const struct bpf_reg_state *reg)
+{
+	struct bpf_diag_scratch *scratch = diag_scratch(env);
+	struct bpf_diag_reg_fmt *fmt;
+	char *start;
+
+	if (tnum_is_const(reg->var_off)) {
+		start = bpf_diag_scratch_buf(env, 2, NULL);
+		if (!start) {
+			scnprintf(buf, size, "constant");
+			return;
+		}
+		bpf_diag_format_s64_sum(start, BPF_DIAG_SCRATCH_STR_LEN, (s64)reg->var_off.value,
+					off);
+		scnprintf(buf, size, "constant %s", start);
+		return;
+	}
+
+	if (tnum_is_unknown(reg->var_off) && diag_cnum64_unknown(reg->r64)) {
+		scnprintf(buf, size, "unbounded");
+		return;
+	}
+
+	fmt = &scratch->reg_fmt;
+	memset(fmt, 0, sizeof(*fmt));
+
+	diag_format_scalar_range(fmt, fmt->range, sizeof(fmt->range), reg->r64);
+	if (off)
+		scnprintf(buf, size,
+			  "variable: known bits %#llx, unknown mask %#llx, plus fixed offset %d; "
+			  "%s",
+			  (u64)reg->var_off.value, reg->var_off.mask, off, fmt->range);
+	else
+		scnprintf(buf, size, "variable: known bits %#llx, unknown mask %#llx; %s",
+			  (u64)reg->var_off.value, reg->var_off.mask, fmt->range);
+}
+
+void bpf_diag_report_mem_bounds(struct bpf_verifier_env *env, u32 insn_idx, int regno,
+				const char *reg_name, const char *type_name, const char *proof,
+				int off, int size, u32 mem_size, const struct bpf_reg_state *reg)
+{
+	struct bpf_diag_history_opts opts = {
+		.scope = BPF_DIAG_HISTORY_SCOPE_REG,
+		.frameno = diag_current_frameno(env),
+		.regno = regno,
+	};
+	char *offset_desc;
+
+	if (!bpf_diag_enabled(env))
+		return;
+
+	offset_desc = bpf_diag_scratch_buf(env, 0, NULL);
+
+	diag_format_access_offset(env, offset_desc, BPF_DIAG_SCRATCH_STR_LEN, off, reg);
+
+	bpf_diag_report_header(env, CATEGORY_MEMORY_SAFETY, "access outside bounds");
+	diag_report_reason(env,
+			   "The verifier cannot prove offset + access_size <= object_size. Here, "
+			   "%s. %s is %s; offset is %s; access_size is %d; object_size is %u.",
+			   proof, reg_name, type_name, offset_desc, size, mem_size);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "access may be outside object bounds");
+
+	if (regno >= 0)
+		diag_print_history(env, &opts);
+
+	diag_report_suggestion(env, "Add or adjust a bounds check that proves offset + access_size "
+				    "stays within the object.");
+}
+
 static void diag_format_var_offset(struct bpf_diag_reg_fmt *fmt, char *buf, size_t size,
 				   const struct bpf_diag_reg_snapshot *snapshot)
 {
kernel/bpf/diagnostics.h +6 -0
index 28bc234cfe56..4fc8abb2f2b9 100644
@@ -14,6 +14,7 @@ struct bpf_verifier_state;
 struct btf;
 
 void bpf_diag_format_btf_type(char *buf, size_t size, const struct btf *btf, u32 type_id);
+void bpf_diag_format_s64_sum(char *buf, size_t size, s64 value, int addend);
 
 enum bpf_diag_mod_reason {
 	BPF_DIAG_MOD_WRITE,
@@ -136,6 +137,11 @@ void bpf_diag_report_unreadable_reg(struct bpf_verifier_env *env, u32 insn_idx,
 void bpf_diag_report_stack_arg_uninit(struct bpf_verifier_env *env, u32 insn_idx, int nargs,
 				      int stack_arg_slot, const char *callee_name,
 				      const char *arg_name);
+void bpf_diag_report_memory(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
+			    const char *reason, const char *suggestion);
+void bpf_diag_report_mem_bounds(struct bpf_verifier_env *env, u32 insn_idx, int regno,
+				const char *reg_name, const char *type_name, const char *proof,
+				int off, int size, u32 mem_size, const struct bpf_reg_state *reg);
 int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true);
 void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
 			 struct bpf_diag_mod_target target, enum bpf_diag_mod_reason reason,
kernel/bpf/verifier.c +93 -9

175 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#22 lore raw

PATCH v3 10/17 bpf: Report Resource Lifetime reference leaks

In reply to Kumar Kartikeya Dwivedi

Augment selected Resource Lifetime Safety failures with structured diagnostics while preserving the existing verifier messages.

Report unreleased references from check_reference_leak() using reference-scoped diagnostic history, and add state reports for dynptr, iterator, lock, and IRQ-flag lifetime misuse.

IRQ restore mismatch and out-of-order diagnostics use IRQ context-scoped history when an IRQ-disabled region is active, so retained save/restore context is still visible after per-state history removal.

---
 kernel/bpf/diagnostics.c |  91 ++++++++++++++++++
 kernel/bpf/diagnostics.h |   9 ++
 kernel/bpf/verifier.c    | 198 ++++++++++++++++++++++++++++++++++-----
 3 files changed, 273 insertions(+), 25 deletions(-)
kernel/bpf/diagnostics.c +91 -0
index d4588b19aac9..e454bcd0a0e0 100644
@@ -1644,6 +1644,97 @@ void bpf_diag_report_mem_bounds(struct bpf_verifier_env *env, u32 insn_idx, int
 				    "stays within the object.");
 }
 
+static const char *diag_lock_name(const struct bpf_reference_state *lock)
+{
+	switch (lock->type) {
+	case REF_TYPE_LOCK:
+		return "bpf_spin_lock";
+	case REF_TYPE_RES_LOCK:
+		return "resource spin lock";
+	case REF_TYPE_RES_LOCK_IRQ:
+		return "IRQ-saving resource spin lock";
+	default:
+		return "lock";
+	}
+}
+
+static void diag_res_report(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
+			    const char *reason)
+{
+	bpf_diag_report_header(env, CATEGORY_RESOURCE_LIFETIME_SAFETY, problem);
+	diag_report_reason(env, "%s", reason);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "%s", problem);
+}
+
+void bpf_diag_res(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
+		  const char *reason, const char *suggestion)
+{
+	diag_res_report(env, insn_idx, problem, reason);
+	diag_report_suggestion(env, "%s", suggestion);
+}
+
+void bpf_diag_lock(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
+		   const char *reason, const char *suggestion,
+		   const struct bpf_reference_state *active_lock)
+{
+	diag_res_report(env, insn_idx, problem, reason);
+
+	if (active_lock) {
+		diag_report_section(env, "Active lock");
+		bpf_diag_report_source(env, active_lock->insn_idx, "acquired",
+				       "active %s has verifier identity %d",
+				       diag_lock_name(active_lock), active_lock->id);
+	}
+
+	diag_report_suggestion(env, "%s", suggestion);
+}
+
+void bpf_diag_irq(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
+		  const char *reason, const char *suggestion, u32 depth)
+{
+	struct bpf_diag_history_opts opts = {
+		.scope = BPF_DIAG_HISTORY_SCOPE_CONTEXT,
+		.ctx_kind = BPF_DIAG_CONTEXT_IRQ,
+		.ctx_depth = depth,
+	};
+
+	bpf_diag_report_header(env, CATEGORY_RESOURCE_LIFETIME_SAFETY, problem);
+	diag_report_reason(env, "%s", reason);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "%s", problem);
+
+	if (depth)
+		diag_print_history(env, &opts);
+
+	diag_report_suggestion(env, "%s", suggestion);
+}
+
+void bpf_diag_leak(struct bpf_verifier_env *env, u32 ref_id, u32 alloc_insn, u32 fail_insn)
+{
+	struct bpf_diag_history_opts opts = {
+		.scope = BPF_DIAG_HISTORY_SCOPE_REF,
+		.ref_id = ref_id,
+	};
+
+	bpf_diag_report_header(env, CATEGORY_RESOURCE_LIFETIME_SAFETY, "unreleased resource");
+	diag_report_reason(env,
+			   "Owned resource (id=%u) was acquired at instruction %u and still needs "
+			   "to be released before this exit path.",
+			   ref_id, alloc_insn);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, fail_insn, "error",
+			       "owned resource (id=%u) still needs release", ref_id);
+
+	diag_print_history(env, &opts);
+
+	diag_report_suggestion(env, "Release or transfer ownership of the acquired resource on "
+				    "every path before the program exits.");
+}
+
 static void diag_format_var_offset(struct bpf_diag_reg_fmt *fmt, char *buf, size_t size,
 				   const struct bpf_diag_reg_snapshot *snapshot)
 {
kernel/bpf/diagnostics.h +9 -0
index 4fc8abb2f2b9..73ddede41d17 100644
@@ -8,6 +8,7 @@
 #include <linux/compiler_attributes.h>
 #include <linux/types.h>
 
+struct bpf_reference_state;
 struct bpf_reg_state;
 struct bpf_verifier_env;
 struct bpf_verifier_state;
@@ -142,6 +143,14 @@ void bpf_diag_report_memory(struct bpf_verifier_env *env, u32 insn_idx, const ch
 void bpf_diag_report_mem_bounds(struct bpf_verifier_env *env, u32 insn_idx, int regno,
 				const char *reg_name, const char *type_name, const char *proof,
 				int off, int size, u32 mem_size, const struct bpf_reg_state *reg);
+void bpf_diag_res(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
+		  const char *reason, const char *suggestion);
+void bpf_diag_lock(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
+		   const char *reason, const char *suggestion,
+		   const struct bpf_reference_state *active_lock);
+void bpf_diag_irq(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
+		  const char *reason, const char *suggestion, u32 depth);
+void bpf_diag_leak(struct bpf_verifier_env *env, u32 ref_id, u32 alloc_insn, u32 fail_insn);
 int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true);
 void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
 			 struct bpf_diag_mod_target target, enum bpf_diag_mod_reason reason,
kernel/bpf/verifier.c +173 -25

359 lines not on this page · raw message

Signature · 1 line
2.53.0
#23 lore raw

Re: [PATCH bpf-next v3 10/17] bpf: Report Resource Lifetime reference leaks

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] Diagnostic functions print `insn 4294967295` due to a hardcoded `-1` instruction index passed to…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] Diagnostic functions print insn 4294967295 due to a hardcoded -1 instruction index passed to process_dynptr_func. --

--- Patch [10]: [PATCH bpf-next v3 10/17] bpf: Report Resource Lifetime reference leaks --- commit 11b108e2b9d6802e27c431d5c20ed1b81781c4e6
Author: Kumar Kartikeya Dwivedi <[email protected]>

bpf: Report Resource Lifetime reference leaks

Augment selected Resource Lifetime Safety failures with structured diagnostics while preserving the existing verifier messages.

Quoted 12 lines
kernel/bpf/verifier.c +4 -0
index bd233083b4950..84eda5e83f873 100644
@@ -7625,9 +7695,18 @@ static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_stat
 	int spi, err = 0;
 
 	if (reg->type != PTR_TO_STACK && reg->type != CONST_PTR_TO_DYNPTR) {
+		const char *fmt = "A dynptr argument must be a pointer to a dynptr stack slot or a "
+				  "verifier-provided const struct bpf_dynptr, but %s is %s.";
+		const char *reason;
+

kernel/bpf/verifier.c static int process_dynptr_func(struct bpf_verifier_env *env, struct bpf_reg_stat · line 7711

Quoted 10 lines
kernel/bpf/verifier.c +5 -0
 		verbose(env,
 			"%s expected pointer to stack or const struct bpf_dynptr\n",
 			reg_arg_name(env, argno));
+		reason = bpf_diag_scratch_printf(env, 0, fmt, reg_arg_name(env, argno),
+						 bpf_diag_reg_type_plain(env, reg->type));
+		bpf_diag_res(env, insn_idx, "invalid dynptr argument", reason,
+			     "Pass the address of a stack dynptr object, or use a const dynptr "
+			     "pointer returned by the verifier-supported path.");
 		return -EINVAL;
 	}

[Severity: Low]
Will passing insn_idx directly to bpf_diag_res() cause an integer underflow in the diagnostic output?

Looking at btf_check_func_arg_match(), it calls process_dynptr_func() with -1 hardcoded as the instruction index:

kernel/bpf/verifier.c:btf_check_func_arg_match() {
    ...
    ret = process_dynptr_func(env, reg, argno, -1, arg->arg_type, 
                              &ref_obj, NULL);
    ...
}

Because bpf_diag_res() expects a u32 for insn_idx, this -1 gets cast to 4294967295. This results in the verifier log printing "insn 4294967295" during validation failures for dynptrs in global subprogram calls.

Could this use env->insn_idx instead, or handle the -1 case explicitly before passing it to bpf_diag_res()?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
author maintainer
#24 lore raw

PATCH v3 11/17 bpf: Report Call Type Safety argument errors

In reply to Kumar Kartikeya Dwivedi

Augment selected helper and kfunc argument-contract failures with Call Type Safety reports. Keep the existing terse verifier messages and add reason, source context, causal register or stack-argument history, and targeted suggestions.

Cover helper register-type mismatch, helper and kfunc non-NULL pointer requirements, release-helper ownership requirements, scalar and constant kfunc arguments, trusted and RCU pointer contracts, kfunc memory arguments, memory/length pairs, refcounted kptrs, constant strings, and IRQ flag stack arguments.

---
 kernel/bpf/diagnostics.c | 152 +++++++++++++++++++++-
 kernel/bpf/diagnostics.h |   8 ++
 kernel/bpf/verifier.c    | 271 ++++++++++++++++++++++++++++++++++++---
 3 files changed, 415 insertions(+), 16 deletions(-)
kernel/bpf/diagnostics.c +151 -1
index e454bcd0a0e0..111999e7682d 100644
@@ -7,6 +7,7 @@
 #include <linux/btf.h>
 #include <linux/ctype.h>
 #include <linux/kernel.h>
+#include <linux/list.h>
 #include <linux/overflow.h>
 #include <linux/slab.h>
 #include <linux/stdarg.h>
@@ -154,6 +155,11 @@ struct bpf_diag_reg_fmt {
 	char umax_buf[32];
 };
 
+struct bpf_diag_fmt_buf {
+	struct list_head node;
+	char data[];
+};
+
 struct bpf_diag_scratch {
 	char str[BPF_DIAG_SCRATCH_STR_CNT][BPF_DIAG_SCRATCH_STR_LEN];
 	struct bpf_reg_state regs[BPF_DIAG_SCRATCH_REG_CNT];
@@ -168,6 +174,7 @@ struct bpf_diag_scratch {
 struct bpf_diag {
 	struct bpf_diag_log log;
 	struct bpf_diag_scratch scratch;
+	struct list_head fmt_bufs;
 };
 
 bool bpf_diag_enabled(const struct bpf_verifier_env *env)
@@ -186,7 +193,11 @@ int bpf_diag_init(struct bpf_verifier_env *env)
 		return 0;
 
 	env->diag = kzalloc_obj(struct bpf_diag, GFP_KERNEL_ACCOUNT);
-	return env->diag ? 0 : -ENOMEM;
+	if (!env->diag)
+		return -ENOMEM;
+
+	INIT_LIST_HEAD(&env->diag->fmt_bufs);
+	return 0;
 }
 
 static struct bpf_diag_scratch *diag_scratch(struct bpf_verifier_env *env)
@@ -217,6 +228,100 @@ char *bpf_diag_scratch_buf(struct bpf_verifier_env *env, unsigned int slot, size
 	return buf;
 }
 
+static void diag_fmt_set_error(struct bpf_diag *diag, int error)
+{
+	if (!diag->log.error)
+		diag->log.error = error;
+}
+
+static char *diag_fmt_alloc(struct bpf_verifier_env *env, size_t size)
+{
+	struct bpf_diag *diag = diag_env(env);
+	struct bpf_diag_fmt_buf *buf;
+
+	if (!diag)
+		return NULL;
+
+	buf = kmalloc(struct_size(buf, data, size), GFP_KERNEL_ACCOUNT);
+	if (!buf) {
+		diag_fmt_set_error(diag, -ENOMEM);
+		return NULL;
+	}
+	list_add_tail(&buf->node, &diag->fmt_bufs);
+	return buf->data;
+}
+
+char *bpf_diag_fmt_buf(struct bpf_verifier_env *env, size_t size)
+{
+	char *buf;
+
+	if (!size)
+		return NULL;
+
+	buf = diag_fmt_alloc(env, size);
+	if (buf)
+		buf[0] = '\0';
+	return buf;
+}
+
+const char *bpf_diag_vfmt(struct bpf_verifier_env *env, const char *fmt, va_list args)
+{
+	struct bpf_diag *diag = diag_env(env);
+	va_list copy;
+	char *buf;
+	int len;
+
+	va_copy(copy, args);
+	len = vsnprintf(NULL, 0, fmt, copy);
+	va_end(copy);
+	if (len < 0 || len == INT_MAX) {
+		if (diag)
+			diag_fmt_set_error(diag, -EOVERFLOW);
+		return "";
+	}
+
+	buf = diag_fmt_alloc(env, len + 1);
+	if (buf)
+		vsnprintf(buf, len + 1, fmt, args);
+	return buf ?: "";
+}
+
+const char *bpf_diag_fmt(struct bpf_verifier_env *env, const char *fmt, ...)
+{
+	const char *buf;
+	va_list args;
+
+	va_start(args, fmt);
+	buf = bpf_diag_vfmt(env, fmt, args);
+	va_end(args);
+	return buf;
+}
+
+const char *bpf_diag_fmt_btf_type(struct bpf_verifier_env *env, const struct btf *btf, u32 type_id)
+{
+	char *buf = bpf_diag_fmt_buf(env, BPF_DIAG_SCRATCH_STR_LEN);
+
+	if (!buf)
+		return "";
+
+	bpf_diag_format_btf_type(buf, BPF_DIAG_SCRATCH_STR_LEN, btf, type_id);
+	return buf;
+}
+
+static void diag_fmt_free(struct bpf_verifier_env *env)
+{
+	struct bpf_diag *diag = diag_env(env);
+	struct bpf_diag_fmt_buf *buf, *tmp;
+
+	if (!diag)
+		return;
+
+	list_for_each_entry_safe(buf, tmp, &diag->fmt_bufs, node) {
+		list_del(&buf->node);
+		kfree(buf);
+	}
+}
+
 const char *bpf_diag_scratch_strcpy(struct bpf_verifier_env *env, unsigned int slot,
 				    const char *str)
 {
@@ -319,6 +424,7 @@ void bpf_diag_free(struct bpf_verifier_env *env)
 	if (!diag)
 		return;
 
+	diag_fmt_free(env);
 	kfree(diag->log.events);
 	kfree(diag->scratch.history_bitmap);
 	kfree(diag);
@@ -946,6 +1052,50 @@ static const char *diag_arg_ordinal(int argno)
 	}
 }
 
+void bpf_diag_report_call_type(struct bpf_verifier_env *env, u32 insn_idx, int argno, int regno,
+			       int stack_arg_slot, const char *call_name, const char *arg_name,
+			       const char *reason, const char *suggestion)
+{
+	struct bpf_diag_history_opts opts = {
+		.frameno = diag_current_frameno(env),
+	};
+	const char *ordinal = diag_arg_ordinal(argno);
+	const char *arg_desc;
+	bool print_history = true;
+
+	if (regno >= 0) {
+		opts.scope = BPF_DIAG_HISTORY_SCOPE_REG;
+		opts.regno = regno;
+	} else if (stack_arg_slot >= 0) {
+		opts.scope = BPF_DIAG_HISTORY_SCOPE_STACK_ARG;
+		opts.stack_arg_slot = stack_arg_slot;
+	} else {
+		print_history = false;
+	}
+
+	if (ordinal && arg_name)
+		arg_desc = bpf_diag_fmt(env, "%s argument (%s)", ordinal, arg_name);
+	else if (ordinal)
+		arg_desc = bpf_diag_fmt(env, "%s argument", ordinal);
+	else if (arg_name)
+		arg_desc = bpf_diag_fmt(env, "argument %s", arg_name);
+	else
+		arg_desc = "argument";
+
+	bpf_diag_report_header(env, CATEGORY_CALL_TYPE_SAFETY, "invalid call argument");
+	diag_report_reason(env, "The %s to %s does not satisfy the verifier contract: %s.",
+			   arg_desc, call_name, reason);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "invalid %s for %s", arg_desc, call_name);
+
+	if (print_history)
+		diag_print_history(env, &opts);
+
+	diag_report_suggestion(env, "%s", suggestion);
+	diag_fmt_free(env);
+}
+
 void bpf_diag_report_invalid_deref(struct bpf_verifier_env *env, u32 insn_idx, int regno,
 				   const char *reg_name, const struct bpf_reg_state *reg,
 				   enum bpf_diag_invalid_deref_kind kind, s64 offset)
kernel/bpf/diagnostics.h +8 -0
index 73ddede41d17..7f1af8f50704 100644
@@ -6,6 +6,7 @@
 
 #include <linux/bpf.h>
 #include <linux/compiler_attributes.h>
+#include <linux/stdarg.h>
 #include <linux/types.h>
 
 struct bpf_reference_state;
@@ -113,6 +114,10 @@ bool bpf_diag_enabled(const struct bpf_verifier_env *env);
 int bpf_diag_init(struct bpf_verifier_env *env);
 char *bpf_diag_scratch_buf(struct bpf_verifier_env *env, unsigned int slot, size_t *size);
 struct bpf_reg_state *bpf_diag_reg_scratch(struct bpf_verifier_env *env, unsigned int slot);
+char *bpf_diag_fmt_buf(struct bpf_verifier_env *env, size_t size);
+const char *bpf_diag_vfmt(struct bpf_verifier_env *env, const char *fmt, va_list args);
+const char *bpf_diag_fmt(struct bpf_verifier_env *env, const char *fmt, ...) __printf(2, 3);
+const char *bpf_diag_fmt_btf_type(struct bpf_verifier_env *env, const struct btf *btf, u32 type_id);
 const char *bpf_diag_scratch_strcpy(struct bpf_verifier_env *env, unsigned int slot,
 				    const char *str);
 const char *bpf_diag_scratch_printf(struct bpf_verifier_env *env, unsigned int slot,
@@ -151,6 +156,9 @@ void bpf_diag_lock(struct bpf_verifier_env *env, u32 insn_idx, const char *probl
 void bpf_diag_irq(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
 		  const char *reason, const char *suggestion, u32 depth);
 void bpf_diag_leak(struct bpf_verifier_env *env, u32 ref_id, u32 alloc_insn, u32 fail_insn);
+void bpf_diag_report_call_type(struct bpf_verifier_env *env, u32 insn_idx, int argno, int regno,
+			       int stack_arg_slot, const char *call_name, const char *arg_name,
+			       const char *reason, const char *suggestion);
 int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true);
 void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
 			 struct bpf_diag_mod_target target, enum bpf_diag_mod_reason reason,
kernel/bpf/verifier.c +256 -15

433 lines not on this page · raw message

Signature · 1 line
2.53.0
#25 lore raw

Re: [PATCH bpf-next v3 11/17] bpf: Report Call Type Safety argument errors

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Incorrect function name reported in NULL pointer diagnostic for global subprograms --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Incorrect function name reported in NULL pointer diagnostic for global subprograms --

--- Patch [11]: [PATCH bpf-next v3 11/17] bpf: Report Call Type Safety argument errors --- commit 42278ddf76eadbac6e7b1b29c475b084fe058a97
Author: Kumar Kartikeya Dwivedi <[email protected]>

bpf: Report Call Type Safety argument errors

Augment selected helper and kfunc argument-contract failures with Call Type Safety reports. Keep the existing terse verifier messages and add reason, source context, causal register or stack-argument history, and targeted suggestions.

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index 84eda5e83f873..07e2c1ed8fbe6 100644

[ ... ]

kernel/bpf/verifier.c static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *re · line 8507

Quoted 6 lines
kernel/bpf/verifier.c +2 -0
@@ -8438,6 +8503,12 @@ static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *re
 		    (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) {
 			verbose(env, "Possibly NULL pointer passed to helper %s\n",
 				reg_arg_name(env, argno));
+			bpf_diag_report_call_arg(env, env->insn_idx, argno,
+						 func_id_name(meta->func_id),
                                                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^

[Severity: Medium]
Will this produce an incorrect diagnostic for global subprograms?

When check_reg_type() is called from btf_check_func_arg_match() for a global subprogram, meta->func_id is explicitly zeroed and the subprogram name is passed via the call_name parameter. By using func_id_name(meta->func_id) here instead of call_name, won't this result in the log message printing "unspec" instead of the actual global subprogram name?

Quoted 6 lines
kernel/bpf/verifier.c +4 -0
+						 "the pointer may be NULL, but this helper "
+						 "requires a non-NULL pointer",
+						 "Add a NULL check and call the helper only on the "
+						 "non-NULL path.");
 			return -EACCES;
 		}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
author maintainer
#26 lore raw

PATCH v3 12/17 bpf: Report Execution Context Safety errors

In reply to Kumar Kartikeya Dwivedi

Augment selected sleepability and critical-section failures with Execution Context Safety reports. Keep the existing verifier messages and add source context, path history, and suggestions tied to the active context.

Use the context history recorded earlier to anchor causal paths to lock, IRQ, RCU, and preempt regions instead of unrelated register updates.

Cover global calls while holding a lock, sleepable global function calls, sleepable helpers, sleepable kfunc calls from disallowed contexts, operations that exit while a context is still active, and unmatched context exits.

---
 kernel/bpf/diagnostics.c | 198 +++++++++++++++++++++++++++++++++++----
 kernel/bpf/diagnostics.h |   9 ++
 kernel/bpf/verifier.c    |  93 ++++++++++++++++++
 3 files changed, 283 insertions(+), 17 deletions(-)
kernel/bpf/diagnostics.c +181 -17
index 111999e7682d..c90be89d4707 100644
@@ -965,6 +965,23 @@ static u32 diag_current_frameno(const struct bpf_verifier_env *env)
 	return env->cur_state->frame[env->cur_state->curframe]->frameno;
 }
 
+static const char *diag_context_name(enum bpf_diag_context_kind kind)
+{
+	switch (kind) {
+	case BPF_DIAG_CONTEXT_RCU:
+		return "RCU read lock region";
+	case BPF_DIAG_CONTEXT_PREEMPT:
+		return "non-preemptible region";
+	case BPF_DIAG_CONTEXT_IRQ:
+		return "IRQ-disabled region";
+	case BPF_DIAG_CONTEXT_LOCK:
+		return "lock region";
+	case BPF_DIAG_CONTEXT_NONE:
+	default:
+		return "context";
+	}
+}
+
 void bpf_diag_report_register_type(struct bpf_verifier_env *env, u32 insn_idx, int regno,
 				   const char *problem, const char *reason, const char *suggestion)
 {
@@ -1096,6 +1113,170 @@ void bpf_diag_report_call_type(struct bpf_verifier_env *env, u32 insn_idx, int a
 	diag_fmt_free(env);
 }
 
+static const char *diag_context_constraint(enum bpf_diag_context_kind kind)
+{
+	switch (kind) {
+	case BPF_DIAG_CONTEXT_RCU:
+		return "RCU read-side critical sections cannot call operations that may sleep";
+	case BPF_DIAG_CONTEXT_PREEMPT:
+		return "preemption-disabled code cannot call operations that may sleep";
+	case BPF_DIAG_CONTEXT_IRQ:
+		return "IRQ-disabled code cannot call operations that may sleep";
+	case BPF_DIAG_CONTEXT_LOCK:
+		return "code holding a BPF spin lock cannot call operations that may sleep";
+	case BPF_DIAG_CONTEXT_NONE:
+	default:
+		return NULL;
+	}
+}
+
+static void diag_format_active_context(char *buf, size_t size, u32 depth, const char *context)
+{
+	if (depth == 1)
+		scnprintf(buf, size, "an active %s (depth 1)", context);
+	else
+		scnprintf(buf, size, "%u active %ss (depth %u)", depth, context, depth);
+}
+
+static u32 diag_context_depth(struct bpf_verifier_env *env, enum bpf_diag_context_kind kind)
+{
+	switch (kind) {
+	case BPF_DIAG_CONTEXT_RCU:
+		return env->cur_state->active_rcu_locks;
+	case BPF_DIAG_CONTEXT_PREEMPT:
+		return env->cur_state->active_preempt_locks;
+	case BPF_DIAG_CONTEXT_IRQ:
+		return bpf_diag_irq_depth(env->cur_state);
+	case BPF_DIAG_CONTEXT_LOCK:
+		return env->cur_state->active_locks;
+	case BPF_DIAG_CONTEXT_NONE:
+	default:
+		return 0;
+	}
+}
+
+static void diag_ctx_forbidden(struct bpf_verifier_env *env, u32 insn_idx, const char *operation,
+			       enum bpf_diag_context_kind ctx_kind, const char *context,
+			       const char *suggestion)
+{
+	u32 depth = diag_context_depth(env, ctx_kind);
+	struct bpf_diag_history_opts opts = {
+		.scope = BPF_DIAG_HISTORY_SCOPE_CONTEXT,
+		.ctx_kind = ctx_kind,
+		.ctx_depth = depth,
+	};
+	const char *depth_buf;
+
+	bpf_diag_report_header(env, CATEGORY_EXECUTION_CONTEXT_SAFETY,
+			       "operation is not allowed in this context");
+	if (diag_context_constraint(ctx_kind)) {
+		if (depth) {
+			depth_buf = bpf_diag_scratch_buf(env, 2, NULL);
+			if (depth_buf)
+				diag_format_active_context((char *)depth_buf,
+							   BPF_DIAG_SCRATCH_STR_LEN, depth,
+							   context);
+			else
+				depth_buf = "";
+			diag_report_reason(env,
+					   "The operation %s cannot be used in %s because %s. This "
+					   "path is still inside %s.",
+					   operation, context, diag_context_constraint(ctx_kind),
+					   depth_buf);
+		} else {
+			diag_report_reason(env, "The operation %s cannot be used in %s because %s.",
+					   operation, context, diag_context_constraint(ctx_kind));
+		}
+	} else {
+		diag_report_reason(env, "The operation %s cannot be used in %s.", operation,
+				   context);
+	}
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "%s is not allowed in %s", operation,
+			       context);
+
+	if (ctx_kind != BPF_DIAG_CONTEXT_NONE)
+		diag_print_history(env, &opts);
+
+	diag_report_suggestion(env, "%s", suggestion);
+}
+
+static void diag_ctx_active(struct bpf_verifier_env *env, u32 insn_idx, const char *operation,
+			    enum bpf_diag_context_kind ctx_kind, const char *context,
+			    const char *suggestion)
+{
+	u32 depth = diag_context_depth(env, ctx_kind);
+	struct bpf_diag_history_opts opts = {
+		.scope = BPF_DIAG_HISTORY_SCOPE_CONTEXT,
+		.ctx_kind = ctx_kind,
+		.ctx_depth = depth,
+	};
+	const char *depth_buf;
+
+	depth_buf = bpf_diag_scratch_buf(env, 2, NULL);
+	if (depth_buf)
+		diag_format_active_context((char *)depth_buf, BPF_DIAG_SCRATCH_STR_LEN, depth,
+					   context);
+	else
+		depth_buf = "";
+
+	bpf_diag_report_header(env, CATEGORY_EXECUTION_CONTEXT_SAFETY,
+			       "operation is not allowed in this context");
+	diag_report_reason(env,
+			   "The operation %s cannot be used while this path is still inside %s. "
+			   "Leave the region before this operation.",
+			   operation, depth_buf);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "%s is not allowed before leaving %s",
+			       operation, context);
+
+	diag_print_history(env, &opts);
+
+	diag_report_suggestion(env, "%s", suggestion);
+}
+
+static void diag_ctx_underflow(struct bpf_verifier_env *env, u32 insn_idx, const char *operation,
+			       enum bpf_diag_context_kind ctx_kind, const char *suggestion)
+{
+	struct bpf_diag_history_opts opts = {
+		.scope = BPF_DIAG_HISTORY_SCOPE_CONTEXT,
+		.ctx_kind = ctx_kind,
+	};
+	const char *context = diag_context_name(ctx_kind);
+
+	bpf_diag_report_header(env, CATEGORY_EXECUTION_CONTEXT_SAFETY, "unmatched context exit");
+	diag_report_reason(env,
+			   "The operation %s tries to leave %s, but this path has no active %s to "
+			   "leave. The current depth is 0.",
+			   operation, context, context);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "%s has no matching enter on this path",
+			       operation);
+
+	diag_print_history(env, &opts);
+
+	diag_report_suggestion(env, "%s", suggestion);
+}
+
+void bpf_diag_ctx(struct bpf_verifier_env *env, enum bpf_diag_ctx_report report, u32 insn_idx,
+		  const char *operation, enum bpf_diag_context_kind ctx_kind, const char *context,
+		  const char *suggestion)
+{
+	switch (report) {
+	case BPF_DIAG_CTX_FORBIDDEN:
+		diag_ctx_forbidden(env, insn_idx, operation, ctx_kind, context, suggestion);
+		return;
+	case BPF_DIAG_CTX_ACTIVE:
+		diag_ctx_active(env, insn_idx, operation, ctx_kind, context, suggestion);
+		return;
+	case BPF_DIAG_CTX_UNDERFLOW:
+		diag_ctx_underflow(env, insn_idx, operation, ctx_kind, suggestion);
+		return;
+	}
+}
 void bpf_diag_report_invalid_deref(struct bpf_verifier_env *env, u32 insn_idx, int regno,
 				   const char *reg_name, const struct bpf_reg_state *reg,
 				   enum bpf_diag_invalid_deref_kind kind, s64 offset)
@@ -2108,23 +2289,6 @@ static void diag_print_ref_event(struct bpf_verifier_env *env,
 			       event->ref.ref_id);
 }
 
-static const char *diag_context_name(enum bpf_diag_context_kind kind)
-{
-	switch (kind) {
-	case BPF_DIAG_CONTEXT_RCU:
-		return "RCU read lock region";
-	case BPF_DIAG_CONTEXT_PREEMPT:
-		return "non-preemptible region";
-	case BPF_DIAG_CONTEXT_IRQ:
-		return "IRQ-disabled region";
-	case BPF_DIAG_CONTEXT_LOCK:
-		return "lock region";
-	case BPF_DIAG_CONTEXT_NONE:
-	default:
-		return "context";
-	}
-}
-
 static void diag_print_context_event(struct bpf_verifier_env *env,
 				     const struct bpf_diag_history_event *event)
 {
kernel/bpf/diagnostics.h +9 -0
index 7f1af8f50704..f26432e84d9f 100644
@@ -96,6 +96,12 @@ enum bpf_diag_context_kind {
 	BPF_DIAG_CONTEXT_LOCK,
 };
 
+enum bpf_diag_ctx_report {
+	BPF_DIAG_CTX_FORBIDDEN,
+	BPF_DIAG_CTX_ACTIVE,
+	BPF_DIAG_CTX_UNDERFLOW,
+};
+
 enum bpf_diag_context_event_kind {
 	BPF_DIAG_CONTEXT_EVENT_RCU = BPF_DIAG_CONTEXT_RCU,
 	BPF_DIAG_CONTEXT_EVENT_PREEMPT = BPF_DIAG_CONTEXT_PREEMPT,
@@ -159,6 +165,9 @@ void bpf_diag_leak(struct bpf_verifier_env *env, u32 ref_id, u32 alloc_insn, u32
 void bpf_diag_report_call_type(struct bpf_verifier_env *env, u32 insn_idx, int argno, int regno,
 			       int stack_arg_slot, const char *call_name, const char *arg_name,
 			       const char *reason, const char *suggestion);
+void bpf_diag_ctx(struct bpf_verifier_env *env, enum bpf_diag_ctx_report report, u32 insn_idx,
+		  const char *operation, enum bpf_diag_context_kind ctx_kind, const char *context,
+		  const char *suggestion);
 int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true);
 void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
 			 struct bpf_diag_mod_target target, enum bpf_diag_mod_reason reason,
kernel/bpf/verifier.c +93 -0

192 lines not on this page · raw message

Signature · 1 line
2.53.0
#27 lore raw

Re: [PATCH bpf-next v3 12/17] bpf: Report Execution Context Safety errors

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Incorrect diagnostic constraint explanation for global function calls under locks --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Incorrect diagnostic constraint explanation for global function calls under locks --

--- Patch [12]: [PATCH bpf-next v3 12/17] bpf: Report Execution Context Safety errors --- commit 4c2714bc706956dcdd83f54e5db8f96839c37f55
Author: Kumar Kartikeya Dwivedi <[email protected]>

bpf: Report Execution Context Safety errors

This commit augments selected sleepability and critical-section failures with Execution Context Safety reports. It adds source context, path history, and suggestions tied to the active context while keeping existing verifier messages.

Quoted 11 lines
kernel/bpf/verifier.c +2 -0
index 07e2c1ed8fbe6..e253fbc733a48 100644
@@ -10109,17 +10111,32 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	if (err == -EFAULT)
 		return err;
 	if (bpf_subprog_is_global(env, subprog)) {
+		const char *context;
 		const char *sub_name = bpf_verifier_subprog_name(env, subprog);
+		const char *operation;

kernel/bpf/verifier.c static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, · line 10126

Quoted 10 lines
kernel/bpf/verifier.c +6 -0
 
 		if (env->cur_state->active_locks) {
 			verbose(env, "global function calls are not allowed while holding a lock,\n"
 				     "use static function instead\n");
+			operation =
+				bpf_diag_scratch_printf(env, 1, "global function %s()", sub_name);
+			bpf_diag_ctx(env, BPF_DIAG_CTX_FORBIDDEN, *insn_idx, operation,
+				     BPF_DIAG_CONTEXT_LOCK, "lock region",
+				     "Release the lock before calling the global function, or use "
+				     "a static function instead.");

[Severity: Medium]
Will this result in an incorrect diagnostic reason being printed?

Since BPF_DIAG_CTX_FORBIDDEN triggers diag_ctx_forbidden(), which in turn uses diag_context_constraint() for the constraint explanation:

kernel/bpf/diagnostics.c:diag_context_constraint() {
	...
	case BPF_DIAG_CONTEXT_LOCK:
		return "code holding a BPF spin lock cannot call operations that may sleep";
	...
}

Doesn't this incorrectly tell the developer that their global function call was rejected because it "may sleep"? Global function calls are generally disallowed under locks due to verifier state limitations rather than just sleepability.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
author maintainer
#28 lore raw

PATCH v3 13/17 bpf: Report Program Structure CFG errors

In reply to Kumar Kartikeya Dwivedi

Augment selected subprogram CFG validation failures with Program Structure reports. These errors are structural rather than path-dependent, so the report focuses on source and instruction context instead of causal history.

Cover jumps that leave the current subprogram, subprograms whose last instruction can fall through into the next subprogram, and recursive bpf2bpf call graph edges.

Format long jump-range reasons directly in diagnostics.c, and keep the fallthrough suggestion aligned with the verifier check by suggesting exit or explicit jumps.

---
 kernel/bpf/cfg.c         | 55 ++++++++++++++++++++++++++++++++++++++++
 kernel/bpf/diagnostics.c | 19 ++++++++++++++
 kernel/bpf/diagnostics.h |  3 +++
 kernel/bpf/verifier.c    | 32 +++++++++++++++++++++++
 4 files changed, 109 insertions(+)
kernel/bpf/cfg.c +55 -0
index 26d37066465f..376f6b6d469c 100644
@@ -5,6 +5,8 @@
 #include <linux/filter.h>
 #include <linux/sort.h>
 
+#include "diagnostics.h"
+
 #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
 
 /* non-recursive DFS pseudo code
@@ -113,6 +115,12 @@ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
 	if (w < 0 || w >= env->prog->len) {
 		verbose_linfo(env, t, "%d: ", t);
 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
+		bpf_diag_report_program_structure(env, t, "jump out of range",
+						  "Keep branch targets inside the program.",
+						  "Instruction %d jumps to instruction %d, but the "
+						  "program only contains instructions 0 through "
+						  "%d.",
+						  t, w, env->prog->len - 1);
 		return -EINVAL;
 	}
 
@@ -136,6 +144,15 @@ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
 		verbose_linfo(env, t, "%d: ", t);
 		verbose_linfo(env, w, "%d: ", w);
 		verbose(env, "back-edge from insn %d to %d\n", t, w);
+		bpf_diag_report_program_structure(env, t, "back-edge is not allowed",
+						  "Load with privileges that allow this back-edge, "
+						  "or rewrite "
+						  "the control flow so it does not branch "
+						  "backward.",
+						  "Instruction %d branches back to instruction %d. "
+						  "This program is being rejected without the "
+						  "privilege needed for this back-edge.",
+						  t, w);
 		return -EINVAL;
 	} else if (insn_state[w] == EXPLORED) {
 		/* forward- or cross-edge */
@@ -316,6 +333,14 @@ static struct bpf_iarray *jt_from_subprog(struct bpf_verifier_env *env,
 
 	if (!jt) {
 		verbose(env, "no jump tables found for subprog starting at %u\n", subprog_start);
+		bpf_diag_report_program_structure(env, subprog_start, "missing jump table",
+						  "Make sure subprograms containing gotox "
+						  "instructions are "
+						  "accompanied by jump tables referencing these "
+						  "subprograms.",
+						  "No jump table was found for the subprogram that "
+						  "starts at instruction %u.",
+						  subprog_start);
 		return ERR_PTR(-EINVAL);
 	}
 
@@ -343,6 +368,13 @@ create_jt(int t, struct bpf_verifier_env *env)
 		if (jt->items[i] < subprog_start || jt->items[i] >= subprog_end) {
 			verbose(env, "jump table for insn %d points outside of the subprog [%u,%u]\n",
 					t, subprog_start, subprog_end);
+			bpf_diag_report_program_structure(env, t, "jump table target out of range",
+							  "Keep every jump-table target inside the "
+							  "same subprogram.",
+							  "The jump table for instruction %d "
+							  "points outside subprogram range "
+							  "[%u,%u).",
+							  t, subprog_start, subprog_end);
 			kvfree(jt);
 			return ERR_PTR(-EINVAL);
 		}
@@ -374,6 +406,13 @@ static int visit_gotox_insn(int t, struct bpf_verifier_env *env)
 		w = jt->items[i];
 		if (w < 0 || w >= env->prog->len) {
 			verbose(env, "indirect jump out of range from insn %d to %d\n", t, w);
+			bpf_diag_report_program_structure(env, t, "indirect jump out of range",
+							  "Keep indirect jump targets inside the "
+							  "program.",
+							  "Instruction %d can jump indirectly to "
+							  "instruction %d, but the program only "
+							  "contains instructions 0 through %d.",
+							  t, w, env->prog->len - 1);
 			return -EINVAL;
 		}
 
@@ -624,12 +663,28 @@ int bpf_check_cfg(struct bpf_verifier_env *env)
 
 		if (insn_state[i] != EXPLORED) {
 			verbose(env, "unreachable insn %d\n", i);
+			bpf_diag_report_program_structure(env, i, "unreachable instruction",
+							  "Remove the unreachable instruction or "
+							  "add valid control flow that reaches it.",
+							  "Instruction %d is not reachable from "
+							  "the program entry point.",
+							  i);
 			ret = -EINVAL;
 			goto err_free;
 		}
 		if (bpf_is_ldimm64(insn)) {
 			if (insn_state[i + 1] != 0) {
 				verbose(env, "jump into the middle of ldimm64 insn %d\n", i);
+				bpf_diag_report_program_structure(env, i,
+								  "jump into ldimm64 immediate",
+								  "Target the first instruction of "
+								  "the ldimm64 pair, or "
+								  "restructure the jump target.",
+								  "Control flow reaches the second "
+								  "half of the ldimm64 instruction "
+								  "pair that starts at instruction "
+								  "%d.",
+								  i);
 				ret = -EINVAL;
 				goto err_free;
 			}
kernel/bpf/diagnostics.c +19 -0
index c90be89d4707..5496e7a0235b 100644
@@ -1277,6 +1277,25 @@ void bpf_diag_ctx(struct bpf_verifier_env *env, enum bpf_diag_ctx_report report,
 		return;
 	}
 }
+
+void bpf_diag_report_program_structure(struct bpf_verifier_env *env, u32 insn_idx,
+				       const char *problem, const char *suggestion,
+				       const char *reason_fmt, ...)
+{
+	va_list args;
+
+	bpf_diag_report_header(env, CATEGORY_PROGRAM_STRUCTURE, problem);
+	diag_report_section(env, "Reason");
+
+	va_start(args, reason_fmt);
+	diag_vprint_indented(env, reason_fmt, args);
+	va_end(args);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "%s", problem);
+
+	diag_report_suggestion(env, "%s", suggestion);
+}
 void bpf_diag_report_invalid_deref(struct bpf_verifier_env *env, u32 insn_idx, int regno,
 				   const char *reg_name, const struct bpf_reg_state *reg,
 				   enum bpf_diag_invalid_deref_kind kind, s64 offset)
kernel/bpf/diagnostics.h +3 -0
index f26432e84d9f..bb29f4235a68 100644
@@ -168,6 +168,9 @@ void bpf_diag_report_call_type(struct bpf_verifier_env *env, u32 insn_idx, int a
 void bpf_diag_ctx(struct bpf_verifier_env *env, enum bpf_diag_ctx_report report, u32 insn_idx,
 		  const char *operation, enum bpf_diag_context_kind ctx_kind, const char *context,
 		  const char *suggestion);
+void bpf_diag_report_program_structure(struct bpf_verifier_env *env, u32 insn_idx,
+				       const char *problem, const char *suggestion,
+				       const char *reason_fmt, ...) __printf(5, 6);
 int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true);
 void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
 			 struct bpf_diag_mod_target target, enum bpf_diag_mod_reason reason,
kernel/bpf/verifier.c +32 -0
index e253fbc733a4..44e1907ac792 100644
@@ -3041,6 +3041,17 @@ static int check_subprogs(struct bpf_verifier_env *env)
 		off = i + bpf_jmp_offset(&insn[i]) + 1;
 		if (off < subprog_start || off >= subprog_end) {
 			verbose(env, "jump out of range from insn %d to %d\n", i, off);
+			bpf_diag_report_program_structure(env, i, "jump out of range",
+							  "Keep branch targets within the same "
+							  "subprogram, or use an explicit "
+							  "subprogram call.",
+							  "Instruction %d jumps to instruction %d, "
+							  "but subprogram %d only contains "
+							  "instructions %d through %d. A branch "
+							  "target must stay inside the same "
+							  "subprogram.",
+							  i, off, cur_subprog, subprog_start,
+							  subprog_end - 1);
 			return -EINVAL;
 		}
 next:
@@ -3053,6 +3064,18 @@ static int check_subprogs(struct bpf_verifier_env *env)
 			    code != (BPF_JMP32 | BPF_JA) &&
 			    code != (BPF_JMP | BPF_JA)) {
 				verbose(env, "last insn is not an exit or jmp\n");
+				bpf_diag_report_program_structure(env, i,
+								  "subprogram can fall through",
+								  "End each subprogram with an "
+								  "exit or an explicit jump that "
+								  "keeps control flow inside the "
+								  "subprogram.",
+								  "Subprogram %d reaches its last "
+								  "instruction %d without an exit "
+								  "or jump, so control could "
+								  "continue into the next "
+								  "subprogram.",
+								  cur_subprog, i);
 				return -EINVAL;
 			}
 			subprog_start = subprog_end;
@@ -3125,6 +3148,15 @@ static int sort_subprogs_topo(struct bpf_verifier_env *env)
 					verbose(env, "recursive call from %s() to %s()\n",
 						bpf_verifier_subprog_name(env, cur),
 						bpf_verifier_subprog_name(env, callee));
+					bpf_diag_report_program_structure(
+						env, idx, "recursive subprogram call",
+						"Rewrite the recursion as an explicit bounded "
+						"loop, or split the logic so subprogram calls do "
+						"not form a cycle.",
+						"This bpf2bpf call would make the subprogram call "
+						"graph recursive. The verifier requires a finite, "
+						"acyclic call graph so it can bound stack depth "
+						"and analysis.");
 					ret = -EINVAL;
 					goto out;
 				}
Signature · 1 line
2.53.0
maintainer
#29 lore raw

Re: [PATCH bpf-next v3 13/17] bpf: Report Program Structure CFG errors

Quoted 35 lines · Kumar Kartikeya Dwivedi

Augment selected subprogram CFG validation failures with Program Structure reports. These errors are structural rather than path-dependent, so the report focuses on source and instruction context instead of causal history.

Cover jumps that leave the current subprogram, subprograms whose last instruction can fall through into the next subprogram, and recursive bpf2bpf call graph edges.

Format long jump-range reasons directly in diagnostics.c, and keep the fallthrough suggestion aligned with the verifier check by suggesting exit or explicit jumps.

---
 kernel/bpf/cfg.c         | 55 ++++++++++++++++++++++++++++++++++++++++
 kernel/bpf/diagnostics.c | 19 ++++++++++++++
 kernel/bpf/diagnostics.h |  3 +++
 kernel/bpf/verifier.c    | 32 +++++++++++++++++++++++
 4 files changed, 109 insertions(+)
kernel/bpf/cfg.c +2 -0
index 26d37066465f..376f6b6d469c 100644
@@ -5,6 +5,8 @@
 #include <linux/filter.h>
 #include <linux/sort.h>
 
+#include "diagnostics.h"
+
 #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
 
 /* non-recursive DFS pseudo code

kernel/bpf/cfg.c static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) · line 123

Quoted 9 lines
kernel/bpf/cfg.c +6 -0
@@ -113,6 +115,12 @@ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
 	if (w < 0 || w >= env->prog->len) {
 		verbose_linfo(env, t, "%d: ", t);
 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
+		bpf_diag_report_program_structure(env, t, "jump out of range",
+						  "Keep branch targets inside the program.",
+						  "Instruction %d jumps to instruction %d, but the "
+						  "program only contains instructions 0 through "
+						  "%d.",
+						  t, w, env->prog->len - 1);

Nit: I'd forgo the formatting rules and just write the above like:

bpf_diag_report_program_structure(
env, t, "jump out of range",
"Keep branch targets inside the program.",
"Instruction %d jumps to instruction %d, but the program only contains instructions 0 through %d.",
t, w, env->prog->len - 1);

Easier to read and easier to grep.

Quoted 3 lines
kernel/bpf/cfg.c +0 -0
 		return -EINVAL;
 	}
 

[...]

author maintainer
#30 lore raw

Re: [PATCH bpf-next v3 13/17] bpf: Report Program Structure CFG errors

Quoted 48 lines · Eduard Zingerman
Quoted 35 lines · Kumar Kartikeya Dwivedi

Augment selected subprogram CFG validation failures with Program Structure reports. These errors are structural rather than path-dependent, so the report focuses on source and instruction context instead of causal history.

Cover jumps that leave the current subprogram, subprograms whose last instruction can fall through into the next subprogram, and recursive bpf2bpf call graph edges.

Format long jump-range reasons directly in diagnostics.c, and keep the fallthrough suggestion aligned with the verifier check by suggesting exit or explicit jumps.

---
 kernel/bpf/cfg.c         | 55 ++++++++++++++++++++++++++++++++++++++++
 kernel/bpf/diagnostics.c | 19 ++++++++++++++
 kernel/bpf/diagnostics.h |  3 +++
 kernel/bpf/verifier.c    | 32 +++++++++++++++++++++++
 4 files changed, 109 insertions(+)
kernel/bpf/cfg.c +2 -0
index 26d37066465f..376f6b6d469c 100644
@@ -5,6 +5,8 @@
 #include <linux/filter.h>
 #include <linux/sort.h>
 
+#include "diagnostics.h"
+
 #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
 
 /* non-recursive DFS pseudo code

kernel/bpf/cfg.c static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) · line 123

Quoted 9 lines
kernel/bpf/cfg.c +6 -0
@@ -113,6 +115,12 @@ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env)
 	if (w < 0 || w >= env->prog->len) {
 		verbose_linfo(env, t, "%d: ", t);
 		verbose(env, "jump out of range from insn %d to %d\n", t, w);
+		bpf_diag_report_program_structure(env, t, "jump out of range",
+						  "Keep branch targets inside the program.",
+						  "Instruction %d jumps to instruction %d, but the "
+						  "program only contains instructions 0 through "
+						  "%d.",
+						  t, w, env->prog->len - 1);

Nit: I'd forgo the formatting rules and just write the above like:

Quoted 12 lines

bpf_diag_report_program_structure(
env, t, "jump out of range",
"Keep branch targets inside the program.",
"Instruction %d jumps to instruction %d, but the program only contains instructions 0 through %d.",
t, w, env->prog->len - 1);

Easier to read and easier to grep.

Quoted 3 lines
kernel/bpf/cfg.c +0 -0
 		return -EINVAL;
 	}
 

Ack, will change throughout the series.

Quoted 1 line

[...]

author maintainer
#31 lore raw

PATCH v3 14/17 bpf: Report Policy helper and kfunc errors

In reply to Kumar Kartikeya Dwivedi

Augment selected helper and kfunc allowability failures with Policy reports. These reports explain which requested operation is forbidden and why, without adding path history for non-path-dependent policy checks.

Cover unprivileged bpf2bpf and kfunc use, helper program-type restrictions, GPL-only helpers, helper-specific allow callbacks, kfunc allowability, and destructive kfunc capability checks.

---
 kernel/bpf/diagnostics.c | 13 +++++++++++++
 kernel/bpf/diagnostics.h |  2 ++
 kernel/bpf/verifier.c    | 37 ++++++++++++++++++++++++++++++++++++-
 3 files changed, 51 insertions(+), 1 deletion(-)
kernel/bpf/diagnostics.c +13 -0
index 5496e7a0235b..8bf5aef0315b 100644
@@ -1296,6 +1296,19 @@ void bpf_diag_report_program_structure(struct bpf_verifier_env *env, u32 insn_id
 
 	diag_report_suggestion(env, "%s", suggestion);
 }
+
+void bpf_diag_report_policy(struct bpf_verifier_env *env, u32 insn_idx, const char *operation,
+			    const char *reason, const char *suggestion)
+{
+	bpf_diag_report_header(env, CATEGORY_POLICY, "operation is not allowed");
+	diag_report_reason(env, "The operation %s is not allowed: %s.", operation, reason);
+
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "policy check failed for %s", operation);
+
+	diag_report_suggestion(env, "%s", suggestion);
+}
+
 void bpf_diag_report_invalid_deref(struct bpf_verifier_env *env, u32 insn_idx, int regno,
 				   const char *reg_name, const struct bpf_reg_state *reg,
 				   enum bpf_diag_invalid_deref_kind kind, s64 offset)
kernel/bpf/diagnostics.h +2 -0
index bb29f4235a68..64ab9de2bbf6 100644
@@ -171,6 +171,8 @@ void bpf_diag_ctx(struct bpf_verifier_env *env, enum bpf_diag_ctx_report report,
 void bpf_diag_report_program_structure(struct bpf_verifier_env *env, u32 insn_idx,
 				       const char *problem, const char *suggestion,
 				       const char *reason_fmt, ...) __printf(5, 6);
+void bpf_diag_report_policy(struct bpf_verifier_env *env, u32 insn_idx, const char *operation,
+			    const char *reason, const char *suggestion);
 int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true);
 void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
 			 struct bpf_diag_mod_target target, enum bpf_diag_mod_reason reason,
kernel/bpf/verifier.c +36 -1
index 44e1907ac792..c67646f98134 100644
@@ -2963,6 +2963,12 @@ static int add_subprog_and_kfunc(struct bpf_verifier_env *env)
 
 		if (!env->bpf_capable) {
 			verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n");
+			bpf_diag_report_policy(env, i, "bpf-to-bpf or kernel function call",
+					       "loading or calling other BPF or kernel functions "
+					       "requires CAP_BPF or CAP_SYS_ADMIN",
+					       "Load this program with the required capability, or "
+					       "avoid bpf-to-bpf and kernel function calls in "
+					       "unprivileged programs.");
 			return -EPERM;
 		}
 
@@ -11030,17 +11036,35 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 	if (err) {
 		verbose(env, "program of this type cannot use helper %s#%d\n",
 			func_id_name(func_id), func_id);
+		operation = bpf_diag_scratch_printf(env, 1, "helper %s#%d", func_id_name(func_id),
+						    func_id);
+		bpf_diag_report_policy(env, insn_idx, operation,
+				       "this program type does not allow the helper",
+				       "Use a helper allowed for this program type, or move the "
+				       "logic to a compatible program type.");
 		return err;
 	}
 
 	/* eBPF programs must be GPL compatible to use GPL-ed functions */
 	if (!env->prog->gpl_compatible && fn->gpl_only) {
 		verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n");
+		operation = bpf_diag_scratch_printf(env, 1, "helper %s#%d", func_id_name(func_id),
+						    func_id);
+		bpf_diag_report_policy(env, insn_idx, operation,
+				       "this helper is restricted to GPL-compatible programs",
+				       "Use a GPL-compatible license, or replace the helper with "
+				       "one that is available to non-GPL programs.");
 		return -EINVAL;
 	}
 
 	if (fn->allowed && !fn->allowed(env->prog)) {
 		verbose(env, "helper call is not allowed in probe\n");
+		operation = bpf_diag_scratch_printf(env, 1, "helper %s#%d", func_id_name(func_id),
+						    func_id);
+		bpf_diag_report_policy(env, insn_idx, operation,
+				       "the helper-specific policy callback rejected this program",
+				       "Use the helper only from an allowed attach point or "
+				       "program configuration.");
 		return -EINVAL;
 	}
 
@@ -13961,8 +13985,14 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		return 0;
 
 	err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
-	if (err == -EACCES && meta.func_name)
+	if (err == -EACCES && meta.func_name) {
 		verbose(env, "calling kernel function %s is not allowed\n", meta.func_name);
+		operation = bpf_diag_scratch_printf(env, 1, "kfunc %s", meta.func_name);
+		bpf_diag_report_policy(env, insn_idx, operation,
+				       "this program cannot call the kfunc",
+				       "Use a kfunc allowed for this program type and attach "
+				       "point, or change the program context.");
+	}
 	if (err)
 		return err;
 	desc_btf = meta.btf;
@@ -14003,6 +14033,11 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 
 	if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) {
 		verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n");
+		operation = bpf_diag_scratch_printf(env, 1, "destructive kfunc %s", meta.func_name);
+		bpf_diag_report_policy(env, insn_idx, operation,
+				       "destructive kfuncs require CAP_SYS_BOOT",
+				       "Load the program with CAP_SYS_BOOT, or avoid destructive "
+				       "kfuncs.");
 		return -EACCES;
 	}
 
Signature · 1 line
2.53.0
#32 lore raw

Re: [PATCH bpf-next v3 14/17] bpf: Report Policy helper and kfunc errors

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] The verifier reads and dereferences an uninitialized stack variable meta.func_name when bpf_fetch_kfunc_arg_meta fails early with -EACCES, leading to an out-of-bounds read or kernel panic when formatting diagnostic messages. --

--- Patch [14]: [PATCH bpf-next v3 14/17] bpf: Report Policy helper and kfunc errors --- commit 64c35288a6fbbafb58f170cb81136c83e594cbdd
Author: Kumar Kartikeya Dwivedi <[email protected]>

bpf: Report Policy helper and kfunc errors

This commit augments selected helper and kfunc allowability failures with Policy reports to explain which requested operation is forbidden and why.

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index 44e1907ac792d..c67646f981342 100644

[ ... ]

kernel/bpf/verifier.c static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, · line 13990

Quoted 8 lines
kernel/bpf/verifier.c +2 -1
@@ -13961,8 +13985,14 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		return 0;
 
 	err = bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
-	if (err == -EACCES && meta.func_name)
+	if (err == -EACCES && meta.func_name) {
 		verbose(env, "calling kernel function %s is not allowed\n", meta.func_name);
+		operation = bpf_diag_scratch_printf(env, 1, "kfunc %s", meta.func_name);

[Severity: High]
This is a pre-existing issue, but could meta.func_name be uninitialized here when bpf_fetch_kfunc_arg_meta() fails early?

Looking at bpf_fetch_kfunc_arg_meta(), if fetch_kfunc_meta() fails and returns -EACCES, the function returns early before the meta struct is initialized:

err = fetch_kfunc_meta(env, func_id, offset, &kfunc); if (err)

	return err;

memset(meta, 0, sizeof(*meta));

Because meta is declared on the stack in check_kfunc_call(), an early error return leaves it containing uninitialized stack garbage. If this garbage evaluates to non-NULL in the err == -EACCES && meta.func_name check, won't this lead to an out-of-bounds memory read when attempting to format the garbage pointer as a string in verbose() and bpf_diag_scratch_printf()?

Quoted 8 lines
kernel/bpf/verifier.c +5 -0
+		bpf_diag_report_policy(env, insn_idx, operation,
+				       "this program cannot call the kfunc",
+				       "Use a kfunc allowed for this program type and attach "
+				       "point, or change the program context.");
+	}
 	if (err)
 		return err;
 	desc_btf = meta.btf;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
author maintainer
#33 lore raw

PATCH v3 15/17 bpf: Report Verifier Limit errors

In reply to Kumar Kartikeya Dwivedi

Augment selected verifier limit failures with Verifier Limit reports. These reports focus on the limit that was exceeded and the observed value or condition, rather than causal branch history.

Cover tail-call stack constraints, per-subprogram stack depth, combined call stack depth, static and runtime bpf2bpf call-frame depth, processed-instruction complexity, and liveness analysis complexity.

Format reason text in diagnostics.c and allocate call-chain descriptions only on failure paths, preserving useful call-chain context without adding large local buffers to verifier frames.

---
 kernel/bpf/diagnostics.c |  37 ++++++++++++
 kernel/bpf/diagnostics.h |   2 +
 kernel/bpf/liveness.c    |   7 +++
 kernel/bpf/verifier.c    | 119 ++++++++++++++++++++++++++++++++++++++-
 4 files changed, 164 insertions(+), 1 deletion(-)
kernel/bpf/diagnostics.c +37 -0
index 8bf5aef0315b..e2772c1deaff 100644
@@ -1309,6 +1309,43 @@ void bpf_diag_report_policy(struct bpf_verifier_env *env, u32 insn_idx, const ch
 	diag_report_suggestion(env, "%s", suggestion);
 }
 
+void bpf_diag_report_limit(struct bpf_verifier_env *env, u32 insn_idx, const char *limit,
+			   const char *suggestion, const char *reason_fmt, ...)
+{
+	char *reason, *text;
+	va_list args;
+
+	if (!bpf_diag_enabled(env))
+		return;
+
+	bpf_diag_report_header(env, CATEGORY_VERIFIER_LIMIT, "limit exceeded");
+	diag_report_section(env, "Reason");
+
+	va_start(args, reason_fmt);
+	reason = kvasprintf(GFP_KERNEL_ACCOUNT, reason_fmt, args);
+	va_end(args);
+	if (!reason) {
+		diag_write(env, "%s<failed to allocate diagnostic text>\n", BPF_DIAG_TEXT_INDENT);
+		goto source;
+	}
+
+	text = kasprintf(GFP_KERNEL_ACCOUNT, "The %s limit was exceeded: %s.", limit, reason);
+	kfree(reason);
+	if (!text) {
+		diag_write(env, "%s<failed to allocate diagnostic text>\n", BPF_DIAG_TEXT_INDENT);
+		goto source;
+	}
+
+	diag_print_wrapped_text(env, text);
+	kfree(text);
+
+source:
+	diag_report_section(env, "At");
+	bpf_diag_report_source(env, insn_idx, "error", "limit exceeded: %s", limit);
+
+	diag_report_suggestion(env, "%s", suggestion);
+}
+
 void bpf_diag_report_invalid_deref(struct bpf_verifier_env *env, u32 insn_idx, int regno,
 				   const char *reg_name, const struct bpf_reg_state *reg,
 				   enum bpf_diag_invalid_deref_kind kind, s64 offset)
kernel/bpf/diagnostics.h +2 -0
index 64ab9de2bbf6..6a013f1e748b 100644
@@ -173,6 +173,8 @@ void bpf_diag_report_program_structure(struct bpf_verifier_env *env, u32 insn_id
 				       const char *reason_fmt, ...) __printf(5, 6);
 void bpf_diag_report_policy(struct bpf_verifier_env *env, u32 insn_idx, const char *operation,
 			    const char *reason, const char *suggestion);
+void bpf_diag_report_limit(struct bpf_verifier_env *env, u32 insn_idx, const char *limit,
+			   const char *suggestion, const char *reason_fmt, ...) __printf(5, 6);
 int bpf_diag_record_branch(struct bpf_verifier_env *env, u32 insn_idx, bool cond_true);
 void bpf_diag_record_mod(struct bpf_verifier_env *env, u32 insn_idx,
 			 struct bpf_diag_mod_target target, enum bpf_diag_mod_reason reason,
kernel/bpf/liveness.c +7 -0
index 0aadfbae0acc..9003be0e5fb8 100644
@@ -8,6 +8,8 @@
 #include <linux/slab.h>
 #include <linux/sort.h>
 
+#include "diagnostics.h"
+
 #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
 
 struct per_frame_masks {
@@ -1862,6 +1864,11 @@ static int analyze_subprog(struct bpf_verifier_env *env,
 	if (++env->liveness->subprog_calls > 10000) {
 		verbose(env, "liveness analysis exceeded complexity limit (%d calls)\n",
 			env->liveness->subprog_calls);
+		bpf_diag_report_limit(env, start, "liveness analysis complexity",
+				      "Reduce the number of distinct call paths or argument "
+				      "patterns reaching these subprograms.",
+				      "The verifier recomputed subprogram liveness too many times "
+				      "while tracking stack and register reads across call paths");
 		return -E2BIG;
 	}
 
kernel/bpf/verifier.c +118 -1

188 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#34 lore raw

PATCH v3 16/17 bpf: Report Verifier Internal errors

In reply to Kumar Kartikeya Dwivedi

Augment selected existing internal-error paths with Verifier Internal Error reports. These reports avoid suggesting source-level fixes and instead identify the verifier invariant that failed.

Cover non-overwritten BPF_PTR_POISON helper argument types and inconsistent kfunc graph-node argument classification.

---
 include/linux/bpf_verifier.h | 10 +++++---
 kernel/bpf/diagnostics.c     | 50 ++++++++++++++++++++++++++++++++++++
 kernel/bpf/verifier.c        | 13 +++++-----
 3 files changed, 62 insertions(+), 11 deletions(-)
include/linux/bpf_verifier.h +6 -4
index 625ea3e394a2..a120110aaf3e 100644
@@ -1090,6 +1090,8 @@ __printf(3, 4) void verbose_linfo(struct bpf_verifier_env *env,
 				  u32 insn_off,
 				  const char *prefix_fmt, ...);
 
+__printf(2, 3) void bpf_verifier_log_bug(struct bpf_verifier_env *env, const char *fmt, ...);
+
 #define verifier_bug_if(cond, env, fmt, args...)						\
 	({											\
 		bool __cond = (cond);								\
@@ -1097,10 +1099,10 @@ __printf(3, 4) void verbose_linfo(struct bpf_verifier_env *env,
 			verifier_bug(env, fmt " (" #cond ")", ##args);				\
 		(__cond);									\
 	})
-#define verifier_bug(env, fmt, args...)								\
-	({											\
-		BPF_WARN_ONCE(1, "verifier bug: " fmt "\n", ##args);				\
-		bpf_log(&env->log, "verifier bug: " fmt "\n", ##args);				\
+#define verifier_bug(env, fmt, args...)                              \
+	({                                                           \
+		BPF_WARN_ONCE(1, "verifier bug: " fmt "\n", ##args); \
+		bpf_verifier_log_bug(env, fmt, ##args);              \
 	})
 
 static inline void mark_prune_point(struct bpf_verifier_env *env, int idx)
kernel/bpf/diagnostics.c +50 -0

56 lines not on this page · raw message

kernel/bpf/verifier.c +6 -7
index 552b3d4dd5ae..f7c5beb88217 100644
@@ -8650,9 +8650,8 @@ static int check_reg_type(struct bpf_verifier_env *env, struct bpf_reg_state *re
 				return -EACCES;
 		} else {
 			if (arg_btf_id == BPF_PTR_POISON) {
-				verbose(env, "verifier internal error:");
-				verbose(env, "%s has non-overwritten BPF_PTR_POISON type\n",
-					reg_arg_name(env, argno));
+				verifier_bug(env, "%s has non-overwritten BPF_PTR_POISON type",
+					     reg_arg_name(env, argno));
 				return -EACCES;
 			}
 
@@ -12748,14 +12747,14 @@ static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env,
 		       kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_right]);
 		break;
 	default:
-		verbose(env, "verifier internal error: unexpected graph node argument type %s\n",
-			btf_field_type_name(node_field_type));
+		verifier_bug(env, "unexpected graph node argument type %s",
+			     btf_field_type_name(node_field_type));
 		return false;
 	}
 
 	if (!ret)
-		verbose(env, "verifier internal error: %s node arg for unknown kfunc\n",
-			btf_field_type_name(node_field_type));
+		verifier_bug(env, "%s node arg for unknown kfunc",
+			     btf_field_type_name(node_field_type));
 	return ret;
 }
 
Signature · 1 line
2.53.0
maintainer
#35 lore raw

Re: [PATCH bpf-next v3 16/17] bpf: Report Verifier Internal errors

Quoted 9 lines · Kumar Kartikeya Dwivedi

Augment selected existing internal-error paths with Verifier Internal Error reports. These reports avoid suggesting source-level fixes and instead identify the verifier invariant that failed.

Cover non-overwritten BPF_PTR_POISON helper argument types and inconsistent kfunc graph-node argument classification.

---

Tbh, I don't think this is really necessary. There is not reasonable action a user can take based on the error message, except for reading kernel source and figuring out a workaround. It doesn't matter how nice or not the error is formatted. I'd just drop this patch.

In case you insist on having this as diag_internal_error(), there is no need to have the error report function that logs it two times.

[...]

author maintainer
#36 lore raw

Re: [PATCH bpf-next v3 16/17] bpf: Report Verifier Internal errors

Quoted 11 lines · Eduard Zingerman
Quoted 9 lines · Kumar Kartikeya Dwivedi

Augment selected existing internal-error paths with Verifier Internal Error reports. These reports avoid suggesting source-level fixes and instead identify the verifier invariant that failed.

Cover non-overwritten BPF_PTR_POISON helper argument types and inconsistent kfunc graph-node argument classification.

---

Quoted 8 lines

Tbh, I don't think this is really necessary. There is not reasonable action a user can take based on the error message, except for reading kernel source and figuring out a workaround. It doesn't matter how nice or not the error is formatted. I'd just drop this patch.

In case you insist on having this as diag_internal_error(), there is no need to have the error report function that logs it two times.

Ack, I will drop it.

Quoted 1 line

[...]

author maintainer
#37 lore raw

PATCH v3 17/17 bpf: Gate verifier diagnostics on log level

In reply to Kumar Kartikeya Dwivedi

Verifier diagnostics collect active-path history and render richer reports for selected verifier failures. That work is useful only when the caller requests normal verifier log output.

Do not enable diagnostic collection or report rendering for BPF_LOG_STATS-only loads. Stats-only loads still need the verifier's summary counters, but not the extra path history used by diagnostic reports.

Keep enablement in the verifier environment and requested log mode so async callback verification uses the same diagnostic policy as the main verifier pass.

---
 kernel/bpf/verifier.c | 24 +++++++++++++++---------
 1 file changed, 15 insertions(+), 9 deletions(-)
kernel/bpf/verifier.c +15 -9
index f7c5beb88217..9da36f850748 100644
@@ -5509,7 +5509,9 @@ static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
 	 * of caller's stack as shown on the example above.
 	 */
 	if (idx && subprog[idx].has_tail_call && depth >= 256) {
-		char *chain = bpf_diag_alloc_subprog_call_chain(env, dinfo, idx);
+		char *chain = bpf_diag_enabled(env) ?
+				      bpf_diag_alloc_subprog_call_chain(env, dinfo, idx) :
+				      NULL;
 
 		verbose(env,
 			"tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n",
@@ -5543,11 +5545,12 @@ static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
 		if (subprog_depth > env->max_stack_depth)
 			env->max_stack_depth = subprog_depth;
 		if (subprog_depth > MAX_BPF_STACK) {
-			char *chain;
+			char *chain = NULL;
 
 			verbose(env, "stack size of subprog %d is %d. Too large\n",
 				idx, subprog_depth);
-			chain = bpf_diag_alloc_subprog_call_chain(env, dinfo, idx);
+			if (bpf_diag_enabled(env))
+				chain = bpf_diag_alloc_subprog_call_chain(env, dinfo, idx);
 			bpf_diag_report_limit(env, subprog[idx].start, "subprogram stack depth",
 					      "Reduce stack usage in this subprogram, or move "
 					      "large data out of the BPF stack.",
@@ -5571,9 +5574,10 @@ static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
 			verbose(env, "combined stack size of %d calls is %d. Too large\n",
 				total, depth);
 			{
-				char *chain;
+				char *chain = NULL;
 
-				chain = bpf_diag_alloc_subprog_call_chain(env, dinfo, idx);
+				if (bpf_diag_enabled(env))
+					chain = bpf_diag_alloc_subprog_call_chain(env, dinfo, idx);
 				bpf_diag_report_limit(env, subprog[idx].start,
 						      "combined call stack depth",
 						      "Reduce stack usage or call depth along this "
@@ -5654,11 +5658,12 @@ static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx,
 
 		frame = bpf_subprog_is_global(env, idx) ? 0 : frame + 1;
 		if (frame >= MAX_CALL_FRAMES) {
-			char *chain;
+			char *chain = NULL;
 
 			verbose(env, "the call stack of %d frames is too deep !\n",
 				frame);
-			chain = bpf_diag_alloc_subprog_call_chain(env, dinfo, idx);
+			if (bpf_diag_enabled(env))
+				chain = bpf_diag_alloc_subprog_call_chain(env, dinfo, idx);
 			bpf_diag_report_limit(env, call_insn, "bpf2bpf call frames",
 					      "Reduce the number of nested bpf2bpf calls on this "
 					      "path.",
@@ -9963,11 +9968,12 @@ static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int calls
 	int err;
 
 	if (state->curframe + 1 >= MAX_CALL_FRAMES) {
-		char *chain;
+		char *chain = NULL;
 
 		verbose(env, "the call stack of %d frames is too deep\n",
 			state->curframe + 2);
-		chain = bpf_diag_alloc_state_call_chain(env, state, subprog);
+		if (bpf_diag_enabled(env))
+			chain = bpf_diag_alloc_state_call_chain(env, state, subprog);
 		bpf_diag_report_limit(env, callsite, "bpf2bpf call frames",
 				      "Reduce the number of nested bpf2bpf calls on this path.",
 				      "Call chain %s would create %d verifier call frames, "
Signature · 1 line
2.53.0
#38 lore raw

Re: [PATCH bpf-next v3 17/17] bpf: Gate verifier diagnostics on log level

kernel test robot noticed the following build warnings:

Hi Kumar,

kernel test robot noticed the following build warnings:

[auto build test WARNING on 9a3a07d06e7d74f4aecc51396c771149336ac55d]

url:    https://github.com/intel-lab-lkp/linux/commits/Kumar-Kartikeya-Dwivedi/bpf-Add-verifier-diagnostics-report-helpers/20260713-235352
base:   9a3a07d06e7d74f4aecc51396c771149336ac55d
patch link:    https://lore.kernel.org/r/20260713153910.2556007-18-memxor%40gmail.com
patch subject: [PATCH bpf-next v3 17/17] bpf: Gate verifier diagnostics on log level
config: x86_64-kexec (https://download.01.org/0day-ci/archive/20260714/[email protected]/config)
compiler: clang version 22.1.8 (https://github.com/llvm/llvm-project ca7933e47d3a3451d81e72ac174dcb5aa28b59d1)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260714/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All warnings (new ones prefixed by >>):

kernel/bpf/diagnostics.c:38:40: warning: diagnostic behavior may be improved by adding the 'format(printf, 2, 3)' attribute to the declaration of 'diag_log' [-Wmissing-format-attribute]

      30 | static void diag_log(struct bpf_verifier_env *env, const char *fmt, ...)
         | __attribute__((format(printf, 2, 3))) 
      31 | {
      32 |         va_list args;
      33 | 
      34 |         if (!bpf_diag_enabled(env))
      35 |                 return;
      36 | 
      37 |         va_start(args, fmt);
      38 |         bpf_verifier_vlog(&env->log, fmt, args);
         |                                               ^
   kernel/bpf/diagnostics.c:30:13: note: 'diag_log' declared here
      30 | static void diag_log(struct bpf_verifier_env *env, const char *fmt, ...)
         |             ^
>> kernel/bpf/diagnostics.c:89:48: warning: diagnostic behavior may be improved by adding the 'format(printf, 2, 0)' attribute to the declaration of 'diag_vprint_indented' [-Wmissing-format-attribute]
      82 | static void diag_vprint_indented(struct bpf_verifier_env *env, const char *fmt, va_list args)
         | __attribute__((format(printf, 2, 0))) 
      83 | {
      84 |         char *buf;
      85 | 
      86 |         if (!bpf_diag_enabled(env))
      87 |                 return;
      88 | 
      89 |         buf = kvasprintf(GFP_KERNEL_ACCOUNT, fmt, args);
         |                                                       ^

kernel/bpf/diagnostics.c:82:13: note: 'diag_vprint_indented' declared here
82 | static void diag_vprint_indented(struct bpf_verifier_env *env, const char *fmt, va_list args)
| ^
kernel/bpf/diagnostics.c:130:13: warning: unused function 'diag_report_reason' [-Wunused-function]
130 | static void diag_report_reason(struct bpf_verifier_env *env, const char *fmt, ...)
| ^~~~~~~~~~~~~~~~~~
kernel/bpf/diagnostics.c:144:13: warning: unused function 'diag_report_suggestion' [-Wunused-function]
144 | static void diag_report_suggestion(struct bpf_verifier_env *env, const char *fmt, ...)
| ^~~~~~~~~~~~~~~~~~~~~~
4 warnings generated.

vim +89 kernel/bpf/diagnostics.c

    81	
    82	static void diag_vprint_indented(struct bpf_verifier_env *env, const char *fmt, va_list args)
    83	{
    84		char *buf;
    85	
    86		if (!bpf_diag_enabled(env))
    87			return;
    88	
  > 89		buf = kvasprintf(GFP_KERNEL_ACCOUNT, fmt, args);
    90		if (!buf) {
    91			diag_log(env, "%s<failed to allocate diagnostic text>\n", BPF_DIAG_TEXT_INDENT);
    92			return;
    93		}
    94	
    95		diag_print_wrapped_text(env, buf);
    96		kfree(buf);
    97	}
    98	

--
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

syzbot Tested-by [email protected] on the v3 series
#39 lore raw
In reply to Kumar Kartikeya Dwivedi
syzbot ci has tested the following series

syzbot ci has tested the following series

[v3] Redesign Verification Errors
https://lore.kernel.org/all/[email protected]
* [PATCH bpf-next v3 01/17] bpf: Add verifier diagnostics report helpers
* [PATCH bpf-next v3 02/17] bpf: Add source and instruction diagnostic context
* [PATCH bpf-next v3 03/17] bpf: Add verifier diagnostic event log
* [PATCH bpf-next v3 04/17] bpf: Prune verifier diagnostics when switching paths
* [PATCH bpf-next v3 05/17] bpf: Track verifier register diagnostic events
* [PATCH bpf-next v3 06/17] bpf: Track verifier reference diagnostic events
* [PATCH bpf-next v3 07/17] bpf: Track verifier context diagnostic events
* [PATCH bpf-next v3 08/17] bpf: Report Register Type Safety errors
* [PATCH bpf-next v3 09/17] bpf: Report Memory Safety bounds errors
* [PATCH bpf-next v3 10/17] bpf: Report Resource Lifetime reference leaks
* [PATCH bpf-next v3 11/17] bpf: Report Call Type Safety argument errors
* [PATCH bpf-next v3 12/17] bpf: Report Execution Context Safety errors
* [PATCH bpf-next v3 13/17] bpf: Report Program Structure CFG errors
* [PATCH bpf-next v3 14/17] bpf: Report Policy helper and kfunc errors
* [PATCH bpf-next v3 15/17] bpf: Report Verifier Limit errors
* [PATCH bpf-next v3 16/17] bpf: Report Verifier Internal errors
* [PATCH bpf-next v3 17/17] bpf: Gate verifier diagnostics on log level

and found the following issue:
WARNING in bpf_diag_record_mod

Full report is available here:
https://ci.syzbot.org/series/60c41043-96fb-4c6b-bc8e-3ddab76db3ec

***

WARNING in bpf_diag_record_mod

tree:      bpf-next
URL:       https://kernel.googlesource.com/pub/scm/linux/kernel/git/bpf/bpf-next.git
base:      9a3a07d06e7d74f4aecc51396c771149336ac55d
arch:      amd64
compiler:  Debian clang version 22.1.6 (++20260514074242+fc4aad7b5db3-1~exp1~20260514074407.73), Debian LLD 22.1.6
config:    https://ci.syzbot.org/builds/bb13c0f7-c05e-4ad3-b3f3-365157b560a0/config
syz repro: https://ci.syzbot.org/findings/fa0ac02b-def4-401c-ac09-aea8fa6688a1/syz_repro
------------[ cut here ]------------
1
WARNING: mm/page_alloc.c:5280 at __alloc_frozen_pages_noprof+0x2ce/0x380 mm/page_alloc.c:5280, CPU#0: syz.0.17/5810
Modules linked in:
CPU: 0 UID: 0 PID: 5810 Comm: syz.0.17 Not tainted syzkaller #0 PREEMPT(full) 
Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.2-debian-1.16.2-1 04/01/2014
RIP: 0010:__alloc_frozen_pages_noprof+0x2ce/0x380 mm/page_alloc.c:5280
Code: 74 10 4c 89 e7 89 54 24 0c e8 4e 2c 0e 00 8b 54 24 0c 49 83 3c 24 00 0f 85 ab fe ff ff e9 ac fe ff ff c6 05 74 45 f6 0d 01 90 <0f> 0b 90 e9 17 ff ff ff a9 00 00 08 00 48 8b 4c 24 10 4c 8d 44 24
RSP: 0018:ffffc90003abef40 EFLAGS: 00010246
RAX: ffffc90003abef00 RBX: 000000000000000b RCX: 0000000000000000
RDX: 0000000000000000 RSI: 0000000000000000 RDI: ffffc90003abefa8
RBP: ffffc90003abf040 R08: ffffc90003abefa7 R09: 0000000000000000
R10: ffffc90003abef80 R11: fffff52000757df5 R12: 0000000000000000
R13: 1ffff92000757dec R14: 0000000000440cc0 R15: dffffc0000000000
FS:  00007f71b81f66c0(0000) GS:ffff88818dc0e000(0000) knlGS:0000000000000000
CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 0000001b33463fff CR3: 000000016f8e4000 CR4: 00000000000006f0
Call Trace:
 <TASK>
 alloc_pages_mpol+0x212/0x380 mm/mempolicy.c:2490
 ___kmalloc_large_node+0x4c/0x120 mm/slub.c:5302
 __kmalloc_large_node_noprof+0x18/0x90 mm/slub.c:5333
 __do_kmalloc_node mm/slub.c:5350 [inline]
 __kmalloc_node_track_caller_noprof+0x164/0x730 mm/slub.c:5497
 __do_krealloc mm/slub.c:6865 [inline]
 krealloc_node_align_noprof+0x19a/0x390 mm/slub.c:6886
 _krealloc_array_noprof include/linux/slab.h:1213 [inline]
 diag_append_history kernel/bpf/diagnostics.c:464 [inline]
 bpf_diag_record_mod+0xcbc/0x1590 kernel/bpf/diagnostics.c:1666
 check_alu_op kernel/bpf/verifier.c:16428 [inline]
 do_check_insn+0x1125c/0x1b4a0 kernel/bpf/verifier.c:18578
 do_check kernel/bpf/verifier.c:18817 [inline]
 do_check_common+0x416c/0x5930 kernel/bpf/verifier.c:19902
 do_check_main+0x63/0x1f0 kernel/bpf/verifier.c:19994
 bpf_check+0x25df/0x2cb0 kernel/bpf/verifier.c:21502
 bpf_prog_load+0x13ec/0x1ac0 kernel/bpf/syscall.c:3118
 __sys_bpf+0xd0d/0xd90 kernel/bpf/syscall.c:6339
 __do_sys_bpf kernel/bpf/syscall.c:6458 [inline]
 __se_sys_bpf kernel/bpf/syscall.c:6455 [inline]
 __x64_sys_bpf+0xba/0xd0 kernel/bpf/syscall.c:6455
 do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
 do_syscall_64+0x174/0x580 arch/x86/entry/syscall_64.c:94
 entry_SYSCALL_64_after_hwframe+0x77/0x7f
RIP: 0033:0x7f71b8b9ce59
Code: ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 e8 ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f71b81f6028 EFLAGS: 00000246 ORIG_RAX: 0000000000000141
RAX: ffffffffffffffda RBX: 00007f71b8e15fa0 RCX: 00007f71b8b9ce59
RDX: 0000000000000094 RSI: 0000200000000b00 RDI: 0000000000000005
RBP: 00007f71b8c32e6f R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000000000
R13: 00007f71b8e16038 R14: 00007f71b8e15fa0 R15: 00007ffe3ec24ce8
 </TASK>

***

If these findings have caused you to resend the series or submit a separate fix, please add the following tag to your commit message:

---
This report is generated by a bot. It may contain errors. syzbot ci engineers can be reached at [email protected].

To test a patch for this bug, please reply with #syz test (should be on a separate line).

The patch should be attached to the email.
Note: arguments like custom git repos and branches are not supported.