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