1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Copyright(c) 2023 Intel Corporation.
4 *
5 * Intel Trusted Domain Extensions (TDX) support
6 */
7
8 #include "asm/page_types.h"
9 #define pr_fmt(fmt) "virt/tdx: " fmt
10
11 #include <linux/types.h>
12 #include <linux/cache.h>
13 #include <linux/init.h>
14 #include <linux/errno.h>
15 #include <linux/printk.h>
16 #include <linux/cpu.h>
17 #include <linux/spinlock.h>
18 #include <linux/percpu-defs.h>
19 #include <linux/mutex.h>
20 #include <linux/list.h>
21 #include <linux/memblock.h>
22 #include <linux/memory.h>
23 #include <linux/minmax.h>
24 #include <linux/sizes.h>
25 #include <linux/pfn.h>
26 #include <linux/align.h>
27 #include <linux/sort.h>
28 #include <linux/log2.h>
29 #include <linux/acpi.h>
30 #include <linux/suspend.h>
31 #include <linux/syscore_ops.h>
32 #include <linux/idr.h>
33 #include <linux/vmalloc.h>
34 #include <asm/page.h>
35 #include <asm/special_insns.h>
36 #include <asm/msr-index.h>
37 #include <asm/msr.h>
38 #include <asm/cpufeature.h>
39 #include <asm/tdx.h>
40 #include <asm/shared/tdx_errno.h>
41 #include <asm/cpu_device_id.h>
42 #include <asm/processor.h>
43 #include <asm/mce.h>
44 #include <asm/virt.h>
45 #include <asm/vmx.h>
46
47 #include "seamcall_internal.h"
48 #include "tdx.h"
49
50 /* Number of DPAMT pages to be provided to TDX module per 2MB region of PA */
51 #define TDX_DPAMT_ENTRY_PAGE_CNT 2
52
53 struct tdx_module_state {
54 bool initialized;
55 bool sysinit_done;
56 int sysinit_ret;
57 };
58
59 static struct tdx_module_state tdx_module_state;
60 static u32 tdx_global_keyid __ro_after_init;
61 static u32 tdx_guest_keyid_start __ro_after_init;
62 static u32 tdx_nr_guest_keyids __ro_after_init;
63
64 static DEFINE_IDA(tdx_guest_keyid_pool);
65
66 static DEFINE_PER_CPU(bool, tdx_lp_initialized);
67
68 static struct tdmr_info_list tdx_tdmr_list;
69
70 /*
71 * On a machine with DPAMT, the kernel maintains a reference counter
72 * for every 2MB range. The counter indicates how many users there are for
73 * the DPAMT at the 2MB range. The kernel allocates DPAMT refcounts at
74 * initialization.
75 */
76 static atomic_t *dpamt_refcounts;
77
78 /* All TDX-usable memory regions. Protected by mem_hotplug_lock. */
79 static LIST_HEAD(tdx_memlist);
80
81 static struct tdx_sys_info tdx_sysinfo;
82
83 static DEFINE_RAW_SPINLOCK(sysinit_lock);
84
85 /*
86 * Do the module global initialization once and return its result.
87 * It can be done on any cpu, and from task or IRQ context.
88 */
try_init_module_global(void)89 static int try_init_module_global(void)
90 {
91 struct tdx_module_args args = {};
92 int ret;
93
94 raw_spin_lock(&sysinit_lock);
95
96 /* Return the "cached" return code. */
97 if (tdx_module_state.sysinit_done) {
98 ret = tdx_module_state.sysinit_ret;
99 goto out;
100 }
101
102 /* RCX is module attributes and all bits are reserved */
103 args.rcx = 0;
104 ret = seamcall_prerr(TDH_SYS_INIT, &args);
105
106 /*
107 * The first SEAMCALL also detects the TDX module, thus
108 * it can fail due to the TDX module is not loaded.
109 * Dump message to let the user know.
110 */
111 if (ret == -ENODEV)
112 pr_err("module not loaded\n");
113
114 /* Save the return code for later callers. */
115 tdx_module_state.sysinit_done = true;
116 tdx_module_state.sysinit_ret = ret;
117 out:
118 raw_spin_unlock(&sysinit_lock);
119 return ret;
120 }
121
122 /**
123 * Enable VMXON and then do one-time TDX module per-cpu initialization SEAMCALL
124 * (and TDX module global initialization SEAMCALL if not done) on local cpu to
125 * make this cpu be ready to run any other SEAMCALLs.
126 */
tdx_cpu_enable(void)127 int tdx_cpu_enable(void)
128 {
129 struct tdx_module_args args = {};
130 int ret;
131
132 if (__this_cpu_read(tdx_lp_initialized))
133 return 0;
134
135 /*
136 * The TDX module global initialization is the very first step
137 * to enable TDX. Need to do it first (if hasn't been done)
138 * before the per-cpu initialization.
139 */
140 ret = try_init_module_global();
141 if (ret)
142 return ret;
143
144 ret = seamcall_prerr(TDH_SYS_LP_INIT, &args);
145 if (ret)
146 return ret;
147
148 __this_cpu_write(tdx_lp_initialized, true);
149
150 return 0;
151 }
152
tdx_online_cpu(unsigned int cpu)153 static int tdx_online_cpu(unsigned int cpu)
154 {
155 int ret;
156
157 ret = x86_virt_get_ref(X86_FEATURE_VMX);
158 if (ret)
159 return ret;
160
161 ret = tdx_cpu_enable();
162 if (ret)
163 x86_virt_put_ref(X86_FEATURE_VMX);
164
165 return ret;
166 }
167
tdx_cpu_flush_cache(void)168 static void tdx_cpu_flush_cache(void)
169 {
170 lockdep_assert_preemption_disabled();
171
172 if (!this_cpu_read(cache_state_incoherent))
173 return;
174
175 wbinvd();
176 this_cpu_write(cache_state_incoherent, false);
177 }
178
tdx_offline_cpu(unsigned int cpu)179 static int tdx_offline_cpu(unsigned int cpu)
180 {
181 int i;
182
183 /* No TD is running. Allow any cpu to be offline. */
184 if (ida_is_empty(&tdx_guest_keyid_pool))
185 goto done;
186
187 /*
188 * In order to reclaim TDX HKID, (i.e. when deleting guest TD), need to
189 * call TDH.PHYMEM.PAGE.WBINVD on all packages to program all memory
190 * controller with pconfig. If we have active TDX HKID, refuse to
191 * offline the last online cpu.
192 */
193 for_each_online_cpu(i) {
194 /*
195 * Found another online cpu on the same package.
196 * Allow to offline.
197 */
198 if (i != cpu && topology_physical_package_id(i) ==
199 topology_physical_package_id(cpu))
200 goto done;
201 }
202
203 /*
204 * This is the last cpu of this package. Don't offline it.
205 *
206 * Because it's hard for human operator to understand the
207 * reason, warn it.
208 */
209 #define MSG_ALLPKG_ONLINE \
210 "TDX requires all packages to have an online CPU. Delete all TDs in order to offline all CPUs of a package.\n"
211 pr_warn_ratelimited(MSG_ALLPKG_ONLINE);
212 return -EBUSY;
213
214 done:
215 /*
216 * Flush cache on the CPU going offline to ensure no dirty
217 * cachelines of TDX private memory remain. This may be
218 * redundant with WBINVD done elsewhere during CPU offline
219 * (e.g. hlt_play_dead()), but do it explicitly for safety.
220 */
221 tdx_cpu_flush_cache();
222 x86_virt_put_ref(X86_FEATURE_VMX);
223 return 0;
224 }
225
tdx_shutdown_cpu(void * ign)226 static void tdx_shutdown_cpu(void *ign)
227 {
228 /*
229 * Flush cache in preparation for kexec - this is necessary to avoid
230 * having dirty private memory cachelines when the new kernel boots,
231 * but WBINVD is a relatively expensive operation and doing it during
232 * kexec can exacerbate races in native_stop_other_cpus(). Do it
233 * now, since this is a safe moment and there is going to be no more
234 * TDX activity on this CPU from this point on.
235 */
236 tdx_cpu_flush_cache();
237 x86_virt_put_ref(X86_FEATURE_VMX);
238 }
239
tdx_shutdown(void * ign)240 static void tdx_shutdown(void *ign)
241 {
242 tdx_sys_disable();
243 on_each_cpu(tdx_shutdown_cpu, NULL, 1);
244 }
245
tdx_suspend(void * ign)246 static int tdx_suspend(void *ign)
247 {
248 x86_virt_put_ref(X86_FEATURE_VMX);
249 return 0;
250 }
251
tdx_resume(void * ign)252 static void tdx_resume(void *ign)
253 {
254 WARN_ON_ONCE(x86_virt_get_ref(X86_FEATURE_VMX));
255 }
256
257 static const struct syscore_ops tdx_syscore_ops = {
258 .suspend = tdx_suspend,
259 .resume = tdx_resume,
260 .shutdown = tdx_shutdown,
261 };
262
263 static struct syscore tdx_syscore = {
264 .ops = &tdx_syscore_ops,
265 };
266
267 /*
268 * Allocate DPAMT reference counters for all physical memory.
269 *
270 * It consumes 2MB for every 1TB of physical memory.
271 */
init_dpamt_refcounts(void)272 static __init int init_dpamt_refcounts(void)
273 {
274 size_t size = DIV_ROUND_UP(max_pfn, PTRS_PER_PTE) * sizeof(*dpamt_refcounts);
275
276 if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
277 return 0;
278
279 dpamt_refcounts = vzalloc(size);
280 if (!dpamt_refcounts)
281 return -ENOMEM;
282
283 return 0;
284 }
285
free_dpamt_refcounts(void)286 static __init void free_dpamt_refcounts(void)
287 {
288 if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
289 return;
290
291 vfree(dpamt_refcounts);
292 dpamt_refcounts = NULL;
293 }
294
tdx_find_dpamt_refcount(unsigned long pfn)295 static atomic_t *tdx_find_dpamt_refcount(unsigned long pfn)
296 {
297 /* Find which PMD a PFN is in. */
298 unsigned long index = pfn >> (PMD_SHIFT - PAGE_SHIFT);
299
300 return &dpamt_refcounts[index];
301 }
302
303 /*
304 * Add a memory region as a TDX memory block. The caller must make sure
305 * all memory regions are added in address ascending order and don't
306 * overlap.
307 */
add_tdx_memblock(struct list_head * tmb_list,unsigned long start_pfn,unsigned long end_pfn,int nid)308 static __init int add_tdx_memblock(struct list_head *tmb_list,
309 unsigned long start_pfn,
310 unsigned long end_pfn, int nid)
311 {
312 struct tdx_memblock *tmb;
313
314 tmb = kmalloc_obj(*tmb);
315 if (!tmb)
316 return -ENOMEM;
317
318 INIT_LIST_HEAD(&tmb->list);
319 tmb->start_pfn = start_pfn;
320 tmb->end_pfn = end_pfn;
321 tmb->nid = nid;
322
323 /* @tmb_list is protected by mem_hotplug_lock */
324 list_add_tail(&tmb->list, tmb_list);
325 return 0;
326 }
327
free_tdx_memlist(struct list_head * tmb_list)328 static __init void free_tdx_memlist(struct list_head *tmb_list)
329 {
330 /* @tmb_list is protected by mem_hotplug_lock */
331 while (!list_empty(tmb_list)) {
332 struct tdx_memblock *tmb = list_first_entry(tmb_list,
333 struct tdx_memblock, list);
334
335 list_del(&tmb->list);
336 kfree(tmb);
337 }
338 }
339
340 /*
341 * Ensure that all memblock memory regions are convertible to TDX
342 * memory. Once this has been established, stash the memblock
343 * ranges off in a secondary structure because memblock is modified
344 * in memory hotplug while TDX memory regions are fixed.
345 */
build_tdx_memlist(struct list_head * tmb_list)346 static __init int build_tdx_memlist(struct list_head *tmb_list)
347 {
348 unsigned long start_pfn, end_pfn;
349 int i, nid, ret;
350
351 for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, &nid) {
352 /*
353 * The first 1MB is not reported as TDX convertible memory.
354 * Although the first 1MB is always reserved and won't end up
355 * to the page allocator, it is still in memblock's memory
356 * regions. Skip them manually to exclude them as TDX memory.
357 */
358 start_pfn = max(start_pfn, PHYS_PFN(SZ_1M));
359 if (start_pfn >= end_pfn)
360 continue;
361
362 /*
363 * Add the memory regions as TDX memory. The regions in
364 * memblock has already guaranteed they are in address
365 * ascending order and don't overlap.
366 */
367 ret = add_tdx_memblock(tmb_list, start_pfn, end_pfn, nid);
368 if (ret)
369 goto err;
370 }
371
372 return 0;
373 err:
374 free_tdx_memlist(tmb_list);
375 return ret;
376 }
377
read_sys_metadata_field(u64 field_id,u64 * data)378 static int read_sys_metadata_field(u64 field_id, u64 *data)
379 {
380 struct tdx_module_args args = {};
381 int ret;
382
383 /*
384 * TDH.SYS.RD -- reads one global metadata field
385 * - RDX (in): the field to read
386 * - R8 (out): the field data
387 */
388 args.rdx = field_id;
389 ret = seamcall_prerr_ret(TDH_SYS_RD, &args);
390 if (ret)
391 return ret;
392
393 *data = args.r8;
394
395 return 0;
396 }
397
398 #include "tdx_global_metadata.c"
399
check_features(struct tdx_sys_info * sysinfo)400 static __init int check_features(struct tdx_sys_info *sysinfo)
401 {
402 u64 tdx_features0 = sysinfo->features.tdx_features0;
403
404 if (!(tdx_features0 & TDX_FEATURES0_NO_RBP_MOD)) {
405 pr_err("frame pointer (RBP) clobber bug present, upgrade TDX module\n");
406 return -EINVAL;
407 }
408
409 return 0;
410 }
411
412 /* Calculate the actual TDMR size */
tdmr_size_single(u16 max_reserved_per_tdmr)413 static __init int tdmr_size_single(u16 max_reserved_per_tdmr)
414 {
415 int tdmr_sz;
416
417 /*
418 * The actual size of TDMR depends on the maximum
419 * number of reserved areas.
420 */
421 tdmr_sz = sizeof(struct tdmr_info);
422 tdmr_sz += sizeof(struct tdmr_reserved_area) * max_reserved_per_tdmr;
423
424 return ALIGN(tdmr_sz, TDMR_INFO_ALIGNMENT);
425 }
426
alloc_tdmr_list(struct tdmr_info_list * tdmr_list,struct tdx_sys_info_tdmr * sysinfo_tdmr)427 static __init int alloc_tdmr_list(struct tdmr_info_list *tdmr_list,
428 struct tdx_sys_info_tdmr *sysinfo_tdmr)
429 {
430 size_t tdmr_sz, tdmr_array_sz;
431 void *tdmr_array;
432
433 tdmr_sz = tdmr_size_single(sysinfo_tdmr->max_reserved_per_tdmr);
434 tdmr_array_sz = tdmr_sz * sysinfo_tdmr->max_tdmrs;
435
436 /*
437 * To keep things simple, allocate all TDMRs together.
438 * The buffer needs to be physically contiguous to make
439 * sure each TDMR is physically contiguous.
440 */
441 tdmr_array = alloc_pages_exact(tdmr_array_sz,
442 GFP_KERNEL | __GFP_ZERO);
443 if (!tdmr_array)
444 return -ENOMEM;
445
446 tdmr_list->tdmrs = tdmr_array;
447
448 /*
449 * Keep the size of TDMR to find the target TDMR
450 * at a given index in the TDMR list.
451 */
452 tdmr_list->tdmr_sz = tdmr_sz;
453 tdmr_list->max_tdmrs = sysinfo_tdmr->max_tdmrs;
454 tdmr_list->nr_consumed_tdmrs = 0;
455
456 return 0;
457 }
458
free_tdmr_list(struct tdmr_info_list * tdmr_list)459 static __init void free_tdmr_list(struct tdmr_info_list *tdmr_list)
460 {
461 free_pages_exact(tdmr_list->tdmrs,
462 tdmr_list->max_tdmrs * tdmr_list->tdmr_sz);
463 }
464
465 /* Get the TDMR from the list at the given index. */
tdmr_entry(struct tdmr_info_list * tdmr_list,int idx)466 static struct tdmr_info *tdmr_entry(struct tdmr_info_list *tdmr_list,
467 int idx)
468 {
469 int tdmr_info_offset = tdmr_list->tdmr_sz * idx;
470
471 return (void *)tdmr_list->tdmrs + tdmr_info_offset;
472 }
473
474 #define TDMR_ALIGNMENT SZ_1G
475 #define TDMR_ALIGN_DOWN(_addr) ALIGN_DOWN((_addr), TDMR_ALIGNMENT)
476 #define TDMR_ALIGN_UP(_addr) ALIGN((_addr), TDMR_ALIGNMENT)
477
tdmr_end(struct tdmr_info * tdmr)478 static inline u64 tdmr_end(struct tdmr_info *tdmr)
479 {
480 return tdmr->base + tdmr->size;
481 }
482
483 /*
484 * Take the memory referenced in @tmb_list and populate the
485 * preallocated @tdmr_list, following all the special alignment
486 * and size rules for TDMR.
487 */
fill_out_tdmrs(struct list_head * tmb_list,struct tdmr_info_list * tdmr_list)488 static __init int fill_out_tdmrs(struct list_head *tmb_list,
489 struct tdmr_info_list *tdmr_list)
490 {
491 struct tdx_memblock *tmb;
492 int tdmr_idx = 0;
493
494 /*
495 * Loop over TDX memory regions and fill out TDMRs to cover them.
496 * To keep it simple, always try to use one TDMR to cover one
497 * memory region.
498 *
499 * In practice TDX supports at least 64 TDMRs. A 2-socket system
500 * typically only consumes less than 10 of those. This code is
501 * dumb and simple and may use more TMDRs than is strictly
502 * required.
503 */
504 list_for_each_entry(tmb, tmb_list, list) {
505 struct tdmr_info *tdmr = tdmr_entry(tdmr_list, tdmr_idx);
506 u64 start, end;
507
508 start = TDMR_ALIGN_DOWN(PFN_PHYS(tmb->start_pfn));
509 end = TDMR_ALIGN_UP(PFN_PHYS(tmb->end_pfn));
510
511 /*
512 * A valid size indicates the current TDMR has already
513 * been filled out to cover the previous memory region(s).
514 */
515 if (tdmr->size) {
516 /*
517 * Loop to the next if the current memory region
518 * has already been fully covered.
519 */
520 if (end <= tdmr_end(tdmr))
521 continue;
522
523 /* Otherwise, skip the already covered part. */
524 if (start < tdmr_end(tdmr))
525 start = tdmr_end(tdmr);
526
527 /*
528 * Create a new TDMR to cover the current memory
529 * region, or the remaining part of it.
530 */
531 tdmr_idx++;
532 if (tdmr_idx >= tdmr_list->max_tdmrs) {
533 pr_warn("initialization failed: TDMRs exhausted.\n");
534 return -ENOSPC;
535 }
536
537 tdmr = tdmr_entry(tdmr_list, tdmr_idx);
538 }
539
540 tdmr->base = start;
541 tdmr->size = end - start;
542 }
543
544 /* @tdmr_idx is always the index of the last valid TDMR. */
545 tdmr_list->nr_consumed_tdmrs = tdmr_idx + 1;
546
547 /*
548 * Warn early that kernel is about to run out of TDMRs.
549 *
550 * This is an indication that TDMR allocation has to be
551 * reworked to be smarter to not run into an issue.
552 */
553 if (tdmr_list->max_tdmrs - tdmr_list->nr_consumed_tdmrs < TDMR_NR_WARN)
554 pr_warn("consumed TDMRs reaching limit: %d used out of %d\n",
555 tdmr_list->nr_consumed_tdmrs,
556 tdmr_list->max_tdmrs);
557
558 return 0;
559 }
560
tdmr_get_pamt_bitmap_sz(struct tdmr_info * tdmr)561 static __init unsigned long tdmr_get_pamt_bitmap_sz(struct tdmr_info *tdmr)
562 {
563 unsigned long pamt_sz, nr_pamt_entries;
564 int bits_per_entry;
565
566 bits_per_entry = tdx_sysinfo.tdmr.pamt_page_bitmap_entry_bits;
567 nr_pamt_entries = tdmr->size >> PAGE_SHIFT;
568 pamt_sz = DIV_ROUND_UP(nr_pamt_entries * bits_per_entry, BITS_PER_BYTE);
569
570 return PAGE_ALIGN(pamt_sz);
571 }
572
573 /*
574 * Calculate PAMT size given a TDMR and a page size. The returned
575 * PAMT size is always aligned up to 4K page boundary.
576 */
tdmr_get_pamt_sz(struct tdmr_info * tdmr,int pgsz)577 static __init unsigned long tdmr_get_pamt_sz(struct tdmr_info *tdmr, int pgsz)
578 {
579 unsigned long pamt_sz, nr_pamt_entries;
580 const int tdx_pg_size_shift[TDX_PS_NR] = { PAGE_SHIFT, PMD_SHIFT, PUD_SHIFT };
581 const u16 pamt_entry_size[TDX_PS_NR] = {
582 tdx_sysinfo.tdmr.pamt_4k_entry_size,
583 tdx_sysinfo.tdmr.pamt_2m_entry_size,
584 tdx_sysinfo.tdmr.pamt_1g_entry_size,
585 };
586
587 nr_pamt_entries = tdmr->size >> tdx_pg_size_shift[pgsz];
588 pamt_sz = nr_pamt_entries * pamt_entry_size[pgsz];
589
590 /* TDX requires PAMT size must be 4K aligned */
591 return PAGE_ALIGN(pamt_sz);
592 }
593
594 /*
595 * Locate a NUMA node which should hold the allocation of the @tdmr
596 * PAMT. This node will have some memory covered by the TDMR. The
597 * relative amount of memory covered is not considered.
598 */
tdmr_get_nid(struct tdmr_info * tdmr,struct list_head * tmb_list)599 static __init int tdmr_get_nid(struct tdmr_info *tdmr, struct list_head *tmb_list)
600 {
601 struct tdx_memblock *tmb;
602
603 /*
604 * A TDMR must cover at least part of one TMB. That TMB will end
605 * after the TDMR begins. But, that TMB may have started before
606 * the TDMR. Find the next 'tmb' that _ends_ after this TDMR
607 * begins. Ignore 'tmb' start addresses. They are irrelevant.
608 */
609 list_for_each_entry(tmb, tmb_list, list) {
610 if (tmb->end_pfn > PHYS_PFN(tdmr->base))
611 return tmb->nid;
612 }
613
614 /*
615 * Fall back to allocating the TDMR's metadata from node 0 when
616 * no TDX memory block can be found. This should never happen
617 * since TDMRs originate from TDX memory blocks.
618 */
619 pr_warn("TDMR [0x%llx, 0x%llx): unable to find local NUMA node for PAMT allocation, fallback to use node 0.\n",
620 tdmr->base, tdmr_end(tdmr));
621 return 0;
622 }
623
624 /*
625 * Allocate PAMTs from the local NUMA node of some memory in @tmb_list
626 * within @tdmr, and set up PAMTs for @tdmr.
627 */
tdmr_set_up_pamt(struct tdmr_info * tdmr,struct list_head * tmb_list)628 static __init int tdmr_set_up_pamt(struct tdmr_info *tdmr,
629 struct list_head *tmb_list)
630 {
631 unsigned long tdmr_pamt_size;
632 struct page *pamt;
633 int nid;
634
635 nid = tdmr_get_nid(tdmr, tmb_list);
636
637 /*
638 * Calculate the PAMT size for each TDX supported page size
639 * and the total PAMT size.
640 */
641 tdmr->pamt_1g_size = tdmr_get_pamt_sz(tdmr, TDX_PS_1G);
642 tdmr->pamt_2m_size = tdmr_get_pamt_sz(tdmr, TDX_PS_2M);
643
644 if (tdx_supports_dynamic_pamt(&tdx_sysinfo)) {
645 /* With DPAMT, PAMT_4K is replaced with a bitmap */
646 tdmr->pamt_4k_size = tdmr_get_pamt_bitmap_sz(tdmr);
647 } else {
648 tdmr->pamt_4k_size = tdmr_get_pamt_sz(tdmr, TDX_PS_4K);
649 }
650
651 tdmr_pamt_size = tdmr->pamt_4k_size + tdmr->pamt_2m_size + tdmr->pamt_1g_size;
652
653 /*
654 * Allocate one chunk of physically contiguous memory for all
655 * PAMTs. This helps minimize the PAMT's use of reserved areas
656 * in overlapped TDMRs.
657 */
658 pamt = alloc_contig_pages(tdmr_pamt_size >> PAGE_SHIFT, GFP_KERNEL,
659 nid, &node_online_map);
660
661 /*
662 * tdmr->pamt_4k_base is still zero so the error
663 * path of the caller will skip freeing the PAMT.
664 */
665 if (!pamt)
666 return -ENOMEM;
667
668 tdmr->pamt_4k_base = page_to_phys(pamt);
669 tdmr->pamt_2m_base = tdmr->pamt_4k_base + tdmr->pamt_4k_size;
670 tdmr->pamt_1g_base = tdmr->pamt_2m_base + tdmr->pamt_2m_size;
671
672 return 0;
673 }
674
tdmr_get_pamt(struct tdmr_info * tdmr,unsigned long * pamt_base,unsigned long * pamt_size)675 static void tdmr_get_pamt(struct tdmr_info *tdmr, unsigned long *pamt_base,
676 unsigned long *pamt_size)
677 {
678 unsigned long pamt_bs, pamt_sz;
679
680 /*
681 * The PAMT was allocated in one contiguous unit. The 4K PAMT
682 * should always point to the beginning of that allocation.
683 */
684 pamt_bs = tdmr->pamt_4k_base;
685 pamt_sz = tdmr->pamt_4k_size + tdmr->pamt_2m_size + tdmr->pamt_1g_size;
686
687 WARN_ON_ONCE((pamt_bs & ~PAGE_MASK) || (pamt_sz & ~PAGE_MASK));
688
689 *pamt_base = pamt_bs;
690 *pamt_size = pamt_sz;
691 }
692
tdmr_do_pamt_func(struct tdmr_info * tdmr,void (* pamt_func)(unsigned long base,unsigned long size))693 static __init void tdmr_do_pamt_func(struct tdmr_info *tdmr,
694 void (*pamt_func)(unsigned long base, unsigned long size))
695 {
696 unsigned long pamt_base, pamt_size;
697
698 tdmr_get_pamt(tdmr, &pamt_base, &pamt_size);
699
700 /* Do nothing if PAMT hasn't been allocated for this TDMR */
701 if (!pamt_base)
702 return;
703
704 pamt_func(pamt_base, pamt_size);
705 }
706
free_pamt(unsigned long pamt_base,unsigned long pamt_size)707 static __init void free_pamt(unsigned long pamt_base, unsigned long pamt_size)
708 {
709 free_contig_range(pamt_base >> PAGE_SHIFT, pamt_size >> PAGE_SHIFT);
710 }
711
tdmr_free_pamt(struct tdmr_info * tdmr)712 static __init void tdmr_free_pamt(struct tdmr_info *tdmr)
713 {
714 tdmr_do_pamt_func(tdmr, free_pamt);
715 }
716
tdmrs_free_pamt_all(struct tdmr_info_list * tdmr_list)717 static __init void tdmrs_free_pamt_all(struct tdmr_info_list *tdmr_list)
718 {
719 int i;
720
721 for (i = 0; i < tdmr_list->nr_consumed_tdmrs; i++)
722 tdmr_free_pamt(tdmr_entry(tdmr_list, i));
723 }
724
725 /* Allocate and set up PAMTs for all TDMRs */
tdmrs_set_up_pamt_all(struct tdmr_info_list * tdmr_list,struct list_head * tmb_list)726 static __init int tdmrs_set_up_pamt_all(struct tdmr_info_list *tdmr_list,
727 struct list_head *tmb_list)
728 {
729 int i, ret = 0;
730
731 for (i = 0; i < tdmr_list->nr_consumed_tdmrs; i++) {
732 ret = tdmr_set_up_pamt(tdmr_entry(tdmr_list, i), tmb_list);
733 if (ret)
734 goto err;
735 }
736
737 return 0;
738 err:
739 tdmrs_free_pamt_all(tdmr_list);
740 return ret;
741 }
742
743 /*
744 * Convert TDX private pages back to normal by using MOVDIR64B to clear these
745 * pages. Typically, any write to the page will convert it from TDX private back
746 * to normal kernel memory. Systems with the X86_BUG_TDX_PW_MCE erratum need to
747 * do the conversion explicitly via MOVDIR64B.
748 */
tdx_quirk_reset_paddr(unsigned long base,unsigned long size)749 void tdx_quirk_reset_paddr(unsigned long base, unsigned long size)
750 {
751 const void *zero_page = (const void *)page_address(ZERO_PAGE(0));
752 unsigned long phys, end;
753
754 if (!boot_cpu_has_bug(X86_BUG_TDX_PW_MCE))
755 return;
756
757 end = base + size;
758 for (phys = base; phys < end; phys += 64)
759 movdir64b(__va(phys), zero_page);
760
761 /*
762 * MOVDIR64B uses WC protocol. Use memory barrier to
763 * make sure any later user of these pages sees the
764 * updated data.
765 */
766 mb();
767 }
768 EXPORT_SYMBOL_FOR_KVM(tdx_quirk_reset_paddr);
769
tdmr_quirk_reset_pamt(struct tdmr_info * tdmr)770 static __init void tdmr_quirk_reset_pamt(struct tdmr_info *tdmr)
771
772 {
773 tdmr_do_pamt_func(tdmr, tdx_quirk_reset_paddr);
774 }
775
tdmrs_quirk_reset_pamt_all(struct tdmr_info_list * tdmr_list)776 static __init void tdmrs_quirk_reset_pamt_all(struct tdmr_info_list *tdmr_list)
777 {
778 int i;
779
780 for (i = 0; i < tdmr_list->nr_consumed_tdmrs; i++)
781 tdmr_quirk_reset_pamt(tdmr_entry(tdmr_list, i));
782 }
783
tdmrs_count_pamt_kb(struct tdmr_info_list * tdmr_list)784 static __init unsigned long tdmrs_count_pamt_kb(struct tdmr_info_list *tdmr_list)
785 {
786 unsigned long pamt_size = 0;
787 int i;
788
789 for (i = 0; i < tdmr_list->nr_consumed_tdmrs; i++) {
790 unsigned long base, size;
791
792 tdmr_get_pamt(tdmr_entry(tdmr_list, i), &base, &size);
793 pamt_size += size;
794 }
795
796 return pamt_size / 1024;
797 }
798
tdmr_add_rsvd_area(struct tdmr_info * tdmr,int * p_idx,u64 addr,u64 size,u16 max_reserved_per_tdmr)799 static __init int tdmr_add_rsvd_area(struct tdmr_info *tdmr, int *p_idx,
800 u64 addr, u64 size, u16 max_reserved_per_tdmr)
801 {
802 struct tdmr_reserved_area *rsvd_areas = tdmr->reserved_areas;
803 int idx = *p_idx;
804
805 /* Reserved area must be 4K aligned in offset and size */
806 if (WARN_ON(addr & ~PAGE_MASK || size & ~PAGE_MASK))
807 return -EINVAL;
808
809 if (idx >= max_reserved_per_tdmr) {
810 pr_warn("initialization failed: TDMR [0x%llx, 0x%llx): reserved areas exhausted.\n",
811 tdmr->base, tdmr_end(tdmr));
812 return -ENOSPC;
813 }
814
815 /*
816 * Consume one reserved area per call. Make no effort to
817 * optimize or reduce the number of reserved areas which are
818 * consumed by contiguous reserved areas, for instance.
819 */
820 rsvd_areas[idx].offset = addr - tdmr->base;
821 rsvd_areas[idx].size = size;
822
823 *p_idx = idx + 1;
824
825 return 0;
826 }
827
828 /*
829 * Go through @tmb_list to find holes between memory areas. If any of
830 * those holes fall within @tdmr, set up a TDMR reserved area to cover
831 * the hole.
832 */
tdmr_populate_rsvd_holes(struct list_head * tmb_list,struct tdmr_info * tdmr,int * rsvd_idx,u16 max_reserved_per_tdmr)833 static __init int tdmr_populate_rsvd_holes(struct list_head *tmb_list,
834 struct tdmr_info *tdmr,
835 int *rsvd_idx,
836 u16 max_reserved_per_tdmr)
837 {
838 struct tdx_memblock *tmb;
839 u64 prev_end;
840 int ret;
841
842 /*
843 * Start looking for reserved blocks at the
844 * beginning of the TDMR.
845 */
846 prev_end = tdmr->base;
847 list_for_each_entry(tmb, tmb_list, list) {
848 u64 start, end;
849
850 start = PFN_PHYS(tmb->start_pfn);
851 end = PFN_PHYS(tmb->end_pfn);
852
853 /* Break if this region is after the TDMR */
854 if (start >= tdmr_end(tdmr))
855 break;
856
857 /* Exclude regions before this TDMR */
858 if (end < tdmr->base)
859 continue;
860
861 /*
862 * Skip over memory areas that
863 * have already been dealt with.
864 */
865 if (start <= prev_end) {
866 prev_end = end;
867 continue;
868 }
869
870 /* Add the hole before this region */
871 ret = tdmr_add_rsvd_area(tdmr, rsvd_idx, prev_end,
872 start - prev_end,
873 max_reserved_per_tdmr);
874 if (ret)
875 return ret;
876
877 prev_end = end;
878 }
879
880 /* Add the hole after the last region if it exists. */
881 if (prev_end < tdmr_end(tdmr)) {
882 ret = tdmr_add_rsvd_area(tdmr, rsvd_idx, prev_end,
883 tdmr_end(tdmr) - prev_end,
884 max_reserved_per_tdmr);
885 if (ret)
886 return ret;
887 }
888
889 return 0;
890 }
891
892 /*
893 * Go through @tdmr_list to find all PAMTs. If any of those PAMTs
894 * overlaps with @tdmr, set up a TDMR reserved area to cover the
895 * overlapping part.
896 */
tdmr_populate_rsvd_pamts(struct tdmr_info_list * tdmr_list,struct tdmr_info * tdmr,int * rsvd_idx,u16 max_reserved_per_tdmr)897 static __init int tdmr_populate_rsvd_pamts(struct tdmr_info_list *tdmr_list,
898 struct tdmr_info *tdmr,
899 int *rsvd_idx,
900 u16 max_reserved_per_tdmr)
901 {
902 int i, ret;
903
904 for (i = 0; i < tdmr_list->nr_consumed_tdmrs; i++) {
905 struct tdmr_info *tmp = tdmr_entry(tdmr_list, i);
906 unsigned long pamt_base, pamt_size, pamt_end;
907
908 tdmr_get_pamt(tmp, &pamt_base, &pamt_size);
909 /* Each TDMR must already have PAMT allocated */
910 WARN_ON_ONCE(!pamt_size || !pamt_base);
911
912 pamt_end = pamt_base + pamt_size;
913 /* Skip PAMTs outside of the given TDMR */
914 if ((pamt_end <= tdmr->base) ||
915 (pamt_base >= tdmr_end(tdmr)))
916 continue;
917
918 /* Only mark the part within the TDMR as reserved */
919 if (pamt_base < tdmr->base)
920 pamt_base = tdmr->base;
921 if (pamt_end > tdmr_end(tdmr))
922 pamt_end = tdmr_end(tdmr);
923
924 ret = tdmr_add_rsvd_area(tdmr, rsvd_idx, pamt_base,
925 pamt_end - pamt_base,
926 max_reserved_per_tdmr);
927 if (ret)
928 return ret;
929 }
930
931 return 0;
932 }
933
934 /* Compare function called by sort() for TDMR reserved areas */
rsvd_area_cmp_func(const void * a,const void * b)935 static __init int rsvd_area_cmp_func(const void *a, const void *b)
936 {
937 struct tdmr_reserved_area *r1 = (struct tdmr_reserved_area *)a;
938 struct tdmr_reserved_area *r2 = (struct tdmr_reserved_area *)b;
939
940 if (r1->offset + r1->size <= r2->offset)
941 return -1;
942 if (r1->offset >= r2->offset + r2->size)
943 return 1;
944
945 /* Reserved areas cannot overlap. The caller must guarantee. */
946 WARN_ON_ONCE(1);
947 return -1;
948 }
949
950 /*
951 * Populate reserved areas for the given @tdmr, including memory holes
952 * (via @tmb_list) and PAMTs (via @tdmr_list).
953 */
tdmr_populate_rsvd_areas(struct tdmr_info * tdmr,struct list_head * tmb_list,struct tdmr_info_list * tdmr_list,u16 max_reserved_per_tdmr)954 static __init int tdmr_populate_rsvd_areas(struct tdmr_info *tdmr,
955 struct list_head *tmb_list,
956 struct tdmr_info_list *tdmr_list,
957 u16 max_reserved_per_tdmr)
958 {
959 int ret, rsvd_idx = 0;
960
961 ret = tdmr_populate_rsvd_holes(tmb_list, tdmr, &rsvd_idx,
962 max_reserved_per_tdmr);
963 if (ret)
964 return ret;
965
966 ret = tdmr_populate_rsvd_pamts(tdmr_list, tdmr, &rsvd_idx,
967 max_reserved_per_tdmr);
968 if (ret)
969 return ret;
970
971 /* TDX requires reserved areas listed in address ascending order */
972 sort(tdmr->reserved_areas, rsvd_idx, sizeof(struct tdmr_reserved_area),
973 rsvd_area_cmp_func, NULL);
974
975 return 0;
976 }
977
978 /*
979 * Populate reserved areas for all TDMRs in @tdmr_list, including memory
980 * holes (via @tmb_list) and PAMTs.
981 */
tdmrs_populate_rsvd_areas_all(struct tdmr_info_list * tdmr_list,struct list_head * tmb_list,u16 max_reserved_per_tdmr)982 static __init int tdmrs_populate_rsvd_areas_all(struct tdmr_info_list *tdmr_list,
983 struct list_head *tmb_list,
984 u16 max_reserved_per_tdmr)
985 {
986 int i;
987
988 for (i = 0; i < tdmr_list->nr_consumed_tdmrs; i++) {
989 int ret;
990
991 ret = tdmr_populate_rsvd_areas(tdmr_entry(tdmr_list, i),
992 tmb_list, tdmr_list, max_reserved_per_tdmr);
993 if (ret)
994 return ret;
995 }
996
997 return 0;
998 }
999
1000 /*
1001 * Construct a list of TDMRs on the preallocated space in @tdmr_list
1002 * to cover all TDX memory regions in @tmb_list based on the TDX module
1003 * TDMR global information in @sysinfo_tdmr.
1004 */
construct_tdmrs(struct list_head * tmb_list,struct tdmr_info_list * tdmr_list,struct tdx_sys_info_tdmr * sysinfo_tdmr)1005 static __init int construct_tdmrs(struct list_head *tmb_list,
1006 struct tdmr_info_list *tdmr_list,
1007 struct tdx_sys_info_tdmr *sysinfo_tdmr)
1008 {
1009 int ret;
1010
1011 ret = fill_out_tdmrs(tmb_list, tdmr_list);
1012 if (ret)
1013 return ret;
1014
1015 ret = tdmrs_set_up_pamt_all(tdmr_list, tmb_list);
1016 if (ret)
1017 return ret;
1018
1019 ret = tdmrs_populate_rsvd_areas_all(tdmr_list, tmb_list,
1020 sysinfo_tdmr->max_reserved_per_tdmr);
1021 if (ret)
1022 tdmrs_free_pamt_all(tdmr_list);
1023
1024 /*
1025 * The tdmr_info_list is read-only from here on out.
1026 * Ensure that these writes are seen by other CPUs.
1027 * Pairs with a smp_rmb() in is_pamt_page().
1028 */
1029 smp_wmb();
1030
1031 return ret;
1032 }
1033
1034 #define TDX_SYS_CONFIG_DYNAMIC_PAMT BIT(16)
1035
config_tdx_module(struct tdmr_info_list * tdmr_list,u64 global_keyid)1036 static __init int config_tdx_module(struct tdmr_info_list *tdmr_list,
1037 u64 global_keyid)
1038 {
1039 struct tdx_module_args args = {};
1040 u64 *tdmr_pa_array;
1041 size_t array_sz;
1042 int i, ret;
1043
1044 /*
1045 * TDMRs are passed to the TDX module via an array of physical
1046 * addresses of each TDMR. The array itself also has certain
1047 * alignment requirement.
1048 */
1049 array_sz = tdmr_list->nr_consumed_tdmrs * sizeof(u64);
1050 array_sz = roundup_pow_of_two(array_sz);
1051 if (array_sz < TDMR_INFO_PA_ARRAY_ALIGNMENT)
1052 array_sz = TDMR_INFO_PA_ARRAY_ALIGNMENT;
1053
1054 tdmr_pa_array = kzalloc(array_sz, GFP_KERNEL);
1055 if (!tdmr_pa_array)
1056 return -ENOMEM;
1057
1058 for (i = 0; i < tdmr_list->nr_consumed_tdmrs; i++)
1059 tdmr_pa_array[i] = __pa(tdmr_entry(tdmr_list, i));
1060
1061 args.rcx = __pa(tdmr_pa_array);
1062 args.rdx = tdmr_list->nr_consumed_tdmrs;
1063 args.r8 = global_keyid;
1064
1065 if (tdx_supports_dynamic_pamt(&tdx_sysinfo)) {
1066 pr_info("Enable Dynamic PAMT\n");
1067 args.r8 |= TDX_SYS_CONFIG_DYNAMIC_PAMT;
1068 }
1069
1070 ret = seamcall_prerr(TDH_SYS_CONFIG, &args);
1071
1072 /* Free the array as it is not required anymore. */
1073 kfree(tdmr_pa_array);
1074
1075 return ret;
1076 }
1077
do_global_key_config(void * unused)1078 static __init int do_global_key_config(void *unused)
1079 {
1080 struct tdx_module_args args = {};
1081
1082 return seamcall_prerr(TDH_SYS_KEY_CONFIG, &args);
1083 }
1084
1085 /*
1086 * Attempt to configure the global KeyID on all physical packages.
1087 *
1088 * This requires running code on at least one CPU in each package.
1089 * TDMR initialization) will fail will fail if any package in the
1090 * system has no online CPUs.
1091 *
1092 * This code takes no affirmative steps to online CPUs. Callers (aka.
1093 * KVM) can ensure success by ensuring sufficient CPUs are online and
1094 * can run SEAMCALLs.
1095 */
config_global_keyid(void)1096 static __init int config_global_keyid(void)
1097 {
1098 cpumask_var_t packages;
1099 int cpu, ret = -EINVAL;
1100
1101 if (!zalloc_cpumask_var(&packages, GFP_KERNEL))
1102 return -ENOMEM;
1103
1104 /*
1105 * Hardware doesn't guarantee cache coherency across different
1106 * KeyIDs. The kernel needs to flush PAMT's dirty cachelines
1107 * (associated with KeyID 0) before the TDX module can use the
1108 * global KeyID to access the PAMT. Given PAMTs are potentially
1109 * large (~1/256th of system RAM), just use WBINVD.
1110 */
1111 wbinvd_on_all_cpus();
1112
1113 for_each_online_cpu(cpu) {
1114 /*
1115 * The key configuration only needs to be done once per
1116 * package and will return an error if configured more
1117 * than once. Avoid doing it multiple times per package.
1118 */
1119 if (cpumask_test_and_set_cpu(topology_physical_package_id(cpu),
1120 packages))
1121 continue;
1122
1123 /*
1124 * TDH.SYS.KEY.CONFIG cannot run concurrently on
1125 * different cpus. Do it one by one.
1126 */
1127 ret = smp_call_on_cpu(cpu, do_global_key_config, NULL, true);
1128 if (ret)
1129 break;
1130 }
1131
1132 free_cpumask_var(packages);
1133 return ret;
1134 }
1135
init_tdmr(struct tdmr_info * tdmr)1136 static __init int init_tdmr(struct tdmr_info *tdmr)
1137 {
1138 u64 next;
1139
1140 /*
1141 * Initializing a TDMR can be time consuming. To avoid long
1142 * SEAMCALLs, the TDX module may only initialize a part of the
1143 * TDMR in each call.
1144 */
1145 do {
1146 struct tdx_module_args args = {
1147 .rcx = tdmr->base,
1148 };
1149 int ret;
1150
1151 ret = seamcall_prerr_ret(TDH_SYS_TDMR_INIT, &args);
1152 if (ret)
1153 return ret;
1154 /*
1155 * RDX contains 'next-to-initialize' address if
1156 * TDH.SYS.TDMR.INIT did not fully complete and
1157 * should be retried.
1158 */
1159 next = args.rdx;
1160 cond_resched();
1161 /* Keep making SEAMCALLs until the TDMR is done */
1162 } while (next < tdmr->base + tdmr->size);
1163
1164 return 0;
1165 }
1166
init_tdmrs(struct tdmr_info_list * tdmr_list)1167 static __init int init_tdmrs(struct tdmr_info_list *tdmr_list)
1168 {
1169 int i;
1170
1171 /*
1172 * This operation is costly. It can be parallelized,
1173 * but keep it simple for now.
1174 */
1175 for (i = 0; i < tdmr_list->nr_consumed_tdmrs; i++) {
1176 int ret;
1177
1178 ret = init_tdmr(tdmr_entry(tdmr_list, i));
1179 if (ret)
1180 return ret;
1181 }
1182
1183 return 0;
1184 }
1185
init_tdx_module(void)1186 static __init int init_tdx_module(void)
1187 {
1188 int ret;
1189
1190 ret = get_tdx_sys_info(&tdx_sysinfo);
1191 if (ret)
1192 return ret;
1193
1194 /* Check whether the kernel can support this module */
1195 ret = check_features(&tdx_sysinfo);
1196 if (ret)
1197 return ret;
1198
1199 /*
1200 * To keep things simple, assume that all TDX-protected memory
1201 * will come from the page allocator. Make sure all pages in the
1202 * page allocator are TDX-usable memory.
1203 *
1204 * Build the list of "TDX-usable" memory regions which cover all
1205 * pages in the page allocator to guarantee that. Do it while
1206 * holding mem_hotplug_lock read-lock as the memory hotplug code
1207 * path reads the @tdx_memlist to reject any new memory.
1208 */
1209 get_online_mems();
1210
1211 ret = init_dpamt_refcounts();
1212 if (ret)
1213 goto out_put_tdxmem;
1214
1215 ret = build_tdx_memlist(&tdx_memlist);
1216 if (ret)
1217 goto err_free_dpamt_refcounts;
1218
1219 /* Allocate enough space for constructing TDMRs */
1220 ret = alloc_tdmr_list(&tdx_tdmr_list, &tdx_sysinfo.tdmr);
1221 if (ret)
1222 goto err_free_tdxmem;
1223
1224 /* Cover all TDX-usable memory regions in TDMRs */
1225 ret = construct_tdmrs(&tdx_memlist, &tdx_tdmr_list, &tdx_sysinfo.tdmr);
1226 if (ret)
1227 goto err_free_tdmrs;
1228
1229 /* Pass the TDMRs and the global KeyID to the TDX module */
1230 ret = config_tdx_module(&tdx_tdmr_list, tdx_global_keyid);
1231 if (ret)
1232 goto err_free_pamts;
1233
1234 /* Config the key of global KeyID on all packages */
1235 ret = config_global_keyid();
1236 if (ret)
1237 goto err_reset_pamts;
1238
1239 /* Initialize TDMRs to complete the TDX module initialization */
1240 ret = init_tdmrs(&tdx_tdmr_list);
1241 if (ret)
1242 goto err_reset_pamts;
1243
1244 pr_info("%lu KB allocated for PAMT\n", tdmrs_count_pamt_kb(&tdx_tdmr_list));
1245
1246 out_put_tdxmem:
1247 /*
1248 * @tdx_memlist is written here and read at memory hotplug time.
1249 * Lock out memory hotplug code while building it.
1250 */
1251 put_online_mems();
1252 return ret;
1253
1254 err_reset_pamts:
1255 /*
1256 * Part of PAMTs may already have been initialized by the
1257 * TDX module. Flush cache before returning PAMTs back
1258 * to the kernel.
1259 */
1260 wbinvd_on_all_cpus();
1261 tdmrs_quirk_reset_pamt_all(&tdx_tdmr_list);
1262 err_free_pamts:
1263 tdmrs_free_pamt_all(&tdx_tdmr_list);
1264 err_free_tdmrs:
1265 free_tdmr_list(&tdx_tdmr_list);
1266 err_free_tdxmem:
1267 free_tdx_memlist(&tdx_memlist);
1268 err_free_dpamt_refcounts:
1269 free_dpamt_refcounts();
1270 goto out_put_tdxmem;
1271 }
1272
tdx_enable(void)1273 static __init int tdx_enable(void)
1274 {
1275 enum cpuhp_state state;
1276 int ret;
1277
1278 if (!cpu_feature_enabled(X86_FEATURE_TDX_HOST_PLATFORM)) {
1279 pr_err("TDX not supported by the host platform\n");
1280 return -ENODEV;
1281 }
1282
1283 if (!cpu_feature_enabled(X86_FEATURE_XSAVE)) {
1284 pr_err("XSAVE is required for TDX\n");
1285 return -EINVAL;
1286 }
1287
1288 if (!cpu_feature_enabled(X86_FEATURE_MOVDIR64B)) {
1289 pr_err("MOVDIR64B is required for TDX\n");
1290 return -EINVAL;
1291 }
1292
1293 if (!cpu_feature_enabled(X86_FEATURE_SELFSNOOP)) {
1294 pr_err("Self-snoop is required for TDX\n");
1295 return -ENODEV;
1296 }
1297
1298 state = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "virt/tdx:online",
1299 tdx_online_cpu, tdx_offline_cpu);
1300 if (state < 0)
1301 return state;
1302
1303 ret = init_tdx_module();
1304 if (ret) {
1305 pr_err("TDX-Module initialization failed (%d)\n", ret);
1306 cpuhp_remove_state(state);
1307 return ret;
1308 }
1309
1310 register_syscore(&tdx_syscore);
1311
1312 tdx_module_state.initialized = true;
1313 pr_info("TDX-Module initialized\n");
1314 return 0;
1315 }
1316 subsys_initcall(tdx_enable);
1317
tdx_module_shutdown(void)1318 int tdx_module_shutdown(void)
1319 {
1320 struct tdx_sys_info_handoff handoff = {};
1321 struct tdx_module_args args = {};
1322 int ret;
1323 int cpu;
1324
1325 ret = get_tdx_sys_info_handoff(&handoff);
1326 /*
1327 * Handoff information is required for proper
1328 * shutdown. Refuse to shut down without it.
1329 */
1330 if (ret)
1331 return ret;
1332
1333 /*
1334 * Use the module's handoff version as it is the highest the
1335 * module can produce and most likely supported by newer modules.
1336 */
1337 args.rcx = handoff.module_hv;
1338
1339 ret = seamcall_prerr(TDH_SYS_SHUTDOWN, &args);
1340 if (ret)
1341 return ret;
1342
1343 /*
1344 * Clear global and per-CPU initialization flags so the new module
1345 * can be fully re-initialized after a successful update.
1346 *
1347 * No locks needed as no concurrent accesses can occur here.
1348 */
1349 memset(&tdx_module_state, 0, sizeof(tdx_module_state));
1350 for_each_possible_cpu(cpu)
1351 per_cpu(tdx_lp_initialized, cpu) = false;
1352
1353 return 0;
1354 }
1355
tdx_module_run_update(void)1356 int tdx_module_run_update(void)
1357 {
1358 struct tdx_module_args args = {};
1359 int ret;
1360
1361 ret = seamcall_prerr(TDH_SYS_UPDATE, &args);
1362 if (ret)
1363 return ret;
1364
1365 ret = get_tdx_sys_info_version(&tdx_sysinfo.version);
1366 /*
1367 * Only fails if there is something unexpected
1368 * and severely wrong with the module.
1369 */
1370 WARN_ON_ONCE(ret);
1371
1372 tdx_module_state.initialized = true;
1373 return 0;
1374 }
1375
is_pamt_page(unsigned long phys)1376 static bool is_pamt_page(unsigned long phys)
1377 {
1378 struct tdmr_info_list *tdmr_list = &tdx_tdmr_list;
1379 int i;
1380
1381 /* Ensure that all remote 'tdmr_list' writes are visible: */
1382 smp_rmb();
1383
1384 /*
1385 * The TDX module is no longer returning TDX_SYS_NOT_READY and
1386 * is initialized. The 'tdmr_list' was initialized long ago
1387 * and is now read-only.
1388 */
1389 for (i = 0; i < tdmr_list->nr_consumed_tdmrs; i++) {
1390 unsigned long base, size;
1391
1392 tdmr_get_pamt(tdmr_entry(tdmr_list, i), &base, &size);
1393
1394 if (phys >= base && phys < (base + size))
1395 return true;
1396 }
1397
1398 return false;
1399 }
1400
1401 /*
1402 * Return whether the memory page at the given physical address is TDX
1403 * private memory or not.
1404 *
1405 * This can be imprecise for two known reasons:
1406 * 1. PAMTs are private memory and exist before the TDX module is
1407 * ready and TDH_PHYMEM_PAGE_RDMD works. This is a relatively
1408 * short window that occurs once per boot.
1409 * 2. TDH_PHYMEM_PAGE_RDMD reflects the TDX module's knowledge of the
1410 * page. However, the page can still cause #MC until it has been
1411 * fully converted to shared using 64-byte writes like MOVDIR64B.
1412 * Buggy hosts might still leave #MC-causing memory in place which
1413 * this function can not detect.
1414 */
paddr_is_tdx_private(unsigned long phys)1415 static bool paddr_is_tdx_private(unsigned long phys)
1416 {
1417 struct tdx_module_args args = {
1418 .rcx = phys & PAGE_MASK,
1419 };
1420 u64 sret;
1421
1422 if (!boot_cpu_has(X86_FEATURE_TDX_HOST_PLATFORM))
1423 return false;
1424
1425 /* Get page type from the TDX module */
1426 sret = __seamcall_dirty_cache(__seamcall_ret, TDH_PHYMEM_PAGE_RDMD, &args);
1427
1428 /*
1429 * The SEAMCALL will not return success unless there is a
1430 * working, "ready" TDX module. Assume an absence of TDX
1431 * private pages until SEAMCALL is working.
1432 */
1433 if (sret)
1434 return false;
1435
1436 /*
1437 * SEAMCALL was successful -- read page type (via RCX):
1438 *
1439 * - PT_NDA: Page is not used by the TDX module
1440 * - PT_RSVD: Reserved for Non-TDX use
1441 * - Others: Page is used by the TDX module
1442 *
1443 * Note PAMT pages are marked as PT_RSVD but they are also TDX
1444 * private memory.
1445 */
1446 switch (args.rcx) {
1447 case PT_NDA:
1448 return false;
1449 case PT_RSVD:
1450 return is_pamt_page(phys);
1451 default:
1452 return true;
1453 }
1454 }
1455
1456 /*
1457 * Some TDX-capable CPUs have an erratum. A write to TDX private
1458 * memory poisons that memory, and a subsequent read of that memory
1459 * triggers #MC.
1460 *
1461 * Help distinguish erratum-triggered #MCs from a normal hardware one.
1462 * Just print additional message to show such #MC may be result of the
1463 * erratum.
1464 */
tdx_dump_mce_info(struct mce * m)1465 const char *tdx_dump_mce_info(struct mce *m)
1466 {
1467 if (!m || !mce_is_memory_error(m) || !mce_usable_address(m))
1468 return NULL;
1469
1470 if (!paddr_is_tdx_private(m->addr))
1471 return NULL;
1472
1473 return "TDX private memory error. Possible kernel bug.";
1474 }
1475
record_keyid_partitioning(u32 * tdx_keyid_start,u32 * nr_tdx_keyids)1476 static __init int record_keyid_partitioning(u32 *tdx_keyid_start,
1477 u32 *nr_tdx_keyids)
1478 {
1479 u32 _nr_mktme_keyids, _tdx_keyid_start, _nr_tdx_keyids;
1480 struct msr val;
1481 int ret;
1482
1483 /*
1484 * IA32_MKTME_KEYID_PARTIONING:
1485 * Bit [31:0]: Number of MKTME KeyIDs.
1486 * Bit [63:32]: Number of TDX private KeyIDs.
1487 */
1488 ret = rdmsrq_safe(MSR_IA32_MKTME_KEYID_PARTITIONING, &val.q);
1489 _nr_mktme_keyids = val.l;
1490 _nr_tdx_keyids = val.h;
1491 if (ret || !_nr_tdx_keyids)
1492 return -EINVAL;
1493
1494 /* TDX KeyIDs start after the last MKTME KeyID. */
1495 _tdx_keyid_start = _nr_mktme_keyids + 1;
1496
1497 *tdx_keyid_start = _tdx_keyid_start;
1498 *nr_tdx_keyids = _nr_tdx_keyids;
1499
1500 return 0;
1501 }
1502
is_tdx_memory(unsigned long start_pfn,unsigned long end_pfn)1503 static bool is_tdx_memory(unsigned long start_pfn, unsigned long end_pfn)
1504 {
1505 struct tdx_memblock *tmb;
1506
1507 /*
1508 * This check assumes that the start_pfn<->end_pfn range does not
1509 * cross multiple @tdx_memlist entries. A single memory online
1510 * event across multiple memblocks (from which @tdx_memlist
1511 * entries are derived at the time of module initialization) is
1512 * not possible. This is because memory offline/online is done
1513 * on granularity of 'struct memory_block', and the hotpluggable
1514 * memory region (one memblock) must be multiple of memory_block.
1515 */
1516 list_for_each_entry(tmb, &tdx_memlist, list) {
1517 if (start_pfn >= tmb->start_pfn && end_pfn <= tmb->end_pfn)
1518 return true;
1519 }
1520 return false;
1521 }
1522
tdx_memory_notifier(struct notifier_block * nb,unsigned long action,void * v)1523 static int tdx_memory_notifier(struct notifier_block *nb, unsigned long action,
1524 void *v)
1525 {
1526 struct memory_notify *mn = v;
1527
1528 if (action != MEM_GOING_ONLINE)
1529 return NOTIFY_OK;
1530
1531 /*
1532 * Empty list means TDX isn't enabled. Allow any memory
1533 * to go online.
1534 */
1535 if (list_empty(&tdx_memlist))
1536 return NOTIFY_OK;
1537
1538 /*
1539 * The TDX memory configuration is static and can not be
1540 * changed. Reject onlining any memory which is outside of
1541 * the static configuration whether it supports TDX or not.
1542 */
1543 if (is_tdx_memory(mn->start_pfn, mn->start_pfn + mn->nr_pages))
1544 return NOTIFY_OK;
1545
1546 return NOTIFY_BAD;
1547 }
1548
1549 static struct notifier_block tdx_memory_nb = {
1550 .notifier_call = tdx_memory_notifier,
1551 };
1552
check_tdx_erratum(void)1553 static void __init check_tdx_erratum(void)
1554 {
1555 u64 basic_msr;
1556
1557 /*
1558 * These CPUs have an erratum. A partial write from non-TD
1559 * software (e.g. via MOVNTI variants or UC/WC mapping) to TDX
1560 * private memory poisons that memory, and a subsequent read of
1561 * that memory triggers #MC.
1562 */
1563 switch (boot_cpu_data.x86_vfm) {
1564 case INTEL_SAPPHIRERAPIDS_X:
1565 case INTEL_EMERALDRAPIDS_X:
1566 setup_force_cpu_bug(X86_BUG_TDX_PW_MCE);
1567 }
1568
1569 /*
1570 * Some TDX-capable CPUs have an erratum where the current VMCS is
1571 * cleared after calling into P-SEAMLDR.
1572 */
1573 rdmsrq(MSR_IA32_VMX_BASIC, basic_msr);
1574 if (!(basic_msr & VMX_BASIC_NO_SEAMRET_INVD_VMCS))
1575 setup_force_cpu_bug(X86_BUG_SEAMRET_INVD_VMCS);
1576 }
1577
tdx_init(void)1578 void __init tdx_init(void)
1579 {
1580 u32 tdx_keyid_start, nr_tdx_keyids;
1581 int err;
1582
1583 err = record_keyid_partitioning(&tdx_keyid_start, &nr_tdx_keyids);
1584 if (err)
1585 return;
1586
1587 pr_info("BIOS enabled: private KeyID range [%u, %u)\n",
1588 tdx_keyid_start, tdx_keyid_start + nr_tdx_keyids);
1589
1590 /*
1591 * The TDX module itself requires one 'global KeyID' to protect
1592 * its metadata. If there's only one TDX KeyID, there won't be
1593 * any left for TDX guests thus there's no point to enable TDX
1594 * at all.
1595 */
1596 if (nr_tdx_keyids < 2) {
1597 pr_err("initialization failed: too few private KeyIDs available.\n");
1598 return;
1599 }
1600
1601 /*
1602 * At this point, hibernation_available() indicates whether or
1603 * not hibernation support has been permanently disabled.
1604 */
1605 if (hibernation_available()) {
1606 pr_err("initialization failed: Hibernation support is enabled\n");
1607 return;
1608 }
1609
1610 err = register_memory_notifier(&tdx_memory_nb);
1611 if (err) {
1612 pr_err("initialization failed: register_memory_notifier() failed (%d)\n",
1613 err);
1614 return;
1615 }
1616
1617 #if defined(CONFIG_ACPI) && defined(CONFIG_SUSPEND)
1618 pr_info("Disable ACPI S3. Turn off TDX in the BIOS to use ACPI S3.\n");
1619 acpi_suspend_lowlevel = NULL;
1620 #endif
1621
1622 /*
1623 * Just use the first TDX KeyID as the 'global KeyID' and
1624 * leave the rest for TDX guests.
1625 */
1626 tdx_global_keyid = tdx_keyid_start;
1627 tdx_guest_keyid_start = tdx_keyid_start + 1;
1628 tdx_nr_guest_keyids = nr_tdx_keyids - 1;
1629
1630 setup_force_cpu_cap(X86_FEATURE_TDX_HOST_PLATFORM);
1631
1632 check_tdx_erratum();
1633 }
1634
tdx_get_sysinfo(void)1635 const struct tdx_sys_info *tdx_get_sysinfo(void)
1636 {
1637 if (!tdx_module_state.initialized)
1638 return NULL;
1639
1640 return (const struct tdx_sys_info *)&tdx_sysinfo;
1641 }
1642 EXPORT_SYMBOL_FOR_MODULES(tdx_get_sysinfo, "kvm-intel,tdx-host");
1643
tdx_get_nr_guest_keyids(void)1644 u32 tdx_get_nr_guest_keyids(void)
1645 {
1646 return tdx_nr_guest_keyids;
1647 }
1648 EXPORT_SYMBOL_FOR_KVM(tdx_get_nr_guest_keyids);
1649
tdx_guest_keyid_alloc(void)1650 int tdx_guest_keyid_alloc(void)
1651 {
1652 return ida_alloc_range(&tdx_guest_keyid_pool, tdx_guest_keyid_start,
1653 tdx_guest_keyid_start + tdx_nr_guest_keyids - 1,
1654 GFP_KERNEL);
1655 }
1656 EXPORT_SYMBOL_FOR_KVM(tdx_guest_keyid_alloc);
1657
tdx_guest_keyid_free(unsigned int keyid)1658 void tdx_guest_keyid_free(unsigned int keyid)
1659 {
1660 ida_free(&tdx_guest_keyid_pool, keyid);
1661 }
1662 EXPORT_SYMBOL_FOR_KVM(tdx_guest_keyid_free);
1663
tdx_tdr_pa(struct tdx_td * td)1664 static inline u64 tdx_tdr_pa(struct tdx_td *td)
1665 {
1666 return page_to_phys(td->tdr_page);
1667 }
1668
1669 /*
1670 * The TDX module exposes a CLFLUSH_BEFORE_ALLOC bit to specify whether
1671 * a CLFLUSH of pages is required before handing them to the TDX module.
1672 * Be conservative and make the code simpler by doing the CLFLUSH
1673 * unconditionally.
1674 */
tdx_clflush_page(struct page * page)1675 static void tdx_clflush_page(struct page *page)
1676 {
1677 clflush_cache_range(page_to_virt(page), PAGE_SIZE);
1678 }
1679
tdx_clflush_pfn(kvm_pfn_t pfn)1680 static void tdx_clflush_pfn(kvm_pfn_t pfn)
1681 {
1682 clflush_cache_range(__va(PFN_PHYS(pfn)), PAGE_SIZE);
1683 }
1684
pg_level_to_tdx_sept_level(enum pg_level level)1685 static int pg_level_to_tdx_sept_level(enum pg_level level)
1686 {
1687 WARN_ON_ONCE(level == PG_LEVEL_NONE);
1688 return level - 1;
1689 }
1690
tdh_vp_enter(struct tdx_vp * td,struct tdx_module_args * args)1691 noinstr u64 tdh_vp_enter(struct tdx_vp *td, struct tdx_module_args *args)
1692 {
1693 args->rcx = td->tdvpr_pa;
1694
1695 return __seamcall_dirty_cache(__seamcall_saved_ret, TDH_VP_ENTER, args);
1696 }
1697 EXPORT_SYMBOL_FOR_KVM(tdh_vp_enter);
1698
tdh_mng_addcx(struct tdx_td * td,struct page * tdcs_page)1699 u64 tdh_mng_addcx(struct tdx_td *td, struct page *tdcs_page)
1700 {
1701 struct tdx_module_args args = {
1702 .rcx = page_to_phys(tdcs_page),
1703 .rdx = tdx_tdr_pa(td),
1704 };
1705
1706 tdx_clflush_page(tdcs_page);
1707 return seamcall(TDH_MNG_ADDCX, &args);
1708 }
1709 EXPORT_SYMBOL_FOR_KVM(tdh_mng_addcx);
1710
tdh_mem_page_add(struct tdx_td * td,u64 gpa,kvm_pfn_t pfn,struct page * source,u64 * ext_err1,u64 * ext_err2)1711 u64 tdh_mem_page_add(struct tdx_td *td, u64 gpa, kvm_pfn_t pfn, struct page *source,
1712 u64 *ext_err1, u64 *ext_err2)
1713 {
1714 struct tdx_module_args args = {
1715 .rcx = gpa,
1716 .rdx = tdx_tdr_pa(td),
1717 .r8 = PFN_PHYS(pfn),
1718 .r9 = page_to_phys(source),
1719 };
1720 u64 ret;
1721
1722 tdx_clflush_pfn(pfn);
1723 ret = seamcall_ret(TDH_MEM_PAGE_ADD, &args);
1724
1725 *ext_err1 = args.rcx;
1726 *ext_err2 = args.rdx;
1727
1728 return ret;
1729 }
1730 EXPORT_SYMBOL_FOR_KVM(tdh_mem_page_add);
1731
tdh_mem_sept_add(struct tdx_td * td,u64 gpa,enum pg_level level,struct page * page,u64 * ext_err1,u64 * ext_err2)1732 u64 tdh_mem_sept_add(struct tdx_td *td, u64 gpa, enum pg_level level,
1733 struct page *page, u64 *ext_err1, u64 *ext_err2)
1734 {
1735 struct tdx_module_args args = {
1736 .rcx = gpa | pg_level_to_tdx_sept_level(level),
1737 .rdx = tdx_tdr_pa(td),
1738 .r8 = page_to_phys(page),
1739 };
1740 u64 ret;
1741
1742 tdx_clflush_page(page);
1743 ret = seamcall_ret(TDH_MEM_SEPT_ADD, &args);
1744
1745 *ext_err1 = args.rcx;
1746 *ext_err2 = args.rdx;
1747
1748 return ret;
1749 }
1750 EXPORT_SYMBOL_FOR_KVM(tdh_mem_sept_add);
1751
tdh_vp_addcx(struct tdx_vp * vp,struct page * tdcx_page)1752 u64 tdh_vp_addcx(struct tdx_vp *vp, struct page *tdcx_page)
1753 {
1754 struct tdx_module_args args = {
1755 .rcx = page_to_phys(tdcx_page),
1756 .rdx = vp->tdvpr_pa,
1757 };
1758
1759 tdx_clflush_page(tdcx_page);
1760 return seamcall(TDH_VP_ADDCX, &args);
1761 }
1762 EXPORT_SYMBOL_FOR_KVM(tdh_vp_addcx);
1763
tdh_mem_page_aug(struct tdx_td * td,u64 gpa,enum pg_level level,kvm_pfn_t pfn,u64 * ext_err1,u64 * ext_err2)1764 u64 tdh_mem_page_aug(struct tdx_td *td, u64 gpa, enum pg_level level,
1765 kvm_pfn_t pfn, u64 *ext_err1, u64 *ext_err2)
1766 {
1767 struct tdx_module_args args = {
1768 .rcx = gpa | pg_level_to_tdx_sept_level(level),
1769 .rdx = tdx_tdr_pa(td),
1770 .r8 = PFN_PHYS(pfn),
1771 };
1772 u64 ret;
1773
1774 tdx_clflush_pfn(pfn);
1775 ret = seamcall_ret(TDH_MEM_PAGE_AUG, &args);
1776
1777 *ext_err1 = args.rcx;
1778 *ext_err2 = args.rdx;
1779
1780 return ret;
1781 }
1782 EXPORT_SYMBOL_FOR_KVM(tdh_mem_page_aug);
1783
tdh_mem_range_block(struct tdx_td * td,u64 gpa,enum pg_level level,u64 * ext_err1,u64 * ext_err2)1784 u64 tdh_mem_range_block(struct tdx_td *td, u64 gpa, enum pg_level level,
1785 u64 *ext_err1, u64 *ext_err2)
1786 {
1787 struct tdx_module_args args = {
1788 .rcx = gpa | pg_level_to_tdx_sept_level(level),
1789 .rdx = tdx_tdr_pa(td),
1790 };
1791 u64 ret;
1792
1793 ret = seamcall_ret(TDH_MEM_RANGE_BLOCK, &args);
1794
1795 *ext_err1 = args.rcx;
1796 *ext_err2 = args.rdx;
1797
1798 return ret;
1799 }
1800 EXPORT_SYMBOL_FOR_KVM(tdh_mem_range_block);
1801
tdh_mng_key_config(struct tdx_td * td)1802 u64 tdh_mng_key_config(struct tdx_td *td)
1803 {
1804 struct tdx_module_args args = {
1805 .rcx = tdx_tdr_pa(td),
1806 };
1807
1808 return seamcall(TDH_MNG_KEY_CONFIG, &args);
1809 }
1810 EXPORT_SYMBOL_FOR_KVM(tdh_mng_key_config);
1811
tdh_mng_create(struct tdx_td * td,u16 hkid)1812 u64 tdh_mng_create(struct tdx_td *td, u16 hkid)
1813 {
1814 struct tdx_module_args args = {
1815 .rcx = tdx_tdr_pa(td),
1816 .rdx = hkid,
1817 };
1818
1819 tdx_clflush_page(td->tdr_page);
1820 return seamcall(TDH_MNG_CREATE, &args);
1821 }
1822 EXPORT_SYMBOL_FOR_KVM(tdh_mng_create);
1823
tdh_vp_create(struct tdx_td * td,struct tdx_vp * vp)1824 u64 tdh_vp_create(struct tdx_td *td, struct tdx_vp *vp)
1825 {
1826 struct tdx_module_args args = {
1827 .rcx = vp->tdvpr_pa,
1828 .rdx = tdx_tdr_pa(td),
1829 };
1830
1831 tdx_clflush_page(vp->tdvpr_page);
1832 return seamcall(TDH_VP_CREATE, &args);
1833 }
1834 EXPORT_SYMBOL_FOR_KVM(tdh_vp_create);
1835
tdh_mng_rd(struct tdx_td * td,u64 field,u64 * data)1836 u64 tdh_mng_rd(struct tdx_td *td, u64 field, u64 *data)
1837 {
1838 struct tdx_module_args args = {
1839 .rcx = tdx_tdr_pa(td),
1840 .rdx = field,
1841 };
1842 u64 ret;
1843
1844 ret = seamcall_ret(TDH_MNG_RD, &args);
1845
1846 /* R8: Content of the field, or 0 in case of error. */
1847 *data = args.r8;
1848
1849 return ret;
1850 }
1851 EXPORT_SYMBOL_FOR_KVM(tdh_mng_rd);
1852
tdh_mr_extend(struct tdx_td * td,u64 gpa,u64 * ext_err1,u64 * ext_err2)1853 u64 tdh_mr_extend(struct tdx_td *td, u64 gpa, u64 *ext_err1, u64 *ext_err2)
1854 {
1855 struct tdx_module_args args = {
1856 .rcx = gpa,
1857 .rdx = tdx_tdr_pa(td),
1858 };
1859 u64 ret;
1860
1861 ret = seamcall_ret(TDH_MR_EXTEND, &args);
1862
1863 *ext_err1 = args.rcx;
1864 *ext_err2 = args.rdx;
1865
1866 return ret;
1867 }
1868 EXPORT_SYMBOL_FOR_KVM(tdh_mr_extend);
1869
tdh_mr_finalize(struct tdx_td * td)1870 u64 tdh_mr_finalize(struct tdx_td *td)
1871 {
1872 struct tdx_module_args args = {
1873 .rcx = tdx_tdr_pa(td),
1874 };
1875
1876 return seamcall(TDH_MR_FINALIZE, &args);
1877 }
1878 EXPORT_SYMBOL_FOR_KVM(tdh_mr_finalize);
1879
tdh_vp_flush(struct tdx_vp * vp)1880 u64 tdh_vp_flush(struct tdx_vp *vp)
1881 {
1882 struct tdx_module_args args = {
1883 .rcx = vp->tdvpr_pa,
1884 };
1885
1886 return seamcall(TDH_VP_FLUSH, &args);
1887 }
1888 EXPORT_SYMBOL_FOR_KVM(tdh_vp_flush);
1889
tdh_mng_vpflushdone(struct tdx_td * td)1890 u64 tdh_mng_vpflushdone(struct tdx_td *td)
1891 {
1892 struct tdx_module_args args = {
1893 .rcx = tdx_tdr_pa(td),
1894 };
1895
1896 return seamcall(TDH_MNG_VPFLUSHDONE, &args);
1897 }
1898 EXPORT_SYMBOL_FOR_KVM(tdh_mng_vpflushdone);
1899
tdh_mng_key_freeid(struct tdx_td * td)1900 u64 tdh_mng_key_freeid(struct tdx_td *td)
1901 {
1902 struct tdx_module_args args = {
1903 .rcx = tdx_tdr_pa(td),
1904 };
1905
1906 return seamcall(TDH_MNG_KEY_FREEID, &args);
1907 }
1908 EXPORT_SYMBOL_FOR_KVM(tdh_mng_key_freeid);
1909
tdh_mng_init(struct tdx_td * td,u64 td_params,u64 * extended_err)1910 u64 tdh_mng_init(struct tdx_td *td, u64 td_params, u64 *extended_err)
1911 {
1912 struct tdx_module_args args = {
1913 .rcx = tdx_tdr_pa(td),
1914 .rdx = td_params,
1915 };
1916 u64 ret;
1917
1918 ret = seamcall_ret(TDH_MNG_INIT, &args);
1919
1920 *extended_err = args.rcx;
1921
1922 return ret;
1923 }
1924 EXPORT_SYMBOL_FOR_KVM(tdh_mng_init);
1925
tdh_vp_rd(struct tdx_vp * vp,u64 field,u64 * data)1926 u64 tdh_vp_rd(struct tdx_vp *vp, u64 field, u64 *data)
1927 {
1928 struct tdx_module_args args = {
1929 .rcx = vp->tdvpr_pa,
1930 .rdx = field,
1931 };
1932 u64 ret;
1933
1934 ret = seamcall_ret(TDH_VP_RD, &args);
1935
1936 /* R8: Content of the field, or 0 in case of error. */
1937 *data = args.r8;
1938
1939 return ret;
1940 }
1941 EXPORT_SYMBOL_FOR_KVM(tdh_vp_rd);
1942
tdh_vp_wr(struct tdx_vp * vp,u64 field,u64 data,u64 mask)1943 u64 tdh_vp_wr(struct tdx_vp *vp, u64 field, u64 data, u64 mask)
1944 {
1945 struct tdx_module_args args = {
1946 .rcx = vp->tdvpr_pa,
1947 .rdx = field,
1948 .r8 = data,
1949 .r9 = mask,
1950 };
1951
1952 return seamcall(TDH_VP_WR, &args);
1953 }
1954 EXPORT_SYMBOL_FOR_KVM(tdh_vp_wr);
1955
tdh_vp_init(struct tdx_vp * vp,u64 initial_rcx,u32 x2apicid)1956 u64 tdh_vp_init(struct tdx_vp *vp, u64 initial_rcx, u32 x2apicid)
1957 {
1958 struct tdx_module_args args = {
1959 .rcx = vp->tdvpr_pa,
1960 .rdx = initial_rcx,
1961 .r8 = x2apicid,
1962 /* apicid requires version == 1. */
1963 .version = 1,
1964 };
1965
1966 return seamcall(TDH_VP_INIT, &args);
1967 }
1968 EXPORT_SYMBOL_FOR_KVM(tdh_vp_init);
1969
1970 /*
1971 * TDX ABI defines output operands as PT, OWNER and SIZE. These are TDX defined fomats.
1972 * So despite the names, they must be interpted specially as described by the spec. Return
1973 * them only for error reporting purposes.
1974 */
tdh_phymem_page_reclaim(struct page * page,u64 * tdx_pt,u64 * tdx_owner,u64 * tdx_size)1975 u64 tdh_phymem_page_reclaim(struct page *page, u64 *tdx_pt, u64 *tdx_owner, u64 *tdx_size)
1976 {
1977 struct tdx_module_args args = {
1978 .rcx = page_to_phys(page),
1979 };
1980 u64 ret;
1981
1982 ret = seamcall_ret(TDH_PHYMEM_PAGE_RECLAIM, &args);
1983
1984 *tdx_pt = args.rcx;
1985 *tdx_owner = args.rdx;
1986 *tdx_size = args.r8;
1987
1988 return ret;
1989 }
1990 EXPORT_SYMBOL_FOR_KVM(tdh_phymem_page_reclaim);
1991
tdh_mem_track(struct tdx_td * td)1992 u64 tdh_mem_track(struct tdx_td *td)
1993 {
1994 struct tdx_module_args args = {
1995 .rcx = tdx_tdr_pa(td),
1996 };
1997
1998 return seamcall(TDH_MEM_TRACK, &args);
1999 }
2000 EXPORT_SYMBOL_FOR_KVM(tdh_mem_track);
2001
tdh_mem_page_remove(struct tdx_td * td,u64 gpa,enum pg_level level,u64 * ext_err1,u64 * ext_err2)2002 u64 tdh_mem_page_remove(struct tdx_td *td, u64 gpa, enum pg_level level,
2003 u64 *ext_err1, u64 *ext_err2)
2004 {
2005 struct tdx_module_args args = {
2006 .rcx = gpa | pg_level_to_tdx_sept_level(level),
2007 .rdx = tdx_tdr_pa(td),
2008 };
2009 u64 ret;
2010
2011 ret = seamcall_ret(TDH_MEM_PAGE_REMOVE, &args);
2012
2013 *ext_err1 = args.rcx;
2014 *ext_err2 = args.rdx;
2015
2016 return ret;
2017 }
2018 EXPORT_SYMBOL_FOR_KVM(tdh_mem_page_remove);
2019
tdh_phymem_cache_wb(bool resume)2020 u64 tdh_phymem_cache_wb(bool resume)
2021 {
2022 struct tdx_module_args args = {
2023 .rcx = resume ? 1 : 0,
2024 };
2025
2026 return seamcall(TDH_PHYMEM_CACHE_WB, &args);
2027 }
2028 EXPORT_SYMBOL_FOR_KVM(tdh_phymem_cache_wb);
2029
mk_keyed_paddr(u16 hkid,kvm_pfn_t pfn)2030 static inline u64 mk_keyed_paddr(u16 hkid, kvm_pfn_t pfn)
2031 {
2032 /* KeyID bits are just above the physical address bits. */
2033 return PFN_PHYS(pfn) | ((u64)hkid << boot_cpu_data.x86_phys_bits);
2034 }
2035
tdh_phymem_page_wbinvd_tdr(struct tdx_td * td)2036 u64 tdh_phymem_page_wbinvd_tdr(struct tdx_td *td)
2037 {
2038 struct tdx_module_args args = {};
2039
2040 args.rcx = mk_keyed_paddr(tdx_global_keyid, page_to_pfn(td->tdr_page));
2041
2042 return seamcall(TDH_PHYMEM_PAGE_WBINVD, &args);
2043 }
2044 EXPORT_SYMBOL_FOR_KVM(tdh_phymem_page_wbinvd_tdr);
2045
tdh_phymem_page_wbinvd_hkid(u64 hkid,kvm_pfn_t pfn)2046 u64 tdh_phymem_page_wbinvd_hkid(u64 hkid, kvm_pfn_t pfn)
2047 {
2048 struct tdx_module_args args = {};
2049
2050 args.rcx = mk_keyed_paddr(hkid, pfn);
2051
2052 return seamcall(TDH_PHYMEM_PAGE_WBINVD, &args);
2053 }
2054 EXPORT_SYMBOL_FOR_KVM(tdh_phymem_page_wbinvd_hkid);
2055
tdx_supports_dynamic_pamt(const struct tdx_sys_info * sysinfo)2056 bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)
2057 {
2058 return sysinfo->features.tdx_features0 & TDX_FEATURES0_DYNAMIC_PAMT;
2059 }
2060 EXPORT_SYMBOL_FOR_KVM(tdx_supports_dynamic_pamt);
2061
tdx_alloc_page_pamt_cache(struct tdx_pamt_cache * cache)2062 static struct page *tdx_alloc_page_pamt_cache(struct tdx_pamt_cache *cache)
2063 {
2064 struct page *page;
2065
2066 page = list_first_entry_or_null(&cache->page_list, struct page, lru);
2067 if (page) {
2068 list_del(&page->lru);
2069 cache->cnt--;
2070 }
2071
2072 return page;
2073 }
2074
alloc_dpamt_page(struct tdx_pamt_cache * cache)2075 static struct page *alloc_dpamt_page(struct tdx_pamt_cache *cache)
2076 {
2077 if (cache)
2078 return tdx_alloc_page_pamt_cache(cache);
2079
2080 return alloc_page(GFP_KERNEL_ACCOUNT);
2081 }
2082
alloc_pamt_array(struct page ** pamt_pages,struct tdx_pamt_cache * cache)2083 static int alloc_pamt_array(struct page **pamt_pages, struct tdx_pamt_cache *cache)
2084 {
2085 int i, j;
2086
2087 for (i = 0; i < TDX_DPAMT_ENTRY_PAGE_CNT; i++) {
2088 pamt_pages[i] = alloc_dpamt_page(cache);
2089 if (!pamt_pages[i])
2090 goto err;
2091 }
2092
2093 return 0;
2094
2095 err:
2096 for (j = 0; j < i; j++)
2097 __free_page(pamt_pages[j]);
2098
2099 return -ENOMEM;
2100 }
2101
free_pamt_array(struct page ** pamt_pages)2102 static void free_pamt_array(struct page **pamt_pages)
2103 {
2104 int i;
2105
2106 for (i = 0; i < TDX_DPAMT_ENTRY_PAGE_CNT; i++) {
2107 /*
2108 * Reset pages unconditionally to cover cases
2109 * where they were passed to the TDX module.
2110 */
2111 tdx_quirk_reset_paddr(page_to_phys(pamt_pages[i]), PAGE_SIZE);
2112
2113 __free_page(pamt_pages[i]);
2114 }
2115 }
2116
2117 /* Helper for building DPAMT seamcall() arguments. */
pamt_2mb_arg(kvm_pfn_t pfn)2118 static u64 pamt_2mb_arg(kvm_pfn_t pfn)
2119 {
2120 /* Find the 2MB-wide DPAMT region for 'pfn': */
2121 unsigned long hpa_2mb = ALIGN_DOWN(pfn << PAGE_SHIFT, PMD_SIZE);
2122
2123 /*
2124 * TDX ABI requires specifying the page level the installed DPAMT
2125 * backing will cover, even though today only 2MB is supported.
2126 */
2127 return hpa_2mb | TDX_PS_2M;
2128 }
2129
2130 /* Add DPAMT backing for the 2MB region surrounding the given pfn. */
tdh_phymem_pamt_add(kvm_pfn_t pfn,struct page ** pamt_pages)2131 static u64 tdh_phymem_pamt_add(kvm_pfn_t pfn, struct page **pamt_pages)
2132 {
2133 struct tdx_module_args args = {
2134 .rcx = pamt_2mb_arg(pfn),
2135 .rdx = page_to_phys(pamt_pages[0]),
2136 .r8 = page_to_phys(pamt_pages[1]),
2137 };
2138
2139 return seamcall(TDH_PHYMEM_PAMT_ADD, &args);
2140 }
2141
2142 /* Remove DPAMT backing for the 2MB region surrounding the given pfn. */
tdh_phymem_pamt_remove(kvm_pfn_t pfn,struct page ** pamt_pages)2143 static u64 tdh_phymem_pamt_remove(kvm_pfn_t pfn, struct page **pamt_pages)
2144 {
2145 struct tdx_module_args args = {
2146 .rcx = pamt_2mb_arg(pfn),
2147 };
2148 u64 ret;
2149
2150 ret = seamcall_ret(TDH_PHYMEM_PAMT_REMOVE, &args);
2151 if (ret)
2152 return ret;
2153
2154 /* Copy PAMT pages out of the struct per the TDX ABI */
2155 pamt_pages[0] = phys_to_page(args.rdx);
2156 pamt_pages[1] = phys_to_page(args.r8);
2157
2158 return 0;
2159 }
2160
2161 /* Serializes adding/removing DPAMT memory */
2162 static DEFINE_SPINLOCK(dpamt_lock);
2163
2164 /* Bump DPAMT refcount for the given pfn and allocate DPAMT backing if needed. */
tdx_pamt_get(kvm_pfn_t pfn,struct tdx_pamt_cache * cache)2165 int tdx_pamt_get(kvm_pfn_t pfn, struct tdx_pamt_cache *cache)
2166 {
2167 struct page *pamt_pages[TDX_DPAMT_ENTRY_PAGE_CNT];
2168 atomic_t *dpamt_refcount;
2169 u64 tdx_status;
2170 int ret;
2171
2172 if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
2173 return 0;
2174
2175 ret = alloc_pamt_array(pamt_pages, cache);
2176 if (ret)
2177 return ret;
2178
2179 dpamt_refcount = tdx_find_dpamt_refcount(pfn);
2180
2181 spin_lock(&dpamt_lock);
2182
2183 /*
2184 * If the DPAMT entry is already added (i.e. refcount >= 1),
2185 * then just increment the refcount.
2186 */
2187 if (atomic_inc_not_zero(dpamt_refcount))
2188 goto out_free;
2189
2190 /* Try to add the PAMT page and take the refcount 0->1. */
2191 tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
2192 if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS)) {
2193 ret = -EIO;
2194 goto out_free;
2195 }
2196
2197 atomic_set(dpamt_refcount, 1);
2198 spin_unlock(&dpamt_lock);
2199 return 0;
2200
2201 out_free:
2202 spin_unlock(&dpamt_lock);
2203 free_pamt_array(pamt_pages);
2204
2205 return ret;
2206 }
2207 EXPORT_SYMBOL_FOR_KVM(tdx_pamt_get);
2208
2209 /* Drop DPAMT refcount for the given pfn and free DPAMT backing if needed. */
tdx_pamt_put(kvm_pfn_t pfn)2210 void tdx_pamt_put(kvm_pfn_t pfn)
2211 {
2212 struct page *pamt_pages[TDX_DPAMT_ENTRY_PAGE_CNT] = {};
2213 atomic_t *dpamt_refcount;
2214 u64 tdx_status;
2215
2216 if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
2217 return;
2218
2219 dpamt_refcount = tdx_find_dpamt_refcount(pfn);
2220
2221 spin_lock(&dpamt_lock);
2222 /*
2223 * If there is more than 1 reference on the DPAMT entry, don't
2224 * remove it yet. Just decrement the refcount.
2225 */
2226 if (atomic_read(dpamt_refcount) > 1) {
2227 atomic_dec(dpamt_refcount);
2228 goto out_unlock;
2229 }
2230
2231 /* Try to remove the pamt page and take the refcount 1->0. */
2232 tdx_status = tdh_phymem_pamt_remove(pfn, pamt_pages);
2233
2234 /*
2235 * Don't free pamt_pages as it could hold garbage when
2236 * tdh_phymem_pamt_remove() fails. Don't panic/BUG_ON(), as
2237 * there is no risk of data corruption, but do yell loudly as
2238 * failure indicates a kernel bug, memory is being leaked, and
2239 * the dangling DPAMT entry may cause future operations to fail.
2240 */
2241 if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS))
2242 goto out_unlock;
2243
2244 atomic_set(dpamt_refcount, 0);
2245 spin_unlock(&dpamt_lock);
2246 free_pamt_array(pamt_pages);
2247 return;
2248 out_unlock:
2249 spin_unlock(&dpamt_lock);
2250 }
2251 EXPORT_SYMBOL_FOR_KVM(tdx_pamt_put);
2252
tdx_free_pamt_cache(struct tdx_pamt_cache * cache)2253 void tdx_free_pamt_cache(struct tdx_pamt_cache *cache)
2254 {
2255 struct page *page;
2256
2257 while ((page = tdx_alloc_page_pamt_cache(cache)))
2258 __free_page(page);
2259 }
2260 EXPORT_SYMBOL_FOR_KVM(tdx_free_pamt_cache);
2261
tdx_topup_pamt_cache(struct tdx_pamt_cache * cache,unsigned long npages)2262 int tdx_topup_pamt_cache(struct tdx_pamt_cache *cache, unsigned long npages)
2263 {
2264 if (WARN_ON_ONCE(!tdx_supports_dynamic_pamt(&tdx_sysinfo)))
2265 return 0;
2266
2267 npages *= TDX_DPAMT_ENTRY_PAGE_CNT;
2268
2269 while (cache->cnt < npages) {
2270 struct page *page = alloc_page(GFP_KERNEL_ACCOUNT);
2271
2272 if (!page)
2273 return -ENOMEM;
2274
2275 list_add(&page->lru, &cache->page_list);
2276 cache->cnt++;
2277 }
2278
2279 return 0;
2280 }
2281 EXPORT_SYMBOL_FOR_KVM(tdx_topup_pamt_cache);
2282
2283 /*
2284 * Return a page that can be gifted to the TDX module for use as a "control"
2285 * page, i.e. pages that are used for control structures for a given TDX
2286 * guest, and thus obtain TDX protections, including DPAMT tracking.
2287 */
tdx_alloc_control_page(void)2288 struct page *tdx_alloc_control_page(void)
2289 {
2290 struct page *page;
2291
2292 page = alloc_page(GFP_KERNEL_ACCOUNT);
2293 if (!page)
2294 return NULL;
2295
2296 if (tdx_pamt_get(page_to_pfn(page), NULL)) {
2297 __free_page(page);
2298 return NULL;
2299 }
2300
2301 return page;
2302 }
2303 EXPORT_SYMBOL_FOR_KVM(tdx_alloc_control_page);
2304
2305 /*
2306 * Free a page that was gifted to the TDX module for use as a control
2307 * page. After this, the page is no longer protected by TDX.
2308 */
tdx_free_control_page(struct page * page)2309 void tdx_free_control_page(struct page *page)
2310 {
2311 if (!page)
2312 return;
2313
2314 tdx_pamt_put(page_to_pfn(page));
2315 __free_page(page);
2316 }
2317 EXPORT_SYMBOL_FOR_KVM(tdx_free_control_page);
2318
tdx_sys_disable(void)2319 void tdx_sys_disable(void)
2320 {
2321 struct tdx_module_args args = {};
2322 u64 ret;
2323
2324 /*
2325 * Don't loop forever.
2326 *
2327 * - TDX_INTERRUPTED_RESUMABLE guarantees forward progress between
2328 * calls.
2329 *
2330 * - TDX_SYS_BUSY could be returned due to contention with other
2331 * TDH.SYS.* SEAMCALLs, but will lock out *new* TDH.SYS.* SEAMCALLs,
2332 * so that SYS.DISABLE can eventually make progress.
2333 *
2334 * This is a 'destructive' SEAMCALL, in that no other SEAMCALL can be
2335 * run after this until a full reinitialization is done.
2336 */
2337 do {
2338 ret = seamcall(TDH_SYS_DISABLE, &args);
2339 } while (ret == TDX_INTERRUPTED_RESUMABLE || ret == TDX_SYS_BUSY);
2340
2341 /*
2342 * Print SEAMCALL failures, but not SW-defined error codes
2343 * (SEAMCALL faulted with #GP/#UD, TDX not supported).
2344 */
2345 if (ret && (ret & TDX_SW_ERROR) != TDX_SW_ERROR)
2346 pr_err("TDH.SYS.DISABLE failed: 0x%016llx\n", ret);
2347 }
2348