[RFC PATCH 02/11] mm/memblock: factor out multi-range contiguous reservation helper from CMA

Suseendran Bhaskaran suseendranb at google.com
Tue Dec 1 16:19:37 PST 2026


cma_declare_contiguous_multi() picks the largest free memblock ranges
above a minimum address, reserves each slice, and sorts the resulting
list by physical base address. Boot-time external memory carving needs
the same multi-range selection when firmware holes split a NUMA node,
plus optional top-down trimming, partial ("max") reservations, hotplug
range inclusion (MEMBLOCK_CONTIG_INCLUDE_HOTPLUG), and per-range node IDs.

Move this loop into memblock_reserve_contig_multi() in mm/memblock.c, run
accept_memory() once all ranges are reserved, and add unit tests in
tools/testing/memblock/. Single-range cma_alloc_mem() and its
CONFIG_HIGHMEM fallback stay in mm/cma.c.

Signed-off-by: Suseendran Bhaskaran <suseendranb at google.com>
---
 mm/cma.c                                      | 101 ++++-----------
 mm/memblock.c                                 | 122 +++++++++++++++++-
 mm/mm_init.h                                  |  19 ++-
 tools/testing/memblock/Makefile               |   2 +-
 tools/testing/memblock/main.c                 |   2 +
 tools/testing/memblock/mm_init.h              |  23 +++-
 .../testing/memblock/tests/alloc_multi_api.c  | 103 +++++++++++++++
 .../testing/memblock/tests/alloc_multi_api.h  |   9 ++
 8 files changed, 301 insertions(+), 80 deletions(-)
 create mode 100644 tools/testing/memblock/tests/alloc_multi_api.c
 create mode 100644 tools/testing/memblock/tests/alloc_multi_api.h

diff --git a/mm/cma.c b/mm/cma.c
index c0db52b4ae29..02865d5a10b5 100644
--- a/mm/cma.c
+++ b/mm/cma.c
@@ -24,7 +24,6 @@
 #include <linux/slab.h>
 #include <linux/string.h>
 #include <linux/log2.h>
-#include <linux/sort.h>
 #include <linux/cma.h>
 #include <linux/highmem.h>
 #include <linux/io.h>
@@ -500,46 +499,6 @@ static int __init __cma_declare_contiguous_nid(phys_addr_t *basep,
 	return 0;
 }
 
-/*
- * Find the largest free range above 4G that can hold a part of a multi-range
- * CMA area.
- */
-static phys_addr_t __init cma_find_free_range(phys_addr_t align,
-		phys_addr_t size_align, int nid, phys_addr_t *basep)
-{
-#ifdef CONFIG_PHYS_ADDR_T_64BIT
-	enum memblock_flags flags = choose_memblock_flags() & ~MEMBLOCK_MIRROR;
-	phys_addr_t start, end, size, orig_start;
-	phys_addr_t max = 0;
-	u64 i;
-
-	for_each_free_mem_range(i, nid, flags, &start, &end, NULL) {
-		orig_start = max_t(phys_addr_t, start, SZ_4G);
-		start = ALIGN(orig_start, align);
-		if (start < orig_start || start >= end)
-			continue;
-
-		size = ALIGN_DOWN(end - start, size_align);
-		if (size > max) {
-			max = size;
-			*basep = start;
-		}
-	}
-
-	return max;
-#else
-	return 0;
-#endif
-}
-
-static int __init cma_range_cmp(const void *a, const void *b)
-{
-	const struct cma_memrange *cmr_a = a;
-	const struct cma_memrange *cmr_b = b;
-
-	return cmp_int(cmr_a->base_pfn, cmr_b->base_pfn);
-}
-
 /*
  * Create CMA areas with a total size of @total_size. A normal allocation
  * for one area is tried first. If that fails, the area is assembled from
@@ -550,12 +509,11 @@ int __init cma_declare_contiguous_multi(phys_addr_t total_size,
 			const char *name, struct cma **res_cma, int nid)
 {
 	const unsigned long size_mb = (unsigned long)total_size / SZ_1M;
-	phys_addr_t size, remaining, size_align;
+	struct memblock_contig_range ranges[CMA_MAX_RANGES];
 	struct cma_memrange *cmrp;
 	phys_addr_t start = 0;
 	struct cma *cma;
-	int nr = 0;
-	int ret;
+	int nr, i, ret;
 
 	/*
 	 * First, try it the normal way, producing just one range.
@@ -569,6 +527,10 @@ int __init cma_declare_contiguous_multi(phys_addr_t total_size,
 	if (ret != -ENOMEM)
 		goto err;
 
+	/* no point searching if the system can't address above 4G */
+	if (!IS_ENABLED(CONFIG_PHYS_ADDR_T_64BIT))
+		goto err;
+
 	/*
 	 * Couldn't find one range that fits our needs, so try multiple
 	 * ranges.
@@ -589,38 +551,32 @@ int __init cma_declare_contiguous_multi(phys_addr_t total_size,
 	if (ret)
 		goto err;
 
+#ifdef CONFIG_PHYS_ADDR_T_64BIT
 	align = max_t(phys_addr_t, align, CMA_MIN_ALIGNMENT_BYTES);
-	size_align = max_t(phys_addr_t, align, PAGE_SIZE << order_per_bit);
-
-	remaining = total_size;
-	while (remaining && nr < CMA_MAX_RANGES) {
-		size = cma_find_free_range(align, size_align, nid, &start);
-		if (!size)
-			break;
-
-		size = min(size, remaining);
-		if (memblock_reserve(start, size))
-			break;
-		accept_memory(start, size);
+	nr = memblock_reserve_contig_multi(total_size, align,
+					   max_t(phys_addr_t, align,
+						 PAGE_SIZE << order_per_bit),
+					   SZ_4G, nid, 0,
+					   ranges, CMA_MAX_RANGES);
+#else
+	nr = -ENOMEM;
+#endif
+	if (nr < 0) {
+		ret = nr;
+		cma_drop_area(cma);
+		goto err;
+	}
 
+	for (i = 0; i < nr; i++) {
 		pr_debug("created region %d: %016llx - %016llx\n",
-		    nr, (u64)start, (u64)start + size);
-		cmrp = &cma->ranges[nr++];
-		cmrp->base_pfn = PHYS_PFN(start);
+			 i, (u64)ranges[i].base,
+			 (u64)ranges[i].base + ranges[i].size);
+		cmrp = &cma->ranges[i];
+		cmrp->base_pfn = PHYS_PFN(ranges[i].base);
 		cmrp->early_pfn = cmrp->base_pfn;
-		cmrp->count = size >> PAGE_SHIFT;
-
-		remaining -= size;
-	}
-
-	if (remaining) {
-		ret = -ENOMEM;
-		goto err_free_ranges;
+		cmrp->count = ranges[i].size >> PAGE_SHIFT;
 	}
 
-	/* allocate from lower addresses first */
-	sort(cma->ranges, nr, sizeof(cma->ranges[0]), cma_range_cmp, NULL);
-
 	cma->nranges = nr;
 	cma->nid = nid;
 	*res_cma = cma;
@@ -628,11 +584,6 @@ int __init cma_declare_contiguous_multi(phys_addr_t total_size,
 	pr_info("Reserved %lu MiB in %d ranges\n", size_mb, nr);
 	return 0;
 
-err_free_ranges:
-	for (int i = 0; i < nr; i++)
-		memblock_phys_free(PFN_PHYS(cma->ranges[i].base_pfn),
-				   PFN_PHYS(cma->ranges[i].count));
-	cma_drop_area(cma);
 err:
 	pr_err("Failed to reserve %lu MiB\n", size_mb);
 	return ret;
diff --git a/mm/memblock.c b/mm/memblock.c
index d81f2074e16e..f95f06412efa 100644
--- a/mm/memblock.c
+++ b/mm/memblock.c
@@ -6,6 +6,7 @@
  * Copyright (C) 2001 Peter Bergner.
  */
 
+#include <linux/align.h>
 #include <linux/kernel.h>
 #include <linux/slab.h>
 #include <linux/init.h>
@@ -172,7 +173,7 @@ bool __init_memblock memblock_has_mirror(void)
 	return system_has_some_mirror;
 }
 
-enum memblock_flags __init_memblock choose_memblock_flags(void)
+static enum memblock_flags __init_memblock choose_memblock_flags(void)
 {
 	/* only use KHO_NOPRSRV memory for kho early boot allocations */
 	if (kho_noprsrv_only)
@@ -1626,6 +1627,125 @@ phys_addr_t __init memblock_alloc_range_nid(phys_addr_t size,
 	return found;
 }
 
+static phys_addr_t __init
+memblock_find_largest_free_range(phys_addr_t align, phys_addr_t size_align,
+				 phys_addr_t min_addr, int nid,
+				 enum memblock_flags mb_flags, bool top_down,
+				 phys_addr_t *basep, int *out_nid)
+{
+	phys_addr_t start, end, orig_start, size, max_size = 0;
+	int rnid;
+	u64 i;
+
+	for_each_free_mem_range(i, nid, mb_flags, &start, &end, &rnid) {
+		orig_start = max(start, min_addr);
+		start = ALIGN(orig_start, align);
+		if (top_down)
+			end = ALIGN_DOWN(end, align);
+		if (start < orig_start || start >= end)
+			continue;
+
+		size = ALIGN_DOWN(end - start, size_align);
+		if (size > max_size || (top_down && size && size == max_size)) {
+			max_size = size;
+			*basep = top_down ? end - size : start;
+			*out_nid = rnid;
+		}
+	}
+
+	return max_size;
+}
+
+/**
+ * memblock_reserve_contig_multi - reserve a pool across multiple free ranges
+ * @total_size: total bytes to reserve (or cap for partial mode)
+ * @align: base address alignment (power of 2)
+ * @size_align: per-range size alignment (power of 2, >= @align)
+ * @min_addr: lower physical address bound
+ * @nid: target NUMA node ID, or %NUMA_NO_NODE for any node
+ * @flags: %MEMBLOCK_CONTIG_* modifiers
+ * @ranges: caller-allocated output array of length @max_ranges
+ * @max_ranges: maximum number of contiguous ranges to reserve
+ *
+ * Greedily selects up to @max_ranges of the largest free memblock ranges at or
+ * above @min_addr, reserves them, keeps @ranges sorted ascending by physical
+ * base, and accepts unaccepted memory once the reservation succeeds.
+ *
+ * Return: number of reserved ranges (>= 0) on success, or negative errno.
+ */
+int __init memblock_reserve_contig_multi(phys_addr_t total_size,
+					 phys_addr_t align,
+					 phys_addr_t size_align,
+					 phys_addr_t min_addr, int nid,
+					 unsigned int flags,
+					 struct memblock_contig_range *ranges,
+					 int max_ranges)
+{
+	bool allow_partial = flags & MEMBLOCK_CONTIG_ALLOW_PARTIAL;
+	bool top_down = flags & MEMBLOCK_CONTIG_TOP_DOWN;
+	phys_addr_t remaining, start, size, take;
+	enum memblock_flags mb_flags;
+	int nr = 0, i, rnid;
+
+	if (WARN_ON_ONCE(slab_is_available()))
+		return -EBUSY;
+	if (!ranges || max_ranges <= 0 ||
+	    !align || (align & (align - 1)) ||
+	    !size_align || (size_align & (size_align - 1)))
+		return -EINVAL;
+
+	size_align = max(size_align, align);
+	if (allow_partial)
+		total_size = ALIGN_DOWN(total_size, size_align);
+	if (!total_size || !IS_ALIGNED(total_size, size_align))
+		return -EINVAL;
+
+	min_addr = max_t(phys_addr_t, min_addr, PAGE_SIZE);
+	mb_flags = choose_memblock_flags() & ~MEMBLOCK_MIRROR;
+	if (flags & MEMBLOCK_CONTIG_INCLUDE_HOTPLUG)
+		mb_flags |= MEMBLOCK_HOTPLUG;
+
+	remaining = total_size;
+	while (remaining && nr < max_ranges) {
+		size = memblock_find_largest_free_range(align, size_align,
+							min_addr, nid, mb_flags,
+							top_down, &start,
+							&rnid);
+		if (!size)
+			break;
+
+		take = min(size, remaining);
+		if (top_down)
+			start += size - take;
+
+		if (memblock_reserve(start, take))
+			goto err_free;
+
+		for (i = nr; i > 0 && ranges[i - 1].base > start; i--)
+			ranges[i] = ranges[i - 1];
+		ranges[i] = (struct memblock_contig_range) {
+			.base = start,
+			.size = take,
+			.nid = rnid,
+		};
+		nr++;
+		remaining -= take;
+	}
+
+	if (remaining && !allow_partial)
+		goto err_free;
+
+	for (i = 0; i < nr; i++)
+		accept_memory(ranges[i].base, ranges[i].size);
+
+	return nr;
+
+err_free:
+	for (i = 0; i < nr; i++)
+		memblock_phys_free(ranges[i].base, ranges[i].size);
+	return -ENOMEM;
+}
+
 /**
  * memblock_phys_alloc_range - allocate a memory block inside specified range
  * @size: size of memory block to be allocated in bytes
diff --git a/mm/mm_init.h b/mm/mm_init.h
index 245baa769add..5f6e4ac87fcd 100644
--- a/mm/mm_init.h
+++ b/mm/mm_init.h
@@ -9,8 +9,8 @@
 #define __MM_MM_INIT_H
 
 #include <linux/types.h>
+#include <linux/bits.h>
 #include <linux/init.h>
-#include <linux/memblock.h>
 #include <linux/mmzone.h>
 #include <linux/jump_label.h>
 #include <linux/printk.h>
@@ -100,9 +100,24 @@ static inline void mminit_verify_zonelist(void)
 
 extern bool mirrored_kernelcore;
 bool memblock_has_mirror(void);
-enum memblock_flags choose_memblock_flags(void);
 void memblock_free_all(void);
 
+struct memblock_contig_range {
+	phys_addr_t base;
+	phys_addr_t size;
+	int nid;
+};
+
+#define MEMBLOCK_CONTIG_TOP_DOWN		BIT(0)
+#define MEMBLOCK_CONTIG_ALLOW_PARTIAL		BIT(1)
+#define MEMBLOCK_CONTIG_INCLUDE_HOTPLUG		BIT(2)
+
+int memblock_reserve_contig_multi(phys_addr_t total_size, phys_addr_t align,
+				  phys_addr_t size_align, phys_addr_t min_addr,
+				  int nid, unsigned int flags,
+				  struct memblock_contig_range *ranges,
+				  int max_ranges);
+
 void memmap_init_page(struct page *page, enum zone_type zone, int nid);
 void __meminit memmap_init_compound_page(struct page *head, unsigned long pfn,
 		const struct zone *zone, unsigned int order);
diff --git a/tools/testing/memblock/Makefile b/tools/testing/memblock/Makefile
index 20524fcbe3c7..dbaf3c88547d 100644
--- a/tools/testing/memblock/Makefile
+++ b/tools/testing/memblock/Makefile
@@ -8,7 +8,7 @@ LDFLAGS += -fsanitize=address -fsanitize=undefined
 TARGETS = main
 TEST_OFILES = tests/alloc_nid_api.o tests/alloc_helpers_api.o tests/alloc_api.o \
 		  tests/basic_api.o tests/common.o tests/alloc_exact_nid_api.o \
-		  tests/alloc_low_api.o
+		  tests/alloc_low_api.o tests/alloc_multi_api.o
 DEP_OFILES = memblock.o lib/slab.o mmzone.o slab.o cmdline.o
 OFILES = main.o $(DEP_OFILES) $(TEST_OFILES)
 EXTR_SRC = ../../../mm/memblock.c
diff --git a/tools/testing/memblock/main.c b/tools/testing/memblock/main.c
index 9a96e178551b..2c21d0485052 100644
--- a/tools/testing/memblock/main.c
+++ b/tools/testing/memblock/main.c
@@ -5,6 +5,7 @@
 #include "tests/alloc_nid_api.h"
 #include "tests/alloc_exact_nid_api.h"
 #include "tests/alloc_low_api.h"
+#include "tests/alloc_multi_api.h"
 #include "tests/common.h"
 
 int main(int argc, char **argv)
@@ -16,6 +17,7 @@ int main(int argc, char **argv)
 	memblock_alloc_low_checks();
 	memblock_alloc_nid_checks();
 	memblock_alloc_exact_nid_checks();
+	memblock_alloc_multi_checks();
 
 	return 0;
 }
diff --git a/tools/testing/memblock/mm_init.h b/tools/testing/memblock/mm_init.h
index 95bc5f2e8ed8..5b1cc957c9d7 100644
--- a/tools/testing/memblock/mm_init.h
+++ b/tools/testing/memblock/mm_init.h
@@ -2,7 +2,28 @@
 #ifndef __MM_MM_INIT_H
 #define __MM_MM_INIT_H
 
-void memblock_free_pages(unsigned long pfn, unsigned int order)
+#include <linux/bits.h>
+#include <linux/types.h>
+
+extern bool mirrored_kernelcore;
+
+struct memblock_contig_range {
+	phys_addr_t base;
+	phys_addr_t size;
+	int nid;
+};
+
+#define MEMBLOCK_CONTIG_TOP_DOWN		BIT(0)
+#define MEMBLOCK_CONTIG_ALLOW_PARTIAL		BIT(1)
+#define MEMBLOCK_CONTIG_INCLUDE_HOTPLUG		BIT(2)
+
+int memblock_reserve_contig_multi(phys_addr_t total_size, phys_addr_t align,
+				  phys_addr_t size_align, phys_addr_t min_addr,
+				  int nid, unsigned int flags,
+				  struct memblock_contig_range *ranges,
+				  int max_ranges);
+
+static inline void memblock_free_pages(unsigned long pfn, unsigned int order)
 {
 }
 
diff --git a/tools/testing/memblock/tests/alloc_multi_api.c b/tools/testing/memblock/tests/alloc_multi_api.c
new file mode 100644
index 000000000000..5c125e638b4b
--- /dev/null
+++ b/tools/testing/memblock/tests/alloc_multi_api.c
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+#include "alloc_multi_api.h"
+#include "../mm_init.h"
+#include <linux/align.h>
+
+static void setup_fragmented_32k(phys_addr_t base)
+{
+	reset_memblock_regions();
+	ASSERT_EQ(memblock_add(base, SZ_32K), 0);
+	ASSERT_EQ(memblock_reserve(base + SZ_4K, SZ_4K), 0);
+	ASSERT_EQ(memblock_reserve(base + 5 * SZ_4K, SZ_4K), 0);
+}
+
+static int alloc_multi_checks(void)
+{
+	struct memblock_contig_range ranges[4];
+	phys_addr_t base = ALIGN(dummy_physical_memory_base(), SZ_4K);
+	int nr;
+
+	PREFIX_PUSH();
+
+	/* Bottom-up trim across 4K, 12K, and 8K free spans, sorted by base. */
+	setup_fragmented_32k(base);
+	nr = memblock_reserve_contig_multi(SZ_16K, SZ_4K, SZ_4K, base,
+					   NUMA_NO_NODE, 0, ranges, 4);
+	ASSERT_EQ(nr, 2);
+	ASSERT_EQ(ranges[0].base, base + SZ_8K);
+	ASSERT_EQ(ranges[0].size, 3 * SZ_4K);
+	ASSERT_EQ(ranges[1].base, base + 6 * SZ_4K);
+	ASSERT_EQ(ranges[1].size, SZ_4K);
+
+	/* Top-down trim on the same layout takes the upper 4K of [24K, 32K). */
+	setup_fragmented_32k(base);
+	nr = memblock_reserve_contig_multi(SZ_16K, SZ_4K, SZ_4K, base,
+					   NUMA_NO_NODE,
+					   MEMBLOCK_CONTIG_TOP_DOWN, ranges, 4);
+	ASSERT_EQ(nr, 2);
+	ASSERT_EQ(ranges[0].base, base + SZ_8K);
+	ASSERT_EQ(ranges[0].size, 3 * SZ_4K);
+	ASSERT_EQ(ranges[1].base, base + 7 * SZ_4K);
+	ASSERT_EQ(ranges[1].size, SZ_4K);
+
+	/* Range straddling min_addr is clamped at min_addr, not skipped. */
+	reset_memblock_regions();
+	ASSERT_EQ(memblock_add(base, SZ_32K), 0);
+	nr = memblock_reserve_contig_multi(SZ_16K, SZ_4K, SZ_4K, base + SZ_8K,
+					   NUMA_NO_NODE, 0, ranges, 2);
+	ASSERT_EQ(nr, 1);
+	ASSERT_EQ(ranges[0].base, base + SZ_8K);
+	ASSERT_EQ(ranges[0].size, SZ_16K);
+
+	/* Unsatisfied strict request rolls back partial reservations. */
+	reset_memblock_regions();
+	ASSERT_EQ(memblock_add(base, SZ_32K), 0);
+	ASSERT_EQ(memblock_reserve(base + SZ_8K, SZ_8K), 0);
+	nr = memblock_reserve_contig_multi(7 * SZ_4K, SZ_4K, SZ_4K, base,
+					   NUMA_NO_NODE, 0, ranges, 4);
+	ASSERT_EQ(nr, -ENOMEM);
+	ASSERT_EQ(memblock.reserved.cnt, 1);
+	ASSERT_EQ(memblock.reserved.total_size, SZ_8K);
+
+	/* ALLOW_PARTIAL reserves all aligned spans up to PHYS_ADDR_MAX. */
+	nr = memblock_reserve_contig_multi(PHYS_ADDR_MAX, SZ_4K, SZ_4K, base,
+					   NUMA_NO_NODE,
+					   MEMBLOCK_CONTIG_TOP_DOWN |
+					   MEMBLOCK_CONTIG_ALLOW_PARTIAL,
+					   ranges, 4);
+	ASSERT_EQ(nr, 2);
+	ASSERT_EQ(ranges[0].base, base);
+	ASSERT_EQ(ranges[0].size, SZ_8K);
+	ASSERT_EQ(ranges[1].base, base + SZ_16K);
+	ASSERT_EQ(ranges[1].size, SZ_16K);
+
+	/* Non-mirrored spans remain eligible under mirrored_kernelcore. */
+	reset_memblock_regions();
+	ASSERT_EQ(memblock_add(base, SZ_32K), 0);
+	mirrored_kernelcore = true;
+	ASSERT_EQ(memblock_mark_mirror(base, SZ_8K), 0);
+	nr = memblock_reserve_contig_multi(SZ_16K, SZ_4K, SZ_4K, base,
+					   NUMA_NO_NODE, 0, ranges, 2);
+	ASSERT_EQ(nr, 1);
+	ASSERT_EQ(ranges[0].base, base + SZ_8K);
+	mirrored_kernelcore = false;
+
+	test_pass_pop();
+	return 0;
+}
+
+int memblock_alloc_multi_checks(void)
+{
+	prefix_reset();
+	prefix_push("memblock_reserve_contig_multi");
+	test_print("Running memblock_reserve_contig_multi tests...\n");
+
+	reset_memblock_attributes();
+	dummy_physical_memory_init();
+	run_top_down(alloc_multi_checks);
+	run_bottom_up(alloc_multi_checks);
+	dummy_physical_memory_cleanup();
+	prefix_pop();
+
+	return 0;
+}
diff --git a/tools/testing/memblock/tests/alloc_multi_api.h b/tools/testing/memblock/tests/alloc_multi_api.h
new file mode 100644
index 000000000000..d3c43fea680b
--- /dev/null
+++ b/tools/testing/memblock/tests/alloc_multi_api.h
@@ -0,0 +1,9 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+#ifndef _MEMBLOCK_ALLOC_MULTI_H
+#define _MEMBLOCK_ALLOC_MULTI_H
+
+#include "common.h"
+
+int memblock_alloc_multi_checks(void);
+
+#endif



More information about the linux-arm-kernel mailing list