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