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