Introduce the `include/linux/kho/abi/kexec_handover.h` header file, which defines the stable ABI for the KHO mechanism. This header specifies how preserved data is passed between kernels using an FDT. The ABI contract includes the FDT structure, node properties, and the "kho-v1" compatible string. By centralizing these definitions, this header serves as the foundational agreement for inter-kernel communication of preserved states, ensuring forward compatibility and preventing misinterpretation of data across kexec transitions. Since the ABI definitions are now centralized in the header files, the YAML files that previously described the FDT interfaces are redundant. These redundant files have therefore been removed. Signed-off-by: Jason Miu --- Documentation/core-api/kho/bindings/kho.yaml | 43 ---------- .../core-api/kho/bindings/sub-fdt.yaml | 27 ------ Documentation/core-api/kho/concepts.rst | 13 +++ Documentation/core-api/kho/fdt.rst | 79 +++-------------- include/linux/kho/abi/kexec_handover.h | 84 +++++++++++++++++++ kernel/liveupdate/kexec_handover.c | 19 ++--- 6 files changed, 116 insertions(+), 149 deletions(-) delete mode 100644 Documentation/core-api/kho/bindings/kho.yaml delete mode 100644 Documentation/core-api/kho/bindings/sub-fdt.yaml create mode 100644 include/linux/kho/abi/kexec_handover.h diff --git a/Documentation/core-api/kho/bindings/kho.yaml b/Documentation/core-api/kho/bindings/kho.yaml deleted file mode 100644 index 11e8ab7b219d..000000000000 --- a/Documentation/core-api/kho/bindings/kho.yaml +++ /dev/null @@ -1,43 +0,0 @@ -# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -%YAML 1.2 ---- -title: Kexec HandOver (KHO) root tree - -maintainers: - - Mike Rapoport - - Changyuan Lyu - -description: | - System memory preserved by KHO across kexec. - -properties: - compatible: - enum: - - kho-v1 - - preserved-memory-map: - description: | - physical address (u64) of an in-memory structure describing all preserved - folios and memory ranges. - -patternProperties: - "$[0-9a-f_]+^": - $ref: sub-fdt.yaml# - description: physical address of a KHO user's own FDT. - -required: - - compatible - - preserved-memory-map - -additionalProperties: false - -examples: - - | - kho { - compatible = "kho-v1"; - preserved-memory-map = <0xf0be16 0x1000000>; - - memblock { - fdt = <0x80cc16 0x1000000>; - }; - }; diff --git a/Documentation/core-api/kho/bindings/sub-fdt.yaml b/Documentation/core-api/kho/bindings/sub-fdt.yaml deleted file mode 100644 index b9a3d2d24850..000000000000 --- a/Documentation/core-api/kho/bindings/sub-fdt.yaml +++ /dev/null @@ -1,27 +0,0 @@ -# SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause) -%YAML 1.2 ---- -title: KHO users' FDT address - -maintainers: - - Mike Rapoport - - Changyuan Lyu - -description: | - Physical address of an FDT blob registered by a KHO user. - -properties: - fdt: - description: | - physical address (u64) of an FDT blob. - -required: - - fdt - -additionalProperties: false - -examples: - - | - memblock { - fdt = <0x80cc16 0x1000000>; - }; diff --git a/Documentation/core-api/kho/concepts.rst b/Documentation/core-api/kho/concepts.rst index d626d1dbd678..e96893937286 100644 --- a/Documentation/core-api/kho/concepts.rst +++ b/Documentation/core-api/kho/concepts.rst @@ -72,3 +72,16 @@ Public API ========== .. kernel-doc:: kernel/liveupdate/kexec_handover.c :export: + +Internal API +============ +.. kernel-doc:: kernel/liveupdate/kexec_handover_internal.h + +.. kernel-doc:: kernel/liveupdate/kexec_handover.c + :internal: + +.. kernel-doc:: kernel/liveupdate/kexec_handover_debugfs.c + :internal: + +.. kernel-doc:: kernel/liveupdate/kexec_handover_debug.c + :internal: diff --git a/Documentation/core-api/kho/fdt.rst b/Documentation/core-api/kho/fdt.rst index 62505285d60d..4e080ccc420e 100644 --- a/Documentation/core-api/kho/fdt.rst +++ b/Documentation/core-api/kho/fdt.rst @@ -4,77 +4,18 @@ KHO FDT ======= -KHO uses the flattened device tree (FDT) container format and libfdt -library to create and parse the data that is passed between the -kernels. The properties in KHO FDT are stored in native format. -It includes the physical address of an in-memory structure describing -all preserved memory regions, as well as physical addresses of KHO users' -own FDTs. Interpreting those sub FDTs is the responsibility of KHO users. +Kexec Handover ABI +================== -KHO nodes and properties -======================== +KHO uses the FDT to pass data between kernels. The exact structure of +this FDT is a stable contract between kernels and is documented +directly in the ABI header file. -Property ``preserved-memory-map`` ---------------------------------- +.. kernel-doc:: include/linux/kho/abi/kexec_handover.h + :doc: Kexec Handover ABI -KHO saves a special property named ``preserved-memory-map`` under the root node. -This node contains the physical address of an in-memory structure for KHO to -preserve memory regions across kexec. - -Property ``compatible`` ------------------------ - -The ``compatible`` property determines compatibility between the kernel -that created the KHO FDT and the kernel that attempts to load it. -If the kernel that loads the KHO FDT is not compatible with it, the entire -KHO process will be bypassed. - -Property ``fdt`` ----------------- - -Generally, a KHO user serialize its state into its own FDT and instructs -KHO to preserve the underlying memory, such that after kexec, the new kernel -can recover its state from the preserved FDT. - -A KHO user thus can create a node in KHO root tree and save the physical address -of its own FDT in that node's property ``fdt`` . - -Examples +See Also ======== -The following example demonstrates KHO FDT that preserves two memory -regions created with ``reserve_mem`` kernel command line parameter:: - - /dts-v1/; - - / { - compatible = "kho-v1"; - - preserved-memory-map = <0x40be16 0x1000000>; - - memblock { - fdt = <0x1517 0x1000000>; - }; - }; - -where the ``memblock`` node contains an FDT that is requested by the -subsystem memblock for preservation. The FDT contains the following -serialized data:: - - /dts-v1/; - - / { - compatible = "memblock-v1"; - - n1 { - compatible = "reserve-mem-v1"; - start = <0xc06b 0x4000000>; - size = <0x04 0x00>; - }; - - n2 { - compatible = "reserve-mem-v1"; - start = <0xc067 0x4000000>; - size = <0x04 0x00>; - }; - }; +- :doc:`/admin-guide/mm/kho` +- :doc:`/core-api/kho/concepts` diff --git a/include/linux/kho/abi/kexec_handover.h b/include/linux/kho/abi/kexec_handover.h new file mode 100644 index 000000000000..d78df2d44cb6 --- /dev/null +++ b/include/linux/kho/abi/kexec_handover.h @@ -0,0 +1,84 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ + +/* + * Copyright (C) 2023 Alexander Graf + * Copyright (C) 2025 Microsoft Corporation, Mike Rapoport + * Copyright (C) 2025 Google LLC, Changyuan Lyu + * Copyright (C) 2025 Google LLC, Jason Miu + */ + +#ifndef _LINUX_KHO_ABI_KEXEC_HANDOVER_H +#define _LINUX_KHO_ABI_KEXEC_HANDOVER_H + +/** + * DOC: Kexec Handover ABI + * + * This header defines the stable ABI for passing preserved data from one kernel + * to the next using a Flattened Device Tree (FDT). The first kernel creates an + * FDT which is then passed to the next kernel during a kexec handover. + * + * This interface is a contract. Any modification to the FDT structure, node + * properties, compatible string, or the layout of the data structures + * referenced here constitutes a breaking change. Such changes require + * incrementing the version number in KHO_FDT_COMPATIBLE to prevent a new kernel + * from misinterpreting data from an older kernel. Changes are allowed provided + * the compatibility version is incremented; however, backward/forward + * compatibility is only guaranteed for kernels supporting the same ABI version. + * + * FDT Structure Overview: + * The FDT serves as a central registry for physical + * addresses of preserved data structures and sub-FDTs. The first kernel + * populates this FDT with references to memory regions and other FDTs that + * need to persist across the kexec transition. The subsequent kernel then + * parses this FDT to locate and restore the preserved data.:: + * + * / { + * compatible = "kho-v1"; + * + * preserved-memory-map = <0x...>; + * + * { + * fdt = <0x...>; + * }; + * + * { + * fdt = <0x...>; + * }; + * ... ... + * { + * fdt = <0x...>; + * }; + * }; + * + * Root KHO Node (/): + * - compatible: "kho-v1" + * + * Indentifies the overall KHO ABI version. + * + * - preserved-memory-map: u64 + * + * Physical memory address pointing to the root of the + * preserved memory map data structure. + * + * Subnodes (): + * Subnodes can also be added to the root node to + * describe other preserved data blobs. The + * is provided by the subsystem that uses KHO for preserving its + * data. + * + * - fdt: u64 + * + * Physical address pointing to a subnode FDT blob that is also + * being preserved. + */ + +/* The compatible string for the KHO FDT root node. */ +#define KHO_FDT_COMPATIBLE "kho-v1" + +/* The FDT property for the preserved memory map. */ +#define KHO_FDT_MEMORY_MAP_PROP_NAME "preserved-memory-map" + +/* The FDT property for sub-FDTs. */ +#define KHO_FDT_SUB_TREE_PROP_NAME "fdt" + +#endif /* _LINUX_KHO_ABI_KEXEC_HANDOVER_H */ diff --git a/kernel/liveupdate/kexec_handover.c b/kernel/liveupdate/kexec_handover.c index 9dc51fab604f..d3d02a9ea391 100644 --- a/kernel/liveupdate/kexec_handover.c +++ b/kernel/liveupdate/kexec_handover.c @@ -15,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -33,10 +34,7 @@ #include "../kexec_internal.h" #include "kexec_handover_internal.h" -#define KHO_FDT_COMPATIBLE "kho-v1" -#define PROP_PRESERVED_MEMORY_MAP "preserved-memory-map" -#define PROP_SUB_FDT "fdt" - +/* The magic token for preserved pages */ #define KHO_PAGE_MAGIC 0x4b484f50U /* ASCII for 'KHOP' */ /* @@ -378,7 +376,7 @@ static void kho_update_memory_map(struct khoser_mem_chunk *first_chunk) void *ptr; u64 phys; - ptr = fdt_getprop_w(kho_out.fdt, 0, PROP_PRESERVED_MEMORY_MAP, NULL); + ptr = fdt_getprop_w(kho_out.fdt, 0, KHO_FDT_MEMORY_MAP_PROP_NAME, NULL); /* Check and discard previous memory map */ phys = get_unaligned((u64 *)ptr); @@ -468,7 +466,7 @@ static bool __init kho_mem_deserialize(const void *fdt) u64 mem; int len; - mem_ptr = fdt_getprop(fdt, 0, PROP_PRESERVED_MEMORY_MAP, &len); + mem_ptr = fdt_getprop(fdt, 0, KHO_FDT_MEMORY_MAP_PROP_NAME, &len); if (!mem_ptr || len != sizeof(u64)) { pr_err("failed to get preserved memory bitmaps\n"); return false; @@ -733,7 +731,8 @@ int kho_add_subtree(const char *name, void *fdt) goto out_pack; } - err = fdt_setprop(root_fdt, off, PROP_SUB_FDT, &phys, sizeof(phys)); + err = fdt_setprop(root_fdt, off, KHO_FDT_SUB_TREE_PROP_NAME, + &phys, sizeof(phys)); if (err < 0) goto out_pack; @@ -764,7 +763,7 @@ void kho_remove_subtree(void *fdt) const u64 *val; int len; - val = fdt_getprop(root_fdt, off, PROP_SUB_FDT, &len); + val = fdt_getprop(root_fdt, off, KHO_FDT_SUB_TREE_PROP_NAME, &len); if (!val || len != sizeof(phys_addr_t)) continue; @@ -1310,7 +1309,7 @@ int kho_retrieve_subtree(const char *name, phys_addr_t *phys) if (offset < 0) return -ENOENT; - val = fdt_getprop(fdt, offset, PROP_SUB_FDT, &len); + val = fdt_getprop(fdt, offset, KHO_FDT_SUB_TREE_PROP_NAME, &len); if (!val || len != sizeof(*val)) return -EINVAL; @@ -1330,7 +1329,7 @@ static __init int kho_out_fdt_setup(void) err |= fdt_finish_reservemap(root); err |= fdt_begin_node(root, ""); err |= fdt_property_string(root, "compatible", KHO_FDT_COMPATIBLE); - err |= fdt_property(root, PROP_PRESERVED_MEMORY_MAP, &empty_mem_map, + err |= fdt_property(root, KHO_FDT_MEMORY_MAP_PROP_NAME, &empty_mem_map, sizeof(empty_mem_map)); err |= fdt_end_node(root); err |= fdt_finish(root); -- 2.52.0.223.gf5cc29aaa4-goog The `struct kho_vmalloc` defines the in-memory layout for preserving vmalloc regions across kexec. This layout is a contract between kernels and part of the KHO ABI. To reflect this relationship, the related structs and helper macros are relocated to the ABI header, `include/linux/kho/abi/kexec_handover.h`. This move places the structure's definition under the protection of the KHO_FDT_COMPATIBLE version string. The structure and its components are now also documented within the ABI header to describe the contract and prevent ABI breaks. Signed-off-by: Jason Miu --- Documentation/core-api/kho/fdt.rst | 6 ++ include/linux/kexec_handover.h | 27 +-------- include/linux/kho/abi/kexec_handover.h | 78 ++++++++++++++++++++++++++ include/linux/kho/abi/memfd.h | 2 +- kernel/liveupdate/kexec_handover.c | 15 ----- lib/test_kho.c | 1 + 6 files changed, 88 insertions(+), 41 deletions(-) diff --git a/Documentation/core-api/kho/fdt.rst b/Documentation/core-api/kho/fdt.rst index 4e080ccc420e..4202b67fcdf9 100644 --- a/Documentation/core-api/kho/fdt.rst +++ b/Documentation/core-api/kho/fdt.rst @@ -14,6 +14,12 @@ directly in the ABI header file. .. kernel-doc:: include/linux/kho/abi/kexec_handover.h :doc: Kexec Handover ABI +Kexec Handover ABI for vmalloc Preservation +=========================================== + +.. kernel-doc:: include/linux/kho/abi/kexec_handover.h + :doc: Kexec Handover ABI for vmalloc Preservation + See Also ======== diff --git a/include/linux/kexec_handover.h b/include/linux/kexec_handover.h index 5f7b9de97e8d..a56ff3ffaf17 100644 --- a/include/linux/kexec_handover.h +++ b/include/linux/kexec_handover.h @@ -11,34 +11,11 @@ struct kho_scratch { phys_addr_t size; }; +struct kho_vmalloc; + struct folio; struct page; -#define DECLARE_KHOSER_PTR(name, type) \ - union { \ - phys_addr_t phys; \ - type ptr; \ - } name -#define KHOSER_STORE_PTR(dest, val) \ - ({ \ - typeof(val) v = val; \ - typecheck(typeof((dest).ptr), v); \ - (dest).phys = virt_to_phys(v); \ - }) -#define KHOSER_LOAD_PTR(src) \ - ({ \ - typeof(src) s = src; \ - (typeof((s).ptr))((s).phys ? phys_to_virt((s).phys) : NULL); \ - }) - -struct kho_vmalloc_chunk; -struct kho_vmalloc { - DECLARE_KHOSER_PTR(first, struct kho_vmalloc_chunk *); - unsigned int total_pages; - unsigned short flags; - unsigned short order; -}; - #ifdef CONFIG_KEXEC_HANDOVER bool kho_is_enabled(void); bool is_kho_boot(void); diff --git a/include/linux/kho/abi/kexec_handover.h b/include/linux/kho/abi/kexec_handover.h index d78df2d44cb6..74f4fa67e458 100644 --- a/include/linux/kho/abi/kexec_handover.h +++ b/include/linux/kho/abi/kexec_handover.h @@ -10,6 +10,8 @@ #ifndef _LINUX_KHO_ABI_KEXEC_HANDOVER_H #define _LINUX_KHO_ABI_KEXEC_HANDOVER_H +#include + /** * DOC: Kexec Handover ABI * @@ -81,4 +83,80 @@ /* The FDT property for sub-FDTs. */ #define KHO_FDT_SUB_TREE_PROP_NAME "fdt" +/** + * DOC: Kexec Handover ABI for vmalloc Preservation + * + * The Kexec Handover ABI for preserving vmalloc'ed memory is defined by + * a set of structures and helper macros. The layout of these structures is a + * stable contract between kernels and is versioned by the KHO_FDT_COMPATIBLE + * string. + * + * The preservation is managed through a main descriptor struct (`kho_vmalloc`), + * which points to a linked list of `kho_vmalloc_chunk` structures. These + * chunks contain the physical addresses of the preserved pages, allowing the + * next kernel to reconstruct the vmalloc area with the same content and layout. + * Helper macros are also defined for storing and loading pointers within + * these structures. + */ + +/* Helper macro to define a union for a serializable pointer. */ +#define DECLARE_KHOSER_PTR(name, type) \ + union { \ + u64 phys; \ + type ptr; \ + } name + +/* Stores the physical address of a serializable pointer. */ +#define KHOSER_STORE_PTR(dest, val) \ + ({ \ + typeof(val) v = val; \ + typecheck(typeof((dest).ptr), v); \ + (dest).phys = virt_to_phys(v); \ + }) + +/* Loads the stored physical address back to a pointer. */ +#define KHOSER_LOAD_PTR(src) \ + ({ \ + typeof(src) s = src; \ + (typeof((s).ptr))((s).phys ? phys_to_virt((s).phys) : NULL); \ + }) + +/* + * This header is embedded at the beginning of each `kho_vmalloc_chunk` + * and contains a pointer to the next chunk in the linked list, + * stored as a physical address for handover. + */ +struct kho_vmalloc_hdr { + DECLARE_KHOSER_PTR(next, struct kho_vmalloc_chunk *); +}; + +#define KHO_VMALLOC_SIZE \ + ((PAGE_SIZE - sizeof(struct kho_vmalloc_hdr)) / \ + sizeof(u64)) + +/* + * Each chunk is a single page and is part of a linked list that describes + * a preserved vmalloc area. It contains the header with the link to the next + * chunk and an array of physical addresses of the pages that make up the + * preserved vmalloc area. + */ +struct kho_vmalloc_chunk { + struct kho_vmalloc_hdr hdr; + u64 phys[KHO_VMALLOC_SIZE]; +}; + +static_assert(sizeof(struct kho_vmalloc_chunk) == PAGE_SIZE); + +/* + * Describes a preserved vmalloc memory area, including the + * total number of pages, allocation flags, page order, and a pointer to the + * first chunk of physical page addresses. + */ +struct kho_vmalloc { + DECLARE_KHOSER_PTR(first, struct kho_vmalloc_chunk *); + unsigned int total_pages; + unsigned short flags; + unsigned short order; +}; + #endif /* _LINUX_KHO_ABI_KEXEC_HANDOVER_H */ diff --git a/include/linux/kho/abi/memfd.h b/include/linux/kho/abi/memfd.h index da7d063474a1..1af4c9dc5a06 100644 --- a/include/linux/kho/abi/memfd.h +++ b/include/linux/kho/abi/memfd.h @@ -12,7 +12,7 @@ #define _LINUX_KHO_ABI_MEMFD_H #include -#include +#include /** * DOC: memfd Live Update ABI diff --git a/kernel/liveupdate/kexec_handover.c b/kernel/liveupdate/kexec_handover.c index d3d02a9ea391..a180b3367e8f 100644 --- a/kernel/liveupdate/kexec_handover.c +++ b/kernel/liveupdate/kexec_handover.c @@ -882,21 +882,6 @@ void kho_unpreserve_pages(struct page *page, unsigned int nr_pages) } EXPORT_SYMBOL_GPL(kho_unpreserve_pages); -struct kho_vmalloc_hdr { - DECLARE_KHOSER_PTR(next, struct kho_vmalloc_chunk *); -}; - -#define KHO_VMALLOC_SIZE \ - ((PAGE_SIZE - sizeof(struct kho_vmalloc_hdr)) / \ - sizeof(phys_addr_t)) - -struct kho_vmalloc_chunk { - struct kho_vmalloc_hdr hdr; - phys_addr_t phys[KHO_VMALLOC_SIZE]; -}; - -static_assert(sizeof(struct kho_vmalloc_chunk) == PAGE_SIZE); - /* vmalloc flags KHO supports */ #define KHO_VMALLOC_SUPPORTED_FLAGS (VM_ALLOC | VM_ALLOW_HUGE_VMAP) diff --git a/lib/test_kho.c b/lib/test_kho.c index 47de56280795..3431daca6968 100644 --- a/lib/test_kho.c +++ b/lib/test_kho.c @@ -19,6 +19,7 @@ #include #include #include +#include #include -- 2.52.0.223.gf5cc29aaa4-goog Introduce a radix tree implementation for tracking preserved memory pages and switch the KHO memory tracking mechanism to use it. This lays the groundwork for a stateless KHO implementation that eliminates the need for serialization and the associated "finalize" state. This patch introduces the core radix tree data structures and constants to the KHO ABI. It adds the radix tree node and leaf structures, along with documentation for the radix tree key encoding scheme that combines a page's physical address and order. To support broader use by other kernel subsystems, such as hugetlb preservation, the core radix tree manipulation functions are exported as a public API. The xarray-based memory tracking is replaced with this new radix tree implementation. The core KHO preservation and unpreservation functions are wired up to use the radix tree helpers. On boot, the second kernel restores the preserved memory map by walking the radix tree whose root physical address is passed via the FDT. The ABI `compatible` version is bumped to "kho-v2" to reflect the structural changes in the preserved memory map and sub-FDT property names. Signed-off-by: Jason Miu --- Documentation/core-api/kho/concepts.rst | 2 +- Documentation/core-api/kho/fdt.rst | 7 + Documentation/core-api/kho/index.rst | 1 + Documentation/core-api/kho/radix_tree.rst | 17 + include/linux/kho/abi/kexec_handover.h | 124 +++- include/linux/kho_radix_tree.h | 81 +++ kernel/liveupdate/kexec_handover.c | 658 ++++++++++++---------- 7 files changed, 568 insertions(+), 322 deletions(-) create mode 100644 Documentation/core-api/kho/radix_tree.rst create mode 100644 include/linux/kho_radix_tree.h diff --git a/Documentation/core-api/kho/concepts.rst b/Documentation/core-api/kho/concepts.rst index e96893937286..d38bcaa951e4 100644 --- a/Documentation/core-api/kho/concepts.rst +++ b/Documentation/core-api/kho/concepts.rst @@ -71,7 +71,7 @@ in the FDT. That state is called the KHO finalization phase. Public API ========== .. kernel-doc:: kernel/liveupdate/kexec_handover.c - :export: + :identifiers: kho_is_enabled kho_restore_folio kho_restore_pages kho_add_subtree kho_remove_subtree kho_preserve_folio kho_unpreserve_folio kho_preserve_pages kho_unpreserve_pages kho_preserve_vmalloc kho_unpreserve_vmalloc kho_restore_vmalloc kho_alloc_preserve kho_unpreserve_free kho_restore_free is_kho_boot kho_retrieve_subtree Internal API ============ diff --git a/Documentation/core-api/kho/fdt.rst b/Documentation/core-api/kho/fdt.rst index 4202b67fcdf9..56993d091b32 100644 --- a/Documentation/core-api/kho/fdt.rst +++ b/Documentation/core-api/kho/fdt.rst @@ -20,8 +20,15 @@ Kexec Handover ABI for vmalloc Preservation .. kernel-doc:: include/linux/kho/abi/kexec_handover.h :doc: Kexec Handover ABI for vmalloc Preservation +Keep track of memory that is to be preserved across KHO +======================================================= + +.. kernel-doc:: include/linux/kho/abi/kexec_handover.h + :doc: Keep track of memory that is to be preserved across KHO. + See Also ======== - :doc:`/admin-guide/mm/kho` - :doc:`/core-api/kho/concepts` +- :doc:`/core-api/kho/radix_tree` diff --git a/Documentation/core-api/kho/index.rst b/Documentation/core-api/kho/index.rst index 0c63b0c5c143..68cdf332076e 100644 --- a/Documentation/core-api/kho/index.rst +++ b/Documentation/core-api/kho/index.rst @@ -9,5 +9,6 @@ Kexec Handover Subsystem concepts fdt + radix_tree .. only:: subproject and html diff --git a/Documentation/core-api/kho/radix_tree.rst b/Documentation/core-api/kho/radix_tree.rst new file mode 100644 index 000000000000..9523ade75d9c --- /dev/null +++ b/Documentation/core-api/kho/radix_tree.rst @@ -0,0 +1,17 @@ +.. SPDX-License-Identifier: GPL-2.0 + +==================== +KHO Radix Tree +==================== + +Description +=========== + +.. kernel-doc:: include/linux/kho_radix_tree.h + :doc: Kexec Handover Radix Tree + +Public API +========== + +.. kernel-doc:: kernel/liveupdate/kexec_handover.c + :identifiers: kho_radix_encode_key kho_radix_decode_key kho_radix_add_page kho_radix_del_page kho_radix_walk_tree diff --git a/include/linux/kho/abi/kexec_handover.h b/include/linux/kho/abi/kexec_handover.h index 74f4fa67e458..bdda2fe67353 100644 --- a/include/linux/kho/abi/kexec_handover.h +++ b/include/linux/kho/abi/kexec_handover.h @@ -10,6 +10,8 @@ #ifndef _LINUX_KHO_ABI_KEXEC_HANDOVER_H #define _LINUX_KHO_ABI_KEXEC_HANDOVER_H +#include +#include #include /** @@ -35,25 +37,25 @@ * parses this FDT to locate and restore the preserved data.:: * * / { - * compatible = "kho-v1"; + * compatible = "kho-v2"; * * preserved-memory-map = <0x...>; * * { - * fdt = <0x...>; + * preserved-data = <0x...>; * }; * * { - * fdt = <0x...>; + * preserved-data = <0x...>; * }; * ... ... * { - * fdt = <0x...>; + * preserved-data = <0x...>; * }; * }; * * Root KHO Node (/): - * - compatible: "kho-v1" + * - compatible: "kho-v2" * * Indentifies the overall KHO ABI version. * @@ -68,20 +70,20 @@ * is provided by the subsystem that uses KHO for preserving its * data. * - * - fdt: u64 + * - preserved-data: u64 * - * Physical address pointing to a subnode FDT blob that is also + * Physical address pointing to a subnode data blob that is also * being preserved. */ /* The compatible string for the KHO FDT root node. */ -#define KHO_FDT_COMPATIBLE "kho-v1" +#define KHO_FDT_COMPATIBLE "kho-v2" /* The FDT property for the preserved memory map. */ #define KHO_FDT_MEMORY_MAP_PROP_NAME "preserved-memory-map" /* The FDT property for sub-FDTs. */ -#define KHO_FDT_SUB_TREE_PROP_NAME "fdt" +#define KHO_FDT_SUB_TREE_PROP_NAME "preserved-data" /** * DOC: Kexec Handover ABI for vmalloc Preservation @@ -159,4 +161,108 @@ struct kho_vmalloc { unsigned short order; }; +/** + * DOC: Keep track of memory that is to be preserved across KHO. + * + * KHO tracks preserved memory using a radix tree data structure. Each node of + * the tree is PAGE_SIZE. The leaf nodes are bitmaps where each set bit + * represents a single preserved page. The intermediate nodes are tables of + * physical addresses that point to a lower level node. + * + * The tree hierarchy is shown below:: + * + * root + * +-------------------+ + * | Level 5 | (struct kho_radix_node) + * +-------------------+ + * | + * v + * +-------------------+ + * | Level 4 | (struct kho_radix_node) + * +-------------------+ + * | + * | ... (intermediate levels) + * | + * v + * +-------------------+ + * | Level 0 | (struct kho_radix_leaf) + * +-------------------+ + * + * This is achieved by encoding the page's physical address (pa) and its order + * into a single unsigned long value. This value is a key then used to traverse + * the tree. The encoded key value is composed of two parts: the 'order bit' in + * the upper part and the 'page offset' in the lower part.:: + * + * +------------+-----------------------------+--------------------------+ + * | Page Order | Order Bit | Page Offset | + * +------------+-----------------------------+--------------------------+ + * | 0 | ...000100 ... (at bit 52) | pa >> (PAGE_SHIFT + 0) | + * | 1 | ...000010 ... (at bit 51) | pa >> (PAGE_SHIFT + 1) | + * | 2 | ...000001 ... (at bit 50) | pa >> (PAGE_SHIFT + 2) | + * | ... | ... | ... | + * +------------+-----------------------------+--------------------------+ + * + * Page Offset: + * The 'page offset' is the physical address normalized for its order. It + * effectively represents the page offset for the given order. + * + * Order Bit: + * The 'order bit' encodes the page order by setting a single bit at a + * specific position. The position of this bit itself represents the order. + * + * For instance, on a 64-bit system with 4KB pages (PAGE_SHIFT = 12), the + * maximum range for a page offset (for order 0) is 52 bits (64 - 12). This + * offset occupies bits [0-51]. For order 0, the order bit is set at + * position 52. + * + * The following diagram illustrates how the encoded key value is split into + * indices for the tree levels, with PAGE_SIZE of 4KB:: + * + * 63:60 59:51 50:42 41:33 32:24 23:15 14:0 + * +---------+--------+--------+--------+--------+--------+-----------------+ + * | 0 | Lv 5 | Lv 4 | Lv 3 | Lv 2 | Lv 1 | Lv 0 (bitmap) | + * +---------+--------+--------+--------+--------+--------+-----------------+ + * + * This design stores pages of all sizes (orders) in a single 6-level table. + * It efficiently shares lower table levels, especially due to common zero top + * address bits, allowing a single, efficient algorithm to manage all pages. + * This bitmap approach also offers memory efficiency; for example, a 512KB + * bitmap can cover a 16GB memory range for 0-order pages with PAGE_SIZE = 4KB. + * + * The data structures defined here are part of the KHO ABI. Any modification + * to these structures that breaks backward compatibility must be accompanied by + * an update to the "compatible" string. This ensures that a newer kernel can + * correctly interpret the data passed by an older kernel. + */ + +/* + * Defines constants for the KHO radix tree structure, used to track preserved + * memory. These constants govern the indexing, sizing, and depth of the tree. + */ +enum kho_radix_consts { + /* The bit position of a 0-order page */ + KHO_ORDER_0_LG2 = 64 - PAGE_SHIFT, + + /* Size of the table in kho_mem_radix_tree, in lg2 */ + KHO_TABLE_SIZE_LG2 = const_ilog2(PAGE_SIZE / sizeof(phys_addr_t)), + + /* Number of bits in the kho_bitmap, in lg2 */ + KHO_BITMAP_SIZE_LG2 = PAGE_SHIFT + const_ilog2(BITS_PER_BYTE), + + /* + * The total tree depth is the number of intermediate levels + * and 1 bitmap level. + */ + KHO_TREE_MAX_DEPTH = DIV_ROUND_UP(KHO_ORDER_0_LG2 - KHO_BITMAP_SIZE_LG2, + KHO_TABLE_SIZE_LG2) + 1, +}; + +struct kho_radix_node { + u64 table[1 << KHO_TABLE_SIZE_LG2]; +}; + +struct kho_radix_leaf { + DECLARE_BITMAP(bitmap, 1 << KHO_BITMAP_SIZE_LG2); +}; + #endif /* _LINUX_KHO_ABI_KEXEC_HANDOVER_H */ diff --git a/include/linux/kho_radix_tree.h b/include/linux/kho_radix_tree.h new file mode 100644 index 000000000000..5101a04f6ae6 --- /dev/null +++ b/include/linux/kho_radix_tree.h @@ -0,0 +1,81 @@ +/* SPDX-License-Identifier: GPL-2.0 */ + +#ifndef _LIVEUPDATE_KEXEC_HANDOVER_RADIX_TREE_H +#define _LIVEUPDATE_KEXEC_HANDOVER_RADIX_TREE_H + +#include +#include +#include + +/** + * DOC: Kexec Handover Radix Tree + * + * This is a radix tree implementation for tracking physical memory pages + * across kexec transitions. It was developed for the KHO mechanism but is + * designed for broader use by any subsystem that needs to preserve pages. + * + * The radix tree is a multi-level tree where leaf nodes are bitmaps + * representing individual pages. To allow pages of different sizes (orders) + * to be stored efficiently in a single tree, it uses a unique key encoding + * scheme. Each key is an unsigned long that combines a page's physical + * address and its order. + * + * Client code is responsible for allocating the root node of the tree and + * managing its lifecycle, and must use the tree data structures defined in + * the KHO ABI, `include/linux/kho/abi/kexec_handover.h`. + */ + +struct kho_radix_node; + +typedef int (*kho_radix_tree_walk_callback_t)(unsigned long radix_key); + +#ifdef CONFIG_KEXEC_HANDOVER + +unsigned long kho_radix_encode_key(phys_addr_t pa, unsigned int order); + +phys_addr_t kho_radix_decode_key(unsigned long radix_key, + unsigned int *order); + +int kho_radix_add_page(struct kho_radix_node *root, unsigned long pfn, + unsigned int order); + +void kho_radix_del_page(struct kho_radix_node *root, unsigned long pfn, + unsigned int order); + +int kho_radix_walk_tree(struct kho_radix_node *root, unsigned int level, + unsigned long start, kho_radix_tree_walk_callback_t cb); + +#else /* #ifdef CONFIG_KEXEC_HANDOVER */ + +static inline unsigned long kho_radix_encode_key(phys_addr_t pa, + unsigned int order) +{ + return 0; +} + +static inline phys_addr_t kho_radix_decode_key(unsigned long radix_key, + unsigned int *order) +{ + return 0; +}; + +static inline int kho_radix_add_page(struct kho_radix_node *root, long pfn, + unsigned int order) +{ + return -EOPNOTSUPP; +} + +static inline void kho_radix_del_page(struct kho_radix_node *root, + unsigned long pfn, unsigned int order) { } + +static inline int kho_radix_walk_tree(struct kho_radix_node *root, + unsigned int level, + unsigned long start, + kho_radix_tree_walk_callback_t cb) +{ + return -EOPNOTSUPP; +} + +#endif /* #ifdef CONFIG_KEXEC_HANDOVER */ + +#endif /* _LIVEUPDATE_KEXEC_HANDOVER_RADIX_TREE_H */ diff --git a/kernel/liveupdate/kexec_handover.c b/kernel/liveupdate/kexec_handover.c index a180b3367e8f..81bac82c8672 100644 --- a/kernel/liveupdate/kexec_handover.c +++ b/kernel/liveupdate/kexec_handover.c @@ -5,6 +5,7 @@ * Copyright (C) 2025 Microsoft Corporation, Mike Rapoport * Copyright (C) 2025 Google LLC, Changyuan Lyu * Copyright (C) 2025 Pasha Tatashin + * Copyright (C) 2025 Google LLC, Jason Miu */ #define pr_fmt(fmt) "KHO: " fmt @@ -15,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -66,155 +68,302 @@ static int __init kho_parse_enable(char *p) early_param("kho", kho_parse_enable); /* - * Keep track of memory that is to be preserved across KHO. - * - * The serializing side uses two levels of xarrays to manage chunks of per-order - * PAGE_SIZE byte bitmaps. For instance if PAGE_SIZE = 4096, the entire 1G order - * of a 8TB system would fit inside a single 4096 byte bitmap. For order 0 - * allocations each bitmap will cover 128M of address space. Thus, for 16G of - * memory at most 512K of bitmap memory will be needed for order 0. - * - * This approach is fully incremental, as the serialization progresses folios - * can continue be aggregated to the tracker. The final step, immediately prior - * to kexec would serialize the xarray information into a linked list for the - * successor kernel to parse. + * `root` points to a page that serves as the root of the + * KHO radix tree. This page is allocated during KHO module initialization. + * Its physical address is written to the FDT and passed to the next kernel + * during kexec. */ - -#define PRESERVE_BITS (PAGE_SIZE * 8) - -struct kho_mem_phys_bits { - DECLARE_BITMAP(preserve, PRESERVE_BITS); -}; - -static_assert(sizeof(struct kho_mem_phys_bits) == PAGE_SIZE); - -struct kho_mem_phys { - /* - * Points to kho_mem_phys_bits, a sparse bitmap array. Each bit is sized - * to order. - */ - struct xarray phys_bits; -}; - struct kho_mem_track { - /* Points to kho_mem_phys, each order gets its own bitmap tree */ - struct xarray orders; + struct kho_radix_node *root; + struct rw_semaphore sem; }; -struct khoser_mem_chunk; - struct kho_out { - void *fdt; - bool finalized; - struct mutex lock; /* protects KHO FDT finalization */ - struct kho_mem_track track; + void *fdt; + struct mutex lock; /* protects KHO FDT */ struct kho_debugfs dbg; }; static struct kho_out kho_out = { - .lock = __MUTEX_INITIALIZER(kho_out.lock), .track = { - .orders = XARRAY_INIT(kho_out.track.orders, 0), + .sem = __RWSEM_INITIALIZER(kho_out.track.sem), }, - .finalized = false, + .lock = __MUTEX_INITIALIZER(kho_out.lock), }; -static void *xa_load_or_alloc(struct xarray *xa, unsigned long index) +/** + * kho_radix_encode_key - Encodes a physical address and order into a radix key. + * @pa: The physical address of the page. + * @order: The order of the page. + * + * This function combines a page's physical address and its order into a + * single unsigned long, which is used as a key for all radix tree + * operations. + * + * Return: The encoded unsigned long key. + */ +unsigned long kho_radix_encode_key(phys_addr_t pa, unsigned int order) { - void *res = xa_load(xa, index); + /* Order bits part */ + unsigned long h = 1UL << (KHO_ORDER_0_LG2 - order); + /* Page offset part */ + unsigned long l = pa >> (PAGE_SHIFT + order); - if (res) - return res; + return h | l; +} +EXPORT_SYMBOL_GPL(kho_radix_encode_key); - void *elm __free(free_page) = (void *)get_zeroed_page(GFP_KERNEL); +/** + * kho_radix_decode_key - Decodes a radix key back into a physical address and order. + * @radix_key: The unsigned long key to decode. + * @order: An output parameter, a pointer to an unsigned int where the decoded + * page order will be stored. + * + * This function reverses the encoding performed by kho_radix_encode_key(), + * extracting the original physical address and page order from a given key. + * + * Return: The decoded physical address. + */ +phys_addr_t kho_radix_decode_key(unsigned long radix_key, + unsigned int *order) +{ + unsigned int order_bit = fls64(radix_key); + phys_addr_t pa; - if (!elm) - return ERR_PTR(-ENOMEM); + /* order_bit is numbered starting at 1 from fls64 */ + *order = KHO_ORDER_0_LG2 - order_bit + 1; + /* The order is discarded by the shift */ + pa = radix_key << (PAGE_SHIFT + *order); - if (WARN_ON(kho_scratch_overlap(virt_to_phys(elm), PAGE_SIZE))) - return ERR_PTR(-EINVAL); + return pa; +} +EXPORT_SYMBOL_GPL(kho_radix_decode_key); + +static unsigned long kho_radix_get_index(unsigned long radix_key, + unsigned int level) +{ + int s; - res = xa_cmpxchg(xa, index, NULL, elm, GFP_KERNEL); - if (xa_is_err(res)) - return ERR_PTR(xa_err(res)); - else if (res) - return res; + if (level == 0) + return radix_key % (1 << KHO_BITMAP_SIZE_LG2); - return no_free_ptr(elm); + s = ((level - 1) * KHO_TABLE_SIZE_LG2) + KHO_BITMAP_SIZE_LG2; + return (radix_key >> s) % (1 << KHO_TABLE_SIZE_LG2); } -static void __kho_unpreserve_order(struct kho_mem_track *track, unsigned long pfn, - unsigned int order) +/** + * kho_radix_add_page - Marks a page as preserved in the radix tree. + * @root: The root of the radix tree. + * @pfn: The page frame number of the page to preserve. + * @order: The order of the page. + * + * This function traverses the radix tree based on the key derived from @pfn + * and @order. It sets the corresponding bit in the leaf bitmap to mark the + * page for preservation. If intermediate nodes do not exist along the path, + * they are allocated and added to the tree. + * + * Return: 0 on success, or a negative error code on failure. + */ +int kho_radix_add_page(struct kho_radix_node *root, + unsigned long pfn, unsigned int order) { - struct kho_mem_phys_bits *bits; - struct kho_mem_phys *physxa; - const unsigned long pfn_high = pfn >> order; + phys_addr_t pa = PFN_PHYS(pfn); + unsigned long radix_key = kho_radix_encode_key(pa, order); + struct kho_radix_node *node; + struct kho_radix_leaf *leaf; + unsigned int i, idx; + int err = 0; - physxa = xa_load(&track->orders, order); - if (WARN_ON_ONCE(!physxa)) - return; + /* + * This array stores pointers to newly allocated intermediate radix tree + * nodes along the insertion path. In case of an error during node + * allocation or insertion, these stored pointers are used to free + * the partially allocated path, preventing memory leaks. + */ + struct kho_radix_node *intermediate_nodes[KHO_TREE_MAX_DEPTH] = { 0 }; - bits = xa_load(&physxa->phys_bits, pfn_high / PRESERVE_BITS); - if (WARN_ON_ONCE(!bits)) - return; + might_sleep(); - clear_bit(pfn_high % PRESERVE_BITS, bits->preserve); + node = root; + + /* Go from high levels to low levels */ + for (i = KHO_TREE_MAX_DEPTH - 1; i > 0; i--) { + idx = kho_radix_get_index(radix_key, i); + + if (node->table[idx]) { + node = phys_to_virt((phys_addr_t)node->table[idx]); + continue; + } + + /* Next node is empty, create a new node for it */ + struct kho_radix_node *new_tree; + + new_tree = (struct kho_radix_node *)get_zeroed_page(GFP_KERNEL); + if (!new_tree) { + err = -ENOMEM; + goto err_free_alloc_nodes; + } + + node->table[idx] = virt_to_phys(new_tree); + node = new_tree; + + intermediate_nodes[i] = new_tree; + } + + /* Handle the leaf level bitmap (level 0) */ + idx = kho_radix_get_index(radix_key, 0); + leaf = (struct kho_radix_leaf *)node; + __set_bit(idx, leaf->bitmap); + + return 0; + +err_free_alloc_nodes: + for (i = KHO_TREE_MAX_DEPTH - 1; i > 0; i--) { + if (intermediate_nodes[i]) + free_page((unsigned long)intermediate_nodes[i]); + } + + return err; } +EXPORT_SYMBOL_GPL(kho_radix_add_page); -static void __kho_unpreserve(struct kho_mem_track *track, unsigned long pfn, - unsigned long end_pfn) +/** + * kho_radix_del_page - Removes a page's preservation status from the radix tree. + * @root: The root of the radix tree. + * @pfn: The page frame number of the page to unpreserve. + * @order: The order of the page. + * + * This function traverses the radix tree and clears the bit corresponding to + * the page, effectively removing its "preserved" status. It does not free + * the tree's intermediate nodes, even if they become empty. + */ +void kho_radix_del_page(struct kho_radix_node *root, unsigned long pfn, + unsigned int order) { - unsigned int order; + unsigned long radix_key = kho_radix_encode_key(PFN_PHYS(pfn), order); + unsigned int tree_level = KHO_TREE_MAX_DEPTH - 1; + struct kho_radix_node *node; + struct kho_radix_leaf *leaf; + unsigned int i, idx; - while (pfn < end_pfn) { - order = min(count_trailing_zeros(pfn), ilog2(end_pfn - pfn)); + might_sleep(); - __kho_unpreserve_order(track, pfn, order); + node = root; - pfn += 1 << order; + /* Go from high levels to low levels */ + for (i = tree_level; i > 0; i--) { + idx = kho_radix_get_index(radix_key, i); + + /* + * Attempting to delete a page that has not been preserved, + * return with a warning. + */ + if (WARN_ON(!node->table[idx])) + return; + + if (node->table[idx]) + node = phys_to_virt((phys_addr_t)node->table[idx]); } + + /* Handle the leaf level bitmap (level 0) */ + leaf = (struct kho_radix_leaf *)node; + __clear_bit(idx, leaf->bitmap); } +EXPORT_SYMBOL_GPL(kho_radix_del_page); -static int __kho_preserve_order(struct kho_mem_track *track, unsigned long pfn, - unsigned int order) +static int kho_radix_walk_leaf(struct kho_radix_leaf *leaf, + unsigned long radix_key, + kho_radix_tree_walk_callback_t cb) { - struct kho_mem_phys_bits *bits; - struct kho_mem_phys *physxa, *new_physxa; - const unsigned long pfn_high = pfn >> order; + unsigned long *bitmap = (unsigned long *)leaf; + unsigned int i; + int err; - might_sleep(); - physxa = xa_load(&track->orders, order); - if (!physxa) { - int err; + for_each_set_bit(i, bitmap, PAGE_SIZE * BITS_PER_BYTE) { + err = cb(radix_key | i); + if (err) + return err; + } + + return 0; +} + +/** + * kho_radix_walk_tree - Traverses the radix tree and calls a callback for each preserved page. + * @root: A pointer to the root node of the radix tree to walk. + * @level: The starting level for the walk (typically KHO_TREE_MAX_DEPTH - 1). + * @start: The initial key prefix for the walk (typically 0). + * @cb: A callback function of type kho_radix_tree_walk_callback_t that will be + * invoked for each preserved page found in the tree. The callback receives + * the full radix key of the preserved page. + * + * This function walks the radix tree, searching from the specified top level + * (@level) down to the lowest level (level 0). For each preserved page found, + * it invokes the provided callback, passing the page's fully reconstructed + * radix key. + * + * Return: 0 if the walk completed the specified subtree, or the non-zero return + * value from the callback that stopped the walk. + */ +int kho_radix_walk_tree(struct kho_radix_node *root, unsigned int level, + unsigned long start, kho_radix_tree_walk_callback_t cb) +{ + struct kho_radix_node *node; + struct kho_radix_leaf *leaf; + unsigned long radix_key, i; + int err; - new_physxa = kzalloc(sizeof(*physxa), GFP_KERNEL); - if (!new_physxa) - return -ENOMEM; + for (i = 0; i < PAGE_SIZE / sizeof(phys_addr_t); i++) { + if (!root->table[i]) + continue; + + unsigned int shift; - xa_init(&new_physxa->phys_bits); - physxa = xa_cmpxchg(&track->orders, order, NULL, new_physxa, - GFP_KERNEL); + shift = ((level - 1) * KHO_TABLE_SIZE_LG2) + + KHO_BITMAP_SIZE_LG2; + radix_key = start | (i << shift); - err = xa_err(physxa); - if (err || physxa) { - xa_destroy(&new_physxa->phys_bits); - kfree(new_physxa); + node = phys_to_virt((phys_addr_t)root->table[i]); + if (level > 1) { + err = kho_radix_walk_tree(node, level - 1, + radix_key, cb); if (err) return err; } else { - physxa = new_physxa; + /* + * we are at level 1, + * node is pointing to the level 0 bitmap. + */ + leaf = (struct kho_radix_leaf *)node; + return kho_radix_walk_leaf(leaf, radix_key, cb); } } - bits = xa_load_or_alloc(&physxa->phys_bits, pfn_high / PRESERVE_BITS); - if (IS_ERR(bits)) - return PTR_ERR(bits); + return 0; +} +EXPORT_SYMBOL_GPL(kho_radix_walk_tree); + - set_bit(pfn_high % PRESERVE_BITS, bits->preserve); - return 0; +static void __kho_unpreserve(unsigned long pfn, unsigned long end_pfn) +{ + struct kho_mem_track *track = &kho_out.track; + unsigned int order; + + if (WARN_ON_ONCE(!track->root)) + return; + + down_write(&track->sem); + while (pfn < end_pfn) { + order = min(count_trailing_zeros(pfn), ilog2(end_pfn - pfn)); + + kho_radix_del_page(track->root, pfn, order); + + pfn += 1 << order; + } + up_write(&track->sem); } static struct page *kho_restore_page(phys_addr_t phys, bool is_folio) @@ -228,9 +377,10 @@ static struct page *kho_restore_page(phys_addr_t phys, bool is_folio) info.page_private = page->private; /* - * deserialize_bitmap() only sets the magic on the head page. This magic - * check also implicitly makes sure phys is order-aligned since for - * non-order-aligned phys addresses, magic will never be set. + * kho_radix_walk_tree_memblock_callback() only sets the magic on the + * head page. This magic check also implicitly makes sure phys is + * order-aligned since for non-order-aligned phys addresses, magic will + * never be set. */ if (WARN_ON_ONCE(info.magic != KHO_PAGE_MAGIC || info.order > MAX_PAGE_ORDER)) return NULL; @@ -301,195 +451,30 @@ struct page *kho_restore_pages(phys_addr_t phys, unsigned int nr_pages) } EXPORT_SYMBOL_GPL(kho_restore_pages); -/* Serialize and deserialize struct kho_mem_phys across kexec - * - * Record all the bitmaps in a linked list of pages for the next kernel to - * process. Each chunk holds bitmaps of the same order and each block of bitmaps - * starts at a given physical address. This allows the bitmaps to be sparse. The - * xarray is used to store them in a tree while building up the data structure, - * but the KHO successor kernel only needs to process them once in order. - * - * All of this memory is normal kmalloc() memory and is not marked for - * preservation. The successor kernel will remain isolated to the scratch space - * until it completes processing this list. Once processed all the memory - * storing these ranges will be marked as free. - */ - -struct khoser_mem_bitmap_ptr { - phys_addr_t phys_start; - DECLARE_KHOSER_PTR(bitmap, struct kho_mem_phys_bits *); -}; - -struct khoser_mem_chunk_hdr { - DECLARE_KHOSER_PTR(next, struct khoser_mem_chunk *); - unsigned int order; - unsigned int num_elms; -}; - -#define KHOSER_BITMAP_SIZE \ - ((PAGE_SIZE - sizeof(struct khoser_mem_chunk_hdr)) / \ - sizeof(struct khoser_mem_bitmap_ptr)) - -struct khoser_mem_chunk { - struct khoser_mem_chunk_hdr hdr; - struct khoser_mem_bitmap_ptr bitmaps[KHOSER_BITMAP_SIZE]; -}; - -static_assert(sizeof(struct khoser_mem_chunk) == PAGE_SIZE); - -static struct khoser_mem_chunk *new_chunk(struct khoser_mem_chunk *cur_chunk, - unsigned long order) -{ - struct khoser_mem_chunk *chunk __free(free_page) = NULL; - - chunk = (void *)get_zeroed_page(GFP_KERNEL); - if (!chunk) - return ERR_PTR(-ENOMEM); - - if (WARN_ON(kho_scratch_overlap(virt_to_phys(chunk), PAGE_SIZE))) - return ERR_PTR(-EINVAL); - - chunk->hdr.order = order; - if (cur_chunk) - KHOSER_STORE_PTR(cur_chunk->hdr.next, chunk); - return no_free_ptr(chunk); -} - -static void kho_mem_ser_free(struct khoser_mem_chunk *first_chunk) -{ - struct khoser_mem_chunk *chunk = first_chunk; - - while (chunk) { - struct khoser_mem_chunk *tmp = chunk; - - chunk = KHOSER_LOAD_PTR(chunk->hdr.next); - free_page((unsigned long)tmp); - } -} - -/* - * Update memory map property, if old one is found discard it via - * kho_mem_ser_free(). - */ -static void kho_update_memory_map(struct khoser_mem_chunk *first_chunk) +static int __init kho_radix_walk_tree_memblock_callback(unsigned long radix_key) { - void *ptr; - u64 phys; - - ptr = fdt_getprop_w(kho_out.fdt, 0, KHO_FDT_MEMORY_MAP_PROP_NAME, NULL); - - /* Check and discard previous memory map */ - phys = get_unaligned((u64 *)ptr); - if (phys) - kho_mem_ser_free((struct khoser_mem_chunk *)phys_to_virt(phys)); - - /* Update with the new value */ - phys = first_chunk ? (u64)virt_to_phys(first_chunk) : 0; - put_unaligned(phys, (u64 *)ptr); -} - -static int kho_mem_serialize(struct kho_out *kho_out) -{ - struct khoser_mem_chunk *first_chunk = NULL; - struct khoser_mem_chunk *chunk = NULL; - struct kho_mem_phys *physxa; - unsigned long order; - int err = -ENOMEM; + union kho_page_info info; + unsigned int order; + unsigned long pa; + struct page *page; + int sz; - xa_for_each(&kho_out->track.orders, order, physxa) { - struct kho_mem_phys_bits *bits; - unsigned long phys; + pa = kho_radix_decode_key(radix_key, &order); - chunk = new_chunk(chunk, order); - if (IS_ERR(chunk)) { - err = PTR_ERR(chunk); - goto err_free; - } - - if (!first_chunk) - first_chunk = chunk; - - xa_for_each(&physxa->phys_bits, phys, bits) { - struct khoser_mem_bitmap_ptr *elm; - - if (chunk->hdr.num_elms == ARRAY_SIZE(chunk->bitmaps)) { - chunk = new_chunk(chunk, order); - if (IS_ERR(chunk)) { - err = PTR_ERR(chunk); - goto err_free; - } - } - - elm = &chunk->bitmaps[chunk->hdr.num_elms]; - chunk->hdr.num_elms++; - elm->phys_start = (phys * PRESERVE_BITS) - << (order + PAGE_SHIFT); - KHOSER_STORE_PTR(elm->bitmap, bits); - } - } + sz = 1 << (order + PAGE_SHIFT); + page = phys_to_page(pa); - kho_update_memory_map(first_chunk); + /* Reserve the memory preserved in KHO radix tree in memblock */ + memblock_reserve(pa, sz); + memblock_reserved_mark_noinit(pa, sz); + info.magic = KHO_PAGE_MAGIC; + info.order = order; + page->private = info.page_private; return 0; - -err_free: - kho_mem_ser_free(first_chunk); - return err; } -static void __init deserialize_bitmap(unsigned int order, - struct khoser_mem_bitmap_ptr *elm) -{ - struct kho_mem_phys_bits *bitmap = KHOSER_LOAD_PTR(elm->bitmap); - unsigned long bit; - - for_each_set_bit(bit, bitmap->preserve, PRESERVE_BITS) { - int sz = 1 << (order + PAGE_SHIFT); - phys_addr_t phys = - elm->phys_start + (bit << (order + PAGE_SHIFT)); - struct page *page = phys_to_page(phys); - union kho_page_info info; - - memblock_reserve(phys, sz); - memblock_reserved_mark_noinit(phys, sz); - info.magic = KHO_PAGE_MAGIC; - info.order = order; - page->private = info.page_private; - } -} -/* Return true if memory was deserizlied */ -static bool __init kho_mem_deserialize(const void *fdt) -{ - struct khoser_mem_chunk *chunk; - const void *mem_ptr; - u64 mem; - int len; - - mem_ptr = fdt_getprop(fdt, 0, KHO_FDT_MEMORY_MAP_PROP_NAME, &len); - if (!mem_ptr || len != sizeof(u64)) { - pr_err("failed to get preserved memory bitmaps\n"); - return false; - } - - mem = get_unaligned((const u64 *)mem_ptr); - chunk = mem ? phys_to_virt(mem) : NULL; - - /* No preserved physical pages were passed, no deserialization */ - if (!chunk) - return false; - - while (chunk) { - unsigned int i; - - for (i = 0; i != chunk->hdr.num_elms; i++) - deserialize_bitmap(chunk->hdr.order, - &chunk->bitmaps[i]); - chunk = KHOSER_LOAD_PTR(chunk->hdr.next); - } - - return true; -} /* * With KHO enabled, memory can become fragmented because KHO regions may @@ -789,14 +774,22 @@ EXPORT_SYMBOL_GPL(kho_remove_subtree); */ int kho_preserve_folio(struct folio *folio) { + struct kho_mem_track *track = &kho_out.track; const unsigned long pfn = folio_pfn(folio); const unsigned int order = folio_order(folio); - struct kho_mem_track *track = &kho_out.track; + int err; if (WARN_ON(kho_scratch_overlap(pfn << PAGE_SHIFT, PAGE_SIZE << order))) return -EINVAL; - return __kho_preserve_order(track, pfn, order); + if (WARN_ON_ONCE(!track->root)) + return -EINVAL; + + down_write(&track->sem); + err = kho_radix_add_page(track->root, pfn, order); + up_write(&track->sem); + + return err; } EXPORT_SYMBOL_GPL(kho_preserve_folio); @@ -810,11 +803,16 @@ EXPORT_SYMBOL_GPL(kho_preserve_folio); */ void kho_unpreserve_folio(struct folio *folio) { + struct kho_mem_track *track = &kho_out.track; const unsigned long pfn = folio_pfn(folio); const unsigned int order = folio_order(folio); - struct kho_mem_track *track = &kho_out.track; - __kho_unpreserve_order(track, pfn, order); + if (WARN_ON_ONCE(!track->root)) + return; + + down_write(&track->sem); + kho_radix_del_page(track->root, pfn, order); + up_write(&track->sem); } EXPORT_SYMBOL_GPL(kho_unpreserve_folio); @@ -842,11 +840,15 @@ int kho_preserve_pages(struct page *page, unsigned int nr_pages) return -EINVAL; } + if (WARN_ON_ONCE(!track->root)) + return -EINVAL; + + down_write(&track->sem); while (pfn < end_pfn) { const unsigned int order = min(count_trailing_zeros(pfn), ilog2(end_pfn - pfn)); - err = __kho_preserve_order(track, pfn, order); + err = kho_radix_add_page(track->root, pfn, order); if (err) { failed_pfn = pfn; break; @@ -854,9 +856,10 @@ int kho_preserve_pages(struct page *page, unsigned int nr_pages) pfn += 1 << order; } + up_write(&track->sem); if (err) - __kho_unpreserve(track, start_pfn, failed_pfn); + __kho_unpreserve(start_pfn, failed_pfn); return err; } @@ -874,11 +877,10 @@ EXPORT_SYMBOL_GPL(kho_preserve_pages); */ void kho_unpreserve_pages(struct page *page, unsigned int nr_pages) { - struct kho_mem_track *track = &kho_out.track; const unsigned long start_pfn = page_to_pfn(page); const unsigned long end_pfn = start_pfn + nr_pages; - __kho_unpreserve(track, start_pfn, end_pfn); + __kho_unpreserve(start_pfn, end_pfn); } EXPORT_SYMBOL_GPL(kho_unpreserve_pages); @@ -937,14 +939,13 @@ static struct kho_vmalloc_chunk *new_vmalloc_chunk(struct kho_vmalloc_chunk *cur static void kho_vmalloc_unpreserve_chunk(struct kho_vmalloc_chunk *chunk, unsigned short order) { - struct kho_mem_track *track = &kho_out.track; unsigned long pfn = PHYS_PFN(virt_to_phys(chunk)); - __kho_unpreserve(track, pfn, pfn + 1); + __kho_unpreserve(pfn, pfn + 1); for (int i = 0; i < ARRAY_SIZE(chunk->phys) && chunk->phys[i]; i++) { pfn = PHYS_PFN(chunk->phys[i]); - __kho_unpreserve(track, pfn, pfn + (1 << order)); + __kho_unpreserve(pfn, pfn + (1 << order)); } } @@ -1213,25 +1214,12 @@ EXPORT_SYMBOL_GPL(kho_restore_free); int kho_finalize(void) { - int ret; - - if (!kho_enable) - return -EOPNOTSUPP; - - guard(mutex)(&kho_out.lock); - ret = kho_mem_serialize(&kho_out); - if (ret) - return ret; - - kho_out.finalized = true; - return 0; } bool kho_finalized(void) { - guard(mutex)(&kho_out.lock); - return kho_out.finalized; + return false; } struct kho_in { @@ -1304,18 +1292,49 @@ int kho_retrieve_subtree(const char *name, phys_addr_t *phys) } EXPORT_SYMBOL_GPL(kho_retrieve_subtree); +/* Return non-zero if error */ +static int __init kho_mem_retrieve(const void *fdt) +{ + struct kho_radix_node *tree_root; + const phys_addr_t *mem; + int len; + + /* Retrieve the KHO radix tree from passed-in FDT. */ + mem = fdt_getprop(fdt, 0, KHO_FDT_MEMORY_MAP_PROP_NAME, &len); + + if (!mem || len != sizeof(*mem)) { + pr_err("failed to get preserved KHO memory tree\n"); + return -ENOENT; + } + + if (!*mem) + return -EINVAL; + + tree_root = phys_to_virt(*mem); + return kho_radix_walk_tree(tree_root, KHO_TREE_MAX_DEPTH - 1, + 0, kho_radix_walk_tree_memblock_callback); +} + static __init int kho_out_fdt_setup(void) { + struct kho_mem_track *track = &kho_out.track; void *root = kho_out.fdt; - u64 empty_mem_map = 0; + u64 preserved_mem_tree_pa; int err; err = fdt_create(root, PAGE_SIZE); err |= fdt_finish_reservemap(root); err |= fdt_begin_node(root, ""); err |= fdt_property_string(root, "compatible", KHO_FDT_COMPATIBLE); - err |= fdt_property(root, KHO_FDT_MEMORY_MAP_PROP_NAME, &empty_mem_map, - sizeof(empty_mem_map)); + + down_read(&track->sem); + preserved_mem_tree_pa = (u64)virt_to_phys(track->root); + up_read(&track->sem); + + err |= fdt_property(root, KHO_FDT_MEMORY_MAP_PROP_NAME, + &preserved_mem_tree_pa, + sizeof(preserved_mem_tree_pa)); + err |= fdt_end_node(root); err |= fdt_finish(root); @@ -1324,16 +1343,26 @@ static __init int kho_out_fdt_setup(void) static __init int kho_init(void) { + struct kho_mem_track *track = &kho_out.track; const void *fdt = kho_get_fdt(); int err = 0; if (!kho_enable) return 0; + down_write(&track->sem); + track->root = (struct kho_radix_node *) + kzalloc(PAGE_SIZE, GFP_KERNEL); + up_write(&track->sem); + if (!track->root) { + err = -ENOMEM; + goto err_free_scratch; + } + kho_out.fdt = kho_alloc_preserve(PAGE_SIZE); if (IS_ERR(kho_out.fdt)) { err = PTR_ERR(kho_out.fdt); - goto err_free_scratch; + goto err_free_kho_radix_tree_root; } err = kho_debugfs_init(); @@ -1379,6 +1408,11 @@ static __init int kho_init(void) err_free_fdt: kho_unpreserve_free(kho_out.fdt); + +err_free_kho_radix_tree_root: + kfree(track->root); + track->root = NULL; + err_free_scratch: kho_out.fdt = NULL; for (int i = 0; i < kho_scratch_cnt; i++) { @@ -1422,7 +1456,7 @@ void __init kho_memory_init(void) kho_scratch = phys_to_virt(kho_in.scratch_phys); kho_release_scratch(); - if (!kho_mem_deserialize(kho_get_fdt())) + if (kho_mem_retrieve(kho_get_fdt())) kho_in.fdt_phys = 0; } else { kho_reserve_scratch(); -- 2.52.0.223.gf5cc29aaa4-goog Eliminate the `kho_finalize()` function and its associated state from the KHO subsystem. The transition to a radix tree for memory tracking makes the explicit "finalize" state and its serialization step obsolete. Remove the `kho_finalize()` and `kho_finalized()` APIs and their stub implementations. Update KHO client code and the debugfs interface to no longer call or depend on the `kho_finalize()` mechanism. Complete the move towards a stateless KHO, simplifying the overall design by removing unnecessary state management. Signed-off-by: Jason Miu --- Documentation/admin-guide/mm/kho.rst | 46 ++++----------------- Documentation/core-api/kho/concepts.rst | 13 +----- kernel/liveupdate/kexec_handover.c | 10 ----- kernel/liveupdate/kexec_handover_debugfs.c | 20 --------- kernel/liveupdate/kexec_handover_internal.h | 3 -- kernel/liveupdate/luo_core.c | 12 +----- kernel/liveupdate/luo_flb.c | 2 +- tools/testing/selftests/kho/init.c | 20 --------- 8 files changed, 10 insertions(+), 116 deletions(-) diff --git a/Documentation/admin-guide/mm/kho.rst b/Documentation/admin-guide/mm/kho.rst index 6dc18ed4b886..13910bc68efe 100644 --- a/Documentation/admin-guide/mm/kho.rst +++ b/Documentation/admin-guide/mm/kho.rst @@ -28,17 +28,7 @@ per NUMA node scratch regions on boot. Perform a KHO kexec =================== -First, before you perform a KHO kexec, you need to move the system into -the :ref:`KHO finalization phase ` :: - - $ echo 1 > /sys/kernel/debug/kho/out/finalize - -After this command, the KHO FDT is available in -``/sys/kernel/debug/kho/out/fdt``. Other subsystems may also register -their own preserved sub FDTs under -``/sys/kernel/debug/kho/out/sub_fdts/``. - -Next, load the target payload and kexec into it. It is important that you +To perform a KHO kexec, load the target payload and kexec into it. It is important that you use the ``-s`` parameter to use the in-kernel kexec file loader, as user space kexec tooling currently has no support for KHO with the user space based file loader :: @@ -52,40 +42,19 @@ For example, if you used ``reserve_mem`` command line parameter to create an early memory reservation, the new kernel will have that memory at the same physical address as the old kernel. -Abort a KHO exec -================ - -You can move the system out of KHO finalization phase again by calling :: - - $ echo 0 > /sys/kernel/debug/kho/out/active - -After this command, the KHO FDT is no longer available in -``/sys/kernel/debug/kho/out/fdt``. - debugfs Interfaces ================== +These debugfs interfaces are available when the kernel is compiled with +``CONFIG_KEXEC_HANDOVER_DEBUGFS`` set to y. + Currently KHO creates the following debugfs interfaces. Notice that these interfaces may change in the future. They will be moved to sysfs once KHO is stabilized. -``/sys/kernel/debug/kho/out/finalize`` - Kexec HandOver (KHO) allows Linux to transition the state of - compatible drivers into the next kexec'ed kernel. To do so, - device drivers will instruct KHO to preserve memory regions, - which could contain serialized kernel state. - While the state is serialized, they are unable to perform - any modifications to state that was serialized, such as - handed over memory allocations. - - When this file contains "1", the system is in the transition - state. When contains "0", it is not. To switch between the - two states, echo the respective number into this file. - ``/sys/kernel/debug/kho/out/fdt`` - When KHO state tree is finalized, the kernel exposes the - flattened device tree blob that carries its current KHO - state in this file. Kexec user space tooling can use this + The kernel exposes the flattened device tree blob that carries its + current KHO state in this file. Kexec user space tooling can use this as input file for the KHO payload image. ``/sys/kernel/debug/kho/out/scratch_len`` @@ -100,8 +69,7 @@ stabilized. it should place its payload images. ``/sys/kernel/debug/kho/out/sub_fdts/`` - In the KHO finalization phase, KHO producers register their own - FDT blob under this directory. + KHO producers can register their own FDT blob under this directory. ``/sys/kernel/debug/kho/in/fdt`` When the kernel was booted with Kexec HandOver (KHO), diff --git a/Documentation/core-api/kho/concepts.rst b/Documentation/core-api/kho/concepts.rst index d38bcaa951e4..0ac01760db18 100644 --- a/Documentation/core-api/kho/concepts.rst +++ b/Documentation/core-api/kho/concepts.rst @@ -6,7 +6,7 @@ Kexec Handover Concepts ======================= Kexec HandOver (KHO) is a mechanism that allows Linux to preserve memory -regions, which could contain serialized system states, across kexec. +regions, containing kernel data structures in their live, in-memory format, across kexec. It introduces multiple concepts: @@ -56,17 +56,6 @@ for boot memory allocations and as target memory for kexec blobs, some parts of that memory region may be reserved. These reservations are irrelevant for the next KHO, because kexec can overwrite even the original kernel. -.. _kho-finalization-phase: - -KHO finalization phase -====================== - -To enable user space based kexec file loader, the kernel needs to be able to -provide the FDT that describes the current kernel's state before -performing the actual kexec. The process of generating that FDT is -called serialization. When the FDT is generated, some properties -of the system may become immutable because they are already written down -in the FDT. That state is called the KHO finalization phase. Public API ========== diff --git a/kernel/liveupdate/kexec_handover.c b/kernel/liveupdate/kexec_handover.c index 81bac82c8672..92b052450ce4 100644 --- a/kernel/liveupdate/kexec_handover.c +++ b/kernel/liveupdate/kexec_handover.c @@ -1212,16 +1212,6 @@ void kho_restore_free(void *mem) } EXPORT_SYMBOL_GPL(kho_restore_free); -int kho_finalize(void) -{ - return 0; -} - -bool kho_finalized(void) -{ - return false; -} - struct kho_in { phys_addr_t fdt_phys; phys_addr_t scratch_phys; diff --git a/kernel/liveupdate/kexec_handover_debugfs.c b/kernel/liveupdate/kexec_handover_debugfs.c index 2abbf62ba942..2f70d9c41831 100644 --- a/kernel/liveupdate/kexec_handover_debugfs.c +++ b/kernel/liveupdate/kexec_handover_debugfs.c @@ -75,24 +75,6 @@ void kho_debugfs_fdt_remove(struct kho_debugfs *dbg, void *fdt) } } -static int kho_out_finalize_get(void *data, u64 *val) -{ - *val = kho_finalized(); - - return 0; -} - -static int kho_out_finalize_set(void *data, u64 val) -{ - if (val) - return kho_finalize(); - else - return -EINVAL; -} - -DEFINE_DEBUGFS_ATTRIBUTE(kho_out_finalize_fops, kho_out_finalize_get, - kho_out_finalize_set, "%llu\n"); - static int scratch_phys_show(struct seq_file *m, void *v) { for (int i = 0; i < kho_scratch_cnt; i++) @@ -198,8 +180,6 @@ __init int kho_out_debugfs_init(struct kho_debugfs *dbg) if (IS_ERR(f)) goto err_rmdir; - f = debugfs_create_file("finalize", 0600, dir, NULL, - &kho_out_finalize_fops); if (IS_ERR(f)) goto err_rmdir; diff --git a/kernel/liveupdate/kexec_handover_internal.h b/kernel/liveupdate/kexec_handover_internal.h index 0202c85ad14f..9a832a35254c 100644 --- a/kernel/liveupdate/kexec_handover_internal.h +++ b/kernel/liveupdate/kexec_handover_internal.h @@ -22,9 +22,6 @@ struct kho_debugfs {}; extern struct kho_scratch *kho_scratch; extern unsigned int kho_scratch_cnt; -bool kho_finalized(void); -int kho_finalize(void); - #ifdef CONFIG_KEXEC_HANDOVER_DEBUGFS int kho_debugfs_init(void); void kho_in_debugfs_init(struct kho_debugfs *dbg, const void *fdt); diff --git a/kernel/liveupdate/luo_core.c b/kernel/liveupdate/luo_core.c index 69298d82f404..e4db15d81f89 100644 --- a/kernel/liveupdate/luo_core.c +++ b/kernel/liveupdate/luo_core.c @@ -231,17 +231,7 @@ int liveupdate_reboot(void) luo_flb_serialize(); - err = kho_finalize(); - if (err) { - pr_err("kho_finalize failed %d\n", err); - /* - * kho_finalize() may return libfdt errors, to aboid passing to - * userspace unknown errors, change this to EAGAIN. - */ - err = -EAGAIN; - } - - return err; + return 0; } /** diff --git a/kernel/liveupdate/luo_flb.c b/kernel/liveupdate/luo_flb.c index e80ac5b575ec..92d35eb5e6ee 100644 --- a/kernel/liveupdate/luo_flb.c +++ b/kernel/liveupdate/luo_flb.c @@ -632,7 +632,7 @@ int __init luo_flb_setup_incoming(void *fdt_in) * data handle, and the final reference count. This allows the new kernel to * find the appropriate handler and reconstruct the FLB's state. * - * Context: Called from liveupdate_reboot() just before kho_finalize(). + * Context: Called from liveupdate_reboot() just before return. */ void luo_flb_serialize(void) { diff --git a/tools/testing/selftests/kho/init.c b/tools/testing/selftests/kho/init.c index 6d9e91d55d68..88a41b6eba95 100644 --- a/tools/testing/selftests/kho/init.c +++ b/tools/testing/selftests/kho/init.c @@ -11,7 +11,6 @@ /* from arch/x86/include/asm/setup.h */ #define COMMAND_LINE_SIZE 2048 -#define KHO_FINALIZE "/debugfs/kho/out/finalize" #define KERNEL_IMAGE "/kernel" static int mount_filesystems(void) @@ -22,22 +21,6 @@ static int mount_filesystems(void) return mount("proc", "/proc", "proc", 0, NULL); } -static int kho_enable(void) -{ - const char enable[] = "1"; - int fd; - - fd = open(KHO_FINALIZE, O_RDWR); - if (fd < 0) - return -1; - - if (write(fd, enable, sizeof(enable)) != sizeof(enable)) - return 1; - - close(fd); - return 0; -} - static long kexec_file_load(int kernel_fd, int initrd_fd, unsigned long cmdline_len, const char *cmdline, unsigned long flags) @@ -78,9 +61,6 @@ int main(int argc, char *argv[]) if (mount_filesystems()) goto err_reboot; - if (kho_enable()) - goto err_reboot; - if (kexec_load()) goto err_reboot; -- 2.52.0.223.gf5cc29aaa4-goog