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