1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * kexec_handover.c - kexec handover metadata processing
4 * Copyright (C) 2023 Alexander Graf <graf@amazon.com>
5 * Copyright (C) 2025 Microsoft Corporation, Mike Rapoport <rppt@kernel.org>
6 * Copyright (C) 2025 Google LLC, Changyuan Lyu <changyuanl@google.com>
7 * Copyright (C) 2025 Pasha Tatashin <pasha.tatashin@soleen.com>
8 * Copyright (C) 2026 Google LLC, Jason Miu <jasonmiu@google.com>
9 */
10
11 #define pr_fmt(fmt) "KHO: " fmt
12
13 #include <linux/cleanup.h>
14 #include <linux/cma.h>
15 #include <linux/kmemleak.h>
16 #include <linux/count_zeros.h>
17 #include <linux/kasan.h>
18 #include <linux/kexec.h>
19 #include <linux/kexec_handover.h>
20 #include <linux/kho_radix_tree.h>
21 #include <linux/utsname.h>
22 #include <linux/kho/abi/kexec_handover.h>
23 #include <linux/kho/abi/kexec_metadata.h>
24 #include <linux/libfdt.h>
25 #include <linux/list.h>
26 #include <linux/memblock.h>
27 #include <linux/page-isolation.h>
28 #include <linux/unaligned.h>
29 #include <linux/vmalloc.h>
30
31 #include <asm/early_ioremap.h>
32
33 /*
34 * KHO is tightly coupled with mm init and needs access to some of mm
35 * internal APIs.
36 */
37 #include "../../mm/internal.h"
38 #include "../kexec_internal.h"
39 #include "kexec_handover_internal.h"
40
41 /*
42 * This is the minimal alignment required by deferred struct page init.
43 * deferred_init_memmap_chunk frees memory to the buddy allocator, which looks
44 * at the neighboring pages (up to MAX_PAGE_ORDER) to merge them.
45 * If KHO scratch is not aligned to that value, buddy can access uninitialized
46 * struct pages, which can cause a crash.
47 */
48 #define SCRATCH_ALIGNMENT_BYTES (PAGE_SIZE * MAX_ORDER_NR_PAGES)
49 static_assert(SCRATCH_ALIGNMENT_BYTES >= CMA_MIN_ALIGNMENT_BYTES);
50
51 /* The magic token for preserved pages */
52 #define KHO_PAGE_MAGIC 0x4b484f50U /* ASCII for 'KHOP' */
53
54 /*
55 * KHO uses page->private, which is an unsigned long, to store page metadata.
56 * Use it to store both the magic and the order.
57 */
58 union kho_page_info {
59 unsigned long page_private;
60 struct {
61 unsigned int order;
62 unsigned int magic;
63 };
64 };
65
66 static_assert(sizeof(union kho_page_info) == sizeof(((struct page *)0)->private));
67
68 static bool kho_enable __ro_after_init = IS_ENABLED(CONFIG_KEXEC_HANDOVER_ENABLE_DEFAULT);
69
kho_is_enabled(void)70 bool kho_is_enabled(void)
71 {
72 return kho_enable;
73 }
74 EXPORT_SYMBOL_GPL(kho_is_enabled);
75
kho_parse_enable(char * p)76 static int __init kho_parse_enable(char *p)
77 {
78 return kstrtobool(p, &kho_enable);
79 }
80 early_param("kho", kho_parse_enable);
81
82 struct kho_out {
83 void *fdt;
84 struct mutex lock; /* protects KHO FDT */
85
86 struct kho_radix_tree radix_tree;
87 struct kho_debugfs dbg;
88 };
89
90 static struct kho_out kho_out = {
91 .lock = __MUTEX_INITIALIZER(kho_out.lock),
92 .radix_tree = {
93 .lock = __MUTEX_INITIALIZER(kho_out.radix_tree.lock),
94 },
95 };
96
97 /**
98 * kho_radix_encode_key - Encodes a physical address and order into a radix key.
99 * @phys: The physical address of the page.
100 * @order: The order of the page.
101 *
102 * This function combines a page's physical address and its order into a
103 * single unsigned long, which is used as a key for all radix tree
104 * operations.
105 *
106 * Return: The encoded unsigned long radix key.
107 */
kho_radix_encode_key(phys_addr_t phys,unsigned int order)108 static unsigned long kho_radix_encode_key(phys_addr_t phys, unsigned int order)
109 {
110 /* Order bits part */
111 unsigned long h = 1UL << (KHO_ORDER_0_LOG2 - order);
112 /* Shifted physical address part */
113 unsigned long l = phys >> (PAGE_SHIFT + order);
114
115 return h | l;
116 }
117
118 /**
119 * kho_radix_decode_key - Decodes a radix key back into a physical address and order.
120 * @key: The unsigned long key to decode.
121 * @order: An output parameter, a pointer to an unsigned int where the decoded
122 * page order will be stored.
123 *
124 * This function reverses the encoding performed by kho_radix_encode_key(),
125 * extracting the original physical address and page order from a given key.
126 *
127 * Return: The decoded physical address.
128 */
kho_radix_decode_key(unsigned long key,unsigned int * order)129 static phys_addr_t kho_radix_decode_key(unsigned long key, unsigned int *order)
130 {
131 unsigned int order_bit = fls64(key);
132 phys_addr_t phys;
133
134 /* order_bit is numbered starting at 1 from fls64 */
135 *order = KHO_ORDER_0_LOG2 - order_bit + 1;
136 /* The order is discarded by the shift */
137 phys = key << (PAGE_SHIFT + *order);
138
139 return phys;
140 }
141
kho_radix_get_bitmap_index(unsigned long key)142 static unsigned long kho_radix_get_bitmap_index(unsigned long key)
143 {
144 return key % (1 << KHO_BITMAP_SIZE_LOG2);
145 }
146
kho_radix_get_table_index(unsigned long key,unsigned int level)147 static unsigned long kho_radix_get_table_index(unsigned long key,
148 unsigned int level)
149 {
150 int s;
151
152 s = ((level - 1) * KHO_TABLE_SIZE_LOG2) + KHO_BITMAP_SIZE_LOG2;
153 return (key >> s) % (1 << KHO_TABLE_SIZE_LOG2);
154 }
155
156 /**
157 * kho_radix_add_page - Marks a page as preserved in the radix tree.
158 * @tree: The KHO radix tree.
159 * @pfn: The page frame number of the page to preserve.
160 * @order: The order of the page.
161 *
162 * This function traverses the radix tree based on the key derived from @pfn
163 * and @order. It sets the corresponding bit in the leaf bitmap to mark the
164 * page for preservation. If intermediate nodes do not exist along the path,
165 * they are allocated and added to the tree.
166 *
167 * Return: 0 on success, or a negative error code on failure.
168 */
kho_radix_add_page(struct kho_radix_tree * tree,unsigned long pfn,unsigned int order)169 int kho_radix_add_page(struct kho_radix_tree *tree,
170 unsigned long pfn, unsigned int order)
171 {
172 /* Newly allocated nodes for error cleanup */
173 struct kho_radix_node *intermediate_nodes[KHO_TREE_MAX_DEPTH] = { 0 };
174 unsigned long key = kho_radix_encode_key(PFN_PHYS(pfn), order);
175 struct kho_radix_node *anchor_node = NULL;
176 struct kho_radix_node *node = tree->root;
177 struct kho_radix_node *new_node;
178 unsigned int i, idx, anchor_idx;
179 struct kho_radix_leaf *leaf;
180 int err = 0;
181
182 if (WARN_ON_ONCE(!tree->root))
183 return -EINVAL;
184
185 might_sleep();
186
187 guard(mutex)(&tree->lock);
188
189 /* Go from high levels to low levels */
190 for (i = KHO_TREE_MAX_DEPTH - 1; i > 0; i--) {
191 idx = kho_radix_get_table_index(key, i);
192
193 if (node->table[idx]) {
194 node = phys_to_virt(node->table[idx]);
195 continue;
196 }
197
198 /* Next node is empty, create a new node for it */
199 new_node = (struct kho_radix_node *)get_zeroed_page(GFP_KERNEL);
200 if (!new_node) {
201 err = -ENOMEM;
202 goto err_free_nodes;
203 }
204
205 node->table[idx] = virt_to_phys(new_node);
206
207 /*
208 * Capture the node where the new branch starts for cleanup
209 * if allocation fails.
210 */
211 if (!anchor_node) {
212 anchor_node = node;
213 anchor_idx = idx;
214 }
215 intermediate_nodes[i] = new_node;
216
217 node = new_node;
218 }
219
220 /* Handle the leaf level bitmap (level 0) */
221 idx = kho_radix_get_bitmap_index(key);
222 leaf = (struct kho_radix_leaf *)node;
223 __set_bit(idx, leaf->bitmap);
224
225 return 0;
226
227 err_free_nodes:
228 for (i = KHO_TREE_MAX_DEPTH - 1; i > 0; i--) {
229 if (intermediate_nodes[i])
230 free_page((unsigned long)intermediate_nodes[i]);
231 }
232 if (anchor_node)
233 anchor_node->table[anchor_idx] = 0;
234
235 return err;
236 }
237 EXPORT_SYMBOL_GPL(kho_radix_add_page);
238
239 /**
240 * kho_radix_del_page - Removes a page's preservation status from the radix tree.
241 * @tree: The KHO radix tree.
242 * @pfn: The page frame number of the page to unpreserve.
243 * @order: The order of the page.
244 *
245 * This function traverses the radix tree and clears the bit corresponding to
246 * the page, effectively removing its "preserved" status. It does not free
247 * the tree's intermediate nodes, even if they become empty.
248 */
kho_radix_del_page(struct kho_radix_tree * tree,unsigned long pfn,unsigned int order)249 void kho_radix_del_page(struct kho_radix_tree *tree, unsigned long pfn,
250 unsigned int order)
251 {
252 unsigned long key = kho_radix_encode_key(PFN_PHYS(pfn), order);
253 struct kho_radix_node *node = tree->root;
254 struct kho_radix_leaf *leaf;
255 unsigned int i, idx;
256
257 if (WARN_ON_ONCE(!tree->root))
258 return;
259
260 might_sleep();
261
262 guard(mutex)(&tree->lock);
263
264 /* Go from high levels to low levels */
265 for (i = KHO_TREE_MAX_DEPTH - 1; i > 0; i--) {
266 idx = kho_radix_get_table_index(key, i);
267
268 /*
269 * Attempting to delete a page that has not been preserved,
270 * return with a warning.
271 */
272 if (WARN_ON(!node->table[idx]))
273 return;
274
275 node = phys_to_virt(node->table[idx]);
276 }
277
278 /* Handle the leaf level bitmap (level 0) */
279 leaf = (struct kho_radix_leaf *)node;
280 idx = kho_radix_get_bitmap_index(key);
281 __clear_bit(idx, leaf->bitmap);
282 }
283 EXPORT_SYMBOL_GPL(kho_radix_del_page);
284
kho_radix_walk_leaf(struct kho_radix_leaf * leaf,unsigned long key,kho_radix_tree_walk_callback_t cb)285 static int kho_radix_walk_leaf(struct kho_radix_leaf *leaf,
286 unsigned long key,
287 kho_radix_tree_walk_callback_t cb)
288 {
289 unsigned long *bitmap = (unsigned long *)leaf;
290 unsigned int order;
291 phys_addr_t phys;
292 unsigned int i;
293 int err;
294
295 for_each_set_bit(i, bitmap, PAGE_SIZE * BITS_PER_BYTE) {
296 phys = kho_radix_decode_key(key | i, &order);
297 err = cb(phys, order);
298 if (err)
299 return err;
300 }
301
302 return 0;
303 }
304
__kho_radix_walk_tree(struct kho_radix_node * root,unsigned int level,unsigned long start,kho_radix_tree_walk_callback_t cb)305 static int __kho_radix_walk_tree(struct kho_radix_node *root,
306 unsigned int level, unsigned long start,
307 kho_radix_tree_walk_callback_t cb)
308 {
309 struct kho_radix_node *node;
310 struct kho_radix_leaf *leaf;
311 unsigned long key, i;
312 unsigned int shift;
313 int err;
314
315 for (i = 0; i < PAGE_SIZE / sizeof(phys_addr_t); i++) {
316 if (!root->table[i])
317 continue;
318
319 shift = ((level - 1) * KHO_TABLE_SIZE_LOG2) +
320 KHO_BITMAP_SIZE_LOG2;
321 key = start | (i << shift);
322
323 node = phys_to_virt(root->table[i]);
324
325 if (level == 1) {
326 /*
327 * we are at level 1,
328 * node is pointing to the level 0 bitmap.
329 */
330 leaf = (struct kho_radix_leaf *)node;
331 err = kho_radix_walk_leaf(leaf, key, cb);
332 } else {
333 err = __kho_radix_walk_tree(node, level - 1,
334 key, cb);
335 }
336
337 if (err)
338 return err;
339 }
340
341 return 0;
342 }
343
344 /**
345 * kho_radix_walk_tree - Traverses the radix tree and calls a callback for each preserved page.
346 * @tree: A pointer to the KHO radix tree to walk.
347 * @cb: A callback function of type kho_radix_tree_walk_callback_t that will be
348 * invoked for each preserved page found in the tree. The callback receives
349 * the physical address and order of the preserved page.
350 *
351 * This function walks the radix tree, searching from the specified top level
352 * down to the lowest level (level 0). For each preserved page found, it invokes
353 * the provided callback, passing the page's physical address and order.
354 *
355 * Return: 0 if the walk completed the specified tree, or the non-zero return
356 * value from the callback that stopped the walk.
357 */
kho_radix_walk_tree(struct kho_radix_tree * tree,kho_radix_tree_walk_callback_t cb)358 int kho_radix_walk_tree(struct kho_radix_tree *tree,
359 kho_radix_tree_walk_callback_t cb)
360 {
361 if (WARN_ON_ONCE(!tree->root))
362 return -EINVAL;
363
364 guard(mutex)(&tree->lock);
365
366 return __kho_radix_walk_tree(tree->root, KHO_TREE_MAX_DEPTH - 1, 0, cb);
367 }
368 EXPORT_SYMBOL_GPL(kho_radix_walk_tree);
369
370 /* For physically contiguous 0-order pages. */
kho_init_pages(struct page * page,unsigned long nr_pages)371 static void kho_init_pages(struct page *page, unsigned long nr_pages)
372 {
373 for (unsigned long i = 0; i < nr_pages; i++) {
374 set_page_count(page + i, 1);
375 /* Clear each page's codetag to avoid accounting mismatch. */
376 clear_page_tag_ref(page + i);
377 }
378 }
379
kho_init_folio(struct page * page,unsigned int order)380 static void kho_init_folio(struct page *page, unsigned int order)
381 {
382 unsigned long nr_pages = (1 << order);
383
384 /* Head page gets refcount of 1. */
385 set_page_count(page, 1);
386 /* Clear head page's codetag to avoid accounting mismatch. */
387 clear_page_tag_ref(page);
388
389 /* For higher order folios, tail pages get a page count of zero. */
390 for (unsigned long i = 1; i < nr_pages; i++)
391 set_page_count(page + i, 0);
392
393 if (order > 0)
394 prep_compound_page(page, order);
395 }
396
kho_restore_page(phys_addr_t phys,bool is_folio)397 static struct page *kho_restore_page(phys_addr_t phys, bool is_folio)
398 {
399 struct page *page = pfn_to_online_page(PHYS_PFN(phys));
400 unsigned long nr_pages;
401 union kho_page_info info;
402
403 if (!page)
404 return NULL;
405
406 info.page_private = page->private;
407 /*
408 * deserialize_bitmap() only sets the magic on the head page. This magic
409 * check also implicitly makes sure phys is order-aligned since for
410 * non-order-aligned phys addresses, magic will never be set.
411 */
412 if (WARN_ON_ONCE(info.magic != KHO_PAGE_MAGIC))
413 return NULL;
414 nr_pages = (1 << info.order);
415
416 /* Clear private to make sure later restores on this page error out. */
417 page->private = 0;
418
419 if (is_folio)
420 kho_init_folio(page, info.order);
421 else
422 kho_init_pages(page, nr_pages);
423
424 adjust_managed_page_count(page, nr_pages);
425 return page;
426 }
427
428 /**
429 * kho_restore_folio - recreates the folio from the preserved memory.
430 * @phys: physical address of the folio.
431 *
432 * Return: pointer to the struct folio on success, NULL on failure.
433 */
kho_restore_folio(phys_addr_t phys)434 struct folio *kho_restore_folio(phys_addr_t phys)
435 {
436 struct page *page = kho_restore_page(phys, true);
437
438 return page ? page_folio(page) : NULL;
439 }
440 EXPORT_SYMBOL_GPL(kho_restore_folio);
441
442 /**
443 * kho_restore_pages - restore list of contiguous order 0 pages.
444 * @phys: physical address of the first page.
445 * @nr_pages: number of pages.
446 *
447 * Restore a contiguous list of order 0 pages that was preserved with
448 * kho_preserve_pages().
449 *
450 * Return: the first page on success, NULL on failure.
451 */
kho_restore_pages(phys_addr_t phys,unsigned long nr_pages)452 struct page *kho_restore_pages(phys_addr_t phys, unsigned long nr_pages)
453 {
454 const unsigned long start_pfn = PHYS_PFN(phys);
455 const unsigned long end_pfn = start_pfn + nr_pages;
456 unsigned long pfn = start_pfn;
457
458 while (pfn < end_pfn) {
459 const unsigned int order =
460 min(count_trailing_zeros(pfn), ilog2(end_pfn - pfn));
461 struct page *page = kho_restore_page(PFN_PHYS(pfn), false);
462
463 if (!page)
464 return NULL;
465 pfn += 1 << order;
466 }
467
468 return pfn_to_page(start_pfn);
469 }
470 EXPORT_SYMBOL_GPL(kho_restore_pages);
471
472 /*
473 * With CONFIG_DEFERRED_STRUCT_PAGE_INIT, struct pages in higher memory regions
474 * may not be initialized yet at the time KHO deserializes preserved memory.
475 * KHO uses the struct page to store metadata and a later initialization would
476 * overwrite it.
477 * Ensure all the struct pages in the preservation are
478 * initialized. kho_preserved_memory_reserve() marks the reservation as noinit
479 * to make sure they don't get re-initialized later.
480 */
kho_get_preserved_page(phys_addr_t phys,unsigned int order)481 static struct page *__init kho_get_preserved_page(phys_addr_t phys,
482 unsigned int order)
483 {
484 unsigned long pfn = PHYS_PFN(phys);
485 int nid;
486
487 if (!IS_ENABLED(CONFIG_DEFERRED_STRUCT_PAGE_INIT))
488 return pfn_to_page(pfn);
489
490 nid = early_pfn_to_nid(pfn);
491 for (unsigned long i = 0; i < (1UL << order); i++)
492 init_deferred_page(pfn + i, nid);
493
494 return pfn_to_page(pfn);
495 }
496
kho_preserved_memory_reserve(phys_addr_t phys,unsigned int order)497 static int __init kho_preserved_memory_reserve(phys_addr_t phys,
498 unsigned int order)
499 {
500 union kho_page_info info;
501 struct page *page;
502 u64 sz;
503
504 sz = 1UL << (order + PAGE_SHIFT);
505 page = kho_get_preserved_page(phys, order);
506
507 /* Reserve the memory preserved in KHO in memblock */
508 memblock_reserve(phys, sz);
509 memblock_reserved_mark_noinit(phys, sz);
510 info.magic = KHO_PAGE_MAGIC;
511 info.order = order;
512 page->private = info.page_private;
513
514 return 0;
515 }
516
517 /* Returns physical address of the preserved memory map from FDT */
kho_get_mem_map_phys(const void * fdt)518 static phys_addr_t __init kho_get_mem_map_phys(const void *fdt)
519 {
520 const void *mem_ptr;
521 int len;
522
523 mem_ptr = fdt_getprop(fdt, 0, KHO_FDT_MEMORY_MAP_PROP_NAME, &len);
524 if (!mem_ptr || len != sizeof(u64)) {
525 pr_err("failed to get preserved memory map\n");
526 return 0;
527 }
528
529 return get_unaligned((const u64 *)mem_ptr);
530 }
531
532 /*
533 * With KHO enabled, memory can become fragmented because KHO regions may
534 * be anywhere in physical address space. The scratch regions give us a
535 * safe zones that we will never see KHO allocations from. This is where we
536 * can later safely load our new kexec images into and then use the scratch
537 * area for early allocations that happen before page allocator is
538 * initialized.
539 */
540 struct kho_scratch *kho_scratch;
541 unsigned int kho_scratch_cnt;
542
543 /*
544 * The scratch areas are scaled by default as percent of memory allocated from
545 * memblock. A user can override the scale with command line parameter:
546 *
547 * kho_scratch=N%
548 *
549 * It is also possible to explicitly define size for a lowmem, a global and
550 * per-node scratch areas:
551 *
552 * kho_scratch=l[KMG],n[KMG],m[KMG]
553 *
554 * The explicit size definition takes precedence over scale definition.
555 */
556 static unsigned int scratch_scale __initdata = 200;
557 static phys_addr_t scratch_size_global __initdata;
558 static phys_addr_t scratch_size_pernode __initdata;
559 static phys_addr_t scratch_size_lowmem __initdata;
560
kho_parse_scratch_size(char * p)561 static int __init kho_parse_scratch_size(char *p)
562 {
563 size_t len;
564 unsigned long sizes[3];
565 size_t total_size = 0;
566 int i;
567
568 if (!p)
569 return -EINVAL;
570
571 len = strlen(p);
572 if (!len)
573 return -EINVAL;
574
575 /* parse nn% */
576 if (p[len - 1] == '%') {
577 /* unsigned int max is 4,294,967,295, 10 chars */
578 char s_scale[11] = {};
579 int ret = 0;
580
581 if (len > ARRAY_SIZE(s_scale))
582 return -EINVAL;
583
584 memcpy(s_scale, p, len - 1);
585 ret = kstrtouint(s_scale, 10, &scratch_scale);
586 if (!ret)
587 pr_notice("scratch scale is %d%%\n", scratch_scale);
588 return ret;
589 }
590
591 /* parse ll[KMG],mm[KMG],nn[KMG] */
592 for (i = 0; i < ARRAY_SIZE(sizes); i++) {
593 char *endp = p;
594
595 if (i > 0) {
596 if (*p != ',')
597 return -EINVAL;
598 p += 1;
599 }
600
601 sizes[i] = memparse(p, &endp);
602 if (endp == p)
603 return -EINVAL;
604 p = endp;
605 total_size += sizes[i];
606 }
607
608 if (!total_size)
609 return -EINVAL;
610
611 /* The string should be fully consumed by now. */
612 if (*p)
613 return -EINVAL;
614
615 scratch_size_lowmem = sizes[0];
616 scratch_size_global = sizes[1];
617 scratch_size_pernode = sizes[2];
618 scratch_scale = 0;
619
620 pr_notice("scratch areas: lowmem: %lluMiB global: %lluMiB pernode: %lldMiB\n",
621 (u64)(scratch_size_lowmem >> 20),
622 (u64)(scratch_size_global >> 20),
623 (u64)(scratch_size_pernode >> 20));
624
625 return 0;
626 }
627 early_param("kho_scratch", kho_parse_scratch_size);
628
scratch_size_update(void)629 static void __init scratch_size_update(void)
630 {
631 /*
632 * If fixed sizes are not provided via command line, calculate them
633 * now.
634 */
635 if (scratch_scale) {
636 phys_addr_t size;
637
638 size = memblock_reserved_kern_size(ARCH_LOW_ADDRESS_LIMIT,
639 NUMA_NO_NODE);
640 size = size * scratch_scale / 100;
641 scratch_size_lowmem = size;
642
643 size = memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE,
644 NUMA_NO_NODE);
645 size = size * scratch_scale / 100 - scratch_size_lowmem;
646 scratch_size_global = size;
647 }
648
649 /*
650 * Scratch areas are released as MIGRATE_CMA. Round them up to the right
651 * size.
652 */
653 scratch_size_lowmem = round_up(scratch_size_lowmem, SCRATCH_ALIGNMENT_BYTES);
654 scratch_size_global = round_up(scratch_size_global, SCRATCH_ALIGNMENT_BYTES);
655 }
656
scratch_size_node(int nid)657 static phys_addr_t __init scratch_size_node(int nid)
658 {
659 phys_addr_t size;
660
661 if (scratch_scale) {
662 size = memblock_reserved_kern_size(MEMBLOCK_ALLOC_ANYWHERE,
663 nid);
664 size = size * scratch_scale / 100;
665 } else {
666 size = scratch_size_pernode;
667 }
668
669 return round_up(size, SCRATCH_ALIGNMENT_BYTES);
670 }
671
672 /**
673 * kho_reserve_scratch - Reserve a contiguous chunk of memory for kexec
674 *
675 * With KHO we can preserve arbitrary pages in the system. To ensure we still
676 * have a large contiguous region of memory when we search the physical address
677 * space for target memory, let's make sure we always have a large CMA region
678 * active. This CMA region will only be used for movable pages which are not a
679 * problem for us during KHO because we can just move them somewhere else.
680 */
kho_reserve_scratch(void)681 static void __init kho_reserve_scratch(void)
682 {
683 phys_addr_t addr, size;
684 int nid, i = 0;
685
686 if (!kho_enable)
687 return;
688
689 scratch_size_update();
690
691 /* FIXME: deal with node hot-plug/remove */
692 kho_scratch_cnt = nodes_weight(node_states[N_MEMORY]) + 2;
693 size = kho_scratch_cnt * sizeof(*kho_scratch);
694 kho_scratch = memblock_alloc(size, PAGE_SIZE);
695 if (!kho_scratch) {
696 pr_err("Failed to reserve scratch array\n");
697 goto err_disable_kho;
698 }
699
700 /*
701 * reserve scratch area in low memory for lowmem allocations in the
702 * next kernel
703 */
704 size = scratch_size_lowmem;
705 addr = memblock_phys_alloc_range(size, SCRATCH_ALIGNMENT_BYTES, 0,
706 ARCH_LOW_ADDRESS_LIMIT);
707 if (!addr) {
708 pr_err("Failed to reserve lowmem scratch buffer\n");
709 goto err_free_scratch_desc;
710 }
711
712 kho_scratch[i].addr = addr;
713 kho_scratch[i].size = size;
714 i++;
715
716 /* reserve large contiguous area for allocations without nid */
717 size = scratch_size_global;
718 addr = memblock_phys_alloc(size, SCRATCH_ALIGNMENT_BYTES);
719 if (!addr) {
720 pr_err("Failed to reserve global scratch buffer\n");
721 goto err_free_scratch_areas;
722 }
723
724 kho_scratch[i].addr = addr;
725 kho_scratch[i].size = size;
726 i++;
727
728 /*
729 * Loop over nodes that have both memory and are online. Skip
730 * memoryless nodes, as we can not allocate scratch areas there.
731 */
732 for_each_node_state(nid, N_MEMORY) {
733 size = scratch_size_node(nid);
734 addr = memblock_alloc_range_nid(size, SCRATCH_ALIGNMENT_BYTES,
735 0, MEMBLOCK_ALLOC_ACCESSIBLE,
736 nid, true);
737 if (!addr) {
738 pr_err("Failed to reserve nid %d scratch buffer\n", nid);
739 goto err_free_scratch_areas;
740 }
741
742 kho_scratch[i].addr = addr;
743 kho_scratch[i].size = size;
744 i++;
745 }
746
747 return;
748
749 err_free_scratch_areas:
750 for (i--; i >= 0; i--)
751 memblock_phys_free(kho_scratch[i].addr, kho_scratch[i].size);
752 err_free_scratch_desc:
753 memblock_free(kho_scratch, kho_scratch_cnt * sizeof(*kho_scratch));
754 err_disable_kho:
755 pr_warn("Failed to reserve scratch area, disabling kexec handover\n");
756 kho_enable = false;
757 }
758
759 /**
760 * kho_add_subtree - record the physical address of a sub blob in KHO root tree.
761 * @name: name of the sub tree.
762 * @blob: the sub tree blob.
763 * @size: size of the blob in bytes.
764 *
765 * Creates a new child node named @name in KHO root FDT and records
766 * the physical address of @blob. The pages of @blob must also be preserved
767 * by KHO for the new kernel to retrieve it after kexec.
768 *
769 * A debugfs blob entry is also created at
770 * ``/sys/kernel/debug/kho/out/sub_fdts/@name`` when kernel is configured with
771 * CONFIG_KEXEC_HANDOVER_DEBUGFS
772 *
773 * Return: 0 on success, error code on failure
774 */
kho_add_subtree(const char * name,void * blob,size_t size)775 int kho_add_subtree(const char *name, void *blob, size_t size)
776 {
777 phys_addr_t phys = virt_to_phys(blob);
778 void *root_fdt = kho_out.fdt;
779 u64 size_u64 = size;
780 int err = -ENOMEM;
781 int off, fdt_err;
782
783 guard(mutex)(&kho_out.lock);
784
785 fdt_err = fdt_open_into(root_fdt, root_fdt, PAGE_SIZE);
786 if (fdt_err < 0)
787 return err;
788
789 off = fdt_add_subnode(root_fdt, 0, name);
790 if (off < 0) {
791 if (off == -FDT_ERR_EXISTS)
792 err = -EEXIST;
793 goto out_pack;
794 }
795
796 fdt_err = fdt_setprop(root_fdt, off, KHO_SUB_TREE_PROP_NAME,
797 &phys, sizeof(phys));
798 if (fdt_err < 0)
799 goto out_del_node;
800
801 fdt_err = fdt_setprop(root_fdt, off, KHO_SUB_TREE_SIZE_PROP_NAME,
802 &size_u64, sizeof(size_u64));
803 if (fdt_err < 0)
804 goto out_del_node;
805
806 WARN_ON_ONCE(kho_debugfs_blob_add(&kho_out.dbg, name, blob,
807 size, false));
808
809 err = 0;
810 goto out_pack;
811
812 out_del_node:
813 fdt_del_node(root_fdt, off);
814 out_pack:
815 fdt_pack(root_fdt);
816
817 return err;
818 }
819 EXPORT_SYMBOL_GPL(kho_add_subtree);
820
kho_remove_subtree(void * blob)821 void kho_remove_subtree(void *blob)
822 {
823 phys_addr_t target_phys = virt_to_phys(blob);
824 void *root_fdt = kho_out.fdt;
825 int off;
826 int err;
827
828 guard(mutex)(&kho_out.lock);
829
830 err = fdt_open_into(root_fdt, root_fdt, PAGE_SIZE);
831 if (err < 0)
832 return;
833
834 for (off = fdt_first_subnode(root_fdt, 0); off >= 0;
835 off = fdt_next_subnode(root_fdt, off)) {
836 const u64 *val;
837 int len;
838
839 val = fdt_getprop(root_fdt, off, KHO_SUB_TREE_PROP_NAME, &len);
840 if (!val || len != sizeof(phys_addr_t))
841 continue;
842
843 if ((phys_addr_t)*val == target_phys) {
844 fdt_del_node(root_fdt, off);
845 kho_debugfs_blob_remove(&kho_out.dbg, blob);
846 break;
847 }
848 }
849
850 fdt_pack(root_fdt);
851 }
852 EXPORT_SYMBOL_GPL(kho_remove_subtree);
853
854 /**
855 * kho_preserve_folio - preserve a folio across kexec.
856 * @folio: folio to preserve.
857 *
858 * Instructs KHO to preserve the whole folio across kexec. The order
859 * will be preserved as well.
860 *
861 * Return: 0 on success, error code on failure
862 */
kho_preserve_folio(struct folio * folio)863 int kho_preserve_folio(struct folio *folio)
864 {
865 struct kho_radix_tree *tree = &kho_out.radix_tree;
866 const unsigned long pfn = folio_pfn(folio);
867 const unsigned int order = folio_order(folio);
868
869 if (WARN_ON(kho_scratch_overlap(pfn << PAGE_SHIFT, PAGE_SIZE << order)))
870 return -EINVAL;
871
872 return kho_radix_add_page(tree, pfn, order);
873 }
874 EXPORT_SYMBOL_GPL(kho_preserve_folio);
875
876 /**
877 * kho_unpreserve_folio - unpreserve a folio.
878 * @folio: folio to unpreserve.
879 *
880 * Instructs KHO to unpreserve a folio that was preserved by
881 * kho_preserve_folio() before. The provided @folio (pfn and order)
882 * must exactly match a previously preserved folio.
883 */
kho_unpreserve_folio(struct folio * folio)884 void kho_unpreserve_folio(struct folio *folio)
885 {
886 struct kho_radix_tree *tree = &kho_out.radix_tree;
887 const unsigned long pfn = folio_pfn(folio);
888 const unsigned int order = folio_order(folio);
889
890 kho_radix_del_page(tree, pfn, order);
891 }
892 EXPORT_SYMBOL_GPL(kho_unpreserve_folio);
893
__kho_preserve_pages_order(unsigned long start_pfn,unsigned long end_pfn)894 static unsigned int __kho_preserve_pages_order(unsigned long start_pfn,
895 unsigned long end_pfn)
896 {
897 unsigned int order = min(count_trailing_zeros(start_pfn),
898 ilog2(end_pfn - start_pfn));
899
900 /*
901 * Make sure all the pages in a single preservation are in the same NUMA
902 * node. The restore machinery can not cope with a preservation spanning
903 * multiple NUMA nodes.
904 */
905 while (pfn_to_nid(start_pfn) != pfn_to_nid(start_pfn + (1UL << order) - 1))
906 order--;
907
908 return order;
909 }
910
__kho_unpreserve(struct kho_radix_tree * tree,unsigned long pfn,unsigned long end_pfn)911 static void __kho_unpreserve(struct kho_radix_tree *tree,
912 unsigned long pfn, unsigned long end_pfn)
913 {
914 unsigned int order;
915
916 while (pfn < end_pfn) {
917 order = __kho_preserve_pages_order(pfn, end_pfn);
918
919 kho_radix_del_page(tree, pfn, order);
920
921 pfn += 1 << order;
922 }
923 }
924
925 /**
926 * kho_preserve_pages - preserve contiguous pages across kexec
927 * @page: first page in the list.
928 * @nr_pages: number of pages.
929 *
930 * Preserve a contiguous list of order 0 pages. Must be restored using
931 * kho_restore_pages() to ensure the pages are restored properly as order 0.
932 *
933 * Return: 0 on success, error code on failure
934 */
kho_preserve_pages(struct page * page,unsigned long nr_pages)935 int kho_preserve_pages(struct page *page, unsigned long nr_pages)
936 {
937 struct kho_radix_tree *tree = &kho_out.radix_tree;
938 const unsigned long start_pfn = page_to_pfn(page);
939 const unsigned long end_pfn = start_pfn + nr_pages;
940 unsigned long pfn = start_pfn;
941 unsigned long failed_pfn = 0;
942 int err = 0;
943
944 if (WARN_ON(kho_scratch_overlap(start_pfn << PAGE_SHIFT,
945 nr_pages << PAGE_SHIFT))) {
946 return -EINVAL;
947 }
948
949 while (pfn < end_pfn) {
950 unsigned int order = __kho_preserve_pages_order(pfn, end_pfn);
951
952 err = kho_radix_add_page(tree, pfn, order);
953 if (err) {
954 failed_pfn = pfn;
955 break;
956 }
957
958 pfn += 1 << order;
959 }
960
961 if (err)
962 __kho_unpreserve(tree, start_pfn, failed_pfn);
963
964 return err;
965 }
966 EXPORT_SYMBOL_GPL(kho_preserve_pages);
967
968 /**
969 * kho_unpreserve_pages - unpreserve contiguous pages.
970 * @page: first page in the list.
971 * @nr_pages: number of pages.
972 *
973 * Instructs KHO to unpreserve @nr_pages contiguous pages starting from @page.
974 * This must be called with the same @page and @nr_pages as the corresponding
975 * kho_preserve_pages() call. Unpreserving arbitrary sub-ranges of larger
976 * preserved blocks is not supported.
977 */
kho_unpreserve_pages(struct page * page,unsigned long nr_pages)978 void kho_unpreserve_pages(struct page *page, unsigned long nr_pages)
979 {
980 struct kho_radix_tree *tree = &kho_out.radix_tree;
981 const unsigned long start_pfn = page_to_pfn(page);
982 const unsigned long end_pfn = start_pfn + nr_pages;
983
984 __kho_unpreserve(tree, start_pfn, end_pfn);
985 }
986 EXPORT_SYMBOL_GPL(kho_unpreserve_pages);
987
988 /* vmalloc flags KHO supports */
989 #define KHO_VMALLOC_SUPPORTED_FLAGS (VM_ALLOC | VM_ALLOW_HUGE_VMAP)
990
991 /* KHO internal flags for vmalloc preservations */
992 #define KHO_VMALLOC_ALLOC 0x0001
993 #define KHO_VMALLOC_HUGE_VMAP 0x0002
994
vmalloc_flags_to_kho(unsigned int vm_flags)995 static unsigned short vmalloc_flags_to_kho(unsigned int vm_flags)
996 {
997 unsigned short kho_flags = 0;
998
999 if (vm_flags & VM_ALLOC)
1000 kho_flags |= KHO_VMALLOC_ALLOC;
1001 if (vm_flags & VM_ALLOW_HUGE_VMAP)
1002 kho_flags |= KHO_VMALLOC_HUGE_VMAP;
1003
1004 return kho_flags;
1005 }
1006
kho_flags_to_vmalloc(unsigned short kho_flags)1007 static unsigned int kho_flags_to_vmalloc(unsigned short kho_flags)
1008 {
1009 unsigned int vm_flags = 0;
1010
1011 if (kho_flags & KHO_VMALLOC_ALLOC)
1012 vm_flags |= VM_ALLOC;
1013 if (kho_flags & KHO_VMALLOC_HUGE_VMAP)
1014 vm_flags |= VM_ALLOW_HUGE_VMAP;
1015
1016 return vm_flags;
1017 }
1018
new_vmalloc_chunk(struct kho_vmalloc_chunk * cur)1019 static struct kho_vmalloc_chunk *new_vmalloc_chunk(struct kho_vmalloc_chunk *cur)
1020 {
1021 struct kho_vmalloc_chunk *chunk;
1022 int err;
1023
1024 chunk = (struct kho_vmalloc_chunk *)get_zeroed_page(GFP_KERNEL);
1025 if (!chunk)
1026 return NULL;
1027
1028 err = kho_preserve_pages(virt_to_page(chunk), 1);
1029 if (err)
1030 goto err_free;
1031 if (cur)
1032 KHOSER_STORE_PTR(cur->hdr.next, chunk);
1033 return chunk;
1034
1035 err_free:
1036 free_page((unsigned long)chunk);
1037 return NULL;
1038 }
1039
kho_vmalloc_unpreserve_chunk(struct kho_vmalloc_chunk * chunk,unsigned short order)1040 static void kho_vmalloc_unpreserve_chunk(struct kho_vmalloc_chunk *chunk,
1041 unsigned short order)
1042 {
1043 struct kho_radix_tree *tree = &kho_out.radix_tree;
1044 unsigned long pfn = PHYS_PFN(virt_to_phys(chunk));
1045
1046 __kho_unpreserve(tree, pfn, pfn + 1);
1047
1048 for (int i = 0; i < ARRAY_SIZE(chunk->phys) && chunk->phys[i]; i++) {
1049 pfn = PHYS_PFN(chunk->phys[i]);
1050 __kho_unpreserve(tree, pfn, pfn + (1 << order));
1051 }
1052 }
1053
1054 /**
1055 * kho_preserve_vmalloc - preserve memory allocated with vmalloc() across kexec
1056 * @ptr: pointer to the area in vmalloc address space
1057 * @preservation: placeholder for preservation metadata
1058 *
1059 * Instructs KHO to preserve the area in vmalloc address space at @ptr. The
1060 * physical pages mapped at @ptr will be preserved and on successful return
1061 * @preservation will hold the physical address of a structure that describes
1062 * the preservation.
1063 *
1064 * NOTE: The memory allocated with vmalloc_node() variants cannot be reliably
1065 * restored on the same node
1066 *
1067 * Return: 0 on success, error code on failure
1068 */
kho_preserve_vmalloc(void * ptr,struct kho_vmalloc * preservation)1069 int kho_preserve_vmalloc(void *ptr, struct kho_vmalloc *preservation)
1070 {
1071 struct kho_vmalloc_chunk *chunk;
1072 struct vm_struct *vm = find_vm_area(ptr);
1073 unsigned int order, flags, nr_contig_pages;
1074 unsigned int idx = 0;
1075 int err;
1076
1077 if (!vm)
1078 return -EINVAL;
1079
1080 if (vm->flags & ~KHO_VMALLOC_SUPPORTED_FLAGS)
1081 return -EOPNOTSUPP;
1082
1083 flags = vmalloc_flags_to_kho(vm->flags);
1084 order = get_vm_area_page_order(vm);
1085
1086 chunk = new_vmalloc_chunk(NULL);
1087 if (!chunk)
1088 return -ENOMEM;
1089 KHOSER_STORE_PTR(preservation->first, chunk);
1090
1091 nr_contig_pages = (1 << order);
1092 for (int i = 0; i < vm->nr_pages; i += nr_contig_pages) {
1093 phys_addr_t phys = page_to_phys(vm->pages[i]);
1094
1095 err = kho_preserve_pages(vm->pages[i], nr_contig_pages);
1096 if (err)
1097 goto err_free;
1098
1099 chunk->phys[idx++] = phys;
1100 if (idx == ARRAY_SIZE(chunk->phys)) {
1101 chunk = new_vmalloc_chunk(chunk);
1102 if (!chunk) {
1103 err = -ENOMEM;
1104 goto err_free;
1105 }
1106 idx = 0;
1107 }
1108 }
1109
1110 preservation->total_pages = vm->nr_pages;
1111 preservation->flags = flags;
1112 preservation->order = order;
1113
1114 return 0;
1115
1116 err_free:
1117 kho_unpreserve_vmalloc(preservation);
1118 return err;
1119 }
1120 EXPORT_SYMBOL_GPL(kho_preserve_vmalloc);
1121
1122 /**
1123 * kho_unpreserve_vmalloc - unpreserve memory allocated with vmalloc()
1124 * @preservation: preservation metadata returned by kho_preserve_vmalloc()
1125 *
1126 * Instructs KHO to unpreserve the area in vmalloc address space that was
1127 * previously preserved with kho_preserve_vmalloc().
1128 */
kho_unpreserve_vmalloc(struct kho_vmalloc * preservation)1129 void kho_unpreserve_vmalloc(struct kho_vmalloc *preservation)
1130 {
1131 struct kho_vmalloc_chunk *chunk = KHOSER_LOAD_PTR(preservation->first);
1132
1133 while (chunk) {
1134 struct kho_vmalloc_chunk *tmp = chunk;
1135
1136 kho_vmalloc_unpreserve_chunk(chunk, preservation->order);
1137
1138 chunk = KHOSER_LOAD_PTR(chunk->hdr.next);
1139 free_page((unsigned long)tmp);
1140 }
1141 }
1142 EXPORT_SYMBOL_GPL(kho_unpreserve_vmalloc);
1143
1144 /**
1145 * kho_restore_vmalloc - recreates and populates an area in vmalloc address
1146 * space from the preserved memory.
1147 * @preservation: preservation metadata.
1148 *
1149 * Recreates an area in vmalloc address space and populates it with memory that
1150 * was preserved using kho_preserve_vmalloc().
1151 *
1152 * Return: pointer to the area in the vmalloc address space, NULL on failure.
1153 */
kho_restore_vmalloc(const struct kho_vmalloc * preservation)1154 void *kho_restore_vmalloc(const struct kho_vmalloc *preservation)
1155 {
1156 struct kho_vmalloc_chunk *chunk = KHOSER_LOAD_PTR(preservation->first);
1157 kasan_vmalloc_flags_t kasan_flags = KASAN_VMALLOC_PROT_NORMAL;
1158 unsigned int align, order, shift, vm_flags;
1159 unsigned long total_pages, contig_pages;
1160 unsigned long addr, size;
1161 struct vm_struct *area;
1162 struct page **pages;
1163 unsigned int idx = 0;
1164 int err;
1165
1166 vm_flags = kho_flags_to_vmalloc(preservation->flags);
1167 if (vm_flags & ~KHO_VMALLOC_SUPPORTED_FLAGS)
1168 return NULL;
1169
1170 total_pages = preservation->total_pages;
1171 pages = kvmalloc_objs(*pages, total_pages);
1172 if (!pages)
1173 return NULL;
1174 order = preservation->order;
1175 contig_pages = (1 << order);
1176 shift = PAGE_SHIFT + order;
1177 align = 1 << shift;
1178
1179 while (chunk) {
1180 struct page *page;
1181
1182 for (int i = 0; i < ARRAY_SIZE(chunk->phys) && chunk->phys[i]; i++) {
1183 phys_addr_t phys = chunk->phys[i];
1184
1185 if (idx + contig_pages > total_pages)
1186 goto err_free_pages_array;
1187
1188 page = kho_restore_pages(phys, contig_pages);
1189 if (!page)
1190 goto err_free_pages_array;
1191
1192 for (int j = 0; j < contig_pages; j++)
1193 pages[idx++] = page + j;
1194
1195 phys += contig_pages * PAGE_SIZE;
1196 }
1197
1198 page = kho_restore_pages(virt_to_phys(chunk), 1);
1199 if (!page)
1200 goto err_free_pages_array;
1201 chunk = KHOSER_LOAD_PTR(chunk->hdr.next);
1202 __free_page(page);
1203 }
1204
1205 if (idx != total_pages)
1206 goto err_free_pages_array;
1207
1208 area = __get_vm_area_node(total_pages * PAGE_SIZE, align, shift,
1209 vm_flags | VM_UNINITIALIZED,
1210 VMALLOC_START, VMALLOC_END,
1211 NUMA_NO_NODE, GFP_KERNEL,
1212 __builtin_return_address(0));
1213 if (!area)
1214 goto err_free_pages_array;
1215
1216 addr = (unsigned long)area->addr;
1217 size = get_vm_area_size(area);
1218 err = vmap_pages_range(addr, addr + size, PAGE_KERNEL, pages, shift);
1219 if (err)
1220 goto err_free_vm_area;
1221
1222 area->nr_pages = total_pages;
1223 area->pages = pages;
1224
1225 if (vm_flags & VM_ALLOC)
1226 kasan_flags |= KASAN_VMALLOC_VM_ALLOC;
1227
1228 area->addr = kasan_unpoison_vmalloc(area->addr, total_pages * PAGE_SIZE,
1229 kasan_flags);
1230 clear_vm_uninitialized_flag(area);
1231
1232 return area->addr;
1233
1234 err_free_vm_area:
1235 free_vm_area(area);
1236 err_free_pages_array:
1237 kvfree(pages);
1238 return NULL;
1239 }
1240 EXPORT_SYMBOL_GPL(kho_restore_vmalloc);
1241
1242 /**
1243 * kho_alloc_preserve - Allocate, zero, and preserve memory.
1244 * @size: The number of bytes to allocate.
1245 *
1246 * Allocates a physically contiguous block of zeroed pages that is large
1247 * enough to hold @size bytes. The allocated memory is then registered with
1248 * KHO for preservation across a kexec.
1249 *
1250 * Note: The actual allocated size will be rounded up to the nearest
1251 * power-of-two page boundary.
1252 *
1253 * @return A virtual pointer to the allocated and preserved memory on success,
1254 * or an ERR_PTR() encoded error on failure.
1255 */
kho_alloc_preserve(size_t size)1256 void *kho_alloc_preserve(size_t size)
1257 {
1258 struct folio *folio;
1259 int order, ret;
1260
1261 if (!size)
1262 return ERR_PTR(-EINVAL);
1263
1264 order = get_order(size);
1265 if (order > MAX_PAGE_ORDER)
1266 return ERR_PTR(-E2BIG);
1267
1268 folio = folio_alloc(GFP_KERNEL | __GFP_ZERO, order);
1269 if (!folio)
1270 return ERR_PTR(-ENOMEM);
1271
1272 ret = kho_preserve_folio(folio);
1273 if (ret) {
1274 folio_put(folio);
1275 return ERR_PTR(ret);
1276 }
1277
1278 return folio_address(folio);
1279 }
1280 EXPORT_SYMBOL_GPL(kho_alloc_preserve);
1281
1282 /**
1283 * kho_unpreserve_free - Unpreserve and free memory.
1284 * @mem: Pointer to the memory allocated by kho_alloc_preserve().
1285 *
1286 * Unregisters the memory from KHO preservation and frees the underlying
1287 * pages back to the system. This function should be called to clean up
1288 * memory allocated with kho_alloc_preserve().
1289 */
kho_unpreserve_free(void * mem)1290 void kho_unpreserve_free(void *mem)
1291 {
1292 struct folio *folio;
1293
1294 if (!mem)
1295 return;
1296
1297 folio = virt_to_folio(mem);
1298 kho_unpreserve_folio(folio);
1299 folio_put(folio);
1300 }
1301 EXPORT_SYMBOL_GPL(kho_unpreserve_free);
1302
1303 /**
1304 * kho_restore_free - Restore and free memory after kexec.
1305 * @mem: Pointer to the memory (in the new kernel's address space)
1306 * that was allocated by the old kernel.
1307 *
1308 * This function is intended to be called in the new kernel (post-kexec)
1309 * to take ownership of and free a memory region that was preserved by the
1310 * old kernel using kho_alloc_preserve().
1311 *
1312 * It first restores the pages from KHO (using their physical address)
1313 * and then frees the pages back to the new kernel's page allocator.
1314 */
kho_restore_free(void * mem)1315 void kho_restore_free(void *mem)
1316 {
1317 struct folio *folio;
1318
1319 if (!mem)
1320 return;
1321
1322 folio = kho_restore_folio(__pa(mem));
1323 if (!WARN_ON(!folio))
1324 folio_put(folio);
1325 }
1326 EXPORT_SYMBOL_GPL(kho_restore_free);
1327
1328 struct kho_in {
1329 phys_addr_t fdt_phys;
1330 phys_addr_t scratch_phys;
1331 char previous_release[__NEW_UTS_LEN + 1];
1332 u32 kexec_count;
1333 struct kho_debugfs dbg;
1334 };
1335
1336 static struct kho_in kho_in = {
1337 };
1338
kho_get_fdt(void)1339 static const void *kho_get_fdt(void)
1340 {
1341 return kho_in.fdt_phys ? phys_to_virt(kho_in.fdt_phys) : NULL;
1342 }
1343
1344 /**
1345 * is_kho_boot - check if current kernel was booted via KHO-enabled
1346 * kexec
1347 *
1348 * This function checks if the current kernel was loaded through a kexec
1349 * operation with KHO enabled, by verifying that a valid KHO FDT
1350 * was passed.
1351 *
1352 * Note: This function returns reliable results only after
1353 * kho_populate() has been called during early boot. Before that,
1354 * it may return false even if KHO data is present.
1355 *
1356 * Return: true if booted via KHO-enabled kexec, false otherwise
1357 */
is_kho_boot(void)1358 bool is_kho_boot(void)
1359 {
1360 return !!kho_get_fdt();
1361 }
1362 EXPORT_SYMBOL_GPL(is_kho_boot);
1363
1364 /**
1365 * kho_retrieve_subtree - retrieve a preserved sub blob by its name.
1366 * @name: the name of the sub blob passed to kho_add_subtree().
1367 * @phys: if found, the physical address of the sub blob is stored in @phys.
1368 * @size: if not NULL and found, the size of the sub blob is stored in @size.
1369 *
1370 * Retrieve a preserved sub blob named @name and store its physical
1371 * address in @phys and optionally its size in @size.
1372 *
1373 * Return: 0 on success, error code on failure
1374 */
kho_retrieve_subtree(const char * name,phys_addr_t * phys,size_t * size)1375 int kho_retrieve_subtree(const char *name, phys_addr_t *phys, size_t *size)
1376 {
1377 const void *fdt = kho_get_fdt();
1378 const u64 *val;
1379 int offset, len;
1380
1381 if (!fdt)
1382 return -ENOENT;
1383
1384 if (!phys)
1385 return -EINVAL;
1386
1387 offset = fdt_subnode_offset(fdt, 0, name);
1388 if (offset < 0)
1389 return -ENOENT;
1390
1391 val = fdt_getprop(fdt, offset, KHO_SUB_TREE_PROP_NAME, &len);
1392 if (!val || len != sizeof(*val))
1393 return -EINVAL;
1394
1395 *phys = (phys_addr_t)*val;
1396
1397 val = fdt_getprop(fdt, offset, KHO_SUB_TREE_SIZE_PROP_NAME, &len);
1398 if (!val || len != sizeof(*val)) {
1399 pr_warn("broken KHO subnode '%s': missing or invalid blob-size property\n",
1400 name);
1401 return -EINVAL;
1402 }
1403
1404 if (size)
1405 *size = (size_t)*val;
1406
1407 return 0;
1408 }
1409 EXPORT_SYMBOL_GPL(kho_retrieve_subtree);
1410
kho_mem_retrieve(const void * fdt)1411 static int __init kho_mem_retrieve(const void *fdt)
1412 {
1413 struct kho_radix_tree tree;
1414 const phys_addr_t *mem;
1415 int len;
1416
1417 /* Retrieve the KHO radix tree from passed-in FDT. */
1418 mem = fdt_getprop(fdt, 0, KHO_FDT_MEMORY_MAP_PROP_NAME, &len);
1419
1420 if (!mem || len != sizeof(*mem)) {
1421 pr_err("failed to get preserved KHO memory tree\n");
1422 return -ENOENT;
1423 }
1424
1425 if (!*mem)
1426 return -EINVAL;
1427
1428 tree.root = phys_to_virt(*mem);
1429 mutex_init(&tree.lock);
1430 return kho_radix_walk_tree(&tree, kho_preserved_memory_reserve);
1431 }
1432
kho_out_fdt_setup(void)1433 static __init int kho_out_fdt_setup(void)
1434 {
1435 struct kho_radix_tree *tree = &kho_out.radix_tree;
1436 void *root = kho_out.fdt;
1437 u64 preserved_mem_tree_pa;
1438 int err;
1439
1440 err = fdt_create(root, PAGE_SIZE);
1441 err |= fdt_finish_reservemap(root);
1442 err |= fdt_begin_node(root, "");
1443 err |= fdt_property_string(root, "compatible", KHO_FDT_COMPATIBLE);
1444
1445 preserved_mem_tree_pa = virt_to_phys(tree->root);
1446
1447 err |= fdt_property(root, KHO_FDT_MEMORY_MAP_PROP_NAME,
1448 &preserved_mem_tree_pa,
1449 sizeof(preserved_mem_tree_pa));
1450
1451 err |= fdt_end_node(root);
1452 err |= fdt_finish(root);
1453
1454 return err;
1455 }
1456
kho_in_kexec_metadata(void)1457 static void __init kho_in_kexec_metadata(void)
1458 {
1459 struct kho_kexec_metadata *metadata;
1460 phys_addr_t metadata_phys;
1461 size_t blob_size;
1462 int err;
1463
1464 err = kho_retrieve_subtree(KHO_METADATA_NODE_NAME, &metadata_phys,
1465 &blob_size);
1466 if (err)
1467 /* This is fine, previous kernel didn't export metadata */
1468 return;
1469
1470 /* Check that, at least, "version" is present */
1471 if (blob_size < sizeof(u32)) {
1472 pr_warn("kexec-metadata blob too small (%zu bytes)\n",
1473 blob_size);
1474 return;
1475 }
1476
1477 metadata = phys_to_virt(metadata_phys);
1478
1479 if (metadata->version != KHO_KEXEC_METADATA_VERSION) {
1480 pr_warn("kexec-metadata version %u not supported (expected %u)\n",
1481 metadata->version, KHO_KEXEC_METADATA_VERSION);
1482 return;
1483 }
1484
1485 if (blob_size < sizeof(*metadata)) {
1486 pr_warn("kexec-metadata blob too small for v%u (%zu < %zu)\n",
1487 metadata->version, blob_size, sizeof(*metadata));
1488 return;
1489 }
1490
1491 /*
1492 * Copy data to the kernel structure that will persist during
1493 * kernel lifetime.
1494 */
1495 kho_in.kexec_count = metadata->kexec_count;
1496 strscpy(kho_in.previous_release, metadata->previous_release,
1497 sizeof(kho_in.previous_release));
1498
1499 pr_info("exec from: %s (count %u)\n",
1500 kho_in.previous_release, kho_in.kexec_count);
1501 }
1502
1503 /*
1504 * Create kexec metadata to pass kernel version and boot count to the
1505 * next kernel. This keeps the core KHO ABI minimal and allows the
1506 * metadata format to evolve independently.
1507 */
kho_out_kexec_metadata(void)1508 static __init int kho_out_kexec_metadata(void)
1509 {
1510 struct kho_kexec_metadata *metadata;
1511 int err;
1512
1513 metadata = kho_alloc_preserve(sizeof(*metadata));
1514 if (IS_ERR(metadata))
1515 return PTR_ERR(metadata);
1516
1517 metadata->version = KHO_KEXEC_METADATA_VERSION;
1518 strscpy(metadata->previous_release, init_uts_ns.name.release,
1519 sizeof(metadata->previous_release));
1520 /* kho_in.kexec_count is set to 0 on cold boot */
1521 metadata->kexec_count = kho_in.kexec_count + 1;
1522
1523 err = kho_add_subtree(KHO_METADATA_NODE_NAME, metadata,
1524 sizeof(*metadata));
1525 if (err)
1526 kho_unpreserve_free(metadata);
1527
1528 return err;
1529 }
1530
kho_kexec_metadata_init(const void * fdt)1531 static int __init kho_kexec_metadata_init(const void *fdt)
1532 {
1533 int err;
1534
1535 if (fdt)
1536 kho_in_kexec_metadata();
1537
1538 /* Populate kexec metadata for the possible next kexec */
1539 err = kho_out_kexec_metadata();
1540 if (err)
1541 pr_warn("failed to initialize kexec-metadata subtree: %d\n",
1542 err);
1543
1544 return err;
1545 }
1546
kho_init(void)1547 static __init int kho_init(void)
1548 {
1549 struct kho_radix_tree *tree = &kho_out.radix_tree;
1550 const void *fdt = kho_get_fdt();
1551 int err = 0;
1552
1553 if (!kho_enable)
1554 return 0;
1555
1556 tree->root = kzalloc(PAGE_SIZE, GFP_KERNEL);
1557 if (!tree->root) {
1558 err = -ENOMEM;
1559 goto err_free_scratch;
1560 }
1561
1562 kho_out.fdt = kho_alloc_preserve(PAGE_SIZE);
1563 if (IS_ERR(kho_out.fdt)) {
1564 err = PTR_ERR(kho_out.fdt);
1565 goto err_free_kho_radix_tree_root;
1566 }
1567
1568 err = kho_debugfs_init();
1569 if (err)
1570 goto err_free_fdt;
1571
1572 err = kho_out_debugfs_init(&kho_out.dbg);
1573 if (err)
1574 goto err_free_fdt;
1575
1576 err = kho_out_fdt_setup();
1577 if (err)
1578 goto err_free_fdt;
1579
1580 err = kho_kexec_metadata_init(fdt);
1581 if (err)
1582 goto err_free_fdt;
1583
1584 if (fdt) {
1585 kho_in_debugfs_init(&kho_in.dbg, fdt);
1586 return 0;
1587 }
1588
1589 for (int i = 0; i < kho_scratch_cnt; i++) {
1590 unsigned long base_pfn = PHYS_PFN(kho_scratch[i].addr);
1591 unsigned long count = kho_scratch[i].size >> PAGE_SHIFT;
1592 unsigned long pfn;
1593
1594 /*
1595 * When debug_pagealloc is enabled, __free_pages() clears the
1596 * corresponding PRESENT bit in the kernel page table.
1597 * Subsequent kmemleak scans of these pages cause the
1598 * non-PRESENT page faults.
1599 * Mark scratch areas with kmemleak_ignore_phys() to exclude
1600 * them from kmemleak scanning.
1601 */
1602 kmemleak_ignore_phys(kho_scratch[i].addr);
1603 for (pfn = base_pfn; pfn < base_pfn + count;
1604 pfn += pageblock_nr_pages)
1605 init_cma_reserved_pageblock(pfn_to_page(pfn));
1606 }
1607
1608 WARN_ON_ONCE(kho_debugfs_blob_add(&kho_out.dbg, "fdt",
1609 kho_out.fdt,
1610 fdt_totalsize(kho_out.fdt), true));
1611
1612 return 0;
1613
1614 err_free_fdt:
1615 kho_unpreserve_free(kho_out.fdt);
1616 err_free_kho_radix_tree_root:
1617 kfree(tree->root);
1618 tree->root = NULL;
1619 err_free_scratch:
1620 kho_out.fdt = NULL;
1621 for (int i = 0; i < kho_scratch_cnt; i++) {
1622 void *start = __va(kho_scratch[i].addr);
1623 void *end = start + kho_scratch[i].size;
1624
1625 free_reserved_area(start, end, -1, "");
1626 }
1627 kho_enable = false;
1628 return err;
1629 }
1630 fs_initcall(kho_init);
1631
kho_memory_init(void)1632 void __init kho_memory_init(void)
1633 {
1634 if (kho_in.scratch_phys) {
1635 kho_scratch = phys_to_virt(kho_in.scratch_phys);
1636
1637 if (kho_mem_retrieve(kho_get_fdt()))
1638 kho_in.fdt_phys = 0;
1639 } else {
1640 kho_reserve_scratch();
1641 }
1642 }
1643
kho_populate(phys_addr_t fdt_phys,u64 fdt_len,phys_addr_t scratch_phys,u64 scratch_len)1644 void __init kho_populate(phys_addr_t fdt_phys, u64 fdt_len,
1645 phys_addr_t scratch_phys, u64 scratch_len)
1646 {
1647 unsigned int scratch_cnt = scratch_len / sizeof(*kho_scratch);
1648 struct kho_scratch *scratch = NULL;
1649 phys_addr_t mem_map_phys;
1650 void *fdt = NULL;
1651 bool populated = false;
1652 int err;
1653
1654 /* Validate the input FDT */
1655 fdt = early_memremap(fdt_phys, fdt_len);
1656 if (!fdt) {
1657 pr_warn("setup: failed to memremap FDT (0x%llx)\n", fdt_phys);
1658 goto report;
1659 }
1660 err = fdt_check_header(fdt);
1661 if (err) {
1662 pr_warn("setup: handover FDT (0x%llx) is invalid: %d\n",
1663 fdt_phys, err);
1664 goto unmap_fdt;
1665 }
1666 err = fdt_node_check_compatible(fdt, 0, KHO_FDT_COMPATIBLE);
1667 if (err) {
1668 pr_warn("setup: handover FDT (0x%llx) is incompatible with '%s': %d\n",
1669 fdt_phys, KHO_FDT_COMPATIBLE, err);
1670 goto unmap_fdt;
1671 }
1672
1673 mem_map_phys = kho_get_mem_map_phys(fdt);
1674 if (!mem_map_phys)
1675 goto unmap_fdt;
1676
1677 scratch = early_memremap(scratch_phys, scratch_len);
1678 if (!scratch) {
1679 pr_warn("setup: failed to memremap scratch (phys=0x%llx, len=%lld)\n",
1680 scratch_phys, scratch_len);
1681 goto unmap_fdt;
1682 }
1683
1684 /*
1685 * We pass a safe contiguous blocks of memory to use for early boot
1686 * purporses from the previous kernel so that we can resize the
1687 * memblock array as needed.
1688 */
1689 for (int i = 0; i < scratch_cnt; i++) {
1690 struct kho_scratch *area = &scratch[i];
1691 u64 size = area->size;
1692
1693 memblock_add(area->addr, size);
1694 err = memblock_mark_kho_scratch(area->addr, size);
1695 if (err) {
1696 pr_warn("failed to mark the scratch region 0x%pa+0x%pa: %pe",
1697 &area->addr, &size, ERR_PTR(err));
1698 goto unmap_scratch;
1699 }
1700 pr_debug("Marked 0x%pa+0x%pa as scratch", &area->addr, &size);
1701 }
1702
1703 memblock_reserve(scratch_phys, scratch_len);
1704
1705 /*
1706 * Now that we have a viable region of scratch memory, let's tell
1707 * the memblocks allocator to only use that for any allocations.
1708 * That way we ensure that nothing scribbles over in use data while
1709 * we initialize the page tables which we will need to ingest all
1710 * memory reservations from the previous kernel.
1711 */
1712 memblock_set_kho_scratch_only();
1713
1714 kho_in.fdt_phys = fdt_phys;
1715 kho_in.scratch_phys = scratch_phys;
1716 kho_scratch_cnt = scratch_cnt;
1717
1718 populated = true;
1719 pr_info("found kexec handover data.\n");
1720
1721 unmap_scratch:
1722 early_memunmap(scratch, scratch_len);
1723 unmap_fdt:
1724 early_memunmap(fdt, fdt_len);
1725 report:
1726 if (!populated)
1727 pr_warn("disabling KHO revival\n");
1728 }
1729
1730 /* Helper functions for kexec_file_load */
1731
kho_fill_kimage(struct kimage * image)1732 int kho_fill_kimage(struct kimage *image)
1733 {
1734 ssize_t scratch_size;
1735 int err = 0;
1736 struct kexec_buf scratch;
1737
1738 if (!kho_enable || image->type == KEXEC_TYPE_CRASH)
1739 return 0;
1740
1741 image->kho.fdt = virt_to_phys(kho_out.fdt);
1742
1743 scratch_size = sizeof(*kho_scratch) * kho_scratch_cnt;
1744 scratch = (struct kexec_buf){
1745 .image = image,
1746 .buffer = kho_scratch,
1747 .bufsz = scratch_size,
1748 .mem = KEXEC_BUF_MEM_UNKNOWN,
1749 .memsz = scratch_size,
1750 .buf_align = SZ_64K, /* Makes it easier to map */
1751 .buf_max = ULONG_MAX,
1752 .top_down = true,
1753 };
1754 err = kexec_add_buffer(&scratch);
1755 if (err)
1756 return err;
1757 image->kho.scratch = &image->segment[image->nr_segments - 1];
1758
1759 return 0;
1760 }
1761
kho_walk_scratch(struct kexec_buf * kbuf,int (* func)(struct resource *,void *))1762 static int kho_walk_scratch(struct kexec_buf *kbuf,
1763 int (*func)(struct resource *, void *))
1764 {
1765 int ret = 0;
1766 int i;
1767
1768 for (i = 0; i < kho_scratch_cnt; i++) {
1769 struct resource res = {
1770 .start = kho_scratch[i].addr,
1771 .end = kho_scratch[i].addr + kho_scratch[i].size - 1,
1772 };
1773
1774 /* Try to fit the kimage into our KHO scratch region */
1775 ret = func(&res, kbuf);
1776 if (ret)
1777 break;
1778 }
1779
1780 return ret;
1781 }
1782
kho_locate_mem_hole(struct kexec_buf * kbuf,int (* func)(struct resource *,void *))1783 int kho_locate_mem_hole(struct kexec_buf *kbuf,
1784 int (*func)(struct resource *, void *))
1785 {
1786 int ret;
1787
1788 if (!kho_enable || kbuf->image->type == KEXEC_TYPE_CRASH)
1789 return 1;
1790
1791 ret = kho_walk_scratch(kbuf, func);
1792
1793 return ret == 1 ? 0 : -EADDRNOTAVAIL;
1794 }
1795