[PATCH 04/11] of: reserved_mem: skip reserved_mem array allocation when there is nothing to save

Chen Wandun
2026-04-29T06:59:24Z

fdt_scan_reserved_mem_late() unconditionally calls
alloc_reserved_mem_array() after confirming /reserved-memory exists.
Two issues with that:

- When __reserved_mem_check_root() subsequently fails, the call
returns right away, leaving the freshly allocated array unused.
- When /reserved-memory exists but fdt_scan_reserved_mem() found no
entries to save (total_reserved_mem_cnt stays at its freshly-set
value of zero, e.g. empty node or all children disabled),
alloc_reserved_mem_array() ends up calling memblock_alloc() with
zero size, which returns NULL and logs an "Failed to allocate
memory for reserved_mem array" error even though nothing was
expected to be allocated.

Move alloc_reserved_mem_array() past the root-node check and gate it
on total_reserved_mem_cnt, so the array is only allocated when there
is at least one entry that needs a slot.

Fixes: 00c9a452a235 ("of: reserved_mem: Add code to dynamically allocate reserved_mem array")
Signed-off-by: Chen Wandun <chenwandun@lixiang.com>
Tested-by: Zhao Meijing <zhaomeijing@lixiang.com>
---
drivers/of/of_reserved_mem.c | 14 +++++++++++---
1 file changed, 11 insertions(+), 3 deletions(-)

diff --git a/drivers/of/of_reserved_mem.c b/drivers/of/of_reserved_mem.c
index 807b222fce5f..93585af9f8a3 100644
--- a/drivers/of/of_reserved_mem.c
+++ b/drivers/of/of_reserved_mem.c
@@ -276,14 +276,22 @@ void __init fdt_scan_reserved_mem_late(void)
return;
}

- /* Attempt dynamic allocation of a new reserved_mem array */
- alloc_reserved_mem_array();
-
if (__reserved_mem_check_root(node)) {
pr_err("Reserved memory: unsupported node format, ignoring\n");
return;
}

+ /*
+ * fdt_scan_reserved_mem() sets total_reserved_mem_cnt to the
+ * number of entries that need a slot in reserved_mem[]. If it is
+ * zero there is nothing to allocate or save.
+ */
+ if (!total_reserved_mem_cnt)
+ return;
+
+ /* Attempt dynamic allocation of a new reserved_mem array */
+ alloc_reserved_mem_array();
+
fdt_for_each_subnode(child, fdt, node) {
const char *uname;
int i, len;
--
2.43.0