xref: /linux/kernel/liveupdate/kexec_handover.c (revision 889dd44491b37c890b1b4ef40876cf19032ca897)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * kexec_handover.c - kexec handover metadata processing
4  * Copyright (C) 2023 Alexander Graf <graf@amazon.com>
5  * Copyright (C) 2025 Microsoft Corporation, Mike Rapoport <rppt@kernel.org>
6  * Copyright (C) 2025 Google LLC, Changyuan Lyu <changyuanl@google.com>
7  * Copyright (C) 2025 Pasha Tatashin <pasha.tatashin@soleen.com>
8  * Copyright (C) 2026 Google LLC, Jason Miu <jasonmiu@google.com>
9  */
10 
11 #define pr_fmt(fmt) "KHO: " fmt
12 
13 #include <linux/cleanup.h>
14 #include <linux/cma.h>
15 #include <linux/crash_dump.h>
16 #include <linux/kmemleak.h>
17 #include <linux/count_zeros.h>
18 #include <linux/kasan.h>
19 #include <linux/kexec.h>
20 #include <linux/kexec_handover.h>
21 #include <linux/kho_radix_tree.h>
22 #include <linux/utsname.h>
23 #include <linux/kho/abi/kexec_handover.h>
24 #include <linux/kho/abi/kexec_metadata.h>
25 #include <linux/libfdt.h>
26 #include <linux/list.h>
27 #include <linux/memblock.h>
28 #include <linux/page-isolation.h>
29 #include <linux/unaligned.h>
30 #include <linux/vmalloc.h>
31 
32 #include <asm/early_ioremap.h>
33 
34 /*
35  * KHO is tightly coupled with mm init and needs access to some of mm
36  * internal APIs.
37  */
38 #include "../../mm/mm_init.h"
39 #include "../../mm/vmalloc.h"
40 #include "../kexec_internal.h"
41 #include "kexec_handover_internal.h"
42 
43 /*
44  * This is the minimal alignment required by deferred struct page init.
45  * deferred_init_memmap_chunk frees memory to the buddy allocator, which looks
46  * at the neighboring pages (up to MAX_PAGE_ORDER) to merge them. If KHO bootmem
47  * is not aligned to that value, buddy can access uninitialized struct pages,
48  * which can cause a crash.
49  */
50 #define BOOTMEM_ALIGNMENT_BYTES (PAGE_SIZE * MAX_ORDER_NR_PAGES)
51 static_assert(BOOTMEM_ALIGNMENT_BYTES >= CMA_MIN_ALIGNMENT_BYTES);
52 
53 /* The magic token for preserved pages */
54 #define KHO_PAGE_MAGIC 0x4b484f50U /* ASCII for 'KHOP' */
55 
56 /*
57  * KHO uses page->private, which is an unsigned long, to store page metadata.
58  * Use it to store both the magic and the order.
59  */
60 union kho_page_info {
61 	unsigned long page_private;
62 	struct {
63 		unsigned int order;
64 		unsigned int magic;
65 	};
66 };
67 
68 static_assert(sizeof(union kho_page_info) == sizeof(((struct page *)0)->private));
69 
70 static bool kho_enable __ro_after_init = IS_ENABLED(CONFIG_KEXEC_HANDOVER_ENABLE_DEFAULT);
71 
72 bool kho_is_enabled(void)
73 {
74 	return kho_enable;
75 }
76 EXPORT_SYMBOL_GPL(kho_is_enabled);
77 
78 static int __init kho_parse_enable(char *p)
79 {
80 	return kstrtobool(p, &kho_enable);
81 }
82 early_param("kho", kho_parse_enable);
83 
84 struct kho_out {
85 	void *fdt;
86 	struct mutex lock; /* protects KHO FDT */
87 
88 	struct kho_radix_tree radix_tree;
89 	struct kho_debugfs dbg;
90 };
91 
92 static struct kho_out kho_out = {
93 	.lock = __MUTEX_INITIALIZER(kho_out.lock),
94 	.radix_tree = {
95 		.lock = __MUTEX_INITIALIZER(kho_out.radix_tree.lock),
96 	},
97 };
98 
99 struct kho_in {
100 	phys_addr_t fdt_phys;
101 	phys_addr_t bootmem_phys;
102 	char previous_release[__NEW_UTS_LEN + 1];
103 	u32 kexec_count;
104 	struct kho_debugfs dbg;
105 	struct kho_radix_tree radix_tree;
106 };
107 
108 static struct kho_in kho_in = {
109 };
110 
111 static const void *kho_get_fdt(void)
112 {
113 	return kho_in.fdt_phys ? phys_to_virt(kho_in.fdt_phys) : NULL;
114 }
115 
116 /**
117  * kho_encode_radix_key - Encodes a physical address and order into a radix key.
118  * @phys: The physical address of the page.
119  * @order: The order of the page.
120  *
121  * This function combines a page's physical address and its order into a
122  * single unsigned long, which is used as a key for all radix tree
123  * operations.
124  *
125  * Return: The encoded unsigned long radix key.
126  */
127 static unsigned long kho_encode_radix_key(phys_addr_t phys, unsigned int order)
128 {
129 	/* The physical address is encoded by shifting the PFN by its order. */
130 	unsigned long shift = PAGE_SHIFT + order;
131 	/* Order bit goes right before the shifted PFN. */
132 	unsigned long h = 1UL << (64 - shift);
133 	/* Shifted PFN. */
134 	unsigned long l = phys >> shift;
135 
136 	return h | l;
137 }
138 
139 /**
140  * kho_decode_radix_key - Decodes a radix key back into a physical address and order.
141  * @key: The unsigned long key to decode.
142  * @order: An output parameter, a pointer to an unsigned int where the decoded
143  *         page order will be stored.
144  *
145  * This function reverses the encoding performed by kho_encode_radix_key(),
146  * extracting the original physical address and page order from a given key.
147  *
148  * Return: The decoded physical address.
149  */
150 static phys_addr_t kho_decode_radix_key(unsigned long key, unsigned int *order)
151 {
152 	/* fls64() indexes starting from 1. */
153 	unsigned int order_bit = fls64(key) - 1;
154 	phys_addr_t phys;
155 
156 	/* order bit goes right before the shifted PFN. */
157 	*order = 64 - (PAGE_SHIFT + order_bit);
158 	/* The order bit is discarded by the shift */
159 	phys = key << (PAGE_SHIFT + *order);
160 
161 	return phys;
162 }
163 
164 static unsigned long kho_radix_get_bitmap_index(unsigned long key)
165 {
166 	return key % (1 << KHO_BITMAP_SIZE_LOG2);
167 }
168 
169 static unsigned long kho_radix_get_table_index(unsigned long key,
170 					       unsigned int level)
171 {
172 	int s;
173 
174 	s = ((level - 1) * KHO_TABLE_SIZE_LOG2) + KHO_BITMAP_SIZE_LOG2;
175 	return (key >> s) % (1 << KHO_TABLE_SIZE_LOG2);
176 }
177 
178 static void __ref *kho_radix_alloc_node(void)
179 {
180 	struct kho_radix_node *node;
181 
182 	if (slab_is_available())
183 		node = (struct kho_radix_node *)get_zeroed_page(GFP_KERNEL);
184 	else
185 		node = memblock_alloc(PAGE_SIZE, PAGE_SIZE);
186 
187 	return node;
188 }
189 
190 static void __ref kho_radix_free_node(struct kho_radix_node *node)
191 {
192 	if (slab_is_available())
193 		free_page((unsigned long)node);
194 	else
195 		memblock_free(node, PAGE_SIZE);
196 }
197 
198 /**
199  * kho_radix_add_key - Add a key to the radix tree.
200  * @tree: The KHO radix tree.
201  * @key: The key to add.
202  *
203  * This function traverses the radix tree based on the @key provided. It sets the
204  * corresponding bit in the leaf bitmap to mark the @key as present. If
205  * intermediate nodes do not exist along the path, they are allocated and added
206  * to the tree.
207  *
208  * NOTE: Currently only keys of width up to %KHO_RADIX_KEY_WIDTH are supported.
209  * This limit only exists because current users of the radix tree don't use more
210  * than that. Changing the maximum width requires changing the tree depth, which
211  * needs bumping the ABI version.
212  *
213  * Return: 0 on success, or a negative error code on failure.
214  */
215 int kho_radix_add_key(struct kho_radix_tree *tree, unsigned long key)
216 {
217 	/* Newly allocated nodes for error cleanup */
218 	struct kho_radix_node *intermediate_nodes[KHO_TREE_MAX_DEPTH] = { 0 };
219 	struct kho_radix_node *anchor_node = NULL;
220 	struct kho_radix_node *node = tree->root;
221 	struct kho_radix_node *new_node;
222 	unsigned int i, idx, anchor_idx;
223 	struct kho_radix_leaf *leaf;
224 	int err = 0;
225 
226 	if (WARN_ON_ONCE(!tree->root))
227 		return -EINVAL;
228 
229 	if (unlikely(fls64(key) > KHO_RADIX_KEY_WIDTH))
230 		return -ERANGE;
231 
232 	might_sleep();
233 
234 	guard(mutex)(&tree->lock);
235 
236 	/* Go from high levels to low levels */
237 	for (i = KHO_TREE_MAX_DEPTH - 1; i > 0; i--) {
238 		idx = kho_radix_get_table_index(key, i);
239 
240 		if (node->table[idx]) {
241 			node = phys_to_virt(node->table[idx]);
242 			continue;
243 		}
244 
245 		/* Next node is empty, create a new node for it */
246 		new_node = kho_radix_alloc_node();
247 		if (!new_node) {
248 			err = -ENOMEM;
249 			goto err_free_nodes;
250 		}
251 
252 		node->table[idx] = virt_to_phys(new_node);
253 
254 		/*
255 		 * Capture the node where the new branch starts for cleanup
256 		 * if allocation fails.
257 		 */
258 		if (!anchor_node) {
259 			anchor_node = node;
260 			anchor_idx = idx;
261 		}
262 		intermediate_nodes[i] = new_node;
263 
264 		node = new_node;
265 	}
266 
267 	/* Handle the leaf level bitmap (level 0) */
268 	idx = kho_radix_get_bitmap_index(key);
269 	leaf = (struct kho_radix_leaf *)node;
270 	__set_bit(idx, leaf->bitmap);
271 
272 	return 0;
273 
274 err_free_nodes:
275 	for (i = KHO_TREE_MAX_DEPTH - 1; i > 0; i--) {
276 		if (intermediate_nodes[i])
277 			kho_radix_free_node(intermediate_nodes[i]);
278 	}
279 	if (anchor_node)
280 		anchor_node->table[anchor_idx] = 0;
281 
282 	return err;
283 }
284 EXPORT_SYMBOL_GPL(kho_radix_add_key);
285 
286 /**
287  * kho_radix_del_key - Removes the key from the radix tree.
288  * @tree: The KHO radix tree.
289  * @key: The key to remove.
290  *
291  * This function traverses the radix tree and clears the bit corresponding to
292  * the @key, effectively removing it from the tree. It does not free the tree's
293  * intermediate nodes, even if they become empty.
294  */
295 void kho_radix_del_key(struct kho_radix_tree *tree, unsigned long key)
296 {
297 	struct kho_radix_node *node = tree->root;
298 	struct kho_radix_leaf *leaf;
299 	unsigned int i, idx;
300 
301 	if (WARN_ON_ONCE(!tree->root))
302 		return;
303 
304 	/* Keys wider than KHO_RADIX_KEY_WIDTH are not allowed to be added. */
305 	if (unlikely(fls64(key) > KHO_RADIX_KEY_WIDTH))
306 		return;
307 
308 	might_sleep();
309 
310 	guard(mutex)(&tree->lock);
311 
312 	/* Go from high levels to low levels */
313 	for (i = KHO_TREE_MAX_DEPTH - 1; i > 0; i--) {
314 		idx = kho_radix_get_table_index(key, i);
315 
316 		/*
317 		 * Attempting to delete a page that has not been preserved,
318 		 * return with a warning.
319 		 */
320 		if (WARN_ON(!node->table[idx]))
321 			return;
322 
323 		node = phys_to_virt(node->table[idx]);
324 	}
325 
326 	/* Handle the leaf level bitmap (level 0) */
327 	leaf = (struct kho_radix_leaf *)node;
328 	idx = kho_radix_get_bitmap_index(key);
329 	__clear_bit(idx, leaf->bitmap);
330 }
331 EXPORT_SYMBOL_GPL(kho_radix_del_key);
332 
333 static void __kho_radix_destroy_tree(struct kho_radix_node *root,
334 				     unsigned int level)
335 {
336 	unsigned long i;
337 
338 	if (level == 0) {
339 		kho_radix_free_node(root);
340 		return;
341 	}
342 
343 	for (i = 0; i < PAGE_SIZE / sizeof(phys_addr_t); i++) {
344 		if (root->table[i])
345 			__kho_radix_destroy_tree(phys_to_virt(root->table[i]),
346 						 level - 1);
347 	}
348 
349 	kho_radix_free_node(root);
350 }
351 
352 /**
353  * kho_radix_init_tree - initialize the radix tree.
354  * @tree:   the tree to initialize.
355  * @root:   root table of the radix tree.
356  *
357  * Initialize the radix tree with the given root node. If root is %NULL, an
358  * empty root table is allocated. If root is not %NULL, it is the caller's
359  * responsibility to make sure the root is valid and in the correct format.
360  *
361  * Return: 0 on success, -errno on failure.
362  */
363 int kho_radix_init_tree(struct kho_radix_tree *tree, struct kho_radix_node *root)
364 {
365 	if (!root)
366 		root = kho_radix_alloc_node();
367 	if (!root)
368 		return -ENOMEM;
369 
370 	tree->root = root;
371 	mutex_init(&tree->lock);
372 	return 0;
373 }
374 EXPORT_SYMBOL_GPL(kho_radix_init_tree);
375 
376 /**
377  * kho_radix_destroy_tree - Destroy the radix tree
378  * @tree: The radix tree to destroy
379  *
380  * Walk @tree and free all its nodes.
381  */
382 void kho_radix_destroy_tree(struct kho_radix_tree *tree)
383 {
384 	if (!tree->root)
385 		return;
386 
387 	__kho_radix_destroy_tree(tree->root, KHO_TREE_MAX_DEPTH - 1);
388 	tree->root = NULL;
389 }
390 EXPORT_SYMBOL_GPL(kho_radix_destroy_tree);
391 
392 static int kho_radix_walk_leaf(struct kho_radix_leaf *leaf, unsigned long key,
393 			       const struct kho_radix_walk_cb *cb, void *data)
394 {
395 	unsigned long *bitmap = (unsigned long *)leaf;
396 	unsigned int i;
397 	int err;
398 
399 	if (cb->node) {
400 		err = cb->node(virt_to_phys(leaf), data);
401 		if (err)
402 			return err;
403 	}
404 
405 	if (!cb->leaf)
406 		return 0;
407 
408 	for_each_set_bit(i, bitmap, PAGE_SIZE * BITS_PER_BYTE) {
409 		err = cb->leaf(key | i, data);
410 		if (err)
411 			return err;
412 	}
413 
414 	return 0;
415 }
416 
417 static int __kho_radix_walk_tree(struct kho_radix_node *root,
418 				 unsigned int level, unsigned long start,
419 				 const struct kho_radix_walk_cb *cb, void *data)
420 {
421 	struct kho_radix_node *node;
422 	struct kho_radix_leaf *leaf;
423 	unsigned long key, i;
424 	unsigned int shift;
425 	int err;
426 
427 	if (cb->node) {
428 		err = cb->node(virt_to_phys(root), data);
429 		if (err)
430 			return err;
431 	}
432 
433 	for (i = 0; i < PAGE_SIZE / sizeof(phys_addr_t); i++) {
434 		if (!root->table[i])
435 			continue;
436 
437 		shift = ((level - 1) * KHO_TABLE_SIZE_LOG2) +
438 			KHO_BITMAP_SIZE_LOG2;
439 		key = start | (i << shift);
440 
441 		node = phys_to_virt(root->table[i]);
442 
443 		if (level == 1) {
444 			/*
445 			 * we are at level 1,
446 			 * node is pointing to the level 0 bitmap.
447 			 */
448 			leaf = (struct kho_radix_leaf *)node;
449 			err = kho_radix_walk_leaf(leaf, key, cb, data);
450 		} else {
451 			err  = __kho_radix_walk_tree(node, level - 1,
452 						     key, cb, data);
453 		}
454 
455 		if (err)
456 			return err;
457 	}
458 
459 	return 0;
460 }
461 
462 /**
463  * kho_radix_walk_tree - Traverses the radix tree and calls a callback for each key.
464  * @tree: A pointer to the KHO radix tree to walk.
465  * @cb:   Set of callbacks to be invoked during the tree walk.
466  * @data: Opaque data pointer passed to each callback in @cb.
467  *
468  * This function walks the radix tree, searching from the top level down to the
469  * lowest level (level 0), invoking the appropriate callbacks.
470  *
471  * Return: 0 if the walk completed the specified tree, or the non-zero return
472  *         value from the callback that stopped the walk.
473  */
474 int kho_radix_walk_tree(struct kho_radix_tree *tree,
475 			const struct kho_radix_walk_cb *cb, void *data)
476 {
477 	if (WARN_ON_ONCE(!tree->root))
478 		return -EINVAL;
479 
480 	guard(mutex)(&tree->lock);
481 
482 	return __kho_radix_walk_tree(tree->root, KHO_TREE_MAX_DEPTH - 1, 0, cb,
483 				     data);
484 }
485 EXPORT_SYMBOL_GPL(kho_radix_walk_tree);
486 
487 /* For physically contiguous 0-order pages. */
488 static void kho_init_pages(struct page *page, unsigned long nr_pages)
489 {
490 	for (unsigned long i = 0; i < nr_pages; i++) {
491 		set_page_count(page + i, 1);
492 		/* Clear each page's codetag to avoid accounting mismatch. */
493 		clear_page_tag_ref(page + i);
494 	}
495 }
496 
497 static void kho_init_folio(struct page *page, unsigned int order)
498 {
499 	unsigned long nr_pages = (1 << order);
500 
501 	/* Head page gets refcount of 1. */
502 	set_page_count(page, 1);
503 	/* Clear head page's codetag to avoid accounting mismatch. */
504 	clear_page_tag_ref(page);
505 
506 	/* For higher order folios, tail pages get a page count of zero. */
507 	for (unsigned long i = 1; i < nr_pages; i++)
508 		set_page_count(page + i, 0);
509 
510 	if (order > 0)
511 		prep_compound_page(page, order);
512 }
513 
514 static struct page *kho_restore_page(phys_addr_t phys, bool is_folio)
515 {
516 	struct page *page = pfn_to_online_page(PHYS_PFN(phys));
517 	unsigned long nr_pages;
518 	union kho_page_info info;
519 
520 	if (!page)
521 		return NULL;
522 
523 	info.page_private = page->private;
524 	/*
525 	 * deserialize_bitmap() only sets the magic on the head page. This magic
526 	 * check also implicitly makes sure phys is order-aligned since for
527 	 * non-order-aligned phys addresses, magic will never be set.
528 	 */
529 	if (WARN_ON_ONCE(info.magic != KHO_PAGE_MAGIC))
530 		return NULL;
531 	nr_pages = (1 << info.order);
532 
533 	/* Clear private to make sure later restores on this page error out. */
534 	page->private = 0;
535 
536 	if (is_folio)
537 		kho_init_folio(page, info.order);
538 	else
539 		kho_init_pages(page, nr_pages);
540 
541 	adjust_managed_page_count(page, nr_pages);
542 	return page;
543 }
544 
545 /**
546  * kho_restore_folio - recreates the folio from the preserved memory.
547  * @phys: physical address of the folio.
548  *
549  * Return: pointer to the struct folio on success, NULL on failure.
550  */
551 struct folio *kho_restore_folio(phys_addr_t phys)
552 {
553 	struct page *page = kho_restore_page(phys, true);
554 
555 	return page ? page_folio(page) : NULL;
556 }
557 EXPORT_SYMBOL_GPL(kho_restore_folio);
558 
559 /**
560  * kho_restore_pages - restore list of contiguous order 0 pages.
561  * @phys: physical address of the first page.
562  * @nr_pages: number of pages.
563  *
564  * Restore a contiguous list of order 0 pages that was preserved with
565  * kho_preserve_pages().
566  *
567  * Return: the first page on success, NULL on failure.
568  */
569 struct page *kho_restore_pages(phys_addr_t phys, unsigned long nr_pages)
570 {
571 	const unsigned long start_pfn = PHYS_PFN(phys);
572 	const unsigned long end_pfn = start_pfn + nr_pages;
573 	unsigned long pfn = start_pfn;
574 
575 	while (pfn < end_pfn) {
576 		const unsigned int order =
577 			min(count_trailing_zeros(pfn), ilog2(end_pfn - pfn));
578 		struct page *page = kho_restore_page(PFN_PHYS(pfn), false);
579 
580 		if (!page)
581 			return NULL;
582 		pfn += 1 << order;
583 	}
584 
585 	return pfn_to_page(start_pfn);
586 }
587 EXPORT_SYMBOL_GPL(kho_restore_pages);
588 
589 /*
590  * With CONFIG_DEFERRED_STRUCT_PAGE_INIT, struct pages in higher memory regions
591  * may not be initialized yet at the time KHO deserializes preserved memory.
592  * KHO uses the struct page to store metadata and a later initialization would
593  * overwrite it.
594  * Ensure all the struct pages in the preservation are
595  * initialized. kho_preserved_memory_reserve() marks the reservation as noinit
596  * to make sure they don't get re-initialized later.
597  */
598 static struct page *__init kho_get_preserved_page(phys_addr_t phys,
599 						  unsigned int order)
600 {
601 	unsigned long pfn = PHYS_PFN(phys);
602 	int nid;
603 
604 	if (!IS_ENABLED(CONFIG_DEFERRED_STRUCT_PAGE_INIT))
605 		return pfn_to_page(pfn);
606 
607 	nid = early_pfn_to_nid(pfn);
608 	for (unsigned long i = 0; i < (1UL << order); i++)
609 		init_deferred_page(pfn + i, nid);
610 
611 	return pfn_to_page(pfn);
612 }
613 
614 static int __init kho_preserved_memory_reserve(unsigned long key, void *data)
615 {
616 	union kho_page_info info;
617 	struct page *page;
618 	unsigned int order;
619 	phys_addr_t phys;
620 	u64 sz;
621 
622 	phys = kho_decode_radix_key(key, &order);
623 
624 	sz = 1UL << (order + PAGE_SHIFT);
625 	page = kho_get_preserved_page(phys, order);
626 
627 	/* Reserve the memory preserved in KHO in memblock */
628 	memblock_reserve(phys, sz);
629 	memblock_reserved_mark_noinit(phys, sz);
630 	info.magic = KHO_PAGE_MAGIC;
631 	info.order = order;
632 	page->private = info.page_private;
633 
634 	return 0;
635 }
636 
637 /* Returns physical address of the preserved memory map from FDT */
638 static phys_addr_t __init kho_get_mem_map_phys(const void *fdt)
639 {
640 	const void *mem_ptr;
641 	int len;
642 
643 	mem_ptr = fdt_getprop(fdt, 0, KHO_FDT_MEMORY_MAP_PROP_NAME, &len);
644 	if (!mem_ptr || len != sizeof(u64)) {
645 		pr_err("failed to get preserved memory map\n");
646 		return 0;
647 	}
648 
649 	return get_unaligned((const u64 *)mem_ptr);
650 }
651 
652 static void __init *kho_get_mem_map(const void *fdt)
653 {
654 	phys_addr_t phys = kho_get_mem_map_phys(fdt);
655 
656 	return phys ? phys_to_virt(phys) : NULL;
657 }
658 
659 /*
660  * With KHO enabled, memory can become fragmented because KHO regions may
661  * be anywhere in physical address space. The bootmem regions give us a
662  * safe zones that we will never see KHO allocations from. This is where we
663  * can later safely load our new kexec images into and then use the bootmem
664  * area for early allocations that happen before page allocator is
665  * initialized.
666  */
667 struct kho_bootmem *kho_bootmem;
668 unsigned int kho_bootmem_cnt;
669 
670 /*
671  * The bootmem areas are scaled by default as percent of memory allocated from
672  * memblock. A user can override the scale with command line parameter:
673  *
674  * kho_bootmem=N%
675  *
676  * It is also possible to explicitly define size for a lowmem, a global and
677  * per-node bootmem areas:
678  *
679  * kho_bootmem=l[KMG],n[KMG],m[KMG]
680  *
681  * The explicit size definition takes precedence over scale definition.
682  */
683 static unsigned int bootmem_scale __initdata = 200;
684 static phys_addr_t bootmem_size_global __initdata;
685 static phys_addr_t bootmem_size_pernode __initdata;
686 static phys_addr_t bootmem_size_lowmem __initdata;
687 
688 static int __init kho_parse_bootmem_size(char *p)
689 {
690 	size_t len;
691 	unsigned long sizes[3];
692 	size_t total_size = 0;
693 	int i;
694 
695 	if (!p)
696 		return -EINVAL;
697 
698 	len = strlen(p);
699 	if (!len)
700 		return -EINVAL;
701 
702 	/* parse nn% */
703 	if (p[len - 1] == '%') {
704 		/* unsigned int max is 4,294,967,295, 10 chars */
705 		char s_scale[11] = {};
706 		int ret = 0;
707 
708 		if (len > ARRAY_SIZE(s_scale))
709 			return -EINVAL;
710 
711 		memcpy(s_scale, p, len - 1);
712 		ret = kstrtouint(s_scale, 10, &bootmem_scale);
713 		if (!ret)
714 			pr_notice("bootmem scale is %d%%\n", bootmem_scale);
715 		return ret;
716 	}
717 
718 	/* parse ll[KMG],mm[KMG],nn[KMG] */
719 	for (i = 0; i < ARRAY_SIZE(sizes); i++) {
720 		char *endp = p;
721 
722 		if (i > 0) {
723 			if (*p != ',')
724 				return -EINVAL;
725 			p += 1;
726 		}
727 
728 		sizes[i] = memparse(p, &endp);
729 		if (endp == p)
730 			return -EINVAL;
731 		p = endp;
732 		total_size += sizes[i];
733 	}
734 
735 	if (!total_size)
736 		return -EINVAL;
737 
738 	/* The string should be fully consumed by now. */
739 	if (*p)
740 		return -EINVAL;
741 
742 	bootmem_size_lowmem = sizes[0];
743 	bootmem_size_global = sizes[1];
744 	bootmem_size_pernode = sizes[2];
745 	bootmem_scale = 0;
746 
747 	pr_notice("bootmem areas: lowmem: %lluMiB global: %lluMiB pernode: %lldMiB\n",
748 		  (u64)(bootmem_size_lowmem >> 20),
749 		  (u64)(bootmem_size_global >> 20),
750 		  (u64)(bootmem_size_pernode >> 20));
751 
752 	return 0;
753 }
754 early_param("kho_bootmem", kho_parse_bootmem_size);
755 
756 static void __init bootmem_size_update(void)
757 {
758 	/*
759 	 * If fixed sizes are not provided via command line, calculate them now.
760 	 * Remove HugeTLB allocations from it because they never get allocated
761 	 * from bootmem.
762 	 */
763 	if (bootmem_scale) {
764 		phys_addr_t size;
765 
766 		size = memblock_reserved_kern_size(ARCH_LOW_ADDRESS_LIMIT,
767 						   NUMA_NO_NODE);
768 		size -= memblock_reserved_hugetlb_size(ARCH_LOW_ADDRESS_LIMIT,
769 						       NUMA_NO_NODE);
770 		size = size * bootmem_scale / 100;
771 		bootmem_size_lowmem = size;
772 
773 		size = memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE,
774 						   NUMA_NO_NODE);
775 		size -= memblock_reserved_hugetlb_size(MEMBLOCK_ALLOC_ANYWHERE,
776 						       NUMA_NO_NODE);
777 		size = size * bootmem_scale / 100 - bootmem_size_lowmem;
778 		bootmem_size_global = size;
779 	}
780 
781 	/*
782 	 * bootmem areas are released as MIGRATE_CMA. Round them up to the right
783 	 * size.
784 	 */
785 	bootmem_size_lowmem = round_up(bootmem_size_lowmem, BOOTMEM_ALIGNMENT_BYTES);
786 	bootmem_size_global = round_up(bootmem_size_global, BOOTMEM_ALIGNMENT_BYTES);
787 }
788 
789 static phys_addr_t __init bootmem_size_node(int nid)
790 {
791 	phys_addr_t size;
792 
793 	if (bootmem_scale) {
794 		size = memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE,
795 						   nid);
796 		/* Do not count HugeTLB pages. */
797 		size -= memblock_reserved_hugetlb_size(MEMBLOCK_ALLOC_ANYWHERE,
798 						       nid);
799 		size = size * bootmem_scale / 100;
800 	} else {
801 		size = bootmem_size_pernode;
802 	}
803 
804 	return round_up(size, BOOTMEM_ALIGNMENT_BYTES);
805 }
806 
807 bool kho_bootmem_overlap(phys_addr_t phys, size_t size)
808 {
809 	phys_addr_t bootmem_start, bootmem_end;
810 	unsigned int i;
811 
812 	for (i = 0; i < kho_bootmem_cnt; i++) {
813 		bootmem_start = kho_bootmem[i].addr;
814 		bootmem_end = kho_bootmem[i].addr + kho_bootmem[i].size;
815 
816 		if (phys < bootmem_end && (phys + size) > bootmem_start)
817 			return true;
818 	}
819 
820 	return false;
821 }
822 
823 /**
824  * kho_reserve_bootmem - Reserve a contiguous chunk of memory for kexec
825  *
826  * With KHO we can preserve arbitrary pages in the system. To ensure we still
827  * have a large contiguous region of memory when we search the physical address
828  * space for target memory, let's make sure we always have a large CMA region
829  * active. This CMA region will only be used for movable pages which are not a
830  * problem for us during KHO because we can just move them somewhere else.
831  */
832 static void __init kho_reserve_bootmem(void)
833 {
834 	int nid, i = 0, max_nr_bootmem;
835 	phys_addr_t addr, size;
836 
837 	if (!kho_enable)
838 		return;
839 
840 	bootmem_size_update();
841 
842 	/* FIXME: deal with node hot-plug/remove */
843 	max_nr_bootmem = nodes_weight(node_states[N_MEMORY]) + 2;
844 	size = max_nr_bootmem * sizeof(*kho_bootmem);
845 	kho_bootmem = memblock_alloc(size, PAGE_SIZE);
846 	if (!kho_bootmem) {
847 		pr_err("Failed to reserve bootmem array\n");
848 		goto err_disable_kho;
849 	}
850 
851 	/*
852 	 * reserve bootmem area in low memory for lowmem allocations in the
853 	 * next kernel
854 	 */
855 	size = bootmem_size_lowmem;
856 	addr = memblock_phys_alloc_range(size, BOOTMEM_ALIGNMENT_BYTES, 0,
857 					 ARCH_LOW_ADDRESS_LIMIT);
858 	if (!addr) {
859 		pr_err("Failed to reserve lowmem bootmem\n");
860 		goto err_free_bootmem_desc;
861 	}
862 
863 	kho_bootmem[i].addr = addr;
864 	kho_bootmem[i].size = size;
865 	i++;
866 
867 	/* reserve large contiguous area for allocations without nid */
868 	size = bootmem_size_global;
869 	addr = memblock_phys_alloc(size, BOOTMEM_ALIGNMENT_BYTES);
870 	if (!addr) {
871 		pr_err("Failed to reserve global bootmem\n");
872 		goto err_free_bootmem_areas;
873 	}
874 
875 	kho_bootmem[i].addr = addr;
876 	kho_bootmem[i].size = size;
877 	i++;
878 
879 	/*
880 	 * Loop over nodes that have both memory and are online. Skip
881 	 * memoryless nodes, as we can not allocate bootmem areas there.
882 	 */
883 	for_each_node_state(nid, N_MEMORY) {
884 		size = bootmem_size_node(nid);
885 		if (!size)
886 			continue;
887 
888 		addr = memblock_alloc_range_nid(size, BOOTMEM_ALIGNMENT_BYTES,
889 						0, MEMBLOCK_ALLOC_ACCESSIBLE,
890 						nid, true);
891 		if (!addr) {
892 			pr_err("Failed to reserve nid %d bootmem\n", nid);
893 			goto err_free_bootmem_areas;
894 		}
895 
896 		kho_bootmem[i].addr = addr;
897 		kho_bootmem[i].size = size;
898 		i++;
899 	}
900 
901 	/*
902 	 * Nodes that needed no bootmem were skipped, so fewer areas than
903 	 * initially estimated may have been reserved.
904 	 */
905 	kho_bootmem_cnt = i;
906 
907 	return;
908 
909 err_free_bootmem_areas:
910 	for (i--; i >= 0; i--)
911 		memblock_phys_free(kho_bootmem[i].addr, kho_bootmem[i].size);
912 err_free_bootmem_desc:
913 	memblock_free(kho_bootmem, max_nr_bootmem * sizeof(*kho_bootmem));
914 err_disable_kho:
915 	pr_warn("Failed to reserve bootmem, disabling kexec handover\n");
916 	kho_enable = false;
917 }
918 
919 /*
920  * Look for free blocks of 1G. This is a heuristic chosen to work efficiently
921  * with large systems with hundreds of gigabytes of memory. It will work poorly
922  * on smaller systems. The algorithm itself doesn't depend on the actual value,
923  * so it can be changed to a different heuristic later if needed.
924  */
925 #define KHO_DISCOVER_BLKSIZE		SZ_1G
926 #define KHO_DISCOVER_BLKSHIFT	const_ilog2(KHO_DISCOVER_BLKSIZE)
927 
928 /* Called for the KHO preserved memory radix tree. */
929 static int __init kho_discover_walk_leaf(unsigned long key, void *data)
930 {
931 	struct kho_radix_tree *busy_blocks = data;
932 	phys_addr_t start, end;
933 	unsigned int order;
934 	int err;
935 
936 	/*
937 	 * The key is from the KHO preserved memory radix tree. It is decoded to
938 	 * a physical address of a preservation and its order.
939 	 */
940 	start = kho_decode_radix_key(key, &order);
941 	end = start + (1UL << (order + PAGE_SHIFT));
942 
943 	while (start < end) {
944 		err = kho_radix_add_key(busy_blocks, start >> KHO_DISCOVER_BLKSHIFT);
945 		if (err)
946 			return err;
947 
948 		start += (1UL << KHO_DISCOVER_BLKSHIFT);
949 	}
950 
951 	return 0;
952 }
953 
954 /* Called for the KHO preserved memory radix tree. */
955 static int __init kho_discover_walk_node(phys_addr_t phys, void *data)
956 {
957 	struct kho_radix_tree *busy_blocks = data;
958 
959 	return kho_radix_add_key(busy_blocks, phys >> KHO_DISCOVER_BLKSHIFT);
960 }
961 
962 /* Called for the busy block radix tree. */
963 static int __init kho_discover_mark_noprsrv(unsigned long key, void *data)
964 {
965 	phys_addr_t *prev_end = data;
966 	phys_addr_t start = key << KHO_DISCOVER_BLKSHIFT;
967 	int err;
968 
969 	if (start > *prev_end) {
970 		err = memblock_mark_kho_noprsrv(*prev_end, start - *prev_end);
971 		if (err)
972 			return err;
973 	}
974 
975 	*prev_end = start + (1UL << KHO_DISCOVER_BLKSHIFT);
976 	return 0;
977 }
978 
979 /*
980  * kho_discover_noprsrv - Discover memory with no preservations
981  *
982  * Discovers memory ranges with no preserved memory and marks it as NOPRSRV.
983  * This lets memblock allocate memory from areas outside KHO bootmem.
984  *
985  * The KHO preserved memory radix tree mixes both physical address and order
986  * into a single key. This makes it hard to look for free ranges directly. This
987  * function first walks the radix tree and digests it down into another radix
988  * tree, whose keys identify blocks of size KHO_DISCOVER_BLKSIZE which contain
989  * preserved memory.
990  *
991  * Then it walks the digested radix tree and marks everything that doesn't have
992  * preserved memory as NOPRSRV.
993  *
994  * NOTE: This function allocates memory so it should be called when bootmem has
995  * available space.
996  *
997  * NOTE: The pages of the KHO preserved memory radix tree tables are not marked
998  * as preserved in the preserved memory tree. But they are expected to remain
999  * untouched until the tree is fully parsed. So this function also considers
1000  * them to be "preserved memory" and marks their blocks as busy.
1001  *
1002  * NOTE: efi_init()::reserve_regions() removes all regions except
1003  * MEMBLOCK_KHO_NOPRSRV. This function adds such regions but they are not KHO
1004  * boot memory, so they should not be removed. This function should always be
1005  * called after reserve_regions().
1006  */
1007 static void __init kho_discover_noprsrv(void)
1008 {
1009 	const struct kho_radix_walk_cb kho_cb = {
1010 		.leaf = kho_discover_walk_leaf,
1011 		.node = kho_discover_walk_node,
1012 	};
1013 	const struct kho_radix_walk_cb ext_cb = {
1014 		.leaf = kho_discover_mark_noprsrv,
1015 	};
1016 	static struct lock_class_key busy_radix_class;
1017 	struct kho_radix_tree busy_blocks;
1018 	phys_addr_t prev_end = 0;
1019 	int err = 0;
1020 
1021 	err = kho_radix_init_tree(&busy_blocks, NULL);
1022 	if (err)
1023 		goto print;
1024 
1025 	/*
1026 	 * The walk of kho_in.radix_tree adds keys to busy_blocks. The walk
1027 	 * takes the kho_in radix tree lock and adding the key takes busy_blocks
1028 	 * lock. Since both are struct kho_radix_tree and share the same lock
1029 	 * class, lockdep gets confused. Set a different class for
1030 	 * busy_blocks.lock to make lockdep happy.
1031 	 */
1032 	lockdep_set_class(&busy_blocks.lock, &busy_radix_class);
1033 
1034 	/* Walk the KHO radix tree to find busy blocks. */
1035 	err = kho_radix_walk_tree(&kho_in.radix_tree, &kho_cb, &busy_blocks);
1036 	if (err)
1037 		goto out;
1038 
1039 	/* Walk the busy blocks and mark everything between keys as noprsrv. */
1040 	err = kho_radix_walk_tree(&busy_blocks, &ext_cb, &prev_end);
1041 	if (err)
1042 		goto out;
1043 
1044 	/* Mark everything from last busy block to end of DRAM. */
1045 	if (prev_end < memblock_end_of_DRAM())
1046 		err = memblock_mark_kho_noprsrv(prev_end, memblock_end_of_DRAM() - prev_end);
1047 
1048 	/* fallthrough */
1049 out:
1050 	kho_radix_destroy_tree(&busy_blocks);
1051 print:
1052 	if (err)
1053 		pr_err("Failed to discover extra allocatable memory: %pe\n", ERR_PTR(err));
1054 }
1055 
1056 /**
1057  * kho_add_subtree - record the physical address of a sub blob in KHO root tree.
1058  * @name: name of the sub tree.
1059  * @blob: the sub tree blob.
1060  * @size: size of the blob in bytes.
1061  *
1062  * Creates a new child node named @name in KHO root FDT and records
1063  * the physical address of @blob. The pages of @blob must also be preserved
1064  * by KHO for the new kernel to retrieve it after kexec.
1065  *
1066  * A debugfs blob entry is also created at
1067  * ``/sys/kernel/debug/kho/out/sub_fdts/@name`` when kernel is configured with
1068  * CONFIG_KEXEC_HANDOVER_DEBUGFS
1069  *
1070  * Return: 0 on success, error code on failure
1071  */
1072 int kho_add_subtree(const char *name, void *blob, size_t size)
1073 {
1074 	phys_addr_t phys = virt_to_phys(blob);
1075 	void *root_fdt = kho_out.fdt;
1076 	u64 size_u64 = size;
1077 	int err = -ENOMEM;
1078 	int off, fdt_err;
1079 
1080 	guard(mutex)(&kho_out.lock);
1081 
1082 	fdt_err = fdt_open_into(root_fdt, root_fdt, PAGE_SIZE);
1083 	if (fdt_err < 0)
1084 		return err;
1085 
1086 	off = fdt_add_subnode(root_fdt, 0, name);
1087 	if (off < 0) {
1088 		if (off == -FDT_ERR_EXISTS)
1089 			err = -EEXIST;
1090 		goto out_pack;
1091 	}
1092 
1093 	fdt_err = fdt_setprop(root_fdt, off, KHO_SUB_TREE_PROP_NAME,
1094 			      &phys, sizeof(phys));
1095 	if (fdt_err < 0)
1096 		goto out_del_node;
1097 
1098 	fdt_err = fdt_setprop(root_fdt, off, KHO_SUB_TREE_SIZE_PROP_NAME,
1099 			      &size_u64, sizeof(size_u64));
1100 	if (fdt_err < 0)
1101 		goto out_del_node;
1102 
1103 	WARN_ON_ONCE(kho_debugfs_blob_add(&kho_out.dbg, name, blob,
1104 					  size, false));
1105 
1106 	err = 0;
1107 	goto out_pack;
1108 
1109 out_del_node:
1110 	fdt_del_node(root_fdt, off);
1111 out_pack:
1112 	fdt_pack(root_fdt);
1113 
1114 	return err;
1115 }
1116 EXPORT_SYMBOL_GPL(kho_add_subtree);
1117 
1118 void kho_remove_subtree(void *blob)
1119 {
1120 	phys_addr_t target_phys = virt_to_phys(blob);
1121 	void *root_fdt = kho_out.fdt;
1122 	int off;
1123 	int err;
1124 
1125 	guard(mutex)(&kho_out.lock);
1126 
1127 	err = fdt_open_into(root_fdt, root_fdt, PAGE_SIZE);
1128 	if (err < 0)
1129 		return;
1130 
1131 	for (off = fdt_first_subnode(root_fdt, 0); off >= 0;
1132 	     off = fdt_next_subnode(root_fdt, off)) {
1133 		const u64 *val;
1134 		int len;
1135 
1136 		val = fdt_getprop(root_fdt, off, KHO_SUB_TREE_PROP_NAME, &len);
1137 		if (!val || len != sizeof(phys_addr_t))
1138 			continue;
1139 
1140 		if ((phys_addr_t)*val == target_phys) {
1141 			fdt_del_node(root_fdt, off);
1142 			kho_debugfs_blob_remove(&kho_out.dbg, blob);
1143 			break;
1144 		}
1145 	}
1146 
1147 	fdt_pack(root_fdt);
1148 }
1149 EXPORT_SYMBOL_GPL(kho_remove_subtree);
1150 
1151 /**
1152  * kho_preserve_folio - preserve a folio across kexec.
1153  * @folio: folio to preserve.
1154  *
1155  * Instructs KHO to preserve the whole folio across kexec. The order
1156  * will be preserved as well.
1157  *
1158  * Return: 0 on success, error code on failure
1159  */
1160 int kho_preserve_folio(struct folio *folio)
1161 {
1162 	struct kho_radix_tree *tree = &kho_out.radix_tree;
1163 	const unsigned long pfn = folio_pfn(folio);
1164 	const unsigned int order = folio_order(folio);
1165 
1166 	if (IS_ENABLED(CONFIG_KEXEC_HANDOVER_DEBUG) &&
1167 	    WARN_ON(kho_bootmem_overlap(pfn << PAGE_SHIFT, PAGE_SIZE << order)))
1168 		return -EINVAL;
1169 
1170 	return kho_radix_add_key(tree, kho_encode_radix_key(PFN_PHYS(pfn),
1171 							    order));
1172 }
1173 EXPORT_SYMBOL_GPL(kho_preserve_folio);
1174 
1175 /**
1176  * kho_unpreserve_folio - unpreserve a folio.
1177  * @folio: folio to unpreserve.
1178  *
1179  * Instructs KHO to unpreserve a folio that was preserved by
1180  * kho_preserve_folio() before. The provided @folio (pfn and order)
1181  * must exactly match a previously preserved folio.
1182  */
1183 void kho_unpreserve_folio(struct folio *folio)
1184 {
1185 	struct kho_radix_tree *tree = &kho_out.radix_tree;
1186 	const unsigned long pfn = folio_pfn(folio);
1187 	const unsigned int order = folio_order(folio);
1188 
1189 	kho_radix_del_key(tree, kho_encode_radix_key(PFN_PHYS(pfn), order));
1190 }
1191 EXPORT_SYMBOL_GPL(kho_unpreserve_folio);
1192 
1193 static unsigned int __kho_preserve_pages_order(unsigned long start_pfn,
1194 					       unsigned long end_pfn)
1195 {
1196 	unsigned int order = min(count_trailing_zeros(start_pfn),
1197 				 ilog2(end_pfn - start_pfn));
1198 
1199 	/*
1200 	 * Make sure all the pages in a single preservation are in the same NUMA
1201 	 * node. The restore machinery can not cope with a preservation spanning
1202 	 * multiple NUMA nodes.
1203 	 */
1204 	while (pfn_to_nid(start_pfn) != pfn_to_nid(start_pfn + (1UL << order) - 1))
1205 		order--;
1206 
1207 	return order;
1208 }
1209 
1210 static void __kho_unpreserve(struct kho_radix_tree *tree,
1211 			     unsigned long pfn, unsigned long end_pfn)
1212 {
1213 	unsigned int order;
1214 
1215 	while (pfn < end_pfn) {
1216 		order = __kho_preserve_pages_order(pfn, end_pfn);
1217 
1218 		kho_radix_del_key(tree, kho_encode_radix_key(PFN_PHYS(pfn),
1219 							     order));
1220 
1221 		pfn += 1 << order;
1222 	}
1223 }
1224 
1225 /**
1226  * kho_preserve_pages - preserve contiguous pages across kexec
1227  * @page: first page in the list.
1228  * @nr_pages: number of pages.
1229  *
1230  * Preserve a contiguous list of order 0 pages. Must be restored using
1231  * kho_restore_pages() to ensure the pages are restored properly as order 0.
1232  *
1233  * Return: 0 on success, error code on failure
1234  */
1235 int kho_preserve_pages(struct page *page, unsigned long nr_pages)
1236 {
1237 	struct kho_radix_tree *tree = &kho_out.radix_tree;
1238 	const unsigned long start_pfn = page_to_pfn(page);
1239 	const unsigned long end_pfn = start_pfn + nr_pages;
1240 	unsigned long pfn = start_pfn;
1241 	unsigned long failed_pfn = 0;
1242 	int err = 0;
1243 
1244 	if (IS_ENABLED(CONFIG_KEXEC_HANDOVER_DEBUG) &&
1245 	    WARN_ON(kho_bootmem_overlap(start_pfn << PAGE_SHIFT,
1246 					nr_pages << PAGE_SHIFT))) {
1247 		return -EINVAL;
1248 	}
1249 
1250 	while (pfn < end_pfn) {
1251 		unsigned int order = __kho_preserve_pages_order(pfn, end_pfn);
1252 
1253 		err = kho_radix_add_key(tree, kho_encode_radix_key(PFN_PHYS(pfn),
1254 								   order));
1255 		if (err) {
1256 			failed_pfn = pfn;
1257 			break;
1258 		}
1259 
1260 		pfn += 1 << order;
1261 	}
1262 
1263 	if (err)
1264 		__kho_unpreserve(tree, start_pfn, failed_pfn);
1265 
1266 	return err;
1267 }
1268 EXPORT_SYMBOL_GPL(kho_preserve_pages);
1269 
1270 /**
1271  * kho_unpreserve_pages - unpreserve contiguous pages.
1272  * @page: first page in the list.
1273  * @nr_pages: number of pages.
1274  *
1275  * Instructs KHO to unpreserve @nr_pages contiguous pages starting from @page.
1276  * This must be called with the same @page and @nr_pages as the corresponding
1277  * kho_preserve_pages() call. Unpreserving arbitrary sub-ranges of larger
1278  * preserved blocks is not supported.
1279  */
1280 void kho_unpreserve_pages(struct page *page, unsigned long nr_pages)
1281 {
1282 	struct kho_radix_tree *tree = &kho_out.radix_tree;
1283 	const unsigned long start_pfn = page_to_pfn(page);
1284 	const unsigned long end_pfn = start_pfn + nr_pages;
1285 
1286 	__kho_unpreserve(tree, start_pfn, end_pfn);
1287 }
1288 EXPORT_SYMBOL_GPL(kho_unpreserve_pages);
1289 
1290 /* vmalloc flags KHO supports */
1291 #define KHO_VMALLOC_SUPPORTED_FLAGS	(VM_ALLOC | VM_ALLOW_HUGE_VMAP)
1292 
1293 /* KHO internal flags for vmalloc preservations */
1294 #define KHO_VMALLOC_ALLOC	0x0001
1295 #define KHO_VMALLOC_HUGE_VMAP	0x0002
1296 
1297 static unsigned short vmalloc_flags_to_kho(unsigned int vm_flags)
1298 {
1299 	unsigned short kho_flags = 0;
1300 
1301 	if (vm_flags & VM_ALLOC)
1302 		kho_flags |= KHO_VMALLOC_ALLOC;
1303 	if (vm_flags & VM_ALLOW_HUGE_VMAP)
1304 		kho_flags |= KHO_VMALLOC_HUGE_VMAP;
1305 
1306 	return kho_flags;
1307 }
1308 
1309 static unsigned int kho_flags_to_vmalloc(unsigned short kho_flags)
1310 {
1311 	unsigned int vm_flags = 0;
1312 
1313 	if (kho_flags & KHO_VMALLOC_ALLOC)
1314 		vm_flags |= VM_ALLOC;
1315 	if (kho_flags & KHO_VMALLOC_HUGE_VMAP)
1316 		vm_flags |= VM_ALLOW_HUGE_VMAP;
1317 
1318 	return vm_flags;
1319 }
1320 
1321 static struct kho_vmalloc_chunk *new_vmalloc_chunk(struct kho_vmalloc_chunk *cur)
1322 {
1323 	struct kho_vmalloc_chunk *chunk;
1324 	int err;
1325 
1326 	chunk = (struct kho_vmalloc_chunk *)get_zeroed_page(GFP_KERNEL);
1327 	if (!chunk)
1328 		return NULL;
1329 
1330 	err = kho_preserve_pages(virt_to_page(chunk), 1);
1331 	if (err)
1332 		goto err_free;
1333 	if (cur)
1334 		KHOSER_STORE_PTR(cur->hdr.next, chunk);
1335 	return chunk;
1336 
1337 err_free:
1338 	free_page((unsigned long)chunk);
1339 	return NULL;
1340 }
1341 
1342 static void kho_vmalloc_unpreserve_chunk(struct kho_vmalloc_chunk *chunk,
1343 					 unsigned short order)
1344 {
1345 	struct kho_radix_tree *tree = &kho_out.radix_tree;
1346 	unsigned long pfn = PHYS_PFN(virt_to_phys(chunk));
1347 
1348 	__kho_unpreserve(tree, pfn, pfn + 1);
1349 
1350 	for (int i = 0; i < ARRAY_SIZE(chunk->phys) && chunk->phys[i]; i++) {
1351 		pfn = PHYS_PFN(chunk->phys[i]);
1352 		__kho_unpreserve(tree, pfn, pfn + (1 << order));
1353 	}
1354 }
1355 
1356 /**
1357  * kho_preserve_vmalloc - preserve memory allocated with vmalloc() across kexec
1358  * @ptr: pointer to the area in vmalloc address space
1359  * @preservation: placeholder for preservation metadata
1360  *
1361  * Instructs KHO to preserve the area in vmalloc address space at @ptr. The
1362  * physical pages mapped at @ptr will be preserved and on successful return
1363  * @preservation will hold the physical address of a structure that describes
1364  * the preservation.
1365  *
1366  * NOTE: The memory allocated with vmalloc_node() variants cannot be reliably
1367  * restored on the same node
1368  *
1369  * Return: 0 on success, error code on failure
1370  */
1371 int kho_preserve_vmalloc(void *ptr, struct kho_vmalloc *preservation)
1372 {
1373 	struct kho_vmalloc_chunk *chunk;
1374 	struct vm_struct *vm = find_vm_area(ptr);
1375 	unsigned int order, flags, nr_contig_pages;
1376 	unsigned int idx = 0;
1377 	int err;
1378 
1379 	if (!vm)
1380 		return -EINVAL;
1381 
1382 	if (vm->flags & ~KHO_VMALLOC_SUPPORTED_FLAGS)
1383 		return -EOPNOTSUPP;
1384 
1385 	flags = vmalloc_flags_to_kho(vm->flags);
1386 	order = get_vm_area_page_order(vm);
1387 
1388 	chunk = new_vmalloc_chunk(NULL);
1389 	if (!chunk)
1390 		return -ENOMEM;
1391 	KHOSER_STORE_PTR(preservation->first, chunk);
1392 
1393 	nr_contig_pages = (1 << order);
1394 	for (int i = 0; i < vm->nr_pages; i += nr_contig_pages) {
1395 		phys_addr_t phys = page_to_phys(vm->pages[i]);
1396 
1397 		err = kho_preserve_pages(vm->pages[i], nr_contig_pages);
1398 		if (err)
1399 			goto err_free;
1400 
1401 		chunk->phys[idx++] = phys;
1402 		if (idx == ARRAY_SIZE(chunk->phys)) {
1403 			chunk = new_vmalloc_chunk(chunk);
1404 			if (!chunk) {
1405 				err = -ENOMEM;
1406 				goto err_free;
1407 			}
1408 			idx = 0;
1409 		}
1410 	}
1411 
1412 	preservation->total_pages = vm->nr_pages;
1413 	preservation->flags = flags;
1414 	preservation->order = order;
1415 
1416 	return 0;
1417 
1418 err_free:
1419 	kho_unpreserve_vmalloc(preservation);
1420 	return err;
1421 }
1422 EXPORT_SYMBOL_GPL(kho_preserve_vmalloc);
1423 
1424 /**
1425  * kho_unpreserve_vmalloc - unpreserve memory allocated with vmalloc()
1426  * @preservation: preservation metadata returned by kho_preserve_vmalloc()
1427  *
1428  * Instructs KHO to unpreserve the area in vmalloc address space that was
1429  * previously preserved with kho_preserve_vmalloc().
1430  */
1431 void kho_unpreserve_vmalloc(struct kho_vmalloc *preservation)
1432 {
1433 	struct kho_vmalloc_chunk *chunk = KHOSER_LOAD_PTR(preservation->first);
1434 
1435 	while (chunk) {
1436 		struct kho_vmalloc_chunk *tmp = chunk;
1437 
1438 		kho_vmalloc_unpreserve_chunk(chunk, preservation->order);
1439 
1440 		chunk = KHOSER_LOAD_PTR(chunk->hdr.next);
1441 		free_page((unsigned long)tmp);
1442 	}
1443 }
1444 EXPORT_SYMBOL_GPL(kho_unpreserve_vmalloc);
1445 
1446 /**
1447  * kho_restore_vmalloc - recreates and populates an area in vmalloc address
1448  * space from the preserved memory.
1449  * @preservation: preservation metadata.
1450  *
1451  * Recreates an area in vmalloc address space and populates it with memory that
1452  * was preserved using kho_preserve_vmalloc().
1453  *
1454  * Return: pointer to the area in the vmalloc address space, NULL on failure.
1455  */
1456 void *kho_restore_vmalloc(const struct kho_vmalloc *preservation)
1457 {
1458 	struct kho_vmalloc_chunk *chunk = KHOSER_LOAD_PTR(preservation->first);
1459 	kasan_vmalloc_flags_t kasan_flags = KASAN_VMALLOC_PROT_NORMAL;
1460 	unsigned int align, order, shift, vm_flags;
1461 	unsigned long total_pages, contig_pages;
1462 	unsigned long addr, size;
1463 	struct vm_struct *area;
1464 	struct page **pages;
1465 	unsigned int idx = 0;
1466 	int err;
1467 
1468 	vm_flags = kho_flags_to_vmalloc(preservation->flags);
1469 	if (vm_flags & ~KHO_VMALLOC_SUPPORTED_FLAGS)
1470 		return NULL;
1471 
1472 	total_pages = preservation->total_pages;
1473 	pages = kvmalloc_objs(*pages, total_pages);
1474 	if (!pages)
1475 		return NULL;
1476 	order = preservation->order;
1477 	contig_pages = (1 << order);
1478 	shift = PAGE_SHIFT + order;
1479 	align = 1 << shift;
1480 
1481 	while (chunk) {
1482 		struct page *page;
1483 
1484 		for (int i = 0; i < ARRAY_SIZE(chunk->phys) && chunk->phys[i]; i++) {
1485 			phys_addr_t phys = chunk->phys[i];
1486 
1487 			if (idx + contig_pages > total_pages)
1488 				goto err_free_pages_array;
1489 
1490 			page = kho_restore_pages(phys, contig_pages);
1491 			if (!page)
1492 				goto err_free_pages_array;
1493 
1494 			for (int j = 0; j < contig_pages; j++)
1495 				pages[idx++] = page + j;
1496 
1497 			phys += contig_pages * PAGE_SIZE;
1498 		}
1499 
1500 		page = kho_restore_pages(virt_to_phys(chunk), 1);
1501 		if (!page)
1502 			goto err_free_pages_array;
1503 		chunk = KHOSER_LOAD_PTR(chunk->hdr.next);
1504 		__free_page(page);
1505 	}
1506 
1507 	if (idx != total_pages)
1508 		goto err_free_pages_array;
1509 
1510 	area = __get_vm_area_node(total_pages * PAGE_SIZE, align, shift,
1511 				  vm_flags | VM_UNINITIALIZED,
1512 				  VMALLOC_START, VMALLOC_END,
1513 				  NUMA_NO_NODE, GFP_KERNEL,
1514 				  __builtin_return_address(0));
1515 	if (!area)
1516 		goto err_free_pages_array;
1517 
1518 	addr = (unsigned long)area->addr;
1519 	size = get_vm_area_size(area);
1520 	err = vmap_pages_range(addr, addr + size, PAGE_KERNEL, pages, shift);
1521 	if (err)
1522 		goto err_free_vm_area;
1523 
1524 	area->nr_pages = total_pages;
1525 	area->pages = pages;
1526 
1527 	if (vm_flags & VM_ALLOC)
1528 		kasan_flags |= KASAN_VMALLOC_VM_ALLOC;
1529 
1530 	area->addr = kasan_unpoison_vmalloc(area->addr, total_pages * PAGE_SIZE,
1531 					    kasan_flags);
1532 	clear_vm_uninitialized_flag(area);
1533 
1534 	return area->addr;
1535 
1536 err_free_vm_area:
1537 	free_vm_area(area);
1538 err_free_pages_array:
1539 	kvfree(pages);
1540 	return NULL;
1541 }
1542 EXPORT_SYMBOL_GPL(kho_restore_vmalloc);
1543 
1544 /**
1545  * kho_alloc_preserve - Allocate, zero, and preserve memory.
1546  * @size: The number of bytes to allocate.
1547  *
1548  * Allocates a physically contiguous block of zeroed pages that is large
1549  * enough to hold @size bytes. The allocated memory is then registered with
1550  * KHO for preservation across a kexec.
1551  *
1552  * Note: The actual allocated size will be rounded up to the nearest
1553  * power-of-two page boundary.
1554  *
1555  * @return A virtual pointer to the allocated and preserved memory on success,
1556  * or an ERR_PTR() encoded error on failure.
1557  */
1558 void *kho_alloc_preserve(size_t size)
1559 {
1560 	struct folio *folio;
1561 	int order, ret;
1562 
1563 	if (!size)
1564 		return ERR_PTR(-EINVAL);
1565 
1566 	order = get_order(size);
1567 	if (order > MAX_PAGE_ORDER)
1568 		return ERR_PTR(-E2BIG);
1569 
1570 	folio = folio_alloc(GFP_KERNEL | __GFP_ZERO, order);
1571 	if (!folio)
1572 		return ERR_PTR(-ENOMEM);
1573 
1574 	ret = kho_preserve_folio(folio);
1575 	if (ret) {
1576 		folio_put(folio);
1577 		return ERR_PTR(ret);
1578 	}
1579 
1580 	return folio_address(folio);
1581 }
1582 EXPORT_SYMBOL_GPL(kho_alloc_preserve);
1583 
1584 /**
1585  * kho_unpreserve_free - Unpreserve and free memory.
1586  * @mem:  Pointer to the memory allocated by kho_alloc_preserve().
1587  *
1588  * Unregisters the memory from KHO preservation and frees the underlying
1589  * pages back to the system. This function should be called to clean up
1590  * memory allocated with kho_alloc_preserve().
1591  */
1592 void kho_unpreserve_free(void *mem)
1593 {
1594 	struct folio *folio;
1595 
1596 	if (!mem)
1597 		return;
1598 
1599 	folio = virt_to_folio(mem);
1600 	kho_unpreserve_folio(folio);
1601 	folio_put(folio);
1602 }
1603 EXPORT_SYMBOL_GPL(kho_unpreserve_free);
1604 
1605 /**
1606  * kho_restore_free - Restore and free memory after kexec.
1607  * @mem:  Pointer to the memory (in the new kernel's address space)
1608  * that was allocated by the old kernel.
1609  *
1610  * This function is intended to be called in the new kernel (post-kexec)
1611  * to take ownership of and free a memory region that was preserved by the
1612  * old kernel using kho_alloc_preserve().
1613  *
1614  * It first restores the pages from KHO (using their physical address)
1615  * and then frees the pages back to the new kernel's page allocator.
1616  */
1617 void kho_restore_free(void *mem)
1618 {
1619 	struct folio *folio;
1620 
1621 	if (!mem)
1622 		return;
1623 
1624 	folio = kho_restore_folio(__pa(mem));
1625 	if (!WARN_ON(!folio))
1626 		folio_put(folio);
1627 }
1628 EXPORT_SYMBOL_GPL(kho_restore_free);
1629 
1630 /**
1631  * is_kho_boot - check if current kernel was booted via KHO-enabled
1632  * kexec
1633  *
1634  * This function checks if the current kernel was loaded through a kexec
1635  * operation with KHO enabled, by verifying that a valid KHO FDT
1636  * was passed.
1637  *
1638  * Note: This function returns reliable results only after
1639  * kho_populate() has been called during early boot. Before that,
1640  * it may return false even if KHO data is present.
1641  *
1642  * Return: true if booted via KHO-enabled kexec, false otherwise
1643  */
1644 bool is_kho_boot(void)
1645 {
1646 	return !!kho_in.fdt_phys;
1647 }
1648 EXPORT_SYMBOL_GPL(is_kho_boot);
1649 
1650 /**
1651  * kho_retrieve_subtree - retrieve a preserved sub blob by its name.
1652  * @name: the name of the sub blob passed to kho_add_subtree().
1653  * @phys: if found, the physical address of the sub blob is stored in @phys.
1654  * @size: if not NULL and found, the size of the sub blob is stored in @size.
1655  *
1656  * Retrieve a preserved sub blob named @name and store its physical
1657  * address in @phys and optionally its size in @size.
1658  *
1659  * Return: 0 on success, error code on failure
1660  */
1661 int kho_retrieve_subtree(const char *name, phys_addr_t *phys, size_t *size)
1662 {
1663 	const void *fdt = kho_get_fdt();
1664 	const u64 *val;
1665 	int offset, len;
1666 
1667 	if (!fdt)
1668 		return -ENOENT;
1669 
1670 	if (!phys)
1671 		return -EINVAL;
1672 
1673 	offset = fdt_subnode_offset(fdt, 0, name);
1674 	if (offset < 0)
1675 		return -ENOENT;
1676 
1677 	val = fdt_getprop(fdt, offset, KHO_SUB_TREE_PROP_NAME, &len);
1678 	if (!val || len != sizeof(*val))
1679 		return -EINVAL;
1680 
1681 	*phys = (phys_addr_t)*val;
1682 
1683 	val = fdt_getprop(fdt, offset, KHO_SUB_TREE_SIZE_PROP_NAME, &len);
1684 	if (!val || len != sizeof(*val)) {
1685 		pr_warn("broken KHO subnode '%s': missing or invalid blob-size property\n",
1686 			name);
1687 		return -EINVAL;
1688 	}
1689 
1690 	if (size)
1691 		*size = (size_t)*val;
1692 
1693 	return 0;
1694 }
1695 EXPORT_SYMBOL_GPL(kho_retrieve_subtree);
1696 
1697 static void __init kho_mem_retrieve(void)
1698 {
1699 	const struct kho_radix_walk_cb cb = {
1700 		.leaf = kho_preserved_memory_reserve,
1701 	};
1702 
1703 	if (kho_radix_walk_tree(&kho_in.radix_tree, &cb, NULL))
1704 		goto err;
1705 
1706 	return;
1707 
1708 err:
1709 	/*
1710 	 * Failed to initialize preserved memory. Clear FDT and radix so KHO
1711 	 * users don't treat it as a KHO boot.
1712 	 */
1713 	kho_in.fdt_phys = 0;
1714 	kho_in.radix_tree.root = NULL;
1715 }
1716 
1717 static __init int kho_out_fdt_setup(void)
1718 {
1719 	struct kho_radix_tree *tree = &kho_out.radix_tree;
1720 	void *root = kho_out.fdt;
1721 	u64 preserved_mem_tree_pa;
1722 	int err;
1723 
1724 	err = fdt_create(root, PAGE_SIZE);
1725 	err |= fdt_finish_reservemap(root);
1726 	err |= fdt_begin_node(root, "");
1727 	err |= fdt_property_string(root, "compatible", KHO_FDT_COMPATIBLE);
1728 
1729 	preserved_mem_tree_pa = virt_to_phys(tree->root);
1730 
1731 	err |= fdt_property(root, KHO_FDT_MEMORY_MAP_PROP_NAME,
1732 			    &preserved_mem_tree_pa,
1733 			    sizeof(preserved_mem_tree_pa));
1734 
1735 	err |= fdt_end_node(root);
1736 	err |= fdt_finish(root);
1737 
1738 	return err;
1739 }
1740 
1741 static void __init kho_in_kexec_metadata(void)
1742 {
1743 	struct kho_kexec_metadata *metadata;
1744 	phys_addr_t metadata_phys;
1745 	size_t blob_size;
1746 	int err;
1747 
1748 	err = kho_retrieve_subtree(KHO_METADATA_NODE_NAME, &metadata_phys,
1749 				   &blob_size);
1750 	if (err)
1751 		/* This is fine, previous kernel didn't export metadata */
1752 		return;
1753 
1754 	/* Check that, at least, "version" is present */
1755 	if (blob_size < sizeof(u32)) {
1756 		pr_warn("kexec-metadata blob too small (%zu bytes)\n",
1757 			blob_size);
1758 		return;
1759 	}
1760 
1761 	metadata = phys_to_virt(metadata_phys);
1762 
1763 	if (metadata->version != KHO_KEXEC_METADATA_VERSION) {
1764 		pr_warn("kexec-metadata version %u not supported (expected %u)\n",
1765 			metadata->version, KHO_KEXEC_METADATA_VERSION);
1766 		return;
1767 	}
1768 
1769 	if (blob_size < sizeof(*metadata)) {
1770 		pr_warn("kexec-metadata blob too small for v%u (%zu < %zu)\n",
1771 			metadata->version, blob_size, sizeof(*metadata));
1772 		return;
1773 	}
1774 
1775 	/*
1776 	 * Copy data to the kernel structure that will persist during
1777 	 * kernel lifetime.
1778 	 */
1779 	kho_in.kexec_count = metadata->kexec_count;
1780 	strscpy(kho_in.previous_release, metadata->previous_release,
1781 		sizeof(kho_in.previous_release));
1782 
1783 	pr_info("exec from: %s (count %u)\n",
1784 		kho_in.previous_release, kho_in.kexec_count);
1785 }
1786 
1787 /*
1788  * Create kexec metadata to pass kernel version and boot count to the
1789  * next kernel. This keeps the core KHO ABI minimal and allows the
1790  * metadata format to evolve independently.
1791  */
1792 static __init int kho_out_kexec_metadata(void)
1793 {
1794 	struct kho_kexec_metadata *metadata;
1795 	int err;
1796 
1797 	metadata = kho_alloc_preserve(sizeof(*metadata));
1798 	if (IS_ERR(metadata))
1799 		return PTR_ERR(metadata);
1800 
1801 	metadata->version = KHO_KEXEC_METADATA_VERSION;
1802 	strscpy(metadata->previous_release, init_uts_ns.name.release,
1803 		sizeof(metadata->previous_release));
1804 	/* kho_in.kexec_count is set to 0 on cold boot */
1805 	metadata->kexec_count = kho_in.kexec_count + 1;
1806 
1807 	err = kho_add_subtree(KHO_METADATA_NODE_NAME, metadata,
1808 			      sizeof(*metadata));
1809 	if (err)
1810 		kho_unpreserve_free(metadata);
1811 
1812 	return err;
1813 }
1814 
1815 static int __init kho_kexec_metadata_init(const void *fdt)
1816 {
1817 	int err;
1818 
1819 	if (fdt)
1820 		kho_in_kexec_metadata();
1821 
1822 	/* Populate kexec metadata for the possible next kexec */
1823 	err = kho_out_kexec_metadata();
1824 	if (err)
1825 		pr_warn("failed to initialize kexec-metadata subtree: %d\n",
1826 			err);
1827 
1828 	return err;
1829 }
1830 
1831 static __init int kho_init(void)
1832 {
1833 	struct kho_radix_tree *tree = &kho_out.radix_tree;
1834 	const void *fdt = kho_get_fdt();
1835 	int err = 0;
1836 
1837 	if (!kho_enable)
1838 		return 0;
1839 
1840 	err = kho_radix_init_tree(tree, NULL);
1841 	if (err)
1842 		goto err_free_bootmem;
1843 
1844 	kho_out.fdt = kho_alloc_preserve(PAGE_SIZE);
1845 	if (IS_ERR(kho_out.fdt)) {
1846 		err = PTR_ERR(kho_out.fdt);
1847 		goto err_free_kho_radix_tree;
1848 	}
1849 
1850 	err = kho_debugfs_init();
1851 	if (err)
1852 		goto err_free_fdt;
1853 
1854 	err = kho_out_debugfs_init(&kho_out.dbg);
1855 	if (err)
1856 		goto err_free_fdt;
1857 
1858 	err = kho_out_fdt_setup();
1859 	if (err)
1860 		goto err_free_fdt;
1861 
1862 	err = kho_kexec_metadata_init(fdt);
1863 	if (err)
1864 		goto err_free_fdt;
1865 
1866 	if (fdt) {
1867 		kho_in_debugfs_init(&kho_in.dbg, fdt);
1868 		return 0;
1869 	}
1870 
1871 	for (int i = 0; i < kho_bootmem_cnt; i++) {
1872 		unsigned long base_pfn = PHYS_PFN(kho_bootmem[i].addr);
1873 		unsigned long count = kho_bootmem[i].size >> PAGE_SHIFT;
1874 		unsigned long pfn;
1875 
1876 		/*
1877 		 * When debug_pagealloc is enabled, __free_pages() clears the
1878 		 * corresponding PRESENT bit in the kernel page table.
1879 		 * Subsequent kmemleak scans of these pages cause the
1880 		 * non-PRESENT page faults.
1881 		 * Mark bootmem areas with kmemleak_ignore_phys() to exclude
1882 		 * them from kmemleak scanning.
1883 		 */
1884 		kmemleak_ignore_phys(kho_bootmem[i].addr);
1885 		for (pfn = base_pfn; pfn < base_pfn + count;
1886 		     pfn += pageblock_nr_pages)
1887 			init_cma_reserved_pageblock(pfn_to_page(pfn));
1888 	}
1889 
1890 	WARN_ON_ONCE(kho_debugfs_blob_add(&kho_out.dbg, "fdt",
1891 					  kho_out.fdt,
1892 					  fdt_totalsize(kho_out.fdt), true));
1893 
1894 	return 0;
1895 
1896 err_free_fdt:
1897 	kho_unpreserve_free(kho_out.fdt);
1898 err_free_kho_radix_tree:
1899 	kho_radix_destroy_tree(tree);
1900 err_free_bootmem:
1901 	kho_out.fdt = NULL;
1902 	for (int i = 0; i < kho_bootmem_cnt; i++) {
1903 		void *start = __va(kho_bootmem[i].addr);
1904 		void *end = start + kho_bootmem[i].size;
1905 
1906 		free_reserved_area(start, end, -1, "");
1907 	}
1908 	kho_enable = false;
1909 	return err;
1910 }
1911 fs_initcall(kho_init);
1912 
1913 void __init kho_memory_init_early(void)
1914 {
1915 	const void *fdt = kho_get_fdt();
1916 	void *mem_map;
1917 
1918 	if (!is_kho_boot())
1919 		return;
1920 
1921 	/*
1922 	 * kho_get_mem_map() should always succeed. If it fails, kho_populate()
1923 	 * catches that and never sets kho_in.bootmem_phys, which stops memory
1924 	 * retrieval.
1925 	 */
1926 	mem_map = kho_get_mem_map(fdt);
1927 	if (WARN_ON(!mem_map))
1928 		goto err;
1929 
1930 	/*
1931 	 * kho_bootmem_overlap() needs kho_bootmem to be initialized. It is used
1932 	 * by free_area_init() on KHO boots, so initialize it early.
1933 	 */
1934 	kho_bootmem = phys_to_virt(kho_in.bootmem_phys);
1935 
1936 	if (kho_radix_init_tree(&kho_in.radix_tree, mem_map))
1937 		goto err;
1938 
1939 	kho_discover_noprsrv();
1940 
1941 	return;
1942 
1943 err:
1944 	/*
1945 	 * Failed to initialize preserved memory radix tree. Clear FDT
1946 	 * and bootmem so KHO users don't treat it as a KHO boot.
1947 	 */
1948 	kho_in.fdt_phys = 0;
1949 	kho_in.bootmem_phys = 0;
1950 }
1951 
1952 void __init kho_memory_init(void)
1953 {
1954 	if (is_kdump_kernel()) {
1955 		kho_enable = false;
1956 		pr_info("disabled in the kdump kernel\n");
1957 		return;
1958 	}
1959 
1960 	if (kho_in.bootmem_phys)
1961 		kho_mem_retrieve();
1962 	else
1963 		kho_reserve_bootmem();
1964 }
1965 
1966 void __init kho_populate(phys_addr_t fdt_phys, u64 fdt_len,
1967 			 phys_addr_t bootmem_phys, u64 bootmem_len)
1968 {
1969 	unsigned int bootmem_cnt = bootmem_len / sizeof(*kho_bootmem);
1970 	struct kho_bootmem *bootmem = NULL;
1971 	phys_addr_t mem_map_phys;
1972 	void *fdt = NULL;
1973 	bool populated = false;
1974 	int err;
1975 
1976 	/* Validate the input FDT */
1977 	fdt = early_memremap(fdt_phys, fdt_len);
1978 	if (!fdt) {
1979 		pr_warn("setup: failed to memremap FDT (0x%llx)\n", fdt_phys);
1980 		goto report;
1981 	}
1982 	err = fdt_check_header(fdt);
1983 	if (err) {
1984 		pr_warn("setup: handover FDT (0x%llx) is invalid: %d\n",
1985 			fdt_phys, err);
1986 		goto unmap_fdt;
1987 	}
1988 	err = fdt_node_check_compatible(fdt, 0, KHO_FDT_COMPATIBLE);
1989 	if (err) {
1990 		pr_warn("setup: handover FDT (0x%llx) is incompatible with '%s': %d\n",
1991 			fdt_phys, KHO_FDT_COMPATIBLE, err);
1992 		goto unmap_fdt;
1993 	}
1994 
1995 	mem_map_phys = kho_get_mem_map_phys(fdt);
1996 	if (!mem_map_phys)
1997 		goto unmap_fdt;
1998 
1999 	bootmem = early_memremap(bootmem_phys, bootmem_len);
2000 	if (!bootmem) {
2001 		pr_warn("setup: failed to memremap bootmem (phys=0x%llx, len=%lld)\n",
2002 			bootmem_phys, bootmem_len);
2003 		goto unmap_fdt;
2004 	}
2005 
2006 	/*
2007 	 * We pass a safe contiguous blocks of memory with no preservations to
2008 	 * use for early boot purporses from the previous kernel so that we can
2009 	 * resize the memblock array as needed.
2010 	 */
2011 	for (int i = 0; i < bootmem_cnt; i++) {
2012 		struct kho_bootmem *area = &bootmem[i];
2013 		u64 size = area->size;
2014 
2015 		memblock_add(area->addr, size);
2016 		err = memblock_mark_kho_noprsrv(area->addr, size);
2017 		if (err) {
2018 			pr_warn("failed to mark the bootmem region 0x%pa+0x%pa: %pe",
2019 				&area->addr, &size, ERR_PTR(err));
2020 			goto unmap_bootmem;
2021 		}
2022 		pr_debug("Marked 0x%pa+0x%pa as bootmem", &area->addr, &size);
2023 	}
2024 
2025 	memblock_reserve(bootmem_phys, bootmem_len);
2026 
2027 	/*
2028 	 * Now that we have a viable region of boot memory, let's tell
2029 	 * the memblocks allocator to only use that for any allocations.
2030 	 * That way we ensure that nothing scribbles over in use data while
2031 	 * we initialize the page tables which we will need to ingest all
2032 	 * memory reservations from the previous kernel.
2033 	 */
2034 	memblock_set_kho_noprsrv_only();
2035 
2036 	kho_in.fdt_phys = fdt_phys;
2037 	kho_in.bootmem_phys = bootmem_phys;
2038 	kho_bootmem_cnt = bootmem_cnt;
2039 
2040 	populated = true;
2041 	pr_info("found kexec handover data.\n");
2042 
2043 unmap_bootmem:
2044 	early_memunmap(bootmem, bootmem_len);
2045 unmap_fdt:
2046 	early_memunmap(fdt, fdt_len);
2047 report:
2048 	if (!populated)
2049 		pr_warn("disabling KHO revival\n");
2050 }
2051 
2052 /* Helper functions for kexec_file_load */
2053 
2054 int kho_fill_kimage(struct kimage *image)
2055 {
2056 	ssize_t bootmem_size;
2057 	int err = 0;
2058 	struct kexec_buf bootmem;
2059 
2060 	if (!kho_enable || image->type == KEXEC_TYPE_CRASH)
2061 		return 0;
2062 
2063 	image->kho.fdt = virt_to_phys(kho_out.fdt);
2064 
2065 	bootmem_size = sizeof(*kho_bootmem) * kho_bootmem_cnt;
2066 	bootmem = (struct kexec_buf){
2067 		.image = image,
2068 		.buffer = kho_bootmem,
2069 		.bufsz = bootmem_size,
2070 		.mem = KEXEC_BUF_MEM_UNKNOWN,
2071 		.memsz = bootmem_size,
2072 		.buf_align = SZ_64K, /* Makes it easier to map */
2073 		.buf_max = ULONG_MAX,
2074 		.top_down = true,
2075 	};
2076 	err = kexec_add_buffer(&bootmem);
2077 	if (err)
2078 		return err;
2079 	image->kho.bootmem = &image->segment[image->nr_segments - 1];
2080 
2081 	return 0;
2082 }
2083 
2084 static int kho_walk_bootmem(struct kexec_buf *kbuf,
2085 			    int (*func)(struct resource *, void *))
2086 {
2087 	int ret = 0;
2088 	int i;
2089 
2090 	for (i = 0; i < kho_bootmem_cnt; i++) {
2091 		struct resource res = {
2092 			.start = kho_bootmem[i].addr,
2093 			.end = kho_bootmem[i].addr + kho_bootmem[i].size - 1,
2094 		};
2095 
2096 		/* Try to fit the kimage into our KHO bootmem region */
2097 		ret = func(&res, kbuf);
2098 		if (ret)
2099 			break;
2100 	}
2101 
2102 	return ret;
2103 }
2104 
2105 int kho_locate_mem_hole(struct kexec_buf *kbuf,
2106 			int (*func)(struct resource *, void *))
2107 {
2108 	int ret;
2109 
2110 	if (!kho_enable || kbuf->image->type == KEXEC_TYPE_CRASH)
2111 		return 1;
2112 
2113 	ret = kho_walk_bootmem(kbuf, func);
2114 
2115 	return ret == 1 ? 0 : -EADDRNOTAVAIL;
2116 }
2117