interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

memfrag: measured cause of host memory fragmentation, read-only sampler and scanner, physics fix proposal (#528)

closed e490c78ed6991434 #582 · opened 2026-10-19 15:30 UTC · closed 2026-10-29 19:01 UTC

Imported from GitHub aien-dev/omega-mv#582, by drakestapleton

Base a8ffd2b912c84197d08f963b05f9c7d8b30a3f8a · Head 49b753138cf1bb92e8b09171ab5c6fb6e2fa8479

drakestapleton wrote on 2026-10-19 15:30 UTC

Measured cause of the Spark's host memory fragmentation, plus read-only tools to measure it again. Host only; no machine setting changed.

Finding (details and tagged claims in docs/host-memory-fragmentation-528.md)

GPU memory is the cause. Every GPU buffer the engine asks for comes back from NVIDIA's driver as 64 KB pieces that Linux may never move. The live 27B server holds 34.6 GB of these spread over about 30,000 of the machine's 2 MB blocks; a benchmark that restarts about every two minutes takes and frees up to 33 GB more each time, leaving free memory in small holes (measured: 29 GB free, zero free 2 MB blocks). With a benchmark loaded, free 2 MB blocks averaged 142; without, 2,176. Slab stayed at 5 to 8 GB and does not drive the swings.

The fix belongs in physics (nvrm/nvrm.c, alloc_with_cacheability: ask the driver for 2 MB pieces for big buffers). It is written up as a proposal with the exact change; it is not applied and not tested on the chip.

What is in it

  • tools/memfrag_sample.sh: read-only sampler (buddyinfo, pagetypeinfo via sudo -n cat, meminfo slab, vmstat compaction/migration/foll_pin, per-process GPU mappings, judge state), one line per interval.
  • tools/memfrag_scan.c: read-only scanner of every physical page (/proc/kpageflags, needs root) reporting what keeps each 2 MB block from being free; can tag one process's GPU pages.
  • tests/test_memfrag_scan.c, tests/memfrag/sample_fixture.sh, mk/memfrag.mk: make test-memfrag (fixtures only, no /proc, no root, no device; two mutants must fail).
  • docs/host-memory-fragmentation-528.md, README pointer. Crumbs recompiled with the pinned tool (d0f0b95d), last commit.

Verification

  • Agent (handoff ~/handoffs/2026-10-19-omega-528.md on the Spark): test-memfrag fails on base (no rule) and passes on the branch; base host suite TOTAL GATES: 14 | PASSED: 14 | FAILED: 0; test-gpu-code-alloc PASS. Sample logs in ~/workspace/investigations/2026-10-19-omega-528/.
  • Desk rerun on the Spark: make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-memfrag rc=0: MEMFRAG_SCAN PASS, NO_GPU_TAG mutant: killed (8 failing checks), NO_FREE_TAIL mutant: killed (4 failing checks), MEMFRAG_SAMPLE PASS, OMEGA_MEMFRAG_GATE PASS.

Not done / UNVERIFIED

  • test-memfrag is not registered as a Spark gate yet (tests/gates change, own PR).
  • Whether the driver accepts 2 MB pieces for GB10 system memory, how GPU mapping and physics' fault latch react, model load time, and how much the fix helps: all need chip time; not run.
  • Not linked to judge activity (the judge was idle in every sample).
  • Two machine settings already differ from the issue text (min_free_kbytes 1048576, compaction_proactiveness 60); who changed them is unknown.

Refs #528 (the physics change is a follow-up in physics-mv).

This PR was opened by the Hermes PR desk on Drake's behalf.

github-advanced-security[bot] commented on tests/test_memfrag_scan.c line 49 on 2026-10-19 15:36 UTC

CodeQL / File created without restricting permissions

A file may be created here with mode 0666, which would make it world-writable.

Show more details

github-advanced-security[bot] reviewed (COMMENTED) on 2026-10-19 15:36 UTC

drakestapleton wrote on 2026-10-29 19:01 UTC

Closing in org cleanup (Drake, 2026-10-29): abandoned: no activity in 10 days with merge conflicts and failing CI checks. Reopen if still needed.

Apply it

git checkout -b patch-e490c78ed6991434 a8ffd2b912c84197d08f963b05f9c7d8b30a3f8a
curl -fsSL https://interplane.io/drakestapleton/omega-mv/patches/e490c78ed6991434.patch | git am

Raw patch (mbox) · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/omega-mv
582
49b753138cf1bb92e8b09171ab5c6fb6e2fa8479
{"kind":"github-import","owner":"aien-dev","repo":"omega-mv","number":582,"url":"https://github.com/aien-dev/omega-mv/pull/582","export_sha256":"7319147b350ad908bf0b731068ec3be7b8dee848041dc862f71455e8e4680140","imported_utc":"2026-11-18T16:35:53Z"}

Changes

diff --git a/.crumb b/.crumb
index d121d2dad..3d684a2bf 100644
--- a/.crumb
+++ b/.crumb
@@ -47,8 +47,8 @@
           "purpose": "Directory calibration. Purpose not yet described by a human."
         },
         {
-          "digest": "d2eb8967a939ebdb0b54e15fe5d849dd5af71c23b812941e4ba86ad2b0f21d39",
-          "last_commit": "4870b0a4",
+          "digest": "89388d1b9cebd481d441a588281baef4a24023fa6a7f70161684d7d3f3b623af",
+          "last_commit": "bf84a142",
           "name": "docs",
           "purpose": "Directory docs. Purpose not yet described by a human."
         },
@@ -59,8 +59,8 @@
           "purpose": "Directory doctrine. Purpose not yet described by a human."
         },
         {
-          "digest": "e7d38c87a51c3c0ee6e3b18419ef4a01d95029de12ac9bf69eb672654f0ace55",
-          "last_commit": "ae4ad9c0",
+          "digest": "b522a08712944a7e6a6dc66ce277749edc4582adb041064c9ec1f96c63bbbe33",
+          "last_commit": "66fe18e5",
           "name": "mk",
           "purpose": "Directory mk. Purpose not yet described by a human."
         },
@@ -83,27 +83,27 @@
           "purpose": "Directory src. Purpose not yet described by a human."
         },
         {
-          "digest": "4eb9d4d76234448c0ed691f0aeb9c90d785f8a47b1b1291d728bbe3e1509dc10",
-          "last_commit": "88e24bdd",
+          "digest": "c166ebd846d9fb80f13f4cb567c1dc9672c892c5587ab4937efe9cd4d82b883c",
+          "last_commit": "ca748b2c",
           "name": "tests",
           "purpose": "Directory tests. Purpose not yet described by a human."
         },
         {
-          "digest": "566a123ba248da906e3c42430b73decd7c3ec030a4fd26c909d265aa9bf67db9",
-          "last_commit": "88e24bdd",
+          "digest": "d86401406bcef451b64a7b4b6eaa57ac1d6d7b146684ecf8b16d0ebb12e7388c",
+          "last_commit": "66fe18e5",
           "name": "tools",
           "purpose": "Directory tools. Purpose not yet described by a human."
         }
       ],
-      "children_root": "sha256:e1a8c008214ad5dbc33a3e184d7e882dc56d1d50f9bd14c58f8773992961557e",
-      "compiled_at": "2026-10-18T21:10:38Z",
+      "children_root": "sha256:69351410bbbea032927af0f0e6a51aa950e1e84608dd8f900b8c237b2f0cbdf8",
+      "compiled_at": "2026-10-19T20:08:21Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:be7220db494238bb4c33023d1df17286c35f947336bee5fc2e0405c136ec3e73",
+      "digest": "sha256:a2960f8299e78cfb70d56d6a1264138abece3d1877b0de6cc5f43b446796866b",
       "evidence_files": 11127,
       "evidence_root": "sha256:4528085ec1661c442b64fb5dc8def65067ea2620ff88e42bcf52d58b7642ea6e",
-      "files": 14100,
-      "generated_at_commit": "f4a9849fb127f8d2d664dfc56890752ad180c507",
-      "source_tree": "sha256:21f93defce6c9ba159a4bd31083db787e156dfaa4afb80c3427cf88f732f8258"
+      "files": 14107,
+      "generated_at_commit": "ca748b2cb7c11df5a394d53a3ea9731d538744fe",
+      "source_tree": "sha256:e47b5b6315c1b136a88d624f65bc0c6cc53839f920478f3dba14171c14f6c883"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/README.md b/README.md
index 87f91fbf1..12ce6a447 100644
--- a/README.md
+++ b/README.md
@@ -41,8 +41,11 @@ Needs gcc and make on an AArch64 Linux host: CI runs the host suites on `ubuntu-
 make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-compiler-quick   # compiler, quick suite
 make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-numeric-cpu      # E1 CPU numerics
 make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-realize
+make PHYSICS_DIR=/nonexistent PHYSICS_LOCK_CHECK=0 test-memfrag          # host memory fragmentation tools
 ```
 
+`tools/memfrag_sample.sh` and `tools/memfrag_scan.c` measure what keeps the Spark from offering free 2 MiB blocks (read-only, root for `/proc/kpageflags`); findings and the proposed physics fix are in [host-memory-fragmentation-528](docs/host-memory-fragmentation-528.md).
+
 The full omegatool build (`make`) links the `physics` repository at the commit in `physics.lock`. Some older milestone gate scripts rewrite their receipts in place, so do not run them on a clean checkout you mean to keep; prefer the `make test-*` targets above. Targets that touch the GB10 need the DGX Spark, run one at a time, and are never killed mid-run. CI definitions in `.github/workflows/` list the suites that run on every push.
 
 ## Repository layout
diff --git a/docs/.crumb b/docs/.crumb
index ca5d5ec00..cb62c1e4c 100644
--- a/docs/.crumb
+++ b/docs/.crumb
@@ -124,14 +124,14 @@
         }
       ],
       "children_root": "sha256:ac7f7ea4b00d4620a993c6dd88a0267f2d49008d415162976e45fa4341e43407",
-      "compiled_at": "2026-10-16T09:04:56Z",
+      "compiled_at": "2026-10-19T15:30:02Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:d2eb8967a939ebdb0b54e15fe5d849dd5af71c23b812941e4ba86ad2b0f21d39",
+      "digest": "sha256:89388d1b9cebd481d441a588281baef4a24023fa6a7f70161684d7d3f3b623af",
       "evidence_files": 34,
       "evidence_root": "sha256:589d8b3706e6d7a202ab20b278dac5fc5bafc973f1c2a867b2668aa7210b65cc",
-      "files": 127,
-      "generated_at_commit": "9d368679f13ea58c46bf7580899aee92e39f5885",
-      "source_tree": "sha256:29d159b6950500f96de859834fd2c5a9e9ba037f9bc88fd97a8ed47a1688233b"
+      "files": 128,
+      "generated_at_commit": "bf84a14205bbffda4ee93c4cf56beafaf811af06",
+      "source_tree": "sha256:caf02470018946a25aec008d60f7b1f1a252d1ec861cd2fb4a7fa3112249ad54"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/docs/host-memory-fragmentation-528.md b/docs/host-memory-fragmentation-528.md
new file mode 100644
index 000000000..e4b57797e
--- /dev/null
+++ b/docs/host-memory-fragmentation-528.md
@@ -0,0 +1,144 @@
+# Host memory fragmentation on the Spark (omega#528)
+
+Question: what keeps the Spark's 128 GB from offering free 2 MiB blocks (one 2 MiB block = one
+Linux pageblock), so that every order-9 allocation, such as the GPU channel's main context buffer
+(omega#523, physics-mv#64), has to fight for one?
+
+Short answer: the GPU memory. Every GPU buffer the Omega engine allocates (through physics
+`nvrm_alloc`) arrives from the NVIDIA driver as 64 KiB pieces of unmovable kernel memory. The
+resident 27B model server holds 34.6 GB of them spread across 29,938 pageblocks, and the 27B
+benchmark loop allocates and frees up to 33 GB more every two minutes. Each cycle leaves free
+memory chopped into 64 KiB to 1 MiB holes that cannot be merged into 2 MiB blocks while server
+GPU pages and kernel slab objects sit between them. The proposed fix is in physics, outside
+omega: ask the driver for 2 MiB pages for buffers of 2 MiB and up.
+
+Claim tags: OBSERVED (measured here, receipt named), DOCUMENTED (vendor source quoted),
+INFERRED (reasoned, confidence given), UNKNOWN, NOT RUN.
+
+## Tools (this change)
+
+- `tools/memfrag_sample.sh <out.tsv> [interval] [count]`: one line per sample with free 2 MiB
+  blocks, free memory in 4 KiB-32 KiB pieces and in 64 KiB-1 MiB pieces, pageblock counts per
+  migrate type, slab, page tables, page cache, anonymous memory, compaction and migration
+  counters, pinned-page counters, the GPU memory each process has mapped, and the local judge's
+  phase. Read-only. `/proc/pagetypeinfo` is root-only and is read with `sudo -n cat` when that is
+  allowed (NA otherwise).
+- `tools/memfrag_scan.c` (`make build/memfrag_scan`): walks `/proc/kpageflags` one pageblock at a
+  time, sorts every page into free, gpu, slab, page table, reserved, other, movable, and reports
+  which classes pin each block. With `--pid P` it reads the process's driver mappings
+  (`/dev/nvidiactl`) through `/proc/P/pagemap` and tags those physical pages as gpu. Root is
+  needed for both files; nothing is written.
+- `make test-memfrag`: host test with fixtures, two mutants that must fail, and a fixture run of
+  the sampler. It contains the claim in miniature: the same 512 GPU pages pin 16 pageblocks as
+  scattered 64 KiB pieces and one pageblock as one 2 MiB piece.
+
+## Documentation read first
+
+- DOCUMENTED, driver 580.173.02 (`/usr/src/nvidia-580.173.02/nvidia/nv-vm.c`,
+  `nv_compute_gfp_mask`): system pages are taken with `NV_GFP_KERNEL` (`GFP_KERNEL |
+  __GFP_NOWARN`, `common/inc/nv-linux.h:288`) plus `__GFP_RETRY_MAYFAIL`, and `__GFP_COMP`
+  when the order is above 0. No `__GFP_MOVABLE`: every GPU page on GB10 is unmovable memory to
+  Linux.
+- DOCUMENTED (`nvidia/nv.c`, `nv_alloc_pages`): for non-contiguous allocations
+  `at->order = get_order(page_size);`, and RM passes the memory descriptor's page size
+  (`osGetPagesInfo`: `*pageSize = memdescGetAdjustedPageSize(pMemDesc)`, open-gpu-kernel-modules
+  `src/nvidia/arch/nvalloc/unix/src/os.c`, via Context7). So the requested page size decides the
+  size of each piece Linux hands out.
+- DOCUMENTED (`src/common/sdk/nvidia/inc/nvos.h:1053-1061`, `:1258-1266`): "HUGE_PAGE = 2 MB on
+  PASCAL+ ... To request for a HUGE page size, set NVOS32_ATTR_PAGE_SIZE to _HUGE and
+  NVOS32_ATTR2_PAGE_SIZE_HUGE to the desired size." The ATTR2 comment says "For virtual allocs";
+  the ATTR comment says the field is also used for physical allocations. DOCS SILENT on whether
+  a GB10 system-memory allocation honours `_HUGE`.
+- OUR CODE: physics `nvrm/nvrm.c` `alloc_with_cacheability` (pin 6d7cf0d4, line 499; main
+  14273c5c, line 579) sets `attr = PHYSICALITY_ALLOW_NONCONTIGUOUS | LOCATION_PCI`, page size
+  left at DEFAULT, alignment 0x1000.
+
+## Measurements (2026-10-19, uptime 1 day 5 h)
+
+Receipts are in `~/workspace/investigations/2026-10-19-omega-528/` on the Spark (`scan-*.txt`,
+`sample.tsv`, `sample2.tsv`).
+
+1. OBSERVED, the piece size. Without any tagging, the server's pages show up as compound pages
+   mapped to user space and not on any LRU list: 554,136 compound heads and 8,312,040 tails,
+   exactly 16 pages (64 KiB, order 4) per piece (calc:5381faf8). With the server's pagemap
+   tagged: 8,866,444 GPU pages, 8,865,519 of them compound (scan-3). The driver hands RM's
+   default system page size of 64 KiB to Linux one piece at a time.
+2. OBSERVED, the spread. The server's 8,866,444 GPU pages (34.6 GB) touch 29,938 pageblocks,
+   296 pages per block on average (calc:88603e0c), where 17,318 whole blocks would hold them
+   (calc:039d5dcd). Only 67 blocks are entirely GPU. Of the physically contiguous runs, 103,375 are 16 to 511
+   pages long (calc:2ae2ffb4) and 122 are 512 or more (scan-1).
+3. OBSERVED, the benchmark. While the 27B benchmark (`qwen38_omega_full`, restarted about every
+   two minutes) was loaded, GPU pages totalled 17,527,356 (67 GB) over 46,815 pageblocks; 16.5 GB
+   was free and only 254 pageblocks were free whole (scan-4-bench, 14:52:08Z).
+4. OBSERVED, the holes. At 14:49:23Z, seconds after a benchmark run exited, 28,954 MiB was free
+   and there were 0 free 2 MiB blocks; 6,963 MiB of the free memory was in 4-32 KiB pieces and
+   the remaining 21,991 MiB in 64 KiB-1 MiB pieces, the size of the freed GPU pieces (sample.tsv;
+   the 64 KiB-1 MiB band is logged directly in sample2.tsv). Over the first 41 samples, free
+   2 MiB blocks averaged 142 with a benchmark loaded and 2,176 without.
+5. OBSERVED, slab. Slab held 1,340,324 pages (5.1 GB) spread over 36,866 pageblocks, 36 pages per
+   block (calc:ddb1969); it shares most blocks with GPU pages: of 55,551 pinned blocks, 29,938
+   hold GPU pages and only 1,002 are pinned by GPU pages alone (scan-3).
+6. OBSERVED, other fixed holders: 1,558,544 pages flagged reserved at boot (memblock, flag bit
+   32) in 3,059 blocks, and about 1.0-1.3 M flag-less pages that no free block covers (kernel
+   allocations without page flags: vmalloc, stacks, driver internals; UNKNOWN which).
+7. OBSERVED, cross-check: the scanner's free count (7,332,521 pages) matches MemFree (29.3 GB)
+   read in the same second.
+8. OBSERVED, not the fragmenter: `nr_foll_pin_acquired == nr_foll_pin_released` in every sample
+   (no long-term pinned user pages), as #528 found on 2026-10-17.
+9. OBSERVED, machine settings differ from #528's text: `vm.min_free_kbytes` is now 1048576 (the
+   issue recorded 45056) and `vm.compaction_proactiveness` 60 (issue: 20). Who changed them and
+   when is UNKNOWN; this investigation changed nothing.
+
+## Root cause
+
+INFERRED, confidence medium-high. Linux keeps unmovable allocations together by retyping whole
+pageblocks as unmovable when it runs out (an order-4 request is at least half a pageblock's
+order, so it may claim the whole block). The GPU pieces are 64 KiB, so a pageblock taken for GPU
+memory still has room for slab objects and other small kernel allocations, and the server's
+long-lived pieces end up interleaved with them (finding 5). When a benchmark run frees its 33 GB,
+its pieces come back as 64 KiB holes beside pieces that stay (server GPU pages, slab), and those
+holes cannot merge into 2 MiB blocks (finding 4). Compaction cannot help: none of these pages is
+movable. The count of free 2 MiB blocks then depends on which pieces happen to free together,
+which is the second-by-second flicker #528 reported.
+
+What this does not explain: the flag-less kernel pages and the reserved pages (finding 6) pin
+about 14,600 blocks by themselves; they are fixed or small and not driven by the benchmark cycle.
+
+## Proposed fix (physics, outside omega)
+
+In physics `nvrm/nvrm.c` `alloc_with_cacheability`, for buffers of 2 MiB and up:
+
+```c
+#define NVRM_HUGE_BYTES (2ull << 20)
+int huge = size >= NVRM_HUGE_BYTES;
+if (huge) size = (size + NVRM_HUGE_BYTES - 1) & ~(NVRM_HUGE_BYTES - 1);
+uint64_t va = va_take(rm, size, huge ? NVRM_HUGE_BYTES : 0x1000);
+...
+mp.attr = (NVOS32_ATTR_PHYSICALITY_ALLOW_NONCONTIGUOUS << 27) | (NVOS32_ATTR_LOCATION_PCI << 25) |
+          (huge ? NVOS32_ATTR_PAGE_SIZE_HUGE << 23 : 0);
+mp.attr2 = (gpu_cacheable << 2) | NVOS32_ATTR2_ZBC_PREFER_NO_ZBC |
+           (huge ? NVOS32_ATTR2_PAGE_SIZE_HUGE_2MB << 20 : 0);
+mp.alignment = huge ? NVRM_HUGE_BYTES : 0x1000;
+```
+
+Then each piece is an order-9 compound page: a whole pageblock. GPU memory stops sharing blocks
+with slab, and a freed GPU buffer returns whole 2 MiB blocks. Smaller buffers keep today's path.
+
+Cost, OBSERVED on the live server's 702 driver mappings: 292 buffers of 2 MiB or more hold
+34,534 MiB; rounding them up to 2 MiB adds 111.4 MiB. The 410 smaller buffers (100 MiB) are
+unchanged.
+
+Open points, all NOT RUN (they need the GPU, and this lane was host-only):
+- whether RM accepts `_HUGE` for GB10 system memory (DOCS SILENT); `scan --pid` on a test
+  process shows it directly (`gpu_compound` with 512 pages per head, `gpu_runs_order9`);
+- the refusal path: today any `rm_alloc` failure sets `rm->faulted`. A refused `_HUGE` request
+  should fall back once to the current attributes, and that fallback needs its own chip test;
+- whether the GPU mapping calls (`NVOS46_FLAGS_PAGE_SIZE_4KB` in the DMA map, the UVM external
+  mapping) accept 2 MiB physical pages mapped with 4 KiB GPU page table entries;
+- load-time cost: an order-9 `GFP_KERNEL | __GFP_RETRY_MAYFAIL` request may run direct
+  compaction when no free 2 MiB block exists. Measure model load time before and after;
+- the effect itself: rerun `tools/memfrag_sample.sh` across several benchmark cycles before and
+  after and compare free 2 MiB blocks and the 64 KiB-1 MiB band.
+
+No machine-wide change (`vm.min_free_kbytes`, `vm.compaction_proactiveness`, hugepage settings)
+is proposed; the orchestrator's 2026-10-17 decision stands.
diff --git a/mk/.crumb b/mk/.crumb
index cd51a1c73..270c5a51b 100644
--- a/mk/.crumb
+++ b/mk/.crumb
@@ -7,14 +7,14 @@
     "generated": {
       "children": [],
       "children_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "compiled_at": "2026-10-16T02:24:36Z",
+      "compiled_at": "2026-10-19T15:30:02Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:e7d38c87a51c3c0ee6e3b18419ef4a01d95029de12ac9bf69eb672654f0ace55",
+      "digest": "sha256:b522a08712944a7e6a6dc66ce277749edc4582adb041064c9ec1f96c63bbbe33",
       "evidence_files": 0,
       "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "files": 71,
-      "generated_at_commit": "ccf021b944b0128a537dfd3dd301e6d83eefa311",
-      "source_tree": "sha256:e7a2b37daa8149cb73da719737df82c74a61685b4076bf2c5b4e0c26bee61dc7"
+      "files": 72,
+      "generated_at_commit": "bf84a14205bbffda4ee93c4cf56beafaf811af06",
+      "source_tree": "sha256:800b13ae2e9c8e971bf0ab91b76274278f54615e1c85a3b288cb1b3f2687a4a6"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/mk/memfrag.mk b/mk/memfrag.mk
new file mode 100644
index 000000000..299f713a8
--- /dev/null
+++ b/mk/memfrag.mk
@@ -0,0 +1,21 @@
+# Host memory fragmentation tools (omega#528): tools/memfrag_scan.c (which pages pin each 2 MiB
+# pageblock, read from /proc/kpageflags + a process's driver mappings) and tools/memfrag_sample.sh
+# (buddyinfo / pagetypeinfo / meminfo / vmstat / GPU mapping sampler). Host only: fixtures, no
+# /proc reads, no root, no device. Two mutants must fail the scanner test; the sampler runs once
+# against a fixture /proc tree and its line is checked field by field.
+.PHONY: test-memfrag
+build/memfrag_scan: tools/memfrag_scan.c
+	@mkdir -p build
+	gcc -std=gnu11 -O2 -Wall -Wextra -Werror -o $@ tools/memfrag_scan.c
+build/test_memfrag_scan: tests/test_memfrag_scan.c tools/memfrag_scan.c
+	@mkdir -p build
+	gcc -std=gnu11 -O2 -Wall -Wextra -Werror -o $@ tests/test_memfrag_scan.c
+test-memfrag: build/memfrag_scan build/test_memfrag_scan
+	./build/test_memfrag_scan
+	@for m in NO_GPU_TAG NO_FREE_TAIL; do \
+		gcc -std=gnu11 -O2 -Wall -Wextra -Werror -DMEMFRAG_MUTANT_$$m -o build/test_memfrag_scan_$$m tests/test_memfrag_scan.c || exit 1; \
+		if ./build/test_memfrag_scan_$$m >build/test_memfrag_scan_$$m.log 2>&1; then echo "MUTANT SURVIVED: $$m"; exit 1; fi; \
+		echo "$$m mutant: killed ($$(grep -c '^FAIL:' build/test_memfrag_scan_$$m.log) failing checks)"; \
+	done
+	tests/memfrag/sample_fixture.sh
+	@echo "OMEGA_MEMFRAG_GATE PASS"
diff --git a/tests/.crumb b/tests/.crumb
index bd5535a8b..07010c7b0 100644
--- a/tests/.crumb
+++ b/tests/.crumb
@@ -296,14 +296,14 @@
         }
       ],
       "children_root": "sha256:ddc3618190458bc5073e3bee67ffccc68a2ee9f065f2cb0d86545386a29fddf8",
-      "compiled_at": "2026-10-16T19:04:20Z",
+      "compiled_at": "2026-10-19T20:08:21Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:4eb9d4d76234448c0ed691f0aeb9c90d785f8a47b1b1291d728bbe3e1509dc10",
+      "digest": "sha256:c166ebd846d9fb80f13f4cb567c1dc9672c892c5587ab4937efe9cd4d82b883c",
       "evidence_files": 16,
       "evidence_root": "sha256:96d08097822ad95f4e562c19e0ba5df5a035774c48632f1832912c40a27bd27a",
-      "files": 1270,
-      "generated_at_commit": "88e24bdd57b27817d030d0ad95f62c3f3eacf426",
-      "source_tree": "sha256:e6c4f0021d383ba2e59da0d85d06a0b98170f6d188289c891b5745200548e6fc"
+      "files": 1273,
+      "generated_at_commit": "ca748b2cb7c11df5a394d53a3ea9731d538744fe",
+      "source_tree": "sha256:a81666ab0a449f28f600461e13ad3ddd707eda4e746056693d478e72086a8e04"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/tests/gates/omega-memfrag.gate b/tests/gates/omega-memfrag.gate
new file mode 100644
index 000000000..53c509b6a
--- /dev/null
+++ b/tests/gates/omega-memfrag.gate
@@ -0,0 +1,24 @@
+# tests/gates/omega-memfrag.gate
+# Host-only memory fragmentation scan (omega #528): make test-memfrag (scan tool, fixture test).
+gate: OMEGA-MEMFRAG
+manifest_version: 2
+owner: omega
+requires:
+  - host
+inputs:
+  - Makefile
+  - mk/
+  - src/
+  - tests/
+  - tools/
+  - physics.lock
+  - tests/gates/
+run:
+  exec: tests/gates/run.sh
+  args: ["memfrag"]
+expects:
+  exit: 0
+  verdict: PASS
+timeout: 15m
+exactness: EXACT
+cache_scope: machine
diff --git a/tests/gates/run.sh b/tests/gates/run.sh
index 6c5c918d5..96216f971 100755
--- a/tests/gates/run.sh
+++ b/tests/gates/run.sh
@@ -160,6 +160,7 @@ case "$step" in
     make "test-$step" | tee "build/gate-$step.log"
     gates_pass "build/gate-$step.log"
     ;;
+  memfrag)            make $NOPHYS test-memfrag ;;
   # rx-host.yml
   rx-host-reference)
     pin physics-src-6d7cf0d physics 6d7cf0d4d8eb2cda7b512100ff6058e25dbb3ddf
diff --git a/tests/memfrag/sample_fixture.sh b/tests/memfrag/sample_fixture.sh
new file mode 100755
index 000000000..2681de449
--- /dev/null
+++ b/tests/memfrag/sample_fixture.sh
@@ -0,0 +1,69 @@
+#!/bin/bash
+# Fixture test for tools/memfrag_sample.sh (omega#528): one sample against a fake /proc tree,
+# every field checked. Negative controls: a process without the driver node mapped is not
+# counted, and a tree without pagetypeinfo gives NA block counts instead of guessing.
+set -eu
+here=$(cd "$(dirname "$0")/../.." && pwd)
+t=$(mktemp -d /tmp/memfrag-sample-XXXXXX)
+trap 'rm -rf "$t"' EXIT
+p=$t/proc
+mkdir -p "$p/123" "$p/456"
+# Normal zone: 1024 free order-0 pages + 128 order-3 = 8 MiB of fragments; 3 order-9 + 1 order-10
+# + 1 order-13 = 3 + 2 + 16 = 21 free 2 MiB blocks; 64 order-4 = 4 MiB of 64 KiB holes
+cat >"$p/buddyinfo" <<'B'
+Node 0, zone      DMA      2      4      4     32     21     42     11      7      3      6     10      3      1     12 
+Node 0, zone   Normal   1024      0      0    128     64      0      0      0      0      3      1      0      0      1 
+B
+cat >"$p/pagetypeinfo" <<'B'
+Page block order: 9
+Pages per block:  512
+
+Free pages count per migrate type at order       0      1      2      3      4      5      6      7      8      9     10     11     12     13 
+Node    0, zone   Normal, type    Unmovable      9      9      9      9      0      0      0      0      0      0      0      0      0      0 
+
+Number of blocks type     Unmovable      Movable  Reclaimable   HighAtomic          CMA      Isolate 
+Node 0, zone      DMA           49          707           16            0           64            0 
+Node 0, zone   Normal        24031        34393         1391            0         4697            0 
+B
+printf 'MemFree:  2048000 kB\nSlab:  1024000 kB\nSReclaimable:  512000 kB\nSUnreclaim:  512000 kB\nPageTables:  10240 kB\nCached:  4096000 kB\nAnonPages:  3072000 kB\n' >"$p/meminfo"
+printf 'compact_stall 11\ncompact_fail 7\ncompact_success 4\npgmigrate_success 100\npgmigrate_fail 9\nnr_foll_pin_acquired 55\nnr_foll_pin_released 55\n' >"$p/vmstat"
+printf '10000000-10040000 rw-s 00000000 00:06 7 /dev/nvidiactl\n' >"$p/123/maps"
+printf 'Name:\tserver\nRssFile:\t35465776 kB\n' >"$p/123/status"
+printf 'aien-serve-http\n' >"$p/123/comm"
+printf '20000000-20001000 rw-p 00000000 00:00 0 [heap]\n' >"$p/456/maps"      # no driver node
+printf 'RssFile:\t999999 kB\n' >"$p/456/status"
+printf 'other\n' >"$p/456/comm"
+printf '{"phase":"gate","pid":1,"repo":"omega","sha":"-","utc":"x"}' >"$t/hb"
+
+MEMFRAG_PROC=$p MEMFRAG_HEARTBEAT=$t/hb "$here/tools/memfrag_sample.sh" "$t/out.tsv" 1 1
+fail=0
+check() { # name expected
+    got=$(awk -F'\t' -v n="$1" 'NR == 1 { for (i = 1; i <= NF; i++) c[$i] = i } NR == 2 { print $(c[n]) }' "$t/out.tsv")
+    if [ "$got" != "$2" ]; then echo "FAIL: $1 = '$got', expected '$2'"; fail=1; fi
+}
+[ "$(wc -l <"$t/out.tsv")" = 2 ] || { echo "FAIL: expected header + one sample"; fail=1; }
+check free_2m 21
+check free_o0_3_mb 8
+check free_o4_8_mb 4
+check blk_unmov 24031
+check blk_mov 34393
+check blk_recl 1391
+check blk_cma 4697
+check memfree_mb 2000
+check slab_mb 1000
+check sunrecl_mb 500
+check compact_stall 11
+check pgmigrate_fail 9
+check foll_pin_acq 55
+check gpu_map_mb 34634
+check gpu_procs aien-serve-http:123:34634
+check judge_phase gate
+
+rm "$p/pagetypeinfo" "$t/out.tsv"
+MEMFRAG_PROC=$p MEMFRAG_HEARTBEAT=$t/missing "$here/tools/memfrag_sample.sh" "$t/out.tsv" 1 1
+check blk_unmov NA
+check judge_phase NA
+check free_2m 21
+
+[ "$fail" = 0 ] || { echo "MEMFRAG_SAMPLE FAIL"; exit 1; }
+echo "MEMFRAG_SAMPLE PASS"
diff --git a/tests/test_memfrag_scan.c b/tests/test_memfrag_scan.c
new file mode 100644
index 000000000..6bd9f349c
--- /dev/null
+++ b/tests/test_memfrag_scan.c
@@ -0,0 +1,164 @@
+/* Host memory fragmentation scanner (tools/memfrag_scan.c, omega#528). Host only: synthetic
+ * kpageflags/maps/pagemap fixtures, no /proc, no root, no device.
+ *
+ * The central check is the omega#528 claim in miniature: the same 512 GPU pages pin 16 pageblocks
+ * when the driver hands them out as 64 KiB pieces spread over the blocks (what the live 27B server
+ * showed), and one pageblock when they come as one 2 MiB piece. Negative control: no GPU pages
+ * and only movable memory pins nothing. Mutants NO_GPU_TAG and NO_FREE_TAIL must fail. */
+#define MEMFRAG_SCAN_NO_MAIN
+#include "../tools/memfrag_scan.c"
+
+#include <sys/stat.h>
+
+static int fails;
+#define CHECK(c, ...) do { if (!(c)) { fails++; printf("FAIL: "); printf(__VA_ARGS__); printf("\n"); } } while (0)
+
+#define NB 16u                                   /* pageblocks per fixture */
+#define NP (NB * MF_BLOCK_PAGES)
+#define F_LRU  KPF_BIT(KPF_LRU)
+#define F_MMAP KPF_BIT(11)
+#define F_HEAD (KPF_BIT(KPF_COMPOUND_HEAD) | F_MMAP)
+#define F_TAIL (KPF_BIT(KPF_COMPOUND_TAIL) | F_MMAP)
+
+static uint64_t flags[NP];
+static mf_bitmap gpu;
+
+static void reset(uint64_t fill) {
+    for (unsigned i = 0; i < NP; i++) flags[i] = fill;
+    free(gpu.bits);
+    gpu.bits = NULL;
+    gpu.nbits = 0;
+}
+
+/* One driver chunk of 2^order pages at pfn: compound head + tails, mapped, tagged. */
+static void gpu_chunk(uint64_t pfn, unsigned order) {
+    for (uint64_t i = 0; i < (1ull << order); i++) {
+        flags[pfn + i] = i ? F_TAIL : F_HEAD;
+        if (mf_bit_set(&gpu, pfn + i)) { printf("FAIL: bitmap alloc\n"); exit(1); }
+    }
+}
+
+static mf_counts scan(void) {
+    mf_counts c = {0};
+    mf_walk w = {0};
+    for (unsigned b = 0; b < NB; b++) mf_block(&c, &w, (uint64_t)b * MF_BLOCK_PAGES, flags + b * MF_BLOCK_PAGES, MF_BLOCK_PAGES, &gpu);
+    return c;
+}
+
+static void write_file(const char *path, const void *p, size_t n) {
+    FILE *f = fopen(path, "wb");
+    if (!f || fwrite(p, 1, n, f) != n || fclose(f)) { printf("FAIL: write %s\n", path); exit(1); }
+}
+
+int main(void) {
+    char dir[] = "/tmp/memfrag-test-XXXXXX";
+    if (!mkdtemp(dir)) { printf("FAIL: mkdtemp\n"); return 1; }
+
+    /* 1. scattered 64 KiB pieces: 32 order-4 chunks, two per block, rest of each block movable */
+    reset(F_LRU);
+    for (unsigned b = 0; b < NB; b++) {
+        gpu_chunk((uint64_t)b * MF_BLOCK_PAGES + 64, 4);
+        gpu_chunk((uint64_t)b * MF_BLOCK_PAGES + 320, 4);
+    }
+    mf_counts s = scan();
+    CHECK(s.pages[MF_GPU] == 512, "scattered: 512 gpu pages (got %llu)", (unsigned long long)s.pages[MF_GPU]);
+    CHECK(s.blocks_with[MF_GPU] == NB, "scattered: gpu in all 16 blocks (got %llu)", (unsigned long long)s.blocks_with[MF_GPU]);
+    CHECK(s.blocks_compactable == 0, "scattered: no block compactable (got %llu)", (unsigned long long)s.blocks_compactable);
+    CHECK(s.blocks_gpu_only_pin == NB && s.pin_combo[1] == NB, "scattered: gpu is the only pinner of 16 blocks (got %llu)", (unsigned long long)s.blocks_gpu_only_pin);
+    CHECK(s.gpu_compound == 512, "scattered: every gpu page compound (got %llu)", (unsigned long long)s.gpu_compound);
+    uint64_t hist[MF_MAX_ORDER + 2];
+    mf_run_hist(&gpu, hist);
+    CHECK(hist[4] == 32 && hist[9] == 0, "scattered: 32 runs of 16 pages (order4=%llu order9=%llu)", (unsigned long long)hist[4], (unsigned long long)hist[9]);
+    char *out = NULL;
+    size_t outn = 0;
+    FILE *mo = open_memstream(&out, &outn);
+    mf_print(mo, &s, 512, 0, &gpu);
+    fclose(mo);
+    CHECK(strstr(out, "\nblocks_pinned=16\n") && strstr(out, "\npinned_by_G---=16\n") && strstr(out, "\ngpu_runs_order4=32\n"),
+          "scattered: report lines (got:\n%s)", out);
+    free(out);
+
+    /* 2. the same 512 pages as one 2 MiB piece: one block pinned, fifteen compactable */
+    reset(F_LRU);
+    gpu_chunk(0, 9);
+    mf_counts p = scan();
+    CHECK(p.pages[MF_GPU] == 512, "packed: 512 gpu pages (got %llu)", (unsigned long long)p.pages[MF_GPU]);
+    CHECK(p.blocks_with[MF_GPU] == 1 && p.blocks_gpu_full == 1, "packed: one full gpu block (with=%llu full=%llu)", (unsigned long long)p.blocks_with[MF_GPU], (unsigned long long)p.blocks_gpu_full);
+    CHECK(p.blocks_compactable == NB - 1, "packed: 15 blocks compactable (got %llu)", (unsigned long long)p.blocks_compactable);
+    mf_run_hist(&gpu, hist);
+    CHECK(hist[9] == 1 && hist[4] == 0, "packed: one run of 512 pages (order9=%llu)", (unsigned long long)hist[9]);
+    CHECK(s.blocks - s.blocks_compactable == NB * (p.blocks - p.blocks_compactable), "scattered pins 16x the blocks of packed");
+
+    /* 3. negative control: movable only, no gpu tags: nothing pinned, every gpu count zero */
+    reset(F_LRU);
+    mf_counts n = scan();
+    CHECK(n.blocks == NB && n.blocks_compactable == NB, "control: all 16 blocks compactable (got %llu)", (unsigned long long)n.blocks_compactable);
+    CHECK(n.pages[MF_GPU] == 0 && n.blocks_with[MF_GPU] == 0 && n.gpu_compound == 0, "control: no gpu pages");
+    for (unsigned b = 1; b < 16; b++) CHECK(n.pin_combo[b] == 0, "control: pin combo %u empty", b);
+
+    /* 4. classes: one slab page, one page-table page, one reserved page, holes */
+    reset(F_LRU);
+    flags[1 * MF_BLOCK_PAGES + 7] = KPF_BIT(KPF_SLAB);
+    flags[2 * MF_BLOCK_PAGES + 9] = KPF_BIT(KPF_PGTABLE);
+    flags[3 * MF_BLOCK_PAGES + 3] = KPF_BIT(KPF_RESERVED);
+    for (unsigned i = 0; i < MF_BLOCK_PAGES; i++) flags[15 * MF_BLOCK_PAGES + i] = KPF_BIT(KPF_NOPAGE);
+    mf_counts k = scan();
+    CHECK(k.blocks == NB - 1, "classes: the all-hole block is not a block (got %llu)", (unsigned long long)k.blocks);
+    CHECK(k.pin_combo[2] == 1 && k.pin_combo[4] == 1 && k.pin_combo[8] == 1, "classes: one block each pinned by slab, pgtable, reserved");
+    CHECK(k.blocks_compactable == NB - 4, "classes: 12 compactable (got %llu)", (unsigned long long)k.blocks_compactable);
+
+    /* 5. free blocks: the kernel flags only the head of a free block */
+    reset(F_LRU);
+    flags[0] = KPF_BIT(KPF_BUDDY);                                 /* block 0: one free 2 MiB block */
+    for (unsigned i = 1; i < MF_BLOCK_PAGES; i++) flags[i] = 0;
+    flags[MF_BLOCK_PAGES] = KPF_BIT(KPF_BUDDY);                    /* block 1: free 64 KiB at its start */
+    for (unsigned i = 1; i < 16; i++) flags[MF_BLOCK_PAGES + i] = 0;
+    flags[MF_BLOCK_PAGES + 16] = KPF_BIT(KPF_SLAB);
+    flags[MF_BLOCK_PAGES + 17] = 0;                                /* flag-less, no free head: other */
+    mf_counts f = scan();
+    CHECK(f.blocks_free == 1, "free: one whole free block (got %llu)", (unsigned long long)f.blocks_free);
+    CHECK(f.pages[MF_FREE] == 512 + 16, "free: 528 free pages (got %llu)", (unsigned long long)f.pages[MF_FREE]);
+    CHECK(f.pages[MF_OTHER] == 1, "free: one unexplained page (got %llu)", (unsigned long long)f.pages[MF_OTHER]);
+    CHECK(f.blocks_compactable == NB - 1, "free: free block counts as compactable (got %llu)", (unsigned long long)f.blocks_compactable);
+
+    /* 6. end to end through files: kpageflags stream with a short last block, maps + pagemap tagging */
+    reset(F_LRU);
+    for (unsigned i = 0; i < 64; i++) flags[MF_BLOCK_PAGES + i] = i ? F_TAIL : F_HEAD;  /* the driver pages */
+    char kpf[64], maps[64], pm[64];
+    snprintf(kpf, sizeof kpf, "%s/kpageflags", dir);
+    write_file(kpf, flags, (NP - 100) * sizeof flags[0]);
+    snprintf(maps, sizeof maps, "%s/maps", dir);
+    const char *m = "10000000-10040000 rw-s 00000000 00:06 7 /dev/nvidiactl\n"
+                    "20000000-20001000 rw-p 00000000 00:00 0 [heap]\n";
+    write_file(maps, m, strlen(m));
+    snprintf(pm, sizeof pm, "%s/pagemap", dir);
+    static uint64_t ent[0x20001];
+    for (unsigned i = 0; i < 64; i++) ent[0x10000 + i] = 1ull << 63 | (MF_BLOCK_PAGES + i);
+    ent[0x20000] = 1ull << 63 | 5;                                 /* heap page: must not be tagged */
+    write_file(pm, ent, sizeof ent);
+    reset(F_LRU);
+    uint64_t hidden = 0;
+    long t = mf_tag_mappings(maps, pm, "nvidiactl", &gpu, &hidden);
+    CHECK(t == 64 && hidden == 0, "files: 64 pages tagged (got %ld)", t);
+    CHECK(!mf_bit_get(&gpu, 5), "files: the heap page is not tagged");
+    int fd = open(kpf, O_RDONLY);
+    mf_counts e = {0};
+    CHECK(fd >= 0 && mf_scan_fd(fd, &gpu, &e) == 0, "files: scan reads the stream");
+    if (fd >= 0) close(fd);
+    CHECK(e.blocks == NB, "files: short last block still counted (got %llu)", (unsigned long long)e.blocks);
+    CHECK(e.pages[MF_GPU] == 64 && e.blocks_with[MF_GPU] == 1, "files: 64 gpu pages in one block (got %llu)", (unsigned long long)e.pages[MF_GPU]);
+    ent[0x10000] = 1ull << 63;                                     /* unprivileged pagemap: pfn 0 */
+    write_file(pm, ent, sizeof ent);
+    reset(F_LRU);
+    t = mf_tag_mappings(maps, pm, "nvidiactl", &gpu, &hidden);
+    CHECK(t == 63 && hidden == 1, "files: a hidden pfn is reported, not tagged (tagged %ld hidden %llu)", t, (unsigned long long)hidden);
+
+    unlink(kpf);
+    unlink(maps);
+    unlink(pm);
+    rmdir(dir);
+    free(gpu.bits);
+    if (fails) { printf("MEMFRAG_SCAN FAIL (%d)\n", fails); return 1; }
+    printf("MEMFRAG_SCAN PASS\n");
+    return 0;
+}
diff --git a/tools/.crumb b/tools/.crumb
index 8cf70bcac..c4c5f4a08 100644
--- a/tools/.crumb
+++ b/tools/.crumb
@@ -62,14 +62,14 @@
         }
       ],
       "children_root": "sha256:e1f826c2beb8604bb0dcba49575f7c6b48cf5488c40b616b212fda2ed70c62ee",
-      "compiled_at": "2026-10-16T19:04:20Z",
+      "compiled_at": "2026-10-19T15:30:02Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:566a123ba248da906e3c42430b73decd7c3ec030a4fd26c909d265aa9bf67db9",
+      "digest": "sha256:d86401406bcef451b64a7b4b6eaa57ac1d6d7b146684ecf8b16d0ebb12e7388c",
       "evidence_files": 0,
       "evidence_root": "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
-      "files": 284,
-      "generated_at_commit": "88e24bdd57b27817d030d0ad95f62c3f3eacf426",
-      "source_tree": "sha256:eee0218ae5c8d003fa0a585291551799e81e6c329a7f5db1295e771a75aee167"
+      "files": 286,
+      "generated_at_commit": "bf84a14205bbffda4ee93c4cf56beafaf811af06",
+      "source_tree": "sha256:fc48480147abff1ec7a51ac64177a63c5fa00e0ff6c888fe2a93150f3f30645b"
     },
     "owner_lane": "",
     "provenance": {
diff --git a/tools/memfrag_sample.sh b/tools/memfrag_sample.sh
new file mode 100755
index 000000000..f54e0003c
--- /dev/null
+++ b/tools/memfrag_sample.sh
@@ -0,0 +1,116 @@
+#!/bin/bash
+# memfrag_sample.sh -- host memory fragmentation sampler (omega#528).
+# Read-only: it reads /proc and the judge heartbeat, never drops caches,
+# compacts, or writes a sysctl.
+#
+#   tools/memfrag_sample.sh <out.tsv> [interval_s] [count]
+#
+# One tab-separated line per sample (header written once):
+#   utc            sample time
+#   free_2m        free 2 MiB-or-larger blocks in the Normal zone, counted in
+#                  2 MiB units (sum over orders 9.. of n << (order - 9))
+#   free_o0_3_mb   free memory sitting in orders 0..3 (MiB), the fragments
+#   free_o4_8_mb   free memory in orders 4..8 (64 KiB to 1 MiB pieces, MiB): the
+#                  size of the holes freed 64 KiB GPU pieces leave behind
+#   blk_unmov blk_mov blk_recl blk_cma   pageblock counts per migrate type
+#                  (/proc/pagetypeinfo is root-only: read with `sudo -n cat`
+#                  when allowed, "NA" otherwise)
+#   memfree_mb slab_mb srecl_mb sunrecl_mb pgtables_mb cached_mb anon_mb
+#   compact_stall compact_fail compact_success pgmigrate_success pgmigrate_fail
+#   foll_pin_acq foll_pin_rel   /proc/vmstat counters (cumulative)
+#   gpu_map_mb     RssFile of every process with /dev/nvidiactl mapped: on
+#                  GB10 this is the driver's system pages mapped to the CPU
+#   gpu_procs      name:pid:MiB for each such process, comma separated
+#   judge_phase    phase from the local judge's worker.heartbeat
+set -u
+OUT=${1:?usage: memfrag_sample.sh <out.tsv> [interval_s] [count]}
+IVL=${2:-10}
+COUNT=${3:-0}                 # 0 = run until killed
+PROC=${MEMFRAG_PROC:-/proc}   # tests point this at a fixture tree
+HEARTBEAT=${MEMFRAG_HEARTBEAT:-$HOME/.local/state/aien-local-ci/worker.heartbeat}
+
+# free_2m, free_o0_3_mb and free_o4_8_mb from buddyinfo (Normal zone; 4 KiB pages)
+buddy_fields() {
+    awk '$4 == "Normal" {
+        for (o = 0; o + 5 <= NF; o++) {
+            n = $(o + 5)
+            if (o >= 9) big += n * 2 ^ (o - 9)
+            if (o <= 3) small += n * 2 ^ o
+            else if (o <= 8) mid += n * 2 ^ o
+        }
+    } END { printf "%d\t%d\t%d", big, small * 4 / 1024, mid * 4 / 1024 }' "$PROC/buddyinfo"
+}
+
+block_fields() {
+    local pti
+    if [ -r "$PROC/pagetypeinfo" ]; then
+        pti=$(cat "$PROC/pagetypeinfo")
+    elif [ "$PROC" = /proc ] && pti=$(sudo -n cat /proc/pagetypeinfo 2>/dev/null); then
+        :
+    else
+        printf 'NA\tNA\tNA\tNA'; return
+    fi
+    printf '%s\n' "$pti" | awk '
+        /^Number of blocks type/ {
+            for (i = 5; i <= NF; i++) col[$i] = i
+            hdr = 1; next
+        }
+        hdr && $4 == "Normal" {
+            printf "%s\t%s\t%s\t%s", $(col["Unmovable"]), $(col["Movable"]),
+                $(col["Reclaimable"]), $(col["CMA"]) == "" ? 0 : $(col["CMA"])
+            found = 1
+        }
+        END { if (!found) printf "NA\tNA\tNA\tNA" }'
+}
+
+meminfo_fields() {
+    awk '{ v[$1] = $2 } END {
+        printf "%d\t%d\t%d\t%d\t%d\t%d\t%d",
+            v["MemFree:"] / 1024, v["Slab:"] / 1024, v["SReclaimable:"] / 1024,
+            v["SUnreclaim:"] / 1024, v["PageTables:"] / 1024, v["Cached:"] / 1024,
+            v["AnonPages:"] / 1024 }' "$PROC/meminfo"
+}
+
+vmstat_fields() {
+    awk '{ v[$1] = $2 } END {
+        printf "%d\t%d\t%d\t%d\t%d\t%d\t%d",
+            v["compact_stall"], v["compact_fail"], v["compact_success"],
+            v["pgmigrate_success"], v["pgmigrate_fail"],
+            v["nr_foll_pin_acquired"], v["nr_foll_pin_released"] }' "$PROC/vmstat"
+}
+
+# Processes with the driver's control node mapped. Only processes whose maps
+# we may read are seen; the rest are skipped silently (ownership, not error).
+gpu_fields() {
+    local total=0 list="" d pid kb name
+    for d in "$PROC"/[0-9]*; do
+        pid=${d##*/}
+        grep -q nvidiactl "$d/maps" 2>/dev/null || continue
+        kb=$(awk '/^RssFile:/ { print $2 }' "$d/status" 2>/dev/null)
+        [ -n "$kb" ] || continue
+        name=$(cat "$d/comm" 2>/dev/null)
+        total=$((total + kb))
+        list="$list${list:+,}${name// /_}:$pid:$((kb / 1024))"
+    done
+    printf '%d\t%s' $((total / 1024)) "${list:--}"
+}
+
+judge_phase() {
+    local p
+    p=$(sed -n 's/.*"phase":"\([^"]*\)".*/\1/p' "$HEARTBEAT" 2>/dev/null)
+    printf '%s' "${p:-NA}"
+}
+
+if [ ! -s "$OUT" ]; then
+    printf 'utc\tfree_2m\tfree_o0_3_mb\tfree_o4_8_mb\tblk_unmov\tblk_mov\tblk_recl\tblk_cma\tmemfree_mb\tslab_mb\tsrecl_mb\tsunrecl_mb\tpgtables_mb\tcached_mb\tanon_mb\tcompact_stall\tcompact_fail\tcompact_success\tpgmigrate_success\tpgmigrate_fail\tfoll_pin_acq\tfoll_pin_rel\tgpu_map_mb\tgpu_procs\tjudge_phase\n' >"$OUT"
+fi
+
+n=0
+while :; do
+    printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
+        "$(buddy_fields)" "$(block_fields)" "$(meminfo_fields)" \
+        "$(vmstat_fields)" "$(gpu_fields)" "$(judge_phase)" >>"$OUT"
+    n=$((n + 1))
+    [ "$COUNT" -gt 0 ] && [ "$n" -ge "$COUNT" ] && break
+    sleep "$IVL"
+done
diff --git a/tools/memfrag_scan.c b/tools/memfrag_scan.c
new file mode 100644
index 000000000..d5aaaaaac
--- /dev/null
+++ b/tools/memfrag_scan.c
@@ -0,0 +1,359 @@
+/* memfrag_scan.c -- which pages keep 2 MiB blocks from forming (omega#528).
+ *
+ * Read-only. Walks /proc/kpageflags one pageblock (512 x 4 KiB = 2 MiB) at a
+ * time and sorts every page into a class. A pageblock can only become a free
+ * 2 MiB block (by freeing or by compaction) when every page in it is free or
+ * movable; one page of any other class pins the whole block. Optionally tags
+ * the physical pages behind one process's driver mappings (default: lines of
+ * /proc/<pid>/maps naming "nvidiactl", which on GB10 are the GPU's system
+ * pages mapped to the CPU) so they can be counted as their own class.
+ *
+ *   memfrag_scan [--kpageflags F] [--pid P]... [--maps F --pagemap F]... [--match S]
+ *
+ * Root (or CAP_SYS_ADMIN) is needed for the real /proc/kpageflags and for
+ * physical frame numbers in /proc/<pid>/pagemap. Output is key=value lines.
+ *
+ * Page classes, from the kernel's page flag bits
+ * (include/uapi/linux/kernel-page-flags.h):
+ *   free     BUDDY head, plus the flag-less pages after it up to the largest
+ *            aligned power-of-two block that starts at the head (the kernel
+ *            marks only the head page of a free block)
+ *   gpu      tagged from the process's driver mappings
+ *   slab     SLAB
+ *   pgtable  PGTABLE
+ *   reserved RESERVED (bit 32): set aside at boot, never freed
+ *   movable  LRU or ANON (page cache and user memory the kernel can migrate)
+ *   other    anything else that is present: driver, vmalloc, kernel stacks,
+ *            pages without flags that no free head covers
+ */
+#include <errno.h>
+#include <fcntl.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#define MF_BLOCK_PAGES 512u
+#define MF_MAX_ORDER   13u
+
+#define KPF_SLAB          7
+#define KPF_BUDDY        10
+#define KPF_LRU           5
+#define KPF_ANON         12
+#define KPF_COMPOUND_HEAD 15
+#define KPF_COMPOUND_TAIL 16
+#define KPF_NOPAGE       20
+#define KPF_PGTABLE      26
+#define KPF_RESERVED     32 /* kernel-hacking bit: memblock reserved at boot */
+#define KPF_BIT(b) (1ull << (b))
+
+enum mf_class { MF_HOLE, MF_FREE, MF_GPU, MF_SLAB, MF_PGTABLE, MF_RESERVED, MF_OTHER, MF_MOVABLE, MF_NCLASS };
+static const char *const mf_class_name[MF_NCLASS] = {
+    "hole", "free", "gpu", "slab", "pgtable", "reserved", "other", "movable"
+};
+
+typedef struct {
+    uint8_t *bits;
+    uint64_t nbits;
+} mf_bitmap;
+
+static int mf_bit_get(const mf_bitmap *b, uint64_t i) {
+    return b && i < b->nbits && (b->bits[i >> 3] >> (i & 7)) & 1;
+}
+
+static int mf_bit_set(mf_bitmap *b, uint64_t i) {
+    if (i >= b->nbits) {
+        uint64_t n = b->nbits ? b->nbits : 1u << 20;
+        while (n <= i) n <<= 1;
+        uint8_t *p = realloc(b->bits, n >> 3);
+        if (!p) return -1;
+        memset(p + (b->nbits >> 3), 0, (n - b->nbits) >> 3);
+        b->bits = p;
+        b->nbits = n;
+    }
+    b->bits[i >> 3] |= (uint8_t)(1u << (i & 7));
+    return 0;
+}
+
+typedef struct {
+    uint64_t pages[MF_NCLASS];        /* pages per class */
+    uint64_t blocks;                  /* pageblocks with any present page */
+    uint64_t blocks_free;             /* every present page free */
+    uint64_t blocks_compactable;      /* free or movable only: compaction can empty it */
+    uint64_t blocks_with[MF_NCLASS];  /* blocks holding >= 1 page of the class */
+    uint64_t blocks_gpu_only_pin;     /* gpu pages are the only pinning pages */
+    uint64_t blocks_gpu_full;         /* all 512 pages gpu */
+    uint64_t gpu_compound;            /* gpu pages that are part of a compound page */
+    uint64_t pin_combo[16];           /* blocks by which pinning classes they hold:
+                                         bit 0 gpu, 1 slab, 2 pgtable, 3 reserved+other */
+    uint64_t other_flag[32];          /* distinct flag words seen on "other" pages */
+    uint64_t other_n[32];             /* ... and how many pages carried each */
+    uint64_t other_spill;             /* "other" pages past the 32 distinct words */
+} mf_counts;
+
+/* Free run state carried across pages: pages below free_end that have no
+ * flags belong to the free block whose head was seen last. */
+typedef struct {
+    uint64_t free_end;
+} mf_walk;
+
+static unsigned mf_aligned_order(uint64_t pfn) {
+    unsigned o = 0;
+    while (o < MF_MAX_ORDER && !(pfn & ((2ull << o) - 1))) o++;
+    return o;
+}
+
+static enum mf_class mf_classify(mf_walk *w, uint64_t pfn, uint64_t flags, int is_gpu) {
+    if (flags & KPF_BIT(KPF_NOPAGE)) return MF_HOLE;
+#ifdef MEMFRAG_MUTANT_NO_GPU_TAG
+    is_gpu = 0; /* mutant: the driver mappings are not counted */
+#endif
+    if (is_gpu) {
+        w->free_end = 0;
+        return MF_GPU;
+    }
+    if (flags & KPF_BIT(KPF_BUDDY)) {
+        w->free_end = pfn + (1ull << mf_aligned_order(pfn));
+        return MF_FREE;
+    }
+#ifndef MEMFRAG_MUTANT_NO_FREE_TAIL /* mutant: only the head page of a free block counts */
+    if (flags == 0 && pfn < w->free_end) return MF_FREE;
+#endif
+    w->free_end = 0;
+    if (flags & KPF_BIT(KPF_SLAB)) return MF_SLAB;
+    if (flags & KPF_BIT(KPF_PGTABLE)) return MF_PGTABLE;
+    if (flags & KPF_BIT(KPF_RESERVED)) return MF_RESERVED;
+    if (flags & (KPF_BIT(KPF_LRU) | KPF_BIT(KPF_ANON))) return MF_MOVABLE;
+    return MF_OTHER;
+}
+
+static void mf_note_other(mf_counts *c, uint64_t flags) {
+    for (unsigned j = 0; j < 32; j++) {
+        if (c->other_n[j] && c->other_flag[j] == flags) {
+            c->other_n[j]++;
+            return;
+        }
+        if (!c->other_n[j]) {
+            c->other_flag[j] = flags;
+            c->other_n[j] = 1;
+            return;
+        }
+    }
+    c->other_spill++;
+}
+
+/* One pageblock: flags[n] for pfn base..base+n-1 (n <= MF_BLOCK_PAGES). */
+static void mf_block(mf_counts *c, mf_walk *w, uint64_t base, const uint64_t *flags,
+                     unsigned n, const mf_bitmap *gpu) {
+    uint64_t per[MF_NCLASS] = {0};
+    for (unsigned i = 0; i < n; i++) {
+        int g = mf_bit_get(gpu, base + i);
+        enum mf_class k = mf_classify(w, base + i, flags[i], g);
+        per[k]++;
+        if (k == MF_GPU && flags[i] & (KPF_BIT(KPF_COMPOUND_HEAD) | KPF_BIT(KPF_COMPOUND_TAIL)))
+            c->gpu_compound++;
+        if (k == MF_OTHER) mf_note_other(c, flags[i]);
+    }
+    uint64_t present = n - per[MF_HOLE];
+    for (int k = 0; k < MF_NCLASS; k++) {
+        c->pages[k] += per[k];
+        if (per[k]) c->blocks_with[k]++;
+    }
+    if (!present) return;
+    c->blocks++;
+    uint64_t pinning = per[MF_GPU] + per[MF_SLAB] + per[MF_PGTABLE] + per[MF_RESERVED] + per[MF_OTHER];
+    if (per[MF_FREE] == present) c->blocks_free++;
+    if (!pinning) c->blocks_compactable++;
+    c->pin_combo[(per[MF_GPU] > 0) | (per[MF_SLAB] > 0) << 1 | (per[MF_PGTABLE] > 0) << 2 |
+                 (per[MF_RESERVED] + per[MF_OTHER] > 0) << 3]++;
+    if (per[MF_GPU] && per[MF_GPU] == pinning) c->blocks_gpu_only_pin++;
+    if (per[MF_GPU] == MF_BLOCK_PAGES) c->blocks_gpu_full++;
+}
+
+/* Walk a kpageflags-format stream (one little-endian u64 per pfn from 0). */
+static int mf_scan_fd(int fd, const mf_bitmap *gpu, mf_counts *c) {
+    uint64_t buf[MF_BLOCK_PAGES];
+    mf_walk w = {0};
+    uint64_t base = 0;
+    for (;;) {
+        size_t got = 0;
+        while (got < sizeof buf) {
+            ssize_t r = read(fd, (char *)buf + got, sizeof buf - got);
+            if (r < 0) {
+                if (errno == EINTR) continue;
+                return -1;
+            }
+            if (r == 0) break;
+            got += (size_t)r;
+        }
+        unsigned n = (unsigned)(got / sizeof buf[0]);
+        if (n) mf_block(c, &w, base, buf, n, gpu);
+        if (got < sizeof buf) return 0;
+        base += MF_BLOCK_PAGES;
+    }
+}
+
+/* Tag the pfns behind every mapping in `maps` whose line contains `match`.
+ * Returns the number of present pages tagged, -1 on error. Pagemap entry:
+ * bit 63 present, bits 0..54 pfn (zero without CAP_SYS_ADMIN). */
+static long mf_tag_mappings(const char *maps, const char *pagemap, const char *match,
+                            mf_bitmap *gpu, uint64_t *zero_pfn) {
+    FILE *m = fopen(maps, "r");
+    if (!m) return -1;
+    int pm = open(pagemap, O_RDONLY);
+    if (pm < 0) {
+        fclose(m);
+        return -1;
+    }
+    char line[4096];
+    long tagged = 0;
+    *zero_pfn = 0;
+    while (fgets(line, sizeof line, m)) {
+        if (!strstr(line, match)) continue;
+        unsigned long lo, hi;
+        if (sscanf(line, "%lx-%lx", &lo, &hi) != 2 || hi <= lo) continue;
+        for (uint64_t va = lo; va < hi; va += 4096 * 512ull) {
+            uint64_t ent[512];
+            uint64_t want = (hi - va) / 4096;
+            if (want > 512) want = 512;
+            ssize_t r = pread(pm, ent, want * 8, (off_t)(va / 4096 * 8));
+            if (r != (ssize_t)(want * 8)) {
+                tagged = -1;
+                goto out;
+            }
+            for (uint64_t i = 0; i < want; i++) {
+                if (!(ent[i] >> 63)) continue;
+                uint64_t pfn = ent[i] & ((1ull << 55) - 1);
+                if (!pfn) {
+                    (*zero_pfn)++;
+                    continue;
+                }
+                if (mf_bit_set(gpu, pfn)) {
+                    tagged = -1;
+                    goto out;
+                }
+                tagged++;
+            }
+        }
+    }
+out:
+    close(pm);
+    fclose(m);
+    return tagged;
+}
+
+/* Lengths of physically contiguous runs among the tagged pfns, as a log2
+ * histogram: hist[k] counts runs of length in [2^k, 2^(k+1)). */
+static void mf_run_hist(const mf_bitmap *gpu, uint64_t hist[MF_MAX_ORDER + 2]) {
+    memset(hist, 0, sizeof(uint64_t) * (MF_MAX_ORDER + 2));
+    uint64_t run = 0;
+    for (uint64_t i = 0; i <= gpu->nbits; i++) {
+        if (i < gpu->nbits && mf_bit_get(gpu, i)) {
+            run++;
+            continue;
+        }
+        if (!run) continue;
+        unsigned k = 0;
+        while (k < MF_MAX_ORDER + 1 && (run >> (k + 1))) k++;
+        hist[k]++;
+        run = 0;
+    }
+}
+
+static void mf_print(FILE *o, const mf_counts *c, long tagged, uint64_t zero_pfn,
+                     const mf_bitmap *gpu) {
+    for (int k = 1; k < MF_NCLASS; k++)
+        fprintf(o, "pages_%s=%llu\n", mf_class_name[k], (unsigned long long)c->pages[k]);
+    fprintf(o, "blocks=%llu\n", (unsigned long long)c->blocks);
+    fprintf(o, "blocks_free=%llu\n", (unsigned long long)c->blocks_free);
+    fprintf(o, "blocks_compactable=%llu\n", (unsigned long long)c->blocks_compactable);
+    fprintf(o, "blocks_pinned=%llu\n", (unsigned long long)(c->blocks - c->blocks_compactable));
+    for (int k = MF_GPU; k < MF_NCLASS; k++)
+        fprintf(o, "blocks_with_%s=%llu\n", mf_class_name[k], (unsigned long long)c->blocks_with[k]);
+    fprintf(o, "blocks_gpu_only_pin=%llu\n", (unsigned long long)c->blocks_gpu_only_pin);
+    fprintf(o, "blocks_gpu_full=%llu\n", (unsigned long long)c->blocks_gpu_full);
+    for (unsigned b = 1; b < 16; b++)
+        fprintf(o, "pinned_by_%s%s%s%s=%llu\n", b & 1 ? "G" : "-", b & 2 ? "S" : "-", b & 4 ? "P" : "-",
+                b & 8 ? "O" : "-", (unsigned long long)c->pin_combo[b]);
+    for (unsigned j = 0; j < 32 && c->other_n[j]; j++)
+        if (c->other_n[j] * 100 >= c->pages[MF_OTHER])
+            fprintf(o, "other_flags_0x%llx=%llu\n", (unsigned long long)c->other_flag[j],
+                    (unsigned long long)c->other_n[j]);
+    fprintf(o, "other_spill=%llu\n", (unsigned long long)c->other_spill);
+    if (tagged < 0) return;
+    fprintf(o, "gpu_tagged=%ld\n", tagged);
+    fprintf(o, "gpu_pfn_hidden=%llu\n", (unsigned long long)zero_pfn);
+    fprintf(o, "gpu_compound=%llu\n", (unsigned long long)c->gpu_compound);
+    uint64_t hist[MF_MAX_ORDER + 2];
+    mf_run_hist(gpu, hist);
+    for (unsigned k = 0; k < MF_MAX_ORDER + 2; k++)
+        if (hist[k]) fprintf(o, "gpu_runs_order%u=%llu\n", k, (unsigned long long)hist[k]);
+}
+
+#ifndef MEMFRAG_SCAN_NO_MAIN
+int main(int argc, char **argv) {
+    const char *kpf = "/proc/kpageflags", *match = "nvidiactl";
+    char *maps[16], *pagemap[16];
+    int nsrc = 0, nmaps = 0, npm = 0;
+    for (int i = 1; i < argc; i++) {
+        if (!strcmp(argv[i], "--kpageflags") && i + 1 < argc) kpf = argv[++i];
+        else if (!strcmp(argv[i], "--match") && i + 1 < argc) match = argv[++i];
+        else if (!strcmp(argv[i], "--maps") && i + 1 < argc && nmaps < 16) maps[nmaps++] = strdup(argv[++i]);
+        else if (!strcmp(argv[i], "--pagemap") && i + 1 < argc && npm < 16) pagemap[npm++] = strdup(argv[++i]);
+        else if (!strcmp(argv[i], "--pid") && i + 1 < argc && nmaps < 16 && npm < 16) {
+            long pid = strtol(argv[++i], NULL, 10);
+            char b[64];
+            snprintf(b, sizeof b, "/proc/%ld/maps", pid);
+            maps[nmaps++] = strdup(b);
+            snprintf(b, sizeof b, "/proc/%ld/pagemap", pid);
+            pagemap[npm++] = strdup(b);
+        } else {
+            fprintf(stderr, "usage: %s [--kpageflags F] [--pid P]... [--maps F --pagemap F]... [--match S]\n",
+                    argv[0]);
+            return 2;
+        }
+    }
+    if (nmaps != npm) {
+        fprintf(stderr, "memfrag_scan: --maps and --pagemap go together\n");
+        return 2;
+    }
+    nsrc = nmaps;
+    mf_bitmap gpu = {0};
+    long tagged = nsrc ? 0 : -1;
+    uint64_t zero_pfn = 0;
+    /* Tag first, then scan: the two reads are not atomic, so pages that move
+     * or are freed in between are counted under their new class. */
+    for (int s = 0; s < nsrc; s++) {
+        uint64_t z = 0;
+        long t = mf_tag_mappings(maps[s], pagemap[s], match, &gpu, &z);
+        if (t < 0) {
+            fprintf(stderr, "memfrag_scan: cannot read %s / %s: %s\n", maps[s], pagemap[s], strerror(errno));
+            return 1;
+        }
+        tagged += t;
+        zero_pfn += z;
+    }
+    if (nsrc && tagged == 0 && zero_pfn)
+        fprintf(stderr, "memfrag_scan: pagemap hides frame numbers (needs CAP_SYS_ADMIN)\n");
+    int fd = open(kpf, O_RDONLY);
+    if (fd < 0) {
+        fprintf(stderr, "memfrag_scan: open %s: %s\n", kpf, strerror(errno));
+        return 1;
+    }
+    mf_counts c = {0};
+    if (mf_scan_fd(fd, &gpu, &c)) {
+        fprintf(stderr, "memfrag_scan: read %s: %s\n", kpf, strerror(errno));
+        close(fd);
+        return 1;
+    }
+    close(fd);
+    mf_print(stdout, &c, tagged, zero_pfn, &gpu);
+    free(gpu.bits);
+    for (int s = 0; s < nsrc; s++) {
+        free(maps[s]);
+        free(pagemap[s]);
+    }
+    return 0;
+}
+#endif