Kexec Archive on lore.kernel.org
 help / color / mirror / Atom feed
* [RFC] OOM on unmovable kernel allocations with large free CMA (no non-CMA -> CMA migration)
@ 2026-12-03 17:58 tarunsahu
  2026-12-03 18:19 ` Frank van der Linden
  2026-12-03 18:25 ` Michal Hocko
  0 siblings, 2 replies; 3+ messages in thread
From: tarunsahu @ 2026-12-03 17:58 UTC (permalink / raw)
  To: linux-mm, Andrew Morton, David Hildenbrand, Johannes Weiner,
	Vlastimil Babka, Michal Hocko, Pasha Tatashin, Mike Rapoport,
	Pratyush Yadav, dmatlack, Chris Down
  Cc: linux-kernel, Zi Yan, Liam R. Howlett, Suren Baghdasaryan,
	Brendan Jackman, Shakeel Butt, David Rientjes, Barry Song,
	Qi Zheng, Kairui Song, Baolin Wang, Wei Xu, Axel Rasmussen,
	Yuanchu Xie, Baoquan He, kexec


Hi all,

I would like to start a discussion on whether migration of movable
memory to CMA area support is useful for others or not.
Under high memory pressure, unmovable kernel allocations can trigger
OOMs even though the CMA area has plenty of free memory. A C
reproducer and a QEMU runner script are included at the bottom (Credit
goes to AI).

There are multiples way a CMA gets reserved like KHO and hugetlb_cma.
Before this hit the production I am writing to audit it is necessary
problem to be solved.

I had rough discussion about this with David@kernel.org at LPC. It took
me a while to find a free time to look at this problem again. Writing
the findings below.

Problem Summary
---------------

I have observed cases where unmovable kernel allocations (for example
order-0 page table allocations in pte_alloc_one() / GFP_KERNEL_ACCOUNT)
trigger the global OOM killer even though tens of GiB of CMA memory
remain completely free and non-CMA ZONE_NORMAL is filled with ordinary,
unpinned, unlocked movable anonymous pages (mlocked=0, unevictable=0).

This happens because:

1. In mm/page_alloc.c (__rmqueue()), movable allocations (ALLOC_CMA)
   only prefer MIGRATE_CMA when:

     zone_page_state(zone, NR_FREE_CMA_PAGES) >
         zone_page_state(zone, NR_FREE_PAGES) / 2

   i.e., free_cma > free_non_cma. Whenever free_non_cma >= free_cma,
   movable allocations go into non-CMA first, and once
   free_cma == free_non_cma they interleave 50/50 between non-CMA and
   CMA.

2. Unmovable kernel allocations (GFP_KERNEL, GFP_KERNEL_ACCOUNT,
   GFP_PGTABLE_USER, slab, etc.) do not set ALLOC_CMA and cannot use
   MIGRATE_CMA; zone_watermark_ok() subtracts NR_FREE_CMA_PAGES.

3. Reclaim (shrink_folio_list() / kswapd / direct reclaim) has no path
   to migrate ordinary movable pages from non-CMA ZONE_NORMAL into free
   CMA pageblocks when non-CMA is exhausted. Without swap (or before
   swap-out makes progress), the zone is declared all_unreclaimable and
   the OOM killer fires despite large free_cma.

This affects both ends of CMA sizing:

- Small/moderate CMA (e.g. ~6-10% of RAM, such as cma=64G on a 1 TiB
  server): free_non_cma > free_cma initially, so movable pages fill
  non-CMA first without touching CMA at all, then interleave 50/50.
  Once CMA-backed allocations (or short-lived tasks using CMA) are
  freed, non-CMA remains packed with movable pages while tens of GiB
  of CMA are free, and unmovable kernel allocations OOM.

- Large CMA (e.g. ~90% of RAM): initially free_cma > free_non_cma so
  movable pages go into CMA first, but once utilization crosses ~80%
  (free_cma <= free_non_cma), movable pages spill into the remaining
  ~10% non-CMA region. If CMA memory is later freed (e.g. a large
  workload or CMA user exits), those spilled movable pages stay stuck
  in the small non-CMA region with no migration back into CMA, leaving
  almost no headroom for unmovable kernel allocations and triggering
  OOM even when most of the 90% CMA region is free.

Questions for Discussion
------------------------

1. Are others seeing this in production or testing (either with small/
   moderate CMA like 10% / 64 GiB or large CMA like 90% of RAM)?
2. Is this considered critical enough to address in core MM?
3. If so, what approach makes the most sense:
   - Migrating movable pages from non-CMA into free CMA pageblocks
     during reclaim/direct-reclaim before declaring OOM (when an
     unmovable allocation fails watermarks and free_cma is high)?



Empirical Results
-----------------

We reproduced this on latest upstream mm-unstable (7.4.0-rc4, commit
e685fdf67323) on bare metal and on QEMU:

1. Bare-metal x86_64 server (2 NUMA nodes, 1 TiB RAM, 240 CPUs,
   SwapTotal=0, cma=64G on Node 0):
   - Initial: MemTotal=1031559 MiB, CmaTotal=65536 MiB,
     CmaFree=65425 MiB, NonCmaFree=957184 MiB.
   - Phase 1 filled non-CMA with ordinary movable anonymous pages (no
     mlock, no pinning). For the first ~378 GiB on Node 0, CmaFree
     stayed untouched at 65425 MiB; once free_non_cma dropped to
     free_cma, allocations interleaved 50/50.
   - Phase 1b released only the CMA-backed movable chunks (27512 MiB),
     leaving CmaFree=27425 MiB (26.8 GiB) and NonCmaFree=4190 MiB,
     with AnonPages=991840 MiB (~968.6 GiB) of ordinary movable pages
     in non-CMA.
   - Phase 2 forked a child (oom_score_adj=1000) that read-faulted 1
     byte per 2 MiB stride (mapping ZERO_PAGE, allocating 0 bytes of
     anon data and only unmovable 4 KiB PTE pages via GFP_PGTABLE_USER).
   - Result: Global OOM kill on order:0 GFP_KERNEL_ACCOUNT
     (pte_alloc_one) while Node 0 Normal still had free: 28255484 kB
     (26.95 GiB), of which free_cma: 28007800 kB (26.71 GiB, 7001950
     pages, including 6804 * 4 MiB contiguous CMA blocks) was completely
     free, and inactive_anon across Nodes 0-1 was 1015649760 kB
     (968.6 GiB).

2. QEMU x86_64 guest (1 NUMA node, 6 GiB RAM, SwapTotal=0, cma=2G,
   7.3.0-rc5+):
   - Initial: MemTotal=5908 MiB, CmaTotal=2048 MiB, CmaFree=2041 MiB,
     NonCmaFree=3809 MiB.
   - After Phase 1b: CmaFree=1212 MiB, NonCmaFree=141 MiB,
     AnonPages=4480 MiB (mlocked=0, unevictable=0).
   - Result: Global OOM kill on order:0 GFP_KERNEL_ACCOUNT
     (pte_alloc_one) while Node 0 Normal still had free: 1177552 kB
     (1150 MiB), of which free_cma: 1155020 kB (1128 MiB, 288755 pages)
     was completely free, and inactive_anon was 4681980 kB (4572 MiB).

Bare-Metal Logs (1 TiB, 2-node x86_64, cma=64G, mm-unstable e685fdf67323)
-------------------------------------------------------------------------

Userspace output:
  [initial] MemTotal=1031559M MemFree=1022609M CmaTotal=65536M CmaFree=65425M NonCmaFree=957184M AnonPages=1204M PageTables=17M
  [parent] Phase 1: Filling memory with MOVABLE anon pages (fast_chunk=256 MiB, fine_chunk=8 MiB, stopping when NonCmaFree <= 4096 MiB)...
  ...
  [phase1-fill] MemTotal=1031559M MemFree=4054M CmaTotal=65536M CmaFree=1M NonCmaFree=4052M AnonPages=1019352M PageTables=2009M
  [parent] Phase 1b: Released 3439 CMA-backed movable chunks (27512 MiB); kept 16545 non-CMA movable chunks (990688 MiB).
  [after-phase1b] MemTotal=1031559M MemFree=31616M CmaTotal=65536M CmaFree=27425M NonCmaFree=4190M AnonPages=991840M PageTables=1955M
  [child] Starting unmovable PTE pressure (pid=97176, target up to 40960 MiB PTEs)...
  [child-pte] MemTotal=1031559M MemFree=30044M CmaTotal=65536M CmaFree=27425M NonCmaFree=2618M AnonPages=991817M PageTables=4407M
  [parent] RESULT: Child pid=97176 KILLED by signal 9 (OOM!)
  [after-child] MemTotal=1031559M MemFree=31123M CmaTotal=65536M CmaFree=26799M NonCmaFree=4323M AnonPages=991899M PageTables=2728M

Kernel dmesg excerpt:
  [    0.008909] cma: Reserved 65536 MiB at 0x0000000100000000
  [    5.034599] Memory: 988516404K/1073281896K available (... 67108864K cma-reserved)
  ...
  [ 3622.384925] <task> invoked oom-killer: gfp_mask=0x440dc0(GFP_KERNEL_ACCOUNT|__GFP_ZERO|__GFP_COMP), order=0, oom_score_adj=0
  [ 3622.384949]  dump_header+0x43/0x130
  [ 3622.384952]  oom_kill_process+0x19b/0x200
  [ 3622.384957]  out_of_memory+0x4d0/0x5d0
  [ 3622.384959]  __alloc_pages_may_oom+0xeb/0x1a0
  [ 3622.384963]  __alloc_pages_slowpath+0xa55/0xef0
  [ 3622.384967]  __alloc_frozen_pages_noprof+0x31a/0x3d0
  [ 3622.384970]  alloc_pages_mpol+0x113/0x1c0
  [ 3622.384974]  alloc_pages_noprof+0x80/0xa0
  [ 3622.384976]  pte_alloc_one+0x19/0x70
  [ 3622.384980]  __pte_alloc+0x1c/0x150
  [ 3622.385021] Mem-Info:
  [ 3622.385031] active_anon:196 inactive_anon:253912440 isolated_anon:0
                 active_file:442 inactive_file:1018 isolated_file:2
                 unevictable:4594 dirty:0 writeback:0
                 slab_reclaimable:23182 slab_unreclaimable:368818
                 mapped:3093 shmem:210 pagetables:1192489
                 sec_pagetables:5160 bounce:0
                 kernel_misc_reclaimable:0
                 free:7737714 free_pcp:38 free_cma:7001950
  [ 3622.385037] Node 0 active_anon:316kB inactive_anon:491776084kB active_file:1768kB inactive_file:0kB unevictable:18244kB ... anon_thp:491393024kB ... pagetables:2848468kB ... all_unreclaimable? yes
  [ 3622.385042] Node 1 active_anon:468kB inactive_anon:523873676kB active_file:0kB inactive_file:4096kB unevictable:132kB ... anon_thp:523440128kB ... pagetables:1921488kB ... all_unreclaimable? yes
  [ 3622.385058] Node 0 Normal free:28255484kB boost:186368kB min:251124kB low:777320kB high:1303516kB ... inactive_anon:491776084kB ... unevictable:18244kB ... managed:526196068kB mlocked:18244kB ... free_cma:28007800kB
  [ 3622.385066] Node 1 Normal free:879556kB boost:815104kB min:880120kB low:1408420kB high:1936720kB ... inactive_anon:523873676kB ... unevictable:132kB ... managed:528300712kB mlocked:56kB ... free_cma:0kB
  [ 3622.385082] Node 0 Normal: 9953*4kB (UMEC) 5402*8kB (UMEC) 2700*16kB (UMEC) 1448*32kB (UMEC) 728*64kB (UMEC) 320*128kB (UMEC) 98*256kB (UMC) 44*512kB (MC) 37*1024kB (UMC) 18*2048kB (MC) 6804*4096kB (C) = 28251668kB
  [ 3622.385107] Free swap  = 0kB
  [ 3622.385107] Total swap = 0kB
  [ 3622.385110] 16777216 pages cma reserved
  [ 3622.386443] oom-kill:constraint=CONSTRAINT_NONE,nodemask=(null),...,mems_allowed=0-1,global_oom,task_memcg=/,task=cma_normal_mova,pid=97176,uid=0
  [ 3622.386465] Out of memory: Killed process 97176 (cma_normal_mova) total-vm:1412925328kB, anon-rss:1014465136kB, file-rss:0kB, shmem-rss:0kB, UID:0 pgtables:2764784kB oom_score_adj:1000

QEMU Logs (6 GiB, 1-node x86_64, cma=2G, 7.3.0-rc5+)
----------------------------------------------------

Userspace output:
  [initial] MemTotal=5908M MemFree=5850M CmaTotal=2048M CmaFree=2041M NonCmaFree=3809M AnonPages=0M PageTables=0M
  [after-phase1b] MemTotal=5908M MemFree=1353M CmaTotal=2048M CmaFree=1212M NonCmaFree=141M AnonPages=4480M PageTables=9M
  [parent] RESULT: Child pid=98 KILLED by signal 9 (OOM!)

Kernel dmesg excerpt:
  [   62.187905] cma_normal_mova invoked oom-killer: gfp_mask=0x440dc0(GFP_KERNEL_ACCOUNT|__GFP_ZERO|__GFP_COMP), order=0, oom_score_adj=1000
  [   62.191406] active_anon:452 inactive_anon:1170495 isolated_anon:0
                 free:301251 free_pcp:2200 free_cma:288755
  [   62.191663] Node 0 active_anon:1808kB inactive_anon:4681980kB active_file:100kB inactive_file:0kB unevictable:0kB ... pagetables:111780kB ... all_unreclaimable? yes
  [   62.191807] Node 0 DMA32 free:27452kB ... min:22516kB ... inactive_anon:2898872kB ... mlocked:0kB ... free_cma:0kB
  [   62.192037] Node 0 Normal free:1177552kB ... min:22536kB ... inactive_anon:1783108kB ... mlocked:0kB ... free_cma:1155020kB
  [   62.195826] Out of memory: Killed process 98 (cma_normal_mova) total-vm:52823176kB, anon-rss:4680740kB, file-rss:24kB, shmem-rss:0kB, UID:0 pgtables:102360kB oom_score_adj:1000

How to Reproduce
----------------

1. Save the two inline files below as:
   - cma_normal_movable_oom.c
   - run_cma_oom_qemu.sh

2. Bare-metal reproduction:
   - Boot a kernel built with CONFIG_CMA=y and CONFIG_DMA_CMA=y, with a
     CMA reservation (e.g. cma=64G on a 1 TiB host, or cma=8G on a
     32 GiB host) and swap disabled (swapoff -a).
   - Compile:
       gcc -O2 -Wall -Wextra -static cma_normal_movable_oom.c -o cma_normal_movable_oom
   - Run as root (from the root memory cgroup if the SSH session sits
     in a memory-limited cgroup):
       ./cma_normal_movable_oom <leave_non_cma_mb> <max_pte_mb> [fast_chunk_mb]
     Examples:
       # 1 TiB host with cma=64G:
       ./cma_normal_movable_oom 4096 40960 256
       # 16-32 GiB host with cma=4G-8G:
       ./cma_normal_movable_oom 256 4096 64
   - Check dmesg for "invoked oom-killer", "free_cma:", and
     "Killed process".

3. QEMU reproduction (~1 minute; requires qemu-system-x86_64, gcc,
   static busybox, and a bzImage built with CONFIG_CMA=y and
   CONFIG_DMA_CMA=y):
     chmod +x run_cma_oom_qemu.sh
     ./run_cma_oom_qemu.sh /path/to/bzImage

Any feedback on whether others are seeing this and whether non-CMA ->
CMA migration (or another mitigation) is worth pursuing would be very
helpful.

Thanks,
Tarun
===================================================
Script that I used to trigger OOM to observe this.
===================================================


#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <unistd.h>

struct mem_stats {
	unsigned long mem_total_kb;
	unsigned long mem_free_kb;
	unsigned long mem_avail_kb;
	unsigned long anon_kb;
	unsigned long pagetables_kb;
	unsigned long cma_total_kb;
	unsigned long cma_free_kb;
};

static void read_meminfo(struct mem_stats *s)
{
	FILE *f = fopen("/proc/meminfo", "r");
	char line[256];

	memset(s, 0, sizeof(*s));
	if (!f)
		return;

	while (fgets(line, sizeof(line), f)) {
		unsigned long val;

		if (sscanf(line, "MemTotal: %lu kB", &val) == 1)
			s->mem_total_kb = val;
		else if (sscanf(line, "MemFree: %lu kB", &val) == 1)
			s->mem_free_kb = val;
		else if (sscanf(line, "MemAvailable: %lu kB", &val) == 1)
			s->mem_avail_kb = val;
		else if (sscanf(line, "AnonPages: %lu kB", &val) == 1)
			s->anon_kb = val;
		else if (sscanf(line, "PageTables: %lu kB", &val) == 1)
			s->pagetables_kb = val;
		else if (sscanf(line, "CmaTotal: %lu kB", &val) == 1)
			s->cma_total_kb = val;
		else if (sscanf(line, "CmaFree: %lu kB", &val) == 1)
			s->cma_free_kb = val;
	}
	fclose(f);
}

static void print_stats(const char *tag)
{
	struct mem_stats s;
	long non_cma_free_kb;

	read_meminfo(&s);
	non_cma_free_kb = (long)s.mem_free_kb - (long)s.cma_free_kb;
	printf("[%s] MemTotal=%luM MemFree=%luM CmaTotal=%luM CmaFree=%luM "
	       "NonCmaFree=%ldM AnonPages=%luM PageTables=%luM\n",
	       tag,
	       s.mem_total_kb / 1024,
	       s.mem_free_kb / 1024,
	       s.cma_total_kb / 1024,
	       s.cma_free_kb / 1024,
	       non_cma_free_kb / 1024,
	       s.anon_kb / 1024,
	       s.pagetables_kb / 1024);
	fflush(stdout);
}

static void set_oom_score_adj(int val)
{
	int fd = open("/proc/self/oom_score_adj", O_WRONLY);
	char buf[32];
	int n;

	if (fd < 0)
		return;
	n = snprintf(buf, sizeof(buf), "%d\n", val);
	if (write(fd, buf, n) < 0)
		perror("write oom_score_adj");
	close(fd);
}

static void *mmap_aligned_2m(size_t sz)
{
	const size_t align = 2ULL << 20;
	uintptr_t raw, aligned;
	size_t head, tail;
	void *p;

	p = mmap(NULL, sz + align, PROT_READ | PROT_WRITE,
		 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
	if (p == MAP_FAILED)
		return MAP_FAILED;

	raw = (uintptr_t)p;
	aligned = (raw + align - 1) & ~(align - 1);
	head = aligned - raw;
	tail = (raw + sz + align) - (aligned + sz);
	if (head)
		munmap((void *)raw, head);
	if (tail)
		munmap((void *)(aligned + sz), tail);
	return (void *)aligned;
}

/*
 * Phase 2 child: allocate pure unmovable kernel page tables (GFP_PGTABLE_USER)
 * by sparsely reading 1 byte per 2 MiB across MAP_PRIVATE|MAP_ANONYMOUS VMAs
 * (with MADV_NOHUGEPAGE). Each read fault maps the shared ZERO_PAGE (0 bytes
 * of movable anon data allocated) while allocating a 4 KiB unmovable PTE page.
 */
static void run_unmovable_pte_child(unsigned long max_pte_mb)
{
	const size_t vma_size = 4ULL << 30; /* 4 GiB per VMA -> 8 MiB of PTEs */
	const size_t stride = 2ULL << 20;   /* 2 MiB per PTE page */
	unsigned long pte_pages = 0;
	unsigned long max_pte_pages = max_pte_mb * 256;

	set_oom_score_adj(1000);
	printf("[child] Starting unmovable PTE pressure (pid=%d, target up to %lu MiB PTEs)...\n",
	       getpid(), max_pte_mb);
	fflush(stdout);

	while (pte_pages < max_pte_pages) {
		char *p = mmap(NULL, vma_size, PROT_READ | PROT_WRITE,
			       MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
		if (p == MAP_FAILED) {
			printf("[child] mmap failed after %lu MiB PTEs: %s\n",
			       pte_pages / 256, strerror(errno));
			fflush(stdout);
			_exit(2);
		}
		madvise(p, vma_size, MADV_NOHUGEPAGE);
		for (size_t off = 0; off < vma_size; off += stride) {
			volatile char v = p[off];
			(void)v;
			pte_pages++;
			if ((pte_pages % (512 * 256)) == 0)
				print_stats("child-pte");
		}
	}

	printf("[child] Completed %lu MiB PTEs without OOM\n", pte_pages / 256);
	fflush(stdout);
	_exit(0);
}

struct chunk_rec {
	void *addr;
	size_t sz;
	bool mostly_cma;
};

int main(int argc, char **argv)
{
	struct mem_stats s, s_before;
	unsigned long leave_non_cma_mb = 128;
	unsigned long max_pte_mb = 2048;
	size_t fast_chunk_sz = 64ULL << 20;
	size_t fine_chunk_sz = 2ULL << 20;
	struct chunk_rec *chunks = NULL;
	size_t n_chunks = 0, cap_chunks = 0;
	size_t freed_cma_chunks = 0, freed_cma_mb = 0, kept_mb = 0;
	bool cma_interleave = false;
	pid_t pid;
	int status = 0;

	if (argc > 1)
		leave_non_cma_mb = strtoul(argv[1], NULL, 0);
	if (argc > 2)
		max_pte_mb = strtoul(argv[2], NULL, 0);
	if (argc > 3)
		fast_chunk_sz = strtoul(argv[3], NULL, 0) << 20;

	/* Protect parent from being OOM-killed before child */
	set_oom_score_adj(-500);

	print_stats("initial");
	read_meminfo(&s);
	if (s.cma_total_kb == 0) {
		fprintf(stderr, "ERROR: CmaTotal == 0 (boot with cma=...)\n");
		return 1;
	}
	if (argc <= 3 && s.mem_total_kb > (64ULL << 20))
		fast_chunk_sz = 256ULL << 20;
	if (s.cma_total_kb > (8ULL << 20))
		fine_chunk_sz = 8ULL << 20;

	/*
	 * Phase 1: Allocate ordinary MOVABLE anonymous pages (no mlock, no
	 * pinning) until NonCmaFree <= leave_non_cma_mb. Use smaller 2 MiB
	 * aligned chunks while CMA is actively interleaving so each chunk
	 * lands predominantly in either CMA or non-CMA.
	 */
	printf("[parent] Phase 1: Filling memory with MOVABLE anon pages "
	       "(fast_chunk=%zu MiB, fine_chunk=%zu MiB, stopping when NonCmaFree <= %lu MiB)...\n",
	       fast_chunk_sz >> 20, fine_chunk_sz >> 20, leave_non_cma_mb);
	fflush(stdout);

	while (1) {
		long non_cma_free_mb, delta_cma_kb;
		size_t cur_sz;
		char *buf;

		read_meminfo(&s_before);
		non_cma_free_mb = ((long)s_before.mem_free_kb - (long)s_before.cma_free_kb) / 1024;
		if (non_cma_free_mb <= (long)leave_non_cma_mb)
			break;

		if (cma_interleave && s_before.cma_free_kb < (64ULL << 10))
			cma_interleave = false;
		cur_sz = cma_interleave ? fine_chunk_sz : fast_chunk_sz;

		buf = mmap_aligned_2m(cur_sz);
		if (buf == MAP_FAILED) {
			perror("parent mmap");
			break;
		}
		madvise(buf, cur_sz, MADV_HUGEPAGE);
		for (size_t off = 0; off < cur_sz; off += 4096)
			buf[off] = (char)(n_chunks + 1);

		read_meminfo(&s);
		delta_cma_kb = (long)s_before.cma_free_kb - (long)s.cma_free_kb;
		if (!cma_interleave && delta_cma_kb > 0 && s.cma_free_kb >= (64ULL << 10))
			cma_interleave = true;

		if (n_chunks == cap_chunks) {
			cap_chunks = cap_chunks ? cap_chunks * 2 : 1024;
			chunks = realloc(chunks, cap_chunks * sizeof(*chunks));
			if (!chunks)
				return 1;
		}
		chunks[n_chunks].addr = buf;
		chunks[n_chunks].sz = cur_sz;
		chunks[n_chunks].mostly_cma = (delta_cma_kb >= (long)(cur_sz / 1024) * 3 / 4);
		n_chunks++;

		if ((cur_sz == fast_chunk_sz && (n_chunks % 16) == 0) ||
		    (cur_sz == fine_chunk_sz && (n_chunks % 2048) == 0))
			print_stats("phase1-fill");
	}

	/*
	 * Phase 1b: Release only the chunks that landed almost entirely in CMA
	 * (simulating short-lived processes or CMA users exiting). Now CmaFree
	 * is huge again, while non-CMA ZONE_NORMAL remains packed with movable
	 * anonymous pages that Linux will NOT migrate into CmaFree.
	 */
	for (size_t i = 0; i < n_chunks; i++) {
		if (chunks[i].mostly_cma) {
			munmap(chunks[i].addr, chunks[i].sz);
			chunks[i].addr = NULL;
			freed_cma_chunks++;
			freed_cma_mb += chunks[i].sz >> 20;
		} else {
			kept_mb += chunks[i].sz >> 20;
		}
	}

	printf("[parent] Phase 1b: Released %zu CMA-backed movable chunks (%zu MiB); "
	       "kept %zu non-CMA movable chunks (%zu MiB).\n",
	       freed_cma_chunks, freed_cma_mb,
	       n_chunks - freed_cma_chunks, kept_mb);
	print_stats("after-phase1b");

	/*
	 * Phase 2: Fork child to allocate unmovable PTEs while non-CMA is
	 * filled with movable pages and CmaFree is huge.
	 */
	pid = fork();
	if (pid < 0) {
		perror("fork");
		return 1;
	}
	if (pid == 0)
		run_unmovable_pte_child(max_pte_mb);

	waitpid(pid, &status, 0);
	if (WIFSIGNALED(status)) {
		printf("[parent] RESULT: Child pid=%d KILLED by signal %d (OOM!)\n",
		       pid, WTERMSIG(status));
	} else if (WIFEXITED(status)) {
		printf("[parent] RESULT: Child pid=%d exited with code %d\n",
		       pid, WEXITSTATUS(status));
	}
	print_stats("after-child");

	/* Clean up remaining movable allocations */
	for (size_t i = 0; i < n_chunks; i++) {
		if (chunks[i].addr)
			munmap(chunks[i].addr, chunks[i].sz);
	}
	free(chunks);
	return 0;
}


=====================================================================
Shell Script to run the above script:
=====================================================================

#!/bin/bash
set -euo pipefail

if [ $# -lt 1 ]; then
	echo "Usage: $0 <path/to/bzImage> [mem_gb=6] [cma_gb=2]" >&2
	exit 1
fi

BZIMAGE="$1"
MEM_GB="${2:-6}"
CMA_GB="${3:-2}"
WORKDIR="$(mktemp -d /tmp/cma_oom_qemu.XXXXXX)"
trap 'rm -rf "$WORKDIR"' EXIT

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SRC="${SCRIPT_DIR}/cma_normal_movable_oom.c"
if [ ! -f "$SRC" ]; then
	echo "ERROR: $SRC not found next to this script." >&2
	exit 1
fi

BUSYBOX="$(command -v busybox || true)"
if [ -z "$BUSYBOX" ]; then
	echo "ERROR: static busybox is required to build the minimal initramfs." >&2
	exit 1
fi

echo "=== Building static cma_normal_movable_oom ==="
gcc -O2 -Wall -Wextra -static "$SRC" -o "$WORKDIR/cma_normal_movable_oom"

echo "=== Building minimal initramfs ==="
ROOT="$WORKDIR/initrd"
mkdir -p "$ROOT"/{bin,dev,proc,sys}
cp "$BUSYBOX" "$ROOT/bin/busybox"
cp "$WORKDIR/cma_normal_movable_oom" "$ROOT/bin/cma_normal_movable_oom"
chmod +x "$ROOT/bin/busybox" "$ROOT/bin/cma_normal_movable_oom"

cat > "$ROOT/init" <<'EOF'
#!/bin/busybox sh
/bin/busybox --install -s /bin
mount -t proc proc /proc
mount -t sysfs sysfs /sys
mount -t devtmpfs devtmpfs /dev 2>/dev/null || true

echo "=== Kernel ==="
uname -a
cat /proc/cmdline

echo "=== Running cma_normal_movable_oom ==="
/bin/cma_normal_movable_oom 128 2048

echo "=== dmesg OOM excerpt ==="
dmesg | grep -E "invoked oom-killer|Out of memory:|Killed process|free_cma:|Normal free:|DMA32 free:|active_anon:|all_unreclaimable" | tail -n 30

echo "=== Powering off ==="
poweroff -f
EOF
chmod +x "$ROOT/init"

(cd "$ROOT" && find . -print0 | cpio --null -ov --format=newc 2>/dev/null | gzip -9 > "$WORKDIR/initrd.cpio.gz")

KVM_ARGS=""
if [ -w /dev/kvm ]; then
	KVM_ARGS="-enable-kvm -cpu host"
else
	KVM_ARGS="-cpu max"
fi

echo "=== Launching QEMU (${MEM_GB}G RAM, cma=${CMA_GB}G) ==="
qemu-system-x86_64 \
	-nographic -no-reboot \
	$KVM_ARGS \
	-smp 4 \
	-m "${MEM_GB}G" \
	-kernel "$BZIMAGE" \
	-initrd "$WORKDIR/initrd.cpio.gz" \
	-append "console=ttyS0 cma=${CMA_GB}G panic=-1 quiet" </dev/null

==============================================================
End of Script
==============================================================


^ permalink raw reply	[flat|nested] 3+ messages in thread

end of thread, other threads:[~2026-12-03 18:25 UTC | newest]

Thread overview: 3+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-03 17:58 [RFC] OOM on unmovable kernel allocations with large free CMA (no non-CMA -> CMA migration) tarunsahu
2026-12-03 18:19 ` Frank van der Linden
2026-12-03 18:25 ` Michal Hocko

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox