xref: /linux/kernel/liveupdate/kexec_handover.c (revision 0e39380a7316122e1b00012b3f3cd3e318b3e7d3)
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 /*
463  * With CONFIG_DEFERRED_STRUCT_PAGE_INIT, struct pages in higher memory regions
464  * may not be initialized yet at the time KHO deserializes preserved memory.
465  * KHO uses the struct page to store metadata and a later initialization would
466  * overwrite it.
467  * Ensure all the struct pages in the preservation are
468  * initialized. kho_preserved_memory_reserve() marks the reservation as noinit
469  * to make sure they don't get re-initialized later.
470  */
471 static struct page *__init kho_get_preserved_page(phys_addr_t phys,
472 						  unsigned int order)
473 {
474 	unsigned long pfn = PHYS_PFN(phys);
475 	int nid;
476 
477 	if (!IS_ENABLED(CONFIG_DEFERRED_STRUCT_PAGE_INIT))
478 		return pfn_to_page(pfn);
479 
480 	nid = early_pfn_to_nid(pfn);
481 	for (unsigned long i = 0; i < (1UL << order); i++)
482 		init_deferred_page(pfn + i, nid);
483 
484 	return pfn_to_page(pfn);
485 }
486 
487 static int __init kho_preserved_memory_reserve(phys_addr_t phys,
488 					       unsigned int order)
489 {
490 	union kho_page_info info;
491 	struct page *page;
492 	u64 sz;
493 
494 	sz = 1 << (order + PAGE_SHIFT);
495 	page = kho_get_preserved_page(phys, order);
496 
497 	/* Reserve the memory preserved in KHO in memblock */
498 	memblock_reserve(phys, sz);
499 	memblock_reserved_mark_noinit(phys, sz);
500 	info.magic = KHO_PAGE_MAGIC;
501 	info.order = order;
502 	page->private = info.page_private;
503 
504 	return 0;
505 }
506 
507 /* Returns physical address of the preserved memory map from FDT */
508 static phys_addr_t __init kho_get_mem_map_phys(const void *fdt)
509 {
510 	const void *mem_ptr;
511 	int len;
512 
513 	mem_ptr = fdt_getprop(fdt, 0, KHO_FDT_MEMORY_MAP_PROP_NAME, &len);
514 	if (!mem_ptr || len != sizeof(u64)) {
515 		pr_err("failed to get preserved memory map\n");
516 		return 0;
517 	}
518 
519 	return get_unaligned((const u64 *)mem_ptr);
520 }
521 
522 /*
523  * With KHO enabled, memory can become fragmented because KHO regions may
524  * be anywhere in physical address space. The scratch regions give us a
525  * safe zones that we will never see KHO allocations from. This is where we
526  * can later safely load our new kexec images into and then use the scratch
527  * area for early allocations that happen before page allocator is
528  * initialized.
529  */
530 struct kho_scratch *kho_scratch;
531 unsigned int kho_scratch_cnt;
532 
533 /*
534  * The scratch areas are scaled by default as percent of memory allocated from
535  * memblock. A user can override the scale with command line parameter:
536  *
537  * kho_scratch=N%
538  *
539  * It is also possible to explicitly define size for a lowmem, a global and
540  * per-node scratch areas:
541  *
542  * kho_scratch=l[KMG],n[KMG],m[KMG]
543  *
544  * The explicit size definition takes precedence over scale definition.
545  */
546 static unsigned int scratch_scale __initdata = 200;
547 static phys_addr_t scratch_size_global __initdata;
548 static phys_addr_t scratch_size_pernode __initdata;
549 static phys_addr_t scratch_size_lowmem __initdata;
550 
551 static int __init kho_parse_scratch_size(char *p)
552 {
553 	size_t len;
554 	unsigned long sizes[3];
555 	size_t total_size = 0;
556 	int i;
557 
558 	if (!p)
559 		return -EINVAL;
560 
561 	len = strlen(p);
562 	if (!len)
563 		return -EINVAL;
564 
565 	/* parse nn% */
566 	if (p[len - 1] == '%') {
567 		/* unsigned int max is 4,294,967,295, 10 chars */
568 		char s_scale[11] = {};
569 		int ret = 0;
570 
571 		if (len > ARRAY_SIZE(s_scale))
572 			return -EINVAL;
573 
574 		memcpy(s_scale, p, len - 1);
575 		ret = kstrtouint(s_scale, 10, &scratch_scale);
576 		if (!ret)
577 			pr_notice("scratch scale is %d%%\n", scratch_scale);
578 		return ret;
579 	}
580 
581 	/* parse ll[KMG],mm[KMG],nn[KMG] */
582 	for (i = 0; i < ARRAY_SIZE(sizes); i++) {
583 		char *endp = p;
584 
585 		if (i > 0) {
586 			if (*p != ',')
587 				return -EINVAL;
588 			p += 1;
589 		}
590 
591 		sizes[i] = memparse(p, &endp);
592 		if (endp == p)
593 			return -EINVAL;
594 		p = endp;
595 		total_size += sizes[i];
596 	}
597 
598 	if (!total_size)
599 		return -EINVAL;
600 
601 	/* The string should be fully consumed by now. */
602 	if (*p)
603 		return -EINVAL;
604 
605 	scratch_size_lowmem = sizes[0];
606 	scratch_size_global = sizes[1];
607 	scratch_size_pernode = sizes[2];
608 	scratch_scale = 0;
609 
610 	pr_notice("scratch areas: lowmem: %lluMiB global: %lluMiB pernode: %lldMiB\n",
611 		  (u64)(scratch_size_lowmem >> 20),
612 		  (u64)(scratch_size_global >> 20),
613 		  (u64)(scratch_size_pernode >> 20));
614 
615 	return 0;
616 }
617 early_param("kho_scratch", kho_parse_scratch_size);
618 
619 static void __init scratch_size_update(void)
620 {
621 	/*
622 	 * If fixed sizes are not provided via command line, calculate them
623 	 * now.
624 	 */
625 	if (scratch_scale) {
626 		phys_addr_t size;
627 
628 		size = memblock_reserved_kern_size(ARCH_LOW_ADDRESS_LIMIT,
629 						   NUMA_NO_NODE);
630 		size = size * scratch_scale / 100;
631 		scratch_size_lowmem = size;
632 
633 		size = memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE,
634 						   NUMA_NO_NODE);
635 		size = size * scratch_scale / 100 - scratch_size_lowmem;
636 		scratch_size_global = size;
637 	}
638 
639 	/*
640 	 * Scratch areas are released as MIGRATE_CMA. Round them up to the right
641 	 * size.
642 	 */
643 	scratch_size_lowmem = round_up(scratch_size_lowmem, CMA_MIN_ALIGNMENT_BYTES);
644 	scratch_size_global = round_up(scratch_size_global, CMA_MIN_ALIGNMENT_BYTES);
645 }
646 
647 static phys_addr_t __init scratch_size_node(int nid)
648 {
649 	phys_addr_t size;
650 
651 	if (scratch_scale) {
652 		size = memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE,
653 						   nid);
654 		size = size * scratch_scale / 100;
655 	} else {
656 		size = scratch_size_pernode;
657 	}
658 
659 	return round_up(size, CMA_MIN_ALIGNMENT_BYTES);
660 }
661 
662 /**
663  * kho_reserve_scratch - Reserve a contiguous chunk of memory for kexec
664  *
665  * With KHO we can preserve arbitrary pages in the system. To ensure we still
666  * have a large contiguous region of memory when we search the physical address
667  * space for target memory, let's make sure we always have a large CMA region
668  * active. This CMA region will only be used for movable pages which are not a
669  * problem for us during KHO because we can just move them somewhere else.
670  */
671 static void __init kho_reserve_scratch(void)
672 {
673 	phys_addr_t addr, size;
674 	int nid, i = 0;
675 
676 	if (!kho_enable)
677 		return;
678 
679 	scratch_size_update();
680 
681 	/* FIXME: deal with node hot-plug/remove */
682 	kho_scratch_cnt = nodes_weight(node_states[N_MEMORY]) + 2;
683 	size = kho_scratch_cnt * sizeof(*kho_scratch);
684 	kho_scratch = memblock_alloc(size, PAGE_SIZE);
685 	if (!kho_scratch) {
686 		pr_err("Failed to reserve scratch array\n");
687 		goto err_disable_kho;
688 	}
689 
690 	/*
691 	 * reserve scratch area in low memory for lowmem allocations in the
692 	 * next kernel
693 	 */
694 	size = scratch_size_lowmem;
695 	addr = memblock_phys_alloc_range(size, CMA_MIN_ALIGNMENT_BYTES, 0,
696 					 ARCH_LOW_ADDRESS_LIMIT);
697 	if (!addr) {
698 		pr_err("Failed to reserve lowmem scratch buffer\n");
699 		goto err_free_scratch_desc;
700 	}
701 
702 	kho_scratch[i].addr = addr;
703 	kho_scratch[i].size = size;
704 	i++;
705 
706 	/* reserve large contiguous area for allocations without nid */
707 	size = scratch_size_global;
708 	addr = memblock_phys_alloc(size, CMA_MIN_ALIGNMENT_BYTES);
709 	if (!addr) {
710 		pr_err("Failed to reserve global scratch buffer\n");
711 		goto err_free_scratch_areas;
712 	}
713 
714 	kho_scratch[i].addr = addr;
715 	kho_scratch[i].size = size;
716 	i++;
717 
718 	/*
719 	 * Loop over nodes that have both memory and are online. Skip
720 	 * memoryless nodes, as we can not allocate scratch areas there.
721 	 */
722 	for_each_node_state(nid, N_MEMORY) {
723 		size = scratch_size_node(nid);
724 		addr = memblock_alloc_range_nid(size, CMA_MIN_ALIGNMENT_BYTES,
725 						0, MEMBLOCK_ALLOC_ACCESSIBLE,
726 						nid, true);
727 		if (!addr) {
728 			pr_err("Failed to reserve nid %d scratch buffer\n", nid);
729 			goto err_free_scratch_areas;
730 		}
731 
732 		kho_scratch[i].addr = addr;
733 		kho_scratch[i].size = size;
734 		i++;
735 	}
736 
737 	return;
738 
739 err_free_scratch_areas:
740 	for (i--; i >= 0; i--)
741 		memblock_phys_free(kho_scratch[i].addr, kho_scratch[i].size);
742 err_free_scratch_desc:
743 	memblock_free(kho_scratch, kho_scratch_cnt * sizeof(*kho_scratch));
744 err_disable_kho:
745 	pr_warn("Failed to reserve scratch area, disabling kexec handover\n");
746 	kho_enable = false;
747 }
748 
749 /**
750  * kho_add_subtree - record the physical address of a sub blob in KHO root tree.
751  * @name: name of the sub tree.
752  * @blob: the sub tree blob.
753  * @size: size of the blob in bytes.
754  *
755  * Creates a new child node named @name in KHO root FDT and records
756  * the physical address of @blob. The pages of @blob must also be preserved
757  * by KHO for the new kernel to retrieve it after kexec.
758  *
759  * A debugfs blob entry is also created at
760  * ``/sys/kernel/debug/kho/out/sub_fdts/@name`` when kernel is configured with
761  * CONFIG_KEXEC_HANDOVER_DEBUGFS
762  *
763  * Return: 0 on success, error code on failure
764  */
765 int kho_add_subtree(const char *name, void *blob, size_t size)
766 {
767 	phys_addr_t phys = virt_to_phys(blob);
768 	void *root_fdt = kho_out.fdt;
769 	u64 size_u64 = size;
770 	int err = -ENOMEM;
771 	int off, fdt_err;
772 
773 	guard(mutex)(&kho_out.lock);
774 
775 	fdt_err = fdt_open_into(root_fdt, root_fdt, PAGE_SIZE);
776 	if (fdt_err < 0)
777 		return err;
778 
779 	off = fdt_add_subnode(root_fdt, 0, name);
780 	if (off < 0) {
781 		if (off == -FDT_ERR_EXISTS)
782 			err = -EEXIST;
783 		goto out_pack;
784 	}
785 
786 	fdt_err = fdt_setprop(root_fdt, off, KHO_SUB_TREE_PROP_NAME,
787 			      &phys, sizeof(phys));
788 	if (fdt_err < 0)
789 		goto out_del_node;
790 
791 	fdt_err = fdt_setprop(root_fdt, off, KHO_SUB_TREE_SIZE_PROP_NAME,
792 			      &size_u64, sizeof(size_u64));
793 	if (fdt_err < 0)
794 		goto out_del_node;
795 
796 	WARN_ON_ONCE(kho_debugfs_blob_add(&kho_out.dbg, name, blob,
797 					  size, false));
798 
799 	err = 0;
800 	goto out_pack;
801 
802 out_del_node:
803 	fdt_del_node(root_fdt, off);
804 out_pack:
805 	fdt_pack(root_fdt);
806 
807 	return err;
808 }
809 EXPORT_SYMBOL_GPL(kho_add_subtree);
810 
811 void kho_remove_subtree(void *blob)
812 {
813 	phys_addr_t target_phys = virt_to_phys(blob);
814 	void *root_fdt = kho_out.fdt;
815 	int off;
816 	int err;
817 
818 	guard(mutex)(&kho_out.lock);
819 
820 	err = fdt_open_into(root_fdt, root_fdt, PAGE_SIZE);
821 	if (err < 0)
822 		return;
823 
824 	for (off = fdt_first_subnode(root_fdt, 0); off >= 0;
825 	     off = fdt_next_subnode(root_fdt, off)) {
826 		const u64 *val;
827 		int len;
828 
829 		val = fdt_getprop(root_fdt, off, KHO_SUB_TREE_PROP_NAME, &len);
830 		if (!val || len != sizeof(phys_addr_t))
831 			continue;
832 
833 		if ((phys_addr_t)*val == target_phys) {
834 			fdt_del_node(root_fdt, off);
835 			kho_debugfs_blob_remove(&kho_out.dbg, blob);
836 			break;
837 		}
838 	}
839 
840 	fdt_pack(root_fdt);
841 }
842 EXPORT_SYMBOL_GPL(kho_remove_subtree);
843 
844 /**
845  * kho_preserve_folio - preserve a folio across kexec.
846  * @folio: folio to preserve.
847  *
848  * Instructs KHO to preserve the whole folio across kexec. The order
849  * will be preserved as well.
850  *
851  * Return: 0 on success, error code on failure
852  */
853 int kho_preserve_folio(struct folio *folio)
854 {
855 	struct kho_radix_tree *tree = &kho_out.radix_tree;
856 	const unsigned long pfn = folio_pfn(folio);
857 	const unsigned int order = folio_order(folio);
858 
859 	if (WARN_ON(kho_scratch_overlap(pfn << PAGE_SHIFT, PAGE_SIZE << order)))
860 		return -EINVAL;
861 
862 	return kho_radix_add_page(tree, pfn, order);
863 }
864 EXPORT_SYMBOL_GPL(kho_preserve_folio);
865 
866 /**
867  * kho_unpreserve_folio - unpreserve a folio.
868  * @folio: folio to unpreserve.
869  *
870  * Instructs KHO to unpreserve a folio that was preserved by
871  * kho_preserve_folio() before. The provided @folio (pfn and order)
872  * must exactly match a previously preserved folio.
873  */
874 void kho_unpreserve_folio(struct folio *folio)
875 {
876 	struct kho_radix_tree *tree = &kho_out.radix_tree;
877 	const unsigned long pfn = folio_pfn(folio);
878 	const unsigned int order = folio_order(folio);
879 
880 	kho_radix_del_page(tree, pfn, order);
881 }
882 EXPORT_SYMBOL_GPL(kho_unpreserve_folio);
883 
884 static unsigned int __kho_preserve_pages_order(unsigned long start_pfn,
885 					       unsigned long end_pfn)
886 {
887 	unsigned int order = min(count_trailing_zeros(start_pfn),
888 				 ilog2(end_pfn - start_pfn));
889 
890 	/*
891 	 * Make sure all the pages in a single preservation are in the same NUMA
892 	 * node. The restore machinery can not cope with a preservation spanning
893 	 * multiple NUMA nodes.
894 	 */
895 	while (pfn_to_nid(start_pfn) != pfn_to_nid(start_pfn + (1UL << order) - 1))
896 		order--;
897 
898 	return order;
899 }
900 
901 static void __kho_unpreserve(struct kho_radix_tree *tree,
902 			     unsigned long pfn, unsigned long end_pfn)
903 {
904 	unsigned int order;
905 
906 	while (pfn < end_pfn) {
907 		order = __kho_preserve_pages_order(pfn, end_pfn);
908 
909 		kho_radix_del_page(tree, pfn, order);
910 
911 		pfn += 1 << order;
912 	}
913 }
914 
915 /**
916  * kho_preserve_pages - preserve contiguous pages across kexec
917  * @page: first page in the list.
918  * @nr_pages: number of pages.
919  *
920  * Preserve a contiguous list of order 0 pages. Must be restored using
921  * kho_restore_pages() to ensure the pages are restored properly as order 0.
922  *
923  * Return: 0 on success, error code on failure
924  */
925 int kho_preserve_pages(struct page *page, unsigned long nr_pages)
926 {
927 	struct kho_radix_tree *tree = &kho_out.radix_tree;
928 	const unsigned long start_pfn = page_to_pfn(page);
929 	const unsigned long end_pfn = start_pfn + nr_pages;
930 	unsigned long pfn = start_pfn;
931 	unsigned long failed_pfn = 0;
932 	int err = 0;
933 
934 	if (WARN_ON(kho_scratch_overlap(start_pfn << PAGE_SHIFT,
935 					nr_pages << PAGE_SHIFT))) {
936 		return -EINVAL;
937 	}
938 
939 	while (pfn < end_pfn) {
940 		unsigned int order = __kho_preserve_pages_order(pfn, end_pfn);
941 
942 		err = kho_radix_add_page(tree, pfn, order);
943 		if (err) {
944 			failed_pfn = pfn;
945 			break;
946 		}
947 
948 		pfn += 1 << order;
949 	}
950 
951 	if (err)
952 		__kho_unpreserve(tree, start_pfn, failed_pfn);
953 
954 	return err;
955 }
956 EXPORT_SYMBOL_GPL(kho_preserve_pages);
957 
958 /**
959  * kho_unpreserve_pages - unpreserve contiguous pages.
960  * @page: first page in the list.
961  * @nr_pages: number of pages.
962  *
963  * Instructs KHO to unpreserve @nr_pages contiguous pages starting from @page.
964  * This must be called with the same @page and @nr_pages as the corresponding
965  * kho_preserve_pages() call. Unpreserving arbitrary sub-ranges of larger
966  * preserved blocks is not supported.
967  */
968 void kho_unpreserve_pages(struct page *page, unsigned long nr_pages)
969 {
970 	struct kho_radix_tree *tree = &kho_out.radix_tree;
971 	const unsigned long start_pfn = page_to_pfn(page);
972 	const unsigned long end_pfn = start_pfn + nr_pages;
973 
974 	__kho_unpreserve(tree, start_pfn, end_pfn);
975 }
976 EXPORT_SYMBOL_GPL(kho_unpreserve_pages);
977 
978 /* vmalloc flags KHO supports */
979 #define KHO_VMALLOC_SUPPORTED_FLAGS	(VM_ALLOC | VM_ALLOW_HUGE_VMAP)
980 
981 /* KHO internal flags for vmalloc preservations */
982 #define KHO_VMALLOC_ALLOC	0x0001
983 #define KHO_VMALLOC_HUGE_VMAP	0x0002
984 
985 static unsigned short vmalloc_flags_to_kho(unsigned int vm_flags)
986 {
987 	unsigned short kho_flags = 0;
988 
989 	if (vm_flags & VM_ALLOC)
990 		kho_flags |= KHO_VMALLOC_ALLOC;
991 	if (vm_flags & VM_ALLOW_HUGE_VMAP)
992 		kho_flags |= KHO_VMALLOC_HUGE_VMAP;
993 
994 	return kho_flags;
995 }
996 
997 static unsigned int kho_flags_to_vmalloc(unsigned short kho_flags)
998 {
999 	unsigned int vm_flags = 0;
1000 
1001 	if (kho_flags & KHO_VMALLOC_ALLOC)
1002 		vm_flags |= VM_ALLOC;
1003 	if (kho_flags & KHO_VMALLOC_HUGE_VMAP)
1004 		vm_flags |= VM_ALLOW_HUGE_VMAP;
1005 
1006 	return vm_flags;
1007 }
1008 
1009 static struct kho_vmalloc_chunk *new_vmalloc_chunk(struct kho_vmalloc_chunk *cur)
1010 {
1011 	struct kho_vmalloc_chunk *chunk;
1012 	int err;
1013 
1014 	chunk = (struct kho_vmalloc_chunk *)get_zeroed_page(GFP_KERNEL);
1015 	if (!chunk)
1016 		return NULL;
1017 
1018 	err = kho_preserve_pages(virt_to_page(chunk), 1);
1019 	if (err)
1020 		goto err_free;
1021 	if (cur)
1022 		KHOSER_STORE_PTR(cur->hdr.next, chunk);
1023 	return chunk;
1024 
1025 err_free:
1026 	free_page((unsigned long)chunk);
1027 	return NULL;
1028 }
1029 
1030 static void kho_vmalloc_unpreserve_chunk(struct kho_vmalloc_chunk *chunk,
1031 					 unsigned short order)
1032 {
1033 	struct kho_radix_tree *tree = &kho_out.radix_tree;
1034 	unsigned long pfn = PHYS_PFN(virt_to_phys(chunk));
1035 
1036 	__kho_unpreserve(tree, pfn, pfn + 1);
1037 
1038 	for (int i = 0; i < ARRAY_SIZE(chunk->phys) && chunk->phys[i]; i++) {
1039 		pfn = PHYS_PFN(chunk->phys[i]);
1040 		__kho_unpreserve(tree, pfn, pfn + (1 << order));
1041 	}
1042 }
1043 
1044 /**
1045  * kho_preserve_vmalloc - preserve memory allocated with vmalloc() across kexec
1046  * @ptr: pointer to the area in vmalloc address space
1047  * @preservation: placeholder for preservation metadata
1048  *
1049  * Instructs KHO to preserve the area in vmalloc address space at @ptr. The
1050  * physical pages mapped at @ptr will be preserved and on successful return
1051  * @preservation will hold the physical address of a structure that describes
1052  * the preservation.
1053  *
1054  * NOTE: The memory allocated with vmalloc_node() variants cannot be reliably
1055  * restored on the same node
1056  *
1057  * Return: 0 on success, error code on failure
1058  */
1059 int kho_preserve_vmalloc(void *ptr, struct kho_vmalloc *preservation)
1060 {
1061 	struct kho_vmalloc_chunk *chunk;
1062 	struct vm_struct *vm = find_vm_area(ptr);
1063 	unsigned int order, flags, nr_contig_pages;
1064 	unsigned int idx = 0;
1065 	int err;
1066 
1067 	if (!vm)
1068 		return -EINVAL;
1069 
1070 	if (vm->flags & ~KHO_VMALLOC_SUPPORTED_FLAGS)
1071 		return -EOPNOTSUPP;
1072 
1073 	flags = vmalloc_flags_to_kho(vm->flags);
1074 	order = get_vm_area_page_order(vm);
1075 
1076 	chunk = new_vmalloc_chunk(NULL);
1077 	if (!chunk)
1078 		return -ENOMEM;
1079 	KHOSER_STORE_PTR(preservation->first, chunk);
1080 
1081 	nr_contig_pages = (1 << order);
1082 	for (int i = 0; i < vm->nr_pages; i += nr_contig_pages) {
1083 		phys_addr_t phys = page_to_phys(vm->pages[i]);
1084 
1085 		err = kho_preserve_pages(vm->pages[i], nr_contig_pages);
1086 		if (err)
1087 			goto err_free;
1088 
1089 		chunk->phys[idx++] = phys;
1090 		if (idx == ARRAY_SIZE(chunk->phys)) {
1091 			chunk = new_vmalloc_chunk(chunk);
1092 			if (!chunk) {
1093 				err = -ENOMEM;
1094 				goto err_free;
1095 			}
1096 			idx = 0;
1097 		}
1098 	}
1099 
1100 	preservation->total_pages = vm->nr_pages;
1101 	preservation->flags = flags;
1102 	preservation->order = order;
1103 
1104 	return 0;
1105 
1106 err_free:
1107 	kho_unpreserve_vmalloc(preservation);
1108 	return err;
1109 }
1110 EXPORT_SYMBOL_GPL(kho_preserve_vmalloc);
1111 
1112 /**
1113  * kho_unpreserve_vmalloc - unpreserve memory allocated with vmalloc()
1114  * @preservation: preservation metadata returned by kho_preserve_vmalloc()
1115  *
1116  * Instructs KHO to unpreserve the area in vmalloc address space that was
1117  * previously preserved with kho_preserve_vmalloc().
1118  */
1119 void kho_unpreserve_vmalloc(struct kho_vmalloc *preservation)
1120 {
1121 	struct kho_vmalloc_chunk *chunk = KHOSER_LOAD_PTR(preservation->first);
1122 
1123 	while (chunk) {
1124 		struct kho_vmalloc_chunk *tmp = chunk;
1125 
1126 		kho_vmalloc_unpreserve_chunk(chunk, preservation->order);
1127 
1128 		chunk = KHOSER_LOAD_PTR(chunk->hdr.next);
1129 		free_page((unsigned long)tmp);
1130 	}
1131 }
1132 EXPORT_SYMBOL_GPL(kho_unpreserve_vmalloc);
1133 
1134 /**
1135  * kho_restore_vmalloc - recreates and populates an area in vmalloc address
1136  * space from the preserved memory.
1137  * @preservation: preservation metadata.
1138  *
1139  * Recreates an area in vmalloc address space and populates it with memory that
1140  * was preserved using kho_preserve_vmalloc().
1141  *
1142  * Return: pointer to the area in the vmalloc address space, NULL on failure.
1143  */
1144 void *kho_restore_vmalloc(const struct kho_vmalloc *preservation)
1145 {
1146 	struct kho_vmalloc_chunk *chunk = KHOSER_LOAD_PTR(preservation->first);
1147 	kasan_vmalloc_flags_t kasan_flags = KASAN_VMALLOC_PROT_NORMAL;
1148 	unsigned int align, order, shift, vm_flags;
1149 	unsigned long total_pages, contig_pages;
1150 	unsigned long addr, size;
1151 	struct vm_struct *area;
1152 	struct page **pages;
1153 	unsigned int idx = 0;
1154 	int err;
1155 
1156 	vm_flags = kho_flags_to_vmalloc(preservation->flags);
1157 	if (vm_flags & ~KHO_VMALLOC_SUPPORTED_FLAGS)
1158 		return NULL;
1159 
1160 	total_pages = preservation->total_pages;
1161 	pages = kvmalloc_objs(*pages, total_pages);
1162 	if (!pages)
1163 		return NULL;
1164 	order = preservation->order;
1165 	contig_pages = (1 << order);
1166 	shift = PAGE_SHIFT + order;
1167 	align = 1 << shift;
1168 
1169 	while (chunk) {
1170 		struct page *page;
1171 
1172 		for (int i = 0; i < ARRAY_SIZE(chunk->phys) && chunk->phys[i]; i++) {
1173 			phys_addr_t phys = chunk->phys[i];
1174 
1175 			if (idx + contig_pages > total_pages)
1176 				goto err_free_pages_array;
1177 
1178 			page = kho_restore_pages(phys, contig_pages);
1179 			if (!page)
1180 				goto err_free_pages_array;
1181 
1182 			for (int j = 0; j < contig_pages; j++)
1183 				pages[idx++] = page + j;
1184 
1185 			phys += contig_pages * PAGE_SIZE;
1186 		}
1187 
1188 		page = kho_restore_pages(virt_to_phys(chunk), 1);
1189 		if (!page)
1190 			goto err_free_pages_array;
1191 		chunk = KHOSER_LOAD_PTR(chunk->hdr.next);
1192 		__free_page(page);
1193 	}
1194 
1195 	if (idx != total_pages)
1196 		goto err_free_pages_array;
1197 
1198 	area = __get_vm_area_node(total_pages * PAGE_SIZE, align, shift,
1199 				  vm_flags | VM_UNINITIALIZED,
1200 				  VMALLOC_START, VMALLOC_END,
1201 				  NUMA_NO_NODE, GFP_KERNEL,
1202 				  __builtin_return_address(0));
1203 	if (!area)
1204 		goto err_free_pages_array;
1205 
1206 	addr = (unsigned long)area->addr;
1207 	size = get_vm_area_size(area);
1208 	err = vmap_pages_range(addr, addr + size, PAGE_KERNEL, pages, shift);
1209 	if (err)
1210 		goto err_free_vm_area;
1211 
1212 	area->nr_pages = total_pages;
1213 	area->pages = pages;
1214 
1215 	if (vm_flags & VM_ALLOC)
1216 		kasan_flags |= KASAN_VMALLOC_VM_ALLOC;
1217 
1218 	area->addr = kasan_unpoison_vmalloc(area->addr, total_pages * PAGE_SIZE,
1219 					    kasan_flags);
1220 	clear_vm_uninitialized_flag(area);
1221 
1222 	return area->addr;
1223 
1224 err_free_vm_area:
1225 	free_vm_area(area);
1226 err_free_pages_array:
1227 	kvfree(pages);
1228 	return NULL;
1229 }
1230 EXPORT_SYMBOL_GPL(kho_restore_vmalloc);
1231 
1232 /**
1233  * kho_alloc_preserve - Allocate, zero, and preserve memory.
1234  * @size: The number of bytes to allocate.
1235  *
1236  * Allocates a physically contiguous block of zeroed pages that is large
1237  * enough to hold @size bytes. The allocated memory is then registered with
1238  * KHO for preservation across a kexec.
1239  *
1240  * Note: The actual allocated size will be rounded up to the nearest
1241  * power-of-two page boundary.
1242  *
1243  * @return A virtual pointer to the allocated and preserved memory on success,
1244  * or an ERR_PTR() encoded error on failure.
1245  */
1246 void *kho_alloc_preserve(size_t size)
1247 {
1248 	struct folio *folio;
1249 	int order, ret;
1250 
1251 	if (!size)
1252 		return ERR_PTR(-EINVAL);
1253 
1254 	order = get_order(size);
1255 	if (order > MAX_PAGE_ORDER)
1256 		return ERR_PTR(-E2BIG);
1257 
1258 	folio = folio_alloc(GFP_KERNEL | __GFP_ZERO, order);
1259 	if (!folio)
1260 		return ERR_PTR(-ENOMEM);
1261 
1262 	ret = kho_preserve_folio(folio);
1263 	if (ret) {
1264 		folio_put(folio);
1265 		return ERR_PTR(ret);
1266 	}
1267 
1268 	return folio_address(folio);
1269 }
1270 EXPORT_SYMBOL_GPL(kho_alloc_preserve);
1271 
1272 /**
1273  * kho_unpreserve_free - Unpreserve and free memory.
1274  * @mem:  Pointer to the memory allocated by kho_alloc_preserve().
1275  *
1276  * Unregisters the memory from KHO preservation and frees the underlying
1277  * pages back to the system. This function should be called to clean up
1278  * memory allocated with kho_alloc_preserve().
1279  */
1280 void kho_unpreserve_free(void *mem)
1281 {
1282 	struct folio *folio;
1283 
1284 	if (!mem)
1285 		return;
1286 
1287 	folio = virt_to_folio(mem);
1288 	kho_unpreserve_folio(folio);
1289 	folio_put(folio);
1290 }
1291 EXPORT_SYMBOL_GPL(kho_unpreserve_free);
1292 
1293 /**
1294  * kho_restore_free - Restore and free memory after kexec.
1295  * @mem:  Pointer to the memory (in the new kernel's address space)
1296  * that was allocated by the old kernel.
1297  *
1298  * This function is intended to be called in the new kernel (post-kexec)
1299  * to take ownership of and free a memory region that was preserved by the
1300  * old kernel using kho_alloc_preserve().
1301  *
1302  * It first restores the pages from KHO (using their physical address)
1303  * and then frees the pages back to the new kernel's page allocator.
1304  */
1305 void kho_restore_free(void *mem)
1306 {
1307 	struct folio *folio;
1308 
1309 	if (!mem)
1310 		return;
1311 
1312 	folio = kho_restore_folio(__pa(mem));
1313 	if (!WARN_ON(!folio))
1314 		folio_put(folio);
1315 }
1316 EXPORT_SYMBOL_GPL(kho_restore_free);
1317 
1318 struct kho_in {
1319 	phys_addr_t fdt_phys;
1320 	phys_addr_t scratch_phys;
1321 	char previous_release[__NEW_UTS_LEN + 1];
1322 	u32 kexec_count;
1323 	struct kho_debugfs dbg;
1324 };
1325 
1326 static struct kho_in kho_in = {
1327 };
1328 
1329 static const void *kho_get_fdt(void)
1330 {
1331 	return kho_in.fdt_phys ? phys_to_virt(kho_in.fdt_phys) : NULL;
1332 }
1333 
1334 /**
1335  * is_kho_boot - check if current kernel was booted via KHO-enabled
1336  * kexec
1337  *
1338  * This function checks if the current kernel was loaded through a kexec
1339  * operation with KHO enabled, by verifying that a valid KHO FDT
1340  * was passed.
1341  *
1342  * Note: This function returns reliable results only after
1343  * kho_populate() has been called during early boot. Before that,
1344  * it may return false even if KHO data is present.
1345  *
1346  * Return: true if booted via KHO-enabled kexec, false otherwise
1347  */
1348 bool is_kho_boot(void)
1349 {
1350 	return !!kho_get_fdt();
1351 }
1352 EXPORT_SYMBOL_GPL(is_kho_boot);
1353 
1354 /**
1355  * kho_retrieve_subtree - retrieve a preserved sub blob by its name.
1356  * @name: the name of the sub blob passed to kho_add_subtree().
1357  * @phys: if found, the physical address of the sub blob is stored in @phys.
1358  * @size: if not NULL and found, the size of the sub blob is stored in @size.
1359  *
1360  * Retrieve a preserved sub blob named @name and store its physical
1361  * address in @phys and optionally its size in @size.
1362  *
1363  * Return: 0 on success, error code on failure
1364  */
1365 int kho_retrieve_subtree(const char *name, phys_addr_t *phys, size_t *size)
1366 {
1367 	const void *fdt = kho_get_fdt();
1368 	const u64 *val;
1369 	int offset, len;
1370 
1371 	if (!fdt)
1372 		return -ENOENT;
1373 
1374 	if (!phys)
1375 		return -EINVAL;
1376 
1377 	offset = fdt_subnode_offset(fdt, 0, name);
1378 	if (offset < 0)
1379 		return -ENOENT;
1380 
1381 	val = fdt_getprop(fdt, offset, KHO_SUB_TREE_PROP_NAME, &len);
1382 	if (!val || len != sizeof(*val))
1383 		return -EINVAL;
1384 
1385 	*phys = (phys_addr_t)*val;
1386 
1387 	val = fdt_getprop(fdt, offset, KHO_SUB_TREE_SIZE_PROP_NAME, &len);
1388 	if (!val || len != sizeof(*val)) {
1389 		pr_warn("broken KHO subnode '%s': missing or invalid blob-size property\n",
1390 			name);
1391 		return -EINVAL;
1392 	}
1393 
1394 	if (size)
1395 		*size = (size_t)*val;
1396 
1397 	return 0;
1398 }
1399 EXPORT_SYMBOL_GPL(kho_retrieve_subtree);
1400 
1401 static int __init kho_mem_retrieve(const void *fdt)
1402 {
1403 	struct kho_radix_tree tree;
1404 	const phys_addr_t *mem;
1405 	int len;
1406 
1407 	/* Retrieve the KHO radix tree from passed-in FDT. */
1408 	mem = fdt_getprop(fdt, 0, KHO_FDT_MEMORY_MAP_PROP_NAME, &len);
1409 
1410 	if (!mem || len != sizeof(*mem)) {
1411 		pr_err("failed to get preserved KHO memory tree\n");
1412 		return -ENOENT;
1413 	}
1414 
1415 	if (!*mem)
1416 		return -EINVAL;
1417 
1418 	tree.root = phys_to_virt(*mem);
1419 	mutex_init(&tree.lock);
1420 	return kho_radix_walk_tree(&tree, kho_preserved_memory_reserve);
1421 }
1422 
1423 static __init int kho_out_fdt_setup(void)
1424 {
1425 	struct kho_radix_tree *tree = &kho_out.radix_tree;
1426 	void *root = kho_out.fdt;
1427 	u64 preserved_mem_tree_pa;
1428 	int err;
1429 
1430 	err = fdt_create(root, PAGE_SIZE);
1431 	err |= fdt_finish_reservemap(root);
1432 	err |= fdt_begin_node(root, "");
1433 	err |= fdt_property_string(root, "compatible", KHO_FDT_COMPATIBLE);
1434 
1435 	preserved_mem_tree_pa = virt_to_phys(tree->root);
1436 
1437 	err |= fdt_property(root, KHO_FDT_MEMORY_MAP_PROP_NAME,
1438 			    &preserved_mem_tree_pa,
1439 			    sizeof(preserved_mem_tree_pa));
1440 
1441 	err |= fdt_end_node(root);
1442 	err |= fdt_finish(root);
1443 
1444 	return err;
1445 }
1446 
1447 static void __init kho_in_kexec_metadata(void)
1448 {
1449 	struct kho_kexec_metadata *metadata;
1450 	phys_addr_t metadata_phys;
1451 	size_t blob_size;
1452 	int err;
1453 
1454 	err = kho_retrieve_subtree(KHO_METADATA_NODE_NAME, &metadata_phys,
1455 				   &blob_size);
1456 	if (err)
1457 		/* This is fine, previous kernel didn't export metadata */
1458 		return;
1459 
1460 	/* Check that, at least, "version" is present */
1461 	if (blob_size < sizeof(u32)) {
1462 		pr_warn("kexec-metadata blob too small (%zu bytes)\n",
1463 			blob_size);
1464 		return;
1465 	}
1466 
1467 	metadata = phys_to_virt(metadata_phys);
1468 
1469 	if (metadata->version != KHO_KEXEC_METADATA_VERSION) {
1470 		pr_warn("kexec-metadata version %u not supported (expected %u)\n",
1471 			metadata->version, KHO_KEXEC_METADATA_VERSION);
1472 		return;
1473 	}
1474 
1475 	if (blob_size < sizeof(*metadata)) {
1476 		pr_warn("kexec-metadata blob too small for v%u (%zu < %zu)\n",
1477 			metadata->version, blob_size, sizeof(*metadata));
1478 		return;
1479 	}
1480 
1481 	/*
1482 	 * Copy data to the kernel structure that will persist during
1483 	 * kernel lifetime.
1484 	 */
1485 	kho_in.kexec_count = metadata->kexec_count;
1486 	strscpy(kho_in.previous_release, metadata->previous_release,
1487 		sizeof(kho_in.previous_release));
1488 
1489 	pr_info("exec from: %s (count %u)\n",
1490 		kho_in.previous_release, kho_in.kexec_count);
1491 }
1492 
1493 /*
1494  * Create kexec metadata to pass kernel version and boot count to the
1495  * next kernel. This keeps the core KHO ABI minimal and allows the
1496  * metadata format to evolve independently.
1497  */
1498 static __init int kho_out_kexec_metadata(void)
1499 {
1500 	struct kho_kexec_metadata *metadata;
1501 	int err;
1502 
1503 	metadata = kho_alloc_preserve(sizeof(*metadata));
1504 	if (IS_ERR(metadata))
1505 		return PTR_ERR(metadata);
1506 
1507 	metadata->version = KHO_KEXEC_METADATA_VERSION;
1508 	strscpy(metadata->previous_release, init_uts_ns.name.release,
1509 		sizeof(metadata->previous_release));
1510 	/* kho_in.kexec_count is set to 0 on cold boot */
1511 	metadata->kexec_count = kho_in.kexec_count + 1;
1512 
1513 	err = kho_add_subtree(KHO_METADATA_NODE_NAME, metadata,
1514 			      sizeof(*metadata));
1515 	if (err)
1516 		kho_unpreserve_free(metadata);
1517 
1518 	return err;
1519 }
1520 
1521 static int __init kho_kexec_metadata_init(const void *fdt)
1522 {
1523 	int err;
1524 
1525 	if (fdt)
1526 		kho_in_kexec_metadata();
1527 
1528 	/* Populate kexec metadata for the possible next kexec */
1529 	err = kho_out_kexec_metadata();
1530 	if (err)
1531 		pr_warn("failed to initialize kexec-metadata subtree: %d\n",
1532 			err);
1533 
1534 	return err;
1535 }
1536 
1537 static __init int kho_init(void)
1538 {
1539 	struct kho_radix_tree *tree = &kho_out.radix_tree;
1540 	const void *fdt = kho_get_fdt();
1541 	int err = 0;
1542 
1543 	if (!kho_enable)
1544 		return 0;
1545 
1546 	tree->root = kzalloc(PAGE_SIZE, GFP_KERNEL);
1547 	if (!tree->root) {
1548 		err = -ENOMEM;
1549 		goto err_free_scratch;
1550 	}
1551 
1552 	kho_out.fdt = kho_alloc_preserve(PAGE_SIZE);
1553 	if (IS_ERR(kho_out.fdt)) {
1554 		err = PTR_ERR(kho_out.fdt);
1555 		goto err_free_kho_radix_tree_root;
1556 	}
1557 
1558 	err = kho_debugfs_init();
1559 	if (err)
1560 		goto err_free_fdt;
1561 
1562 	err = kho_out_debugfs_init(&kho_out.dbg);
1563 	if (err)
1564 		goto err_free_fdt;
1565 
1566 	err = kho_out_fdt_setup();
1567 	if (err)
1568 		goto err_free_fdt;
1569 
1570 	err = kho_kexec_metadata_init(fdt);
1571 	if (err)
1572 		goto err_free_fdt;
1573 
1574 	if (fdt) {
1575 		kho_in_debugfs_init(&kho_in.dbg, fdt);
1576 		return 0;
1577 	}
1578 
1579 	for (int i = 0; i < kho_scratch_cnt; i++) {
1580 		unsigned long base_pfn = PHYS_PFN(kho_scratch[i].addr);
1581 		unsigned long count = kho_scratch[i].size >> PAGE_SHIFT;
1582 		unsigned long pfn;
1583 
1584 		/*
1585 		 * When debug_pagealloc is enabled, __free_pages() clears the
1586 		 * corresponding PRESENT bit in the kernel page table.
1587 		 * Subsequent kmemleak scans of these pages cause the
1588 		 * non-PRESENT page faults.
1589 		 * Mark scratch areas with kmemleak_ignore_phys() to exclude
1590 		 * them from kmemleak scanning.
1591 		 */
1592 		kmemleak_ignore_phys(kho_scratch[i].addr);
1593 		for (pfn = base_pfn; pfn < base_pfn + count;
1594 		     pfn += pageblock_nr_pages)
1595 			init_cma_reserved_pageblock(pfn_to_page(pfn));
1596 	}
1597 
1598 	WARN_ON_ONCE(kho_debugfs_blob_add(&kho_out.dbg, "fdt",
1599 					  kho_out.fdt,
1600 					  fdt_totalsize(kho_out.fdt), true));
1601 
1602 	return 0;
1603 
1604 err_free_fdt:
1605 	kho_unpreserve_free(kho_out.fdt);
1606 err_free_kho_radix_tree_root:
1607 	kfree(tree->root);
1608 	tree->root = NULL;
1609 err_free_scratch:
1610 	kho_out.fdt = NULL;
1611 	for (int i = 0; i < kho_scratch_cnt; i++) {
1612 		void *start = __va(kho_scratch[i].addr);
1613 		void *end = start + kho_scratch[i].size;
1614 
1615 		free_reserved_area(start, end, -1, "");
1616 	}
1617 	kho_enable = false;
1618 	return err;
1619 }
1620 fs_initcall(kho_init);
1621 
1622 void __init kho_memory_init(void)
1623 {
1624 	if (kho_in.scratch_phys) {
1625 		kho_scratch = phys_to_virt(kho_in.scratch_phys);
1626 
1627 		if (kho_mem_retrieve(kho_get_fdt()))
1628 			kho_in.fdt_phys = 0;
1629 	} else {
1630 		kho_reserve_scratch();
1631 	}
1632 }
1633 
1634 void __init kho_populate(phys_addr_t fdt_phys, u64 fdt_len,
1635 			 phys_addr_t scratch_phys, u64 scratch_len)
1636 {
1637 	unsigned int scratch_cnt = scratch_len / sizeof(*kho_scratch);
1638 	struct kho_scratch *scratch = NULL;
1639 	phys_addr_t mem_map_phys;
1640 	void *fdt = NULL;
1641 	bool populated = false;
1642 	int err;
1643 
1644 	/* Validate the input FDT */
1645 	fdt = early_memremap(fdt_phys, fdt_len);
1646 	if (!fdt) {
1647 		pr_warn("setup: failed to memremap FDT (0x%llx)\n", fdt_phys);
1648 		goto report;
1649 	}
1650 	err = fdt_check_header(fdt);
1651 	if (err) {
1652 		pr_warn("setup: handover FDT (0x%llx) is invalid: %d\n",
1653 			fdt_phys, err);
1654 		goto unmap_fdt;
1655 	}
1656 	err = fdt_node_check_compatible(fdt, 0, KHO_FDT_COMPATIBLE);
1657 	if (err) {
1658 		pr_warn("setup: handover FDT (0x%llx) is incompatible with '%s': %d\n",
1659 			fdt_phys, KHO_FDT_COMPATIBLE, err);
1660 		goto unmap_fdt;
1661 	}
1662 
1663 	mem_map_phys = kho_get_mem_map_phys(fdt);
1664 	if (!mem_map_phys)
1665 		goto unmap_fdt;
1666 
1667 	scratch = early_memremap(scratch_phys, scratch_len);
1668 	if (!scratch) {
1669 		pr_warn("setup: failed to memremap scratch (phys=0x%llx, len=%lld)\n",
1670 			scratch_phys, scratch_len);
1671 		goto unmap_fdt;
1672 	}
1673 
1674 	/*
1675 	 * We pass a safe contiguous blocks of memory to use for early boot
1676 	 * purporses from the previous kernel so that we can resize the
1677 	 * memblock array as needed.
1678 	 */
1679 	for (int i = 0; i < scratch_cnt; i++) {
1680 		struct kho_scratch *area = &scratch[i];
1681 		u64 size = area->size;
1682 
1683 		memblock_add(area->addr, size);
1684 		err = memblock_mark_kho_scratch(area->addr, size);
1685 		if (err) {
1686 			pr_warn("failed to mark the scratch region 0x%pa+0x%pa: %pe",
1687 				&area->addr, &size, ERR_PTR(err));
1688 			goto unmap_scratch;
1689 		}
1690 		pr_debug("Marked 0x%pa+0x%pa as scratch", &area->addr, &size);
1691 	}
1692 
1693 	memblock_reserve(scratch_phys, scratch_len);
1694 
1695 	/*
1696 	 * Now that we have a viable region of scratch memory, let's tell
1697 	 * the memblocks allocator to only use that for any allocations.
1698 	 * That way we ensure that nothing scribbles over in use data while
1699 	 * we initialize the page tables which we will need to ingest all
1700 	 * memory reservations from the previous kernel.
1701 	 */
1702 	memblock_set_kho_scratch_only();
1703 
1704 	kho_in.fdt_phys = fdt_phys;
1705 	kho_in.scratch_phys = scratch_phys;
1706 	kho_scratch_cnt = scratch_cnt;
1707 
1708 	populated = true;
1709 	pr_info("found kexec handover data.\n");
1710 
1711 unmap_scratch:
1712 	early_memunmap(scratch, scratch_len);
1713 unmap_fdt:
1714 	early_memunmap(fdt, fdt_len);
1715 report:
1716 	if (!populated)
1717 		pr_warn("disabling KHO revival\n");
1718 }
1719 
1720 /* Helper functions for kexec_file_load */
1721 
1722 int kho_fill_kimage(struct kimage *image)
1723 {
1724 	ssize_t scratch_size;
1725 	int err = 0;
1726 	struct kexec_buf scratch;
1727 
1728 	if (!kho_enable || image->type == KEXEC_TYPE_CRASH)
1729 		return 0;
1730 
1731 	image->kho.fdt = virt_to_phys(kho_out.fdt);
1732 
1733 	scratch_size = sizeof(*kho_scratch) * kho_scratch_cnt;
1734 	scratch = (struct kexec_buf){
1735 		.image = image,
1736 		.buffer = kho_scratch,
1737 		.bufsz = scratch_size,
1738 		.mem = KEXEC_BUF_MEM_UNKNOWN,
1739 		.memsz = scratch_size,
1740 		.buf_align = SZ_64K, /* Makes it easier to map */
1741 		.buf_max = ULONG_MAX,
1742 		.top_down = true,
1743 	};
1744 	err = kexec_add_buffer(&scratch);
1745 	if (err)
1746 		return err;
1747 	image->kho.scratch = &image->segment[image->nr_segments - 1];
1748 
1749 	return 0;
1750 }
1751 
1752 static int kho_walk_scratch(struct kexec_buf *kbuf,
1753 			    int (*func)(struct resource *, void *))
1754 {
1755 	int ret = 0;
1756 	int i;
1757 
1758 	for (i = 0; i < kho_scratch_cnt; i++) {
1759 		struct resource res = {
1760 			.start = kho_scratch[i].addr,
1761 			.end = kho_scratch[i].addr + kho_scratch[i].size - 1,
1762 		};
1763 
1764 		/* Try to fit the kimage into our KHO scratch region */
1765 		ret = func(&res, kbuf);
1766 		if (ret)
1767 			break;
1768 	}
1769 
1770 	return ret;
1771 }
1772 
1773 int kho_locate_mem_hole(struct kexec_buf *kbuf,
1774 			int (*func)(struct resource *, void *))
1775 {
1776 	int ret;
1777 
1778 	if (!kho_enable || kbuf->image->type == KEXEC_TYPE_CRASH)
1779 		return 1;
1780 
1781 	ret = kho_walk_scratch(kbuf, func);
1782 
1783 	return ret == 1 ? 0 : -EADDRNOTAVAIL;
1784 }
1785