Skip to contentSkip to conversation

kho: make boot time huge page allocation work nicely with KHO

PATCH Superseded Pratyush Yadav 3 participants 38 messages Jun 5 – Jun 16

Subsystems (5)

v2 of 6 Superseded Latest is v6 →

lore
Share & tools
lore

Pratyush Yadav

author maintainer
#0 lore raw

v2 cover kho: make boot time huge page allocation work nicely with KHO

From: "Pratyush Yadav (Google)" <[email protected]>

Hi,

Gigantic huge page allocation is somewhat broken currently with KHO.

First, they break scratch size accounting. Since they are allocated using the memblock alloc APIs, they count towards RSRV_KERN, and this scratch size when using scratch_scale. This means if huge pages take a large enough chunk of system memory scratch size will blow up and fail to allocate.

Second, scratch can not contain preserved memory, and if hugepages are allocated from scratch, they will fail to be preserved with the upcoming hugetlb preservation series [0].

Fix this by introducing the concept of extended scratch areas. They are areas that the kernel discovers on boot by walking the radix tree and finding free memory ranges. See patch 10 for more details.

Discovering the scratch areas needs some preparatory changes to KHO, the radix tree APIs, and to memblock. Patches 1-14 do that.

Patch 15 adds the scratch discovery logic.

Patch 16 adds the dedicated memblock hugetlb allocator.

Patch 17-18 fix the scratch size calculation with using scratch_scale.

[0] https://lore.kernel.org/linux-mm/[email protected]/T/#u

Changes in v2:

Detailed changelog below.

At a high level, the major change in this version is to remove MEMBLOCK_KHO_SCRATCH_EXT. Keep MEMBLOCK_KHO_SCRATCH as the only memory type and mark the discovered areas with it. For HugeTLB, add a dedicated allocation routine and if allocated memory lands in scratch, do a retry. Also introduce MEMBLOCK_RSRV_HUGETLB to help with accounting of scratch area sizes.

- Fixup commit message in patch 1 to make namespacing change clearer.
- Use @key in kernel-doc for radix functions.
- Add a runtime check on key width.
- Move all mem retrieval logic to kho_mem_retrieve().
- Add a comment in kho_mem_retrieve() explaining why mem_map won't be NULL.
- Rename callbacks to ->leaf() and ->node().
- Fixup commit messages.
- Clear tree->root in kho_radix_destroy_tree(). This lets the tree be re-initialized by calling kho_radix_init_tree()
- Add kho_get_mem_map() earlier in the series.
- Export kho_scratch_overlap() and use it in memblock_is_kho_scratch_memory().
- Get rid of MEMBLOCK_KHO_SCRATCH_EXT.
- Introduce MEMBLOCK_RSRV_HUGETLB.
- Introduce memblock_alloc_hugetlb() for hugetlb bootmem allocations.
- Refactor memblock_reserved_kern_size() to allow calculating size by flags.
- Exclude hugetlb memory from scratch size calculation.
- Collect R-bys.

Regards,
Pratyush Yadav

Pratyush Yadav (Google) (18):
kho: generalize radix tree APIs
kho: disallow wide keys in radix tree
kho: return virtual address of mem_map
kho: store incoming radix tree in kho_in
kho: move all memory retrieval logic to kho_mem_retrieve()
kho: add a struct for radix callbacks
kho: add callback for table pages
kho: add data argument to radix walk callback
kho: allow early-boot usage of the KHO radix tree
kho: allow destroying KHO radix tree
kho: add kho_radix_init_tree()
kho: export kho_scratch_overlap()
kho: initialize kho_scratch pointer earlier in boot
memblock: use kho_scratch_overlap() to decide migratetype
kho: extend scratch
memblock: make HugeTLB bootmem allocation work with KHO
memblock: allow calculating reserved size by flags
kho: exclude hugetlb memory from scratch size calculation

 include/linux/kexec_handover.h              |  10 +
 include/linux/kho/abi/kexec_handover.h      |   8 +
 include/linux/kho_radix_tree.h              |  44 +-
 include/linux/memblock.h                    |   9 +-
 kernel/liveupdate/Makefile                  |   1 -
 kernel/liveupdate/kexec_handover.c          | 495 +++++++++++++++-----
 kernel/liveupdate/kexec_handover_debug.c    |  25 -
 kernel/liveupdate/kexec_handover_internal.h |   9 -
 mm/hugetlb.c                                |  22 +-
 mm/memblock.c                               | 120 ++++-
 mm/mm_init.c                                |   1 +
 11 files changed, 540 insertions(+), 204 deletions(-)
 delete mode 100644 kernel/liveupdate/kexec_handover_debug.c

base-commit: 2935777b418d2bfcbfe96705bb2c0fa6c0d94e18

Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
author maintainer
#1 lore raw

PATCH v2 1/18 kho: generalize radix tree APIs

From: "Pratyush Yadav (Google)" <[email protected]>

The KHO radix tree is a data structure that can track the presence or absence of an arbitrary key, with nothing inherently tied to KHO memory preservation tracking. This was one of the design goals of the radix tree. This was done to enable it to be re-used by other users of KHO.

Despite that, the radix tree APIs are very closely tied to KHO memory preservation tracking. Adding a key is done by kho_radix_add_page(), which encodes it as a page tracking operation and takes in PFN and order. kho_radix_del_page() does the same. These functions encode the key internally that goes into the radix tree. kho_radix_walk_tree() does the same by baking the PFN and order into the callback arguments.

Generalize the APIs by taking the key directly and doing the encoding at the callers. Rename the functions to kho_radix_add_key() and kho_radix_del_key(). In practice, this removes a line each from the functions and moves the encoding function call to the callers. Similarly, update kho_radix_tree_walk_callback_t to take the key directly.

Now that key encoding is no longer an inherent part of the radix tree and can be decided by the user, rename kho_radix_{encode,decode}_key() to kho_{encode,decode}_radix_key(). This moves them out of the "kho_radix_" name space into the "kho_" namespace. This emphasizes that this is KHO's way of encoding the key for its radix tree.

---
 include/linux/kho_radix_tree.h     | 18 +++----
 kernel/liveupdate/kexec_handover.c | 76 ++++++++++++++----------------
 2 files changed, 42 insertions(+), 52 deletions(-)
include/linux/kho_radix_tree.h +6 -12
index 84e918b96e53..f368f3b9f923 100644
@@ -34,30 +34,24 @@ struct kho_radix_tree {
 	struct mutex lock; /* protects the tree's structure and root pointer */
 };
 
-typedef int (*kho_radix_tree_walk_callback_t)(phys_addr_t phys,
-					      unsigned int order);
+typedef int (*kho_radix_tree_walk_callback_t)(unsigned long key);
 
 #ifdef CONFIG_KEXEC_HANDOVER
 
-int kho_radix_add_page(struct kho_radix_tree *tree, unsigned long pfn,
-		       unsigned int order);
-
-void kho_radix_del_page(struct kho_radix_tree *tree, unsigned long pfn,
-			unsigned int order);
-
+int kho_radix_add_key(struct kho_radix_tree *tree, unsigned long key);
+void kho_radix_del_key(struct kho_radix_tree *tree, unsigned long key);
 int kho_radix_walk_tree(struct kho_radix_tree *tree,
 			kho_radix_tree_walk_callback_t cb);
 
 #else  /* #ifdef CONFIG_KEXEC_HANDOVER */
 
-static inline int kho_radix_add_page(struct kho_radix_tree *tree, long pfn,
-				     unsigned int order)
+static inline int kho_radix_add_key(struct kho_radix_tree *tree, unsigned long key)
 {
 	return -EOPNOTSUPP;
 }
 
-static inline void kho_radix_del_page(struct kho_radix_tree *tree,
-				      unsigned long pfn, unsigned int order) { }
+static inline void kho_radix_del_key(struct kho_radix_tree *tree,
+				     unsigned long key) { }
 
 static inline int kho_radix_walk_tree(struct kho_radix_tree *tree,
 				      kho_radix_tree_walk_callback_t cb)
kernel/liveupdate/kexec_handover.c +36 -40

190 lines not on this page · raw message

Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
author maintainer
#2 lore raw

PATCH v2 2/18 kho: disallow wide keys in radix tree

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

The KHO radix tree was designed to track preserved pages. So it does not provide the capability to track any 64-bit key. Instead, it limits the key width to how much it needs for tracking PFNs and their orders. Limiting the width reduces the number of levels in the tree.

KHO is not expected to be the only user of the radix tree. With the API generalized to allow other users, now it is possible to add any key to the tree.

Check the key width at kho_radix_add_key(), and error out if it exceeds what the tree can handle. Do this instead of increasing the tree depth since right now there are no users that need to use wider keys, so this avoids memory overhead and ABI breakage.

---
 include/linux/kho/abi/kexec_handover.h |  8 ++++++++
 kernel/liveupdate/kexec_handover.c     | 12 ++++++++++++
 2 files changed, 20 insertions(+)
include/linux/kho/abi/kexec_handover.h +8 -0
index fb2d37417ad9..6dbb98bfb586 100644
@@ -278,6 +278,14 @@ enum kho_radix_consts {
 			     KHO_TABLE_SIZE_LOG2) + 1,
 };
 
+/*
+ * The maximum key width this radix tree can track.
+ *
+ * This value isn't ABI itself, but it is derived from values that are ABI.
+ */
+#define KHO_RADIX_KEY_WIDTH (((KHO_TREE_MAX_DEPTH - 1) * KHO_TABLE_SIZE_LOG2) + \
+			     KHO_BITMAP_SIZE_LOG2)
+
 struct kho_radix_node {
 	u64 table[1 << KHO_TABLE_SIZE_LOG2];
 };
kernel/liveupdate/kexec_handover.c +12 -0
index 7349cc82f6dc..e8454dc5b489 100644
@@ -153,6 +153,11 @@ static unsigned long kho_radix_get_table_index(unsigned long key,
  * intermediate nodes do not exist along the path, they are allocated and added
  * to the tree.
  *
+ * NOTE: Currently only keys of width up to %KHO_RADIX_KEY_WIDTH are supported.
+ * This limit only exists because current users of the radix tree don't use more
+ * than that. Changing the maximum width requires changing the tree depth, which
+ * needs bumping the ABI version.
+ *
  * Return: 0 on success, or a negative error code on failure.
  */
 int kho_radix_add_key(struct kho_radix_tree *tree, unsigned long key)
@@ -169,6 +174,9 @@ int kho_radix_add_key(struct kho_radix_tree *tree, unsigned long key)
 	if (WARN_ON_ONCE(!tree->root))
 		return -EINVAL;
 
+	if (unlikely(fls64(key) > KHO_RADIX_KEY_WIDTH))
+		return -ERANGE;
+
 	might_sleep();
 
 	guard(mutex)(&tree->lock);
@@ -241,6 +249,10 @@ void kho_radix_del_key(struct kho_radix_tree *tree, unsigned long key)
 	if (WARN_ON_ONCE(!tree->root))
 		return;
 
+	/* Keys wider than KHO_RADIX_KEY_WIDTH are not allowed to be added. */
+	if (unlikely(fls64(key) > KHO_RADIX_KEY_WIDTH))
+		return;
+
 	might_sleep();
 
 	guard(mutex)(&tree->lock);
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
#3 lore raw

Re: [PATCH v2 02/18] kho: disallow wide keys in radix tree

Quoted 27 lines · Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

The KHO radix tree was designed to track preserved pages. So it does not provide the capability to track any 64-bit key. Instead, it limits the key width to how much it needs for tracking PFNs and their orders. Limiting the width reduces the number of levels in the tree.

KHO is not expected to be the only user of the radix tree. With the API generalized to allow other users, now it is possible to add any key to the tree.

Check the key width at kho_radix_add_key(), and error out if it exceeds what the tree can handle. Do this instead of increasing the tree depth since right now there are no users that need to use wider keys, so this avoids memory overhead and ABI breakage.

---
include/linux/kho/abi/kexec_handover.h | 8 ++++++++
kernel/liveupdate/kexec_handover.c | 12 ++++++++++++

2 files changed, 20 insertions(+)
include/linux/kho/abi/kexec_handover.h +0 -0
index fb2d37417ad9..6dbb98bfb586 100644

include/linux/kho/abi/kexec_handover.h enum kho_radix_consts { · line 287

Quoted 10 lines
include/linux/kho/abi/kexec_handover.h +7 -0
@@ -278,6 +278,14 @@ enum kho_radix_consts {
 			     KHO_TABLE_SIZE_LOG2) + 1,
 };
 
+/*
+ * The maximum key width this radix tree can track.
+ *
+ * This value isn't ABI itself, but it is derived from values that are ABI.
+ */
+#define KHO_RADIX_KEY_WIDTH (((KHO_TREE_MAX_DEPTH - 1) * KHO_TABLE_SIZE_LOG2) + \
+			     KHO_BITMAP_SIZE_LOG2)

Love the auto-derivation of these values, this totally makes sense. That said, my lazy brain complained a bit when I asked it "so how many bits can a consumer actually use?". So I wonder:

1) Why is the value not "ABI itself"; it feels like it should as it determines client behavior.

2) Would you consider expanding the actual values for the most relevant architectures (x86-64 w/ 4kb pages, arm64 w/ 4k/16/64k page-sizes) and put it in a block-comment?

include/linux/kho/abi/kexec_handover.h enum kho_radix_consts { · line 291

Quoted 4 lines
include/linux/kho/abi/kexec_handover.h +4 -0
+ * NOTE: Currently only keys of width up to %KHO_RADIX_KEY_WIDTH are supported.
+ * This limit only exists because current users of the radix tree don't use more
+ * than that. Changing the maximum width requires changing the tree depth, which
+ * needs bumping the ABI version.

It takes longer to walk the tree. The current implementation is a good tradeoff.

Best,
Jork

author maintainer
#4 lore raw

Re: [PATCH v2 02/18] kho: disallow wide keys in radix tree

Quoted 44 lines · Jork Loeser
Quoted 27 lines · Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

The KHO radix tree was designed to track preserved pages. So it does not provide the capability to track any 64-bit key. Instead, it limits the key width to how much it needs for tracking PFNs and their orders. Limiting the width reduces the number of levels in the tree.

KHO is not expected to be the only user of the radix tree. With the API generalized to allow other users, now it is possible to add any key to the tree.

Check the key width at kho_radix_add_key(), and error out if it exceeds what the tree can handle. Do this instead of increasing the tree depth since right now there are no users that need to use wider keys, so this avoids memory overhead and ABI breakage.

---
include/linux/kho/abi/kexec_handover.h | 8 ++++++++
kernel/liveupdate/kexec_handover.c | 12 ++++++++++++

2 files changed, 20 insertions(+)
include/linux/kho/abi/kexec_handover.h +0 -0
index fb2d37417ad9..6dbb98bfb586 100644

include/linux/kho/abi/kexec_handover.h enum kho_radix_consts { · line 287

Quoted 10 lines
include/linux/kho/abi/kexec_handover.h +7 -0
@@ -278,6 +278,14 @@ enum kho_radix_consts {
 			     KHO_TABLE_SIZE_LOG2) + 1,
 };
 
+/*
+ * The maximum key width this radix tree can track.
+ *
+ * This value isn't ABI itself, but it is derived from values that are ABI.
+ */
+#define KHO_RADIX_KEY_WIDTH (((KHO_TREE_MAX_DEPTH - 1) * KHO_TABLE_SIZE_LOG2) + \
+			     KHO_BITMAP_SIZE_LOG2)

Love the auto-derivation of these values, this totally makes sense. That said, my lazy brain complained a bit when I asked it "so how many bits can a consumer actually use?". So I wonder:

Quoted 2 lines

1) Why is the value not "ABI itself"; it feels like it should as it determines client behavior.

The main idea was that if you delve into the details, the value is a combination of other values, and doesn't directly influence the binary structure. For example, KHO_ORDER_0_LOG2 (64 - PAGE_SHIFT) influences it directly. It decides the width of the keys that can be supported.

But now that I think of this again, I think this patch is kind of stupid. The equation for KHO_RADIX_KEY_WIDTH is exactly the inverse of the equation KHO_TREE_MAX_DEPTH. The max key width is (KHO_ORDER_0_LOG2
+ 1), and the equation for KHO_TREE_MAX_DEPTH uses that to arrive at the tree depth.

All this is very obscure unfortunately. First of all, KHO_ORDER_0_LOG2 is a very undescriptive name. I have no idea what it is supposed to mean or represent. The comment above doesn't help much either and I think is misleading.

Second, the equation for KHO_TREE_MAX_DEPTH hides in itself the fact that we need one extra bit on top of KHO_ORDER_0_LOG2. KHO_ORDER_0_LOG2 is essentially the width of PFN. And we need one more bit for the order. That +1 is hidden in

    DIV_ROUND_UP(KHO_ORDER_0_LOG2 - KHO_BITMAP_SIZE_LOG2 + 1, ...),

I think we should to the following:

1. Rename KHO_ORDER_0_LOG2 to KHO_RADIX_KEY_WIDTH and make its equation (64 - PAGE_SHIFT + 1) with the comment above clearly explaining the reasoning.

2. Now that the +1 is in the key width itself, the equation for tree depth can be simplified to:

       ((KHO_RADIX_KEY_WIDTH - KHO_BITMAP_SIZE_LOG2) / KHO_TABLE_SIZE_LOG2) + 1

... which is an improvement I think.

I've been tripped by this radix tree math before, so I think this might help out a bit. Will fix that in the next version.

Quoted 4 lines

2) Would you consider expanding the actual values for the most relevant architectures (x86-64 w/ 4kb pages, arm64 w/ 4k/16/64k page-sizes) and put it in a block-comment?

Good idea. Will do.

[...]

Signature · 2 lines
Regards,
Pratyush Yadav
author maintainer
#5 lore raw

PATCH v2 3/18 kho: return virtual address of mem_map

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

Currently it is only used by kho_populate(), which doesn't care whether the address is virtual or physical and only cares that it exists and is valid. In coming patches, more callers will be added, all of which will need the virtual address.

Make things simpler by directly returning the virtual address. Rename kho_get_mem_map_phys() to kho_get_mem_map() to accurately reflect what it returns.

---
 kernel/liveupdate/kexec_handover.c | 18 +++++++++++-------
 1 file changed, 11 insertions(+), 7 deletions(-)
kernel/liveupdate/kexec_handover.c +11 -7
index e8454dc5b489..d8dd0ede4f87 100644
@@ -509,10 +509,11 @@ static int __init kho_preserved_memory_reserve(unsigned long key)
 	return 0;
 }
 
-/* Returns physical address of the preserved memory map from FDT */
-static phys_addr_t __init kho_get_mem_map_phys(const void *fdt)
+/* Returns virtual address of the preserved memory map from FDT */
+static __init void *kho_get_mem_map(const void *fdt)
 {
 	const void *mem_ptr;
+	phys_addr_t mem_map_phys;
 	int len;
 
 	mem_ptr = fdt_getprop(fdt, 0, KHO_FDT_MEMORY_MAP_PROP_NAME, &len);
@@ -521,7 +522,11 @@ static phys_addr_t __init kho_get_mem_map_phys(const void *fdt)
 		return 0;
 	}
 
-	return get_unaligned((const u64 *)mem_ptr);
+	mem_map_phys = get_unaligned((const u64 *)mem_ptr);
+	if (!mem_map_phys)
+		return NULL;
+
+	return phys_to_virt(mem_map_phys);
 }
 
 /*
@@ -1644,8 +1649,7 @@ void __init kho_populate(phys_addr_t fdt_phys, u64 fdt_len,
 {
 	unsigned int scratch_cnt = scratch_len / sizeof(*kho_scratch);
 	struct kho_scratch *scratch = NULL;
-	phys_addr_t mem_map_phys;
-	void *fdt = NULL;
+	void *fdt = NULL, *mem_map;
 	bool populated = false;
 	int err;
 
@@ -1668,8 +1672,8 @@ void __init kho_populate(phys_addr_t fdt_phys, u64 fdt_len,
 		goto unmap_fdt;
 	}
 
-	mem_map_phys = kho_get_mem_map_phys(fdt);
-	if (!mem_map_phys)
+	mem_map = kho_get_mem_map(fdt);
+	if (!mem_map)
 		goto unmap_fdt;
 
 	scratch = early_memremap(scratch_phys, scratch_len);
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
maintainer
#6 lore raw

Re: [PATCH v2 03/18] kho: return virtual address of mem_map

kernel/liveupdate/kexec_handover.c static phys_addr_t __init kho_get_mem_map_phys(const void *fdt) · line 522

Quoted 6 lines · Pratyush Yadav
kernel/liveupdate/kexec_handover.c +0 -0
index e8454dc5b489..d8dd0ede4f87 100644
@@ -521,7 +522,11 @@ static phys_addr_t __init kho_get_mem_map_phys(const void *fdt)
 		return 0;

sashiko:

Does this error path need to be updated to return NULL? Since the function signature was changed to return a void pointer instead of phys_addr_t, returning a plain integer 0 instead of NULL might trigger static analysis warnings.

kernel/liveupdate/kexec_handover.c void __init kho_populate(phys_addr_t fdt_phys, u64 fdt_len, · line 1676

Quoted 8 lines
kernel/liveupdate/kexec_handover.c +2 -2
@@ -1668,8 +1672,8 @@ void __init kho_populate(phys_addr_t fdt_phys, u64 fdt_len,
 		goto unmap_fdt;
 	}
 
-	mem_map_phys = kho_get_mem_map_phys(fdt);
-	if (!mem_map_phys)
+	mem_map = kho_get_mem_map(fdt);
+	if (!mem_map)

Here we can't use mem_map as an actual pointer because phys_to_virt() returns pre-KASLR addres.

Since we only call get_mem_map() here to verify that it's available in the FDT and don't care about the actual virtual address, let's add a comment about that, drop the mem_map varialble and directly check

	if (!kho_get_mem_map_phys())
Signature · 2 lines
Sincerely yours,
Mike.
author maintainer
#7 lore raw

Re: [PATCH v2 03/18] kho: return virtual address of mem_map

Quoted 10 lines · Mike Rapoport

kernel/liveupdate/kexec_handover.c static phys_addr_t __init kho_get_mem_map_phys(const void *fdt) · line 522

Quoted 6 lines · Pratyush Yadav
kernel/liveupdate/kexec_handover.c +0 -0
index e8454dc5b489..d8dd0ede4f87 100644
@@ -521,7 +522,11 @@ static phys_addr_t __init kho_get_mem_map_phys(const void *fdt)
 		return 0;

sashiko:

Quoted 4 lines

Does this error path need to be updated to return NULL? Since the function signature was changed to return a void pointer instead of phys_addr_t, returning a plain integer 0 instead of NULL might trigger static analysis warnings.

Good catch, will fix.

Quoted 5 lines
Quoted 5 lines
kernel/liveupdate/kexec_handover.c +0 -0
@@ -1668,8 +1672,8 @@ void __init kho_populate(phys_addr_t fdt_phys, u64 fdt_len,
 		goto unmap_fdt;
 	}
 
Quoted 7 lines

kernel/liveupdate/kexec_handover.c void __init kho_populate(phys_addr_t fdt_phys, u64 fdt_len, · line 1676

Quoted 4 lines
kernel/liveupdate/kexec_handover.c +2 -2
-	mem_map_phys = kho_get_mem_map_phys(fdt);
-	if (!mem_map_phys)
+	mem_map = kho_get_mem_map(fdt);
+	if (!mem_map)

Here we can't use mem_map as an actual pointer because phys_to_virt() returns pre-KASLR addres.

Ugh, yeah. It also won't work on ARM64 because memstart_addr is not set at this point.

Quoted 6 lines

Since we only call get_mem_map() here to verify that it's available in the FDT and don't care about the actual virtual address, let's add a comment about that, drop the mem_map varialble and directly check

	if (!kho_get_mem_map_phys())

Makes sense. Will do.

Signature · 2 lines
Regards,
Pratyush Yadav
author maintainer
#8 lore raw

PATCH v2 4/18 kho: store incoming radix tree in kho_in

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

This allows other functions to also use the radix tree. While at it, also use kho_get_mem_map_phys() instead of duplicating the code to get the radix tree root from the FDT.

---
 kernel/liveupdate/kexec_handover.c | 32 ++++++++++++------------------
 1 file changed, 13 insertions(+), 19 deletions(-)
kernel/liveupdate/kexec_handover.c +13 -19
index d8dd0ede4f87..61e436f5077e 100644
@@ -1334,6 +1334,7 @@ struct kho_in {
 	char previous_release[__NEW_UTS_LEN + 1];
 	u32 kexec_count;
 	struct kho_debugfs dbg;
+	struct kho_radix_tree radix_tree;
 };
 
 static struct kho_in kho_in = {
@@ -1413,24 +1414,15 @@ EXPORT_SYMBOL_GPL(kho_retrieve_subtree);
 
 static int __init kho_mem_retrieve(const void *fdt)
 {
-	struct kho_radix_tree tree;
-	const phys_addr_t *mem;
-	int len;
-
-	/* Retrieve the KHO radix tree from passed-in FDT. */
-	mem = fdt_getprop(fdt, 0, KHO_FDT_MEMORY_MAP_PROP_NAME, &len);
-
-	if (!mem || len != sizeof(*mem)) {
-		pr_err("failed to get preserved KHO memory tree\n");
-		return -ENOENT;
-	}
-
-	if (!*mem)
-		return -EINVAL;
-
-	tree.root = phys_to_virt(*mem);
-	mutex_init(&tree.lock);
-	return kho_radix_walk_tree(&tree, kho_preserved_memory_reserve);
+	/*
+	 * kho_get_mem_map() should always succeed. If it fails, kho_populate()
+	 * catches that and never sets kho_in.scratch_phys, which stops memory
+	 * retrieval.
+	 */
+	kho_in.radix_tree.root = kho_get_mem_map(fdt);
+	mutex_init(&kho_in.radix_tree.lock);
+	return kho_radix_walk_tree(&kho_in.radix_tree,
+				   kho_preserved_memory_reserve);
 }
 
 static __init int kho_out_fdt_setup(void)
@@ -1637,8 +1629,10 @@ void __init kho_memory_init(void)
 	if (kho_in.scratch_phys) {
 		kho_scratch = phys_to_virt(kho_in.scratch_phys);
 
-		if (kho_mem_retrieve(kho_get_fdt()))
+		if (kho_mem_retrieve(kho_get_fdt())) {
 			kho_in.fdt_phys = 0;
+			kho_in.radix_tree.root = NULL;
+		}
 	} else {
 		kho_reserve_scratch();
 	}
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
author maintainer
#9 lore raw

PATCH v2 5/18 kho: move all memory retrieval logic to kho_mem_retrieve()

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

The memory retrieval logic is spread out across kho_mem_retrieve() and kho_memory_init(). The incoming scratch area is initialized at kho_memory_init(), and the error handling is done there too.

Consolidate all this logic into kho_mem_retrieve() to make the code cleaner.

---
 kernel/liveupdate/kexec_handover.c | 31 ++++++++++++++++++------------
 1 file changed, 19 insertions(+), 12 deletions(-)
kernel/liveupdate/kexec_handover.c +19 -12
index 61e436f5077e..7e556afae283 100644
@@ -1412,8 +1412,13 @@ int kho_retrieve_subtree(const char *name, phys_addr_t *phys, size_t *size)
 }
 EXPORT_SYMBOL_GPL(kho_retrieve_subtree);
 
-static int __init kho_mem_retrieve(const void *fdt)
+static void __init kho_mem_retrieve(void)
 {
+	const void *fdt = kho_get_fdt();
+	int err;
+
+	kho_scratch = phys_to_virt(kho_in.scratch_phys);
+
 	/*
 	 * kho_get_mem_map() should always succeed. If it fails, kho_populate()
 	 * catches that and never sets kho_in.scratch_phys, which stops memory
@@ -1421,8 +1426,16 @@ static int __init kho_mem_retrieve(const void *fdt)
 	 */
 	kho_in.radix_tree.root = kho_get_mem_map(fdt);
 	mutex_init(&kho_in.radix_tree.lock);
-	return kho_radix_walk_tree(&kho_in.radix_tree,
-				   kho_preserved_memory_reserve);
+
+	err = kho_radix_walk_tree(&kho_in.radix_tree, kho_preserved_memory_reserve);
+	if (err) {
+		/*
+		 * Failed to initialize preserved memory. Clear FDT and radix
+		 * so KHO users don't treat it as a KHO boot.
+		 */
+		kho_in.fdt_phys = 0;
+		kho_in.radix_tree.root = NULL;
+	}
 }
 
 static __init int kho_out_fdt_setup(void)
@@ -1626,16 +1639,10 @@ fs_initcall(kho_init);
 
 void __init kho_memory_init(void)
 {
-	if (kho_in.scratch_phys) {
-		kho_scratch = phys_to_virt(kho_in.scratch_phys);
-
-		if (kho_mem_retrieve(kho_get_fdt())) {
-			kho_in.fdt_phys = 0;
-			kho_in.radix_tree.root = NULL;
-		}
-	} else {
+	if (kho_in.scratch_phys)
+		kho_mem_retrieve();
+	else
 		kho_reserve_scratch();
-	}
 }
 
 void __init kho_populate(phys_addr_t fdt_phys, u64 fdt_len,
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
author maintainer
#10 lore raw

PATCH v2 6/18 kho: add a struct for radix callbacks

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

A future commit will add more callbacks for the KHO radix tree. Add a struct for collecting the callbacks.

---
 include/linux/kho_radix_tree.h     | 15 ++++++++++++---
 kernel/liveupdate/kexec_handover.c | 27 +++++++++++++++------------
 2 files changed, 27 insertions(+), 15 deletions(-)
include/linux/kho_radix_tree.h +12 -3
index f368f3b9f923..426a9cc9bcde 100644
@@ -34,14 +34,23 @@ struct kho_radix_tree {
 	struct mutex lock; /* protects the tree's structure and root pointer */
 };
 
-typedef int (*kho_radix_tree_walk_callback_t)(unsigned long key);
+/**
+ * struct kho_radix_walk_cb - Callbacks for KHO radix tree walk.
+ * @leaf:      Called on each present key in the radix tree.
+ *
+ * For each callback, a return value of 0 continues the walk and a non-zero
+ * return value is directly returned to the caller.
+ */
+struct kho_radix_walk_cb {
+	int (*leaf)(unsigned long key);
+};
 
 #ifdef CONFIG_KEXEC_HANDOVER
 
 int kho_radix_add_key(struct kho_radix_tree *tree, unsigned long key);
 void kho_radix_del_key(struct kho_radix_tree *tree, unsigned long key);
 int kho_radix_walk_tree(struct kho_radix_tree *tree,
-			kho_radix_tree_walk_callback_t cb);
+			const struct kho_radix_walk_cb *cb);
 
 #else  /* #ifdef CONFIG_KEXEC_HANDOVER */
 
@@ -54,7 +63,7 @@ static inline void kho_radix_del_key(struct kho_radix_tree *tree,
 				     unsigned long key) { }
 
 static inline int kho_radix_walk_tree(struct kho_radix_tree *tree,
-				      kho_radix_tree_walk_callback_t cb)
+				      const struct kho_radix_walk_cb *cb)
 {
 	return -EOPNOTSUPP;
 }
kernel/liveupdate/kexec_handover.c +15 -12
index 7e556afae283..dbe075348ce4 100644
@@ -278,16 +278,18 @@ void kho_radix_del_key(struct kho_radix_tree *tree, unsigned long key)
 }
 EXPORT_SYMBOL_GPL(kho_radix_del_key);
 
-static int kho_radix_walk_leaf(struct kho_radix_leaf *leaf,
-			       unsigned long key,
-			       kho_radix_tree_walk_callback_t cb)
+static int kho_radix_walk_leaf(struct kho_radix_leaf *leaf, unsigned long key,
+			       const struct kho_radix_walk_cb *cb)
 {
 	unsigned long *bitmap = (unsigned long *)leaf;
 	unsigned int i;
 	int err;
 
+	if (!cb->leaf)
+		return 0;
+
 	for_each_set_bit(i, bitmap, PAGE_SIZE * BITS_PER_BYTE) {
-		err = cb(key | i);
+		err = cb->leaf(key | i);
 		if (err)
 			return err;
 	}
@@ -297,7 +299,7 @@ static int kho_radix_walk_leaf(struct kho_radix_leaf *leaf,
 
 static int __kho_radix_walk_tree(struct kho_radix_node *root,
 				 unsigned int level, unsigned long start,
-				 kho_radix_tree_walk_callback_t cb)
+				 const struct kho_radix_walk_cb *cb)
 {
 	struct kho_radix_node *node;
 	struct kho_radix_leaf *leaf;
@@ -337,18 +339,16 @@ static int __kho_radix_walk_tree(struct kho_radix_node *root,
 /**
  * kho_radix_walk_tree - Traverses the radix tree and calls a callback for each key.
  * @tree: A pointer to the KHO radix tree to walk.
- * @cb: A callback function of type kho_radix_tree_walk_callback_t that will be
- *      invoked for each key in the tree.
+ * @cb:   Set of callbacks to be invoked during the tree walk.
  *
- * This function walks the radix tree, searching from the specified top level
- * down to the lowest level (level 0). For each key found, it invokes the
- * provided callback.
+ * This function walks the radix tree, searching from the top level down to the
+ * lowest level (level 0), invoking the appropriate callbacks.
  *
  * Return: 0 if the walk completed the specified tree, or the non-zero return
  *         value from the callback that stopped the walk.
  */
 int kho_radix_walk_tree(struct kho_radix_tree *tree,
-			kho_radix_tree_walk_callback_t cb)
+			const struct kho_radix_walk_cb *cb)
 {
 	if (WARN_ON_ONCE(!tree->root))
 		return -EINVAL;
@@ -1414,6 +1414,9 @@ EXPORT_SYMBOL_GPL(kho_retrieve_subtree);
 
 static void __init kho_mem_retrieve(void)
 {
+	const struct kho_radix_walk_cb cb = {
+		.leaf = kho_preserved_memory_reserve,
+	};
 	const void *fdt = kho_get_fdt();
 	int err;
 
@@ -1427,7 +1430,7 @@ static void __init kho_mem_retrieve(void)
 	kho_in.radix_tree.root = kho_get_mem_map(fdt);
 	mutex_init(&kho_in.radix_tree.lock);
 
-	err = kho_radix_walk_tree(&kho_in.radix_tree, kho_preserved_memory_reserve);
+	err = kho_radix_walk_tree(&kho_in.radix_tree, &cb);
 	if (err) {
 		/*
 		 * Failed to initialize preserved memory. Clear FDT and radix
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
author maintainer
#11 lore raw

PATCH v2 7/18 kho: add callback for table pages

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

The KHO memory preservation radix tree does not mark the table pages themselves as preserved. This is done to avoid a circular dependency where preserving a page can lead of allocating other preserved pages. This means any walker looking for free ranges of memory outside of scratch areas will ignore the table

Add a table callback that is invoked for each table page. The callback is given the physical address of the table page.

This is useful for the upcoming mechanism that discovers blocks of memory with no preserved pages and lets them be used for boot memory.

Another use case is for users of the radix tree other than KHO itself. The radix tree does not preserve its own pages due to the circular dependency described above. But external users of the radix tree would need to preserve and restore their pages for the radix tree to survive past early boot. They can use this callback to do so.

---
 include/linux/kho_radix_tree.h     |  3 +++
 kernel/liveupdate/kexec_handover.c | 12 ++++++++++++
 2 files changed, 15 insertions(+)
include/linux/kho_radix_tree.h +3 -0
index 426a9cc9bcde..ac7ba7e567e1 100644
@@ -37,12 +37,15 @@ struct kho_radix_tree {
 /**
  * struct kho_radix_walk_cb - Callbacks for KHO radix tree walk.
  * @leaf:      Called on each present key in the radix tree.
+ * @node:      Called on each node of the radix tree itself. Receives the
+ *             physical address of the page containing the node.
  *
  * For each callback, a return value of 0 continues the walk and a non-zero
  * return value is directly returned to the caller.
  */
 struct kho_radix_walk_cb {
 	int (*leaf)(unsigned long key);
+	int (*node)(phys_addr_t phys);
 };
 
 #ifdef CONFIG_KEXEC_HANDOVER
kernel/liveupdate/kexec_handover.c +12 -0
index dbe075348ce4..94f18fe42c4b 100644
@@ -285,6 +285,12 @@ static int kho_radix_walk_leaf(struct kho_radix_leaf *leaf, unsigned long key,
 	unsigned int i;
 	int err;
 
+	if (cb->node) {
+		err = cb->node(virt_to_phys(leaf));
+		if (err)
+			return err;
+	}
+
 	if (!cb->leaf)
 		return 0;
 
@@ -307,6 +313,12 @@ static int __kho_radix_walk_tree(struct kho_radix_node *root,
 	unsigned int shift;
 	int err;
 
+	if (cb->node) {
+		err = cb->node(virt_to_phys(root));
+		if (err)
+			return err;
+	}
+
 	for (i = 0; i < PAGE_SIZE / sizeof(phys_addr_t); i++) {
 		if (!root->table[i])
 			continue;
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
author maintainer
#12 lore raw

PATCH v2 8/18 kho: add data argument to radix walk callback

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

Add an opaque data pointer argument to kho_radix_walk_cb_t. This can be used by callers to pass extra information to the callback.

---
 include/linux/kho_radix_tree.h     |  8 ++++----
 kernel/liveupdate/kexec_handover.c | 24 +++++++++++++-----------
 2 files changed, 17 insertions(+), 15 deletions(-)
include/linux/kho_radix_tree.h +4 -4
index ac7ba7e567e1..4138621e0e87 100644
@@ -44,8 +44,8 @@ struct kho_radix_tree {
  * return value is directly returned to the caller.
  */
 struct kho_radix_walk_cb {
-	int (*leaf)(unsigned long key);
-	int (*node)(phys_addr_t phys);
+	int (*leaf)(unsigned long key, void *data);
+	int (*node)(phys_addr_t phys, void *data);
 };
 
 #ifdef CONFIG_KEXEC_HANDOVER
@@ -53,7 +53,7 @@ struct kho_radix_walk_cb {
 int kho_radix_add_key(struct kho_radix_tree *tree, unsigned long key);
 void kho_radix_del_key(struct kho_radix_tree *tree, unsigned long key);
 int kho_radix_walk_tree(struct kho_radix_tree *tree,
-			const struct kho_radix_walk_cb *cb);
+			const struct kho_radix_walk_cb *cb, void *data);
 
 #else  /* #ifdef CONFIG_KEXEC_HANDOVER */
 
@@ -66,7 +66,7 @@ static inline void kho_radix_del_key(struct kho_radix_tree *tree,
 				     unsigned long key) { }
 
 static inline int kho_radix_walk_tree(struct kho_radix_tree *tree,
-				      const struct kho_radix_walk_cb *cb)
+				      const struct kho_radix_walk_cb *cb, void *data)
 {
 	return -EOPNOTSUPP;
 }
kernel/liveupdate/kexec_handover.c +13 -11
index 94f18fe42c4b..b890a69bddd5 100644
@@ -279,14 +279,14 @@ void kho_radix_del_key(struct kho_radix_tree *tree, unsigned long key)
 EXPORT_SYMBOL_GPL(kho_radix_del_key);
 
 static int kho_radix_walk_leaf(struct kho_radix_leaf *leaf, unsigned long key,
-			       const struct kho_radix_walk_cb *cb)
+			       const struct kho_radix_walk_cb *cb, void *data)
 {
 	unsigned long *bitmap = (unsigned long *)leaf;
 	unsigned int i;
 	int err;
 
 	if (cb->node) {
-		err = cb->node(virt_to_phys(leaf));
+		err = cb->node(virt_to_phys(leaf), data);
 		if (err)
 			return err;
 	}
@@ -295,7 +295,7 @@ static int kho_radix_walk_leaf(struct kho_radix_leaf *leaf, unsigned long key,
 		return 0;
 
 	for_each_set_bit(i, bitmap, PAGE_SIZE * BITS_PER_BYTE) {
-		err = cb->leaf(key | i);
+		err = cb->leaf(key | i, data);
 		if (err)
 			return err;
 	}
@@ -305,7 +305,7 @@ static int kho_radix_walk_leaf(struct kho_radix_leaf *leaf, unsigned long key,
 
 static int __kho_radix_walk_tree(struct kho_radix_node *root,
 				 unsigned int level, unsigned long start,
-				 const struct kho_radix_walk_cb *cb)
+				 const struct kho_radix_walk_cb *cb, void *data)
 {
 	struct kho_radix_node *node;
 	struct kho_radix_leaf *leaf;
@@ -314,7 +314,7 @@ static int __kho_radix_walk_tree(struct kho_radix_node *root,
 	int err;
 
 	if (cb->node) {
-		err = cb->node(virt_to_phys(root));
+		err = cb->node(virt_to_phys(root), data);
 		if (err)
 			return err;
 	}
@@ -335,10 +335,10 @@ static int __kho_radix_walk_tree(struct kho_radix_node *root,
 			 * node is pointing to the level 0 bitmap.
 			 */
 			leaf = (struct kho_radix_leaf *)node;
-			err = kho_radix_walk_leaf(leaf, key, cb);
+			err = kho_radix_walk_leaf(leaf, key, cb, data);
 		} else {
 			err  = __kho_radix_walk_tree(node, level - 1,
-						     key, cb);
+						     key, cb, data);
 		}
 
 		if (err)
@@ -352,6 +352,7 @@ static int __kho_radix_walk_tree(struct kho_radix_node *root,
  * kho_radix_walk_tree - Traverses the radix tree and calls a callback for each key.
  * @tree: A pointer to the KHO radix tree to walk.
  * @cb:   Set of callbacks to be invoked during the tree walk.
+ * @data: Opaque data pointer passed to each callback in @cb.
  *
  * This function walks the radix tree, searching from the top level down to the
  * lowest level (level 0), invoking the appropriate callbacks.
@@ -360,14 +361,15 @@ static int __kho_radix_walk_tree(struct kho_radix_node *root,
  *         value from the callback that stopped the walk.
  */
 int kho_radix_walk_tree(struct kho_radix_tree *tree,
-			const struct kho_radix_walk_cb *cb)
+			const struct kho_radix_walk_cb *cb, void *data)
 {
 	if (WARN_ON_ONCE(!tree->root))
 		return -EINVAL;
 
 	guard(mutex)(&tree->lock);
 
-	return __kho_radix_walk_tree(tree->root, KHO_TREE_MAX_DEPTH - 1, 0, cb);
+	return __kho_radix_walk_tree(tree->root, KHO_TREE_MAX_DEPTH - 1, 0, cb,
+				     data);
 }
 EXPORT_SYMBOL_GPL(kho_radix_walk_tree);
 
@@ -498,7 +500,7 @@ static struct page *__init kho_get_preserved_page(phys_addr_t phys,
 	return pfn_to_page(pfn);
 }
 
-static int __init kho_preserved_memory_reserve(unsigned long key)
+static int __init kho_preserved_memory_reserve(unsigned long key, void *data)
 {
 	union kho_page_info info;
 	struct page *page;
@@ -1442,7 +1444,7 @@ static void __init kho_mem_retrieve(void)
 	kho_in.radix_tree.root = kho_get_mem_map(fdt);
 	mutex_init(&kho_in.radix_tree.lock);
 
-	err = kho_radix_walk_tree(&kho_in.radix_tree, &cb);
+	err = kho_radix_walk_tree(&kho_in.radix_tree, &cb, NULL);
 	if (err) {
 		/*
 		 * Failed to initialize preserved memory. Clear FDT and radix
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
author maintainer
#13 lore raw

PATCH v2 9/18 kho: allow early-boot usage of the KHO radix tree

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

The KHO radix tree allocates memory for table pages from the buddy allocator using get_zeroed_page(). This is not available in early boot when memblock is still active.

Using the radix tree in early boot is useful for KHO to track metadata about its memory. One such example is for tracking free blocks for memory allocation when scratch runs out of space. This feature will be added in the following commits.

Add kho_radix_{alloc,free}_node() which allocate and free the table pages. They use slab_is_available() to decide which allocator to use. While slab_is_available() indicates availability of the slab allocator, it gets initialized right after buddy so it serves the same practical purpose.

---
 kernel/liveupdate/kexec_handover.c | 24 ++++++++++++++++++++++--
 1 file changed, 22 insertions(+), 2 deletions(-)
kernel/liveupdate/kexec_handover.c +22 -2
index b890a69bddd5..452b4dcdf2d2 100644
@@ -143,6 +143,26 @@ static unsigned long kho_radix_get_table_index(unsigned long key,
 	return (key >> s) % (1 << KHO_TABLE_SIZE_LOG2);
 }
 
+static void __ref *kho_radix_alloc_node(void)
+{
+	struct kho_radix_node *node;
+
+	if (slab_is_available())
+		node = (struct kho_radix_node *)get_zeroed_page(GFP_KERNEL);
+	else
+		node = memblock_alloc(PAGE_SIZE, PAGE_SIZE);
+
+	return node;
+}
+
+static void __ref kho_radix_free_node(struct kho_radix_node *node)
+{
+	if (slab_is_available())
+		free_page((unsigned long)node);
+	else
+		memblock_free(node, PAGE_SIZE);
+}
+
 /**
  * kho_radix_add_key - Add a key to the radix tree.
  * @tree: The KHO radix tree.
@@ -191,7 +211,7 @@ int kho_radix_add_key(struct kho_radix_tree *tree, unsigned long key)
 		}
 
 		/* Next node is empty, create a new node for it */
-		new_node = (struct kho_radix_node *)get_zeroed_page(GFP_KERNEL);
+		new_node = kho_radix_alloc_node();
 		if (!new_node) {
 			err = -ENOMEM;
 			goto err_free_nodes;
@@ -222,7 +242,7 @@ int kho_radix_add_key(struct kho_radix_tree *tree, unsigned long key)
 err_free_nodes:
 	for (i = KHO_TREE_MAX_DEPTH - 1; i > 0; i--) {
 		if (intermediate_nodes[i])
-			free_page((unsigned long)intermediate_nodes[i]);
+			kho_radix_free_node(intermediate_nodes[i]);
 	}
 	if (anchor_node)
 		anchor_node->table[anchor_idx] = 0;
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
author maintainer
#14 lore raw

PATCH v2 10/18 kho: allow destroying KHO radix tree

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

Add kho_radix_destroy_tree() which allows destroying the radix tree and freeing all its pages.

This is will be used by the upcoming scratch extension mechanism. It creates a radix tree to track free blocks and then frees them after telling memblock about them.

---
 include/linux/kho_radix_tree.h     |  3 +++
 kernel/liveupdate/kexec_handover.c | 35 ++++++++++++++++++++++++++++++
 2 files changed, 38 insertions(+)
include/linux/kho_radix_tree.h +3 -0
index 4138621e0e87..66ca936b3f06 100644
@@ -54,6 +54,7 @@ int kho_radix_add_key(struct kho_radix_tree *tree, unsigned long key);
 void kho_radix_del_key(struct kho_radix_tree *tree, unsigned long key);
 int kho_radix_walk_tree(struct kho_radix_tree *tree,
 			const struct kho_radix_walk_cb *cb, void *data);
+void kho_radix_destroy_tree(struct kho_radix_tree *tree);
 
 #else  /* #ifdef CONFIG_KEXEC_HANDOVER */
 
@@ -71,6 +72,8 @@ static inline int kho_radix_walk_tree(struct kho_radix_tree *tree,
 	return -EOPNOTSUPP;
 }
 
+static inline void kho_radix_destroy_tree(struct kho_radix_tree *tree) { }
+
 #endif /* #ifdef CONFIG_KEXEC_HANDOVER */
 
 #endif	/* _LINUX_KHO_RADIX_TREE_H */
kernel/liveupdate/kexec_handover.c +35 -0
index 452b4dcdf2d2..df3f5eb01bf1 100644
@@ -298,6 +298,41 @@ void kho_radix_del_key(struct kho_radix_tree *tree, unsigned long key)
 }
 EXPORT_SYMBOL_GPL(kho_radix_del_key);
 
+static void __kho_radix_destroy_tree(struct kho_radix_node *root,
+				     unsigned int level)
+{
+	unsigned long i;
+
+	if (level == 0) {
+		kho_radix_free_node(root);
+		return;
+	}
+
+	for (i = 0; i < PAGE_SIZE / sizeof(phys_addr_t); i++) {
+		if (root->table[i])
+			__kho_radix_destroy_tree(phys_to_virt(root->table[i]),
+						 level - 1);
+	}
+
+	kho_radix_free_node(root);
+}
+
+/**
+ * kho_radix_destroy_tree - Destroy the radix tree
+ * @tree: The radix tree to destroy
+ *
+ * Walk @tree and free all its nodes.
+ */
+void kho_radix_destroy_tree(struct kho_radix_tree *tree)
+{
+	if (!tree->root)
+		return;
+
+	__kho_radix_destroy_tree(tree->root, KHO_TREE_MAX_DEPTH - 1);
+	tree->root = NULL;
+}
+EXPORT_SYMBOL_GPL(kho_radix_destroy_tree);
+
 static int kho_radix_walk_leaf(struct kho_radix_leaf *leaf, unsigned long key,
 			       const struct kho_radix_walk_cb *cb, void *data)
 {
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
author maintainer
#15 lore raw

PATCH v2 11/18 kho: add kho_radix_init_tree()

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

Move the initialization logic of the radix tree into kho_radix_init_tree() instead of having users open-code it. Makes the boundaries cleaner and reduces code duplication when a new user of the radix tree will be added in a future commit.

---
 include/linux/kho_radix_tree.h     |  7 ++++
 kernel/liveupdate/kexec_handover.c | 66 ++++++++++++++++++++++--------
 2 files changed, 55 insertions(+), 18 deletions(-)
include/linux/kho_radix_tree.h +7 -0
index 66ca936b3f06..5d6ae2893684 100644
@@ -54,6 +54,7 @@ int kho_radix_add_key(struct kho_radix_tree *tree, unsigned long key);
 void kho_radix_del_key(struct kho_radix_tree *tree, unsigned long key);
 int kho_radix_walk_tree(struct kho_radix_tree *tree,
 			const struct kho_radix_walk_cb *cb, void *data);
+int kho_radix_init_tree(struct kho_radix_tree *tree, struct kho_radix_node *root);
 void kho_radix_destroy_tree(struct kho_radix_tree *tree);
 
 #else  /* #ifdef CONFIG_KEXEC_HANDOVER */
@@ -72,6 +73,12 @@ static inline int kho_radix_walk_tree(struct kho_radix_tree *tree,
 	return -EOPNOTSUPP;
 }
 
+static inline int kho_radix_init_tree(struct kho_radix_tree *tree,
+				      struct kho_radix_node *root)
+{
+	return 0;
+}
+
 static inline void kho_radix_destroy_tree(struct kho_radix_tree *tree) { }
 
 #endif /* #ifdef CONFIG_KEXEC_HANDOVER */
kernel/liveupdate/kexec_handover.c +48 -18

97 lines not on this page · raw message

Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
author maintainer
#16 lore raw

PATCH v2 12/18 kho: export kho_scratch_overlap()

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

Support for discovering memory blocks with no preserved memory will be added in coming patches. These areas will also be marked as scratch to allow allocations from them. Memblock will switch to looking through the scratch array to decide the right migratetype.

Export kho_scratch_overlap(). Since it is now used by non-debug code, move it out of kexec_handover_debug.c and into kexec_handover.c. Gate the overlap checks in kho_preserve_folio() and kho_preserve_pages() by IS_ENABLED(CONFIG_KEXEC_HANDOVER_DEBUG) instead.

Since kexec_handover_debug.c is now empty, delete it.

No functional changes.

---
 include/linux/kexec_handover.h              |  7 ++++++
 kernel/liveupdate/Makefile                  |  1 -
 kernel/liveupdate/kexec_handover.c          | 22 ++++++++++++++++--
 kernel/liveupdate/kexec_handover_debug.c    | 25 ---------------------
 kernel/liveupdate/kexec_handover_internal.h |  9 --------
 5 files changed, 27 insertions(+), 37 deletions(-)
 delete mode 100644 kernel/liveupdate/kexec_handover_debug.c
include/linux/kexec_handover.h +7 -0
index 8968c56d2d73..3740c14d970d 100644
@@ -40,6 +40,8 @@ void kho_memory_init(void);
 
 void kho_populate(phys_addr_t fdt_phys, u64 fdt_len, phys_addr_t scratch_phys,
 		  u64 scratch_len);
+
+bool kho_scratch_overlap(phys_addr_t phys, size_t size);
 #else
 static inline bool kho_is_enabled(void)
 {
@@ -116,6 +118,11 @@ static inline void kho_populate(phys_addr_t fdt_phys, u64 fdt_len,
 				phys_addr_t scratch_phys, u64 scratch_len)
 {
 }
+
+static inline bool kho_scratch_overlap(phys_addr_t phys, size_t size)
+{
+	return false;
+}
 #endif /* CONFIG_KEXEC_HANDOVER */
 
 #endif /* LINUX_KEXEC_HANDOVER_H */
kernel/liveupdate/Makefile +0 -1
index d2f779cbe279..dc352839ccf0 100644
@@ -7,7 +7,6 @@ luo-y :=								\
 		luo_session.o
 
 obj-$(CONFIG_KEXEC_HANDOVER)		+= kexec_handover.o
-obj-$(CONFIG_KEXEC_HANDOVER_DEBUG)	+= kexec_handover_debug.o
 obj-$(CONFIG_KEXEC_HANDOVER_DEBUGFS)	+= kexec_handover_debugfs.o
 
 obj-$(CONFIG_LIVEUPDATE)		+= luo.o
kernel/liveupdate/kexec_handover.c +20 -2
index 8ab2c7e234e1..a66f23a35389 100644
@@ -766,6 +766,22 @@ static phys_addr_t __init scratch_size_node(int nid)
 	return round_up(size, CMA_MIN_ALIGNMENT_BYTES);
 }
 
+bool kho_scratch_overlap(phys_addr_t phys, size_t size)
+{
+	phys_addr_t scratch_start, scratch_end;
+	unsigned int i;
+
+	for (i = 0; i < kho_scratch_cnt; i++) {
+		scratch_start = kho_scratch[i].addr;
+		scratch_end = kho_scratch[i].addr + kho_scratch[i].size;
+
+		if (phys < scratch_end && (phys + size) > scratch_start)
+			return true;
+	}
+
+	return false;
+}
+
 /**
  * kho_reserve_scratch - Reserve a contiguous chunk of memory for kexec
  *
@@ -963,7 +979,8 @@ int kho_preserve_folio(struct folio *folio)
 	const unsigned long pfn = folio_pfn(folio);
 	const unsigned int order = folio_order(folio);
 
-	if (WARN_ON(kho_scratch_overlap(pfn << PAGE_SHIFT, PAGE_SIZE << order)))
+	if (IS_ENABLED(CONFIG_KEXEC_HANDOVER_DEBUG) &&
+	    WARN_ON(kho_scratch_overlap(pfn << PAGE_SHIFT, PAGE_SIZE << order)))
 		return -EINVAL;
 
 	return kho_radix_add_key(tree, kho_encode_radix_key(PFN_PHYS(pfn),
@@ -1040,7 +1057,8 @@ int kho_preserve_pages(struct page *page, unsigned long nr_pages)
 	unsigned long failed_pfn = 0;
 	int err = 0;
 
-	if (WARN_ON(kho_scratch_overlap(start_pfn << PAGE_SHIFT,
+	if (IS_ENABLED(CONFIG_KEXEC_HANDOVER_DEBUG) &&
+	    WARN_ON(kho_scratch_overlap(start_pfn << PAGE_SHIFT,
 					nr_pages << PAGE_SHIFT))) {
 		return -EINVAL;
 	}
kernel/liveupdate/kexec_handover_debug.c deleted +0 -25
deleted file mode 100644
index 6efb696f5426..000000000000
@@ -1,25 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0-only
-/*
- * kexec_handover_debug.c - kexec handover optional debug functionality
- * Copyright (C) 2025 Google LLC, Pasha Tatashin <[email protected]>
- */
-
-#define pr_fmt(fmt) "KHO: " fmt
-
-#include "kexec_handover_internal.h"
-
-bool kho_scratch_overlap(phys_addr_t phys, size_t size)
-{
-	phys_addr_t scratch_start, scratch_end;
-	unsigned int i;
-
-	for (i = 0; i < kho_scratch_cnt; i++) {
-		scratch_start = kho_scratch[i].addr;
-		scratch_end = kho_scratch[i].addr + kho_scratch[i].size;
-
-		if (phys < scratch_end && (phys + size) > scratch_start)
-			return true;
-	}
-
-	return false;
-}
kernel/liveupdate/kexec_handover_internal.h +0 -9
index 0399ff107775..805d2a76c388 100644
@@ -41,13 +41,4 @@ static inline void kho_debugfs_blob_remove(struct kho_debugfs *dbg,
 					   void *blob) { }
 #endif /* CONFIG_KEXEC_HANDOVER_DEBUGFS */
 
-#ifdef CONFIG_KEXEC_HANDOVER_DEBUG
-bool kho_scratch_overlap(phys_addr_t phys, size_t size);
-#else
-static inline bool kho_scratch_overlap(phys_addr_t phys, size_t size)
-{
-	return false;
-}
-#endif /* CONFIG_KEXEC_HANDOVER_DEBUG */
-
 #endif /* LINUX_KEXEC_HANDOVER_INTERNAL_H */
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
maintainer
#17 lore raw

Re: [PATCH v2 12/18] kho: export kho_scratch_overlap()

On Fri, 05 Jun 2026 20:34:45 +0200, Pratyush Yadav <[email protected]> wrote:

Subject: kho: export kho_scratch_overlap()

rather make it available for !kho users and regardless of KHO_DEBUG.

Nit: we are not really exporting this in the sense of EXPORT_SYMBOL, we

Nit: we are not really exporting this in the sense of EXPORT_SYMBOL, we

Signature · 2 lines
Sincerely yours,
Mike.
author maintainer
#18 lore raw

Re: [PATCH v2 12/18] kho: export kho_scratch_overlap()

Quoted 7 lines · Mike Rapoport

On Fri, 05 Jun 2026 20:34:45 +0200, Pratyush Yadav <[email protected]> wrote:

Subject: kho: export kho_scratch_overlap()

rather make it available for !kho users and regardless of KHO_DEBUG.

Nit: we are not really exporting this in the sense of EXPORT_SYMBOL, we

ACK, will update in next revision.

Signature · 2 lines
Regards,
Pratyush Yadav
author maintainer
#19 lore raw

PATCH v2 13/18 kho: initialize kho_scratch pointer earlier in boot

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

In a future patch, mm init will use kho_scratch_overlap() for deciding the migrate type of pageblocks it initializes. The earliest user currently is free_area_init(). kho_scratch_overlap()
relies on kho_scratch pointer being initialized. Introduce kho_memory_init_early() to do this.

kho_populate() would normally be a good place to do this, but unfortunately, phys_to_virt() does not work at that point on ARM64. So we need yet another initialization function.

---
 include/linux/kexec_handover.h     |  3 +++
 kernel/liveupdate/kexec_handover.c | 12 ++++++++++--
 mm/mm_init.c                       |  1 +
 3 files changed, 14 insertions(+), 2 deletions(-)
include/linux/kexec_handover.h +3 -0
index 3740c14d970d..9e961032e06b 100644
@@ -37,6 +37,7 @@ void kho_remove_subtree(void *blob);
 int kho_retrieve_subtree(const char *name, phys_addr_t *phys, size_t *size);
 
 void kho_memory_init(void);
+void kho_memory_init_early(void);
 
 void kho_populate(phys_addr_t fdt_phys, u64 fdt_len, phys_addr_t scratch_phys,
 		  u64 scratch_len);
@@ -114,6 +115,8 @@ static inline int kho_retrieve_subtree(const char *name, phys_addr_t *phys,
 
 static inline void kho_memory_init(void) { }
 
+static inline void kho_memory_init_early(void) { }
+
 static inline void kho_populate(phys_addr_t fdt_phys, u64 fdt_len,
 				phys_addr_t scratch_phys, u64 scratch_len)
 {
kernel/liveupdate/kexec_handover.c +10 -2
index a66f23a35389..af22086ca2d6 100644
@@ -1535,8 +1535,6 @@ static void __init kho_mem_retrieve(void)
 	const void *fdt = kho_get_fdt();
 	int err;
 
-	kho_scratch = phys_to_virt(kho_in.scratch_phys);
-
 	/*
 	 * kho_get_mem_map() should always succeed. If it fails, kho_populate()
 	 * catches that and never sets kho_in.scratch_phys, which stops memory
@@ -1757,6 +1755,16 @@ static __init int kho_init(void)
 }
 fs_initcall(kho_init);
 
+void __init kho_memory_init_early(void)
+{
+	/*
+	 * kho_scratch_overlap() needs kho_scratch to be initialized. It is used
+	 * by free_area_init() on KHO boots, so initialize it early.
+	 */
+	if (kho_in.scratch_phys)
+		kho_scratch = phys_to_virt(kho_in.scratch_phys);
+}
+
 void __init kho_memory_init(void)
 {
 	if (kho_in.scratch_phys)
mm/mm_init.c +1 -0
index eddc0f03a779..0675837bbfc9 100644
@@ -2688,6 +2688,7 @@ void __init __weak mem_init(void)
 
 void __init mm_core_init_early(void)
 {
+	kho_memory_init_early();
 	hugetlb_cma_reserve();
 	hugetlb_bootmem_alloc();
 
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
author maintainer
#20 lore raw

PATCH v2 14/18 memblock: use kho_scratch_overlap() to decide migratetype

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

Support for discovering memory blocks with no preserved memory will be added in coming patches. These areas will also be marked as MEMBLOCK_KHO_SCRATCH to allow allocations from them.

But only the scratch areas passed to KHO should be marked as MIGRATE_CMA, all others should be left as normal. So instead of checking the flags on the region, ask KHO to loop through its scratch array.

---
 include/linux/memblock.h | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/memblock.h +2 -1
index 5afcd99aa8c1..546d7ef798b8 100644
@@ -11,6 +11,7 @@
 #include <linux/init.h>
 #include <linux/mm.h>
 #include <asm/dma.h>
+#include <linux/kexec_handover.h>
 
 extern unsigned long max_low_pfn;
 extern unsigned long min_low_pfn;
@@ -618,7 +619,7 @@ bool memblock_is_kho_scratch_memory(phys_addr_t addr);
 static inline enum migratetype kho_scratch_migratetype(unsigned long pfn,
 						       enum migratetype mt)
 {
-	if (memblock_is_kho_scratch_memory(PFN_PHYS(pfn)))
+	if (kho_scratch_overlap(PFN_PHYS(pfn), pageblock_nr_pages << PAGE_SHIFT))
 		return MIGRATE_CMA;
 	return mt;
 }
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
maintainer
#21 lore raw

Re: [PATCH v2 14/18] memblock: use kho_scratch_overlap() to decide migratetype

include/linux/memblock.h bool memblock_is_kho_scratch_memory(phys_addr_t addr); · line 622

Quoted 10 lines · Pratyush Yadav
include/linux/memblock.h +1 -1
index 5afcd99aa8c1..546d7ef798b8 100644
@@ -618,7 +619,7 @@ bool memblock_is_kho_scratch_memory(phys_addr_t addr);
 static inline enum migratetype kho_scratch_migratetype(unsigned long pfn,
 						       enum migratetype mt)
 {
-	if (memblock_is_kho_scratch_memory(PFN_PHYS(pfn)))
+	if (kho_scratch_overlap(PFN_PHYS(pfn), pageblock_nr_pages << PAGE_SHIFT))

I'd move it to kexec_handover.h and kill memblock_is_kho_scratch_memory() in the same patch

BTW, please double check that the extended scratch does not require updates to efi_init()::reserve_regions().

Signature · 2 lines
Sincerely yours,
Mike.
author maintainer
#22 lore raw

Re: [PATCH v2 14/18] memblock: use kho_scratch_overlap() to decide migratetype

Quoted 15 lines · Mike Rapoport

include/linux/memblock.h bool memblock_is_kho_scratch_memory(phys_addr_t addr); · line 622

Quoted 10 lines · Pratyush Yadav
include/linux/memblock.h +1 -1
index 5afcd99aa8c1..546d7ef798b8 100644
@@ -618,7 +619,7 @@ bool memblock_is_kho_scratch_memory(phys_addr_t addr);
 static inline enum migratetype kho_scratch_migratetype(unsigned long pfn,
 						       enum migratetype mt)
 {
-	if (memblock_is_kho_scratch_memory(PFN_PHYS(pfn)))
+	if (kho_scratch_overlap(PFN_PHYS(pfn), pageblock_nr_pages << PAGE_SHIFT))

I'd move it to kexec_handover.h and kill memblock_is_kho_scratch_memory() in the same patch

Quoted 2 lines

BTW, please double check that the extended scratch does not require updates to efi_init()::reserve_regions().

It does not. efi_init() happens in setup_arch() on both x86 and arm64. The extended scratch is discovered after setup_arch(), in mm_core_init_early().

But I do think this is worth a comment since the interaction is not obvious at all.

Signature · 2 lines
Regards,
Pratyush Yadav
author maintainer
#23 lore raw

PATCH v2 15/18 kho: extend scratch

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

Motivation
==========

The scratch space is allocated by the first kernel in the KHO chain, and is reused by all subsequent kernels. The size of the space is either set via the commandline by the system administrator or by calculating the amount of memory used by the kernel and adding a multiplier. In either case, the scratch space is a heuristic and is liable to fill up and fail allocation if a kernel uses more memory than expected.

In addition, gigantic huge pages (usually 1 GiB) are allocated via memblock, and in a KHO boot that memory comes from the scratch space. In hypervisors it is common to dedicate a major part of the system's memory to gigantic hugepages for VM memory.

If this memory needs to come from scratch space, then scratch needs to be greater than the memory needed for huge pages, which is impractical. In addition, hugepages can be preserved memory. Allocating them from scratch violates the assumption that scratch contains no preserved memory.

Methodology
===========

Discover areas that don't contain any preserved memory at boot by walking the preserved memory radix tree. Mark them as scratch to allow allocations from them. This makes KHO more resilient to memory pressure and allows supporting huge page preservation.

Since the preserved memory radix tree mixes both physical address and order into a single key, and does not track table pages, it is difficult to identify free areas from it directly. Walk the tree and digest it down into another radix tree. The latter tracks blocks of KHO_EXT_SHIFT (1 GiB as of now) granularity. Then walk the digested tree and mark the areas between the present keys as scratch.

Performance
===========

The discovery algorithm traverses the preserved memory radix tree exactly once. While it does use memory for the digested radix tree, since the blocks are split by 1 GiB, a single bitmap with 4k pages can track up to 32 TiB of memory. So there are likely to be very few radix tree pages used in this tracking. For systems with all physical memory below 32 TiB, this should result in a total of 6 pages being used (KHO_TREE_MAX_DEPTH == 6).

An alternate way of achieving this would be to call kho_mem_retrieve() earlier in boot and mark all the KHO preservations as reserved. But that can blow up memblock.reserved with a bunch of 4K pages scattered everywhere, which will reduce performance of subsequent allocations. Since the free blocks are tracked in chunks of 1 GiB, this won't blow up memblock.memory as much.

There is no inherent reason for using 1 GiB as the discovered block size. This can be changed later if needed. Currently, KHO is mainly targeted for server grade systems with hundreds of gigabytes to terabytes of memory. So 1 GiB is a reasonable granularity for those systems. For smaller systems this doesn't work as well, but we can arrive at a better heuristic when we have concrete use cases.

Practical evaluation
====================

The testing is done on a x86_64 qemu VM running under KVM with 64G memory and 12 CPUs. The machine pre-allocates 50 1G pages.

Since the performance scales with how busy the radix tree is, tests are done with 2 preservation patterns: first with two 1M memfds, second with two 1G memfds, both using 4k pages.

Test case 1 - 1M memfd
~~~~~~~~~~~~~~~~~~~~~~

This test case has two memfds with 1M memory each in 4k pages, plus other preservations from LUO core and other KHO users.

This is how the radix tree stats look like:

    radix_nodes:       0x13
    nr_preservations:  0x214
    mem_preserved:     0x227000
    per order preservations:
      order  0:  0x20f
      order  1:  0x4
      order  4:  0x1

and this is how long it takes to extend the scratch after KHO boot:

KHO: KHO extend time: 47 us
KHO: KHO extend total mem: 0xe6c17b000 (~57G)

Test case 2 - 1G memfd
~~~~~~~~~~~~~~~~~~~~~~

This test case has two memfds with 1G memory each in 4k pages, plus other preservations from LUO core and other KHO users.

This is how the radix tree stats look like:

    radix_nodes:       0x28
    nr_preservations:  0x80816
    mem_preserved:     0x80829000
    per order preservations:
      order  0:  0x80811
      order  1:  0x4
      order  4:  0x1

and this is how long it takes to extend the scratch after KHO boot:

KHO: KHO extend time: 22514 us
KHO: KHO extend total mem: 0xd3f200000 (~52G)

---

Notes:
As one might notice, the "scratch" terminology starts to break down here. There is the original "scratch", which is passed down by the previous kernel. It is marked MEMBLOCK_KHO_SCRATCH. There is also the discovered "scratch", which also gets marked MEMBLOCK_KHO_SCRATCH, but has nothing to do with the former.

For limiting the scope of this series, I haven't done the rename here. I can do it as a follow up series once this stabilizes and lands into -next.

I suggest the following scheme:

- Rename "KHO scratch" to "KHO bootmem". Update the documentation and all code to use this name. We have the kho_scratch kernel cmdline parameter, which is harder to change, but perhaps we can rename it to "kho_bootmem" and if someone complains we can add it back.

- Rename MEMBLOCK_KHO_SCRATCH to MEMBLOCK_KHO_NOPRSRV. This describes the property of the memory not its origin. Then KHO can mark its "bootmem" as KHO_NOPRSRV because bootmem never has any preserved memory. Later, kho_extend_scratch() (which is also due for a better name) can also mark its discovered areas as KHO_NOPRSRV.

 kernel/liveupdate/kexec_handover.c | 149 +++++++++++++++++++++++++----
 1 file changed, 132 insertions(+), 17 deletions(-)
kernel/liveupdate/kexec_handover.c +132 -17
index af22086ca2d6..8540608b8602 100644
@@ -84,6 +84,23 @@ static struct kho_out kho_out = {
 	},
 };
 
+struct kho_in {
+	phys_addr_t fdt_phys;
+	phys_addr_t scratch_phys;
+	char previous_release[__NEW_UTS_LEN + 1];
+	u32 kexec_count;
+	struct kho_debugfs dbg;
+	struct kho_radix_tree radix_tree;
+};
+
+static struct kho_in kho_in = {
+};
+
+static const void *kho_get_fdt(void)
+{
+	return kho_in.fdt_phys ? phys_to_virt(kho_in.fdt_phys) : NULL;
+}
+
 /**
  * kho_encode_radix_key - Encodes a physical address and order into a radix key.
  * @phys: The physical address of the page.
@@ -869,6 +886,119 @@ static void __init kho_reserve_scratch(void)
 	kho_enable = false;
 }
 
+#define KHO_EXT_SHIFT 30 /* 1 GiB */
+
+static int __init kho_ext_walk_key(unsigned long key, void *data)
+{
+	struct kho_radix_tree *tree = data;
+	phys_addr_t start, end;
+	unsigned int order;
+	int err;
+
+	start = kho_decode_radix_key(key, &order);
+	end = start + (1UL << (order + PAGE_SHIFT));
+
+	while (start < end) {
+		err = kho_radix_add_key(tree, start >> KHO_EXT_SHIFT);
+		if (err)
+			return err;
+
+		start += (1UL << KHO_EXT_SHIFT);
+	}
+
+	return 0;
+}
+
+static int __init kho_ext_walk_node(phys_addr_t phys, void *data)
+{
+	struct kho_radix_tree *tree = data;
+
+	return kho_radix_add_key(tree, phys >> KHO_EXT_SHIFT);
+}
+
+static int __init kho_ext_mark_scratch(unsigned long key, void *data)
+{
+	phys_addr_t *prev_end = data;
+	phys_addr_t start = key << KHO_EXT_SHIFT;
+	int err;
+
+	if (start > *prev_end) {
+		err = memblock_mark_kho_scratch(*prev_end, start - *prev_end);
+		if (err)
+			return err;
+	}
+
+	*prev_end = start + (1UL << KHO_EXT_SHIFT);
+	return 0;
+}
+
+/**
+ * kho_extend_scratch - Extend the scratch regions
+ *
+ * The KHO radix tree mixes both physical address and order into a single key.
+ * This makes it hard to look for free ranges directly. This function first
+ * walks the radix tree and digests it down into another radix tree, whose keys
+ * identify blocks of KHO_EXT_SHIFT which contain preserved memory.
+ *
+ * Then it walks the digested radix tree and marks everything that doesn't have
+ * preserved memory as scratch.
+ *
+ * NOTE: This function allocates memory so it should be called when scratch has
+ * available space.
+ *
+ * NOTE: The pages of the KHO radix tree tables are not marked as preserved in
+ * the KHO tree. But they are expected to remain untouched until the tree is
+ * fully parsed. So this function also considers them to be "preserved memory"
+ * and marks their blocks as busy.
+ */
+static void __init kho_extend_scratch(void)
+{
+	const struct kho_radix_walk_cb kho_cb = {
+		.leaf = kho_ext_walk_key,
+		.node = kho_ext_walk_node,
+	};
+	const struct kho_radix_walk_cb ext_cb = {
+		.leaf = kho_ext_mark_scratch,
+	};
+	struct kho_radix_tree radix;
+	phys_addr_t prev_end = 0;
+	int err = 0;
+
+	if (!is_kho_boot())
+		return;
+
+	/* Make sure the KHO radix tree is initialized. */
+	err = kho_radix_init_tree(&kho_in.radix_tree,
+				  kho_get_mem_map(kho_get_fdt()));
+	if (err)
+		goto print;
+
+	err = kho_radix_init_tree(&radix, NULL);
+	if (err)
+		goto print;
+
+	/* Walk the KHO radix tree to find busy blocks. */
+	err = kho_radix_walk_tree(&kho_in.radix_tree, &kho_cb, &radix);
+	if (err)
+		goto out;
+
+	/* Walk the blocks and mark everything between keys as scratch. */
+	err = kho_radix_walk_tree(&radix, &ext_cb, &prev_end);
+	if (err)
+		goto out;
+
+	/* Mark everything from last busy block to end of DRAM. */
+	if (prev_end < memblock_end_of_DRAM())
+		err = memblock_mark_kho_scratch(prev_end, memblock_end_of_DRAM() - prev_end);
+
+	/* fallthrough */
+out:
+	kho_radix_destroy_tree(&radix);
+print:
+	if (err)
+		pr_err("Failed to extend scratch: %pe\n", ERR_PTR(err));
+}
+
 /**
  * kho_add_subtree - record the physical address of a sub blob in KHO root tree.
  * @name: name of the sub tree.
@@ -1443,23 +1573,6 @@ void kho_restore_free(void *mem)
 }
 EXPORT_SYMBOL_GPL(kho_restore_free);
 
-struct kho_in {
-	phys_addr_t fdt_phys;
-	phys_addr_t scratch_phys;
-	char previous_release[__NEW_UTS_LEN + 1];
-	u32 kexec_count;
-	struct kho_debugfs dbg;
-	struct kho_radix_tree radix_tree;
-};
-
-static struct kho_in kho_in = {
-};
-
-static const void *kho_get_fdt(void)
-{
-	return kho_in.fdt_phys ? phys_to_virt(kho_in.fdt_phys) : NULL;
-}
-
 /**
  * is_kho_boot - check if current kernel was booted via KHO-enabled
  * kexec
@@ -1763,6 +1876,8 @@ void __init kho_memory_init_early(void)
 	 */
 	if (kho_in.scratch_phys)
 		kho_scratch = phys_to_virt(kho_in.scratch_phys);
+
+	kho_extend_scratch();
 }
 
 void __init kho_memory_init(void)
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
maintainer
#24 lore raw

Re: [PATCH v2 15/18] kho: extend scratch

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 889

Quoted 9 lines · Pratyush Yadav
kernel/liveupdate/kexec_handover.c +1 -0
index af22086ca2d6..8540608b8602 100644
@@ -869,6 +886,119 @@ static void __init kho_reserve_scratch(void)
 	kho_enable = false;
 }
 
+#define KHO_EXT_SHIFT 30 /* 1 GiB */

Please add a comment why exactly 1 Gib.
I'd also define a size macro as SZ_1G and make shift const_ilog2(SIZE)

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 891

Quoted 2 lines
kernel/liveupdate/kexec_handover.c +2 -0
+
+static int __init kho_ext_walk_key(unsigned long key, void *data)

Maybe _leaf? No strong feelings though

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 893

Quoted 2 lines
kernel/liveupdate/kexec_handover.c +2 -0
+{
+	struct kho_radix_tree *tree = data;

Would be nice to say which tree in the variable name ;)

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 914

Quoted 7 lines

[ ... skip 15 lines ... ]

kernel/liveupdate/kexec_handover.c +6 -0
+	return 0;
+}
+
+static int __init kho_ext_walk_node(phys_addr_t phys, void *data)
+{
+	struct kho_radix_tree *tree = data;

Ditto

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 935

Quoted 7 lines

[ ... skip 15 lines ... ]

kernel/liveupdate/kexec_handover.c +6 -0
+
+	*prev_end = start + (1UL << KHO_EXT_SHIFT);
+	return 0;
+}
+
+/**

I don't think we expose statics as kernel-doc somewhere, so this probably shouldn't be a kernel-doc comment

Quoted 3 lines

+ * kho_extend_scratch - Extend the scratch regions
+ *
+ * The KHO radix tree mixes both physical address and order into a single key.

Here it's rather the preserved memory map radix tree or something like that.

Quoted 2 lines

+ * This makes it hard to look for free ranges directly. This function first
+ * walks the radix tree and digests it down into another radix tree, whose keys

Here as well, maybe don't even mention radix to make it shorter, the important part is that we wakk the preserved memory map and create a radix tree that identifies blocks around the preserved memory.

Quoted 9 lines

+ * identify blocks of KHO_EXT_SHIFT which contain preserved memory.
+ *
+ * Then it walks the digested radix tree and marks everything that doesn't have
+ * preserved memory as scratch.
+ *
+ * NOTE: This function allocates memory so it should be called when scratch has
+ * available space.
+ *
+ * NOTE: The pages of the KHO radix tree tables are not marked as preserved in

^ preserved memory map radix tree :)

Quoted 4 lines

+ * the KHO tree. But they are expected to remain untouched until the tree is
+ * fully parsed. So this function also considers them to be "preserved memory"
+ * and marks their blocks as busy.
+ */

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 963

Quoted 10 lines
kernel/liveupdate/kexec_handover.c +10 -0
+static void __init kho_extend_scratch(void)
+{
+	const struct kho_radix_walk_cb kho_cb = {
+		.leaf = kho_ext_walk_key,
+		.node = kho_ext_walk_node,
+	};
+	const struct kho_radix_walk_cb ext_cb = {
+		.leaf = kho_ext_mark_scratch,
+	};
+	struct kho_radix_tree radix;

sashiko says:

Is it possible for the radix variable to contain uninitialized stack memory here?
If radix is uninitialized, tree->root might contain garbage data when passed to kho_radix_init_tree()

and I agree :)

This should be

	struct kho_radix_tree radix = { 0 };
Signature · 2 lines
Sincerely yours,
Mike.
author maintainer
#25 lore raw

Re: [PATCH v2 15/18] kho: extend scratch

Quoted 9 lines · Mike Rapoport
Quoted 8 lines · Pratyush Yadav
kernel/liveupdate/kexec_handover.c +0 -0
index af22086ca2d6..8540608b8602 100644
@@ -869,6 +886,119 @@ static void __init kho_reserve_scratch(void)
 	kho_enable = false;
 }
 
Quoted 4 lines

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 889

Quoted 1 line
kernel/liveupdate/kexec_handover.c +1 -0
+#define KHO_EXT_SHIFT 30 /* 1 GiB */

Please add a comment why exactly 1 Gib.
I'd also define a size macro as SZ_1G and make shift const_ilog2(SIZE)

ACK.

Quoted 5 lines

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 891

Quoted 3 lines
kernel/liveupdate/kexec_handover.c +2 -0
+
+static int __init kho_ext_walk_key(unsigned long key, void *data)

Maybe _leaf? No strong feelings though

Sure.

Quoted 5 lines

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 893

Quoted 3 lines
kernel/liveupdate/kexec_handover.c +2 -0
+{
+	struct kho_radix_tree *tree = data;

Would be nice to say which tree in the variable name ;)

How about preserved_mem_map?

Quoted 11 lines

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 914

Quoted 8 lines

[ ... skip 15 lines ... ]

kernel/liveupdate/kexec_handover.c +6 -0
+	return 0;
+}
+
+static int __init kho_ext_walk_node(phys_addr_t phys, void *data)
+{
+	struct kho_radix_tree *tree = data;

Ditto

Quoted 10 lines

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 935

Quoted 7 lines

[ ... skip 15 lines ... ]

kernel/liveupdate/kexec_handover.c +6 -0
+
+	*prev_end = start + (1UL << KHO_EXT_SHIFT);
+	return 0;
+}
+
+/**

I don't think we expose statics as kernel-doc somewhere, so this probably shouldn't be a kernel-doc comment

This is a leftover from the previous version, where this was external.

I think the documentation is still worthwhile though, so I suppose I'll turn it into a normal comment by removing the /**.

Quoted 7 lines
Quoted 4 lines

+ * kho_extend_scratch - Extend the scratch regions
+ *
+ * The KHO radix tree mixes both physical address and order into a single key.

Here it's rather the preserved memory map radix tree or something like that.

Sure, will update.

Quoted 7 lines
Quoted 3 lines

+ * This makes it hard to look for free ranges directly. This function first
+ * walks the radix tree and digests it down into another radix tree, whose keys

Here as well, maybe don't even mention radix to make it shorter, the important part is that we wakk the preserved memory map and create a radix tree that identifies blocks around the preserved memory.

ACK.

Quoted 11 lines
Quoted 10 lines

+ * identify blocks of KHO_EXT_SHIFT which contain preserved memory.
+ *
+ * Then it walks the digested radix tree and marks everything that doesn't have
+ * preserved memory as scratch.
+ *
+ * NOTE: This function allocates memory so it should be called when scratch has
+ * available space.
+ *
+ * NOTE: The pages of the KHO radix tree tables are not marked as preserved in

Quoted 1 line

^ preserved memory map radix tree :)

ACK.

Quoted 23 lines
Quoted 5 lines

+ * the KHO tree. But they are expected to remain untouched until the tree is
+ * fully parsed. So this function also considers them to be "preserved memory"
+ * and marks their blocks as busy.
+ */

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 963

Quoted 10 lines
kernel/liveupdate/kexec_handover.c +10 -0
+static void __init kho_extend_scratch(void)
+{
+	const struct kho_radix_walk_cb kho_cb = {
+		.leaf = kho_ext_walk_key,
+		.node = kho_ext_walk_node,
+	};
+	const struct kho_radix_walk_cb ext_cb = {
+		.leaf = kho_ext_mark_scratch,
+	};
+	struct kho_radix_tree radix;

sashiko says:

Is it possible for the radix variable to contain uninitialized stack memory here?
If radix is uninitialized, tree->root might contain garbage data when passed to kho_radix_init_tree()

Quoted 5 lines

and I agree :)

This should be

	struct kho_radix_tree radix = { 0 };

Ugh, right. But at the same time, it is odd for an initialization function to expect an initialized object. Perhaps I should move the kho_radix_init_tree() from kho_mem_retrieve() to kho_memory_init_early(). Then kho_extend_scratch() won't have to do the init at all and I can remove the if (tree->root) check from kho_radix_init_tree().

Signature · 2 lines
Regards,
Pratyush Yadav
maintainer
#26 lore raw

Re: [PATCH v2 15/18] kho: extend scratch

Quoted 9 lines · Pratyush Yadav
Quoted 6 lines · Mike Rapoport

Review

Quoted 2 lines · Pratyush Yadav
(quoted diff) +2 -0
+{
+	struct kho_radix_tree *tree = data;

Would be nice to say which tree in the variable name ;)

How about preserved_mem_map?

But this is the new tree, isn't it?
Maybe keep the variable name and add a comment?

Quoted 9 lines
Quoted 4 lines
Quoted 1 line

+/**

I don't think we expose statics as kernel-doc somewhere, so this probably shouldn't be a kernel-doc comment

This is a leftover from the previous version, where this was external.

I think the documentation is still worthwhile though, so I suppose I'll turn it into a normal comment by removing the /**.

Yeah, I meant it should not be a kernel-doc, just a plain comment.

Quoted 22 lines
Quoted 22 lines

kernel/liveupdate/kexec_handover.c static void __init kho_reserve_scratch(void) · line 963

Quoted 10 lines
kernel/liveupdate/kexec_handover.c +10 -0
+static void __init kho_extend_scratch(void)
+{
+	const struct kho_radix_walk_cb kho_cb = {
+		.leaf = kho_ext_walk_key,
+		.node = kho_ext_walk_node,
+	};
+	const struct kho_radix_walk_cb ext_cb = {
+		.leaf = kho_ext_mark_scratch,
+	};
+	struct kho_radix_tree radix;

sashiko says:

Is it possible for the radix variable to contain uninitialized stack memory here?
If radix is uninitialized, tree->root might contain garbage data when passed to kho_radix_init_tree()

and I agree :)

This should be

Quoted 8 lines
Quoted 1 line
	struct kho_radix_tree radix = { 0 };

Ugh, right. But at the same time, it is odd for an initialization function to expect an initialized object. Perhaps I should move the kho_radix_init_tree() from kho_mem_retrieve() to kho_memory_init_early(). Then kho_extend_scratch() won't have to do the init at all and I can remove the if (tree->root) check from kho_radix_init_tree().

Sounds about right :)

Quoted 3 lines
Signature · 2 lines
Regards,
Pratyush Yadav
Signature · 2 lines
Sincerely yours,
Mike.
author maintainer
#27 lore raw

Re: [PATCH v2 15/18] kho: extend scratch

Quoted 9 lines · Mike Rapoport
Quoted 8 lines · Pratyush Yadav
Quoted 6 lines · Mike Rapoport

Review

Quoted 2 lines · Pratyush Yadav
(quoted diff) +2 -0
+{
+	struct kho_radix_tree *tree = data;

Would be nice to say which tree in the variable name ;)

Quoted 4 lines
Quoted 1 line

How about preserved_mem_map?

But this is the new tree, isn't it?
Maybe keep the variable name and add a comment?

Oh, right. The fact that I didn't remember it certainly means a comment is needed. Will add.

[...]

Signature · 2 lines
Regards,
Pratyush Yadav
author maintainer
#28 lore raw

PATCH v2 16/18 memblock: make HugeTLB bootmem allocation work with KHO

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

Gigantic huge page allocation is somewhat broken currently when KHO is used.

Firstly, they break KHO scratch size accounting. RSRV_KERN is used to track how much memory is reserved for use by the kernel. Since alloc_bootmem() calls the memblock_alloc*() APIs, the hugepages allocated also get marked as RSRV_KERN.

Allocations marked RSRV_KERN are used by KHO to calculate how much scratch space it should reserve to make sure the next kernel has enough memory to boot when it is in scratch-only phase. Counting hugepages in that blows up scratch size, and can lead to the scratch allocation failing, making KHO unusable. This will show up when huge pages make up more than 50% of the system, which is a fairly common use case.

Secondly, while not supported right now, huge pages are user memory and can be preserved via KHO. The scratch spaces should not have any preserved memory. Allocating hugepages from scratch (on a KHO boot) can lead to them being un-preservable.

Introduce memblock_alloc_hugetlb(). This lets memblock tailor to the needs of hugetb without exposing those details to the general allocation routines.

First, it does not use mirrored memory for hugetlb. Mirrored memory is a limited resource that is best saved for kernel data structures, not user memory.

Second, if the memory found overlaps with KHO scratch areas, it discards the memory and retries.

Third, it simplifies the argument list by baking in some hugetlb assumptions like alignment and exact_nid. This also simplifies allocation logic in alloc_bootmem().

Also introduce MEMBLOCK_RSRV_HUGETLB to mark reservations made for HugeTLB. This will be used by KHO in future patches to correctly calculate scratch sizes.

Refactor some of the preparation logic like kmemleak tracking and accepting memory into a separate helper memblock_prep_allocation(), and use it from both memblock_alloc_hugetlb() and the usual memblock_alloc_range_nid().

---
 include/linux/memblock.h |   3 ++
 mm/hugetlb.c             |  22 +++-----
 mm/memblock.c            | 112 +++++++++++++++++++++++++++++++--------
 3 files changed, 100 insertions(+), 37 deletions(-)
include/linux/memblock.h +3 -0
index 546d7ef798b8..b3b4a6145fad 100644
@@ -52,6 +52,7 @@ extern unsigned long long max_possible_pfn;
  * memory reservations yet, so we get scratch memory from the previous
  * kernel that we know is good to use. It is the only memory that
  * allocations may happen from in this phase.
+ * @MEMBLOCK_RSRV_HUGETLB: memory is reserved for hugetlb pages
  */
 enum memblock_flags {
 	MEMBLOCK_NONE		= 0x0,	/* No special request */
@@ -62,6 +63,7 @@ enum memblock_flags {
 	MEMBLOCK_RSRV_NOINIT	= 0x10,	/* don't initialize struct pages */
 	MEMBLOCK_RSRV_KERN	= 0x20,	/* memory reserved for kernel use */
 	MEMBLOCK_KHO_SCRATCH	= 0x40,	/* scratch memory for kexec handover */
+	MEMBLOCK_RSRV_HUGETLB	= 0x80, /* memory reserved for hugetlb pages */
 };
 
 /**
@@ -421,6 +423,7 @@ void *memblock_alloc_try_nid_raw(phys_addr_t size, phys_addr_t align,
 void *memblock_alloc_try_nid(phys_addr_t size, phys_addr_t align,
 			     phys_addr_t min_addr, phys_addr_t max_addr,
 			     int nid);
+void *memblock_alloc_hugetlb(phys_addr_t size, int nid, bool exact_nid);
 
 static __always_inline void *memblock_alloc(phys_addr_t size, phys_addr_t align)
 {
mm/hugetlb.c +7 -15
index 4b80b167cc9c..fadcfa267ceb 100644
@@ -3029,29 +3029,21 @@ static __init void *alloc_bootmem(struct hstate *h, int nid, bool node_exact)
 	if (hugetlb_early_cma(h))
 		m = hugetlb_cma_alloc_bootmem(h, &listnode, node_exact);
 	else {
-		if (node_exact)
-			m = memblock_alloc_exact_nid_raw(huge_page_size(h),
-				huge_page_size(h), 0,
-				MEMBLOCK_ALLOC_ACCESSIBLE, nid);
-		else {
-			m = memblock_alloc_try_nid_raw(huge_page_size(h),
-				huge_page_size(h), 0,
-				MEMBLOCK_ALLOC_ACCESSIBLE, nid);
+		m = memblock_alloc_hugetlb(huge_page_size(h), nid, node_exact);
+		if (m) {
+			m->flags = 0;
+			m->cma = NULL;
+
 			/*
 			 * For pre-HVO to work correctly, pages need to be on
 			 * the list for the node they were actually allocated
 			 * from. That node may be different in the case of
-			 * fallback by memblock_alloc_try_nid_raw. So,
+			 * fallback by memblock_alloc_hugetlb_bootmem. So,
 			 * extract the actual node first.
 			 */
-			if (m)
+			if (!node_exact)
 				listnode = early_pfn_to_nid(PHYS_PFN(__pa(m)));
 		}
-
-		if (m) {
-			m->flags = 0;
-			m->cma = NULL;
-		}
 	}
 
 	if (m) {
mm/memblock.c +90 -22

130 lines not on this page · raw message

Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
maintainer
#29 lore raw

Re: [PATCH v2 16/18] memblock: make HugeTLB bootmem allocation work with KHO

Quoted 6 lines · Pratyush Yadav

Gigantic huge page allocation is somewhat broken currently when KHO is used.

Firstly, they break KHO scratch size accounting. RSRV_KERN is used to track how much memory is reserved for use by the kernel. Since alloc_bootmem() calls the memblock_alloc*() APIs, the hugepages

hugetlb::alloc_bootmem()

Quoted 7 lines

[...]
First, it does not use mirrored memory for hugetlb. Mirrored memory is a limited resource that is best saved for kernel data structures, not user memory.

Second, if the memory found overlaps with KHO scratch areas, it discards the memory and retries.

This sentence is somewhat hard to parse.

Quoted 8 lines
mm/memblock.c +0 -0
index 6349c48154f4..131e54dd5d8d 100644
@@ -1756,6 +1761,69 @@ void * __init memblock_alloc_try_nid_raw(

[ ... skip 51 lines ... ]

mm/memblock.c void * __init memblock_alloc_try_nid_raw( · line 1817

Quoted 6 lines
mm/memblock.c +6 -0
+		if (memblock_bottom_up())
+			start = addr + size;
+		else
+			start = addr - size;
+
+		goto retry;

Hmm, two goto retry don't seem nice :/
Although I can't see how to imporove it really.

Maybe add a helper for going the node fallback?

Signature · 2 lines
Sincerely yours,
Mike.
author maintainer
#30 lore raw

Re: [PATCH v2 16/18] memblock: make HugeTLB bootmem allocation work with KHO

Quoted 9 lines · Mike Rapoport
Quoted 6 lines · Pratyush Yadav

Gigantic huge page allocation is somewhat broken currently when KHO is used.

Firstly, they break KHO scratch size accounting. RSRV_KERN is used to track how much memory is reserved for use by the kernel. Since alloc_bootmem() calls the memblock_alloc*() APIs, the hugepages

hugetlb::alloc_bootmem()

ACK.

Quoted 10 lines
Quoted 8 lines

[...]
First, it does not use mirrored memory for hugetlb. Mirrored memory is a limited resource that is best saved for kernel data structures, not user memory.

Second, if the memory found overlaps with KHO scratch areas, it discards the memory and retries.

This sentence is somewhat hard to parse.

Okay, let me retry:

Second, if the free memory area found by memblock_find_in_range_node() is a part of a KHO scratch area, the free area is not used. Allocation is retried starting after the free area to ensure no hugepages come from KHO scratch.

Any better?

Quoted 18 lines
Quoted 9 lines
mm/memblock.c +0 -0
index 6349c48154f4..131e54dd5d8d 100644
@@ -1756,6 +1761,69 @@ void * __init memblock_alloc_try_nid_raw(

[ ... skip 51 lines ... ]

mm/memblock.c void * __init memblock_alloc_try_nid_raw( · line 1817

Quoted 6 lines
mm/memblock.c +6 -0
+		if (memblock_bottom_up())
+			start = addr + size;
+		else
+			start = addr - size;
+
+		goto retry;

Hmm, two goto retry don't seem nice :/
Although I can't see how to imporove it really.

Dunno, looked easy enough to understand to me.

Quoted 2 lines

Maybe add a helper for going the node fallback?

There is a small downside. There will then be no way to know the fallback was tried already, so if a retry is done because of scratch overlap, the fallback needs to be done again.

I don't think it should be too bad, so if you still prefer this then I can do it.

Signature · 2 lines
Regards,
Pratyush Yadav
maintainer
#31 lore raw

Re: [PATCH v2 16/18] memblock: make HugeTLB bootmem allocation work with KHO

Quoted 12 lines · Pratyush Yadav
Quoted 10 lines · Mike Rapoport
Quoted 6 lines · Pratyush Yadav

First, it does not use mirrored memory for hugetlb. Mirrored memory is a limited resource that is best saved for kernel data structures, not user memory.

Second, if the memory found overlaps with KHO scratch areas, it discards the memory and retries.

This sentence is somewhat hard to parse.

Quoted 8 lines

Okay, let me retry:

Second, if the free memory area found by memblock_find_in_range_node() is a part of a KHO scratch area, the free area is not used. Allocation is retried starting after the free area to ensure no hugepages come from KHO scratch.

Any better?

Yep :)

Quoted 21 lines
Quoted 18 lines
Quoted 9 lines
mm/memblock.c +0 -0
index 6349c48154f4..131e54dd5d8d 100644
@@ -1756,6 +1761,69 @@ void * __init memblock_alloc_try_nid_raw(

[ ... skip 51 lines ... ]

mm/memblock.c void * __init memblock_alloc_try_nid_raw( · line 1817

Quoted 6 lines
mm/memblock.c +6 -0
+		if (memblock_bottom_up())
+			start = addr + size;
+		else
+			start = addr - size;
+
+		goto retry;

Hmm, two goto retry don't seem nice :/
Although I can't see how to imporove it really.

Dunno, looked easy enough to understand to me.

Quoted 1 line
Quoted 8 lines
Quoted 1 line

Maybe add a helper for going the node fallback?

There is a small downside. There will then be no way to know the fallback was tried already, so if a retry is done because of scratch overlap, the fallback needs to be done again.

I don't think it should be too bad, so if you still prefer this then I can do it.

Let's keep it for now, maybe will find something smarter later.

Quoted 3 lines
Signature · 2 lines
Regards,
Pratyush Yadav
Signature · 2 lines
Sincerely yours,
Mike.
author maintainer
#32 lore raw

PATCH v2 17/18 memblock: allow calculating reserved size by flags

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

memblock_reserved_kern_size() returns the total size of all reserved areas flagged RSRV_KERN. KHO also needs total size of all reserved areas flagged HUGETLB to correctly size its scratch areas.

Refactor memblock_reserved_kern_size() into memblock_reserved_size_flags(). The new function returns total size of all reserved areas which match _any_ of the flags.

---
 include/linux/memblock.h           |  3 ++-
 kernel/liveupdate/kexec_handover.c | 14 ++++++++------
 mm/memblock.c                      |  8 +++++---
 3 files changed, 15 insertions(+), 10 deletions(-)
include/linux/memblock.h +2 -1
index b3b4a6145fad..a3b57066611d 100644
@@ -487,7 +487,8 @@ static inline __init_memblock bool memblock_bottom_up(void)
 
 phys_addr_t memblock_phys_mem_size(void);
 phys_addr_t memblock_reserved_size(void);
-phys_addr_t memblock_reserved_kern_size(phys_addr_t limit, int nid);
+phys_addr_t memblock_reserved_size_flags(phys_addr_t limit, int nid,
+					 enum memblock_flags flags);
 unsigned long memblock_estimated_nr_free_pages(void);
 phys_addr_t memblock_start_of_DRAM(void);
 phys_addr_t memblock_end_of_DRAM(void);
kernel/liveupdate/kexec_handover.c +8 -6
index 8540608b8602..b3c33f150e85 100644
@@ -749,13 +749,15 @@ static void __init scratch_size_update(void)
 	if (scratch_scale) {
 		phys_addr_t size;
 
-		size = memblock_reserved_kern_size(ARCH_LOW_ADDRESS_LIMIT,
-						   NUMA_NO_NODE);
+		size = memblock_reserved_size_flags(ARCH_LOW_ADDRESS_LIMIT,
+						    NUMA_NO_NODE,
+						    MEMBLOCK_RSRV_KERN);
 		size = size * scratch_scale / 100;
 		scratch_size_lowmem = size;
 
-		size = memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE,
-						   NUMA_NO_NODE);
+		size = memblock_reserved_size_flags(MEMBLOCK_ALLOC_ANYWHERE,
+						    NUMA_NO_NODE,
+						    MEMBLOCK_RSRV_KERN);
 		size = size * scratch_scale / 100 - scratch_size_lowmem;
 		scratch_size_global = size;
 	}
@@ -773,8 +775,8 @@ static phys_addr_t __init scratch_size_node(int nid)
 	phys_addr_t size;
 
 	if (scratch_scale) {
-		size = memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE,
-						   nid);
+		size = memblock_reserved_size_flags(MEMBLOCK_ALLOC_ANYWHERE,
+						    nid, MEMBLOCK_RSRV_KERN);
 		size = size * scratch_scale / 100;
 	} else {
 		size = scratch_size_pernode;
mm/memblock.c +5 -3
index 131e54dd5d8d..cc21f877cb67 100644
@@ -1893,7 +1893,8 @@ phys_addr_t __init_memblock memblock_reserved_size(void)
 	return memblock.reserved.total_size;
 }
 
-phys_addr_t __init_memblock memblock_reserved_kern_size(phys_addr_t limit, int nid)
+phys_addr_t __init_memblock memblock_reserved_size_flags(phys_addr_t limit, int nid,
+							 enum memblock_flags flags)
 {
 	struct memblock_region *r;
 	phys_addr_t total = 0;
@@ -1908,7 +1909,7 @@ phys_addr_t __init_memblock memblock_reserved_kern_size(phys_addr_t limit, int n
 			size = limit - r->base;
 
 		if (nid == memblock_get_region_node(r) || !numa_valid_node(nid))
-			if (r->flags & MEMBLOCK_RSRV_KERN)
+			if (r->flags & flags)
 				total += size;
 	}
 
@@ -1930,7 +1931,8 @@ phys_addr_t __init_memblock memblock_reserved_kern_size(phys_addr_t limit, int n
 unsigned long __init memblock_estimated_nr_free_pages(void)
 {
 	return PHYS_PFN(memblock_phys_mem_size() -
-			memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE, NUMA_NO_NODE));
+			memblock_reserved_size_flags(MEMBLOCK_ALLOC_ANYWHERE, NUMA_NO_NODE,
+						     MEMBLOCK_RSRV_KERN));
 }
 
 /* lowest address */
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
maintainer
#33 lore raw

Re: [PATCH v2 17/18] memblock: allow calculating reserved size by flags

include/linux/memblock.h static inline __init_memblock bool memblock_bottom_up(void) · line 491

Quoted 11 lines · Pratyush Yadav
include/linux/memblock.h +2 -1
index b3b4a6145fad..a3b57066611d 100644
@@ -487,7 +487,8 @@ static inline __init_memblock bool memblock_bottom_up(void)
 
 phys_addr_t memblock_phys_mem_size(void);
 phys_addr_t memblock_reserved_size(void);
-phys_addr_t memblock_reserved_kern_size(phys_addr_t limit, int nid);
+phys_addr_t memblock_reserved_size_flags(phys_addr_t limit, int nid,
+					 enum memblock_flags flags);

Ugh, I'd hate memblock_reserved_hugetlb_size() less ;-)

Signature · 2 lines
Sincerely yours,
Mike.
author maintainer
#34 lore raw

Re: [PATCH v2 17/18] memblock: allow calculating reserved size by flags

Quoted 7 lines · Mike Rapoport
Quoted 6 lines · Pratyush Yadav
include/linux/memblock.h +0 -0
index b3b4a6145fad..a3b57066611d 100644
@@ -487,7 +487,8 @@ static inline __init_memblock bool memblock_bottom_up(void)
 
Quoted 7 lines

include/linux/memblock.h static inline __init_memblock bool memblock_bottom_up(void) · line 491

Quoted 5 lines
include/linux/memblock.h +2 -1
 phys_addr_t memblock_phys_mem_size(void);
 phys_addr_t memblock_reserved_size(void);
-phys_addr_t memblock_reserved_kern_size(phys_addr_t limit, int nid);
+phys_addr_t memblock_reserved_size_flags(phys_addr_t limit, int nid,
+					 enum memblock_flags flags);

Ugh, I'd hate memblock_reserved_hugetlb_size() less ;-)

Sure, will do.

Signature · 2 lines
Regards,
Pratyush Yadav
author maintainer
#35 lore raw

PATCH v2 18/18 kho: exclude hugetlb memory from scratch size calculation

In reply to Pratyush Yadav

From: "Pratyush Yadav (Google)" <[email protected]>

HugeTLB pages can be preserved memory. So they are never allocated from scratch. Instead, they are allocated from the memory blocks with no preserved memory. These areas are detected at runtime on each boot.

But since they are allocated via memblock, they show up as RSRV_KERN, and blow up the scratch size when scratch scale is in use.

All hugetlb pages are marked RSRV_HUGETLB. Subtract their size from RSRV_KERN when calculating scratch sizes.

---
 kernel/liveupdate/kexec_handover.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
kernel/liveupdate/kexec_handover.c +12 -1
index b3c33f150e85..0d106c9197d9 100644
@@ -744,7 +744,8 @@ static void __init scratch_size_update(void)
 {
 	/*
 	 * If fixed sizes are not provided via command line, calculate them
-	 * now.
+	 * now. Use RSRV_KERN to count allocated memory, but remove HugeTLB
+	 * allocations from it because they never get allocated from scratch.
 	 */
 	if (scratch_scale) {
 		phys_addr_t size;
@@ -752,12 +753,19 @@ static void __init scratch_size_update(void)
 		size = memblock_reserved_size_flags(ARCH_LOW_ADDRESS_LIMIT,
 						    NUMA_NO_NODE,
 						    MEMBLOCK_RSRV_KERN);
+		size -= memblock_reserved_size_flags(ARCH_LOW_ADDRESS_LIMIT,
+						     NUMA_NO_NODE,
+						     MEMBLOCK_RSRV_HUGETLB);
+
 		size = size * scratch_scale / 100;
 		scratch_size_lowmem = size;
 
 		size = memblock_reserved_size_flags(MEMBLOCK_ALLOC_ANYWHERE,
 						    NUMA_NO_NODE,
 						    MEMBLOCK_RSRV_KERN);
+		size -= memblock_reserved_size_flags(MEMBLOCK_ALLOC_ANYWHERE,
+						     NUMA_NO_NODE,
+						     MEMBLOCK_RSRV_HUGETLB);
 		size = size * scratch_scale / 100 - scratch_size_lowmem;
 		scratch_size_global = size;
 	}
@@ -777,6 +785,9 @@ static phys_addr_t __init scratch_size_node(int nid)
 	if (scratch_scale) {
 		size = memblock_reserved_size_flags(MEMBLOCK_ALLOC_ANYWHERE,
 						    nid, MEMBLOCK_RSRV_KERN);
+		/* Do not count HugeTLB pages. */
+		size -= memblock_reserved_size_flags(MEMBLOCK_ALLOC_ANYWHERE,
+						     nid, MEMBLOCK_RSRV_HUGETLB);
 		size = size * scratch_scale / 100;
 	} else {
 		size = scratch_size_pernode;
Signature · 1 line
2.54.0.1032.g2f8565e1d1-goog
maintainer
#36 lore raw
In reply to Pratyush Yadav

On Fri, 05 Jun 2026 20:34:33 +0200, Pratyush Yadav <[email protected]> wrote:

Hi,

Quoted 7 lines

[...]
allocated from scratch, they will fail to be preserved with the upcoming hugetlb preservation series [0].

Fix this by introducing the concept of extended scratch areas. They are areas that the kernel discovers on boot by walking the radix tree and finding free memory ranges. See patch 10 for more details.

Overlall LGTM.

I have some small comments here and there for now as I din't get into all the details yet.

Signature · 2 lines
Sincerely yours,
Mike.
author maintainer
#37 lore raw
Quoted 8 lines · Mike Rapoport

On Fri, 05 Jun 2026 20:34:33 +0200, Pratyush Yadav <[email protected]> wrote:

Hi,

Quoted 4 lines

[...]
allocated from scratch, they will fail to be preserved with the upcoming hugetlb preservation series [0].

Quoted 8 lines
Quoted 3 lines

Fix this by introducing the concept of extended scratch areas. They are areas that the kernel discovers on boot by walking the radix tree and finding free memory ranges. See patch 10 for more details.

Overlall LGTM.

I have some small comments here and there for now as I din't get into all the details yet.

Thanks for reviewing, much appreciated! :-)

Signature · 2 lines
Regards,
Pratyush Yadav