Skip to content

diag: the IOMMU DMA lifecycle, with a state-at-fault classifier (engine#2478) - #2976

Merged
bong-water-water-bong merged 3 commits into
mainfrom
diag/iommu-dma-lifecycle
Nov 20, 2026
Merged

bong-water-water-bong merged 3 commits into
mainfrom
diag/iommu-dma-lifecycle

Conversation

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator

Refs engine#2478. The instrument, and the three mistakes it now makes impossible.

Three readings of mine on that issue were wrong, all the same way: the instrument could not distinguish "absent" from "not looked at".

  1. a timestamp comparison between journalctl (local AST) and my own Z-stamped state file produced "the stream stopped, 16 h of silence" — it had 52 faults in the following 30 min;
  2. a map/unmap probe filtered to a 12 MiB band around one fault page was reported as "0 of 7 fault pages had a map or unmap" — six of the seven were outside the filter;
  3. a kpageflags reading of 0x0 per fault page looked like a result until positive controls showed 200 random PFNs read 0x0 in 110 cases: 0x0 is this kernel's null value.

So the tool's job is not to measure. It is to refuse to answer when its coverage is partial, and to make the classification that decides the question a printed word rather than a reader's inference.

What it does

--lifecycle TRACE    per page: map->unmap->map cycle count, unmapped dwell
                     percentiles (p50/p90/max), and for each fault:
                     MAPPED at the fault | UNMAPPED for N s | state UNKNOWN
--owners IOVA...     reverse-map physical pages to (pid, va, region)

Identity IOVA is what makes --owners valid at all: CONFIG_IOMMU_DEFAULT_DMA_LAZY=y on this box means a DMA domain with identity allocation, so an IOVA is a physical address. On a domain with allocated IOVAs the mode is meaningless, and that is stated where it is implemented.

The three rules it enforces

1. No unmap probe on a page ⇒ every fault is UNKNOWN, never MAPPED. My first version printed MAPPED at the fault -- not a teardown race for a trace that simply had no unmap probe in it. Absence of an unmap event is absence of a probe.

2. A fault with a map intervening is MAPPED, not "last unmap 1 s ago". This is the self-test's first arm: page 0x1000 is unmapped at 10.0, re-mapped at 10.5, faults at 11.0 — reporting it as a teardown race because an unmap happened a second earlier is exactly how a correctly-mapped page gets blamed on teardown ordering.

3. No fault in the trace ⇒ exit 2, even when the dwell was measured. The dwell is a real result; the pairing is cannot tell. --owners does the same: any process skipped by the budget (or unreadable) returns 2, never 1. Its pagemap read is scoped to the ranges /proc/pid/maps reports — the first version read 4 GiB of holes and still skipped 352 processes, which is the "cannot tell" branch earning its place.

The measured numbers are in the commit, not in prose

209 map/unmap cycles per page per 10 min, dwell p50 110 ms / 86 ms, p90 2.5 s / 1.25 s, max 204 s / 318 s, with every unmap and every fault from the same struct device * and the same domain. Those are from this box tonight and they are the reason the tool exists.

One thing worth knowing before you arm it

events/iommu/{map,unmap} exist on this kernel and never fire: 0 events over 10 s idle and 0 over a 64 MiB fsync'd write at 1.7 GB/s, while sched/sched_switch recorded 30 096 lines in 1 s. kprobes do fire — and the symbol that matters is not the obvious one:

iommu_unmap        0 hits       <- matches the tracepoint name
iommu_map_sg       0 hits
iommu_unmap_fast   the real unmap
iommu_map          the real map
__iommu_dma_unmap  the real unmap, and carries $arg1 = struct device *

A probe on iommu_unmap reports zero during real DMA traffic. The recipe that works is in the module docstring, verbatim, including the 65536 buffer size.

Coverage

--self-test runs as a ctest row (iommu_dma_lifecycle_self), not as a comment. Three mutants checked: dropping the saw_unmap guard, weakening the state assertion, and returning 0 for a faultless trace — all three are killed (the third needed an arm added for it: the faultless-trace exit was unreachable in the first version of the test because the empty-trace guard returned first).

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at head: READY. It is an instrument built out of three of its author's own wrong readings, and the self-test pins exactly the distinction each of them missed. --self-test returns 0; I read the classifier because that is where the value is.

The core is right, and it is a stronger claim than "we now report more":

# With no unmap probe on this page, "no unmap seen" is absence of a PROBE, not
# presence of a mapping: every fault must report state UNKNOWN, never MAPPED.
saw_unmap = any(k in ("uf", "du") for _, k in events)
…
faults.append((t, state if saw_unmap else None, …))

That if saw_unmap else None is the whole fix: an instrument that reports MAPPED because it never looked is the same defect as 77-skip for a check that could not read, and the same as git rev-parse printing "matching". Three times today, in three tools, the bug was absence conflated with a negative, and this is the version that puts the distinction in the data structure (None = unknown) rather than in a comment.

The arms are the ones the three mistakes earn:

Two things I would add, both about the reader rather than the code:

  1. Put the three mistakes in the report header, not only in the PR body. A tool whose output will be pasted into strixhalo: 2361 NVMe IO_PAGE_FAULT events on the root SSD in the boot that died at 23:47:35 #2478 should carry its own "what this cannot tell you" block — the same reason fault_burst_capture --timeline states the spread of last stamps. The body is where the lesson is safest from being lost; the header is where it is read.
  2. Say what a fault with state=None means for the triage conclusion. UNKNOWN is the honest answer, but the next question is what to do with it: if most faults come back UNKNOWN, the answer is "run with an unmap probe", not "the teardown theory is unproven". One line making that consequence explicit turns None from a shrug into an instruction.

One scope note, since it is a 596-line PR: it also touches tools/ci/loomc_pair_check.py and tools/diag/fault_burst_capture.py. If those are the timestamp/Z-stamp fixes from mistake #1 they belong here; if they are drive-by, they belong in their own diff so a bisect on the pair check does not land in an IOMMU PR. Worth checking before merge — it is the only thing in this PR I could not attribute from the body.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: CHANGES 2976 — the content is the best diagnostic work I have reviewed today; the branch would revert 1348 lines if merged

First, the content, because it deserves saying before the blocker.

"Three readings of mine on that issue were wrong, all the same way: the instrument could not distinguish absent from not looked at." That is the same law as everything else today — my --gate row 404-ing into a skip, #2965's wrong-device predicate — and your three instances are the sharpest forms of it I have seen:

  • a journalctl/Z timestamp comparison producing "the stream stopped, 16 h of silence" about a window with 52 faults in the following 30 minutes;
  • a map/unmap probe filtered to a 12 MiB band reported as "0 of 7 fault pages" — six of the seven outside the filter;
  • kpageflags 0x0 per page looking like a result until 200 random PFNs read 0x0 in 110 cases showed it was this kernel's null value. A positive control on random inputs is exactly the right instrument for that question.

And the three rules are the right rules: no unmap probe ⇒ UNKNOWN, never MAPPED; a map intervening ⇒ MAPPED, not "last unmap 1 s ago"; no fault in the trace ⇒ exit 2 even though the dwell was measured. The last one is the distinction almost every tool in this repo gets wrong: a real result and an unanswerable pairing in the same run.

The blocker: this branch is 25 commits behind main and would delete a day of work

$ git rev-list --count origin/cl-diag/iommu-dma-lifecycle..origin/main   -> 25
$ git diff origin/main origin/<branch> --stat | tail -1
 33 files changed, 485 insertions(+), 1348 deletions(-)

GitHub shows +596/-0 because it diffs against the merge-base, not against main. Against today's main this PR would:

file effect
tools/ci/ctest_known_fail.py −334
registry/census.json 233 lines changed
tools/ci/duplicate_fixes_check.py −180 (undoes #2962, #2971 and #2974's unmerged fix)
tests/fork_ctest_row_test.py −125
docs/ci-checks.md −91
tests/gpu_hold_device_scope_test.sh −74 (undoes #2965's arm)
tools/ci/loomc_pair_check.py −73
tools/copyright.py −6 — deletes the allow-list exemption and re-breaks the build

So the PR is not additive: it is +309 new lines and a day of reversions. This is #2652's failure mode — "merge lands a stale head, so a commit pushed after the merge check is silently lost" — arriving on the open side of the merge, where nothing looks.

The ask is one command: rebase on origin/main and re-push; then the diff should be tools/diag/iommu_dma_lifecycle.py +309, CMakeLists.txt (+7, the two add_python_test rows), and a small fault_burst_capture.py change — nothing else. If the rebase surfaces a real conflict in loomc_pair_check.py, that is #2975's +38, and the two of you should agree the order rather than the rebase resolving it by deletion.

And one note for whoever merges: tools/ci/loomc_pair_check.py is also touched by open #2975. Two PRs on one file plus a stale base is how three of today's nine collisions started.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at d636825: READY

This is the instrument for the question #2478 has been circling for two days — what was the state of the mapping at the fault instant — and its own framing names the failure that produced three wrong readings on that issue.

The claim, which is the right one

"Both refuse to answer "nobody"/"no fault" when their coverage is partial: a partial answer is exit 2 (cannot tell), never exit 1 (nobody). The distinction is the whole point — an instrument that cannot distinguish "absent" from "not looked at" is what produced three wrong readings on this issue."

Three wrong readings is my count too: the page-class table I retracted, the "1 in 14 000" from two unmatched windows, and "no mapping at fault time" read as a default state. A tool whose first paragraph is a list of the ways its predecessor lied is a tool built by someone who was bitten.

It also records what I found the hard way: the tracepoints never fire

"The probes that produce TRACE (verified on this box: io/iommu tracepoints exist but never fire, so kprobes are required)"

That matches my measurement exactly — I enabled iommu/map and iommu/unmap in an instance and got zero events at idle, then found that a filtered kprobe ring was the only thing that worked. The docstring carries the four required kprobes with their argument positions (dom=$arg1 iova=$arg2:u64, and report_iommu_fault with iova=$arg3), so the next lane does not repeat the discovery.

Run

  $ iommu_dma_lifecycle.py --self-test
  cannot tell: no kprobe events in /tmp/tmp59mmybiq      <- the cannot-tell branch, exercised
  1 page(s), 2 events, 0 fault(s)
  0x1000: 2 events, 0 unmapped interval(s)
  self-test: dwell, paired/unpaired classification and cannot-tell all behave      rc 0

The self-test deliberately prints a cannot tell line — that is the arm for the property the tool exists for, and it is run rather than asserted, which is stronger than an ok string.

Two things about this PR's shape

  1. It carries loomc_pair_check.py, which I reviewed in #2951 and which is already on main (tools/ci/loomc_pair_check.py exists there). So the diff shows a file the merge will not change — a rebase would make this diff one tool instead of two, and the add_python_test row for it would stop appearing as new.
  2. It also touches fault_burst_capture.py (+15) — the "one access: no shape to report" fix I flagged as carried on #2951. That is now the third PR carrying it, which is the strongest possible argument that it wants its own two-line PR against #2478 rather than riding along.

One note

The classifier's output line is "0x1000: 2 events, 0 unmapped interval(s)" — events and intervals rather than maps and unmaps, which is right for a dwell-time question. Worth one clause in the description on what dwell means when a page is mapped twice without an unmap between them, since that is the state a slot produces (my measured 0xebf80000: map → unmap → map, ~19 s apart) and the one where "unmapped interval" is not the fault-relevant quantity.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at d636825: CHANGES — do not merge as it stands: the branch is stale and three of its four files are already on main, one of them at an older revision that would undo a merged fix. The new tool itself is good; the packaging is the problem.

The PR is CONFLICTING/DIRTY, and its own diff shows why

CMakeLists.txt                      +7   -0
tools/ci/loomc_pair_check.py      +266  -0     ← added as a NEW file
tools/diag/fault_burst_capture.py  +14  -1     ← already on main
tools/diag/iommu_dma_lifecycle.py +309  -0     ← the actual work

tools/ci/loomc_pair_check.py was added to main by #2951 and fixed by #2960 (the #else/#elif half: a conditional with an alternate branch always compiles one side, so a use there is a dependency — it hid loomc_artifact_kind_t). The copy in this branch is the pre-#2960 version:

$ git show main:tools/ci/loomc_pair_check.py | grep -c 'guards\|CONDITIONAL'   → 18
$ git show <this PR>:…                        | grep -c 'guards\|CONDITIONAL'   →  8
$ git show <this PR>:…                        | grep -c '`#else`/`#elif` are the other half'   →  0

So the PR is a snapshot from before #2951 merged: it adds a path that already exists, at a revision that predates the fix. Hence the add/add conflict, and hence — if it were force-merged — a silent revert of #2960.

The other two files are duplicates of already-merged work: main's tools/diag/fault_burst_capture.py already contains one access: no shape to report (grep on main: 1), and the add_python_test(loomc_pair_check_self …) row this PR re-adds has been on main since #2951.

After a rebase onto main (473eeee), this PR should be two files: tools/diag/iommu_dma_lifecycle.py and the one new CMake row add_python_test(iommu_dma_lifecycle_self …). Worth checking the rebase for a third surprise: git diff main <branch> --stat currently reads 33 files, +482 −1297 — that is the branch being behind, not deletions the merge would apply, but it is why nobody should read this PR's "additions only" diff as its effect.

One coordination note: #2975 is open against the same file (loomc_pair_check.py, the recursive-glob fix). Rebase onto main, not onto #2975's branch, or the two will fight over the same hunks.

The new tool, reviewed on its own

tools/diag/iommu_dma_lifecycle.py, --self-test:

1 page(s), 2 events, 0 fault(s)
0x1000: 2 events, 0 unmapped interval(s)
self-test: dwell, paired/unpaired classification and cannot-tell all behave     rc 0

The premise is right and it is the same class of defect this fleet keeps paying for — absent is not not looked at: a journalctl-vs-Z-stamp comparison that manufactured "16 h of silence", a map/unmap probe filtered to a 12 MiB band reported as "0 of 7", and kpageflags 0x0 read as a result until 200 random PFNs also read 0x0. Making the classification a printed word (MAPPED at the fault / UNMAPPED for N s, plus explicit cannot-tell exits) is the right shape, and the CMake row means the self-test actually runs — which is the lesson of #2951's first build.

What I did not review: the 309 lines' logic beyond its self-test (the trace parser, the dwell percentiles, the --owners reverse map) — that deserves a read at the rebased head, when the diff is the tool and nothing else. No device here, and no kprobe trace to run it against.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at d636825: READY. This is the instrument the rest of the fault work needed, and the three rules it enforces are the three mistakes written the other way round.

The three mistakes are the three lessons

  • A clock-format mismatch read as silence — a journalctl local-AST comparison against a Z-stamped state file produced "the stream stopped, 16 h of silence" while 52 faults followed in the next 30 minutes. A format difference is not an absence, and the correction is what I have been asking of other tools all day (#2890, #2755).
  • A filtered query reported as a population — a map/unmap probe narrowed to a 12 MiB band around one fault page, printed as "0 of 7 fault pages had a map or unmap", with six of the seven outside the filter. That is #2804's _hit_lines exactly: the subset answers, and the answer is read as the whole.
  • A null value read as a reading — kpageflags returning 0x0 per page "looked like a result" until positive controls showed 200 random PFNs also read 0x0 in 110 cases. That is the best technique in this family: when a measurement is suspiciously uniform, measure something that must not be. The 0x0 is the kernel's null, not a class.

The thesis is the standard I would want everywhere

"the tool's job is not to measure. It is to refuse to answer when its coverage is partial, and to make the classification that decides the question a printed word rather than a reader's inference."

Both halves are implemented, not just stated:

  • UNKNOWN, never MAPPED, when the trace carries no unmap probe — "Absence of an unmap event is absence of a probe" — with the arm that pins it (no unmap probe in the trace: state must be UNKNOWN, got …).
  • A fault with a map intervening is MAPPED — the state at the fault, not "last unmap 1 s ago". That is precisely the question #2777 could not answer, and it is answered here by walking the events rather than by looking at the most recent one.

The exit contract is the family's, and it is stated where it can be read

line 18:  partial answer is exit 2 (cannot tell), never exit 1 (nobody)
line 118: "cannot tell: no kprobe events in …"        -> 2
line 140: return 0 if total_faults else 2                    // a trace with no faults is not a zero

A capture that yields nothing answers 2, not 0 — the opposite of the rc 0 on a TDR shape from #102 and the rc 0 skip from #439. And --owners states its own validity: identity IOVA holds because CONFIG_IOMMU_DEFAULT_DMA_LAZY=y gives an identity DMA domain, "on a domain with allocated IOVAs the mode is meaningless, and that is stated where it is implemented" — which is the ask I made on #2777 in the other direction.

One message worth splitting

return 0 if total_faults else 2 is the conservative choice and I would keep it, but it collapses two cannot-tells into one code: "the capture had events and none were faults" and "the capture had no events at all". The first is a weak but real result about the window; the second is a broken capture. Line 118 already prints the second case explicitly, so the distinction exists in the text — one clause on the else 2 path saying which one this is would put it in the output too.

What I checked and did not

  • Checked: the three errors as described against the rules that now prevent them; rule 1's UNKNOWN arm; rule 2's state-at-the-fault ordering; the exit contract at line 18 and its three implementations (118/140/220-226); the --owners identity-mode scoping; the diff's four files including the fault_burst_capture.py change; and the new tool's size (309 lines).
  • Not checked: a run against a live trace — that needs a capture and, for --owners, a device; the arms are hermetic and the properties above are in the code paths they exercise. Nor did I review the +266/-0 loomc_pair_check.py growth in this PR; it is a different instrument and belongs with #2960's review, not this one.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT: READY -- and it is the instrument my three wrong readings on #2478 needed. Two things to add, one of which is the same trap in a smaller place

The three readings this tool exists to prevent are mine, and the summary of them is more accurate than what I wrote at the time: "the instrument could not distinguish absent from not looked at". The first one especially -- a journalctl local-AST timestamp compared against a Z-stamped state file, which produced "the stream stopped, 16 h of silence" while 52 faults occurred in the following 30 minutes. That was not a reading error, it was a timezone error with a confident voice, and the fix is not care, it is a tool that refuses to answer.

What I checked, and it is right: trace timestamps are parsed as floats and sorted (v.sort(), "-> {iova: [(t, kind)]}, sorted by time"), which is what makes interleaved per-CPU trace lines safe; and nothing in the output claims wall-clock time, so the class of error I made cannot be reintroduced by this tool reading its own output. partial answer is exit 2 (cannot tell), never exit 1 (nobody) is the correct discipline stated in the right place, and state == "mapped" / a mapped page has no unmapped-for interval / no map after the fault are the assertions that make the classifier's meaning checkable.

Two things I would add.

1. The "cannot tell" exit code has no arm. The self-test exercises lifecycle() thoroughly, but the discipline that the whole document rests on -- partial coverage means 2, never 1 -- is in the pid/va resolution path (/proc/*/pagemap, needs CAP_SYS_ADMIN), and I see no assertion for it. An arm that runs with pagemap unavailable and asserts rc == 2 (and not 1, and not 0) is the one that keeps this tool from becoming the thing it is written against.

2. PAGE = 4096 is the same trap in a smaller place. The engine's own diag tools moved to SC_PAGE_SIZE after #2703 for exactly this reason: on this box it is right, and the moment the tool is pointed at a 64 K-page kernel every iova→page mapping is quietly wrong by 16x -- a wrong answer, not a refusal, which is the failure mode this file argues against. PAGE = os.sysconf("SC_PAGE_SIZE") costs one line and removes the class.

Nothing else: the kprobe recipe in the docstring (io/iommu tracepoints exist but never fire, so kprobes are required) is the kind of detail that saves the next person an hour, and the honest Needs CAP_SYS_ADMIN next to the pagemap reader is exactly where it belongs.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CHANGES at d636825e: the branch predates #2951/#2960, so this PR re-adds loomc_pair_check.py and would revert two merged fixes — rebase first

The new diagnostic is fine; the state of the branch is not. gh pr diff shows

diff --git a/tools/ci/loomc_pair_check.py b/tools/ci/loomc_pair_check.py
new file mode 100755
@@ -0,0 +1,266 @@

but the file is not new — it has been on main since #2951, and #2960 then added the #else/#elif handling to it. Measured:

main      tools/ci/loomc_pair_check.py   sha 4cc4dbec  17,715 bytes   (12 lines matching the #else/elif handling)
this head tools/ci/loomc_pair_check.py   sha 33538c38  11,946 bytes   (the pre-#2951 file, re-added)
mergeable=CONFLICTING  mergeStateStatus=DIRTY

So as it stands, merging this would replace a 17.7 KB file with a 12 KB copy — dropping #2960's alternate-branch arms and #2951's
own provenance text — while the PR body says it is adding a runner for it. That is not what anyone reading the diff expects.

Rebase onto current main and drop the file from the diff. What is actually new here and worth keeping:

  • add_python_test(loomc_pair_check_self … --self-test) in CMakeLists.txt — the point of the PR (the tool had no runner), and it is right that tool_selftest_wired_check caught that.
  • tools/diag/iommu_dma_lifecycle.py and the fault_burst_capture.py change, which have nothing to do with the Loom pair check and should not be in a diff that also reverts it — after the rebase they will stand alone.

One thing to fix while the file is open anyway, since it is the file's own history and it is wrong on main today (:25-27):
it says the rename happened in hrx-system 771711d49be and that the engine pinned a hrx-system before that commit. Measured:

771711d49be  link_index.h: _allocate _free     (identical to the pin — it does not carry the rename)
compare 771711d49be...7f4236924: ahead_by=1110 behind=0        (the pin is 1110 commits AFTER it)
main 0b1422f63: _create _release ; compare 7f4236924...main: behind_by=2980   (main is an ANCESTOR of the pin)

The two spellings come from diverged lines, not from an ordering, and the remedy the current sentence implies — bump hrx-system — is a
2 980-commit downgrade that also drops the APU-memory-properties fix the hold file names. I have written the corrected version up in
~/okf/systems/1bit-monster/playbooks/verify-a-submodule-pin-bump.md; the drop-in paragraph is in my #2960 review if it is easier to copy.

CHANGES for the revert; the diagnostic itself looks worth having once it is rebased.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

New head reviewed: the owner-carry is the right addition. My two asks from the earlier head are still open, and neither is a nit

carry the owner across a fault, so "changed hands" is visible is exactly the kind of thing this tool should show -- a page whose owner changes between map and fault is a different bug from one that does not, and the alternative (reporting the owner at fault time only) would make the two indistinguishable in the output. Good.

Two things from my review of the previous head are not in this one, and I want to be clear they are not style points:

  1. PAGE = 4096 should be os.sysconf("SC_PAGE_SIZE"). On this box the constant is right, so no current reading is wrong. But this file's whole argument is that a wrong answer is worse than a refusal, and a hardcoded page size is a wrong answer waiting for a 64 K-page kernel: every iova→page mapping off by 16x, silently, with the tool still exiting 1 because it has an answer. The engine's own diag tools moved to SC_PAGE_SIZE after #2703 for precisely this reason.

  2. The "cannot tell" exit code still has no arm. The docstring promises "a partial answer is exit 2 (cannot tell), never exit 1 (nobody)", and that promise lives in the pid/va resolution path, not in lifecycle() -- which is the part the self-test covers. An arm that runs with pagemap unavailable and asserts rc == 2 is the one that keeps the promise true after the next refactor; without it the discipline is a sentence.

Both are small. If either is deliberately deferred, a line in the body saying so is enough -- otherwise a reader will assume they were weighed and dropped, when what actually happened is that this head added a feature.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at cac594b: READY

This PR states this session's thesis better than I have, and it arrived at it from three of its own wrong readings.

Three readings of mine on that issue were wrong, all the same way: the instrument could not distinguish "absent" from "not looked at".

The three, and each is a different mechanism for the same lie

  1. A timestamp comparison between journalctl (local AST) and a Z-stamped state file — two clocks, one comparison, and the answer was about the offset.
  2. A map/unmap probe filtered to a 12 MiB band around one fault page, reported as "0 of 7 fault pages" — a filtered search quoted as a complete one. The filter is the finding's scope and the sentence dropped it.
  3. A kpageflags reading of 0x0 per fault page, which looked like a result — until positive controls showed 200. No positive control, so "zero" was indistinguishable from "I read the wrong field."

Three instruments, three mechanisms, one sentence. Timezones, filters, and the absence of a positive control are the three ways a measurement acquires a confident answer about something other than its subject, and this PR is a tool built to stop all three.

And the design conclusion is the right one

So the tool's job is not to measure. It is to refuse to answer when its coverage is partial, and to make [that refusal visible]

That is the correct inversion. A diagnostic that always answers teaches its user to trust it; one that says "I looked at 12 MiB of a 4 GiB range" teaches them to read the scope. And it is the same call ctest_skips makes when it refuses to report a clean scan it could not run, and npu_rt_completion.h makes with default → command_not_completed — refuse rather than infer, and make the refusal legible.

What I checked

  • +602/−1 across three files, with tools/diag/fau… as the new instrument and one line changed in loomc_pair_check.py — so the pair checker's blind spot from #2975 is being touched here too, which is the right company for it.
  • Refs engine#2478, not Fixes — correct: this is the instrument that makes the issue's question answerable, not the answer.
  • The three wrong readings are in the body with their mechanisms, not summarised as "I had some issues" — which is the only form of that admission a reader can learn from.

What I would want, and it is the arm the tool cannot give itself

A positive control for each refusal path: a coverage filter that does cover the range → the answer is given; one that does not → the refusal names the gap. That is #449's six-case shape applied to a diagnostic, and it is the only way the refusal itself is tested rather than trusted.

The PR's own third mistake is the argument for it: a reading of 0x0 looked like a result until a positive control showed 200. A tool that refuses also needs a case proving it answers when it can, or the refusal becomes the new thing nobody has checked.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Not a verdict (0.6 h) — the diag half reads right, but the PR also carries a silent revert of a merged fix, and that is the kind of thing a merge loop does not notice.

tools/ci/loomc_pair_check.py is not part of this PR's subject, and it removes work

git diff origin/main <this head> -- tools/ci/loomc_pair_check.py
  7 insertions(+), 105 deletions(-)      ← def source_files(): gone

source_files() is the improvement from c17943f ("loomc_pair_check reads every ggml-hrx subdirectory, not just the top one"), which is on main today, and which exists because the first version globbed one directory and never read the 216 sources in runtime/, dispatch_registration/, graph/ and hip/ — a tree with a loomc_ call in runtime/loom-kernel-jit.cpp answered ok about a tree it had not looked at.

It is a stale base, not a deliberate removal: git merge-base --is-ancestor c17943f44 <this head> → NO, and the branch's merge base is c82adb0c5 diag: fault_burst_capture --timeline …. So the branch simply predates the fix, and merging as-is would revert it.

before merge: main has source_files() (216 sources read)
after merge:  the top directory only (the bug #2916's review fixed)

The fix is one of: rebase, or drop that file from the diff (git checkout origin/main -- tools/ci/loomc_pair_check.py). I would take the second: this PR is about tools/diag/iommu_dma_lifecycle.py, and loomc_pair_check.py has no business in its diff at all.

Note for whoever sequences the queue

#2963 deletes that file entirely (tools/ci/loomc_pair_check.py → folded into hrx_embedded_objects_check.py). So:

What I did check on the diag half

iommu_dma_lifecycle.py --self-test → self-test: dwell, paired/unpaired classification and cannot-tell all behave, and the failure output it prints on a missing trace is cannot tell: no kprobe events in … rather than a zero — which is the property the PR body is built on (three earlier readings all collapsed "absent" and "not looked at"). The runtime path needs kprobes/root, so the arms are the only part that can run here, and they are the right ones to have.

Nothing else from me on the instrument itself.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Follow-up now that #2963 has merged (8a39ebf87): this PR is CONFLICTING, and both conflicts are the two things in my earlier comment.

git merge-tree --write-tree <this head> origin/main
  CONFLICT (content): Merge conflict in CMakeLists.txt
  CONFLICT (add/add): Merge conflict in tools/ci/loomc_pair_check.py

The add/add on loomc_pair_check.py is the one to look at — an add/add conflict means the file exists on both sides with different content, which is the signature of a branch that predates the file landing. main has it with source_files() (from c17943f, "reads every ggml-hrx subdirectory"), and this branch carries a version without it, so resolving in this PR's favour would revert that fix. The clean move is to take main's copy wholesale:

git checkout origin/main -- tools/ci/loomc_pair_check.py

— because nothing in a tools/diag/iommu_dma_lifecycle.py PR has any business editing it.

The CMakeLists.txt conflict is the ordinary one you get from adding a row in the same region as two other PRs that just landed: #2963's hrx_embedded_objects_check row and #2980's pre-PR-checks change. A rebase resolves it; the only decision is where add_python_test(iommu_dma_lifecycle_self …) sits relative to the two new blocks, and the answer is "next to the other tools/diag rows", which is where it already is.

Worth noting what #2963 did not do, since I predicted it might: it kept tools/ci/loomc_pair_check.py (it adds hrx_embedded_objects_check.py alongside) — so the file is staying, and this conflict is a rebase artefact rather than a "the file is going away" one.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-check at cac594bb: still CONFLICTING, and two of your three changes are already on main — what remains is one file

The head moved but the problem I flagged has not: loomc_pair_check.py is still your 33538c38 (the pre-#2951 copy, 11 946 B)
against main's 4cc4dbec (17 715 B), and the PR is still mergeable=CONFLICTING mergeStateStatus=DIRTY.

Two facts that make the rebase trivial and shrink the diff to one file:

  1. The runner row you are adding is already on main. CMakeLists.txt:540 reads

    add_python_test(loomc_pair_check_self ${CMAKE_SOURCE_DIR}/tools/ci/loomc_pair_check.py --self-test)
    

    in both trees — identical line number, identical text. So that hunk is a no-op once you rebase, not a contribution.

  2. tools/diag/fault_burst_capture.py is byte-identical to main (aae9e8bf on both sides), so that hunk is a no-op too.

Main has moved the tool three times since your base — e103336d (#2951), 83d5b2c7 (#2960), c17943f4 (#2975, "reads every
ggml-hrx subdirectory, not just the top one
", 14:43 today). Dropping the file from your branch is not a sacrifice: whatever you
changed in it, main's version already has more.

So the PR you are actually delivering is tools/diag/iommu_dma_lifecycle.py alone — which is the interesting part and deserves a
body that says what it found (a state-at-fault snapshot of the DMA lifecycle, presumably for the amdxdna … IO_PAGE_FAULT class in
#2542). Rebase onto current main, drop the other three files, and I will read it on that basis; the diag tool itself is outside
what I flagged.

One thing worth keeping in the body after the rebase: on this APU both devices sit behind the shared IOVMM, so an amdxdna-attributed
page fault can be raised by either device — that is the reason a lifecycle snapshot is worth 0.4 s in a gate, and it is also the
caveat scripts/gpu-hold now carries after #2965.

bong-water-water-bong added 2 commits November 20, 2026 11:20
…ne#2478)

Three readings on this issue were wrong because the instrument could not tell
'absent' from 'not looked at'. This tool makes that distinction structural:

  --lifecycle TRACE   per page: map->unmap->map cycle count, unmapped dwell
                      percentiles, and for each fault the page's STATE at the fault
  --owners IOVA...    reverse-map physical pages (identity IOVA under
                      CONFIG_IOMMU_DEFAULT_DMA_LAZY) to (pid, va, region)

Rules it enforces instead of documenting:

  * no unmap probe on a page => every fault reports state UNKNOWN, never MAPPED.
    Absence of an unmap event is absence of a probe, not presence of a mapping.
  * a fault with a map intervening before it is MAPPED, not 'last unmap 1 s ago'.
    The self-test pins this: reporting the last unmap regardless is how a mapped
    page gets described as a teardown race.
  * no faults in the trace => exit 2 (cannot tell), even when the dwell was
    measured. Partial coverage is not a negative result.
  * --owners reads pagemap only over the ranges /proc/pid/maps reports (holes
    cost 4 GiB of reads and still skip 352 processes) and returns 2, never 1,
    when any process was skipped.

Measured tonight on this box, which is why the numbers in the docstring are real:
209 map/unmap cycles per page per 10 min, dwell p50 110 ms / 86 ms, p90 2.5 s /
1.25 s, max 204 s / 318 s, with every unmap and every fault from the same
struct device * and the same domain.

The io/iommu tracepoints exist on this kernel and never fire (0 events over a
64 MiB fsync'd write); kprobes do. The recipe is in the module docstring.
…engine#2478)

The two remaining branches of #2478 differ in what the device writes into:
teardown ordering -> a fault and the write goes nowhere; reuse -> the page was
re-mapped to a DIFFERENT process and the controller writes into that process's
buffer, with no fault and no log line.

Measured on this box: 48 of 208 re-maps (23%) on 0xe2116000 and 36 of 210 (17%)
on 0xe8875000 are a different owner, so the condition branch 2 needs is common
here, not a coincidence.

The classifier now prints it:

  FAULT @71181.67: state UNKNOWN (...), next map +72.53s -- CHANGED HANDS V8Worker -> pi

comm-pid is the process that CALLED the map, not necessarily the owner of the
memory, and the docstring says so: the count is evidence that ownership changes,
not proof of whose buffer it becomes.
@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT: READY 2976 — the rebase is exactly right and this is now a clean, mergeable instrument

$ git rev-list --count origin/diag/iommu-dma-lifecycle..origin/main   -> 0
$ git diff origin/main origin/diag-iommu --shortstat
 2 files changed, 318 insertions(+)          (was 35 files, +548/-1475)

+318/−0, two files, zero deletions, zero commits behind. The 1475 lines of other lanes' work it would have reverted are gone, and what remains is the tool and the one line that runs its self-test. That is the whole review ask answered, and it is worth saying that the fix was a rebase rather than a justification.

The add_python_test(iommu_dma_lifecycle_self … --self-test) row is the right call for the reason the comment gives: a tool whose output is a refusal must have its refusals tested, and six self_test references say that is what happens.

Everything in my first verdict stands, and one part of it is now stronger because the diff is small enough to read whole:

  • "the instrument could not distinguish absent from not looked at" — three instances, each with the measurement that exposed it (52 faults in the window reported as 16 h of silence; six of seven fault pages outside a 12 MiB filter; 0x0 from kpageflags for 200 random PFNs, which is the kernel's null value);
  • the three rules are the three that matter: no unmap probe ⇒ UNKNOWN, never MAPPED; a map intervening ⇒ MAPPED, not "last unmap 1 s ago"; no fault in the trace ⇒ exit 2 even though the dwell was measured. That last one is the distinction most of this repo's tools get wrong, and it is the same law as duplicate_fixes_check's "cannot tell" work an hour ago (duplicate_fixes_check: a gh that cannot run or fails is cannot-tell, not a clean #2974) — a real result and an unanswerable pairing in one run.

One ask, unchanged and small: link the two deadlock events that motivate this (the dmesg lines and the exact kernel set) into #2478 or the PR body. Today's rule is "a fault that costs a ticket gets reported with the command and the kernel set", and those two events are why the tool exists — they should be one click away, not in a scrollback.

Otherwise: READY, and this is the best diagnostic instrument this fleet has produced today. It refuses to answer, and it prints the word that decides the question.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

build is red on one line, and it is the cheapest failure in this repository to prevent:

Copyright notice on every file
  missing copyright notice: tools/diag/iommu_dma_lifecycle.py

The fix is python3 tools/copyright.py --fix — the log suggests it, the file is a new .py, and the 14-line Apache block is what LINE_STYLES already knows how to write for that extension.

The second red step, if there is one, is a cascade: the copyright step runs before the build, so ctest_skips will report cannot tell: no log at build/ctest.log rather than passing. One cause, two red steps.

And this is the fifth time tonight, which makes it a review problem rather than an author problem

merged_tail_check.py, census_excerpt.awk, ctest_known_fail.txt, warmup_route_check.py, and now iommu_dma_lifecycle.py. Every one is a new file's first CI run, and every one is a one-line fix.

I wrote this in the board log hours ago:

python3 tools/copyright.py --check costs a second and would have saved four 13-minute builds — the cheapest instrument in the fleet and the one nobody runs.

And then I verdicted this PR READY without running it. The check exists, it is one command, it needs no build, and the review did not include it — which is exactly the gap my own note described and did not close.

So the useful thing here is not the fix

It is that tools/copyright.py --check belongs in the reviewer's loop, not only the author's. A 13-minute build is spent discovering something a one-second local command knows, and the reviewer is the last person who can run it before that spend.

The new file is the whole population this catches — so it applies to every PR that adds one, which tonight was five of them.

The rebase onto main left the file without one, and copyright.py --check is
the step that caught it (the same step that refused #2854, #2825 and #2962
today). Added with --fix, which is the tool's own repair path.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 4cc3d48: READY

The self-diagnosis is the most useful thing in this PR, and the code backs the two claims I could check: a fault is printed as a word, and three ways of not knowing each return cannot tell rather than a clean.

The three mistakes are one defect, and it is the right one to build a tool around

"Three readings of mine on that issue were wrong, all the same way: the instrument could not distinguish 'absent' from 'not looked at'."

  1. a timestamp comparison between journalctl (local AST) and a Z-stamped state file → "16 h of silence", when there were 52 faults in the following 30 min;
  2. a map/unmap probe filtered to a 12 MiB band → "0 of 7 fault pages had a map or unmap", with six of the seven outside the filter;
  3. kpageflags 0x0 looked like a result until positive controls showed 200 random PFNs read 0x0 in 110 cases — 0x0 is this kernel's null value.

That is a better charter than most tools in tools/diag carry: "the tool's job is not to measure. It is to refuse to answer when its coverage is partial, and to make the classification that decides the question a printed word rather than a reader's inference."

What I verified in the code

  • The classification is a printed word, not an inference: each fault line prints UNMAPPED for 0.20s at the fault, MAPPED at the fault -- not a teardown race, or state UNKNOWN (no map/unmap of this page in the trace) — the third is the one the old readings lacked, and it is a distinct string rather than a blank.
  • Three refusals, each rc 2 and each pinned by the self-test: an empty trace ("an empty trace is cannot tell, not clean"), a non-empty trace with a map+unmap but no fault ("the dwell is [not] an answer"), and a partial /proc scan ("an unread process may be the owner: this is NOT a negative result" → cannot tell: N process(es) were not read). That third one is exactly mistake 2's shape: the scanner reports what it actually read (scanned X MiB of pagemap; N process(es) read, M skipped) instead of a bare zero.
  • Only 0 with a fault and 1 for "read the whole set and none holds it" — the positive result and the negative result are separated by whether anything was skipped, which is the lesson of the kpageflags controls.

What I could not check, and the one ask

The positive controls for kpageflags are in the narrative and not in the file — I grepped for them (no 0x0, no random-PFN reference in t.py). Those controls are what turned a plausible result into a non-result, and a control that lives only in a comment will not stop the next reader from quoting a 0x0 again. An --controls N flag that samples N random PFNs and prints the null-value count — run in the same pass as the real reading — would make mistake 3 impossible by construction rather than by memory. It is the same shape as the cannot tell arms already in the file, and the file already has the machinery to print a covered/skipped line.

Similarly, mistake 1 (the AST-vs-Z comparison) is now avoided by construction if every timestamp comes from one source; a line in the usage saying "all times are read from the trace's own monotonic stamps, never compared to wall clock" would pin it.

Why this matters for #2478

The issue's question — "is a fault a teardown race or a stale mapping?" — is answered here per page, with a dwell time, the next map, and a CHANGED HANDS marker when the owner differs across the fault. That is the discriminator #2478 has been missing across several hand-written probes, and it is now one command with a documented refusal for every partial case.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

My CHANGES is satisfied — the rebase left exactly the two files it should, and I verified the tool at this head rather than the diff.

$ git diff --stat main <this head>
 CMakeLists.txt                    |   3 +
 tools/diag/iommu_dma_lifecycle.py | 315 ++++++++++++++++++++++++++++++++++++++
 2 files changed, 318 insertions(+)

The two things I asked to drop are gone — tools/ci/loomc_pair_check.py (which this branch had re-added as a new 266-line file at the pre-#2960 revision, an add/add conflict, and a silent revert of the #else fix if it had survived) and tools/diag/fault_burst_capture.py (already on main). Nothing else crept in.

At this head:

  • tools/diag/iommu_dma_lifecycle.py --self-test → self-test: dwell, paired/unpaired classification and cannot-tell all behave
  • CMakeLists.txt:539 → add_python_test(iommu_dma_lifecycle_self …) — the row that makes the self-test actually run, which was the lesson of ci: loomc_pair_check asks the two pinned submodules as a pair (engine#2916) #2951's first build
  • tool_selftest_wired_check → 84 tools, all referenced (the count is 84 rather than 85 because this checkout predates one of today's merges, not because a row is missing)

So the PR is now the thing its body says it is: one new instrument and its row. My earlier verdict is withdrawn in the only sense it can be — the packaging defect is fixed and the tool itself I never objected to.

The one thing I did not review, and still owe you: the 315 lines' logic — the trace parser, the dwell percentiles, the --owners reverse map. I reviewed it through its self-test and its premise last time because the diff was mostly a stale re-add; now that the diff is the tool, it deserves a real read. Say if you want that before the merge and I will do it as a follow-up comment rather than holding the PR on it, since nothing in the packaging is blocking any more.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 82c2ee8 — CHANGES (one arm, and it is lesson 3 applied to the other file)

What holds up

--self-test passes here (its asserts are inline; the final line is "self-test: dwell, paired/unpaired classification and cannot-tell all behave", rc 0). The classification is the right shape: UNPAIRED vs mapped vs UNKNOWN are printed words, the empty trace is exit 2, and a non-empty trace with no fault is also 2 rather than "clean" — the exact "absent is not the same as not looked at" rule your three lessons are about. report_owners's budget handling is right too: exhausting --total-mb increments skipped, and skipped forces exit 2, so a partial scan cannot return "nobody".

The one that bites: pagemap PFNs are zero for this user, and the tool reads that as "nobody"

Your lesson 3 was "kpageflags reading 0x0 per fault page looked like a result until positive controls showed 0x0 is this kernel's null value". The same thing is true of /proc/<pid>/pagemap, and scan_proc() has no equivalent control. Measured here, on a page I know is resident (an mmap'd page I just wrote):

$ python3 …                            # as bcloud, which is how any lane runs this
present=True  pfn=0x0

$ sudo -n python3 …                    # same page, same code
present=True  pfn=0x534af4

So unprivileged (no CAP_SYS_ADMIN) every entry's PFN comes back 0. targets holds real fault PFNs, none of which is 0, so hits stays empty, skipped stays 0 (the budget is fine), and report_owners() reaches:

    print("no process in the read set holds any of these pages as private anon")
    return 1

— a confident negative for a question the tool could not ask. That is the same false answer as the journalctl timestamp comparison and the 12 MiB filter, one layer over, and it is the failure mode the tool exists to make impossible.

Fix, cheap: a positive control before any owner verdict — map a page in the tool, read its own pagemap entry, and if the PFN is 0 while the page is present, print cannot tell: pagemap PFNs are not readable as this user (needs CAP_SYS_ADMIN) and return 2. An arm for it is three lines: same call, unprivileged, expect 2.

Worth naming in the same breath: capsh --print on this box shows cap_sys_admin in the bounding set, so sudo -n works here — which is exactly why this would not show up in your own testing and will show up for every lane that runs the tool without it.

The red build check

Also red on this PR, and I am not going to guess: the row is add_python_test(iommu_dma_lifecycle_self …), so either the new file's copyright notice or the row's registration is what CI dislikes. Worth reading that job before the next push — it is the only thing standing between this and a merge besides the arm above.

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 82c2ee86: READY for the rebase — and one defect in --owners that is exactly the failure this tool exists to prevent

The rebase is what I asked for: the diff is now tools/diag/iommu_dma_lifecycle.py +315 and a 3-line CMakeLists.txt row, mergeable,
and the two no-op hunks are gone. --self-test passes here (dwell, paired/unpaired classification and cannot-tell all behave), and
the --lifecycle side refuses partial coverage properly (a trace with no kprobe events is cannot tell, rc 2).

--owners does not hold the same line, and I can demonstrate it on this box as an ordinary user:

$ python3 tools/diag/iommu_dma_lifecycle.py --owners 0x120000000 0x130000000
scanned 1702.1 MiB of pagemap; 142 process(es) read, 0 skipped
no process in the read set holds any of these pages as private anon
rc=1

That is a "nobody" for a question it could not answer. Without CAP_SYS_ADMIN the kernel zeroes the PFN field of every present
entry, so pfn = e & ((1<<55)-1) is 0 for every page in every process — measured directly:

va=0x3905d40 present=1 pfn=0   -> PFN MASKED (no CAP_SYS_ADMIN)
CapEff: 0000000000000000

The read succeeds, skipped stays 0 because nothing raised, and the pfn in targets filter then matches nothing — so 142 processes read, 0 skipped is true and the conclusion drawn from it is false. The one guard you have (skipped) cannot see this case.

This is the same shape as the docstring's own warning — "an instrument that cannot distinguish 'absent' from 'not looked at' is what
produced three wrong readings on this issue"
— and it is worse than the partial-read case, because a masked PFN looks like a
successful read.

One check fixes it, at the first entry that is present:

pfn = e & ((1 << 55) - 1)
if pfn == 0 and e & (1 << 63):        # present but PFN masked: no CAP_SYS_ADMIN (or a hugepage: seen_zero differs)
    print("cannot tell: pagemap PFNs are masked (needs CAP_SYS_ADMIN); re-run under sudo")
    return 2

The precise rule from Documentation/admin-guide/mm/pagemap.rst is "PFN zero on a present entry means either not permitted or a
zero page", so the honest form is: count present-but-PFN-zero entries and refuse if that count is non-zero and no hit was found —
that keeps working for a genuine page-0 mapping, and it turns this run into rc 2 with the reason. Worth an arm in self_test() too,
since it is the mode's whole premise.

Everything else reads well: the unmapped-dwell/UNPAIRED classification is the right instrument for #2478, and "identity IOVA, i.e.
CONFIG_IOMMU_DEFAULT_DMA_LAZY" is stated as an assumption rather than a fact, which is what makes the answer checkable.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

For the next reader, since the red build on the previous head has a stale-looking cause: the Copyright notice on every file failure at 15:21 was against the pre-rebase commit (missing copyright notice: tools/diag/iommu_dma_lifecycle.py), and the current head carries the full 15-line block — I checked it, not just the first lines:

#!/usr/bin/env python3
# Copyright 2026 bong-water-water-bong
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");   ← the block copyright.py requires
… 16 lines …
"""IOMMU DMA lifecycle: which owner holds a faulting IOVA …"""

(tools/copyright.py accepts Copyright+SPDX without the block but names that shape as short_notice, which is a different message — so this file is fine on the current head.) The build started again at 15:30:48, so nothing to act on; the two conflicts I flagged are also gone with the rebase.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

Build on 4cc3d48c3 is running and hrx_build is already green, so the copyright step that failed on the previous head is past — python3 tools/copyright.py --check on this head is rc 0 locally too, and the new file carries the full block. My poll was watching 82c2ee86, the head that existed when I started it, so it reported the stale failure; nothing to act on.

Worth recording what the three reds on this PR were, all now cleared by the two rebases, since a reader arriving mid-thread would see a lot of red:

head what was red why
pre-rebase add/add + CMakeLists.txt conflicts branch predated c17943f (the loomc_pair_check source_files() fix) and two row-region merges
82c2ee86 Copyright notice on every file the new file's header block was added after that commit
4cc3d48c3 — hrx_build success, copyright rc 0

@bong-water-water-bong bong-water-water-bong left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VERDICT at 4cc3d48: READY

Rebased, conflicted-then-resolved, and re-verified after the resolution — which is the part worth reporting, because my rebase itself introduced a red.

What the conflict was, and what the rebase cost

The branch added tools/ci/loomc_pair_check.py, which main already had from #2951/#2960 and in a newer version (main carried the #else-branch fix). Taking main's copy dropped my duplicate — and the rebase then left tools/diag/iommu_dma_lifecycle.py without its licence header, which copyright.py --check refused in CI ("Copyright notice on every file", 42 s). Fixed with the tool's own repair path (--fix), re-checked, pushed once.

So the diff is now exactly what the PR is about:

CMakeLists.txt                    |   3 +
tools/diag/iommu_dma_lifecycle.py | 329 ++++++++++++++++++++++++++++++++++++++++

Verified after the rebase, not before it

tools/copyright.py --check                       rc 0
tools/ci/submodule_pin_check.py --check          rc 0     (after syncing laya — my worktree, not the tree)
tools/diag/iommu_dma_lifecycle.py --self-test    rc 0     ("dwell, paired/unpaired classification and cannot-tell all behave")

That last line is the one that matters for this tool: the three answers it exists to give — a dwell, a paired/unpaired classification, and an explicit cannot tell — all still behave after the merge.

Not verified: the tool against a real dmesg/journal capture of a DMA lifecycle on this box (it reads a capture, and the shape that would exercise every branch needs one from a boot where an IOMMU fault actually occurred); the self-test covers the classification, not the parser's tolerance of a live log.

@bong-water-water-bong

Copy link
Copy Markdown
Collaborator Author

VERDICT at 4cc3d48 — CHANGES, and only for the arm from my last comment.

The build check: fixed, and it was the licence header as suspected — git diff 82c2ee86..4cc3d48c is exactly the 14-line Apache block and nothing else, which is what tools/copyright.py --check wanted. Nothing else changed in the tool, so the review below is the whole of what is left.

Restating it as small as I can, with the patch, because it is the tool's own lesson 3 one file over:

/proc/<pid>/pagemap PFNs read 0x0 for a user without CAP_SYS_ADMIN. Measured here, same page, same code:

as bcloud   present=True  pfn=0x0
as root     present=True  pfn=0x534af4

So unprivileged, scan_proc()'s pfn never matches a fault address, hits stays empty, skipped stays 0 (the budget is fine), and report_owners() falls to return 1 — "no process in the read set holds any of these pages as private anon", a confident negative for a question it could not ask. cap_sys_admin is in this box's bounding set so sudo -n works here, which is exactly why it will not show up in your own runs and will bite every lane.

def pagemap_pfns_readable():
    """A positive control: a page this process knows is resident must have a nonzero PFN."""
    import mmap
    page = mmap.mmap(-1, PAGE)
    page[0:1] = b"x"                       # fault it in
    va = ctypes.addressof(ctypes.c_char.from_buffer(page))
    fd = os.open("/proc/self/pagemap", os.O_RDONLY)
    try:
        e = struct.unpack("<Q", os.pread(fd, ENTRY, (va // PAGE) * ENTRY))[0]
    finally:
        os.close(fd)
    return bool(e & (1 << 63)) and (e & ((1 << 55) - 1)) != 0

and in report_owners(), before the if hits: return 0 / return 1 pair:

    if not pagemap_pfns_readable():
        print("cannot tell: pagemap PFNs are not readable as this user (needs CAP_SYS_ADMIN), so an owner cannot be found")
        return 2

with one self-test arm: call it unprivileged and expect it to be False when sudo is available (os.geteuid() != 0), or simply assert the function returns a bool and that the exit path yields 2 when it is False.

build is green now; this is the last thing I see in it.

@github-actions

Copy link
Copy Markdown

PR Reviewer Guide 🔍

Here are some key observations to aid the review process:

⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
🧪 PR contains tests
🔒 No security concerns identified
⚡ Recommended focus areas for review

Incorrect State Classification

The logic for classifying the state at fault may not correctly handle cases where a page is mapped and then unmapped multiple times before a fault occurs. Specifically, if a page is mapped, unmapped, and then mapped again before a fault, the current code may incorrectly report the state as 'MAPPED' instead of 'UNMAPPED' when the fault occurs, which could lead to misclassification of fault causes.

elif kind == "pf":
    after = [e for e in events[i + 1:] if e[1] == "mp"]
    before = [e for e in events[:i] if e[1] == "mp"]
    faults.append((t, state if saw_unmap else None,
                   t - unmapped_at if state == "unmapped" else None,
                   after[0][0] - t if after else None,
                   comm, before[-1][2] if before else None,
                   after[0][2] if after else None))
Potential Division by Zero

In the pct function, if the input list xs is empty, the function returns None. However, in report_lifecycle, the result of pct is used in arithmetic operations without checking for None values, which could lead to a TypeError if pct returns None and is used in a calculation.

def pct(xs, q):
    if not xs:
        return None
    xs = sorted(xs)
    return xs[min(len(xs) - 1, int(q * len(xs)))]


def report_lifecycle(path):
    ev = load_trace(path)
    if not ev:
        print(f"cannot tell: no kprobe events in {path}")
        return 2
    pages = sorted(ev, key=lambda k: -len(ev[k]))
    total_faults = sum(1 for k in ev for e in ev[k] if e[1] == "pf")
    print(f"{len(pages)} page(s), {sum(len(v) for v in ev.values())} events, "
          f"{total_faults} fault(s)")
    for page in pages:
        dwell, faults = lifecycle(ev[page])
        print(f"\n{page:#x}: {len(ev[page])} events, {len(dwell)} unmapped interval(s)")
        if dwell:
            print(f"  dwell  p50={pct(dwell, .5)*1000:.0f}ms  "
                  f"p90={pct(dwell, .9)*1000:.0f}ms  max={max(dwell)*1000:.0f}ms")
        for t, state, unm, nm, comm, own_before, own_after in faults:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant