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