Skip to contentSkip to conversation

Dynamic PAMT

PATCH Superseded Rick Edgecombe 10 participants 107 messages May 26 – Jul 10

Subsystems (5)
Documentation x86 KVM KVM x86 +1 more subsystems

v6 of 11 Superseded Latest is v11 →

lore
Share & tools
lore

Rick Edgecombe

author maintainer
#0 lore raw

v6 cover Dynamic PAMT

Hi,

This is next revision of Dynamic PAMT TDX series, which I’m calling v6 in order to differentiate it from Sean’s giant MMU refactor/DPAMT/Huge-page series which he called v5 [0]. But things are not quite linear, because that v5 didn’t include the feedback from v4 [1].

So this version is the conflict resolution of:
1. Comments on Dynamic PAMT v4
2. Sean changes in Dynamic PAMT v4 -> Sean Mega v5
3. Feedback to Sean’s v5

For Dynamic PAMT background, please refer to [2].

This series is pretty mature at this point, however with 2 pre-req series still on the list (more on that below under "Base"), I can't ask for it to be merged at this point. So I'm hoping to collect some Acks and RB's in the meantime and then it can have a smooth path once those other series land. Please especially consider any reviewabiliy concerns on the tip side that can be ironed out in the meantime.

Changes
=======

Sean’s mega v5
--------------
This had a bunch of MMU refactor work, which did:
a. TDX MMU refactor that generally pushed more TDX knowledge into TDX.c
out of the core MMU. This covered the needs of both DPAMT and huge pages.
b. Redid the solution for installing DPAMT backing for the pages the MMU
uses for the S-EPT operations.
c. Some huge page changes that I’ll skip here.

(a) has been split into another series [3]. After long discussions on v5, the changes for (b) were rolled back to the original solution in v4. Sean’s v5 included him trying to do Kai’s idea and running into trouble, then a second new idea which also was found to have issues on review of v5. By my count we have had at least 4 or 5 ideas by smart people that led us back to the same solution of keeping a cache of pages and adjusting the DPAMT right before give the page to the TDX module. I, again, think that we should either accept the current solution or get started on going back to change the arch in order to make it more workable for this problem.

Dropping Non-Required Changes
-----------------------------
In the interest of finally clearing these patches, I dropped everything I could out of the series.

The most significant thing dropped was the optimization around the refcount allocation. It is a good thing to drop because it is not required to make Dynamic PAMT useful as a memory optimization. And there is room for debate on how far to optimize the last little bit of memory usage.

To recap, the kernel implementation keeps a kernel side refcount for each 2MB of the physical memory. The non-optimized version just uses a single vmalloc to cover the range from 0 to max_pfn. In the worst case this is 8GB of memory. The optimization tried to not allocate refcounts for the sparse ranges that didn't have any RAM.

For a simple small server with mostly physical contiguous RAM and no CXL complications, the basic implementation should be close to optimal anyway. And for big servers, an 8GB allocation is going to have less impact. In the end Dynamic PAMT *is* an optimization that we will force on as a good default option. Even with all the optimizations we could throw at it, if the system is 100% TDs, Dynamic PAMT could come out slightly behind. So judgment on good defaults is needed regardless.

Consider a couple simple examples of TDX enabled, but no TDs, and the non-optimized refcount solution:

Machine                    PAMT (GB)   DPAMT (GB)   Savings/(Loss)
256GB (max_pfn at 256GB)   1.02        0.01         100x
256GB (max_pfn at maxpa)   1.02        8.01         (8x)
2TB   (max_pfn at 2TB)     8.19        0.08         99x
2TB   (max_pfn at maxpa)   8.19        8.08         1x

The weird server loses a little bit, but not nearly as much as the normal ones gain. Still enough benefit in general to make Dynamic PAMT a worthwhile default setting. So let's start with the simplest solution, which is an improvement in most cases. And then separate out the refcount optimization discussion for later.

Besides that, I dropped the error cleanups. As I was implementing the last discussion, I found it a bit awkward in some places. Also I noticed that Dave did not fully agree to that proposal either. So it's a continual source of style controversy and we can separate it out from the Dynamic PAMT work.

I did not drop the optimization that uses the refcounts to avoid taking the global lock in tdx_pamt_get/put() because I considered it critical for making Dynamic PAMT default on. It is more about avoid regressing KVM EPT violation contention, and not about squeezing out more memory savings from Dynamic PAMT.

Regarding whether we could strip more out of the series if we made this a boot time kernel parameter. I think it's possible to drop "x86/virt/tdx:
Allocate reference counters for PAMT memory" and "x86/virt/tdx: Allocate reference counters for PAMT memory" and still have something that is functional. I didn't go that route for this revision because making the feature optional seemed like too much of a divergence from past discussion. But it is an option if this series seems like too much to digest at once.

AI use in this revision
=======================
While AI enhanced development is still relatively new to the kernel world, I wanted to share a bit about how this series was generated. For both consideration in reviewing, and also maybe people might find it interesting. This was my first time using AI for serious kernel work, so it was kind of a micromanaged evaluation type use. I used an opus model with a dump of the many mail threads and a description of how they were related. Since the previous discussion was pretty disordered, I had it try to catch any feedback that was missed or conflicted for each patch. And it caught a few that I had missed. I also used it to turn some of the feedback into code changes, and to heavily scrutinize the concurrency logic in tdx_pamt_get/put(). I used it to suggest some log changes too, but had to edit most of those pretty heavily. Lastly, I used the Chris Meson and Sashiko review prompts to review the series, which generated a few changes. All this experimentation generated quite a few Assisted-by tags, which now feels kinda excessive...

Base
====
This is based on v2 of the MMU refactor series Yan posted a few weeks ago [3], which is itself based on the struct page to pfn conversion series[4]. A full stack branch can be found here: [5].

Testing
=======
This series was tested in the usual suite, but also with the optimization patch removed.

[0] https://lore.kernel.org/kvm/[email protected]/
[1] https://lore.kernel.org/kvm/[email protected]/
[2] https://lore.kernel.org/kvm/[email protected]/
[3] https://lore.kernel.org/kvm/[email protected]/
[4] https://lore.kernel.org/kvm/[email protected]/
[5] https://github.com/intel-staging/tdx/tree/dpamt_v6

Kiryl Shutsemau (9):
x86/virt/tdx: Allocate page bitmap for Dynamic PAMT x86/virt/tdx: Add tdx_alloc/free_control_page() helpers x86/virt/tdx: Allocate ref counts for Dynamic PAMT memory x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put() x86/virt/tdx: Optimize tdx_pamt_get/put()
KVM: TDX: Allocate PAMT memory for TD and vCPU control structures
KVM: TDX: Get/put PAMT pages when (un)mapping private memory x86/virt/tdx: Enable Dynamic PAMT
Documentation/x86: Add documentation for TDX's Dynamic PAMT

Rick Edgecombe (2):
x86/virt/tdx: Simplify tdmr_get_pamt_sz()
x86/tdx: Add APIs to support Dynamic PAMT ops from KVM's fault path

 Documentation/arch/x86/tdx.rst              |  22 +
 arch/x86/include/asm/kvm-x86-ops.h          |   1 +
 arch/x86/include/asm/kvm_host.h             |   2 +
 arch/x86/include/asm/tdx.h                  |  38 ++
 arch/x86/include/asm/tdx_global_metadata.h  |   3 +
 arch/x86/kvm/mmu/mmu.c                      |   4 +
 arch/x86/kvm/vmx/tdx.c                      | 100 +++--
 arch/x86/kvm/vmx/tdx.h                      |   2 +
 arch/x86/virt/vmx/tdx/tdx.c                 | 445 +++++++++++++++++---
 arch/x86/virt/vmx/tdx/tdx.h                 |   5 +-
 arch/x86/virt/vmx/tdx/tdx_global_metadata.c |  21 +-
 11 files changed, 544 insertions(+), 99 deletions(-)
Signature · 1 line
2.54.0
author maintainer
#1 lore raw

PATCH v6 1/11 x86/virt/tdx: Simplify tdmr_get_pamt_sz()

For each memory region that the TDX module might use (called TDMR), three separate traditional PAMT allocations are needed. One for each supported page size (1GB, 2MB, 4KB). These store information on each page in the TDMR. In Linux, they are allocated out of one physically contiguous block, in order to more efficiently use some internal TDX module book keeping resources. So some simple math is needed to break the single large allocation into three smaller allocations for each page size.

There are some commonalities in the math needed to calculate the base and size for each smaller allocation, and so an effort was made to share logic across the three. Unfortunately doing this turned out unnaturally tortured, with a loop iterating over the three page sizes, only to call into a function with cases statement for each page size. In the future Dynamic PAMT will add more logic that is special to the 4KB page size, making the benefit of the math sharing even more questionable.

Three is not a very high number, so get rid of the loop and just duplicate the small calculation three times. In doing so, setup for future Dynamic PAMT changes.

Since the loop that iterates over it is gone, further simplify the code by dropping the array of intermediate size and base storage. Just store the values to their final locations. Accept the small complication of having to clear tdmr->pamt_4k_base in the error path, so that tdmr_do_pamt_func() will not try to operate on the TDMR struct when attempting to free it.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

---
v6:
- Drop {} by moving a comment (Binbin)
- Log tweaks

v4:
- Just refer to global var instead of passing pamt_entry_size around (Xiaoyao)
- Remove setting pamt_4k_base to zero, because it already is zero. Adjust the comment appropriately (Kai)

v3:
- New patch

---
 arch/x86/virt/vmx/tdx/tdx.c | 93 ++++++++++++-------------------------
 1 file changed, 29 insertions(+), 64 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +29 -64
index 967482ae3c801..487f389f52f4b 100644
@@ -516,31 +516,21 @@ static __init int fill_out_tdmrs(struct list_head *tmb_list,
  * Calculate PAMT size given a TDMR and a page size.  The returned
  * PAMT size is always aligned up to 4K page boundary.
  */
-static __init unsigned long tdmr_get_pamt_sz(struct tdmr_info *tdmr, int pgsz,
-					     u16 pamt_entry_size)
+static __init unsigned long tdmr_get_pamt_sz(struct tdmr_info *tdmr, int pgsz)
 {
 	unsigned long pamt_sz, nr_pamt_entries;
+	const int tdx_pg_size_shift[] = { PAGE_SHIFT, PMD_SHIFT, PUD_SHIFT };
+	const u16 pamt_entry_size[TDX_PS_NR] = {
+		tdx_sysinfo.tdmr.pamt_4k_entry_size,
+		tdx_sysinfo.tdmr.pamt_2m_entry_size,
+		tdx_sysinfo.tdmr.pamt_1g_entry_size,
+	};
 
-	switch (pgsz) {
-	case TDX_PS_4K:
-		nr_pamt_entries = tdmr->size >> PAGE_SHIFT;
-		break;
-	case TDX_PS_2M:
-		nr_pamt_entries = tdmr->size >> PMD_SHIFT;
-		break;
-	case TDX_PS_1G:
-		nr_pamt_entries = tdmr->size >> PUD_SHIFT;
-		break;
-	default:
-		WARN_ON_ONCE(1);
-		return 0;
-	}
+	nr_pamt_entries = tdmr->size >> tdx_pg_size_shift[pgsz];
+	pamt_sz = nr_pamt_entries * pamt_entry_size[pgsz];
 
-	pamt_sz = nr_pamt_entries * pamt_entry_size;
 	/* TDX requires PAMT size must be 4K aligned */
-	pamt_sz = ALIGN(pamt_sz, PAGE_SIZE);
-
-	return pamt_sz;
+	return PAGE_ALIGN(pamt_sz);
 }
 
 /*
@@ -578,28 +568,21 @@ static __init int tdmr_get_nid(struct tdmr_info *tdmr, struct list_head *tmb_lis
  * within @tdmr, and set up PAMTs for @tdmr.
  */
 static __init int tdmr_set_up_pamt(struct tdmr_info *tdmr,
-				   struct list_head *tmb_list,
-				   u16 pamt_entry_size[])
+				   struct list_head *tmb_list)
 {
-	unsigned long pamt_base[TDX_PS_NR];
-	unsigned long pamt_size[TDX_PS_NR];
-	unsigned long tdmr_pamt_base;
 	unsigned long tdmr_pamt_size;
 	struct page *pamt;
-	int pgsz, nid;
-
+	int nid;
 	nid = tdmr_get_nid(tdmr, tmb_list);
 
 	/*
 	 * Calculate the PAMT size for each TDX supported page size
 	 * and the total PAMT size.
 	 */
-	tdmr_pamt_size = 0;
-	for (pgsz = TDX_PS_4K; pgsz < TDX_PS_NR; pgsz++) {
-		pamt_size[pgsz] = tdmr_get_pamt_sz(tdmr, pgsz,
-					pamt_entry_size[pgsz]);
-		tdmr_pamt_size += pamt_size[pgsz];
-	}
+	tdmr->pamt_4k_size = tdmr_get_pamt_sz(tdmr, TDX_PS_4K);
+	tdmr->pamt_2m_size = tdmr_get_pamt_sz(tdmr, TDX_PS_2M);
+	tdmr->pamt_1g_size = tdmr_get_pamt_sz(tdmr, TDX_PS_1G);
+	tdmr_pamt_size = tdmr->pamt_4k_size + tdmr->pamt_2m_size + tdmr->pamt_1g_size;
 
 	/*
 	 * Allocate one chunk of physically contiguous memory for all
@@ -607,26 +590,18 @@ static __init int tdmr_set_up_pamt(struct tdmr_info *tdmr,
 	 * in overlapped TDMRs.
 	 */
 	pamt = alloc_contig_pages(tdmr_pamt_size >> PAGE_SHIFT, GFP_KERNEL,
-			nid, &node_online_map);
+				  nid, &node_online_map);
+
+	/*
+	 * tdmr->pamt_4k_base is still zero so the error
+	 * path of the caller will skip freeing the pamt.
+	 */
 	if (!pamt)
 		return -ENOMEM;
 
-	/*
-	 * Break the contiguous allocation back up into the
-	 * individual PAMTs for each page size.
-	 */
-	tdmr_pamt_base = page_to_pfn(pamt) << PAGE_SHIFT;
-	for (pgsz = TDX_PS_4K; pgsz < TDX_PS_NR; pgsz++) {
-		pamt_base[pgsz] = tdmr_pamt_base;
-		tdmr_pamt_base += pamt_size[pgsz];
-	}
-
-	tdmr->pamt_4k_base = pamt_base[TDX_PS_4K];
-	tdmr->pamt_4k_size = pamt_size[TDX_PS_4K];
-	tdmr->pamt_2m_base = pamt_base[TDX_PS_2M];
-	tdmr->pamt_2m_size = pamt_size[TDX_PS_2M];
-	tdmr->pamt_1g_base = pamt_base[TDX_PS_1G];
-	tdmr->pamt_1g_size = pamt_size[TDX_PS_1G];
+	tdmr->pamt_4k_base = page_to_phys(pamt);
+	tdmr->pamt_2m_base = tdmr->pamt_4k_base + tdmr->pamt_4k_size;
+	tdmr->pamt_1g_base = tdmr->pamt_2m_base + tdmr->pamt_2m_size;
 
 	return 0;
 }
@@ -657,10 +632,7 @@ static __init void tdmr_do_pamt_func(struct tdmr_info *tdmr,
 	tdmr_get_pamt(tdmr, &pamt_base, &pamt_size);
 
 	/* Do nothing if PAMT hasn't been allocated for this TDMR */
-	if (!pamt_size)
-		return;
-
-	if (WARN_ON_ONCE(!pamt_base))
+	if (!pamt_base)
 		return;
 
 	pamt_func(pamt_base, pamt_size);
@@ -686,14 +658,12 @@ static __init void tdmrs_free_pamt_all(struct tdmr_info_list *tdmr_list)
 
 /* Allocate and set up PAMTs for all TDMRs */
 static __init int tdmrs_set_up_pamt_all(struct tdmr_info_list *tdmr_list,
-					struct list_head *tmb_list,
-					u16 pamt_entry_size[])
+				 struct list_head *tmb_list)
 {
 	int i, ret = 0;
 
 	for (i = 0; i < tdmr_list->nr_consumed_tdmrs; i++) {
-		ret = tdmr_set_up_pamt(tdmr_entry(tdmr_list, i), tmb_list,
-				pamt_entry_size);
+		ret = tdmr_set_up_pamt(tdmr_entry(tdmr_list, i), tmb_list);
 		if (ret)
 			goto err;
 	}
@@ -970,18 +940,13 @@ static __init int construct_tdmrs(struct list_head *tmb_list,
 				  struct tdmr_info_list *tdmr_list,
 				  struct tdx_sys_info_tdmr *sysinfo_tdmr)
 {
-	u16 pamt_entry_size[TDX_PS_NR] = {
-		sysinfo_tdmr->pamt_4k_entry_size,
-		sysinfo_tdmr->pamt_2m_entry_size,
-		sysinfo_tdmr->pamt_1g_entry_size,
-	};
 	int ret;
 
 	ret = fill_out_tdmrs(tmb_list, tdmr_list);
 	if (ret)
 		return ret;
 
-	ret = tdmrs_set_up_pamt_all(tdmr_list, tmb_list, pamt_entry_size);
+	ret = tdmrs_set_up_pamt_all(tdmr_list, tmb_list);
 	if (ret)
 		return ret;
 
Signature · 1 line
2.54.0
maintainer Reviewed-by on v6 1/11
#2 lore raw

Re: [PATCH v6 01/11] x86/virt/tdx: Simplify tdmr_get_pamt_sz()

Quoted 26 lines · Rick Edgecombe

For each memory region that the TDX module might use (called TDMR), three separate traditional PAMT allocations are needed. One for each supported page size (1GB, 2MB, 4KB). These store information on each page in the TDMR. In Linux, they are allocated out of one physically contiguous block, in order to more efficiently use some internal TDX module book keeping resources. So some simple math is needed to break the single large allocation into three smaller allocations for each page size.

There are some commonalities in the math needed to calculate the base and size for each smaller allocation, and so an effort was made to share logic across the three. Unfortunately doing this turned out unnaturally tortured, with a loop iterating over the three page sizes, only to call into a function with cases statement for each page size. In the future Dynamic PAMT will add more logic that is special to the 4KB page size, making the benefit of the math sharing even more questionable.

Three is not a very high number, so get rid of the loop and just duplicate the small calculation three times. In doing so, setup for future Dynamic PAMT changes.

Since the loop that iterates over it is gone, further simplify the code by dropping the array of intermediate size and base storage. Just store the values to their final locations. Accept the small complication of having to clear tdmr->pamt_4k_base in the error path, so that tdmr_do_pamt_func() will not try to operate on the TDMR struct when attempting to free it.

Quoted 3 lines
Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

Couple of nits below.

Quoted 69 lines

---
v6:
- Drop {} by moving a comment (Binbin)
- Log tweaks

v4:
- Just refer to global var instead of passing pamt_entry_size around (Xiaoyao)
- Remove setting pamt_4k_base to zero, because it already is zero. Adjust the comment appropriately (Kai)

v3:
- New patch

---
 arch/x86/virt/vmx/tdx/tdx.c | 93 ++++++++++++-------------------------
 1 file changed, 29 insertions(+), 64 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +10 -22
index 967482ae3c801..487f389f52f4b 100644
@@ -516,31 +516,21 @@ static __init int fill_out_tdmrs(struct list_head *tmb_list,
  * Calculate PAMT size given a TDMR and a page size.  The returned
  * PAMT size is always aligned up to 4K page boundary.
  */
-static __init unsigned long tdmr_get_pamt_sz(struct tdmr_info *tdmr, int pgsz,
-					     u16 pamt_entry_size)
+static __init unsigned long tdmr_get_pamt_sz(struct tdmr_info *tdmr, int pgsz)
 {
 	unsigned long pamt_sz, nr_pamt_entries;
+	const int tdx_pg_size_shift[] = { PAGE_SHIFT, PMD_SHIFT, PUD_SHIFT };
+	const u16 pamt_entry_size[TDX_PS_NR] = {
+		tdx_sysinfo.tdmr.pamt_4k_entry_size,
+		tdx_sysinfo.tdmr.pamt_2m_entry_size,
+		tdx_sysinfo.tdmr.pamt_1g_entry_size,
+	};
 
-	switch (pgsz) {
-	case TDX_PS_4K:
-		nr_pamt_entries = tdmr->size >> PAGE_SHIFT;
-		break;
-	case TDX_PS_2M:
-		nr_pamt_entries = tdmr->size >> PMD_SHIFT;
-		break;
-	case TDX_PS_1G:
-		nr_pamt_entries = tdmr->size >> PUD_SHIFT;
-		break;
-	default:
-		WARN_ON_ONCE(1);
-		return 0;
-	}
+	nr_pamt_entries = tdmr->size >> tdx_pg_size_shift[pgsz];
+	pamt_sz = nr_pamt_entries * pamt_entry_size[pgsz];
 
-	pamt_sz = nr_pamt_entries * pamt_entry_size;
 	/* TDX requires PAMT size must be 4K aligned */
-	pamt_sz = ALIGN(pamt_sz, PAGE_SIZE);
-
-	return pamt_sz;
+	return PAGE_ALIGN(pamt_sz);
 }
 
 /*
@@ -578,28 +568,21 @@ static __init int tdmr_get_nid(struct tdmr_info *tdmr, struct list_head *tmb_lis
  * within @tdmr, and set up PAMTs for @tdmr.
  */
 static __init int tdmr_set_up_pamt(struct tdmr_info *tdmr,
-				   struct list_head *tmb_list,
-				   u16 pamt_entry_size[])

arch/x86/virt/vmx/tdx/tdx.c static __init int tdmr_get_nid(struct tdmr_info *tdmr, struct list_head *tmb_lis · line 575

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +2 -5
+				   struct list_head *tmb_list)
 {
-	unsigned long pamt_base[TDX_PS_NR];
-	unsigned long pamt_size[TDX_PS_NR];
-	unsigned long tdmr_pamt_base;
 	unsigned long tdmr_pamt_size;
 	struct page *pamt;
-	int pgsz, nid;
-
+	int nid;

Add a newline here?

Quoted 20 lines
arch/x86/virt/vmx/tdx/tdx.c +4 -6
 	nid = tdmr_get_nid(tdmr, tmb_list);
 
 	/*
 	 * Calculate the PAMT size for each TDX supported page size
 	 * and the total PAMT size.
 	 */
-	tdmr_pamt_size = 0;
-	for (pgsz = TDX_PS_4K; pgsz < TDX_PS_NR; pgsz++) {
-		pamt_size[pgsz] = tdmr_get_pamt_sz(tdmr, pgsz,
-					pamt_entry_size[pgsz]);
-		tdmr_pamt_size += pamt_size[pgsz];
-	}
+	tdmr->pamt_4k_size = tdmr_get_pamt_sz(tdmr, TDX_PS_4K);
+	tdmr->pamt_2m_size = tdmr_get_pamt_sz(tdmr, TDX_PS_2M);
+	tdmr->pamt_1g_size = tdmr_get_pamt_sz(tdmr, TDX_PS_1G);
+	tdmr_pamt_size = tdmr->pamt_4k_size + tdmr->pamt_2m_size + tdmr->pamt_1g_size;
 
 	/*
 	 * Allocate one chunk of physically contiguous memory for all

arch/x86/virt/vmx/tdx/tdx.c static __init int tdmr_set_up_pamt(struct tdmr_info *tdmr, · line 594

Quoted 6 lines
arch/x86/virt/vmx/tdx/tdx.c +2 -1
@@ -607,26 +590,18 @@ static __init int tdmr_set_up_pamt(struct tdmr_info *tdmr,
 	 * in overlapped TDMRs.
 	 */
 	pamt = alloc_contig_pages(tdmr_pamt_size >> PAGE_SHIFT, GFP_KERNEL,
-			nid, &node_online_map);
+				  nid, &node_online_map);
+

Looks like unrelated whitespace change. Is it intentional?

Quoted 81 lines
arch/x86/virt/vmx/tdx/tdx.c +11 -30
+	/*
+	 * tdmr->pamt_4k_base is still zero so the error
+	 * path of the caller will skip freeing the pamt.
+	 */
 	if (!pamt)
 		return -ENOMEM;
 
-	/*
-	 * Break the contiguous allocation back up into the
-	 * individual PAMTs for each page size.
-	 */
-	tdmr_pamt_base = page_to_pfn(pamt) << PAGE_SHIFT;
-	for (pgsz = TDX_PS_4K; pgsz < TDX_PS_NR; pgsz++) {
-		pamt_base[pgsz] = tdmr_pamt_base;
-		tdmr_pamt_base += pamt_size[pgsz];
-	}
-
-	tdmr->pamt_4k_base = pamt_base[TDX_PS_4K];
-	tdmr->pamt_4k_size = pamt_size[TDX_PS_4K];
-	tdmr->pamt_2m_base = pamt_base[TDX_PS_2M];
-	tdmr->pamt_2m_size = pamt_size[TDX_PS_2M];
-	tdmr->pamt_1g_base = pamt_base[TDX_PS_1G];
-	tdmr->pamt_1g_size = pamt_size[TDX_PS_1G];
+	tdmr->pamt_4k_base = page_to_phys(pamt);
+	tdmr->pamt_2m_base = tdmr->pamt_4k_base + tdmr->pamt_4k_size;
+	tdmr->pamt_1g_base = tdmr->pamt_2m_base + tdmr->pamt_2m_size;
 
 	return 0;
 }
@@ -657,10 +632,7 @@ static __init void tdmr_do_pamt_func(struct tdmr_info *tdmr,
 	tdmr_get_pamt(tdmr, &pamt_base, &pamt_size);
 
 	/* Do nothing if PAMT hasn't been allocated for this TDMR */
-	if (!pamt_size)
-		return;
-
-	if (WARN_ON_ONCE(!pamt_base))
+	if (!pamt_base)
 		return;
 
 	pamt_func(pamt_base, pamt_size);
@@ -686,14 +658,12 @@ static __init void tdmrs_free_pamt_all(struct tdmr_info_list *tdmr_list)
 
 /* Allocate and set up PAMTs for all TDMRs */
 static __init int tdmrs_set_up_pamt_all(struct tdmr_info_list *tdmr_list,
-					struct list_head *tmb_list,
-					u16 pamt_entry_size[])
+				 struct list_head *tmb_list)
 {
 	int i, ret = 0;
 
 	for (i = 0; i < tdmr_list->nr_consumed_tdmrs; i++) {
-		ret = tdmr_set_up_pamt(tdmr_entry(tdmr_list, i), tmb_list,
-				pamt_entry_size);
+		ret = tdmr_set_up_pamt(tdmr_entry(tdmr_list, i), tmb_list);
 		if (ret)
 			goto err;
 	}
@@ -970,18 +940,13 @@ static __init int construct_tdmrs(struct list_head *tmb_list,
 				  struct tdmr_info_list *tdmr_list,
 				  struct tdx_sys_info_tdmr *sysinfo_tdmr)
 {
-	u16 pamt_entry_size[TDX_PS_NR] = {
-		sysinfo_tdmr->pamt_4k_entry_size,
-		sysinfo_tdmr->pamt_2m_entry_size,
-		sysinfo_tdmr->pamt_1g_entry_size,
-	};
 	int ret;
 
 	ret = fill_out_tdmrs(tmb_list, tdmr_list);
 	if (ret)
 		return ret;
 
-	ret = tdmrs_set_up_pamt_all(tdmr_list, tmb_list, pamt_entry_size);
+	ret = tdmrs_set_up_pamt_all(tdmr_list, tmb_list);
 	if (ret)
 		return ret;
 
Signature · 1 line
2.54.0
Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
Reviewed-by on v6 1/11
#4 lore raw

Re: [PATCH v6 01/11] x86/virt/tdx: Simplify tdmr_get_pamt_sz()

In reply to Rick Edgecombe
Quoted 27 lines · Rick Edgecombe

For each memory region that the TDX module might use (called TDMR), three separate traditional PAMT allocations are needed. One for each supported page size (1GB, 2MB, 4KB). These store information on each page in the TDMR. In Linux, they are allocated out of one physically contiguous block, in order to more efficiently use some internal TDX module book keeping resources. So some simple math is needed to break the single large allocation into three smaller allocations for each page size.

There are some commonalities in the math needed to calculate the base and size for each smaller allocation, and so an effort was made to share logic across the three. Unfortunately doing this turned out unnaturally tortured, with a loop iterating over the three page sizes, only to call into a function with cases statement for each page size. In the future Dynamic PAMT will add more logic that is special to the 4KB page size, making the benefit of the math sharing even more questionable.

Three is not a very high number, so get rid of the loop and just duplicate the small calculation three times. In doing so, setup for future Dynamic PAMT changes.

Since the loop that iterates over it is gone, further simplify the code by dropping the array of intermediate size and base storage. Just store the values to their final locations. Accept the small complication of having to clear tdmr->pamt_4k_base in the error path, so that tdmr_do_pamt_func() will not try to operate on the TDMR struct when attempting to free it.

Quoted 3 lines
Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7
Reviewed-by on v6 1/11
#5 lore raw

Re: [PATCH v6 01/11] x86/virt/tdx: Simplify tdmr_get_pamt_sz()

In reply to Rick Edgecombe
Quoted 7 lines · Rick Edgecombe

Since the loop that iterates over it is gone, further simplify the code by dropping the array of intermediate size and base storage. Just store the values to their final locations.

Accept the small complication of having
to clear tdmr->pamt_4k_base in the error path, so that tdmr_do_pamt_func() will not try to operate on the TDMR struct when attempting to free it.

The clearing of tdmr->pamt_4k_base was dropped, so this section is a bit stale. Apart from this nit,

author maintainer
#6 lore raw

Re: [PATCH v6 01/11] x86/virt/tdx: Simplify tdmr_get_pamt_sz()

Quoted 11 lines · Chao Gao
Quoted 7 lines · Rick Edgecombe

Since the loop that iterates over it is gone, further simplify the code by dropping the array of intermediate size and base storage. Just store the values to their final locations.

Accept the small complication of having
to clear tdmr->pamt_4k_base in the error path, so that tdmr_do_pamt_func() will not try to operate on the TDMR struct when attempting to free it.

The clearing of tdmr->pamt_4k_base was dropped, so this section is a bit stale. Apart from this nit,

Oh, good point.

Quoted 2 lines

Thanks, and for the others.

Reviewed-by
#7 lore raw

Re: [PATCH v6 01/11] x86/virt/tdx: Simplify tdmr_get_pamt_sz()

Quoted 3 lines · Rick P
Quoted 2 lines · Chao Gao
Quoted 1 line · Rick Edgecombe

Since the loop that iterates over it is gone, further simplify the code by

Nit:
The patch is titled "Simplify tdmr_get_pamt_sz()" but the log mainly talks about removing the loop in tdmr_set_up_pamt().
So, how about renaming the patch to "Simplify setting up pamt calculation for TDMRs"?

Quoted 11 lines
Quoted 9 lines
Quoted 6 lines

dropping the array of intermediate size and base storage. Just store the values to their final locations.

Accept the small complication of having
to clear tdmr->pamt_4k_base in the error path, so that tdmr_do_pamt_func() will not try to operate on the TDMR struct when attempting to free it.

The clearing of tdmr->pamt_4k_base was dropped, so this section is a bit stale. Apart from this nit,

Oh, good point.

With those nits fixed,

author maintainer
#8 lore raw

Re: [PATCH v6 01/11] x86/virt/tdx: Simplify tdmr_get_pamt_sz()

Quoted 9 lines · Yan Zhao
Quoted 3 lines · Rick P
Quoted 2 lines · Chao Gao
Quoted 1 line · Rick Edgecombe

Since the loop that iterates over it is gone, further simplify the code by

Nit:
The patch is titled "Simplify tdmr_get_pamt_sz()" but the log mainly talks about removing the loop in tdmr_set_up_pamt().
So, how about renaming the patch to "Simplify setting up pamt calculation for TDMRs"?

Hmm, yea. I'll change it to:

x86/virt/tdx: Simplify PAMT layout calculation

Quoted 8 lines
Quoted 8 lines
Quoted 8 lines
Quoted 7 lines

dropping the array of intermediate size and base storage. Just store the values to their final locations.

Accept the small complication of having
to clear tdmr->pamt_4k_base in the error path, so that tdmr_do_pamt_func() will not try to operate on the TDMR struct when attempting to free it.

Quoted 8 lines
Quoted 4 lines
Quoted 2 lines

The clearing of tdmr->pamt_4k_base was dropped, so this section is a bit stale. Apart from this nit,

Oh, good point.

With those nits fixed,

Thanks.

#9 lore raw

Re: [PATCH v6 01/11] x86/virt/tdx: Simplify tdmr_get_pamt_sz()

In reply to Rick Edgecombe
Quoted 4 lines · Rick Edgecombe

For each memory region that the TDX module might use (called TDMR), three separate traditional PAMT allocations are needed.

One for each supported page size (1GB, 2MB, 4KB).

Missing verb in this sentence. Maybe use a '-' to merge it with the previous sentence.

Quoted 5 lines

There are some commonalities in the math needed to calculate the base and size for each smaller allocation, and so an effort was made to share logic across the three. Unfortunately doing this turned out unnaturally tortured, with a loop iterating over the three page sizes, only to call into a function with cases statement for each page size.

Did you mean "..with a case statement for each.."?

Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +0 -0
index 967482ae3c801..487f389f52f4b 100644

arch/x86/virt/vmx/tdx/tdx.c static __init int fill_out_tdmrs(struct list_head *tmb_list, · line 522

Quoted 9 lines
arch/x86/virt/vmx/tdx/tdx.c +2 -2
@@ -516,31 +516,21 @@ static __init int fill_out_tdmrs(struct list_head *tmb_list,
  * Calculate PAMT size given a TDMR and a page size.  The returned
  * PAMT size is always aligned up to 4K page boundary.
  */
-static __init unsigned long tdmr_get_pamt_sz(struct tdmr_info *tdmr, int pgsz,
-					     u16 pamt_entry_size)
+static __init unsigned long tdmr_get_pamt_sz(struct tdmr_info *tdmr, int pgsz)
 {
 	unsigned long pamt_sz, nr_pamt_entries;
+	const int tdx_pg_size_shift[] = { PAGE_SHIFT, PMD_SHIFT, PUD_SHIFT };

Both of these consts go hand-in-hand, right? I would write it as tdx_pg_size_shift[TDX_PS_NR] to make the connection obvious.

Just curious, why is TDX_PS_NR defined as (TDX_PS_1G + 1)? I don't think we are planning to add TDX_PS_256G anytime soon. But, should TDX_PS_4K..TDX_PS_NR be an enum?

Quoted 6 lines
arch/x86/virt/vmx/tdx/tdx.c +5 -0
+	const u16 pamt_entry_size[TDX_PS_NR] = {
+		tdx_sysinfo.tdmr.pamt_4k_entry_size,
+		tdx_sysinfo.tdmr.pamt_2m_entry_size,
+		tdx_sysinfo.tdmr.pamt_1g_entry_size,
+	};
 
author maintainer
#10 lore raw

Re: [PATCH v6 01/11] x86/virt/tdx: Simplify tdmr_get_pamt_sz()

Thanks for the review!

Quoted 7 lines · Sohil Mehta
Quoted 4 lines · Rick Edgecombe

For each memory region that the TDX module might use (called TDMR), three separate traditional PAMT allocations are needed.

One for each supported page size (1GB, 2MB, 4KB).

Missing verb in this sentence. Maybe use a '-' to merge it with the previous sentence.

Hmm, yea I'll update it to:

There is one for each supported page size (1GB, 2MB, 4KB).

Quoted 9 lines
Quoted 7 lines

There are some commonalities in the math needed to calculate the base and size for each smaller allocation, and so an effort was made to share logic across the three. Unfortunately doing this turned out unnaturally tortured, with a loop iterating over the three page sizes, only to call into a function with cases statement for each page size.

Did you mean "..with a case statement for each.."?

yep.

Quoted 12 lines
Quoted 12 lines
arch/x86/virt/vmx/tdx/tdx.c +0 -1
index 967482ae3c801..487f389f52f4b 100644
@@ -516,31 +516,21 @@ static __init int fill_out_tdmrs(struct list_head *tmb_list,
    * Calculate PAMT size given a TDMR and a page size.  The returned
    * PAMT size is always aligned up to 4K page boundary.
    */
-static __init unsigned long tdmr_get_pamt_sz(struct tdmr_info *tdmr, int pgsz,
Quoted 8 lines

arch/x86/virt/vmx/tdx/tdx.c static __init int fill_out_tdmrs(struct list_head *tmb_list, · line 522

Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +2 -1
-					     u16 pamt_entry_size)
+static __init unsigned long tdmr_get_pamt_sz(struct tdmr_info *tdmr, int pgsz)
   {
   	unsigned long pamt_sz, nr_pamt_entries;
+	const int tdx_pg_size_shift[] = { PAGE_SHIFT, PMD_SHIFT, PUD_SHIFT };

Both of these consts go hand-in-hand, right? I would write it as tdx_pg_size_shift[TDX_PS_NR] to make the connection obvious.

Yea that seems reasonable.

Quoted 4 lines

Just curious, why is TDX_PS_NR defined as (TDX_PS_1G + 1)? I don't think we are planning to add TDX_PS_256G anytime soon. But, should TDX_PS_4K..TDX_PS_NR be an enum?

Yea probably. The point of this patch is to improve the code such the following patch can not make it worse. So I'd think it's best not to add extra cleanups to it. I'll add this to the list. But we probably have more pressing cleanups.

author maintainer
#11 lore raw

PATCH v6 2/11 x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

In reply to Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The TDX Physical Address Metadata Table (PAMT) holds data about the physical memory used by TDX, and must be allocated by the kernel during TDX module initialization.

The exact size of the required PAMT memory is determined by the TDX module and may vary between TDX module versions. Currently it is approximately 0.4% of the system memory. This is a significant commitment, especially if it is not known upfront whether the machine will run any TDX guests.

Each memory region that the TDX module might use needs three separate PAMT allocations. One for each supported page size (1GB, 2MB, 4KB). The TDX module supports a new feature designed to reduce PAMT overhead called Dynamic PAMT. At a high level, Dynamic PAMT still has the 1GB and 2MB levels allocated on TDX module initialization, but the 4KB level is allocated dynamically during runtime.

However, in the details, Dynamic PAMT still needs some smaller per 4KB page scoped data (currently it is 1 bit per page). The TDX module exposes the number of bits as a separate piece of metadata than the 4KB static allocation for regular PAMT. Although the size is enumerated differently, it is handed to the TDX module in the same way the 4KB page size PAMT allocation is for regular, non-dynamic PAMT.

Begin to implement Dynamic PAMT in the kernel by reading the bits-per-page needed for Dynamic PAMT. Calculate the size needed for the bitmap, and use it instead of the 4KB size determined for normal PAMT, in the case of Dynamic PAMT.

Unlike the existing metadata reading code, this code is not generated by a script. So adjust the comment to be more generic. Also, start to adopt a more normal kernel code style without the tenary statements and if conditionals assignments that the auto generated code has.

---
v6:
- Improve comment (Binbin)
- Log tweaks
- Mark tdmr_get_pamt_bitmap_sz() __init in response to upstream changes
- Switch to more normal kernel code style, even though it differs from the existing auto generated code.

---
 arch/x86/include/asm/tdx.h                  |  5 +++++
 arch/x86/include/asm/tdx_global_metadata.h  |  3 +++
 arch/x86/virt/vmx/tdx/tdx.c                 | 19 ++++++++++++++++++-
 arch/x86/virt/vmx/tdx/tdx_global_metadata.c | 21 ++++++++++++++++++++-
 4 files changed, 46 insertions(+), 2 deletions(-)
arch/x86/include/asm/tdx.h +5 -0
index 503f9a3f46d61..82dc27aecf297 100644
@@ -149,6 +149,11 @@ static __always_inline u64 sc_retry(sc_func_t func, u64 fn,
 const char *tdx_dump_mce_info(struct mce *m);
 const struct tdx_sys_info *tdx_get_sysinfo(void);
 
+static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)
+{
+	return false; /* To be enabled when kernel is ready */
+}
+
 int tdx_guest_keyid_alloc(void);
 u32 tdx_get_nr_guest_keyids(void);
 void tdx_guest_keyid_free(unsigned int keyid);
arch/x86/include/asm/tdx_global_metadata.h +3 -0
index 40689c8dc67eb..88040ddb51af4 100644
@@ -21,6 +21,9 @@ struct tdx_sys_info_tdmr {
 	u16 pamt_4k_entry_size;
 	u16 pamt_2m_entry_size;
 	u16 pamt_1g_entry_size;
+
+	/* Optional metadata, if Dynamic PAMT is supported */
+	u8  pamt_page_bitmap_entry_bits;
 };
 
 struct tdx_sys_info_td_ctrl {
arch/x86/virt/vmx/tdx/tdx.c +18 -1
index 487f389f52f4b..9ebd192cb5c17 100644
@@ -512,6 +512,18 @@ static __init int fill_out_tdmrs(struct list_head *tmb_list,
 	return 0;
 }
 
+static __init unsigned long tdmr_get_pamt_bitmap_sz(struct tdmr_info *tdmr)
+{
+	unsigned long pamt_sz, nr_pamt_entries;
+	int bits_per_entry;
+
+	bits_per_entry = tdx_sysinfo.tdmr.pamt_page_bitmap_entry_bits;
+	nr_pamt_entries = tdmr->size >> PAGE_SHIFT;
+	pamt_sz = DIV_ROUND_UP(nr_pamt_entries * bits_per_entry, BITS_PER_BYTE);
+
+	return PAGE_ALIGN(pamt_sz);
+}
+
 /*
  * Calculate PAMT size given a TDMR and a page size.  The returned
  * PAMT size is always aligned up to 4K page boundary.
@@ -579,7 +591,12 @@ static __init int tdmr_set_up_pamt(struct tdmr_info *tdmr,
 	 * Calculate the PAMT size for each TDX supported page size
 	 * and the total PAMT size.
 	 */
-	tdmr->pamt_4k_size = tdmr_get_pamt_sz(tdmr, TDX_PS_4K);
+	if (tdx_supports_dynamic_pamt(&tdx_sysinfo)) {
+		/* With Dynamic PAMT, PAMT_4K is replaced with a bitmap */
+		tdmr->pamt_4k_size = tdmr_get_pamt_bitmap_sz(tdmr);
+	} else {
+		tdmr->pamt_4k_size = tdmr_get_pamt_sz(tdmr, TDX_PS_4K);
+	}
 	tdmr->pamt_2m_size = tdmr_get_pamt_sz(tdmr, TDX_PS_2M);
 	tdmr->pamt_1g_size = tdmr_get_pamt_sz(tdmr, TDX_PS_1G);
 	tdmr_pamt_size = tdmr->pamt_4k_size + tdmr->pamt_2m_size + tdmr->pamt_1g_size;
arch/x86/virt/vmx/tdx/tdx_global_metadata.c +20 -1
index c7db393a9cfb1..7e8e913463be1 100644
@@ -1,6 +1,6 @@
 // SPDX-License-Identifier: GPL-2.0
 /*
- * Automatically generated functions to read TDX global metadata.
+ * Functions to read TDX global metadata.
  *
  * This file doesn't compile on its own as it lacks of inclusion
  * of SEAMCALL wrapper primitive which reads global metadata.
@@ -33,6 +33,18 @@ static __init int get_tdx_sys_info_features(struct tdx_sys_info_features *sysinf
 	return ret;
 }
 
+static __init int get_tdx_sys_info_tdmr_dpamt(struct tdx_sys_info_tdmr *sysinfo_tdmr)
+{
+	int ret;
+	u64 val;
+
+	ret = read_sys_metadata_field(0x9100000100000013, &val);
+	if (!ret)
+		sysinfo_tdmr->pamt_page_bitmap_entry_bits = val;
+
+	return ret;
+}
+
 static __init int get_tdx_sys_info_tdmr(struct tdx_sys_info_tdmr *sysinfo_tdmr)
 {
 	int ret = 0;
@@ -116,5 +128,12 @@ static __init int get_tdx_sys_info(struct tdx_sys_info *sysinfo)
 	ret = ret ?: get_tdx_sys_info_td_ctrl(&sysinfo->td_ctrl);
 	ret = ret ?: get_tdx_sys_info_td_conf(&sysinfo->td_conf);
 
+	/*
+	 * Don't treat a module that doesn't support Dynamic PAMT
+	 * as a failure. Only read the metadata optionally.
+	 */
+	if (!ret && tdx_supports_dynamic_pamt(sysinfo))
+		ret = get_tdx_sys_info_tdmr_dpamt(&sysinfo->tdmr);
+
 	return ret;
 }
Signature · 1 line
2.54.0
maintainer
#12 lore raw

Re: [PATCH v6 02/11] x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

Quoted 4 lines · Rick Edgecombe
arch/x86/virt/vmx/tdx/tdx.c +0 -0
@@ -579,7 +591,12 @@ static __init int tdmr_set_up_pamt(struct tdmr_info *tdmr,
 	 * Calculate the PAMT size for each TDX supported page size
 	 * and the total PAMT size.
 	 */

arch/x86/virt/vmx/tdx/tdx.c static __init int tdmr_set_up_pamt(struct tdmr_info *tdmr, · line 602

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +6 -1
-	tdmr->pamt_4k_size = tdmr_get_pamt_sz(tdmr, TDX_PS_4K);
+	if (tdx_supports_dynamic_pamt(&tdx_sysinfo)) {
+		/* With Dynamic PAMT, PAMT_4K is replaced with a bitmap */
+		tdmr->pamt_4k_size = tdmr_get_pamt_bitmap_sz(tdmr);
+	} else {
+		tdmr->pamt_4k_size = tdmr_get_pamt_sz(tdmr, TDX_PS_4K);
+	}
 	tdmr->pamt_2m_size = tdmr_get_pamt_sz(tdmr, TDX_PS_2M);
 	tdmr->pamt_1g_size = tdmr_get_pamt_sz(tdmr, TDX_PS_1G);
 	tdmr_pamt_size = tdmr->pamt_4k_size + tdmr->pamt_2m_size + tdmr->pamt_1g_size;

Maybe it would more readable if we reverse the size order:

	/*
	 * Calculate the PAMT size for each TDX supported page size
	 * and the total PAMT size.
	 */

tdmr->pamt_1g_size = tdmr_get_pamt_sz(tdmr, TDX_PS_1G); tdmr->pamt_2m_size = tdmr_get_pamt_sz(tdmr, TDX_PS_2M);

	if (tdx_supports_dynamic_pamt(&tdx_sysinfo)) {
		/* With Dynamic PAMT, PAMT_4K is replaced with a bitmap */
		tdmr->pamt_4k_size = tdmr_get_pamt_bitmap_sz(tdmr);
	} else {
		tdmr->pamt_4k_size = tdmr_get_pamt_sz(tdmr, TDX_PS_4K);
	}
  	tdmr_pamt_size = tdmr->pamt_1g_size + tdmr->pamt_2m_size + tdmr->pamt_4k_size;

It allows split it into logical blocks while keeping the comment attached.

Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
author maintainer
#13 lore raw

Re: [PATCH v6 02/11] x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

Quoted 32 lines · Kiryl Shutsemau
Quoted 4 lines · Rick Edgecombe
arch/x86/virt/vmx/tdx/tdx.c +0 -0
@@ -579,7 +591,12 @@ static __init int tdmr_set_up_pamt(struct tdmr_info *tdmr,
   	 * Calculate the PAMT size for each TDX supported page size
   	 * and the total PAMT size.
   	 */

arch/x86/virt/vmx/tdx/tdx.c static __init int tdmr_set_up_pamt(struct tdmr_info *tdmr, · line 602

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +6 -1
-	tdmr->pamt_4k_size = tdmr_get_pamt_sz(tdmr, TDX_PS_4K);
+	if (tdx_supports_dynamic_pamt(&tdx_sysinfo)) {
+		/* With Dynamic PAMT, PAMT_4K is replaced with a bitmap */
+		tdmr->pamt_4k_size = tdmr_get_pamt_bitmap_sz(tdmr);
+	} else {
+		tdmr->pamt_4k_size = tdmr_get_pamt_sz(tdmr, TDX_PS_4K);
+	}
   	tdmr->pamt_2m_size = tdmr_get_pamt_sz(tdmr, TDX_PS_2M);
   	tdmr->pamt_1g_size = tdmr_get_pamt_sz(tdmr, TDX_PS_1G);
   	tdmr_pamt_size = tdmr->pamt_4k_size + tdmr->pamt_2m_size + tdmr->pamt_1g_size;

Maybe it would more readable if we reverse the size order:

	/*
	 * Calculate the PAMT size for each TDX supported page size
	 * and the total PAMT size.
	 */

   tdmr->pamt_1g_size = tdmr_get_pamt_sz(tdmr, TDX_PS_1G); tdmr->pamt_2m_size = tdmr_get_pamt_sz(tdmr, TDX_PS_2M);

	if (tdx_supports_dynamic_pamt(&tdx_sysinfo)) {
		/* With Dynamic PAMT, PAMT_4K is replaced with a bitmap */
		tdmr->pamt_4k_size = tdmr_get_pamt_bitmap_sz(tdmr);
	} else {
		tdmr->pamt_4k_size = tdmr_get_pamt_sz(tdmr, TDX_PS_4K);
	}
Quoted 3 lines

   tdmr_pamt_size = tdmr->pamt_1g_size + tdmr->pamt_2m_size + tdmr->pamt_4k_size;

It allows split it into logical blocks while keeping the comment attached.

Uhh, yea. I can see it a little. I'll swap it.

Reviewed-by on v6 2/11
#14 lore raw

Re: [PATCH v6 02/11] x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

In reply to Rick Edgecombe
Quoted 36 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The TDX Physical Address Metadata Table (PAMT) holds data about the physical memory used by TDX, and must be allocated by the kernel during TDX module initialization.

The exact size of the required PAMT memory is determined by the TDX module and may vary between TDX module versions. Currently it is approximately 0.4% of the system memory. This is a significant commitment, especially if it is not known upfront whether the machine will run any TDX guests.

Each memory region that the TDX module might use needs three separate PAMT allocations. One for each supported page size (1GB, 2MB, 4KB). The TDX module supports a new feature designed to reduce PAMT overhead called Dynamic PAMT. At a high level, Dynamic PAMT still has the 1GB and 2MB levels allocated on TDX module initialization, but the 4KB level is allocated dynamically during runtime.

However, in the details, Dynamic PAMT still needs some smaller per 4KB page scoped data (currently it is 1 bit per page). The TDX module exposes the number of bits as a separate piece of metadata than the 4KB static allocation for regular PAMT. Although the size is enumerated differently, it is handed to the TDX module in the same way the 4KB page size PAMT allocation is for regular, non-dynamic PAMT.

Begin to implement Dynamic PAMT in the kernel by reading the bits-per-page needed for Dynamic PAMT. Calculate the size needed for the bitmap, and use it instead of the 4KB size determined for normal PAMT, in the case of Dynamic PAMT.

Unlike the existing metadata reading code, this code is not generated by a script. So adjust the comment to be more generic. Also, start to adopt a more normal kernel code style without the tenary statements and if conditionals assignments that the auto generated code has.

Quoted 5 lines

Kirill's comment make sense to me.

Reviewed-by on v6 2/11
#15 lore raw

Re: [PATCH v6 02/11] x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

In reply to Rick Edgecombe
Quoted 35 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The TDX Physical Address Metadata Table (PAMT) holds data about the physical memory used by TDX, and must be allocated by the kernel during TDX module initialization.

The exact size of the required PAMT memory is determined by the TDX module and may vary between TDX module versions. Currently it is approximately 0.4% of the system memory. This is a significant commitment, especially if it is not known upfront whether the machine will run any TDX guests.

Each memory region that the TDX module might use needs three separate PAMT allocations. One for each supported page size (1GB, 2MB, 4KB). The TDX module supports a new feature designed to reduce PAMT overhead called Dynamic PAMT. At a high level, Dynamic PAMT still has the 1GB and 2MB levels allocated on TDX module initialization, but the 4KB level is allocated dynamically during runtime.

However, in the details, Dynamic PAMT still needs some smaller per 4KB page scoped data (currently it is 1 bit per page). The TDX module exposes the number of bits as a separate piece of metadata than the 4KB static allocation for regular PAMT. Although the size is enumerated differently, it is handed to the TDX module in the same way the 4KB page size PAMT allocation is for regular, non-dynamic PAMT.

Begin to implement Dynamic PAMT in the kernel by reading the bits-per-page needed for Dynamic PAMT. Calculate the size needed for the bitmap, and use it instead of the 4KB size determined for normal PAMT, in the case of Dynamic PAMT.

Unlike the existing metadata reading code, this code is not generated by a script. So adjust the comment to be more generic. Also, start to adopt a more normal kernel code style without the tenary statements and if conditionals assignments that the auto generated code has.

Quoted 5 lines
Reviewed-by on v6 2/11
#16 lore raw

Re: [PATCH v6 02/11] x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

In reply to Rick Edgecombe

arch/x86/include/asm/tdx.h static __always_inline u64 sc_retry(sc_func_t func, u64 fn, · line 156

Quoted 5 lines · Rick Edgecombe
arch/x86/include/asm/tdx.h +5 -0
+static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)
+{
+	return false; /* To be enabled when kernel is ready */
+}
+

Nit:
Would the following style be better, though the comment will soon be removed?

static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)

{
	 /* To be enabled when kernel is ready */
	return false;
}
author maintainer
#17 lore raw

Re: [PATCH v6 02/11] x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

Quoted 9 lines · Yan Zhao

arch/x86/include/asm/tdx.h static __always_inline u64 sc_retry(sc_func_t func, u64 fn, · line 156

Quoted 5 lines · Rick Edgecombe
arch/x86/include/asm/tdx.h +5 -0
+static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)
+{
+	return false; /* To be enabled when kernel is ready */
+}
+

Nit:
Would the following style be better, though the comment will soon be removed?

Quoted 7 lines

static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)

{
	 /* To be enabled when kernel is ready */
	return false;
}

Sure.

#18 lore raw

Re: [PATCH v6 02/11] x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

In reply to Rick Edgecombe
Quoted 11 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The TDX Physical Address Metadata Table (PAMT) holds data about the physical memory used by TDX, and must be allocated by the kernel during TDX module initialization.

The exact size of the required PAMT memory is determined by the TDX module and may vary between TDX module versions. Currently it is approximately 0.4% of the system memory. This is a significant commitment, especially if it is not known upfront whether the machine will run any TDX guests.

Quoted 6 lines

Each memory region that the TDX module might use needs three separate PAMT allocations. One for each supported page size (1GB, 2MB, 4KB). The TDX module supports a new feature designed to reduce PAMT overhead called Dynamic PAMT. At a high level, Dynamic PAMT still has the 1GB and 2MB levels allocated on TDX module initialization, but the 4KB level is allocated dynamically during runtime.

The last statement is slightly confusing to me. Is it trying to say that the "dynamic" part is only applicable to 4KB allocations?

Quoted 8 lines

However, in the details, Dynamic PAMT still needs some smaller per 4KB page scoped data (currently it is 1 bit per page). The TDX module exposes the number of bits as a separate piece of metadata than the 4KB static allocation for regular PAMT. Although the size is enumerated differently, it is handed to the TDX module in the same way the 4KB page size PAMT allocation is for regular, non-dynamic PAMT.

Quoted 7 lines

Begin to implement Dynamic PAMT in the kernel by reading the bits-per-page needed for Dynamic PAMT. Calculate the size needed for the bitmap, and use it instead of the 4KB size determined for normal PAMT, in the case of Dynamic PAMT.

Unlike the existing metadata reading code, this code is not generated by a script.

It might be useful to say that this file was auto-generated in the past but going forward it is going to be manually updated.

Quoted 2 lines

So adjust the comment to be more generic. Also, start to adopt a more normal kernel code style without the tenary statements and if

s/a more/
s/tenary/ternary

Quoted 4 lines

conditionals assignments that the auto generated code has.

Assisted-by Sashiko:claude-opus-4-6

The review tags goes after the SOBs.

Quoted 10 lines

---

arch/x86/include/asm/tdx.h +0 -0
index 503f9a3f46d61..82dc27aecf297 100644

arch/x86/include/asm/tdx.h static __always_inline u64 sc_retry(sc_func_t func, u64 fn, · line 154

Quoted 6 lines
arch/x86/include/asm/tdx.h +3 -0
@@ -149,6 +149,11 @@ static __always_inline u64 sc_retry(sc_func_t func, u64 fn,
 const char *tdx_dump_mce_info(struct mce *m);
 const struct tdx_sys_info *tdx_get_sysinfo(void);
 
+static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)
+{
+	return false; /* To be enabled when kernel is ready */

I would avoid the tail comment even if it is temporary.

Quoted 9 lines
arch/x86/include/asm/tdx.h +2 -0
+}
+
 int tdx_guest_keyid_alloc(void);
 u32 tdx_get_nr_guest_keyids(void);
 void tdx_guest_keyid_free(unsigned int keyid);

arch/x86/include/asm/tdx.h static __init int get_tdx_sys_info_features(struct tdx_sys_info_features *sysinf · line 41

Quoted 9 lines
arch/x86/include/asm/tdx.h +6 -0
@@ -33,6 +33,18 @@ static __init int get_tdx_sys_info_features(struct tdx_sys_info_features *sysinf
 	return ret;
 }
 
+static __init int get_tdx_sys_info_tdmr_dpamt(struct tdx_sys_info_tdmr *sysinfo_tdmr)
+{
+	int ret;
+	u64 val;
+
+	ret = read_sys_metadata_field(0x9100000100000013, &val);

Should this be a #define now that the file is being manually updated? Or is the plan to do it all together? A #define would make it easier to read this patch.

Quoted 10 lines
arch/x86/include/asm/tdx.h +6 -0
+	if (!ret)
+		sysinfo_tdmr->pamt_page_bitmap_entry_bits = val;
+
+	return ret;
+}
+
 static __init int get_tdx_sys_info_tdmr(struct tdx_sys_info_tdmr *sysinfo_tdmr)
 {
 	int ret = 0;

arch/x86/include/asm/tdx.h static __init int get_tdx_sys_info(struct tdx_sys_info *sysinfo) · line 136

Quoted 9 lines
arch/x86/include/asm/tdx.h +6 -0
@@ -116,5 +128,12 @@ static __init int get_tdx_sys_info(struct tdx_sys_info *sysinfo)
 	ret = ret ?: get_tdx_sys_info_td_ctrl(&sysinfo->td_ctrl);
 	ret = ret ?: get_tdx_sys_info_td_conf(&sysinfo->td_conf);
 
+	/*
+	 * Don't treat a module that doesn't support Dynamic PAMT
+	 * as a failure. Only read the metadata optionally.
+	 */
+	if (!ret && tdx_supports_dynamic_pamt(sysinfo))
+		ret = get_tdx_sys_info_tdmr_dpamt(&sysinfo->tdmr);

There is a need for the comment because it combines two checks:

1) Did any of the previous stages fail?
2) Does the TDX module support Dynamic PAMT?

Should these be separated for readability and to follow the typical kernel style?

	if (ret)
		return ret;

	if (tdx_supports_dynamic_pamt(sysinfo))
		ret = get_tdx_sys_info_tdmr_dpamt(&sysinfo->tdmr);

	return ret;

I think you can avoid the comment altogether in that case.

Quoted 3 lines
arch/x86/include/asm/tdx.h +1 -0
+
 	return ret;
 }
author maintainer
#19 lore raw

Re: [PATCH v6 02/11] x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

Quoted 19 lines · Sohil Mehta
Quoted 11 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The TDX Physical Address Metadata Table (PAMT) holds data about the physical memory used by TDX, and must be allocated by the kernel during TDX module initialization.

The exact size of the required PAMT memory is determined by the TDX module and may vary between TDX module versions. Currently it is approximately 0.4% of the system memory. This is a significant commitment, especially if it is not known upfront whether the machine will run any TDX guests.

Quoted 6 lines

Each memory region that the TDX module might use needs three separate PAMT allocations. One for each supported page size (1GB, 2MB, 4KB). The TDX module supports a new feature designed to reduce PAMT overhead called Dynamic PAMT. At a high level, Dynamic PAMT still has the 1GB and 2MB levels allocated on TDX module initialization, but the 4KB level is allocated dynamically during runtime.

Quoted 2 lines

The last statement is slightly confusing to me. Is it trying to say that the "dynamic" part is only applicable to 4KB allocations?

Yea. Can you explain more about what is confusing? I guess this is more compact:

Under Dynamic PAMT the 4KB level is allocated dynamically during runtime, while the 1GB and 2MB levels remain allocated on TDX module initialization.

Quoted 19 lines
Quoted 10 lines

However, in the details, Dynamic PAMT still needs some smaller per 4KB page scoped data (currently it is 1 bit per page). The TDX module exposes the number of bits as a separate piece of metadata than the 4KB static allocation for regular PAMT. Although the size is enumerated differently, it is handed to the TDX module in the same way the 4KB page size PAMT allocation is for regular, non-dynamic PAMT.

Quoted 7 lines

Begin to implement Dynamic PAMT in the kernel by reading the bits-per-page needed for Dynamic PAMT. Calculate the size needed for the bitmap, and use it instead of the 4KB size determined for normal PAMT, in the case of Dynamic PAMT.

Unlike the existing metadata reading code, this code is not generated by a script.

Quoted 8 lines

It might be useful to say that this file was auto-generated in the past but going forward it is going to be manually updated.

Quoted 2 lines

So adjust the comment to be more generic. Also, start to adopt a more normal kernel code style without the tenary statements and if

s/a more/
s/tenary/ternary

How about this?

The existing metadata reading code was generated by a script, but the current plan is to stop generating this code, as the script has continued to need adjustments. So add manually written code and adjust the comment about it being autogenerated to be more generic. Start to adopt a more normal kernel code style without the ternary statements and if conditionals assignments that the auto generated code has.

Quoted 8 lines
Quoted 6 lines

conditionals assignments that the auto generated code has.

Assisted-by Sashiko:claude-opus-4-6

The review tags goes after the SOBs.

Yep, I have been fixing those across the series.

Quoted 14 lines
Quoted 14 lines

---

arch/x86/include/asm/tdx.h +0 -0
index 503f9a3f46d61..82dc27aecf297 100644
@@ -149,6 +149,11 @@ static __always_inline u64 sc_retry(sc_func_t func, u64 fn,
 const char *tdx_dump_mce_info(struct mce *m);
 const struct tdx_sys_info *tdx_get_sysinfo(void);
 
Quoted 5 lines

arch/x86/include/asm/tdx.h static __always_inline u64 sc_retry(sc_func_t func, u64 fn, · line 154

Quoted 3 lines
arch/x86/include/asm/tdx.h +3 -0
+static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)
+{
+	return false; /* To be enabled when kernel is ready */

I would avoid the tail comment even if it is temporary.

Yep, Yan commented the same thing.

Quoted 13 lines
Quoted 13 lines
arch/x86/include/asm/tdx.h +2 -0
+}
+
 int tdx_guest_keyid_alloc(void);
 u32 tdx_get_nr_guest_keyids(void);
 void tdx_guest_keyid_free(unsigned int keyid);
@@ -33,6 +33,18 @@ static __init int get_tdx_sys_info_features(struct tdx_sys_info_features *sysinf
 	return ret;
 }
 
Quoted 10 lines

arch/x86/include/asm/tdx.h static __init int get_tdx_sys_info_features(struct tdx_sys_info_features *sysinf · line 41

Quoted 6 lines
arch/x86/include/asm/tdx.h +6 -0
+static __init int get_tdx_sys_info_tdmr_dpamt(struct tdx_sys_info_tdmr *sysinfo_tdmr)
+{
+	int ret;
+	u64 val;
+
+	ret = read_sys_metadata_field(0x9100000100000013, &val);

Should this be a #define now that the file is being manually updated? Or is the plan to do it all together? A #define would make it easier to read this patch.

I think switching to defines would overlap too much into the ultimate metadata reading solution that gets discussed. Chao is currently working on a series for this, so I'd think to leave that part for later.

Quoted 37 lines
Quoted 11 lines
arch/x86/include/asm/tdx.h +6 -0
+	if (!ret)
+		sysinfo_tdmr->pamt_page_bitmap_entry_bits = val;
+
+	return ret;
+}
+
 static __init int get_tdx_sys_info_tdmr(struct tdx_sys_info_tdmr *sysinfo_tdmr)
 {
 	int ret = 0;

arch/x86/include/asm/tdx.h static __init int get_tdx_sys_info(struct tdx_sys_info *sysinfo) · line 136

Quoted 9 lines
arch/x86/include/asm/tdx.h +6 -0
@@ -116,5 +128,12 @@ static __init int get_tdx_sys_info(struct tdx_sys_info *sysinfo)
 	ret = ret ?: get_tdx_sys_info_td_ctrl(&sysinfo->td_ctrl);
 	ret = ret ?: get_tdx_sys_info_td_conf(&sysinfo->td_conf);
 
+	/*
+	 * Don't treat a module that doesn't support Dynamic PAMT
+	 * as a failure. Only read the metadata optionally.
+	 */
+	if (!ret && tdx_supports_dynamic_pamt(sysinfo))
+		ret = get_tdx_sys_info_tdmr_dpamt(&sysinfo->tdmr);

There is a need for the comment because it combines two checks:

1) Did any of the previous stages fail?
2) Does the TDX module support Dynamic PAMT?

Should these be separated for readability and to follow the typical kernel style?

	if (ret)
		return ret;

	if (tdx_supports_dynamic_pamt(sysinfo))
		ret = get_tdx_sys_info_tdmr_dpamt(&sysinfo->tdmr);

	return ret;
Quoted 1 line

I think you can avoid the comment altogether in that case.

I don't think it removes the need for a comment. The point is if tdx_supports_dynamic_pamt() is not supported. The comment should be more about "why", than what the code does, right?

How about:

	if (ret)
		return ret;

	/*
	 * The kernel supports using TDX without Dynamic PAMT, so
	 * avoid reporting failure if it's not supported.
	 */
	if (tdx_supports_dynamic_pamt(sysinfo))
		ret = get_tdx_sys_info_tdmr_dpamt(&sysinfo->tdmr);

	return ret;
Quoted 5 lines
Quoted 4 lines
arch/x86/include/asm/tdx.h +1 -0
+
 	return ret;
 }
author maintainer
#20 lore raw

Re: [PATCH v6 02/11] x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

Quoted 8 lines · Rick Edgecombe
Quoted 1 line

I think you can avoid the comment altogether in that case.

I don't think it removes the need for a comment. The point is if tdx_supports_dynamic_pamt() is not supported. The comment should be more about "why", than what the code does, right?

How about:

Quoted 11 lines
	if (ret)
		return ret;

	/*
	 * The kernel supports using TDX without Dynamic PAMT, so
	 * avoid reporting failure if it's not supported.
	 */
	if (tdx_supports_dynamic_pamt(sysinfo))
		ret = get_tdx_sys_info_tdmr_dpamt(&sysinfo->tdmr);

	return ret;

Actually this really stands out from the autogenerated code now, how about:

	/*
	 * The kernel supports using TDX without Dynamic PAMT, so
	 * avoid reporting failure if it's not supported.
	 */
	if (!ret && tdx_supports_dynamic_pamt(sysinfo))
		ret = get_tdx_sys_info_tdmr_dpamt(&sysinfo->tdmr);

It why-ifys the comment more, but only gently moves from the auto-generated patterns.

#21 lore raw

Re: [PATCH v6 02/11] x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

Quoted 19 lines · Rick P
Quoted 18 lines · Rick Edgecombe
Quoted 1 line

I think you can avoid the comment altogether in that case.

I don't think it removes the need for a comment. The point is if tdx_supports_dynamic_pamt() is not supported. The comment should be more about "why", than what the code does, right?

How about:

	if (ret)
		return ret;

	/*
	 * The kernel supports using TDX without Dynamic PAMT, so
	 * avoid reporting failure if it's not supported.
	 */
	if (tdx_supports_dynamic_pamt(sysinfo))
		ret = get_tdx_sys_info_tdmr_dpamt(&sysinfo->tdmr);
Quoted 4 lines
Quoted 1 line
	return ret;

Actually this really stands out from the autogenerated code now, how about:

I thought that's a good thing. Eventually, we want to make this file conform to the standard kernel style, right? The autogenerated pattern in this file to "check any previous failure" before doing the current step is odd.

Quoted 9 lines
	/*
	 * The kernel supports using TDX without Dynamic PAMT, so
	 * avoid reporting failure if it's not supported.
	 */
	if (!ret && tdx_supports_dynamic_pamt(sysinfo))
		ret = get_tdx_sys_info_tdmr_dpamt(&sysinfo->tdmr);

It why-ifys the comment more, but only gently moves from the auto-generated patterns.

Sure, that's fine if you want to continue the style in this file.

BTW, do you also want to clarify why we fail the init if get_tdx_sys_info_tdmr_dpamt() fails?

Is it because:

If reading the DPAMT metadata fails, something is really wrong with the TDX module. It is better to fail the initialization in that case.

author maintainer
#22 lore raw

Re: [PATCH v6 02/11] x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

Quoted 5 lines · Sohil Mehta
Quoted 2 lines

It why-ifys the comment more, but only gently moves from the auto-generated patterns.

Sure, that's fine if you want to continue the style in this file.

Quoted 7 lines

BTW, do you also want to clarify why we fail the init if get_tdx_sys_info_tdmr_dpamt() fails?

Is it because:

If reading the DPAMT metadata fails, something is really wrong with the TDX module. It is better to fail the initialization in that case.

The reason why it doesn't try to handle it by falling back to normal PAMT is just to reduce complexity. It's not to protect the kernel or anything. Supporting broken TDX modules is just not worth the extra possible states we'd have to consider.

I tweaked it like this, seem reasonable?

/*
* The kernel supports using TDX without Dynamic PAMT, so
* avoid reporting failure if it's not supported. Don't try
* to support buggy TDX modules that advertise dynamic PAMT
* but don't expose the metadata.
*/

#23 lore raw

Re: [PATCH v6 02/11] x86/virt/tdx: Allocate page bitmap for Dynamic PAMT

Quoted 8 lines · Rick P

I tweaked it like this, seem reasonable?

/*
* The kernel supports using TDX without Dynamic PAMT, so
* avoid reporting failure if it's not supported. Don't try
* to support buggy TDX modules that advertise dynamic PAMT
* but don't expose the metadata.
*/

Looks good.

author maintainer
#24 lore raw

PATCH v6 3/11 x86/virt/tdx: Add tdx_alloc/free_control_page() helpers

In reply to Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Add helpers to use when allocating or preparing pages that are handed to the TDX-Module for use as control/S-EPT pages, and thus need Dynamic PAMT adjustments.

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So for pages that TDX will use as 2MB physically contiguous pages, Dynamic PAMT backing is not needed.

KVM will need to hand pages to the TDX module that it will use at 4KB granularity. So these pages will need Dynamic PAMT backing added before they are used by the TDX module, and removed afterwards.

Add tdx_alloc_control_page() and tdx_free_control_page() to handle both page allocation and Dynamic PAMT installation. Make them behave like normal alloc/free functions where allocation can fail in the case of no memory, but free (with any necessary Dynamic PAMT release) always succeeds. Do this so they can support the existing TDX flows that require teardowns to succeed.

Also create tdx_pamt_get/put() to handle installing Dynamic PAMT 4KB backing for pages that are already allocated (such as KVM's use of S-EPT page tables or guest private memory). Have them take a pfn instead of a struct page, as future changes will want to use these helpers for guest pages which are tracked by PFN.

Don't CLFLUSH the Dynamic PAMT pages handed to the TDX module, as is done for some other SEAMCALLs, as the TDX docs specify that this is only needed on "TD private memory or TD control structure page".

Since these allocations will be easily user triggerable, account the memory.

Leave logic to handle concurrency issues for future changes.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7 Sashiko:claude-opus-4-6

---
v6:
The major change was to split out the concurrency stuff into a future patch. It makes it easier to explain in the log. This one is the basic functionality. Then the simple version of the concurrency and why in the next patch. Also, to get rid of the dynamically sized DPAMT backing support which was not based on a formal spec.

Details:
- Split out concurrency stuff into next patch because the log was too long
- Switch to fixed size pamt page arrays (Nikolay)
- Rename tdx_alloc_page()/tdx_free_page() to tdx_alloc_control_page()/ tdx_free_control_page() to reflect control/S-EPT purpose (Sean)
- Take gfp from the caller in tdx_alloc_control_page() (Sean)
- Narrow external API: make tdx_pamt_get()/tdx_pamt_put() static and export only tdx_alloc_control_page()/tdx_free_control_page() (note:
dropped inline helpers since the discussion on Sean's series resulted in them not being needed)
- Switch EXPORT_SYMBOL_GPL to EXPORT_SYMBOL_FOR_KVM (Sean)
- Use WARN_ON_ONCE() instead of pr_err() for TDX module failures (Sean)
- Fold alloc_pamt_array()/free_pamt_array() helpers back in and fix the error-unwind index bug (dpamt_pages[i] -> [j])
- Adjustments after struct page->pfn
- Adjustments from dropping error helper patches
- Make the free error paths more normal
- Drop gfp_t arg in tdx_alloc_control_page(). In the Sean mega v5, it was really needed because the kvm_mmu_memory_cache had a gfp_t it needed something to do with. But this was still weird because that version didn't handle allocating the DPAMT pages as the gfp_t. And in the end all the callers pass GFP_KERNEL_ACCOUNT. So just drop the arg.
- Log tweaks

---
 arch/x86/include/asm/tdx.h  |   7 ++
 arch/x86/virt/vmx/tdx/tdx.c | 159 ++++++++++++++++++++++++++++++++++++
 arch/x86/virt/vmx/tdx/tdx.h |   2 +
 3 files changed, 168 insertions(+)
arch/x86/include/asm/tdx.h +7 -0
index 82dc27aecf297..74e75db5728c7 100644
@@ -37,6 +37,7 @@
 
 #include <uapi/asm/mce.h>
 #include <asm/tdx_global_metadata.h>
+#include <linux/mm.h>
 #include <linux/pgtable.h>
 
 /*
@@ -160,6 +161,12 @@ void tdx_guest_keyid_free(unsigned int keyid);
 
 void tdx_quirk_reset_paddr(unsigned long base, unsigned long size);
 
+/* Number PAMT pages to be provided to TDX module per 2MB region of PA */
+#define TDX_DPAMT_ENTRY_PAGE_CNT 2
+
+struct page *tdx_alloc_control_page(void);
+void tdx_free_control_page(struct page *page);
+
 struct tdx_td {
 	/* TD root structure: */
 	struct page *tdr_page;
arch/x86/virt/vmx/tdx/tdx.c +159 -0

165 lines not on this page · raw message

arch/x86/virt/vmx/tdx/tdx.h +2 -0
index dde219c823b41..8c39dde347cc2 100644
@@ -46,6 +46,8 @@
 #define TDH_PHYMEM_PAGE_WBINVD		41
 #define TDH_VP_WR			43
 #define TDH_SYS_CONFIG			45
+#define TDH_PHYMEM_PAMT_ADD		58
+#define TDH_PHYMEM_PAMT_REMOVE		59
 
 /*
  * SEAMCALL leaf:
Signature · 1 line
2.54.0
Reviewed-by on v6 3/11
#25 lore raw

Re: [PATCH v6 03/11] x86/virt/tdx: Add tdx_alloc/free_control_page() helpers

Quoted 37 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Add helpers to use when allocating or preparing pages that are handed to the TDX-Module for use as control/S-EPT pages, and thus need Dynamic PAMT adjustments.

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So for pages that TDX will use as 2MB physically contiguous pages, Dynamic PAMT backing is not needed.

KVM will need to hand pages to the TDX module that it will use at 4KB granularity. So these pages will need Dynamic PAMT backing added before they are used by the TDX module, and removed afterwards.

Add tdx_alloc_control_page() and tdx_free_control_page() to handle both page allocation and Dynamic PAMT installation. Make them behave like normal alloc/free functions where allocation can fail in the case of no memory, but free (with any necessary Dynamic PAMT release) always succeeds. Do this so they can support the existing TDX flows that require teardowns to succeed.

Also create tdx_pamt_get/put() to handle installing Dynamic PAMT 4KB backing for pages that are already allocated (such as KVM's use of S-EPT page tables or guest private memory). Have them take a pfn instead of a struct page, as future changes will want to use these helpers for guest pages which are tracked by PFN.

Don't CLFLUSH the Dynamic PAMT pages handed to the TDX module, as is done for some other SEAMCALLs, as the TDX docs specify that this is only needed on "TD private memory or TD control structure page".

Since these allocations will be easily user triggerable, account the memory.

Quoted 8 lines

Leave logic to handle concurrency issues for future changes.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7 Sashiko:claude-opus-4-6

One comment below.

arch/x86/include/asm/tdx.h line 40

Quoted 10 lines
arch/x86/include/asm/tdx.h +1 -0
index 82dc27aecf297..74e75db5728c7 100644
@@ -37,6 +37,7 @@
 
 #include <uapi/asm/mce.h>
 #include <asm/tdx_global_metadata.h>
+#include <linux/mm.h>

I think the header is not needed here.

Quoted 18 lines
arch/x86/include/asm/tdx.h +6 -0
 #include <linux/pgtable.h>
 
 /*
@@ -160,6 +161,12 @@ void tdx_guest_keyid_free(unsigned int keyid);
 
 void tdx_quirk_reset_paddr(unsigned long base, unsigned long size);
 
+/* Number PAMT pages to be provided to TDX module per 2MB region of PA */
+#define TDX_DPAMT_ENTRY_PAGE_CNT 2
+
+struct page *tdx_alloc_control_page(void);
+void tdx_free_control_page(struct page *page);
+
 struct tdx_td {
 	/* TD root structure: */
 	struct page *tdr_page;
arch/x86/virt/vmx/tdx/tdx.c +0 -0
index 9ebd192cb5c17..9e0812d87ab06 100644[...]
#26 lore raw

Re: [PATCH v6 03/11] x86/virt/tdx: Add tdx_alloc/free_control_page() helpers

Quoted 11 lines · Binbin Wu

arch/x86/include/asm/tdx.h line 40

Quoted 9 lines
arch/x86/include/asm/tdx.h +1 -0
index 82dc27aecf297..74e75db5728c7 100644
@@ -37,6 +37,7 @@
 
 #include <uapi/asm/mce.h>
 #include <asm/tdx_global_metadata.h>
+#include <linux/mm.h>

I think the header is not needed here.

Right. This version does not invoke page_address() in tdx.h for tdx_alloc_control_page() any more.

Also no need to include mm.h for tdx.c (which has invoked page_address() before this patch), since tdx.c includes memblock.h which further includes mm.h.

author maintainer
#27 lore raw

Re: [PATCH v6 03/11] x86/virt/tdx: Add tdx_alloc/free_control_page() helpers

Quoted 12 lines · Yan Zhao
Quoted 11 lines · Binbin Wu
Quoted 9 lines
arch/x86/include/asm/tdx.h +0 -0
index 82dc27aecf297..74e75db5728c7 100644
@@ -37,6 +37,7 @@


  #include <uapi/asm/mce.h>
  #include <asm/tdx_global_metadata.h>
+#include <linux/mm.h>

I think the header is not needed here.

Quoted 5 lines

Right. This version does not invoke page_address() in tdx.h for tdx_alloc_control_page() any more.

Also no need to include mm.h for tdx.c (which has invoked page_address() before this patch), since tdx.c includes memblock.h which further includes mm.h.

Thanks for the analysis. Will remove both.

Reviewed-by on v6 3/11
#28 lore raw

Re: [PATCH v6 03/11] x86/virt/tdx: Add tdx_alloc/free_control_page() helpers

In reply to Rick Edgecombe
Quoted 4 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Add helpers to use when allocating or preparing pages that are handed to the TDX-Module for use as control/S-EPT pages, and thus need Dynamic PAMT

For the whole series: s/TDX-Module/TDX module, to match the existing convention.

arch/x86/virt/vmx/tdx/tdx.c u64 tdh_phymem_page_wbinvd_hkid(u64 hkid, kvm_pfn_t pfn) · line 1958

Quoted 7 lines
arch/x86/virt/vmx/tdx/tdx.c +7 -0
+/*
+ * Calculate the arg needed for operating on the DPAMT backing for
+ * a given 4KB page.
+ */
+static u64 pamt_2mb_arg(kvm_pfn_t pfn)
+{
+	unsigned long hpa_2mb = ALIGN_DOWN(pfn << PAGE_SHIFT, PMD_SIZE);

The changelog and the comment don't explain why the pfn is aligned down to a 2MB boundary. And ...

arch/x86/virt/vmx/tdx/tdx.c u64 tdh_phymem_page_wbinvd_hkid(u64 hkid, kvm_pfn_t pfn) · line 1963

Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +5 -0
+
+	return hpa_2mb | TDX_PS_2M;
+}
+
+/* Add PAMT backing for the given page. */

... this adds PAMT backing for the whole 2MB region containing the given page, not just the given page itself. Is it worth clarifying in the comment?

<snip>

Quoted 6 lines

+/*
+ * Return a page that can be gifted to the TDX-Module for use as a "control"
+ * page, i.e. pages that are used for control and S-EPT structures for a given
+ * TDX guest, and bound to said guest's HKID and thus obtain TDX protections,
+ * including PAMT tracking.
+ */

IIUC, S-EPT structures are not allocated through this helper. Why mention it?

Quoted 11 lines
arch/x86/virt/vmx/tdx/tdx.c +11 -0
+struct page *tdx_alloc_control_page(void)
+{
+	struct page *page;
+
+	page = alloc_page(GFP_KERNEL_ACCOUNT);
+	if (!page)
+		return NULL;
+
+	if (tdx_pamt_get(page_to_pfn(page))) {
+		__free_page(page);
+		return NULL;

arch/x86/virt/vmx/tdx/tdx.c u64 tdh_phymem_page_wbinvd_hkid(u64 hkid, kvm_pfn_t pfn) · line 2070

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+	}
+
+	return page;
+}
+EXPORT_SYMBOL_FOR_KVM(tdx_alloc_control_page);
+
+/*
+ * Free a page that was gifted to the TDX-Module for use as a control/S-EPT
+ * page. After this, the page is no longer protected by TDX.
+ */

Ditto.

arch/x86/virt/vmx/tdx/tdx.c u64 tdh_phymem_page_wbinvd_hkid(u64 hkid, kvm_pfn_t pfn) · line 2079

Quoted 9 lines
arch/x86/virt/vmx/tdx/tdx.c +9 -0
+void tdx_free_control_page(struct page *page)
+{
+	if (!page)
+		return;
+
+	tdx_pamt_put(page_to_pfn(page));
+	__free_page(page);
+}
+EXPORT_SYMBOL_FOR_KVM(tdx_free_control_page);

With above nits fixed,

author maintainer
#29 lore raw

Re: [PATCH v6 03/11] x86/virt/tdx: Add tdx_alloc/free_control_page() helpers

Quoted 8 lines · Chao Gao
Quoted 4 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Add helpers to use when allocating or preparing pages that are handed to the TDX-Module for use as control/S-EPT pages, and thus need Dynamic PAMT

For the whole series: s/TDX-Module/TDX module, to match the existing convention.

Doh, I actually changed the whole series to TDX-module before realizing that most of the references are "TDX module". So I thought to standardize on that going forward. I missed this one when changing back.

Quoted 12 lines

arch/x86/virt/vmx/tdx/tdx.c u64 tdh_phymem_page_wbinvd_hkid(u64 hkid, kvm_pfn_t pfn) · line 1958

Quoted 8 lines
arch/x86/virt/vmx/tdx/tdx.c +7 -0
+/*
+ * Calculate the arg needed for operating on the DPAMT backing for
+ * a given 4KB page.
+ */
+static u64 pamt_2mb_arg(kvm_pfn_t pfn)
+{
+	unsigned long hpa_2mb = ALIGN_DOWN(pfn << PAGE_SHIFT, PMD_SIZE);

The changelog and the comment don't explain why the pfn is aligned down to a 2MB boundary. And ...

Quoted 8 lines

arch/x86/virt/vmx/tdx/tdx.c u64 tdh_phymem_page_wbinvd_hkid(u64 hkid, kvm_pfn_t pfn) · line 1963

Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +5 -0
+
+	return hpa_2mb | TDX_PS_2M;
+}
+
+/* Add PAMT backing for the given page. */

... this adds PAMT backing for the whole 2MB region containing the given page, not just the given page itself. Is it worth clarifying in the comment?

Yea that is a good comment.

Quoted 11 lines

<snip>

Quoted 6 lines

+/*
+ * Return a page that can be gifted to the TDX-Module for use as a "control"
+ * page, i.e. pages that are used for control and S-EPT structures for a given
+ * TDX guest, and bound to said guest's HKID and thus obtain TDX protections,
+ * including PAMT tracking.
+ */

IIUC, S-EPT structures are not allocated through this helper. Why mention it?

Oh, yea that is removed with v6. I'll update it.

Quoted 38 lines
Quoted 12 lines
arch/x86/virt/vmx/tdx/tdx.c +11 -0
+struct page *tdx_alloc_control_page(void)
+{
+	struct page *page;
+
+	page = alloc_page(GFP_KERNEL_ACCOUNT);
+	if (!page)
+		return NULL;
+
+	if (tdx_pamt_get(page_to_pfn(page))) {
+		__free_page(page);
+		return NULL;

arch/x86/virt/vmx/tdx/tdx.c u64 tdh_phymem_page_wbinvd_hkid(u64 hkid, kvm_pfn_t pfn) · line 2070

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+	}
+
+	return page;
+}
+EXPORT_SYMBOL_FOR_KVM(tdx_alloc_control_page);
+
+/*
+ * Free a page that was gifted to the TDX-Module for use as a control/S-EPT
+ * page. After this, the page is no longer protected by TDX.
+ */

Ditto.

arch/x86/virt/vmx/tdx/tdx.c u64 tdh_phymem_page_wbinvd_hkid(u64 hkid, kvm_pfn_t pfn) · line 2079

Quoted 9 lines
arch/x86/virt/vmx/tdx/tdx.c +9 -0
+void tdx_free_control_page(struct page *page)
+{
+	if (!page)
+		return;
+
+	tdx_pamt_put(page_to_pfn(page));
+	__free_page(page);
+}
+EXPORT_SYMBOL_FOR_KVM(tdx_free_control_page);

With above nits fixed,

#30 lore raw

Re: [PATCH v6 03/11] x86/virt/tdx: Add tdx_alloc/free_control_page() helpers

In reply to Rick Edgecombe

How about?

x86/virt/tdx: Add tdx_{alloc,free}_control_page() helpers

Quoted 6 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Add helpers to use when allocating or preparing pages that are handed to the TDX-Module for use as control/S-EPT pages, and thus need Dynamic PAMT adjustments.

Quoted 6 lines

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So for pages that TDX will use as 2MB physically contiguous pages, Dynamic PAMT backing is not needed.

I lost the continuation in the last sentence. Why does it only talk about 2MB if only 4KB is dynamically allocated. What about 1GB?

(Probably due to my lack of TDX knowledge)
Similarly, why do these functions only refer to 2MB only and not 1GB?

pamt_2mb_arg(), tdh_phymem_pamt_add(), tdh_phymem_pamt_remove().

Quoted 5 lines

KVM will need to hand pages to the TDX module that it will use at 4KB granularity. So these pages will need Dynamic PAMT backing added before they are used by the TDX module, and removed afterwards.

...

Quoted 13 lines
arch/x86/include/asm/tdx.h +1 -0
index 82dc27aecf297..74e75db5728c7 100644
@@ -37,6 +37,7 @@
 
 #include <uapi/asm/mce.h>
 #include <asm/tdx_global_metadata.h>
+#include <linux/mm.h>
 #include <linux/pgtable.h>
 
 /*

arch/x86/include/asm/tdx.h void tdx_guest_keyid_free(unsigned int keyid); · line 164

Quoted 4 lines
arch/x86/include/asm/tdx.h +1 -0
@@ -160,6 +161,12 @@ void tdx_guest_keyid_free(unsigned int keyid);
 
 void tdx_quirk_reset_paddr(unsigned long base, unsigned long size);
 
+/* Number PAMT pages to be provided to TDX module per 2MB region of PA */

^^^ of PAMT pages

Quoted 21 lines
arch/x86/include/asm/tdx.h +5 -0
+#define TDX_DPAMT_ENTRY_PAGE_CNT 2
+
+struct page *tdx_alloc_control_page(void);
+void tdx_free_control_page(struct page *page);
+
 struct tdx_td {
 	/* TD root structure: */
 	struct page *tdr_page;
arch/x86/virt/vmx/tdx/tdx.c +5 -0
index 9ebd192cb5c17..9e0812d87ab06 100644
@@ -1919,6 +1919,165 @@ u64 tdh_phymem_page_wbinvd_hkid(u64 hkid, kvm_pfn_t pfn)
 }
 EXPORT_SYMBOL_FOR_KVM(tdh_phymem_page_wbinvd_hkid);
 
+static int alloc_pamt_array(struct page **pamt_pages)
+{
+	int i, j;
+
+	for (i = 0; i < TDX_DPAMT_ENTRY_PAGE_CNT; i++) {

arch/x86/virt/vmx/tdx/tdx.c u64 tdh_phymem_page_wbinvd_hkid(u64 hkid, kvm_pfn_t pfn) · line 1936

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+		pamt_pages[i] = alloc_page(GFP_KERNEL_ACCOUNT);
+		if (!pamt_pages[i])
+			goto err;
+	}
+
+	return 0;
+err:
+	for (j = 0; j < i; j++)
+		__free_page(pamt_pages[j]);
+	return -ENOMEM;

Add a blank line before the return to separate from the for loop?

Quoted 68 lines
arch/x86/virt/vmx/tdx/tdx.c +68 -0
+}
+
+static void free_pamt_array(struct page **pamt_pages)
+{
+	for (int i = 0; i < TDX_DPAMT_ENTRY_PAGE_CNT; i++) {
+		/*
+		 * Reset pages unconditionally to cover cases
+		 * where they were passed to the TDX module.
+		 */
+		tdx_quirk_reset_paddr(page_to_phys(pamt_pages[i]), PAGE_SIZE);
+
+		__free_page(pamt_pages[i]);
+	}
+}
+
+/*
+ * Calculate the arg needed for operating on the DPAMT backing for
+ * a given 4KB page.
+ */
+static u64 pamt_2mb_arg(kvm_pfn_t pfn)
+{
+	unsigned long hpa_2mb = ALIGN_DOWN(pfn << PAGE_SHIFT, PMD_SIZE);
+
+	return hpa_2mb | TDX_PS_2M;
+}
+
+/* Add PAMT backing for the given page. */
+static u64 tdh_phymem_pamt_add(kvm_pfn_t pfn, struct page **pamt_pages)
+{
+	struct tdx_module_args args = {
+		.rcx = pamt_2mb_arg(pfn),
+		.rdx = page_to_phys(pamt_pages[0]),
+		.r8 = page_to_phys(pamt_pages[1]),
+	};
+
+	return seamcall(TDH_PHYMEM_PAMT_ADD, &args);
+}
+
+/* Remove PAMT backing for the given page. */
+static u64 tdh_phymem_pamt_remove(kvm_pfn_t pfn, struct page **pamt_pages)
+{
+	struct tdx_module_args args = {
+		.rcx = pamt_2mb_arg(pfn),
+	};
+	u64 ret;
+
+	ret = seamcall_ret(TDH_PHYMEM_PAMT_REMOVE, &args);
+	if (ret)
+		return ret;
+
+	/* Copy PAMT pages out of the struct per the TDX ABI */
+	pamt_pages[0] = phys_to_page(args.rdx);
+	pamt_pages[1] = phys_to_page(args.r8);
+
+	return 0;
+}
+
+/* Allocate PAMT memory for the given page */
+static int tdx_pamt_get(kvm_pfn_t pfn)
+{
+	struct page *pamt_pages[TDX_DPAMT_ENTRY_PAGE_CNT];
+	u64 tdx_status;
+	int ret;
+
+	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
+		return 0;
+
+	ret = alloc_pamt_array(pamt_pages);

arch/x86/virt/vmx/tdx/tdx.c u64 tdh_phymem_page_wbinvd_hkid(u64 hkid, kvm_pfn_t pfn) · line 2014

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+	if (ret)
+		return ret;
+
+	tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
+	if (tdx_status != TDX_SUCCESS) {
+		ret = -EIO;
+		goto out_free;
+	}
+
+	return 0;

Blank line here as well.

Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +5 -0
+out_free:
+	free_pamt_array(pamt_pages);
+	return ret;
+}
+
author maintainer
#31 lore raw

Re: [PATCH v6 03/11] x86/virt/tdx: Add tdx_alloc/free_control_page() helpers

Quoted 3 lines · Sohil Mehta

How about?

x86/virt/tdx: Add tdx_{alloc,free}_control_page() helpers

Sure.

Quoted 15 lines · Rick Edgecombe
Quoted 6 lines

From: "Kirill A. Shutemov" <[email protected]>

Add helpers to use when allocating or preparing pages that are handed to the TDX-Module for use as control/S-EPT pages, and thus need Dynamic PAMT adjustments.

Quoted 6 lines

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So for pages that TDX will use as 2MB physically contiguous pages, Dynamic PAMT backing is not needed.

Quoted 7 lines

I lost the continuation in the last sentence. Why does it only talk about 2MB if only 4KB is dynamically allocated. What about 1GB?

(Probably due to my lack of TDX knowledge)
Similarly, why do these functions only refer to 2MB only and not 1GB?

pamt_2mb_arg(), tdh_phymem_pamt_add(), tdh_phymem_pamt_remove().

We only need to dynamically allocate the 4k level of the PAMT. This is the detail we discussed in patch 2. There it was necessary to explain why we are changing the 4K level of the PAMT to be a bitmap thing, and not the others. Here I think it is useful to understand why the helpers are all for 4KB page size of host memory. I think it's clearer actually with just the last line removed:

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically.

KVM will need to hand pages to the TDX module that it will use at 4KB granularity. So these pages will need Dynamic PAMT backing added before they are used by the TDX module, and removed afterwards.

And, I'll address the trimmed style comments.

author maintainer
#32 lore raw

PATCH v6 4/11 x86/virt/tdx: Allocate ref counts for Dynamic PAMT memory

In reply to Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The PAMT memory holds metadata for all possible TDX protected memory. Each physical address range is covered by PAMT entries at three levels (1GB, 2MB, 4KB). With Dynamic PAMT, the 4KB range of PAMT is allocated on demand. The kernel supplies the TDX module with page pairs to store the 4KB entries, which cover 2MB of host physical memory. The kernel must provide this page pair before using pages from the range for TDX. If this is not done, SEAMCALLs that give the pages to be protected by the TDX module will fail.

Allocate reference counters for every 2MB range to track TDX memory usage. This can be used to handle concurrent get/put callers, in order to accurately determine when the dynamic 4KB level of Dynamic PAMT needs to be allocated and when it can be freed.

This allocation will currently consume 2 MB for every 1 TB of address space from 0 to max_pfn. The allocation size will depend on how the RAM is physically laid out. In a worst case scenario where the entire 52-bit address space is covered this would be 8GB. Then the DPAMT refcount allocations could hypothetically cause the savings from Dynamic PAMT to go negative on exotic platforms with sparse, small amounts of memory.

Future changes could reduce this refcount overhead to be only allocating refcounts for physical ranges that contain memory that TDX can use. However, this is left for future work.

Assisted-by Sashiko:claude-opus-4-6 GitHub Copilot:claude-opus-4-6 Sashiko:claude-opus-4-6

---
v6:
- Remove confusing reference to allocating PAMT memory in pamt_refcounts comment. (Yan)
- Rename "metadata" function names that really deal with refcounts, as metadata already has a different meaning in TDX.
- Move tdx_find_pamt_refcount() to this patch to aid in reviewability

v4:
- Log typo (Binbin)
- round correctly when computing PAMT refcount size (Binbin)
- Zero refcount vmalloc allocation (Note: This got replaced in optimization patch with a zero-ed allocation, but this showed up in testing with the optimization patches removed. Since it's fixed before this code is exercised, it's not a bisectability issue, but fix it anyway.)

v3:
- Split out lazily populate optimization to next patch (Dave)
- Add comment around pamt_refcounts (Dave)
- Improve log

---
 arch/x86/virt/vmx/tdx/tdx.c | 54 ++++++++++++++++++++++++++++++++++++-
 1 file changed, 53 insertions(+), 1 deletion(-)
arch/x86/virt/vmx/tdx/tdx.c +53 -1
index 9e0812d87ab06..6658a6be6697c 100644
@@ -30,6 +30,7 @@
 #include <linux/suspend.h>
 #include <linux/syscore_ops.h>
 #include <linux/idr.h>
+#include <linux/vmalloc.h>
 #include <asm/page.h>
 #include <asm/special_insns.h>
 #include <asm/msr-index.h>
@@ -52,6 +53,14 @@ static DEFINE_PER_CPU(bool, tdx_lp_initialized);
 
 static struct tdmr_info_list tdx_tdmr_list;
 
+/*
+ * On a machine with Dynamic PAMT, the kernel maintains a reference counter
+ * for every 2M range. The counter indicates how many users there are for
+ * the PAMT memory of the 2M range. The kernel allocates PAMT refcounts at
+ * initialization.
+ */
+static atomic_t *pamt_refcounts;
+
 /* All TDX-usable memory regions.  Protected by mem_hotplug_lock. */
 static LIST_HEAD(tdx_memlist);
 
@@ -254,6 +263,43 @@ static struct syscore tdx_syscore = {
 	.ops = &tdx_syscore_ops,
 };
 
+/*
+ * Allocate PAMT reference counters for all physical memory.
+ *
+ * It consumes 2MiB for every 1TiB of physical memory.
+ */
+static int init_pamt_refcounts(void)
+{
+	size_t size = DIV_ROUND_UP(max_pfn, PTRS_PER_PTE) * sizeof(*pamt_refcounts);
+
+	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
+		return 0;
+
+	pamt_refcounts = __vmalloc(size, GFP_KERNEL | __GFP_ZERO);
+	if (!pamt_refcounts)
+		return -ENOMEM;
+
+	return 0;
+}
+
+static void free_pamt_refcounts(void)
+{
+	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
+		return;
+
+	vfree(pamt_refcounts);
+	pamt_refcounts = NULL;
+}
+
+/* Find PAMT refcount for a given physical address */
+static atomic_t * __maybe_unused tdx_find_pamt_refcount(unsigned long pfn)
+{
+	/* Find which PMD a PFN is in. */
+	unsigned long index = pfn >> (PMD_SHIFT - PAGE_SHIFT);
+
+	return &pamt_refcounts[index];
+}
+
 /*
  * Add a memory region as a TDX memory block.  The caller must make sure
  * all memory regions are added in address ascending order and don't
@@ -1151,10 +1197,14 @@ static __init int init_tdx_module(void)
 	 */
 	get_online_mems();
 
-	ret = build_tdx_memlist(&tdx_memlist);
+	ret = init_pamt_refcounts();
 	if (ret)
 		goto out_put_tdxmem;
 
+	ret = build_tdx_memlist(&tdx_memlist);
+	if (ret)
+		goto err_free_pamt_refcounts;
+
 	/* Allocate enough space for constructing TDMRs */
 	ret = alloc_tdmr_list(&tdx_tdmr_list, &tdx_sysinfo.tdmr);
 	if (ret)
@@ -1204,6 +1254,8 @@ static __init int init_tdx_module(void)
 	free_tdmr_list(&tdx_tdmr_list);
 err_free_tdxmem:
 	free_tdx_memlist(&tdx_memlist);
+err_free_pamt_refcounts:
+	free_pamt_refcounts();
 	goto out_put_tdxmem;
 }
 
Signature · 1 line
2.54.0
Reviewed-by on v6 4/11
#33 lore raw

Re: [PATCH v6 04/11] x86/virt/tdx: Allocate ref counts for Dynamic PAMT memory

Quoted 16 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The PAMT memory holds metadata for all possible TDX protected memory. Each physical address range is covered by PAMT entries at three levels (1GB, 2MB, 4KB). With Dynamic PAMT, the 4KB range of PAMT is allocated on demand. The kernel supplies the TDX module with page pairs to store the 4KB entries, which cover 2MB of host physical memory. The kernel must provide this page pair before using pages from the range for TDX. If this is not done, SEAMCALLs that give the pages to be protected by the TDX module will fail.

Allocate reference counters for every 2MB range to track TDX memory usage. This can be used to handle concurrent get/put callers, in order to accurately determine when the dynamic 4KB level of Dynamic PAMT needs to be allocated and when it can be freed.

Quoted 6 lines

This allocation will currently consume 2 MB for every 1 TB of address space from 0 to max_pfn. The allocation size will depend on how the RAM is physically laid out. In a worst case scenario where the entire 52-bit address space is covered this would be 8GB. Then the DPAMT refcount allocations could hypothetically cause the savings from Dynamic PAMT to go negative on exotic platforms with sparse, small amounts of memory.

Nit:
Do you think it make sense to print the memory size allocated for DPAMT refcounts in the kernel log?

Quoted 9 lines

Future changes could reduce this refcount overhead to be only allocating refcounts for physical ranges that contain memory that TDX can use. However, this is left for future work.

Assisted-by Sashiko:claude-opus-4-6 GitHub Copilot:claude-opus-4-6 Sashiko:claude-opus-4-6
author maintainer
#34 lore raw

Re: [PATCH v6 04/11] x86/virt/tdx: Allocate ref counts for Dynamic PAMT memory

Quoted 24 lines · Binbin Wu
Quoted 16 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The PAMT memory holds metadata for all possible TDX protected memory. Each physical address range is covered by PAMT entries at three levels (1GB, 2MB, 4KB). With Dynamic PAMT, the 4KB range of PAMT is allocated on demand. The kernel supplies the TDX module with page pairs to store the 4KB entries, which cover 2MB of host physical memory. The kernel must provide this page pair before using pages from the range for TDX. If this is not done, SEAMCALLs that give the pages to be protected by the TDX module will fail.

Allocate reference counters for every 2MB range to track TDX memory usage. This can be used to handle concurrent get/put callers, in order to accurately determine when the dynamic 4KB level of Dynamic PAMT needs to be allocated and when it can be freed.

Quoted 6 lines

This allocation will currently consume 2 MB for every 1 TB of address space from 0 to max_pfn. The allocation size will depend on how the RAM is physically laid out. In a worst case scenario where the entire 52-bit address space is covered this would be 8GB. Then the DPAMT refcount allocations could hypothetically cause the savings from Dynamic PAMT to go negative on exotic platforms with sparse, small amounts of memory.

Quoted 3 lines

Nit:
Do you think it make sense to print the memory size allocated for DPAMT refcounts in the kernel log?

I think, no? Because it should normally be "small" on the scale of the system. We have to draw the line somewhere.

Quoted 6 lines
Quoted 6 lines

Future changes could reduce this refcount overhead to be only allocating refcounts for physical ranges that contain memory that TDX can use. However, this is left for future work.

Quoted 6 lines
Quoted 4 lines
Assisted-by Sashiko:claude-opus-4-6 GitHub Copilot:claude-opus-4-6 Sashiko:claude-opus-4-6

Thanks, and for the others.

Reviewed-by on v6 4/11
#35 lore raw

Re: [PATCH v6 04/11] x86/virt/tdx: Allocate ref counts for Dynamic PAMT memory

In reply to Rick Edgecombe
Quoted 17 lines
arch/x86/virt/vmx/tdx/tdx.c +17 -0
+/*
+ * Allocate PAMT reference counters for all physical memory.
+ *
+ * It consumes 2MiB for every 1TiB of physical memory.
+ */
+static int init_pamt_refcounts(void)
+{
+	size_t size = DIV_ROUND_UP(max_pfn, PTRS_PER_PTE) * sizeof(*pamt_refcounts);
+
+	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
+		return 0;
+
+	pamt_refcounts = __vmalloc(size, GFP_KERNEL | __GFP_ZERO);
+	if (!pamt_refcounts)
+		return -ENOMEM;
+
+	return 0;

arch/x86/virt/vmx/tdx/tdx.c static struct syscore tdx_syscore = { · line 292

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+}
+
+static void free_pamt_refcounts(void)
+{
+	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
+		return;
+
+	vfree(pamt_refcounts);
+	pamt_refcounts = NULL;
+}

Both functions are only called during boot. They can be annotated with __init.

author maintainer
#36 lore raw

Re: [PATCH v6 04/11] x86/virt/tdx: Allocate ref counts for Dynamic PAMT memory

Quoted 22 lines · Chao Gao
Quoted 22 lines
arch/x86/virt/vmx/tdx/tdx.c +8 -0
+/*
+ * Allocate PAMT reference counters for all physical memory.
+ *
+ * It consumes 2MiB for every 1TiB of physical memory.
+ */
+static int init_pamt_refcounts(void)
+{
+	size_t size = DIV_ROUND_UP(max_pfn, PTRS_PER_PTE) *

sizeof(*pamt_refcounts);

arch/x86/virt/vmx/tdx/tdx.c +13 -0
+
+	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
+		return 0;
+
+	pamt_refcounts = __vmalloc(size, GFP_KERNEL | __GFP_ZERO);
+	if (!pamt_refcounts)
+		return -ENOMEM;
+
+	return 0;
+}
+
+static void free_pamt_refcounts(void)
+{
Quoted 8 lines

arch/x86/virt/vmx/tdx/tdx.c static struct syscore tdx_syscore = { · line 292

Quoted 6 lines
arch/x86/virt/vmx/tdx/tdx.c +6 -0
+	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
+		return;
+
+	vfree(pamt_refcounts);
+	pamt_refcounts = NULL;
+}

Both functions are only called during boot. They can be annotated with __init.

Yep, thanks.

Quoted 2 lines
Reviewed-by on v6 4/11
#37 lore raw

Re: [PATCH v6 04/11] x86/virt/tdx: Allocate ref counts for Dynamic PAMT memory

In reply to Rick Edgecombe
Quoted 5 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The PAMT memory holds metadata for all possible TDX protected memory. Each physical address range is covered by PAMT entries at three levels (1GB, 2MB, 4KB). With Dynamic PAMT, the 4KB range of PAMT is allocated on

^level ?

Quoted 2 lines

demand. The kernel supplies the TDX module with page pairs to store the 4KB entries, which cover 2MB of host physical memory. The kernel must

4KB-level entries ?

Quoted 2 lines

provide this page pair before using pages from the range for TDX. If this is not done, SEAMCALLs that give the pages to be protected by the TDX module

Nit: > 75 chars per line.

author maintainer
#38 lore raw

Re: [PATCH v6 04/11] x86/virt/tdx: Allocate ref counts for Dynamic PAMT memory

Quoted 10 lines · Yan Zhao
Quoted 5 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The PAMT memory holds metadata for all possible TDX protected memory. Each physical address range is covered by PAMT entries at three levels (1GB, 2MB, 4KB). With Dynamic PAMT, the 4KB range of PAMT is allocated on

                                         ^level ?

Quoted 2 lines

demand. The kernel supplies the TDX module with page pairs to store the 4KB entries, which cover 2MB of host physical memory. The kernel must

4KB-level entries ?

Sure.

Quoted 4 lines
Quoted 3 lines

provide this page pair before using pages from the range for TDX. If this is not done, SEAMCALLs that give the pages to be protected by the TDX module

Nit: > 75 chars per line.

Oh yea, must have been a late change.

Quoted 2 lines
#39 lore raw

Re: [PATCH v6 04/11] x86/virt/tdx: Allocate ref counts for Dynamic PAMT memory

In reply to Rick Edgecombe
Quoted 23 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The PAMT memory holds metadata for all possible TDX protected memory. Each physical address range is covered by PAMT entries at three levels (1GB, 2MB, 4KB). With Dynamic PAMT, the 4KB range of PAMT is allocated on demand. The kernel supplies the TDX module with page pairs to store the 4KB entries, which cover 2MB of host physical memory. The kernel must provide this page pair before using pages from the range for TDX. If this is not done, SEAMCALLs that give the pages to be protected by the TDX module will fail.

Allocate reference counters for every 2MB range to track TDX memory usage. This can be used to handle concurrent get/put callers, in order to accurately determine when the dynamic 4KB level of Dynamic PAMT needs to be allocated and when it can be freed.

This allocation will currently consume 2 MB for every 1 TB of address space from 0 to max_pfn. The allocation size will depend on how the RAM is physically laid out. In a worst case scenario where the entire 52-bit address space is covered this would be 8GB. Then the DPAMT refcount allocations could hypothetically cause the savings from Dynamic PAMT to go negative on exotic platforms with sparse, small amounts of memory.

...

Quoted 3 lines

+/*
+ * On a machine with Dynamic PAMT, the kernel maintains a reference counter
+ * for every 2M range.

Commit log says every 2MB range.

The counter indicates how many users there are for

Quoted 9 lines

+ * the PAMT memory of the 2M range. The kernel allocates PAMT refcounts at
+ * initialization.
+ */

arch/x86/virt/vmx/tdx/tdx.c +2 -0
+static atomic_t *pamt_refcounts;
+
 /* All TDX-usable memory regions.  Protected by mem_hotplug_lock. */
 static LIST_HEAD(tdx_memlist);

arch/x86/virt/vmx/tdx/tdx.c static struct syscore tdx_syscore = { · line 269

Quoted 7 lines
arch/x86/virt/vmx/tdx/tdx.c +4 -0
@@ -254,6 +263,43 @@ static struct syscore tdx_syscore = {
 	.ops = &tdx_syscore_ops,
 };
 
+/*
+ * Allocate PAMT reference counters for all physical memory.
+ *
+ * It consumes 2MiB for every 1TiB of physical memory.

Commit log says 2MB and 1TB. I would make both consistent.

arch/x86/virt/vmx/tdx/tdx.c static struct syscore tdx_syscore = { · line 278

Quoted 9 lines
arch/x86/virt/vmx/tdx/tdx.c +9 -0
+ */
+static int init_pamt_refcounts(void)
+{
+	size_t size = DIV_ROUND_UP(max_pfn, PTRS_PER_PTE) * sizeof(*pamt_refcounts);
+
+	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
+		return 0;
+
+	pamt_refcounts = __vmalloc(size, GFP_KERNEL | __GFP_ZERO);

vzalloc()?

Quoted 6 lines
arch/x86/virt/vmx/tdx/tdx.c +6 -0
+	if (!pamt_refcounts)
+		return -ENOMEM;
+
+	return 0;
+}
+

arch/x86/virt/vmx/tdx/tdx.c static struct syscore tdx_syscore = { · line 294

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+static void free_pamt_refcounts(void)
+{
+	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
+		return;
+
+	vfree(pamt_refcounts);
+	pamt_refcounts = NULL;
+}
+
+/* Find PAMT refcount for a given physical address */

This comment is probably not that useful. The function name is descriptive by itself.

Quoted 8 lines
arch/x86/virt/vmx/tdx/tdx.c +8 -0
+static atomic_t * __maybe_unused tdx_find_pamt_refcount(unsigned long pfn)
+{
+	/* Find which PMD a PFN is in. */
+	unsigned long index = pfn >> (PMD_SHIFT - PAGE_SHIFT);
+
+	return &pamt_refcounts[index];
+}
+
author maintainer
#40 lore raw

Re: [PATCH v6 04/11] x86/virt/tdx: Allocate ref counts for Dynamic PAMT memory

Quoted 25 lines · Sohil Mehta
Quoted 16 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The PAMT memory holds metadata for all possible TDX protected memory. Each physical address range is covered by PAMT entries at three levels (1GB, 2MB, 4KB). With Dynamic PAMT, the 4KB range of PAMT is allocated on demand. The kernel supplies the TDX module with page pairs to store the 4KB entries, which cover 2MB of host physical memory. The kernel must provide this page pair before using pages from the range for TDX. If this is not done, SEAMCALLs that give the pages to be protected by the TDX module will fail.

Allocate reference counters for every 2MB range to track TDX memory usage. This can be used to handle concurrent get/put callers, in order to accurately determine when the dynamic 4KB level of Dynamic PAMT needs to be allocated and when it can be freed.

Quoted 7 lines

This allocation will currently consume 2 MB for every 1 TB of address space from 0 to max_pfn. The allocation size will depend on how the RAM is physically laid out. In a worst case scenario where the entire 52-bit address space is covered this would be 8GB. Then the DPAMT refcount allocations could hypothetically cause the savings from Dynamic PAMT to go negative on exotic platforms with sparse, small amounts of memory.

Quoted 7 lines

...

Quoted 3 lines

+/*
+ * On a machine with Dynamic PAMT, the kernel maintains a reference counter
+ * for every 2M range.

Commit log says every 2MB range.

Yea, I'll unify to MB, TB, KB.

Quoted 14 lines

The counter indicates how many users there are for

Quoted 12 lines

+ * the PAMT memory of the 2M range. The kernel allocates PAMT refcounts at
+ * initialization.
+ */

arch/x86/virt/vmx/tdx/tdx.c +2 -0
+static atomic_t *pamt_refcounts;
+
 /* All TDX-usable memory regions.  Protected by mem_hotplug_lock. */
 static LIST_HEAD(tdx_memlist);
@@ -254,6 +263,43 @@ static struct syscore tdx_syscore = {
 	.ops = &tdx_syscore_ops,
 };
 
Quoted 6 lines

arch/x86/virt/vmx/tdx/tdx.c static struct syscore tdx_syscore = { · line 269

Quoted 4 lines
arch/x86/virt/vmx/tdx/tdx.c +4 -0
+/*
+ * Allocate PAMT reference counters for all physical memory.
+ *
+ * It consumes 2MiB for every 1TiB of physical memory.

Commit log says 2MB and 1TB. I would make both consistent.

Yea, different authors for some of this text.

Quoted 12 lines

arch/x86/virt/vmx/tdx/tdx.c static struct syscore tdx_syscore = { · line 278

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +9 -0
+ */
+static int init_pamt_refcounts(void)
+{
+	size_t size = DIV_ROUND_UP(max_pfn, PTRS_PER_PTE) * sizeof(*pamt_refcounts);
+
+	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
+		return 0;
+
+	pamt_refcounts = __vmalloc(size, GFP_KERNEL | __GFP_ZERO);

vzalloc()?

Totally.

Quoted 12 lines
Quoted 12 lines
arch/x86/virt/vmx/tdx/tdx.c +11 -0
+	if (!pamt_refcounts)
+		return -ENOMEM;
+
+	return 0;
+}
+
+static void free_pamt_refcounts(void)
+{
+	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
+		return;
+
Quoted 8 lines

arch/x86/virt/vmx/tdx/tdx.c static struct syscore tdx_syscore = { · line 294

Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +5 -0
+	vfree(pamt_refcounts);
+	pamt_refcounts = NULL;
+}
+
+/* Find PAMT refcount for a given physical address */

This comment is probably not that useful. The function name is descriptive by itself.

I'll delete it.

Quoted 9 lines
Quoted 9 lines
arch/x86/virt/vmx/tdx/tdx.c +8 -0
+static atomic_t * __maybe_unused tdx_find_pamt_refcount(unsigned long pfn)
+{
+	/* Find which PMD a PFN is in. */
+	unsigned long index = pfn >> (PMD_SHIFT - PAGE_SHIFT);
+
+	return &pamt_refcounts[index];
+}
+
author maintainer
#41 lore raw

PATCH v6 5/11 x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

In reply to Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

tdx_pamt_get()/tdx_pamt_put() unconditionally add or remove Dynamic PAMT backing for the 2MB region covering the passed pfn. However, multiple callers can concurrently operate on 4KB pages that fall within the same 2MB region. When this happens only one Dynamic PAMT page pair needs to be installed to cover the 2MB range. And when one page is freed, the Dynamic PAMT backing cannot be freed until all pages in the range are no longer in use. Make the helpers handle these races internally.

Use the per-2MB refcounts from previous changes to track how many 4KB pages are in use within each region. Gate the actual Dynamic PAMT add and remove on refcount transitions (0->1 and 1->0). Serialize the refcount check and SEAMCALL with a global spinlock so the read-decide-act sequence is atomic. This also avoids TDX module BUSY errors, as Dynamic PAMT add and remove SEAMCALLs take an internal TDX module locks at 2MB granularity, so simultaneous attempts on the same region would conflict.

The lock is global and heavyweight. Use simple conditional logic to keep correctness obvious. This will be optimized in a later change.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

---
v6:
- Split from "x86/virt/tdx: Add tdx_alloc/free_control_page() helpers"
- Return 0 instead of ret to be clearer (Binbin)
- Clarify log (Nikolay)
- Justify why the patch is not optimized in response to comments by (Nikolay)
- Move tdx_find_pamt_refcount() to faciliate patch re-order
- Adjustments from dropping error helper patches
- Log tweaks

---
 arch/x86/virt/vmx/tdx/tdx.c | 72 ++++++++++++++++++++++++++++---------
 1 file changed, 56 insertions(+), 16 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +56 -16
index 6658a6be6697c..50333eb96efa6 100644
@@ -2043,10 +2043,14 @@ static u64 tdh_phymem_pamt_remove(kvm_pfn_t pfn, struct page **pamt_pages)
 	return 0;
 }
 
-/* Allocate PAMT memory for the given page */
+/* Serializes adding/removing PAMT memory */
+static DEFINE_SPINLOCK(pamt_lock);
+
+/* Bump PAMT refcount for the given page and allocate PAMT memory if needed */
 static int tdx_pamt_get(kvm_pfn_t pfn)
 {
 	struct page *pamt_pages[TDX_DPAMT_ENTRY_PAGE_CNT];
+	atomic_t *pamt_refcount;
 	u64 tdx_status;
 	int ret;
 
@@ -2057,10 +2061,26 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
 	if (ret)
 		return ret;
 
-	tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
-	if (tdx_status != TDX_SUCCESS) {
-		ret = -EIO;
-		goto out_free;
+	pamt_refcount = tdx_find_pamt_refcount(pfn);
+
+	scoped_guard(spinlock, &pamt_lock) {
+		/*
+		 * If the pamt page is already added (i.e. refcount >= 1),
+		 * then just increment the refcount.
+		 */
+		if (atomic_read(pamt_refcount)) {
+			atomic_inc(pamt_refcount);
+			goto out_free;
+		}
+
+		/* Try to add the pamt page and take the refcount 0->1. */
+		tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
+		if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS)) {
+			ret = -EIO;
+			goto out_free;
+		}
+
+		atomic_set(pamt_refcount, 1);
 	}
 
 	return 0;
@@ -2069,26 +2089,46 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
 	return ret;
 }
 
-/* Free PAMT memory for the given page */
+/*
+ * Drop PAMT refcount for the given page and free PAMT memory if it is no
+ * longer needed.
+ */
 static void tdx_pamt_put(kvm_pfn_t pfn)
 {
 	struct page *pamt_pages[TDX_DPAMT_ENTRY_PAGE_CNT] = {};
+	atomic_t *pamt_refcount;
 	u64 tdx_status;
 
 	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
 		return;
 
-	tdx_status = tdh_phymem_pamt_remove(pfn, pamt_pages);
+	pamt_refcount = tdx_find_pamt_refcount(pfn);
 
-	/*
-	 * Don't free pamt_pages as it could hold garbage when
-	 * tdh_phymem_pamt_remove() fails.  Don't panic/BUG_ON(), as
-	 * there is no risk of data corruption, but do yell loudly as
-	 * failure indicates a kernel bug, memory is being leaked, and
-	 * the dangling PAMT entry may cause future operations to fail.
-	 */
-	if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS))
-		return;
+	scoped_guard(spinlock, &pamt_lock) {
+		/*
+		 * If the there are more than 1 references on the pamt page,
+		 * don't remove it yet. Just decrement the refcount.
+		 */
+		if (atomic_read(pamt_refcount) > 1) {
+			atomic_dec(pamt_refcount);
+			return;
+		}
+
+		/* Try to remove the pamt page and take the refcount 1->0. */
+		tdx_status = tdh_phymem_pamt_remove(pfn, pamt_pages);
+
+		/*
+		 * Don't free pamt_pages as it could hold garbage when
+		 * tdh_phymem_pamt_remove() fails.  Don't panic/BUG_ON(), as
+		 * there is no risk of data corruption, but do yell loudly as
+		 * failure indicates a kernel bug, memory is being leaked, and
+		 * the dangling PAMT entry may cause future operations to fail.
+		 */
+		if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS))
+			return;
+
+		atomic_set(pamt_refcount, 0);
+	}
 
 	free_pamt_array(pamt_pages);
 }
Signature · 1 line
2.54.0
Reviewed-by on v6 5/11
#42 lore raw

Re: [PATCH v6 05/11] x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

Quoted 18 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

tdx_pamt_get()/tdx_pamt_put() unconditionally add or remove Dynamic PAMT backing for the 2MB region covering the passed pfn. However, multiple callers can concurrently operate on 4KB pages that fall within the same 2MB region. When this happens only one Dynamic PAMT page pair needs to be installed to cover the 2MB range. And when one page is freed, the Dynamic PAMT backing cannot be freed until all pages in the range are no longer in use. Make the helpers handle these races internally.

Use the per-2MB refcounts from previous changes to track how many 4KB pages are in use within each region. Gate the actual Dynamic PAMT add and remove on refcount transitions (0->1 and 1->0). Serialize the refcount check and SEAMCALL with a global spinlock so the read-decide-act sequence is atomic. This also avoids TDX module BUSY errors, as Dynamic PAMT add and remove SEAMCALLs take an internal TDX module locks at 2MB granularity, so simultaneous attempts on the same region would conflict.

Quoted 7 lines

The lock is global and heavyweight. Use simple conditional logic to keep correctness obvious. This will be optimized in a later change.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

One nit below.

[...]

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2064

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +1 -4
@@ -2057,10 +2061,26 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
 	if (ret)
 		return ret;
 
-	tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
-	if (tdx_status != TDX_SUCCESS) {
-		ret = -EIO;
-		goto out_free;
+	pamt_refcount = tdx_find_pamt_refcount(pfn);

tdx_find_pamt_refcount() is tagged as __maybe_unused in the previous patch. I think the tag should be removed.

[...]

author maintainer
#43 lore raw

Re: [PATCH v6 05/11] x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

Quoted 33 lines · Binbin Wu
Quoted 18 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

tdx_pamt_get()/tdx_pamt_put() unconditionally add or remove Dynamic PAMT backing for the 2MB region covering the passed pfn. However, multiple callers can concurrently operate on 4KB pages that fall within the same 2MB region. When this happens only one Dynamic PAMT page pair needs to be installed to cover the 2MB range. And when one page is freed, the Dynamic PAMT backing cannot be freed until all pages in the range are no longer in use. Make the helpers handle these races internally.

Use the per-2MB refcounts from previous changes to track how many 4KB pages are in use within each region. Gate the actual Dynamic PAMT add and remove on refcount transitions (0->1 and 1->0). Serialize the refcount check and SEAMCALL with a global spinlock so the read-decide-act sequence is atomic. This also avoids TDX module BUSY errors, as Dynamic PAMT add and remove SEAMCALLs take an internal TDX module locks at 2MB granularity, so simultaneous attempts on the same region would conflict.

Quoted 7 lines

The lock is global and heavyweight. Use simple conditional logic to keep correctness obvious. This will be optimized in a later change.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

One nit below.

[...]

Quoted 13 lines

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2064

Quoted 10 lines

arch/x86/virt/vmx/tdx/tdx.c +0 -0
@@ -2057,10 +2061,26 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
   	if (ret)
   		return ret;

arch/x86/virt/vmx/tdx/tdx.c +1 -4
-	tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
-	if (tdx_status != TDX_SUCCESS) {
-		ret = -EIO;
-		goto out_free;
+	pamt_refcount = tdx_find_pamt_refcount(pfn);

tdx_find_pamt_refcount() is tagged as __maybe_unused in the previous patch. I think the tag should be removed.

Oh yea, that was the intention. Will fix.

Reviewed-by on v6 5/11
#44 lore raw

Re: [PATCH v6 05/11] x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

In reply to Rick Edgecombe

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2066

Quoted 11 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -4
@@ -2057,10 +2061,26 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
 	if (ret)
 		return ret;
 
-	tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
-	if (tdx_status != TDX_SUCCESS) {
-		ret = -EIO;
-		goto out_free;
+	pamt_refcount = tdx_find_pamt_refcount(pfn);
+
+	scoped_guard(spinlock, &pamt_lock) {

I am assuming you will convert this to plain lock/unlock as discussed.

With this fixed,

Reviewed-by on v6 5/11
#45 lore raw

Re: [PATCH v6 05/11] x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

In reply to Rick Edgecombe
Quoted 6 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

tdx_pamt_get()/tdx_pamt_put() unconditionally add or remove Dynamic PAMT backing for the 2MB region covering the passed pfn. However, multiple callers can concurrently operate on 4KB pages that fall within the same 2MB region. When this happens only one Dynamic PAMT page pair needs to be

What "this" stands for is not clear and a comma is missing after "happens".

Quoted 10 lines

installed to cover the 2MB range. And when one page is freed, the Dynamic PAMT backing cannot be freed until all pages in the range are no longer in use. Make the helpers handle these races internally.

Use the per-2MB refcounts from previous changes to track how many 4KB pages are in use within each region. Gate the actual Dynamic PAMT add and remove on refcount transitions (0->1 and 1->0). Serialize the refcount check and SEAMCALL with a global spinlock so the read-decide-act sequence is atomic. This also avoids TDX module BUSY errors, as Dynamic PAMT add and remove SEAMCALLs take an internal TDX module locks at 2MB granularity,

"an internal TDX module locks" --> "internal TDX module locks"?

Quoted 1 line

so simultaneous attempts on the same region would conflict.

How about:
"This also avoids TDX module BUSY errors, as Dynamic PAMT add and remove SEAMCALLs take internal TDX module locks for the 2MB ranges of the specified PFN and the PAMT page pair PFNs, so simultaneous attempts on the same 2MB ranges of the PFNs would conflict." ?

Quoted 26 lines

The lock is global and heavyweight. Use simple conditional logic to keep correctness obvious. This will be optimized in a later change.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

---
v6:
- Split from "x86/virt/tdx: Add tdx_alloc/free_control_page() helpers"
- Return 0 instead of ret to be clearer (Binbin)
- Clarify log (Nikolay)
- Justify why the patch is not optimized in response to comments by (Nikolay)
- Move tdx_find_pamt_refcount() to faciliate patch re-order
- Adjustments from dropping error helper patches
- Log tweaks

---
 arch/x86/virt/vmx/tdx/tdx.c | 72 ++++++++++++++++++++++++++++---------
 1 file changed, 56 insertions(+), 16 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +0 -0
index 6658a6be6697c..50333eb96efa6 100644

arch/x86/virt/vmx/tdx/tdx.c static u64 tdh_phymem_pamt_remove(kvm_pfn_t pfn, struct page **pamt_pages) · line 2049

Quoted 8 lines
arch/x86/virt/vmx/tdx/tdx.c +4 -1
@@ -2043,10 +2043,14 @@ static u64 tdh_phymem_pamt_remove(kvm_pfn_t pfn, struct page **pamt_pages)
 	return 0;
 }
 
-/* Allocate PAMT memory for the given page */
+/* Serializes adding/removing PAMT memory */
+static DEFINE_SPINLOCK(pamt_lock);
+
+/* Bump PAMT refcount for the given page and allocate PAMT memory if needed */

How about
"Bump the refcount of the PAMT page pair for the given PFN and add the PAMT page pair on the first reference." ?

Quoted 39 lines
arch/x86/virt/vmx/tdx/tdx.c +21 -4
 static int tdx_pamt_get(kvm_pfn_t pfn)
 {
 	struct page *pamt_pages[TDX_DPAMT_ENTRY_PAGE_CNT];
+	atomic_t *pamt_refcount;
 	u64 tdx_status;
 	int ret;
 
@@ -2057,10 +2061,26 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
 	if (ret)
 		return ret;
 
-	tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
-	if (tdx_status != TDX_SUCCESS) {
-		ret = -EIO;
-		goto out_free;
+	pamt_refcount = tdx_find_pamt_refcount(pfn);
+
+	scoped_guard(spinlock, &pamt_lock) {
+		/*
+		 * If the pamt page is already added (i.e. refcount >= 1),
+		 * then just increment the refcount.
+		 */
+		if (atomic_read(pamt_refcount)) {
+			atomic_inc(pamt_refcount);
+			goto out_free;
+		}
+
+		/* Try to add the pamt page and take the refcount 0->1. */
+		tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
+		if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS)) {
+			ret = -EIO;
+			goto out_free;
+		}
+
+		atomic_set(pamt_refcount, 1);
 	}
 
 	return 0;

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2094

Quoted 7 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -1
@@ -2069,26 +2089,46 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
 	return ret;
 }
 
-/* Free PAMT memory for the given page */
+/*
+ * Drop PAMT refcount for the given page and free PAMT memory if it is no
+ * longer needed.

How about:
"Drop the refcount of the PAMT page pair for the given PFN, and remove the PAMT page pair if it is no longer needed." ?

Quoted 15 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -3
+ */
 static void tdx_pamt_put(kvm_pfn_t pfn)
 {
 	struct page *pamt_pages[TDX_DPAMT_ENTRY_PAGE_CNT] = {};
+	atomic_t *pamt_refcount;
 	u64 tdx_status;
 
 	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
 		return;
 
-	tdx_status = tdh_phymem_pamt_remove(pfn, pamt_pages);
+	pamt_refcount = tdx_find_pamt_refcount(pfn);
 
-	/*
-	 * Don't free pamt_pages as it could hold garbage when

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2109

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -7
-	 * tdh_phymem_pamt_remove() fails.  Don't panic/BUG_ON(), as
-	 * there is no risk of data corruption, but do yell loudly as
-	 * failure indicates a kernel bug, memory is being leaked, and
-	 * the dangling PAMT entry may cause future operations to fail.
-	 */
-	if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS))
-		return;
+	scoped_guard(spinlock, &pamt_lock) {
+		/*
+		 * If the there are more than 1 references on the pamt page,

s/If the/If
s/references/reference

Quoted 15 lines
arch/x86/virt/vmx/tdx/tdx.c +15 -0
+		 * don't remove it yet. Just decrement the refcount.
+		 */
+		if (atomic_read(pamt_refcount) > 1) {
+			atomic_dec(pamt_refcount);
+			return;
+		}
+
+		/* Try to remove the pamt page and take the refcount 1->0. */
+		tdx_status = tdh_phymem_pamt_remove(pfn, pamt_pages);
+
+		/*
+		 * Don't free pamt_pages as it could hold garbage when
+		 * tdh_phymem_pamt_remove() fails.  Don't panic/BUG_ON(), as
+		 * there is no risk of data corruption, but do yell loudly as
+		 * failure indicates a kernel bug, memory is being leaked, and

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2134

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +7 -0
+		 * the dangling PAMT entry may cause future operations to fail.
+		 */
+		if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS))
+			return;
+
+		atomic_set(pamt_refcount, 0);
+	}
 
 	free_pamt_array(pamt_pages);
 }

Another nit:
How about renaming the title from
"Handle concurrent callers in tdx_pamt_get/put()" to "Handle concurrent calls to tdx_pamt_get/put()" ?

author maintainer
#46 lore raw

Re: [PATCH v6 05/11] x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

Thanks for the review!

Quoted 8 lines · Yan Zhao
Quoted 6 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

tdx_pamt_get()/tdx_pamt_put() unconditionally add or remove Dynamic PAMT backing for the 2MB region covering the passed pfn. However, multiple callers can concurrently operate on 4KB pages that fall within the same 2MB region. When this happens only one Dynamic PAMT page pair needs to be

What "this" stands for is not clear and a comma is missing after "happens".

Really this is not clear? The previous sentence is all about a senario being possible "multiple callers can concurrently operate on 4KB pages that fall within the same 2MB region". So I thought this would be clear.

I could say "When that scenario happens..."? But trying to keep the word count down.

Quoted 5 lines
Quoted 5 lines

installed to cover the 2MB range. And when one page is freed, the Dynamic PAMT backing cannot be freed until all pages in the range are no longer in use. Make the helpers handle these races internally.

Quoted 7 lines
Quoted 6 lines

Use the per-2MB refcounts from previous changes to track how many 4KB pages are in use within each region. Gate the actual Dynamic PAMT add and remove on refcount transitions (0->1 and 1->0). Serialize the refcount check and SEAMCALL with a global spinlock so the read-decide-act sequence is atomic. This also avoids TDX module BUSY errors, as Dynamic PAMT add and remove SEAMCALLs take an internal TDX module locks at 2MB granularity,

"an internal TDX module locks" --> "internal TDX module locks"?

Yep, thanks.

Quoted 7 lines
Quoted 2 lines

so simultaneous attempts on the same region would conflict.

How about:
"This also avoids TDX module BUSY errors, as Dynamic PAMT add and remove SEAMCALLs take internal TDX module locks for the 2MB ranges of the specified PFN and the PAMT page pair PFNs, so simultaneous attempts on the same 2MB ranges of the PFNs would conflict." ?

Hmm, yea.

Quoted 31 lines
Quoted 31 lines

The lock is global and heavyweight. Use simple conditional logic to keep correctness obvious. This will be optimized in a later change.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

---
v6:
- Split from "x86/virt/tdx: Add tdx_alloc/free_control_page() helpers"
- Return 0 instead of ret to be clearer (Binbin)
- Clarify log (Nikolay)
- Justify why the patch is not optimized in response to comments by (Nikolay)
- Move tdx_find_pamt_refcount() to faciliate patch re-order
- Adjustments from dropping error helper patches
- Log tweaks

---
 arch/x86/virt/vmx/tdx/tdx.c | 72 ++++++++++++++++++++++++++++---------
 1 file changed, 56 insertions(+), 16 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +0 -0
index 6658a6be6697c..50333eb96efa6 100644
@@ -2043,10 +2043,14 @@ static u64 tdh_phymem_pamt_remove(kvm_pfn_t pfn, struct page **pamt_pages)
 	return 0;
 }
 
Quoted 8 lines

arch/x86/virt/vmx/tdx/tdx.c static u64 tdh_phymem_pamt_remove(kvm_pfn_t pfn, struct page **pamt_pages) · line 2049

Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +4 -1
-/* Allocate PAMT memory for the given page */
+/* Serializes adding/removing PAMT memory */
+static DEFINE_SPINLOCK(pamt_lock);
+
+/* Bump PAMT refcount for the given page and allocate PAMT memory if needed */

How about
"Bump the refcount of the PAMT page pair for the given PFN and add the PAMT page pair on the first reference." ?

I think I see what you are getting at. How about this instead:
Bump PAMT refcount for the given pfn and allocate PAMT backing if needed

Quoted 43 lines
Quoted 43 lines
arch/x86/virt/vmx/tdx/tdx.c +21 -4
 static int tdx_pamt_get(kvm_pfn_t pfn)
 {
 	struct page *pamt_pages[TDX_DPAMT_ENTRY_PAGE_CNT];
+	atomic_t *pamt_refcount;
 	u64 tdx_status;
 	int ret;
 
@@ -2057,10 +2061,26 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
 	if (ret)
 		return ret;
 
-	tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
-	if (tdx_status != TDX_SUCCESS) {
-		ret = -EIO;
-		goto out_free;
+	pamt_refcount = tdx_find_pamt_refcount(pfn);
+
+	scoped_guard(spinlock, &pamt_lock) {
+		/*
+		 * If the pamt page is already added (i.e. refcount >= 1),
+		 * then just increment the refcount.
+		 */
+		if (atomic_read(pamt_refcount)) {
+			atomic_inc(pamt_refcount);
+			goto out_free;
+		}
+
+		/* Try to add the pamt page and take the refcount 0->1. */
+		tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
+		if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS)) {
+			ret = -EIO;
+			goto out_free;
+		}
+
+		atomic_set(pamt_refcount, 1);
 	}
 
 	return 0;
@@ -2069,26 +2089,46 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
 	return ret;
 }
 
Quoted 7 lines

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2094

Quoted 4 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -1
-/* Free PAMT memory for the given page */
+/*
+ * Drop PAMT refcount for the given page and free PAMT memory if it is no
+ * longer needed.

How about:
"Drop the refcount of the PAMT page pair for the given PFN, and remove the PAMT page pair if it is no longer needed." ?

Matching the above:

Drop PAMT refcount for the given pfn and free PAMT backing if needed

Quoted 14 lines
Quoted 14 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -1
+ */
 static void tdx_pamt_put(kvm_pfn_t pfn)
 {
 	struct page *pamt_pages[TDX_DPAMT_ENTRY_PAGE_CNT] = {};
+	atomic_t *pamt_refcount;
 	u64 tdx_status;
 
 	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
 		return;
 
-	tdx_status = tdh_phymem_pamt_remove(pfn, pamt_pages);
+	pamt_refcount = tdx_find_pamt_refcount(pfn);
 
Quoted 14 lines

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2109

Quoted 12 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -9
-	/*
-	 * Don't free pamt_pages as it could hold garbage when
-	 * tdh_phymem_pamt_remove() fails.  Don't panic/BUG_ON(), as
-	 * there is no risk of data corruption, but do yell loudly as
-	 * failure indicates a kernel bug, memory is being leaked, and
-	 * the dangling PAMT entry may cause future operations to fail.
-	 */
-	if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS))
-		return;
+	scoped_guard(spinlock, &pamt_lock) {
+		/*
+		 * If the there are more than 1 references on the pamt page,

s/If the/If
s/references/reference

Yep, thanks.

Quoted 24 lines
Quoted 24 lines
arch/x86/virt/vmx/tdx/tdx.c +22 -0
+		 * don't remove it yet. Just decrement the refcount.
+		 */
+		if (atomic_read(pamt_refcount) > 1) {
+			atomic_dec(pamt_refcount);
+			return;
+		}
+
+		/* Try to remove the pamt page and take the refcount 1->0. */
+		tdx_status = tdh_phymem_pamt_remove(pfn, pamt_pages);
+
+		/*
+		 * Don't free pamt_pages as it could hold garbage when
+		 * tdh_phymem_pamt_remove() fails.  Don't panic/BUG_ON(), as
+		 * there is no risk of data corruption, but do yell loudly as
+		 * failure indicates a kernel bug, memory is being leaked, and
+		 * the dangling PAMT entry may cause future operations to fail.
+		 */
+		if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS))
+			return;
+
+		atomic_set(pamt_refcount, 0);
+	}
 
Quoted 7 lines

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2134

Quoted 2 lines
arch/x86/virt/vmx/tdx/tdx.c +0 -0
 	free_pamt_array(pamt_pages);
 }

Another nit:
How about renaming the title from
"Handle concurrent callers in tdx_pamt_get/put()" to "Handle concurrent calls to tdx_pamt_get/put()" ?

I'm not seeing a benefit. Just because it's shorter?

Quoted 3 lines
#47 lore raw

Re: [PATCH v6 05/11] x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

Quoted 10 lines · Rick P

Thanks for the review!

Quoted 7 lines · Yan Zhao
Quoted 6 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

tdx_pamt_get()/tdx_pamt_put() unconditionally add or remove Dynamic PAMT backing for the 2MB region covering the passed pfn. However, multiple callers can concurrently operate on 4KB pages that fall within the same 2MB region. When this happens only one Dynamic PAMT page pair needs to be

Quoted 5 lines
Quoted 1 line

What "this" stands for is not clear and a comma is missing after "happens".

Really this is not clear? The previous sentence is all about a senario being possible "multiple callers can concurrently operate on 4KB pages that fall within the same 2MB region". So I thought this would be clear.

Hmm, sorry for nitpicking.
But the previous sentence says "multiple callers can concurrently operate on 4KB pages", where "operate" doesn't necessarily imply allocating pages. However, the latter sentence assumes PAMT pages need to be installed. That's why I think "it" is not clear.

Quoted 2 lines

I could say "When that scenario happens..."? But trying to keep the word count down.

...

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

+/* Bump PAMT refcount for the given page and allocate PAMT memory if needed */

How about
"Bump the refcount of the PAMT page pair for the given PFN and add the PAMT page pair on the first reference." ?

I think I see what you are getting at. How about this instead:
Bump PAMT refcount for the given pfn and allocate PAMT backing if needed

Hmm, in this patch, "allocate PAMT backing" is always performed. Only "add PAMT backing" is "if needed".
That's my reasoning. :)

And I can understand that "PAMT refcount" refers to the refcount of the PAMT page pair. I just thought it would be clear to call this out explicitly. No strong opinion though.

Quoted 50 lines
Quoted 42 lines
Quoted 42 lines

static int tdx_pamt_get(kvm_pfn_t pfn)
{

arch/x86/virt/vmx/tdx/tdx.c +21 -4
 	struct page *pamt_pages[TDX_DPAMT_ENTRY_PAGE_CNT];
+	atomic_t *pamt_refcount;
 	u64 tdx_status;
 	int ret;
@@ -2057,10 +2061,26 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
 	if (ret)
 		return ret;
 
-	tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
-	if (tdx_status != TDX_SUCCESS) {
-		ret = -EIO;
-		goto out_free;
+	pamt_refcount = tdx_find_pamt_refcount(pfn);
+
+	scoped_guard(spinlock, &pamt_lock) {
+		/*
+		 * If the pamt page is already added (i.e. refcount >= 1),
+		 * then just increment the refcount.
+		 */
+		if (atomic_read(pamt_refcount)) {
+			atomic_inc(pamt_refcount);
+			goto out_free;
+		}
+
+		/* Try to add the pamt page and take the refcount 0->1. */
+		tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
+		if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS)) {
+			ret = -EIO;
+			goto out_free;
+		}
+
+		atomic_set(pamt_refcount, 1);
 	}
 
 	return 0;
@@ -2069,26 +2089,46 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
 	return ret;
 }
 
Quoted 7 lines

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2094

Quoted 4 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -1
-/* Free PAMT memory for the given page */
+/*
+ * Drop PAMT refcount for the given page and free PAMT memory if it is no
+ * longer needed.

How about:
"Drop the refcount of the PAMT page pair for the given PFN, and remove the PAMT page pair if it is no longer needed." ?

Quoted 3 lines

Matching the above:

Drop PAMT refcount for the given pfn and free PAMT backing if needed

LGTM.

Quoted 6 lines
Quoted 4 lines

Another nit:
How about renaming the title from
"Handle concurrent callers in tdx_pamt_get/put()" to "Handle concurrent calls to tdx_pamt_get/put()" ?

I'm not seeing a benefit. Just because it's shorter?

I previously thought "callers in" sounded odd.
Feel free to ignore it if it is not :)

author maintainer
#48 lore raw

Re: [PATCH v6 05/11] x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

Quoted 8 lines · Yan Zhao
Quoted 8 lines
Quoted 7 lines
Quoted 5 lines

tdx_pamt_get()/tdx_pamt_put() unconditionally add or remove Dynamic PAMT backing for the 2MB region covering the passed pfn. However, multiple callers can concurrently operate on 4KB pages that fall within the same 2MB region. When this happens only one Dynamic PAMT page pair needs to be

What "this" stands for is not clear and a comma is missing after "happens".

Quoted 8 lines
Quoted 3 lines

Really this is not clear? The previous sentence is all about a senario being possible "multiple callers can concurrently operate on 4KB pages that fall within the same 2MB region". So I thought this would be clear.

Hmm, sorry for nitpicking.
But the previous sentence says "multiple callers can concurrently operate on 4KB pages", where "operate" doesn't necessarily imply allocating pages. However, the latter sentence assumes PAMT pages need to be installed. That's why I think "it" is not clear.

Not sure what you mean by "it", but I guess you are saying that "this" could refer to the first sentence and not the one that immediately preceded the "this" reference? That part still reads ok to me, but if you still feel it's unclear I'll change it to.

Actually, another problem with this paragraph is focuses too much on concurrent callers, when the main thing this patch does is address get-ing multiple pages. The concurrency is added to make the refcounts work. I'd like to address that too. How is this to you?

x86/virt/tdx: Handle multiple callers in tdx_pamt_get/put()

tdx_pamt_get()/tdx_pamt_put() unconditionally add or remove Dynamic PAMT backing for the 2MB region covering the passed page. However, multiple callers can add or remove 4KB pages that fall within the same 2MB region and in that scenario only a single PAMT entry is required.

Make the helpers handle only adding/removing Dynamic PAMT backing when required, by refcounting each 2MB range. Gate the actual Dynamic PAMT add and remove on refcount transitions (0->1 and 1->0). Serialize the refcount check and SEAMCALL with a global spinlock so the read-decide-act sequence is atomic. This also avoids TDX module BUSY errors, as the Dynamic PAMT add and remove SEAMCALLs take internal TDX module locks for the 2MB ranges of the specified PFN and the PAMT page pair PFNs. So simultaneous attempts on the same 2MB ranges of the PFNs would otherwise encounter and error, which would not be handleable in the put case.

The lock is global and heavyweight. Use simple conditional logic to keep correctness obvious. This will be optimized in a later change.

The pamt_refcount[]s are atomic_t's. They do not strictly need to be because all access is protected by pamt_lock. The overhead of an atomic_t in this situation is minuscule compared to the global lock. Leave the atomic_t in place to enable future optimization with minimal churn.

#49 lore raw

Re: [PATCH v6 05/11] x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

Quoted 12 lines · Rick P
Quoted 11 lines · Yan Zhao
Quoted 11 lines
Quoted 7 lines
Quoted 5 lines

tdx_pamt_get()/tdx_pamt_put() unconditionally add or remove Dynamic PAMT backing for the 2MB region covering the passed pfn. However, multiple callers can concurrently operate on 4KB pages that fall within the same 2MB region. When this happens only one Dynamic PAMT page pair needs to be

What "this" stands for is not clear and a comma is missing after "happens".

Really this is not clear? The previous sentence is all about a senario being possible "multiple callers can concurrently operate on 4KB pages that fall within the same 2MB region". So I thought this would be clear.

Quoted 7 lines
Quoted 5 lines

Hmm, sorry for nitpicking.
But the previous sentence says "multiple callers can concurrently operate on 4KB pages", where "operate" doesn't necessarily imply allocating pages. However, the latter sentence assumes PAMT pages need to be installed. That's why I think "it" is not clear.

Not sure what you mean by "it", but I guess you are saying that "this" could

Oh, yes, "this"! :D

Quoted 8 lines

refer to the first sentence and not the one that immediately preceded the "this" reference? That part still reads ok to me, but if you still feel it's unclear I'll change it to.

Actually, another problem with this paragraph is focuses too much on concurrent callers, when the main thing this patch does is address get-ing multiple pages. The concurrency is added to make the refcounts work. I'd like to address that too. How is this to you?

This version looks great!
Thanks!

Quoted 17 lines

x86/virt/tdx: Handle multiple callers in tdx_pamt_get/put()

tdx_pamt_get()/tdx_pamt_put() unconditionally add or remove Dynamic PAMT backing for the 2MB region covering the passed page. However, multiple callers can add or remove 4KB pages that fall within the same 2MB region and in that scenario only a single PAMT entry is required.

Make the helpers handle only adding/removing Dynamic PAMT backing when required, by refcounting each 2MB range. Gate the actual Dynamic PAMT add and remove on refcount transitions (0->1 and 1->0). Serialize the refcount check and SEAMCALL with a global spinlock so the read-decide-act sequence is atomic. This also avoids TDX module BUSY errors, as the Dynamic PAMT add and remove SEAMCALLs take internal TDX module locks for the 2MB ranges of the specified PFN and the PAMT page pair PFNs. So simultaneous attempts on the same 2MB ranges of the PFNs would otherwise encounter and error, which would not be handleable in the put case.

Quoted 4 lines

The lock is global and heavyweight. Use simple conditional logic to keep correctness obvious. This will be optimized in a later change.

The pamt_refcount[]s are atomic_t's. They do not strictly need to be

Nit: Not sure if it's correct.
Just in case it's a typo: pamt_refcounts[].

Quoted 3 lines

because all access is protected by pamt_lock. The overhead of an atomic_t in this situation is minuscule compared to the global lock. Leave the atomic_t in place to enable future optimization with minimal churn.

#50 lore raw

Re: [PATCH v6 05/11] x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

In reply to Rick Edgecombe

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2074

Quoted 9 lines · Rick Edgecombe
arch/x86/virt/vmx/tdx/tdx.c +9 -0
+	scoped_guard(spinlock, &pamt_lock) {
+		/*
+		 * If the pamt page is already added (i.e. refcount >= 1),
+		 * then just increment the refcount.
+		 */
+		if (atomic_read(pamt_refcount)) {
+			atomic_inc(pamt_refcount);
+			goto out_free;
+		}

I think this pattern is a good fit for atomic_inc_not_zero().

I think it's also fair to say that using an atomic_t here is unnecessary because of the spinlock protecting all accesses. But I also understand that it's here because you want to optimize this path to avoid the spinlock in the future.

This is not a hot enough path to care about an atomic_t vs. int. In practice, the performance is going to be bottlenecked on the big spinlock, *not* the atomic_t overhead.

I'd just add a changelog blurb to handwave it away for the moment:

The pamt_refcount[]s are atomic_t's. They do not strictly need to be because all access is protected by pamt_lock. The overhead of an atomic_t in this situation is minuscule compared to the global lock. Leave the (unnecessary) atomic_t in place to enable future optimization with minimal churn.

Does that work for everybody?

author maintainer
#51 lore raw

Re: [PATCH v6 05/11] x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

Quoted 12 lines · Dave Hansen

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2074

Quoted 9 lines · Rick Edgecombe
arch/x86/virt/vmx/tdx/tdx.c +9 -0
+	scoped_guard(spinlock, &pamt_lock) {
+		/*
+		 * If the pamt page is already added (i.e. refcount >= 1),
+		 * then just increment the refcount.
+		 */
+		if (atomic_read(pamt_refcount)) {
+			atomic_inc(pamt_refcount);
+			goto out_free;
+		}

I think this pattern is a good fit for atomic_inc_not_zero().

Sure. The intention was to make this one as obviously correct as possible and I thought to leverage the most familiar concepts of read/inc/if.

Quoted 12 lines

I think it's also fair to say that using an atomic_t here is unnecessary because of the spinlock protecting all accesses. But I also understand that it's here because you want to optimize this path to avoid the spinlock in the future.

This is not a hot enough path to care about an atomic_t vs. int. In practice, the performance is going to be bottlenecked on the big spinlock, *not* the atomic_t overhead.

I'd just add a changelog blurb to handwave it away for the moment:

Quoted 7 lines

The pamt_refcount[]s are atomic_t's. They do not strictly need to be because all access is protected by pamt_lock. The overhead of an atomic_t in this situation is minuscule compared to the global lock. Leave the (unnecessary) atomic_t in place to enable future optimization with minimal churn.

Does that work for everybody?

Works for me, thanks.

#52 lore raw

Re: [PATCH v6 05/11] x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

Quoted 8 lines
Quoted 8 lines

I'd just add a changelog blurb to handwave it away for the moment:

The pamt_refcount[]s are atomic_t's. They do not strictly need to be because all access is protected by pamt_lock. The overhead of an atomic_t in this situation is minuscule compared to the global lock. Leave the (unnecessary) atomic_t in place to enable future optimization with minimal churn.

The atomic_t is introduced primarily by this patch (and slightly by the previous one).

Instead of "Leave the atomic_t in place", would it be more appropriate to say "Use an (unnecessary) atomic_t to enable future ..."?

Quoted 2 lines
Quoted 1 line

Does that work for everybody?

Yes, this works.

Quoted 1 line

Works for me, thanks.

#53 lore raw

Re: [PATCH v6 05/11] x86/virt/tdx: Handle concurrent callers in tdx_pamt_get/put()

Quoted 2 lines · Sohil Mehta

Instead of "Leave the atomic_t in place", would it be more appropriate to say "Use an (unnecessary) atomic_t to enable future ..."?

That reads fine to me.

author maintainer
#54 lore raw

PATCH v6 6/11 x86/virt/tdx: Optimize tdx_pamt_get/put()

In reply to Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The Dynamic PAMT get/put helpers use a global spinlock to serialize all refcount updates and SEAMCALL invocations. This gives correct behavior for concurrent callers, but leads to contention. It is especially bad from the KVM side, which is designed to allow faulting in EPT under a shared lock. With the global spinlock, not only is the lock an exclusive one, but it is for all TDs instead of just a single one.

But taking the global lock each time is actually unnecessary. Only the 0->1 and 1->0 refcount transitions actually need the lock (to pair with SEAMCALLs that actually add and remove with the Dynamic PAMT pages). The common case of incrementing or decrementing a non-zero refcount can be done locklessly.

So create a fast and slow path. Check the refcount outside the lock and only take it for the slowpath (0->1 and 1->0 transitions).

On the put side make the refcount adjustment and lock taking atomic so if a 'get' happens between them, it doesn't cause the Dynamic PAMT to be freed incorrectly. On the get side there is no technique for doing the refcount adjustment and lock atomically, so check the refcount again inside the lock.

Assisted-by GitHub Copilot:claude-opus-4-6

---
v6:
- Fix "tdx_pamt_add()" typo to "tdx_pamt_get()" in lost-race comment
- Fix error path bug: set ret = -EIO and use WARN_ON_ONCE() instead of pr_err() for unexpected PAMT.ADD failures (Sean)
- Use "set the refcount 0->1" wording to match atomic_set() usage
- Wrap comments to 80 columns
- Switch to atomic_dec_and_lock() and remove handling of races that are no longer needed as a result. Adjust comments as appropriate. (Dave)
- Adjustments from dropping error helper patches
v4:
- Use atomic_set() in the HPA_RANGE_NOT_FREE case (Kiryl)
- Log, comment typos (Binbin)
- Move PAMT page allocation after refcount check in tdx_pamt_get() to avoid an alloc/free in the common path.

v3:
- Split out optimization from “x86/virt/tdx: Add tdx_alloc/free_page() helpers”
- Remove edge case handling that I could not find a reason for
- Write log

---
 arch/x86/virt/vmx/tdx/tdx.c | 102 +++++++++++++++++++++---------------
 1 file changed, 61 insertions(+), 41 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +61 -41
index 50333eb96efa6..c41c632a4cdf2 100644
@@ -2057,32 +2057,50 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
 	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
 		return 0;
 
+	pamt_refcount = tdx_find_pamt_refcount(pfn);
+
+	/*
+	 * If the pamt page is already added (i.e. refcount >= 1),
+	 * then just increment the refcount.
+	 */
+	if (atomic_inc_not_zero(pamt_refcount))
+		return 0;
+
 	ret = alloc_pamt_array(pamt_pages);
 	if (ret)
 		return ret;
 
-	pamt_refcount = tdx_find_pamt_refcount(pfn);
+	spin_lock(&pamt_lock);
 
-	scoped_guard(spinlock, &pamt_lock) {
-		/*
-		 * If the pamt page is already added (i.e. refcount >= 1),
-		 * then just increment the refcount.
-		 */
-		if (atomic_read(pamt_refcount)) {
-			atomic_inc(pamt_refcount);
-			goto out_free;
-		}
-
-		/* Try to add the pamt page and take the refcount 0->1. */
-		tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
-		if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS)) {
-			ret = -EIO;
-			goto out_free;
-		}
-
-		atomic_set(pamt_refcount, 1);
+	/*
+	 * Unlike tdx_pamt_put() which uses atomic_dec_and_lock() to
+	 * atomically handle the 1->0 transition, the get side has no
+	 * equivalent combined primitive for 0->1. Recheck under the
+	 * lock since another get may have already done the 0->1
+	 * transition after both saw atomic_inc_not_zero() fail.
+	 */
+	if (atomic_read(pamt_refcount)) {
+		atomic_inc(pamt_refcount);
+		spin_unlock(&pamt_lock);
+		goto out_free;
 	}
 
+	tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
+	if (tdx_status == TDX_SUCCESS) {
+		/*
+		 * The refcount is zero, and this locked path is the
+		 * only way to increase it from 0->1.
+		 */
+		atomic_set(pamt_refcount, 1);
+	} else {
+		WARN_ON_ONCE(1);
+		ret = -EIO;
+		spin_unlock(&pamt_lock);
+		goto out_free;
+	}
+
+	spin_unlock(&pamt_lock);
+
 	return 0;
 out_free:
 	free_pamt_array(pamt_pages);
@@ -2104,32 +2122,34 @@ static void tdx_pamt_put(kvm_pfn_t pfn)
 
 	pamt_refcount = tdx_find_pamt_refcount(pfn);
 
-	scoped_guard(spinlock, &pamt_lock) {
+	/*
+	 * If there is more than 1 reference on the pamt page, don't
+	 * remove it yet. Just decrement the refcount.
+	 */
+	if (!atomic_dec_and_lock(pamt_refcount, &pamt_lock))
+		return;
+
+	tdx_status = tdh_phymem_pamt_remove(pfn, pamt_pages);
+
+	/*
+	 * Don't free pamt_pages as it could hold garbage when
+	 * tdh_phymem_pamt_remove() fails.  Don't panic/BUG_ON(), as
+	 * there is no risk of data corruption, but do yell loudly as
+	 * failure indicates a kernel bug, memory is being leaked, and
+	 * the dangling PAMT entry may cause future operations to fail.
+	 */
+	if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS)) {
 		/*
-		 * If the there are more than 1 references on the pamt page,
-		 * don't remove it yet. Just decrement the refcount.
+		 * atomic_dec_and_lock() already decremented it to 0,
+		 * but the PAMT entry still exists since REMOVE failed.
 		 */
-		if (atomic_read(pamt_refcount) > 1) {
-			atomic_dec(pamt_refcount);
-			return;
-		}
-
-		/* Try to remove the pamt page and take the refcount 1->0. */
-		tdx_status = tdh_phymem_pamt_remove(pfn, pamt_pages);
-
-		/*
-		 * Don't free pamt_pages as it could hold garbage when
-		 * tdh_phymem_pamt_remove() fails.  Don't panic/BUG_ON(), as
-		 * there is no risk of data corruption, but do yell loudly as
-		 * failure indicates a kernel bug, memory is being leaked, and
-		 * the dangling PAMT entry may cause future operations to fail.
-		 */
-		if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS))
-			return;
-
-		atomic_set(pamt_refcount, 0);
+		atomic_set(pamt_refcount, 1);
+		spin_unlock(&pamt_lock);
+		return;
 	}
 
+	spin_unlock(&pamt_lock);
+
 	free_pamt_array(pamt_pages);
 }
 
Signature · 1 line
2.54.0
#55 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

Quoted 11 lines · Rick Edgecombe
arch/x86/virt/vmx/tdx/tdx.c +7 -0
@@ -2057,32 +2057,50 @@ static int tdx_pamt_get(kvm_pfn_t pfn)
 	if (!tdx_supports_dynamic_pamt(&tdx_sysinfo))
 		return 0;
 
+	pamt_refcount = tdx_find_pamt_refcount(pfn);
+
+	/*
+	 * If the pamt page is already added (i.e. refcount >= 1),
+	 * then just increment the refcount.
+	 */
+	if (atomic_inc_not_zero(pamt_refcount))

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2066

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -2
+		return 0;
+
 	ret = alloc_pamt_array(pamt_pages);
 	if (ret)
 		return ret;
 
-	pamt_refcount = tdx_find_pamt_refcount(pfn);
+	spin_lock(&pamt_lock);
 
-	scoped_guard(spinlock, &pamt_lock) {

This converts the scoped_guard() added by the previous patch to explicit lock/unlock and goto. It would reduce code churn if the previous patch used that form directly.

Quoted 50 lines
arch/x86/virt/vmx/tdx/tdx.c +27 -17
-		/*
-		 * If the pamt page is already added (i.e. refcount >= 1),
-		 * then just increment the refcount.
-		 */
-		if (atomic_read(pamt_refcount)) {
-			atomic_inc(pamt_refcount);
-			goto out_free;
-		}
-
-		/* Try to add the pamt page and take the refcount 0->1. */
-		tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
-		if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS)) {
-			ret = -EIO;
-			goto out_free;
-		}
-
-		atomic_set(pamt_refcount, 1);
+	/*
+	 * Unlike tdx_pamt_put() which uses atomic_dec_and_lock() to
+	 * atomically handle the 1->0 transition, the get side has no
+	 * equivalent combined primitive for 0->1. Recheck under the
+	 * lock since another get may have already done the 0->1
+	 * transition after both saw atomic_inc_not_zero() fail.
+	 */
+	if (atomic_read(pamt_refcount)) {
+		atomic_inc(pamt_refcount);
+		spin_unlock(&pamt_lock);
+		goto out_free;
 	}
 
+	tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
+	if (tdx_status == TDX_SUCCESS) {
+		/*
+		 * The refcount is zero, and this locked path is the
+		 * only way to increase it from 0->1.
+		 */
+		atomic_set(pamt_refcount, 1);
+	} else {
+		WARN_ON_ONCE(1);
+		ret = -EIO;
+		spin_unlock(&pamt_lock);
+		goto out_free;
+	}
+
+	spin_unlock(&pamt_lock);
+
 	return 0;

out_free:

	free_pamt_array(pamt_pages);

arch/x86/virt/vmx/tdx/tdx.c static void tdx_pamt_put(kvm_pfn_t pfn) · line 2107

Quoted 4 lines
arch/x86/virt/vmx/tdx/tdx.c +0 -1
@@ -2104,32 +2122,34 @@ static void tdx_pamt_put(kvm_pfn_t pfn)
 
 	pamt_refcount = tdx_find_pamt_refcount(pfn);
 
-	scoped_guard(spinlock, &pamt_lock) {

Ditto

Quoted 55 lines
arch/x86/virt/vmx/tdx/tdx.c +24 -21
+	/*
+	 * If there is more than 1 reference on the pamt page, don't
+	 * remove it yet. Just decrement the refcount.
+	 */
+	if (!atomic_dec_and_lock(pamt_refcount, &pamt_lock))
+		return;
+
+	tdx_status = tdh_phymem_pamt_remove(pfn, pamt_pages);
+
+	/*
+	 * Don't free pamt_pages as it could hold garbage when
+	 * tdh_phymem_pamt_remove() fails.  Don't panic/BUG_ON(), as
+	 * there is no risk of data corruption, but do yell loudly as
+	 * failure indicates a kernel bug, memory is being leaked, and
+	 * the dangling PAMT entry may cause future operations to fail.
+	 */
+	if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS)) {
 		/*
-		 * If the there are more than 1 references on the pamt page,
-		 * don't remove it yet. Just decrement the refcount.
+		 * atomic_dec_and_lock() already decremented it to 0,
+		 * but the PAMT entry still exists since REMOVE failed.
 		 */
-		if (atomic_read(pamt_refcount) > 1) {
-			atomic_dec(pamt_refcount);
-			return;
-		}
-
-		/* Try to remove the pamt page and take the refcount 1->0. */
-		tdx_status = tdh_phymem_pamt_remove(pfn, pamt_pages);
-
-		/*
-		 * Don't free pamt_pages as it could hold garbage when
-		 * tdh_phymem_pamt_remove() fails.  Don't panic/BUG_ON(), as
-		 * there is no risk of data corruption, but do yell loudly as
-		 * failure indicates a kernel bug, memory is being leaked, and
-		 * the dangling PAMT entry may cause future operations to fail.
-		 */
-		if (WARN_ON_ONCE(tdx_status != TDX_SUCCESS))
-			return;
-
-		atomic_set(pamt_refcount, 0);
+		atomic_set(pamt_refcount, 1);
+		spin_unlock(&pamt_lock);
+		return;
 	}
 
+	spin_unlock(&pamt_lock);
+
 	free_pamt_array(pamt_pages);
 }
 
Signature · 1 line
2.54.0
author maintainer
#56 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

Quoted 5 lines · Chao Gao

Review

Quoted 1 line
(quoted diff) +0 -1
-	scoped_guard(spinlock, &pamt_lock) {

This converts the scoped_guard() added by the previous patch to explicit lock/unlock and goto. It would reduce code churn if the previous patch used that form directly.

Yea, it's a good point. I actually debated doing it, but decided not to because the scoped version is cleaner for the non-optimized version. But for reviewability, never doing the scoped version is probably better.

maintainer
#57 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

Quoted 10 lines · Rick P
Quoted 5 lines · Chao Gao

Review

Quoted 1 line
(quoted diff) +0 -1
-	scoped_guard(spinlock, &pamt_lock) {

This converts the scoped_guard() added by the previous patch to explicit lock/unlock and goto. It would reduce code churn if the previous patch used that form directly.

Yea, it's a good point. I actually debated doing it, but decided not to because the scoped version is cleaner for the non-optimized version. But for reviewability, never doing the scoped version is probably better.

I don't see a reason why we can't keep the scoped_guard() on get side.

On put side, we cannot get atomic_get_and_lock() semantics without dropping the scoped_guard().

Maybe we should keep it for get?

Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
#58 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

Quoted 8 lines · Kiryl Shutsemau
Quoted 7 lines · Rick P
Quoted 5 lines · Chao Gao

Review

Quoted 1 line
(quoted diff) +0 -1
-	scoped_guard(spinlock, &pamt_lock) {

This converts the scoped_guard() added by the previous patch to explicit lock/unlock and goto. It would reduce code churn if the previous patch used that form directly.

Quoted 5 lines
Quoted 3 lines

Yea, it's a good point. I actually debated doing it, but decided not to because the scoped version is cleaner for the non-optimized version. But for reviewability, never doing the scoped version is probably better.

I don't see a reason why we can't keep the scoped_guard() on get side.

One additional reason to drop scoped_guard() is that it mixes cleanup helpers with goto, which is discouraged. See [*]

:Lastly, given that the benefit of cleanup helpers is removal of “goto”, and :that the “goto” statement can jump between scopes, the expectation is that :usage of “goto” and cleanup helpers is never mixed in the same function.

Removing scoped_guard() here also reduces indentation.

*: https://www.kernel.org/doc/html/v7.1-rc6/core-api/cleanup.html

Quoted 8 lines

On put side, we cannot get atomic_get_and_lock() semantics without dropping the scoped_guard().

Maybe we should keep it for get?

Signature · 1 line
 Kiryl Shutsemau / Kirill A. Shutemov
maintainer
#59 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

Quoted 13 lines · Chao Gao
Quoted 12 lines · Kiryl Shutsemau
Quoted 10 lines · Rick P
Quoted 5 lines · Chao Gao

Review

Quoted 1 line
(quoted diff) +0 -1
-	scoped_guard(spinlock, &pamt_lock) {

This converts the scoped_guard() added by the previous patch to explicit lock/unlock and goto. It would reduce code churn if the previous patch used that form directly.

Yea, it's a good point. I actually debated doing it, but decided not to because the scoped version is cleaner for the non-optimized version. But for reviewability, never doing the scoped version is probably better.

Quoted 8 lines
Quoted 1 line

I don't see a reason why we can't keep the scoped_guard() on get side.

One additional reason to drop scoped_guard() is that it mixes cleanup helpers with goto, which is discouraged. See [*]

:Lastly, given that the benefit of cleanup helpers is removal of “goto”, and :that the “goto” statement can jump between scopes, the expectation is that :usage of “goto” and cleanup helpers is never mixed in the same function.

Fair enough.

But it can also be address if we free the PAMT page array with the guard too :P

Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
#60 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

Quoted 11 lines · Kiryl Shutsemau
Quoted 7 lines
Quoted 1 line

I don't see a reason why we can't keep the scoped_guard() on get side.

One additional reason to drop scoped_guard() is that it mixes cleanup helpers with goto, which is discouraged. See [*]

:Lastly, given that the benefit of cleanup helpers is removal of “goto”, and :that the “goto” statement can jump between scopes, the expectation is that :usage of “goto” and cleanup helpers is never mixed in the same function.

Fair enough.

But it can also be address if we free the PAMT page array with the guard too :P

How important is this patch? I see "Optimize" but I read "Optional".

If we're arguing about it, maybe we should just kick it out and focus on the more important bits.

maintainer
#61 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

Quoted 10 lines · Dave Hansen
Quoted 9 lines · Kiryl Shutsemau
Quoted 7 lines
Quoted 1 line

I don't see a reason why we can't keep the scoped_guard() on get side.

One additional reason to drop scoped_guard() is that it mixes cleanup helpers with goto, which is discouraged. See [*]

:Lastly, given that the benefit of cleanup helpers is removal of “goto”, and :that the “goto” statement can jump between scopes, the expectation is that :usage of “goto” and cleanup helpers is never mixed in the same function.

Fair enough.

Quoted 7 lines
Quoted 2 lines

But it can also be address if we free the PAMT page array with the guard too :P

How important is this patch? I see "Optimize" but I read "Optional".

If we're arguing about it, maybe we should just kick it out and focus on the more important bits.

I don't think it is optional for anything outside of test setup.

Without the optimization, we have all KVM memory allocations serialized on a single spinlock. And we do alloc_pamt_array()/free_pamt_array() all the time too.

And since the lock is global, it is an easy DoS attack vector: one guest can do a shared->private->shared conversion loop and make every guest on the host suffer.

Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
#62 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

In reply to Dave Hansen
Quoted 8 lines · Dave Hansen
Quoted 7 lines · Kiryl Shutsemau
Quoted 7 lines
Quoted 1 line

I don't see a reason why we can't keep the scoped_guard() on get side.

One additional reason to drop scoped_guard() is that it mixes cleanup helpers with goto, which is discouraged. See [*]

:Lastly, given that the benefit of cleanup helpers is removal of “goto”, and :that the “goto” statement can jump between scopes, the expectation is that :usage of “goto” and cleanup helpers is never mixed in the same function.

Quoted 6 lines
Quoted 4 lines

Fair enough.

But it can also be address if we free the PAMT page array with the guard too :P

How important is this patch? I see "Optimize" but I read "Optional".

This patch reduces the number of global pamt_lock acquisitions.

Reference testing data with/without the optimization:
(collected on my SPR test machine)

Booting/teardown of 1 TD (8 vcpus/8G memory) per iteration:

                |--------------|-------------|------------|
                |    avg (us)  |   max (us)  |   min (us) | 
                |  w/o  |  w/  |  w/o  | w/  | w/o  |  w/ |
----------------|-------|------|-------|-----|------|-----|
__tdx_pamt_get()|   2   |  0   |  578  | 505 |  2   |  0  |
__tdx_pamt_put()|   0   |  0   |  563  | 496 |  0   |  0  |
----------------|--------------|-------------|------------|

Boot/teardown of 5 TDs (each TD: 8 vcpus/8G memory) concurrently:

                |--------------|-------------|------------|
                |    avg (us)  |   max (us)  |   min (us) | 
                |  w/o  |  w/  |  w/o  | w/  | w/o  |  w/ |
----------------|-------|------|-------|-----|------|-----|
__tdx_pamt_get()|  15   |  0   |  1723 | 1386|  2   |  0  |
__tdx_pamt_put()|   0   |  0   |   562 |  733|  0   |  0  |
----------------|--------------|-------------|------------|
Quoted 2 lines

If we're arguing about it, maybe we should just kick it out and focus on the more important bits.

DPAMT still works fine without this optimization. The optimization can reduce the average time spent on the global lock, especially when there's high contention.

author maintainer
#63 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

Oh! You already did some testing.

Quoted 6 lines · Yan Zhao
Quoted 1 line

How important is this patch? I see "Optimize" but I read "Optional".

This patch reduces the number of global pamt_lock acquisitions.

Reference testing data with/without the optimization:
(collected on my SPR test machine)

Quoted 6 lines

Booting/teardown of 1 TD (8 vcpus/8G memory) per iteration:

                |--------------|-------------|------------|
                |    avg (us)  |   max (us)  |   min (us) | 
                |  w/o  |  w/  |  w/o  | w/  | w/o  |  w/ |
----------------|-------|------|-------|-----|------|-----|
__tdx_pamt_get()|   2   |  0   |  578  | 505 |  2   |  0  |

^ it looks like the old version. Is this on a huge page stack? Or just plain
dynamic PAMT?

Quoted 11 lines

__tdx_pamt_put()|   0   |  0   |  563  | 496 |  0   |  0  | ----------------|--------------|-------------|------------|

Boot/teardown of 5 TDs (each TD: 8 vcpus/8G memory) concurrently:

                |--------------|-------------|------------|
                |    avg (us)  |   max (us)  |   min (us) | 
                |  w/o  |  w/  |  w/o  | w/  | w/o  |  w/ |
----------------|-------|------|-------|-----|------|-----|
__tdx_pamt_get()|  15   |  0   |  1723 | 1386|  2   |  0  |
__tdx_pamt_put()|   0   |  0   |   562 |  733|  0   |  0  |
----------------|--------------|-------------|------------|

Did you record total time, or number of invocations that we could use to turn this into some more real world impact?

#64 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

Quoted 16 lines · Rick P

Oh! You already did some testing.

Quoted 6 lines · Yan Zhao
Quoted 1 line

How important is this patch? I see "Optimize" but I read "Optional".

This patch reduces the number of global pamt_lock acquisitions.

Reference testing data with/without the optimization:
(collected on my SPR test machine)

Quoted 6 lines

Booting/teardown of 1 TD (8 vcpus/8G memory) per iteration:

                |--------------|-------------|------------|
                |    avg (us)  |   max (us)  |   min (us) | 
                |  w/o  |  w/  |  w/o  | w/  | w/o  |  w/ |
----------------|-------|------|-------|-----|------|-----|
__tdx_pamt_get()|   2   |  0   |  578  | 505 |  2   |  0  |
Quoted 2 lines

^ it looks like the old version. Is this on a huge page stack? Or just plain
dynamic PAMT?

It's DPAMT v6 with the huge page stack. But the data was collected with huge pages disabled.

Quoted 14 lines
Quoted 4 lines

__tdx_pamt_put()|   0   |  0   |  563  | 496 |  0   |  0  | ----------------|--------------|-------------|------------|

Quoted 8 lines

Boot/teardown of 5 TDs (each TD: 8 vcpus/8G memory) concurrently:

                |--------------|-------------|------------|
                |    avg (us)  |   max (us)  |   min (us) | 
                |  w/o  |  w/  |  w/o  | w/  | w/o  |  w/ |
----------------|-------|------|-------|-----|------|-----|
__tdx_pamt_get()|  15   |  0   |  1723 | 1386|  2   |  0  |
__tdx_pamt_put()|   0   |  0   |   562 |  733|  0   |  0  |
----------------|--------------|-------------|------------|
Quoted 2 lines

Did you record total time, or number of invocations that we could use to turn this into some more real world impact?

Below data was collected on SPR, averaged over 3 runs (huge pages disabled):

Bootup+teardown of 1 TD (8 vcpus/8G memory):

                |--------------|-------------|------------|
                |    avg (us)  |   #cnt      | total (us) | 
                |  w/o  |  w/  |  w/o  | w/  | w/o  |  w/ |
----------------|-------|------|-------|-----|------|-----|
__tdx_pamt_get()|   2   |  0   |  706k |704k |2025k | 51k |
__tdx_pamt_put()|   0   |  0   |  706k |704k | 130k | 34k |
----------------|--------------|-------------|------------|

Bootup+teardown of 5 TDs (each TD: 8 vcpus/8G memory) concurrently:

                |--------------|-------------|------------|
                |    avg (us)  |   #cnt      | total (us) | 
                |  w/o  |  w/  |  w/o  | w/  | w/o  |  w/ |
----------------|-------|------|-------|-----|------|-----|
__tdx_pamt_get()|  15   |  0   | 3431k |3420k|55517k|334k |
__tdx_pamt_put()|   0   |  0   | 3431k |3420k| 2066k|137k |
----------------|--------------|-------------|------------|
author maintainer
#65 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

In reply to Dave Hansen
Quoted 10 lines · Dave Hansen
Quoted 9 lines · Kiryl Shutsemau
Quoted 7 lines
Quoted 1 line

I don't see a reason why we can't keep the scoped_guard() on get side.

One additional reason to drop scoped_guard() is that it mixes cleanup helpers with goto, which is discouraged. See [*]

  :Lastly, given that the benefit of cleanup helpers is removal of “goto”, and :that the “goto” statement can jump between scopes, the expectation is that :usage of “goto” and cleanup helpers is never mixed in the same function.

Fair enough.

Quoted 7 lines
Quoted 2 lines

But it can also be address if we free the PAMT page array with the guard too :P

How important is this patch? I see "Optimize" but I read "Optional".

If we're arguing about it, maybe we should just kick it out and focus on the more important bits.

I had done some testing previously to see if the refcount solution avoided contention enough:
V2 of the series includes a global lock to be used around actual installation/removal of the DPAMT backing, combined with opportunistic checking outside the lock to avoid taking it most of the time. In testing, booting 10 16GB TDs, the lock only hit contention 1136 times, with 4ms waiting. This is very small for an operation that took 60s of wall time. So despite being an (ugly) global lock, the actual impact was small. It will probably further be reduced in the case of huge pages, where most of the time 4KB DPAMT installation will not be necessary.
https://lore.kernel.org/all/[email protected]/

But I did not test without this global lock avoiding optimization. I can look into it.

The other way to drop this patch I was considering was to limit the situations when dynamic PAMT gets enabled somehow, like early LASS support. A boot time param would be the simplest. Or define a policy based on the number of keyids with the reasoning that if you are only able to run one TD, you will at least not contend with other TDs. Then we could revisit the optimization after huge pages is settled.

For the subject of the arguing though, my vote would be to drop the scope guard stuff and stick with the old pattern from the beginning.

Reviewed-by on v6 6/11
#66 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

In reply to Rick Edgecombe
Quoted 1 line · Rick Edgecombe
(quoted diff) +0 -0
@@ -2057,32 +2057,50 @@ static int tdx_pamt_get(kvm_pfn_t pfn)

[snip]

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2085

Quoted 11 lines
arch/x86/virt/vmx/tdx/tdx.c +11 -0
+	/*
+	 * Unlike tdx_pamt_put() which uses atomic_dec_and_lock() to
+	 * atomically handle the 1->0 transition, the get side has no
+	 * equivalent combined primitive for 0->1. Recheck under the
+	 * lock since another get may have already done the 0->1
+	 * transition after both saw atomic_inc_not_zero() fail.
+	 */
+	if (atomic_read(pamt_refcount)) {
+		atomic_inc(pamt_refcount);
+		spin_unlock(&pamt_lock);
+		goto out_free;

spin_unlock() can be moved to out_free to avoid repeating it before each 'goto out_free'.

Quoted 5 lines
	}
arch/x86/virt/vmx/tdx/tdx.c +3 -0
+	tdx_status = tdh_phymem_pamt_add(pfn, pamt_pages);
+	if (tdx_status == TDX_SUCCESS) {
+		/*

arch/x86/virt/vmx/tdx/tdx.c static int tdx_pamt_get(kvm_pfn_t pfn) · line 2100

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+		 * The refcount is zero, and this locked path is the
+		 * only way to increase it from 0->1.
+		 */
+		atomic_set(pamt_refcount, 1);
+	} else {
+		WARN_ON_ONCE(1);
+		ret = -EIO;
+		spin_unlock(&pamt_lock);
+		goto out_free;
+	}

Reduce indentation for the normal path:

	if (tdx_status != TDX_SUCCESS) {
		WARN_ON_ONCE(1);
		ret = -EIO;
		spin_unlock(&pamt_lock);
		goto out_free;
	}

	/*
	 * The refcount is zero, and this locked path is the
	 * only way to increase it from 0->1.
	 */
	atomic_set(pamt_refcount, 1);

The rest looks good to me.

#67 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

In reply to Rick Edgecombe
Quoted 24 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The Dynamic PAMT get/put helpers use a global spinlock to serialize all refcount updates and SEAMCALL invocations. This gives correct behavior for concurrent callers, but leads to contention. It is especially bad from the KVM side, which is designed to allow faulting in EPT under a shared lock. With the global spinlock, not only is the lock an exclusive one, but it is for all TDs instead of just a single one.

But taking the global lock each time is actually unnecessary. Only the 0->1 and 1->0 refcount transitions actually need the lock (to pair with SEAMCALLs that actually add and remove with the Dynamic PAMT pages). The common case of incrementing or decrementing a non-zero refcount can be done locklessly.

So create a fast and slow path. Check the refcount outside the lock and only take it for the slowpath (0->1 and 1->0 transitions).

On the put side make the refcount adjustment and lock taking atomic so if a 'get' happens between them, it doesn't cause the Dynamic PAMT to be freed incorrectly. On the get side there is no technique for doing the refcount adjustment and lock atomically, so check the refcount again inside the lock.

Quoted 4 lines
Assisted-by GitHub Copilot:claude-opus-4-6

The optimization LGTM.

author maintainer
#68 lore raw

Re: [PATCH v6 06/11] x86/virt/tdx: Optimize tdx_pamt_get/put()

Quoted 1 line · Yan Zhao

The optimization LGTM.

Thanks for checking it.

author maintainer
#69 lore raw

PATCH v6 7/11 KVM: TDX: Allocate PAMT memory for TD and vCPU control structures

In reply to Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Use control page helpers for allocating and freeing TD control structures, such these operations can work for Dynamic PAMT.

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So the kernel must install PAMT backing for each 4KB page before gifting it to the TDX module, and tear it down after the page is reclaimed.

TD-scoped control pages (TDR, TDCS) and vCPU-scoped control pages (TDVPR, TDCX) are all handed to the TDX module at 4KB page size and are therefore subject to this requirement. Replace the raw alloc_page()/__free_page() calls for these pages with tdx_alloc/free_control_page().

Switching between special Dynamic PAMT operations or normal page alloc/free operations is handled internally in tdx_alloc/free_control_page(). So don't check for Dynamic PAMT around these calls. Just call them unconditionally. Similarly, drop the NULL checks before freeing, as tdx_free_control_page() handles NULL internally.

No functional change intended when Dynamic PAMT is not in use.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7
[sean: handle alloc+free+reclaim in one patch]
[Rick: enhance log]
---
 arch/x86/kvm/vmx/tdx.c | 35 ++++++++++++++---------------------
 1 file changed, 14 insertions(+), 21 deletions(-)
arch/x86/kvm/vmx/tdx.c +14 -21
index 2539107e0ad3d..3e67e2471ffe3 100644
@@ -362,7 +362,7 @@ static void tdx_reclaim_control_page(struct page *ctrl_page)
 	if (tdx_reclaim_page(ctrl_page))
 		return;
 
-	__free_page(ctrl_page);
+	tdx_free_control_page(ctrl_page);
 }
 
 struct tdx_flush_vp_arg {
@@ -599,7 +599,7 @@ static void tdx_reclaim_td_control_pages(struct kvm *kvm)
 
 	tdx_quirk_reset_paddr(page_to_phys(kvm_tdx->td.tdr_page), PAGE_SIZE);
 
-	__free_page(kvm_tdx->td.tdr_page);
+	tdx_free_control_page(kvm_tdx->td.tdr_page);
 	kvm_tdx->td.tdr_page = NULL;
 }
 
@@ -2444,7 +2444,7 @@ static int __tdx_td_init(struct kvm *kvm, struct td_params *td_params,
 
 	ret = -ENOMEM;
 
-	tdr_page = alloc_page(GFP_KERNEL_ACCOUNT);
+	tdr_page = tdx_alloc_control_page();
 	if (!tdr_page)
 		goto free_hkid;
 
@@ -2458,7 +2458,7 @@ static int __tdx_td_init(struct kvm *kvm, struct td_params *td_params,
 		goto free_tdr;
 
 	for (i = 0; i < kvm_tdx->td.tdcs_nr_pages; i++) {
-		tdcs_pages[i] = alloc_page(GFP_KERNEL_ACCOUNT);
+		tdcs_pages[i] = tdx_alloc_control_page();
 		if (!tdcs_pages[i])
 			goto free_tdcs;
 	}
@@ -2576,10 +2576,8 @@ static int __tdx_td_init(struct kvm *kvm, struct td_params *td_params,
 teardown:
 	/* Only free pages not yet added, so start at 'i' */
 	for (; i < kvm_tdx->td.tdcs_nr_pages; i++) {
-		if (tdcs_pages[i]) {
-			__free_page(tdcs_pages[i]);
-			tdcs_pages[i] = NULL;
-		}
+		tdx_free_control_page(tdcs_pages[i]);
+		tdcs_pages[i] = NULL;
 	}
 	if (!kvm_tdx->td.tdcs_pages)
 		kfree(tdcs_pages);
@@ -2594,16 +2592,13 @@ static int __tdx_td_init(struct kvm *kvm, struct td_params *td_params,
 	free_cpumask_var(packages);
 
 free_tdcs:
-	for (i = 0; i < kvm_tdx->td.tdcs_nr_pages; i++) {
-		if (tdcs_pages[i])
-			__free_page(tdcs_pages[i]);
-	}
+	for (i = 0; i < kvm_tdx->td.tdcs_nr_pages; i++)
+		tdx_free_control_page(tdcs_pages[i]);
 	kfree(tdcs_pages);
 	kvm_tdx->td.tdcs_pages = NULL;
 
 free_tdr:
-	if (tdr_page)
-		__free_page(tdr_page);
+	tdx_free_control_page(tdr_page);
 	kvm_tdx->td.tdr_page = NULL;
 
 free_hkid:
@@ -2933,7 +2928,7 @@ static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx)
 	int ret, i;
 	u64 err;
 
-	page = alloc_page(GFP_KERNEL_ACCOUNT);
+	page = tdx_alloc_control_page();
 	if (!page)
 		return -ENOMEM;
 	tdx->vp.tdvpr_page = page;
@@ -2953,7 +2948,7 @@ static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx)
 	}
 
 	for (i = 0; i < kvm_tdx->td.tdcx_nr_pages; i++) {
-		page = alloc_page(GFP_KERNEL_ACCOUNT);
+		page = tdx_alloc_control_page();
 		if (!page) {
 			ret = -ENOMEM;
 			goto free_tdcx;
@@ -2975,7 +2970,7 @@ static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx)
 			 * method, but the rest are freed here.
 			 */
 			for (; i < kvm_tdx->td.tdcx_nr_pages; i++) {
-				__free_page(tdx->vp.tdcx_pages[i]);
+				tdx_free_control_page(tdx->vp.tdcx_pages[i]);
 				tdx->vp.tdcx_pages[i] = NULL;
 			}
 			return -EIO;
@@ -3003,16 +2998,14 @@ static int tdx_td_vcpu_init(struct kvm_vcpu *vcpu, u64 vcpu_rcx)
 
 free_tdcx:
 	for (i = 0; i < kvm_tdx->td.tdcx_nr_pages; i++) {
-		if (tdx->vp.tdcx_pages[i])
-			__free_page(tdx->vp.tdcx_pages[i]);
+		tdx_free_control_page(tdx->vp.tdcx_pages[i]);
 		tdx->vp.tdcx_pages[i] = NULL;
 	}
 	kfree(tdx->vp.tdcx_pages);
 	tdx->vp.tdcx_pages = NULL;
 
 free_tdvpr:
-	if (tdx->vp.tdvpr_page)
-		__free_page(tdx->vp.tdvpr_page);
+	tdx_free_control_page(tdx->vp.tdvpr_page);
 	tdx->vp.tdvpr_page = NULL;
 	tdx->vp.tdvpr_pa = 0;
 
Signature · 1 line
2.54.0
Reviewed-by on v6 7/11
#70 lore raw

Re: [PATCH v6 07/11] KVM: TDX: Allocate PAMT memory for TD and vCPU control structures

Quoted 4 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Use control page helpers for allocating and freeing TD control structures, such these operations can work for Dynamic PAMT.

      ^

Nit:
It appears to be missing the word "that".

Quoted 22 lines

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So the kernel must install PAMT backing for each 4KB page before gifting it to the TDX module, and tear it down after the page is reclaimed.

TD-scoped control pages (TDR, TDCS) and vCPU-scoped control pages (TDVPR, TDCX) are all handed to the TDX module at 4KB page size and are therefore subject to this requirement. Replace the raw alloc_page()/__free_page() calls for these pages with tdx_alloc/free_control_page().

Switching between special Dynamic PAMT operations or normal page alloc/free operations is handled internally in tdx_alloc/free_control_page(). So don't check for Dynamic PAMT around these calls. Just call them unconditionally. Similarly, drop the NULL checks before freeing, as tdx_free_control_page() handles NULL internally.

No functional change intended when Dynamic PAMT is not in use.

Quoted 7 lines
Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7
[sean: handle alloc+free+reclaim in one patch]
[Rick: enhance log]
#71 lore raw

Re: [PATCH v6 07/11] KVM: TDX: Allocate PAMT memory for TD and vCPU control structures

In reply to Rick Edgecombe
Quoted 24 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Use control page helpers for allocating and freeing TD control structures, such these operations can work for Dynamic PAMT.

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So the kernel must install PAMT backing for each 4KB page before gifting it to the TDX module, and tear it down after the page is reclaimed.

TD-scoped control pages (TDR, TDCS) and vCPU-scoped control pages (TDVPR, TDCX) are all handed to the TDX module at 4KB page size and are therefore subject to this requirement. Replace the raw alloc_page()/__free_page() calls for these pages with tdx_alloc/free_control_page().

Switching between special Dynamic PAMT operations or normal page alloc/free operations is handled internally in tdx_alloc/free_control_page(). So don't check for Dynamic PAMT around these calls. Just call them unconditionally. Similarly, drop the NULL checks before freeing, as tdx_free_control_page() handles NULL internally.

Quoted 3 lines

No functional change intended when Dynamic PAMT is not in use.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

Exactly what assistance was given, and when? I certainly didn't use any of these tools, and given that Claude Opus 4.6 was released after I posted the v5 RFC, I doubt Kirill did either.

And in my strong opinion, even if AI tooling was used to rebase the patches, I don't think that level of "assistance" should be presented this way. E.g. I would rather a more informal:

[ Rick: enhance log, rebase with help from AI tooling]

Because unless I'm missing something, claiming that AI was used to write the patch is misleading and disingenuous.

Quoted 3 lines
[sean: handle alloc+free+reclaim in one patch]

Where did this come from? I don't think me squashing two patches together warrants a Co-developed-by.

Quoted 3 lines
author maintainer
#72 lore raw

Re: [PATCH v6 07/11] KVM: TDX: Allocate PAMT memory for TD and vCPU control structures

Quoted 25 lines · Sean Christopherson
Quoted 24 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Use control page helpers for allocating and freeing TD control structures, such these operations can work for Dynamic PAMT.

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So the kernel must install PAMT backing for each 4KB page before gifting it to the TDX module, and tear it down after the page is reclaimed.

TD-scoped control pages (TDR, TDCS) and vCPU-scoped control pages (TDVPR, TDCX) are all handed to the TDX module at 4KB page size and are therefore subject to this requirement. Replace the raw alloc_page()/__free_page() calls for these pages with tdx_alloc/free_control_page().

Switching between special Dynamic PAMT operations or normal page alloc/free operations is handled internally in tdx_alloc/free_control_page(). So don't check for Dynamic PAMT around these calls. Just call them unconditionally. Similarly, drop the NULL checks before freeing, as tdx_free_control_page() handles NULL internally.

Quoted 7 lines
Quoted 3 lines

No functional change intended when Dynamic PAMT is not in use.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

Exactly what assistance was given, and when? I certainly didn't use any of these tools, and given that Claude Opus 4.6 was released after I posted the v5 RFC, I doubt Kirill did either.

On this patch specifically, lots of "review this patch" type experiments IIRC. Probably mostly around the log.

Quoted 9 lines

And in my strong opinion, even if AI tooling was used to rebase the patches, I don't think that level of "assistance" should be presented this way. E.g. I would rather a more informal:

[ Rick: enhance log, rebase with help from AI tooling]

Because unless I'm missing something, claiming that AI was used to write the patch is misleading and disingenuous.

Yea, I was just trying to follow the policy. It seems things are swinging the other way now. This works.

Quoted 7 lines
Quoted 4 lines
[sean: handle alloc+free+reclaim in one patch]

Where did this come from? I don't think me squashing two patches together warrants a Co-developed-by.

Gosh, I'm sorry. It looks like I added it. Will remove.

Quoted 4 lines
Quoted 4 lines
#73 lore raw

Re: [PATCH v6 07/11] KVM: TDX: Allocate PAMT memory for TD and vCPU control structures

Quoted 42 lines · Rick P Edgecombe
Quoted 25 lines · Sean Christopherson
Quoted 24 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Use control page helpers for allocating and freeing TD control structures, such these operations can work for Dynamic PAMT.

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So the kernel must install PAMT backing for each 4KB page before gifting it to the TDX module, and tear it down after the page is reclaimed.

TD-scoped control pages (TDR, TDCS) and vCPU-scoped control pages (TDVPR, TDCX) are all handed to the TDX module at 4KB page size and are therefore subject to this requirement. Replace the raw alloc_page()/__free_page() calls for these pages with tdx_alloc/free_control_page().

Switching between special Dynamic PAMT operations or normal page alloc/free operations is handled internally in tdx_alloc/free_control_page(). So don't check for Dynamic PAMT around these calls. Just call them unconditionally. Similarly, drop the NULL checks before freeing, as tdx_free_control_page() handles NULL internally.

Quoted 7 lines
Quoted 3 lines

No functional change intended when Dynamic PAMT is not in use.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

Exactly what assistance was given, and when? I certainly didn't use any of these tools, and given that Claude Opus 4.6 was released after I posted the v5 RFC, I doubt Kirill did either.

On this patch specifically, lots of "review this patch" type experiments IIRC. Probably mostly around the log.

Quoted 5 lines

And in my strong opinion, even if AI tooling was used to rebase the patches, I don't think that level of "assistance" should be presented this way. E.g. I would rather a more informal:

Quoted 7 lines
Quoted 4 lines

[ Rick: enhance log, rebase with help from AI tooling]

Because unless I'm missing something, claiming that AI was used to write the patch is misleading and disingenuous.

Yea, I was just trying to follow the policy. It seems things are swinging the other way now. This works.

FWIW, my read of the official policy, even before any change in direction, is that it only applies to using AI to write code. It's not like we given any credit in the patch itself when changes are made in response to code review from human.

#74 lore raw

Re: [PATCH v6 07/11] KVM: TDX: Allocate PAMT memory for TD and vCPU control structures

In reply to Sean Christopherson
Quoted 5 lines · Sean Christopherson
Quoted 3 lines
[sean: handle alloc+free+reclaim in one patch]

Where did this come from? I don't think me squashing two patches together warrants a Co-developed-by.

FWIW, I think the pendulum has swung way too far in terms of people trying to tell the whole tortured story of their patches via tags. I prefer some prose which is less formal *and* more descriptive than tags.

Sounds like Sean and I are mostly on the same page here too, which is a bonus.

Reviewed-by on v6 7/11
#75 lore raw

Re: [PATCH v6 07/11] KVM: TDX: Allocate PAMT memory for TD and vCPU control structures

In reply to Rick Edgecombe
Quoted 26 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Use control page helpers for allocating and freeing TD control structures, such these operations can work for Dynamic PAMT.

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So the kernel must install PAMT backing for each 4KB page before gifting it to the TDX module, and tear it down after the page is reclaimed.

TD-scoped control pages (TDR, TDCS) and vCPU-scoped control pages (TDVPR, TDCX) are all handed to the TDX module at 4KB page size and are therefore subject to this requirement. Replace the raw alloc_page()/__free_page() calls for these pages with tdx_alloc/free_control_page().

Switching between special Dynamic PAMT operations or normal page alloc/free operations is handled internally in tdx_alloc/free_control_page(). So don't check for Dynamic PAMT around these calls. Just call them unconditionally. Similarly, drop the NULL checks before freeing, as tdx_free_control_page() handles NULL internally.

No functional change intended when Dynamic PAMT is not in use.

Quoted 7 lines
Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7
[sean: handle alloc+free+reclaim in one patch]
[Rick: enhance log]
Reviewed-by on v6 7/11
#76 lore raw

Re: [PATCH v6 07/11] KVM: TDX: Allocate PAMT memory for TD and vCPU control structures

In reply to Rick Edgecombe
Quoted 7 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Use control page helpers for allocating and freeing TD control structures, such these operations can work for Dynamic PAMT.

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for

Nit: It records this state in the PAMT ?

Quoted 3 lines

each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So the kernel must install PAMT backing for each 4KB

How about
"..., only the backend to hold the 4KB page size state is allocated dynamically" ?

Quoted 2 lines

page before gifting it to the TDX module, and tear it down after the page is reclaimed.

How about
"So the kernel must check whether it is necessary to install/remove PAMT backing for each 4KB page, and do so when necessary before gifting the page to the TDX module or after it is reclaimed." ?

Quoted 5 lines

TD-scoped control pages (TDR, TDCS) and vCPU-scoped control pages (TDVPR, TDCX) are all handed to the TDX module at 4KB page size and are therefore subject to this requirement. Replace the raw alloc_page()/__free_page() calls for these pages with tdx_alloc/free_control_page().

Quoted 7 lines

Switching between special Dynamic PAMT operations or normal page alloc/free operations is handled internally in tdx_alloc/free_control_page(). So don't check for Dynamic PAMT around these calls. Just call them unconditionally. Similarly, drop the NULL checks before freeing, as tdx_free_control_page() handles NULL internally.

No functional change intended when Dynamic PAMT is not in use.

author maintainer
#77 lore raw

Re: [PATCH v6 07/11] KVM: TDX: Allocate PAMT memory for TD and vCPU control structures

Quoted 9 lines · Yan Zhao
Quoted 7 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Use control page helpers for allocating and freeing TD control structures, such these operations can work for Dynamic PAMT.

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for

Nit: It records this state in the PAMT ?

The text is trying to describe what PAMT is, so I'm not sure about this one.

Quoted 7 lines
Quoted 4 lines

each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So the kernel must install PAMT backing for each 4KB

How about
"..., only the backend to hold the 4KB page size state is allocated dynamically" ?

How about:
In Dynamic PAMT, only the 4KB page size backing is allocated dynamically.

Quoted 7 lines
Quoted 3 lines

page before gifting it to the TDX module, and tear it down after the page is reclaimed.

How about
"So the kernel must check whether it is necessary to install/remove PAMT backing for each 4KB page, and do so when necessary before gifting the page to the TDX module or after it is reclaimed." ?

The checking part is true, but is it needed to understand this patch? I think it just needs a background of what is happening. How about:

So the kernel must install PAMT backing for any 4KB page being gifting to the TDX module, and tear down the backing when the associated gifted pages are reclaimed.

Quoted 16 lines
Quoted 6 lines

TD-scoped control pages (TDR, TDCS) and vCPU-scoped control pages (TDVPR, TDCX) are all handed to the TDX module at 4KB page size and are therefore subject to this requirement. Replace the raw alloc_page()/__free_page() calls for these pages with tdx_alloc/free_control_page().

Quoted 7 lines

Switching between special Dynamic PAMT operations or normal page alloc/free operations is handled internally in tdx_alloc/free_control_page(). So don't check for Dynamic PAMT around these calls. Just call them unconditionally. Similarly, drop the NULL checks before freeing, as tdx_free_control_page() handles NULL internally.

No functional change intended when Dynamic PAMT is not in use.

#78 lore raw

Re: [PATCH v6 07/11] KVM: TDX: Allocate PAMT memory for TD and vCPU control structures

Quoted 4 lines · Rick P
Quoted 3 lines · Yan Zhao
Quoted 2 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Quoted 8 lines
Quoted 6 lines
Quoted 5 lines

Use control page helpers for allocating and freeing TD control structures, such these operations can work for Dynamic PAMT.

The TDX module tracks some state for each page of physical memory that it might use. It calls this state the PAMT. It includes separate state for

Nit: It records this state in the PAMT ?

The text is trying to describe what PAMT is, so I'm not sure about this one.

Ok.
To me, PAMT stands for physical address metadata table, and the metadata the table tracks is the "state" of a page.
Feel free to ignore the nit though :)

Quoted 9 lines
Quoted 6 lines
Quoted 3 lines

each page size a physical page could be utilized at within the TDX module (1GB, 2MB, 4KB). In Dynamic PAMT, only the 4KB page size state is allocated dynamically. So the kernel must install PAMT backing for each 4KB

How about
"..., only the backend to hold the 4KB page size state is allocated dynamically" ?

How about:
In Dynamic PAMT, only the 4KB page size backing is allocated dynamically.

LGTM.

Quoted 7 lines
Quoted 6 lines
Quoted 2 lines

page before gifting it to the TDX module, and tear it down after the page is reclaimed.

How about
"So the kernel must check whether it is necessary to install/remove PAMT backing for each 4KB page, and do so when necessary before gifting the page to the TDX module or after it is reclaimed." ?

Quoted 6 lines

The checking part is true, but is it needed to understand this patch? I think it just needs a background of what is happening. How about:

So the kernel must install PAMT backing for any 4KB page being gifting to the TDX module, and tear down the backing when the associated gifted pages are reclaimed.

Hmm. I'm not sure if it would be confusing for people without sufficient background, because the kernel only needs to install PAMT backing before the gifting the first 4KB page.

How about:
So the kernel must ensure PAMT backing installed for any 4KB page being gifting to the TDX module, and tear down the backing when all associated gifted pages are reclaimed.

author maintainer
#79 lore raw

Re: [PATCH v6 07/11] KVM: TDX: Allocate PAMT memory for TD and vCPU control structures

Quoted 13 lines · Yan Zhao
Quoted 7 lines
Quoted 6 lines
Quoted 2 lines

page before gifting it to the TDX module, and tear it down after the page is reclaimed.

How about
"So the kernel must check whether it is necessary to install/remove PAMT backing for each 4KB page, and do so when necessary before gifting the page to the TDX module or after it is reclaimed." ?

Quoted 6 lines

The checking part is true, but is it needed to understand this patch? I think it just needs a background of what is happening. How about:

So the kernel must install PAMT backing for any 4KB page being gifting to the TDX module, and tear down the backing when the associated gifted pages are reclaimed.

Quoted 8 lines

Hmm. I'm not sure if it would be confusing for people without sufficient background, because the kernel only needs to install PAMT backing before the gifting the first 4KB page.

How about:
So the kernel must ensure PAMT backing installed for any 4KB page being gifting to the TDX module, and tear down the backing when all associated gifted pages are reclaimed.

I see how it's better. I added a few missed word tweaks and ended up with:

So the kernel must ensure PAMT backing is installed for any 4KB page being gifting to the TDX module, and must tear down the backing when all associated gifted pages are reclaimed.

Thanks!

#80 lore raw

Re: [PATCH v6 07/11] KVM: TDX: Allocate PAMT memory for TD and vCPU control structures

Quoted 22 lines · Rick P
Quoted 13 lines · Yan Zhao
Quoted 7 lines
Quoted 6 lines
Quoted 2 lines

page before gifting it to the TDX module, and tear it down after the page is reclaimed.

How about
"So the kernel must check whether it is necessary to install/remove PAMT backing for each 4KB page, and do so when necessary before gifting the page to the TDX module or after it is reclaimed." ?

Quoted 6 lines

The checking part is true, but is it needed to understand this patch? I think it just needs a background of what is happening. How about:

So the kernel must install PAMT backing for any 4KB page being gifting to the TDX module, and tear down the backing when the associated gifted pages are reclaimed.

Quoted 8 lines

Hmm. I'm not sure if it would be confusing for people without sufficient background, because the kernel only needs to install PAMT backing before the gifting the first 4KB page.

How about:
So the kernel must ensure PAMT backing installed for any 4KB page being gifting to the TDX module, and tear down the backing when all associated gifted pages are reclaimed.

Quoted 5 lines

I see how it's better. I added a few missed word tweaks and ended up with:

So the kernel must ensure PAMT backing is installed for any 4KB page being gifting to the TDX module, and must tear down the backing when all associated gifted pages are reclaimed.

It's better! Thanks!

author maintainer
#81 lore raw

PATCH v6 8/11 x86/tdx: Add APIs to support Dynamic PAMT ops from KVM's fault path

In reply to Rick Edgecombe

When handling an EPT violation, KVM holds a spinlock while manipulating the EPT. Before entering the spinlock it doesn't know how many EPT page tables will need to be installed or whether a huge page will be used. For this reason it allocates a worst case number of page tables that it might need as part of servicing the EPT violation.

Under Dynamic PAMT these pre-allocated pages will potentially need to have Dynamic PAMT backing pages installed for them. KVM already has helpers to manage topping up page caches before taking the MMU lock, but they cannot be passed from KVM to arch/x86 code.

The problem of how and when to install the DPAMT backing pages for the pages given to the TDX module during the fault path has had a lot of design attempts.
- Extracting KVM's MMU caches requires too much inlined code added to headers.
- A few varieties of installing Dynamic PAMT backing when allocating the S-EPT page tables. [0][1]
- Using mempool_t to transfer the pages between KVM and arch/x86 doesn't work because it is the component is designed more around maintaining a pool of pages, rather than topping up a continually drained cache.

So don't do these as they all had various problems. Instead just create a small simple data structure to use for handing a pre-allocated list of pages between KVM and arch/x86 code. Model this on KVM's existing MMU memory caches.

Add a tdx_pamt_cache arg to tdx_pamt_get() so it can draw pages from a cache when needed. Not all DPAMT page installations will happen under spinlock, for example control pages. So have tdx_pamt_get() maintain the existing behavior of allocating from the page allocator when NULL is passed for the struct tdx_pamt_cache arg. This prevents excess allocations for cases where it can be avoided.

Export the new helpers for KVM.

---
v6:
- Filled out log from Sean's series

---
 arch/x86/include/asm/tdx.h  | 17 ++++++++++
 arch/x86/virt/vmx/tdx/tdx.c | 65 +++++++++++++++++++++++++++++++++----
 2 files changed, 76 insertions(+), 6 deletions(-)
arch/x86/include/asm/tdx.h +17 -0
index 74e75db5728c7..191da84bbf2a1 100644
@@ -155,6 +155,23 @@ static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)
 	return false; /* To be enabled when kernel is ready */
 }
 
+/* Simple structure for pre-allocating Dynamic PAMT pages outside of locks. */
+struct tdx_pamt_cache {
+	struct list_head page_list;
+	int cnt;
+};
+
+static inline void tdx_init_pamt_cache(struct tdx_pamt_cache *cache)
+{
+	INIT_LIST_HEAD(&cache->page_list);
+	cache->cnt = 0;
+}
+
+void tdx_free_pamt_cache(struct tdx_pamt_cache *cache);
+int tdx_topup_pamt_cache(struct tdx_pamt_cache *cache, unsigned long npages);
+int tdx_pamt_get(kvm_pfn_t pfn, struct tdx_pamt_cache *cache);
+void tdx_pamt_put(kvm_pfn_t pfn);
+
 int tdx_guest_keyid_alloc(void);
 u32 tdx_get_nr_guest_keyids(void);
 void tdx_guest_keyid_free(unsigned int keyid);
arch/x86/virt/vmx/tdx/tdx.c +59 -6

110 lines not on this page · raw message

Signature · 1 line
2.54.0
maintainer Reviewed-by on v6 8/11
#82 lore raw

Re: [PATCH v6 08/11] x86/tdx: Add APIs to support Dynamic PAMT ops from KVM's fault path

Quoted 34 lines · Rick Edgecombe

When handling an EPT violation, KVM holds a spinlock while manipulating the EPT. Before entering the spinlock it doesn't know how many EPT page tables will need to be installed or whether a huge page will be used. For this reason it allocates a worst case number of page tables that it might need as part of servicing the EPT violation.

Under Dynamic PAMT these pre-allocated pages will potentially need to have Dynamic PAMT backing pages installed for them. KVM already has helpers to manage topping up page caches before taking the MMU lock, but they cannot be passed from KVM to arch/x86 code.

The problem of how and when to install the DPAMT backing pages for the pages given to the TDX module during the fault path has had a lot of design attempts.
- Extracting KVM's MMU caches requires too much inlined code added to headers.
- A few varieties of installing Dynamic PAMT backing when allocating the S-EPT page tables. [0][1]
- Using mempool_t to transfer the pages between KVM and arch/x86 doesn't work because it is the component is designed more around maintaining a pool of pages, rather than topping up a continually drained cache.

So don't do these as they all had various problems. Instead just create a small simple data structure to use for handing a pre-allocated list of pages between KVM and arch/x86 code. Model this on KVM's existing MMU memory caches.

Add a tdx_pamt_cache arg to tdx_pamt_get() so it can draw pages from a cache when needed. Not all DPAMT page installations will happen under spinlock, for example control pages. So have tdx_pamt_get() maintain the existing behavior of allocating from the page allocator when NULL is passed for the struct tdx_pamt_cache arg. This prevents excess allocations for cases where it can be avoided.

Quoted 8 lines

Export the new helpers for KVM.

Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
Reviewed-by on v6 8/11
#83 lore raw

Re: [PATCH v6 08/11] x86/tdx: Add APIs to support Dynamic PAMT ops from KVM's fault path

In reply to Rick Edgecombe
Quoted 11 lines · Rick Edgecombe

When handling an EPT violation, KVM holds a spinlock while manipulating the EPT. Before entering the spinlock it doesn't know how many EPT page tables will need to be installed or whether a huge page will be used. For this reason it allocates a worst case number of page tables that it might need as part of servicing the EPT violation.

Under Dynamic PAMT these pre-allocated pages will potentially need to have Dynamic PAMT backing pages installed for them. KVM already has helpers to manage topping up page caches before taking the MMU lock, but they cannot be passed from KVM to arch/x86 code.

Quoted 9 lines

The problem of how and when to install the DPAMT backing pages for the pages given to the TDX module during the fault path has had a lot of design attempts.
- Extracting KVM's MMU caches requires too much inlined code added to headers.
- A few varieties of installing Dynamic PAMT backing when allocating the S-EPT page tables. [0][1]
- Using mempool_t to transfer the pages between KVM and arch/x86 doesn't work because it is the component is designed more around maintaining a

                  ^^^^^

Nit: extra "it is"

Quoted 14 lines

pool of pages, rather than topping up a continually drained cache.

So don't do these as they all had various problems. Instead just create a small simple data structure to use for handing a pre-allocated list of pages between KVM and arch/x86 code. Model this on KVM's existing MMU memory caches.

Add a tdx_pamt_cache arg to tdx_pamt_get() so it can draw pages from a cache when needed. Not all DPAMT page installations will happen under spinlock, for example control pages. So have tdx_pamt_get() maintain the existing behavior of allocating from the page allocator when NULL is passed for the struct tdx_pamt_cache arg. This prevents excess allocations for cases where it can be avoided.

Quoted 8 lines

Export the new helpers for KVM.

Reviewed-by on v6 8/11
#84 lore raw

Re: [PATCH v6 08/11] x86/tdx: Add APIs to support Dynamic PAMT ops from KVM's fault path

In reply to Rick Edgecombe
Quoted 34 lines · Rick Edgecombe

When handling an EPT violation, KVM holds a spinlock while manipulating the EPT. Before entering the spinlock it doesn't know how many EPT page tables will need to be installed or whether a huge page will be used. For this reason it allocates a worst case number of page tables that it might need as part of servicing the EPT violation.

Under Dynamic PAMT these pre-allocated pages will potentially need to have Dynamic PAMT backing pages installed for them. KVM already has helpers to manage topping up page caches before taking the MMU lock, but they cannot be passed from KVM to arch/x86 code.

The problem of how and when to install the DPAMT backing pages for the pages given to the TDX module during the fault path has had a lot of design attempts.
- Extracting KVM's MMU caches requires too much inlined code added to headers.
- A few varieties of installing Dynamic PAMT backing when allocating the S-EPT page tables. [0][1]
- Using mempool_t to transfer the pages between KVM and arch/x86 doesn't work because it is the component is designed more around maintaining a pool of pages, rather than topping up a continually drained cache.

So don't do these as they all had various problems. Instead just create a small simple data structure to use for handing a pre-allocated list of pages between KVM and arch/x86 code. Model this on KVM's existing MMU memory caches.

Add a tdx_pamt_cache arg to tdx_pamt_get() so it can draw pages from a cache when needed. Not all DPAMT page installations will happen under spinlock, for example control pages. So have tdx_pamt_get() maintain the existing behavior of allocating from the page allocator when NULL is passed for the struct tdx_pamt_cache arg. This prevents excess allocations for cases where it can be avoided.

Quoted 6 lines

Export the new helpers for KVM.

Assisted-by GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7
Reviewed-by on v6 8/11
#85 lore raw

Re: [PATCH v6 08/11] x86/tdx: Add APIs to support Dynamic PAMT ops from KVM's fault path

In reply to Rick Edgecombe
Quoted 11 lines · Rick Edgecombe

When handling an EPT violation, KVM holds a spinlock while manipulating the EPT. Before entering the spinlock it doesn't know how many EPT page tables will need to be installed or whether a huge page will be used. For this reason it allocates a worst case number of page tables that it might need as part of servicing the EPT violation.

Under Dynamic PAMT these pre-allocated pages will potentially need to have Dynamic PAMT backing pages installed for them. KVM already has helpers to manage topping up page caches before taking the MMU lock, but they cannot be passed from KVM to arch/x86 code.

Quoted 7 lines

The problem of how and when to install the DPAMT backing pages for the pages given to the TDX module during the fault path has had a lot of design attempts.
- Extracting KVM's MMU caches requires too much inlined code added to headers.
- A few varieties of installing Dynamic PAMT backing when allocating the S-EPT page tables. [0][1]

IIUC, [0][1] here refer to design attempts that had various problems, right? However, [1] looks exactly like the one being adopted in v6?

Did you paste a wrong link? Should [1] instead be
https://lore.kernel.org/kvm/[email protected] or
https://lore.kernel.org/kvm/[email protected] ?

Quoted 4 lines

- Using mempool_t to transfer the pages between KVM and arch/x86 doesn't work because it is the component is designed more around maintaining a pool of pages, rather than topping up a continually drained cache.

Quoted 8 lines

So don't do these as they all had various problems. Instead just create a small simple data structure to use for handing a pre-allocated list of pages between KVM and arch/x86 code. Model this on KVM's existing MMU memory caches.

Add a tdx_pamt_cache arg to tdx_pamt_get() so it can draw pages from a cache when needed. Not all DPAMT page installations will happen under spinlock, for example control pages. So have tdx_pamt_get() maintain the

Nit: In patch 9, S-EPT pages are regarded as control pages as well. So maybe
"..., for example some control pages." or
"..., for example control pages other than S-EPT pages." ?

Quoted 25 lines

existing behavior of allocating from the page allocator when NULL is passed for the struct tdx_pamt_cache arg. This prevents excess allocations for cases where it can be avoided.

Export the new helpers for KVM.

---
v6:
- Filled out log from Sean's series

---
 arch/x86/include/asm/tdx.h  | 17 ++++++++++
 arch/x86/virt/vmx/tdx/tdx.c | 65 +++++++++++++++++++++++++++++++++----
 2 files changed, 76 insertions(+), 6 deletions(-)
arch/x86/include/asm/tdx.h +0 -0
index 74e75db5728c7..191da84bbf2a1 100644

arch/x86/include/asm/tdx.h static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo) · line 158

Quoted 4 lines
arch/x86/include/asm/tdx.h +1 -0
@@ -155,6 +155,23 @@ static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)
 	return false; /* To be enabled when kernel is ready */
 }
 
+/* Simple structure for pre-allocating Dynamic PAMT pages outside of locks. */

outside of spinlocks?

Pre-allocating Dynamic PAMT pages are still inside mutex, e.g., inside of kvm->slots_lock, vcpu->mutex...

arch/x86/include/asm/tdx.h static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo) · line 162

Quoted 4 lines
arch/x86/include/asm/tdx.h +4 -0
+struct tdx_pamt_cache {
+	struct list_head page_list;
+	int cnt;
+};

The rest LGTM.

author maintainer
#86 lore raw

Re: [PATCH v6 08/11] x86/tdx: Add APIs to support Dynamic PAMT ops from KVM's fault path

Quoted 19 lines · Yan Zhao
Quoted 11 lines · Rick Edgecombe

When handling an EPT violation, KVM holds a spinlock while manipulating the EPT. Before entering the spinlock it doesn't know how many EPT page tables will need to be installed or whether a huge page will be used. For this reason it allocates a worst case number of page tables that it might need as part of servicing the EPT violation.

Under Dynamic PAMT these pre-allocated pages will potentially need to have Dynamic PAMT backing pages installed for them. KVM already has helpers to manage topping up page caches before taking the MMU lock, but they cannot be passed from KVM to arch/x86 code.

Quoted 7 lines

The problem of how and when to install the DPAMT backing pages for the pages given to the TDX module during the fault path has had a lot of design attempts.
- Extracting KVM's MMU caches requires too much inlined code added to headers.
- A few varieties of installing Dynamic PAMT backing when allocating the S-EPT page tables. [0][1]

Quoted 6 lines

IIUC, [0][1] here refer to design attempts that had various problems, right? However, [1] looks exactly like the one being adopted in v6?

Did you paste a wrong link? Should [1] instead be
https://lore.kernel.org/kvm/[email protected] or
https://lore.kernel.org/kvm/[email protected] ?

Oh yea... I think it should be:
Kai's original idea: https://lore.kernel.org/kvm/[email protected]/
Sean's fixup of it:
https://lore.kernel.org/kvm/[email protected]/
The problem with Sean's:
https://lore.kernel.org/kvm/[email protected]/

TBH I'm a little on the fence about how useful the links will be in general. If someone tries to rip it out, it would be good breadcrumbs I guess

Quoted 10 lines
Quoted 10 lines

- Using mempool_t to transfer the pages between KVM and arch/x86 doesn't work because it is the component is designed more around maintaining a pool of pages, rather than topping up a continually drained cache.

So don't do these as they all had various problems. Instead just create a small simple data structure to use for handing a pre-allocated list of pages between KVM and arch/x86 code. Model this on KVM's existing MMU memory caches.

Quoted 6 lines
Quoted 3 lines

Add a tdx_pamt_cache arg to tdx_pamt_get() so it can draw pages from a cache when needed. Not all DPAMT page installations will happen under spinlock, for example control pages. So have tdx_pamt_get() maintain the

Nit: In patch 9, S-EPT pages are regarded as control pages as well. So maybe
"..., for example some control pages." or

Yea that is better. The patch 9 changes are after this, so it's technically correct, but we can make it clearer:
..., for example TD and vCPU scoped control pages for

Quoted 30 lines

"..., for example control pages other than S-EPT pages." ?

Quoted 28 lines

existing behavior of allocating from the page allocator when NULL is passed for the struct tdx_pamt_cache arg. This prevents excess allocations for cases where it can be avoided.

Export the new helpers for KVM.

---
v6:
- Filled out log from Sean's series

---
 arch/x86/include/asm/tdx.h  | 17 ++++++++++
 arch/x86/virt/vmx/tdx/tdx.c | 65 +++++++++++++++++++++++++++++++++----
 2 files changed, 76 insertions(+), 6 deletions(-)
arch/x86/include/asm/tdx.h +0 -0
index 74e75db5728c7..191da84bbf2a1 100644
@@ -155,6 +155,23 @@ static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)
 	return false; /* To be enabled when kernel is ready */
 }
 
Quoted 5 lines

arch/x86/include/asm/tdx.h static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo) · line 158

Quoted 1 line
arch/x86/include/asm/tdx.h +1 -0
+/* Simple structure for pre-allocating Dynamic PAMT pages outside of locks. */

outside of spinlocks?

Pre-allocating Dynamic PAMT pages are still inside mutex, e.g., inside of kvm->slots_lock, vcpu->mutex...

Ok.

Quoted 9 lines

arch/x86/include/asm/tdx.h static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo) · line 162

Quoted 5 lines
arch/x86/include/asm/tdx.h +4 -0
+struct tdx_pamt_cache {
+	struct list_head page_list;
+	int cnt;
+};

The rest LGTM.

Thanks!

#87 lore raw

Re: [PATCH v6 08/11] x86/tdx: Add APIs to support Dynamic PAMT ops from KVM's fault path

Quoted 34 lines · Rick P
Quoted 19 lines · Yan Zhao
Quoted 11 lines · Rick Edgecombe

When handling an EPT violation, KVM holds a spinlock while manipulating the EPT. Before entering the spinlock it doesn't know how many EPT page tables will need to be installed or whether a huge page will be used. For this reason it allocates a worst case number of page tables that it might need as part of servicing the EPT violation.

Under Dynamic PAMT these pre-allocated pages will potentially need to have Dynamic PAMT backing pages installed for them. KVM already has helpers to manage topping up page caches before taking the MMU lock, but they cannot be passed from KVM to arch/x86 code.

Quoted 7 lines

The problem of how and when to install the DPAMT backing pages for the pages given to the TDX module during the fault path has had a lot of design attempts.
- Extracting KVM's MMU caches requires too much inlined code added to headers.
- A few varieties of installing Dynamic PAMT backing when allocating the S-EPT page tables. [0][1]

Quoted 6 lines

IIUC, [0][1] here refer to design attempts that had various problems, right? However, [1] looks exactly like the one being adopted in v6?

Did you paste a wrong link? Should [1] instead be
https://lore.kernel.org/kvm/[email protected] or
https://lore.kernel.org/kvm/[email protected] ?

Oh yea... I think it should be:
Kai's original idea: https://lore.kernel.org/kvm/[email protected]/
Sean's fixup of it:
https://lore.kernel.org/kvm/[email protected]/
The problem with Sean's:
https://lore.kernel.org/kvm/[email protected]/

Quoted 2 lines

TBH I'm a little on the fence about how useful the links will be in general. If someone tries to rip it out, it would be good breadcrumbs I guess

No problem. I am fine with either keeping or removing those links :)

author maintainer
#88 lore raw

PATCH v6 9/11 KVM: TDX: Get/put PAMT pages when (un)mapping private memory

In reply to Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Add Dynamic PAMT support to KVM's S-EPT MMU by "getting" a PAMT page when adding guest memory (PAGE.ADD or PAGE.AUG), and "putting" the page when removing guest memory (PAGE.REMOVE).

To access the per-vCPU PAMT caches without plumbing @vcpu throughout the TDP MMU, begrudgingly use kvm_get_running_vcpu() to get the vCPU, and bug the VM if KVM attempts to set an S-EPT leaf without an active vCPU. KVM only supports creating _new_ mappings in page (pre)fault paths, all of which require an active vCPU.

The PAMT memory holds metadata for TDX-protected memory. With Dynamic PAMT, PAMT_4K is allocated on demand. The kernel supplies the TDX module with a few pages that cover 2M of host physical memory.

Releases are balanced via tdx_pamt_put(): every control-page free goes through tdx_free_control_page(), and guest data pages are put directly on the successful tdh_mem_page_remove() path and in the tdx_mem_page_add/aug() error path.

Assisted-by Sashiko:claude-opus-4-6 GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

---
v6:
- Don't have topup op take a min param (Yan, Sean)
- Make log match style of the rest of the series
- Adjustments from dropping error helper patches

---
 arch/x86/include/asm/kvm-x86-ops.h |  1 +
 arch/x86/include/asm/kvm_host.h    |  2 +
 arch/x86/kvm/mmu/mmu.c             |  4 ++
 arch/x86/kvm/vmx/tdx.c             | 65 ++++++++++++++++++++++++++----
 arch/x86/kvm/vmx/tdx.h             |  2 +
 5 files changed, 66 insertions(+), 8 deletions(-)
arch/x86/include/asm/kvm-x86-ops.h +1 -0
index 10ccf6ea9d9a2..320f1d30edacc 100644
@@ -97,6 +97,7 @@ KVM_X86_OP_OPTIONAL_RET0(get_mt_mask)
 KVM_X86_OP(load_mmu_pgd)
 KVM_X86_OP_OPTIONAL_RET0(set_external_spte)
 KVM_X86_OP_OPTIONAL(free_external_spt)
+KVM_X86_OP_OPTIONAL_RET0(topup_external_cache)
 KVM_X86_OP(has_wbinvd_exit)
 KVM_X86_OP(get_l2_tsc_offset)
 KVM_X86_OP(get_l2_tsc_multiplier)
arch/x86/include/asm/kvm_host.h +2 -0
index 6b28dd387bc61..bfe92e993a212 100644
@@ -1898,6 +1898,8 @@ struct kvm_x86_ops {
 	/* Update external page tables for page table about to be freed. */
 	void (*free_external_spt)(struct kvm *kvm, struct kvm_mmu_page *sp);
 
+	int (*topup_external_cache)(struct kvm_vcpu *vcpu, int min_nr_spts);
+
 
 	bool (*has_wbinvd_exit)(void);
 
arch/x86/kvm/mmu/mmu.c +4 -0
index 892246204435c..2a48fc7fccc11 100644
@@ -607,6 +607,10 @@ static int mmu_topup_memory_caches(struct kvm_vcpu *vcpu, bool maybe_indirect)
 					       PT64_ROOT_MAX_LEVEL);
 		if (r)
 			return r;
+
+		r = kvm_x86_call(topup_external_cache)(vcpu, PT64_ROOT_MAX_LEVEL);
+		if (r)
+			return r;
 	}
 	r = kvm_mmu_topup_memory_cache(&vcpu->arch.mmu_shadow_page_cache,
 				       PT64_ROOT_MAX_LEVEL);
arch/x86/kvm/vmx/tdx.c +57 -8

148 lines not on this page · raw message

arch/x86/kvm/vmx/tdx.h +2 -0
index b5cd2ffb303e5..47334a5a74eab 100644
@@ -73,6 +73,8 @@ struct vcpu_tdx {
 
 	u64 map_gpa_next;
 	u64 map_gpa_end;
+
+	struct tdx_pamt_cache pamt_cache;
 };
 
 void tdh_vp_rd_failed(struct vcpu_tdx *tdx, char *uclass, u32 field, u64 err);
Signature · 1 line
2.54.0
Reviewed-by on v6 9/11
#89 lore raw

Re: [PATCH v6 09/11] KVM: TDX: Get/put PAMT pages when (un)mapping private memory

Quoted 21 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Add Dynamic PAMT support to KVM's S-EPT MMU by "getting" a PAMT page when adding guest memory (PAGE.ADD or PAGE.AUG), and "putting" the page when removing guest memory (PAGE.REMOVE).

To access the per-vCPU PAMT caches without plumbing @vcpu throughout the TDP MMU, begrudgingly use kvm_get_running_vcpu() to get the vCPU, and bug the VM if KVM attempts to set an S-EPT leaf without an active vCPU. KVM only supports creating _new_ mappings in page (pre)fault paths, all of which require an active vCPU.

The PAMT memory holds metadata for TDX-protected memory. With Dynamic PAMT, PAMT_4K is allocated on demand. The kernel supplies the TDX module with a few pages that cover 2M of host physical memory.

Releases are balanced via tdx_pamt_put(): every control-page free goes through tdx_free_control_page(), and guest data pages are put directly on the successful tdh_mem_page_remove() path and in the tdx_mem_page_add/aug() error path.

Quoted 6 lines
Assisted-by Sashiko:claude-opus-4-6 GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

One nit below.

[...]

arch/x86/kvm/vmx/tdx.c static struct page *tdx_spte_to_sept_pt(struct kvm *kvm, gfn_t gfn, · line 1687

Quoted 6 lines
arch/x86/kvm/vmx/tdx.c +2 -0
@@ -1669,16 +1683,29 @@ static struct page *tdx_spte_to_sept_pt(struct kvm *kvm, gfn_t gfn,
 static int tdx_sept_map_nonleaf_spte(struct kvm *kvm, gfn_t gfn,
 				     enum pg_level level, u64 new_spte)
 {
+	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
+	struct vcpu_tdx *tdx = to_tdx(vcpu);

Nit:
Is it better to move this after checking vcpu is not NULL? Although tdx is not dereferenced in between, if vcpu is NULL, it means container_of() does arithmetic to a NULL pointer.

Quoted 25 lines
arch/x86/kvm/vmx/tdx.c +11 -0
 	gpa_t gpa = gfn_to_gpa(gfn);
 	u64 err, entry, level_state;
 	struct page *sept_pt;
+	int ret;
+
+	if (KVM_BUG_ON(!vcpu, kvm))
+		return -EIO;
 
 	sept_pt = tdx_spte_to_sept_pt(kvm, gfn, new_spte, level);
 	if (!sept_pt)
 		return -EIO;
 
+	ret = tdx_pamt_get(page_to_pfn(sept_pt), &tdx->pamt_cache);
+	if (ret)
+		return ret;
+
 	err = tdh_mem_sept_add(&to_kvm_tdx(kvm)->td, gpa, level, sept_pt,
 			       &entry, &level_state);
+	if (err)
+		tdx_pamt_put(page_to_pfn(sept_pt));
+
 	if (unlikely(tdx_operand_busy(err)))
 		return -EBUSY;
 

arch/x86/kvm/vmx/tdx.c static int tdx_sept_map_nonleaf_spte(struct kvm *kvm, gfn_t gfn, · line 1722

Quoted 5 lines
arch/x86/kvm/vmx/tdx.c +1 -0
@@ -1691,8 +1718,14 @@ static int tdx_sept_map_nonleaf_spte(struct kvm *kvm, gfn_t gfn,
 static int tdx_sept_map_leaf_spte(struct kvm *kvm, gfn_t gfn, enum pg_level level,
 				  u64 new_spte)
 {
+	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
 	struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);

Ditto

Quoted 7 lines
arch/x86/kvm/vmx/tdx.c +5 -0
 	kvm_pfn_t pfn = spte_to_pfn(new_spte);
+	struct vcpu_tdx *tdx = to_tdx(vcpu);
+	int ret;
+
+	if (KVM_BUG_ON(!vcpu, kvm))
+		return -EIO;
 

[...]

author maintainer
#90 lore raw

Re: [PATCH v6 09/11] KVM: TDX: Get/put PAMT pages when (un)mapping private memory

Quoted 4 lines · Binbin Wu
Quoted 4 lines
arch/x86/kvm/vmx/tdx.c +0 -0
@@ -1669,16 +1683,29 @@ static struct page *tdx_spte_to_sept_pt(struct kvm
 *kvm, gfn_t gfn,
   static int tdx_sept_map_nonleaf_spte(struct kvm *kvm, gfn_t gfn,
   				     enum pg_level level, u64 new_spte)
Quoted 8 lines

arch/x86/kvm/vmx/tdx.c static struct page *tdx_spte_to_sept_pt(struct kvm *kvm, gfn_t gfn, · line 1687

Quoted 3 lines
arch/x86/kvm/vmx/tdx.c +2 -0
   {
+	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
+	struct vcpu_tdx *tdx = to_tdx(vcpu);

Nit:
Is it better to move this after checking vcpu is not NULL? Although tdx is not dereferenced in between, if vcpu is NULL, it means container_of() does arithmetic to a NULL pointer.

Personally I'm on the fence. I'm going to leave it, because Sean did it that way:
https://lore.kernel.org/kvm/[email protected]/

#91 lore raw

Re: [PATCH v6 09/11] KVM: TDX: Get/put PAMT pages when (un)mapping private memory

Quoted 14 lines · Rick P Edgecombe
Quoted 4 lines · Binbin Wu
Quoted 4 lines
(quoted diff) +0 -0
@@ -1669,16 +1683,29 @@ static struct page *tdx_spte_to_sept_pt(struct kvm
 *kvm, gfn_t gfn,
   static int tdx_sept_map_nonleaf_spte(struct kvm *kvm, gfn_t gfn,
   				     enum pg_level level, u64 new_spte)
Quoted 8 lines

Review static struct page *tdx_spte_to_sept_pt(struct kvm · line 1688

Quoted 3 lines
(quoted diff) +2 -0
   {
+	struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
+	struct vcpu_tdx *tdx = to_tdx(vcpu);

Nit:
Is it better to move this after checking vcpu is not NULL? Although tdx is not dereferenced in between, if vcpu is NULL, it means container_of() does arithmetic to a NULL pointer.

Quoted 3 lines

Personally I'm on the fence. I'm going to leave it, because Sean did it that way:
https://lore.kernel.org/kvm/[email protected]/

Heh, because of course I'm omnipotent and never make mistakes.

I agree with the nit in the sense that this isn't a great pattern to encourage, but IMO the root of the ugly pattern is the use of kvm_get_running_vcpu() (which is sadly the lesser evil in this case). I.e. I'm not terribly concerned about this code leading to more "problems" in the future. And I don't really want to grab "tdx" later on because that deviates from the standard patterns in KVM and incorrectly suggests there _is_ a need to pre-check for a non-NULL vCPU.

All that said, we can get the bost of both words by simply not caching "tdx"; there's only one use anyways.

x86/kvm/vmx/tdx.c +2 -4
index ee073cacafbe..f53bac52449b 100644
@@ -1684,7 +1684,6 @@ static int tdx_sept_map_nonleaf_spte(struct kvm *kvm, gfn_t gfn,
                                     enum pg_level level, u64 new_spte)
 {
        struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
-       struct vcpu_tdx *tdx = to_tdx(vcpu);
        gpa_t gpa = gfn_to_gpa(gfn);
        u64 err, entry, level_state;
        struct page *sept_pt;
@@ -1697,7 +1696,7 @@ static int tdx_sept_map_nonleaf_spte(struct kvm *kvm, gfn_t gfn,
        if (!sept_pt)
                return -EIO;
 
-       ret = tdx_pamt_get(page_to_pfn(sept_pt), &tdx->pamt_cache);
+       ret = tdx_pamt_get(page_to_pfn(sept_pt), &to_tdx(vcpu)->pamt_cache);
        if (ret)
                return ret;
 
@@ -1721,7 +1720,6 @@ static int tdx_sept_map_leaf_spte(struct kvm *kvm, gfn_t gfn, enum pg_level leve
        struct kvm_vcpu *vcpu = kvm_get_running_vcpu();
        struct kvm_tdx *kvm_tdx = to_kvm_tdx(kvm);
        kvm_pfn_t pfn = spte_to_pfn(new_spte);
-       struct vcpu_tdx *tdx = to_tdx(vcpu);
        int ret;
 
        if (KVM_BUG_ON(!vcpu, kvm))
@@ -1733,7 +1731,7 @@ static int tdx_sept_map_leaf_spte(struct kvm *kvm, gfn_t gfn, enum pg_level leve
 
        WARN_ON_ONCE((new_spte & VMX_EPT_RWX_MASK) != VMX_EPT_RWX_MASK);
 
-       ret = tdx_pamt_get(pfn, &tdx->pamt_cache);
+       ret = tdx_pamt_get(pfn, &to_tdx(vcpu)->pamt_cache);
        if (ret)
                return ret;
author maintainer
#92 lore raw

Re: [PATCH v6 09/11] KVM: TDX: Get/put PAMT pages when (un)mapping private memory

Quoted 1 line · Sean Christopherson

Heh, because of course I'm omnipotent and never make mistakes.

Just using failable Sean as a tie breaker.

Quoted 10 lines

I agree with the nit in the sense that this isn't a great pattern to encourage, but IMO the root of the ugly pattern is the use of kvm_get_running_vcpu() (which is sadly the lesser evil in this case).  I.e. I'm not terribly concerned about this code leading to more "problems" in the future.  And I don't really want to grab "tdx" later on because that deviates from the standard patterns in KVM and incorrectly suggests there _is_ a need to pre-check for a non-NULL vCPU.

All that said, we can get the bost of both words by simply not caching "tdx"; there's only one use anyways.

Oh yea duh, that's better.

#93 lore raw

Re: [PATCH v6 09/11] KVM: TDX: Get/put PAMT pages when (un)mapping private memory

In reply to Rick Edgecombe
Quoted 27 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Add Dynamic PAMT support to KVM's S-EPT MMU by "getting" a PAMT page when adding guest memory (PAGE.ADD or PAGE.AUG), and "putting" the page when removing guest memory (PAGE.REMOVE).

To access the per-vCPU PAMT caches without plumbing @vcpu throughout the TDP MMU, begrudgingly use kvm_get_running_vcpu() to get the vCPU, and bug the VM if KVM attempts to set an S-EPT leaf without an active vCPU. KVM only supports creating _new_ mappings in page (pre)fault paths, all of which require an active vCPU.

The PAMT memory holds metadata for TDX-protected memory. With Dynamic PAMT, PAMT_4K is allocated on demand. The kernel supplies the TDX module with a few pages that cover 2M of host physical memory.

Releases are balanced via tdx_pamt_put(): every control-page free goes through tdx_free_control_page(), and guest data pages are put directly on the successful tdh_mem_page_remove() path and in the tdx_mem_page_add/aug() error path.

Assisted-by Sashiko:claude-opus-4-6 GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7
Quoted 3 lines

---
v6:
- Don't have topup op take a min param (Yan, Sean)

The topup_external_cache x86 op still takes int min_nr_spts. Did you forget to remove it, or am I misreading this changelog?

author maintainer
#94 lore raw

Re: [PATCH v6 09/11] KVM: TDX: Get/put PAMT pages when (un)mapping private memory

Quoted 32 lines · Chao Gao
Quoted 27 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Add Dynamic PAMT support to KVM's S-EPT MMU by "getting" a PAMT page when adding guest memory (PAGE.ADD or PAGE.AUG), and "putting" the page when removing guest memory (PAGE.REMOVE).

To access the per-vCPU PAMT caches without plumbing @vcpu throughout the TDP MMU, begrudgingly use kvm_get_running_vcpu() to get the vCPU, and bug the VM if KVM attempts to set an S-EPT leaf without an active vCPU. KVM only supports creating _new_ mappings in page (pre)fault paths, all of which require an active vCPU.

The PAMT memory holds metadata for TDX-protected memory. With Dynamic PAMT, PAMT_4K is allocated on demand. The kernel supplies the TDX module with a few pages that cover 2M of host physical memory.

Releases are balanced via tdx_pamt_put(): every control-page free goes through tdx_free_control_page(), and guest data pages are put directly on the successful tdh_mem_page_remove() path and in the tdx_mem_page_add/aug() error path.

Assisted-by Sashiko:claude-opus-4-6 GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7
Quoted 3 lines

---
v6:
- Don't have topup op take a min param (Yan, Sean)

Quoted 2 lines

The topup_external_cache x86 op still takes int min_nr_spts. Did you forget to remove it, or am I misreading this changelog?

There was some discussion on v5 to drop the "min" param, but it got added back in later discussion and renamed min_nr_spts:
https://lore.kernel.org/lkml/[email protected]/#t

author maintainer
#95 lore raw

PATCH v6 10/11 x86/virt/tdx: Enable Dynamic PAMT

In reply to Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The Physical Address Metadata Table (PAMT) holds TDX metadata for physical memory and must be allocated by the kernel during TDX module initialization. Dynamic PAMT is a TDX module feature that can reduce this memory use by allocating part of the PAMT dynamically.

All pieces are in place to Enable Dynamic PAMT if it is supported. Determine if the TDX module supports it by checking the 'features0' bit exposed by the TDX module.

The TDX module also exposes information about whether the *system* (and not the module) supports Dynamic PAMT.

The TDX module documentation describes how PAMT works internally. To allow the last level to be dynamically allocated, it uses a 3 level tree structure, not unlike page tables. Like page tables, it has a maximum address space that it can cover. This address space can be covered in 48 bits. If the host physical address space is higher than this, than the TDX module can't guarantee the tree will be able to cover the TDX memory.

The TDX module exposes this system support via metadata stating the minimum number of HKIDs that need to be available in order for Dynamic PAMT to be usable. The reasoning appears to be that more HKIDs can shrink the "real" addressable physical address bits enough to make the 48 bit Dynamic PAMT limit workable on high physical address width HW. However, the docs also clearly explain the 48 bit limit and how this fits into the Dymamic PAMT tree constraints.

The handy x86_phys_bits value is already read and adjusted for keyid bits. So just compare that against 48 instead of reading more metadata and burdening the code with the more tenuous connection to minimum HKID bits.

---
v6:
- After Nikolai pointed out that the TDX docs actually have the Dynamic PAMT pages-per-2MB region fixed at 2 instead of variable sized, I checked over the docs more closely looking for anything else that might have been missed. Spotted this 48 bit physical address bit check in the docs, so added it.

---
 arch/x86/include/asm/tdx.h  | 11 ++++++++++-
 arch/x86/virt/vmx/tdx/tdx.c | 11 +++++++++--
 arch/x86/virt/vmx/tdx/tdx.h |  3 ---
 3 files changed, 19 insertions(+), 6 deletions(-)
arch/x86/include/asm/tdx.h +10 -1
index 191da84bbf2a1..187014686df3e 100644
@@ -33,6 +33,10 @@
 #define TDX_SUCCESS		0ULL
 #define TDX_RND_NO_ENTROPY	0x8000020300000000ULL
 
+/* Bit definitions of TDX_FEATURES0 metadata field */
+#define TDX_FEATURES0_NO_RBP_MOD		BIT_ULL(18)
+#define TDX_FEATURES0_DYNAMIC_PAMT		BIT_ULL(36)
+
 #ifndef __ASSEMBLER__
 
 #include <uapi/asm/mce.h>
@@ -152,7 +156,12 @@ const struct tdx_sys_info *tdx_get_sysinfo(void);
 
 static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)
 {
-	return false; /* To be enabled when kernel is ready */
+	/*
+	 * The TDX Module's internal Dynamic PAMT tree structure can't
+	 * handle physical addresses with more than 48 bits.
+	 */
+	return sysinfo->features.tdx_features0 & TDX_FEATURES0_DYNAMIC_PAMT &&
+	       boot_cpu_data.x86_phys_bits <= 48;
 }
 
 /* Simple structure for pre-allocating Dynamic PAMT pages outside of locks. */
arch/x86/virt/vmx/tdx/tdx.c +9 -2
index 3544794fb092a..75140511571bf 100644
@@ -1028,8 +1028,9 @@ static __init int construct_tdmrs(struct list_head *tmb_list,
 	return ret;
 }
 
-static __init int config_tdx_module(struct tdmr_info_list *tdmr_list,
-				    u64 global_keyid)
+#define TDX_SYS_CONFIG_DYNAMIC_PAMT	BIT(16)
+
+static __init int config_tdx_module(struct tdmr_info_list *tdmr_list, u64 global_keyid)
 {
 	struct tdx_module_args args = {};
 	u64 *tdmr_pa_array;
@@ -1056,6 +1057,12 @@ static __init int config_tdx_module(struct tdmr_info_list *tdmr_list,
 	args.rcx = __pa(tdmr_pa_array);
 	args.rdx = tdmr_list->nr_consumed_tdmrs;
 	args.r8 = global_keyid;
+
+	if (tdx_supports_dynamic_pamt(&tdx_sysinfo)) {
+		pr_info("Enable Dynamic PAMT\n");
+		args.r8 |= TDX_SYS_CONFIG_DYNAMIC_PAMT;
+	}
+
 	ret = seamcall_prerr(TDH_SYS_CONFIG, &args);
 
 	/* Free the array as it is not required anymore. */
arch/x86/virt/vmx/tdx/tdx.h +0 -3
index 8c39dde347cc2..68a68468fbeb6 100644
@@ -86,9 +86,6 @@ struct tdmr_info {
 	DECLARE_FLEX_ARRAY(struct tdmr_reserved_area, reserved_areas);
 } __packed __aligned(TDMR_INFO_ALIGNMENT);
 
-/* Bit definitions of TDX_FEATURES0 metadata field */
-#define TDX_FEATURES0_NO_RBP_MOD	BIT(18)
-
 /*
  * Do not put any hardware-defined TDX structure representations below
  * this comment!
Signature · 1 line
2.54.0
maintainer
#96 lore raw

Re: [PATCH v6 10/11] x86/virt/tdx: Enable Dynamic PAMT

arch/x86/include/asm/tdx.h const struct tdx_sys_info *tdx_get_sysinfo(void); · line 164

Quoted 11 lines · Rick Edgecombe
arch/x86/include/asm/tdx.h +6 -1
@@ -152,7 +156,12 @@ const struct tdx_sys_info *tdx_get_sysinfo(void);
 
 static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)
 {
-	return false; /* To be enabled when kernel is ready */
+	/*
+	 * The TDX Module's internal Dynamic PAMT tree structure can't
+	 * handle physical addresses with more than 48 bits.
+	 */
+	return sysinfo->features.tdx_features0 & TDX_FEATURES0_DYNAMIC_PAMT &&
+	       boot_cpu_data.x86_phys_bits <= 48;

Should we warn for >48?

Signature · 1 line
  Kiryl Shutsemau / Kirill A. Shutemov
#97 lore raw

Re: [PATCH v6 10/11] x86/virt/tdx: Enable Dynamic PAMT

Quoted 14 lines · Kiryl Shutsemau

arch/x86/include/asm/tdx.h const struct tdx_sys_info *tdx_get_sysinfo(void); · line 164

Quoted 11 lines · Rick Edgecombe
arch/x86/include/asm/tdx.h +6 -1
@@ -152,7 +156,12 @@ const struct tdx_sys_info *tdx_get_sysinfo(void);
 
 static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo)
 {
-	return false; /* To be enabled when kernel is ready */
+	/*
+	 * The TDX Module's internal Dynamic PAMT tree structure can't
+	 * handle physical addresses with more than 48 bits.
+	 */
+	return sysinfo->features.tdx_features0 & TDX_FEATURES0_DYNAMIC_PAMT &&
+	       boot_cpu_data.x86_phys_bits <= 48;

Should we warn for >48?

Maybe we should drop this check. If the TDX module cannot handle that case, advertising TDX_FEATURES0_DYNAMIC_PAMT is a bug and should be fixed by the module.

author maintainer
#98 lore raw

Re: [PATCH v6 10/11] x86/virt/tdx: Enable Dynamic PAMT

Quoted 16 lines · Chao Gao
Quoted 14 lines · Kiryl Shutsemau

arch/x86/include/asm/tdx.h const struct tdx_sys_info *tdx_get_sysinfo(void); · line 164

Quoted 11 lines · Rick Edgecombe
(quoted diff) +0 -0
@@ -152,7 +156,12 @@ const struct tdx_sys_info *tdx_get_sysinfo(void);


  static inline bool tdx_supports_dynamic_pamt(const struct tdx_sys_info *sysinfo) {

arch/x86/include/asm/tdx.h +6 -1
-	return false; /* To be enabled when kernel is ready */
+	/*
+	 * The TDX Module's internal Dynamic PAMT tree structure can't
+	 * handle physical addresses with more than 48 bits.
+	 */
+	return sysinfo->features.tdx_features0 & TDX_FEATURES0_DYNAMIC_PAMT &&
+	       boot_cpu_data.x86_phys_bits <= 48;

Should we warn for >48?

Quoted 3 lines

Maybe we should drop this check. If the TDX module cannot handle that case, advertising TDX_FEATURES0_DYNAMIC_PAMT is a bug and should be fixed by the module.

I totally agree this is an awkward thing to make the VMM check. But I think tdx_features0 is normally about what the *TDX Module* supports? When this is kind of a valid configuration check. The user can configure enough keyids to make Dynamic PAMT workable.

Looking... Actually there are some dynamic supported ones. Ok, I'll ask.

author maintainer
#99 lore raw

Re: [PATCH v6 10/11] x86/virt/tdx: Enable Dynamic PAMT

Quoted 1 line · Rick Edgecombe

Looking... Actually there are some dynamic supported ones. Ok, I'll ask.

Thanks for this suggestion. Looks like we can drop the check.

#100 lore raw

Re: [PATCH v6 10/11] x86/virt/tdx: Enable Dynamic PAMT

In reply to Rick Edgecombe
Quoted 11 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

The Physical Address Metadata Table (PAMT) holds TDX metadata for physical memory and must be allocated by the kernel during TDX module initialization. Dynamic PAMT is a TDX module feature that can reduce this memory use by allocating part of the PAMT dynamically.

All pieces are in place to Enable Dynamic PAMT if it is supported. Determine if the TDX module supports it by checking the 'features0' bit exposed by the TDX module.

Quoted 8 lines

The TDX module also exposes information about whether the *system* (and not the module) supports Dynamic PAMT.

The TDX module documentation describes how PAMT works internally. To allow the last level to be dynamically allocated, it uses a 3 level tree structure, not unlike page tables. Like page tables, it has a maximum address space that it can cover. This address space can be covered in 48 bits. If the host physical address space is higher than this, than the

                                                                  ^
                                                                then
Quoted 9 lines

TDX module can't guarantee the tree will be able to cover the TDX memory.

The TDX module exposes this system support via metadata stating the minimum number of HKIDs that need to be available in order for Dynamic PAMT to be usable. The reasoning appears to be that more HKIDs can shrink the "real" addressable physical address bits enough to make the 48 bit Dynamic PAMT limit workable on high physical address width HW. However, the docs also clearly explain the 48 bit limit and how this fits into the Dymamic PAMT tree constraints.

    ^

Dynamic

Quoted 8 lines

The handy x86_phys_bits value is already read and adjusted for keyid bits. So just compare that against 48 instead of reading more metadata and burdening the code with the more tenuous connection to minimum HKID bits.

It looks like whether to check 48 bit physical address width limitation is still open.

The rest LGTM.

author maintainer
#101 lore raw

PATCH v6 11/11 Documentation/x86: Add documentation for TDX's Dynamic PAMT

In reply to Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Expand TDX documentation to include information on the Dynamic PAMT feature.

The new section explains PAMT support in the TDX module and how Dynamic PAMT affects the kernel memory use.

Assisted-by Sashiko:claude-opus-4-6 GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

---
v6:
- Add missing word (Binbin)
- Use "::" instead of ":"
- Make format of dmesg example accurate

v3:
- Trim down docs to be about things that user cares about, instead of development history and other details like this.

---
 Documentation/arch/x86/tdx.rst | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
Documentation/arch/x86/tdx.rst +22 -0
index ff6b110291bc6..ce026a88b6f78 100644
@@ -73,6 +73,28 @@ initialize::
 
   [..] virt/tdx: TDX-Module initialization failed ...
 
+Dynamic PAMT
+------------
+
+PAMT is memory that the TDX module needs to keep data about each page
+(think like struct page). It needs to be handed to the TDX module for its
+exclusive use. For normal PAMT, this is installed when the TDX module
+is first loaded and comes to about 0.4% of system memory.
+
+Dynamic PAMT is a TDX feature that allows VMM to allocate part of the
+PAMT as needed (the parts for tracking 4KB size pages). The other page
+sizes (1GB and 2MB) are still allocated statically at the time of
+TDX module initialization. This reduces the amount of memory that TDX
+uses while TDs are not in use.
+
+When Dynamic PAMT is in use, dmesg shows it like::
+
+  [..] virt/tdx: Enable Dynamic PAMT
+  [..] virt/tdx: 10092 KB allocated for PAMT
+  [..] virt/tdx: TDX-Module initialized
+
+Dynamic PAMT is enabled automatically if supported.
+
 TDX Interaction to Other Kernel Components
 ------------------------------------------
 
Signature · 1 line
2.54.0
Reviewed-by on v6 11/11
#102 lore raw

Re: [PATCH v6 11/11] Documentation/x86: Add documentation for TDX's Dynamic PAMT

Quoted 5 lines · Rick Edgecombe

From: "Kirill A. Shutemov" <[email protected]>

Expand TDX documentation to include information on the Dynamic PAMT feature.

Quoted 7 lines

The new section explains PAMT support in the TDX module and how Dynamic PAMT affects the kernel memory use.

Assisted-by Sashiko:claude-opus-4-6 GitHub Copilot:claude-opus-4-6 Claude:claude-opus-4-7

One nit below.

Quoted 18 lines

---
v6:
- Add missing word (Binbin)
- Use "::" instead of ":"
- Make format of dmesg example accurate

v3:
- Trim down docs to be about things that user cares about, instead of development history and other details like this.

---
 Documentation/arch/x86/tdx.rst | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)
Documentation/arch/x86/tdx.rst +0 -0
index ff6b110291bc6..ce026a88b6f78 100644

Documentation/arch/x86/tdx.rst initialize:: · line 79

Quoted 7 lines
Documentation/arch/x86/tdx.rst +4 -0
@@ -73,6 +73,28 @@ initialize::
 
   [..] virt/tdx: TDX-Module initialization failed ...
 
+Dynamic PAMT
+------------
+
+PAMT

Nit:
It seems that there is no spelling out of the acronym in the source code or the documentation. Maybe it's a good place to give the full version. E.g.

Physical Address Metadata Table (PAMT) is ...

Quoted 22 lines

is memory that the TDX module needs to keep data about each page

Documentation/arch/x86/tdx.rst +18 -0
+(think like struct page). It needs to be handed to the TDX module for its
+exclusive use. For normal PAMT, this is installed when the TDX module
+is first loaded and comes to about 0.4% of system memory.
+
+Dynamic PAMT is a TDX feature that allows VMM to allocate part of the
+PAMT as needed (the parts for tracking 4KB size pages). The other page
+sizes (1GB and 2MB) are still allocated statically at the time of
+TDX module initialization. This reduces the amount of memory that TDX
+uses while TDs are not in use.
+
+When Dynamic PAMT is in use, dmesg shows it like::
+
+  [..] virt/tdx: Enable Dynamic PAMT
+  [..] virt/tdx: 10092 KB allocated for PAMT
+  [..] virt/tdx: TDX-Module initialized
+
+Dynamic PAMT is enabled automatically if supported.
+
 TDX Interaction to Other Kernel Components
 ------------------------------------------
Reviewed-by on the v6 series
#103 lore raw
In reply to Rick Edgecombe
Quoted 7 lines · Rick Edgecombe

For a simple small server with mostly physical contiguous RAM and no CXL complications, the basic implementation should be close to optimal anyway. And for big servers, an 8GB allocation is going to have less impact. In the end Dynamic PAMT *is* an optimization that we will force on as a good default option. Even with all the optimizations we could throw at it, if the system is 100% TDs, Dynamic PAMT could come out slightly behind. So judgment on good defaults is needed regardless.

From usage point of view it's not just a memory optimization though. These patches make it easier to see what gets allocated for TDX IMO.

This based on rebasing other patches on the dynamic PAMT series a few times over the past year. So for the series:

author maintainer
#104 lore raw
In reply to Rick Edgecombe

Sean,

Quoted 2 lines · Rick Edgecombe

  KVM: TDX: Allocate PAMT memory for TD and vCPU control structures
  KVM: TDX: Get/put PAMT pages when (un)mapping private memory

Would you be willing to take a look at these two patches that need ack's from the KVM side? I'm hoping to make the next version of this the last one. So it would be great to get any remaining comments before then.

Thanks.

#105 lore raw
Quoted 9 lines · Rick P Edgecombe

Sean,

Quoted 2 lines · Rick Edgecombe

  KVM: TDX: Allocate PAMT memory for TD and vCPU control structures
  KVM: TDX: Get/put PAMT pages when (un)mapping private memory

Would you be willing to take a look at these two patches that need ack's from the KVM side? I'm hoping to make the next version of this the last one. So it would be great to get any remaining comments before then.

LGTM beyond the to_tdx() and Assited-by nits.

author maintainer
#106 lore raw
Quoted 4 lines · Sean Christopherson
Quoted 3 lines · Rick P Edgecombe

Sean,

On Mon, 2026-05-25 at 19:35 -0700, Rick Edgecombe wrote:

Quoted 8 lines
Quoted 6 lines
Quoted 2 lines

  KVM: TDX: Allocate PAMT memory for TD and vCPU control structures
  KVM: TDX: Get/put PAMT pages when (un)mapping private memory

Would you be willing to take a look at these two patches that need ack's from the KVM side? I'm hoping to make the next version of this the last one. So it would be great to get any remaining comments before then.

LGTM beyond the to_tdx() and Assited-by nits.

Thanks Sean!