1 // SPDX-License-Identifier: GPL-2.0-only
2 
3 #include "error.h"
4 #include "misc.h"
5 #include "tdx.h"
6 #include "sev.h"
7 #include <asm/shared/tdx.h>
8 
9 /*
10  * accept_memory() and process_unaccepted_memory() called from EFI stub which
11  * runs before decompressor and its early_tdx_detect().
12  *
13  * Enumerate TDX directly from the early users.
14  */
early_is_tdx_guest(void)15 static bool early_is_tdx_guest(void)
16 {
17 	static bool once;
18 	static bool is_tdx;
19 
20 	if (!IS_ENABLED(CONFIG_INTEL_TDX_GUEST))
21 		return false;
22 
23 	if (!once) {
24 		u32 eax, sig[3];
25 
26 		cpuid_count(TDX_CPUID_LEAF_ID, 0, &eax,
27 			    &sig[0], &sig[2],  &sig[1]);
28 		is_tdx = !memcmp(TDX_IDENT, sig, sizeof(sig));
29 		once = true;
30 	}
31 
32 	return is_tdx;
33 }
34 
arch_accept_memory(phys_addr_t start,phys_addr_t end)35 void arch_accept_memory(phys_addr_t start, phys_addr_t end)
36 {
37 	static bool sevsnp;
38 
39 	/* Platform-specific memory-acceptance call goes here */
40 	if (early_is_tdx_guest()) {
41 		if (!tdx_accept_memory(start, end))
42 			panic("TDX: Failed to accept memory\n");
43 	} else if (sevsnp || (sev_get_status() & MSR_AMD64_SEV_SNP_ENABLED)) {
44 		sevsnp = true;
45 		snp_accept_memory(start, end);
46 	} else {
47 		error("Cannot accept memory: unknown platform\n");
48 	}
49 }
50 
init_unaccepted_memory(void)51 bool init_unaccepted_memory(void)
52 {
53 	guid_t guid = LINUX_EFI_UNACCEPTED_MEM_TABLE_GUID;
54 	struct efi_unaccepted_memory *table;
55 	unsigned long cfg_table_pa;
56 	unsigned int cfg_table_len;
57 	enum efi_type et;
58 	int ret;
59 
60 	et = efi_get_type(boot_params_ptr);
61 	if (et == EFI_TYPE_NONE)
62 		return false;
63 
64 	ret = efi_get_conf_table(boot_params_ptr, &cfg_table_pa, &cfg_table_len);
65 	if (ret) {
66 		warn("EFI config table not found.");
67 		return false;
68 	}
69 
70 	table = (void *)efi_find_vendor_table(boot_params_ptr, cfg_table_pa,
71 					      cfg_table_len, guid);
72 	if (!table)
73 		return false;
74 
75 	if (table->version != 1)
76 		error("Unknown version of unaccepted memory table\n");
77 
78 	/*
79 	 * In many cases unaccepted_table is already set by EFI stub, but it
80 	 * has to be initialized again to cover cases when the table is not
81 	 * allocated by EFI stub or EFI stub copied the kernel image with
82 	 * efi_relocate_kernel() before the variable is set.
83 	 *
84 	 * It must be initialized before the first usage of accept_memory().
85 	 */
86 	unaccepted_table = table;
87 
88 	return true;
89 }
90