Skip to contentSkip to conversation

TDX host kernel support

PATCH Superseded Kai Huang 11 participants 163 messages Nov 21, 2022 – Dec 8, 2022 Page 2 of 2

Subsystems (6)

v7 of 15 Superseded Latest is v15 →

lore
Share & tools
lore
author
#103 lore raw

Re: [PATCH v7 10/20] x86/virt/tdx: Use all system memory when initializing TDX module as TDX memory

In reply to David Hildenbrand
Quoted 50 lines · David Hildenbrand
Quoted 49 lines · Kai
Quoted 5 lines · Dan Williams
Quoted 5 lines
arch/x86/mm/init_64.c +0 -0
@@ -968,6 +969,15 @@ int arch_add_memory(int nid, u64 start, u64 size,
   	unsigned long start_pfn = start >> PAGE_SHIFT;
   	unsigned long nr_pages = size >> PAGE_SHIFT;
 
Quoted 12 lines

arch/x86/mm/init_64.c int arch_add_memory(int nid, u64 start, u64 size, · line 979

Quoted 8 lines
arch/x86/mm/init_64.c +8 -0
+	/*
+	 * For now if TDX is enabled, all pages in the page allocator
+	 * must be TDX memory, which is a fixed set of memory regions
+	 * that are passed to the TDX module.  Reject the new region
+	 * if it is not TDX memory to guarantee above is true.
+	 */
+	if (!tdx_cc_memory_compatible(start_pfn, start_pfn + nr_pages))
+		return -EINVAL;

arch_add_memory() does not add memory to the page allocator.  For example, memremap_pages() uses arch_add_memory() and explicitly does not release the memory to the page allocator.

Indeed. Sorry I missed this.

Quoted 3 lines

This check belongs in
add_memory_resource() to prevent new memory that violates TDX from being onlined.

This would require adding another 'arch_cc_memory_compatible()' to the common add_memory_resource() (I actually long time ago had such patch to work with the memremap_pages() you mentioned above).

How about adding a memory_notifier to the TDX code, and reject online of TDX incompatible memory (something like below)? The benefit is this is TDX code self contained and won't pollute the common mm code:

(quoted diff) +16 -0
+static int tdx_memory_notifier(struct notifier_block *nb,
+                              unsigned long action, void *v)
+{
+       struct memory_notify *mn = v;
+
+       if (action != MEM_GOING_ONLINE)
+               return NOTIFY_OK;
+
+       /*
+        * Not all memory is compatible with TDX.  Reject
+        * online of any incompatible memory.
+        */
+       return tdx_cc_memory_compatible(mn->start_pfn,
+                       mn->start_pfn + mn->nr_pages) ? NOTIFY_OK : NOTIFY_BAD;
+}
+
Quoted 8 lines

Review

Quoted 3 lines
(quoted diff) +3 -0
+static struct notifier_block tdx_memory_nb = {
+       .notifier_call = tdx_memory_notifier,
+};

With mhp_memmap_on_memory() some memory might already be touched during add_memory() (because part of the hotplug memory is used for holding the memmap), not when actually onlining memory. So in that case, this would be too late.

Hi David,

Thanks for the review!

Right. The memmap pages are added to the zone before online_pages(), but IIUC those memmap pages will never be free pages thus won't be allocated by the page allocator, correct? Therefore in practice there won't be problem even they are not TDX compatible memory.

Quoted 4 lines

add_memory_resource() sounds better, even though I disgust such TDX special handling in common code.

Given above, do you still prefer changing add_memory_resource()? If so I'll change to modify add_memory_resource().

#104 lore raw

Re: [PATCH v7 10/20] x86/virt/tdx: Use all system memory when initializing TDX module as TDX memory

Quoted 60 lines · Kai
Quoted 50 lines · David Hildenbrand
Quoted 49 lines · Kai
Quoted 5 lines · Dan Williams
Quoted 5 lines
arch/x86/mm/init_64.c +0 -0
@@ -968,6 +969,15 @@ int arch_add_memory(int nid, u64 start, u64 size,
    	unsigned long start_pfn = start >> PAGE_SHIFT;
    	unsigned long nr_pages = size >> PAGE_SHIFT;
 
Quoted 12 lines

arch/x86/mm/init_64.c int arch_add_memory(int nid, u64 start, u64 size, · line 979

Quoted 8 lines
arch/x86/mm/init_64.c +8 -0
+	/*
+	 * For now if TDX is enabled, all pages in the page allocator
+	 * must be TDX memory, which is a fixed set of memory regions
+	 * that are passed to the TDX module.  Reject the new region
+	 * if it is not TDX memory to guarantee above is true.
+	 */
+	if (!tdx_cc_memory_compatible(start_pfn, start_pfn + nr_pages))
+		return -EINVAL;

arch_add_memory() does not add memory to the page allocator.  For example, memremap_pages() uses arch_add_memory() and explicitly does not release the memory to the page allocator.

Indeed. Sorry I missed this.

Quoted 3 lines

This check belongs in
add_memory_resource() to prevent new memory that violates TDX from being onlined.

This would require adding another 'arch_cc_memory_compatible()' to the common add_memory_resource() (I actually long time ago had such patch to work with the memremap_pages() you mentioned above).

How about adding a memory_notifier to the TDX code, and reject online of TDX incompatible memory (something like below)? The benefit is this is TDX code self contained and won't pollute the common mm code:

(quoted diff) +16 -0
+static int tdx_memory_notifier(struct notifier_block *nb,
+                              unsigned long action, void *v)
+{
+       struct memory_notify *mn = v;
+
+       if (action != MEM_GOING_ONLINE)
+               return NOTIFY_OK;
+
+       /*
+        * Not all memory is compatible with TDX.  Reject
+        * online of any incompatible memory.
+        */
+       return tdx_cc_memory_compatible(mn->start_pfn,
+                       mn->start_pfn + mn->nr_pages) ? NOTIFY_OK : NOTIFY_BAD;
+}
+
Quoted 8 lines

Review

Quoted 3 lines
(quoted diff) +3 -0
+static struct notifier_block tdx_memory_nb = {
+       .notifier_call = tdx_memory_notifier,
+};

With mhp_memmap_on_memory() some memory might already be touched during add_memory() (because part of the hotplug memory is used for holding the memmap), not when actually onlining memory. So in that case, this would be too late.

Quoted 8 lines

Hi David,

Thanks for the review!

Right. The memmap pages are added to the zone before online_pages(), but IIUC those memmap pages will never be free pages thus won't be allocated by the page allocator, correct? Therefore in practice there won't be problem even they are not TDX compatible memory.

But that memory will be read/written. Isn't that an issue, for example, if memory doesn't get accepted etc?

Signature · 3 lines
Thanks,

David / dhildenb
author
#135 lore raw

Re: [PATCH v7 14/20] x86/virt/tdx: Set up reserved areas for all TDMRs

In reply to Dave Hansen
Quoted 8 lines · Dave Hansen

arch/x86/virt/vmx/tdx/tdx.c static unsigned long tdmrs_count_pamt_pages(struct tdmr_info *tdmr_array, · line 795

Quoted 3 lines
arch/x86/virt/vmx/tdx/tdx.c +3 -0
+static int tdmr_set_up_memory_hole_rsvd_areas(struct tdmr_info *tdmr,
+					      int *rsvd_idx)
+{

This needs a comment.

This is another case where it's confusing to be passing around 'struct tdmr_info *'. Is this *A* TDMR or an array?

It is for one TDMR but not an array. All functions in form of tdmr_xxx() are operations for one TDMR.

But I agree it's not clear.

Quoted 9 lines

/*
 * Go through tdx_memlist to find holes between memory areas. If any of
 * those holes fall within @tdmr, set up a TDMR reserved area to cover
 * the hole.
 */
static int tdmr_populate_rsvd_holes(struct list_head *tdx_memlist,
struct tdmr_info *tdmr, int *rsvd_idx)

Thanks!

Should I also change below function 'tdmr_set_up_pamt_rsvd_areas()' to, i.e. tdmr_populate_rsvd_pamts()?

Actually, there are two more functions in this patch: tdmr_set_up_rsvd_areas() and tdmrs_set_up_rsvd_areas_all(). Should I also change them to tdmr_populate_rsvd_areas() and tdmrs_populate_rsvd_areas_all()?

Quoted 11 lines

arch/x86/virt/vmx/tdx/tdx.c static unsigned long tdmrs_count_pamt_pages(struct tdmr_info *tdmr_array, · line 801

Quoted 7 lines
arch/x86/virt/vmx/tdx/tdx.c +6 -0
+	struct tdx_memblock *tmb;
+	u64 prev_end;
+	int ret;
+
+	/* Mark holes between memory regions as reserved */
+	prev_end = tdmr_start(tdmr);

I'm having a hard time following this, especially the mixing of semantics between 'prev_end' both pointing to tdmr and to tmb addresses.

Quoted 6 lines

Here, 'prev_end' logically represents the last address which we know has been handled. All of the holes in the addresses below it have been dealt with. It is safe to set here to tdmr_start() because this function call is uniquely tasked with setting up reserved areas in 'tdmr'. So, it can safely consider any holes before tdmr_start(tdmr) as being handled.

Yes.

Quoted 7 lines

But, dang, there's a lot of complexity there.

First, the:

	/* Mark holes between memory regions as reserved */
Quoted 7 lines

comment is misleading. It has *ZILCH* to do with the "prev_end = tdmr_start(tdmr);" assignment.

This at least needs:

   /* Start looking for reserved blocks at the beginning of the TDMR: */ prev_end = tdmr_start(tdmr);

Right. Sorry for the bad comment.

Quoted 13 lines

but I also get the feeling that 'prev_end' is a crummy variable name. I don't have any better suggestions at the moment.

arch/x86/virt/vmx/tdx/tdx.c static unsigned long tdmrs_count_pamt_pages(struct tdmr_info *tdmr_array, · line 807

Quoted 6 lines
arch/x86/virt/vmx/tdx/tdx.c +6 -0
+	list_for_each_entry(tmb, &tdx_memlist, list) {
+		u64 start, end;
+
+		start = tmb->start_pfn << PAGE_SHIFT;
+		end = tmb->end_pfn << PAGE_SHIFT;
+

More alignment opportunities:

Quoted 2 lines
		start = tmb->start_pfn << PAGE_SHIFT;
		end   = tmb->end_pfn   << PAGE_SHIFT;

Should I use PFN_PHYS()? Then looks we don't need this alignment.

Quoted 23 lines
Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +8 -0
+		/* Break if this region is after the TDMR */
+		if (start >= tdmr_end(tdmr))
+			break;
+
+		/* Exclude regions before this TDMR */
+		if (end < tdmr_start(tdmr))
+			continue;
+

arch/x86/virt/vmx/tdx/tdx.c static unsigned long tdmrs_count_pamt_pages(struct tdmr_info *tdmr_array, · line 825

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.c +10 -0
+		/*
+		 * Skip if no hole exists before this region. "<=" is
+		 * used because one memory region might span two TDMRs
+		 * (when the previous TDMR covers part of this region).
+		 * In this case the start address of this region is
+		 * smaller than the start address of the second TDMR.
+		 *
+		 * Update the prev_end to the end of this region where
+		 * the possible memory hole starts.
+		 */

Can't this just be:

Quoted 4 lines
		/*
		 * Skip over memory areas that
		 * have already been dealt with.
		 */

I think so. This actually also covers the "two contiguous memory regions" case, which isn't mentioned in the original comment.

Quoted 114 lines
Quoted 109 lines
arch/x86/virt/vmx/tdx/tdx.c +26 -0
+		if (start <= prev_end) {
+			prev_end = end;
+			continue;
+		}
+
+		/* Add the hole before this region */
+		ret = tdmr_add_rsvd_area(tdmr, rsvd_idx, prev_end,
+				start - prev_end);
+		if (ret)
+			return ret;
+
+		prev_end = end;
+	}
+
+	/* Add the hole after the last region if it exists. */
+	if (prev_end < tdmr_end(tdmr)) {
+		ret = tdmr_add_rsvd_area(tdmr, rsvd_idx, prev_end,
+				tdmr_end(tdmr) - prev_end);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
+static int tdmr_set_up_pamt_rsvd_areas(struct tdmr_info *tdmr, int

*rsvd_idx,

arch/x86/virt/vmx/tdx/tdx.c +72 -0
+				       struct tdmr_info *tdmr_array,
+				       int tdmr_num)
+{
+	int i, ret;
+
+	/*
+	 * If any PAMT overlaps with this TDMR, the overlapping part
+	 * must also be put to the reserved area too.  Walk over all
+	 * TDMRs to find out those overlapping PAMTs and put them to
+	 * reserved areas.
+	 */
+	for (i = 0; i < tdmr_num; i++) {
+		struct tdmr_info *tmp = tdmr_array_entry(tdmr_array, i);
+		unsigned long pamt_start_pfn, pamt_npages;
+		u64 pamt_start, pamt_end;
+
+		tdmr_get_pamt(tmp, &pamt_start_pfn, &pamt_npages);
+		/* Each TDMR must already have PAMT allocated */
+		WARN_ON_ONCE(!pamt_npages || !pamt_start_pfn);
+
+		pamt_start = pamt_start_pfn << PAGE_SHIFT;
+		pamt_end = pamt_start + (pamt_npages << PAGE_SHIFT);
+
+		/* Skip PAMTs outside of the given TDMR */
+		if ((pamt_end <= tdmr_start(tdmr)) ||
+				(pamt_start >= tdmr_end(tdmr)))
+			continue;
+
+		/* Only mark the part within the TDMR as reserved */
+		if (pamt_start < tdmr_start(tdmr))
+			pamt_start = tdmr_start(tdmr);
+		if (pamt_end > tdmr_end(tdmr))
+			pamt_end = tdmr_end(tdmr);
+
+		ret = tdmr_add_rsvd_area(tdmr, rsvd_idx, pamt_start,
+				pamt_end - pamt_start);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
+/* Compare function called by sort() for TDMR reserved areas */
+static int rsvd_area_cmp_func(const void *a, const void *b)
+{
+	struct tdmr_reserved_area *r1 = (struct tdmr_reserved_area *)a;
+	struct tdmr_reserved_area *r2 = (struct tdmr_reserved_area *)b;
+
+	if (r1->offset + r1->size <= r2->offset)
+		return -1;
+	if (r1->offset >= r2->offset + r2->size)
+		return 1;
+
+	/* Reserved areas cannot overlap.  The caller should guarantee. */
+	WARN_ON_ONCE(1);
+	return -1;
+}
+
+/* Set up reserved areas for a TDMR, including memory holes and PAMTs */
+static int tdmr_set_up_rsvd_areas(struct tdmr_info *tdmr,
+				  struct tdmr_info *tdmr_array,
+				  int tdmr_num)
+{
+	int ret, rsvd_idx = 0;
+
+	/* Put all memory holes within the TDMR into reserved areas */
+	ret = tdmr_set_up_memory_hole_rsvd_areas(tdmr, &rsvd_idx);
+	if (ret)
+		return ret;
+
+	/* Put all (overlapping) PAMTs within the TDMR into reserved areas

*/

(quoted diff) +1 -0
+	ret = tdmr_set_up_pamt_rsvd_areas(tdmr, &rsvd_idx, tdmr_array,

tdmr_num);

arch/x86/virt/vmx/tdx/tdx.c +5 -0
+	if (ret)
+		return ret;
+
+	/* TDX requires reserved areas listed in address ascending order */
+	sort(tdmr->reserved_areas, rsvd_idx, sizeof(struct

tdmr_reserved_area),

arch/x86/virt/vmx/tdx/tdx.c static unsigned long tdmrs_count_pamt_pages(struct tdmr_info *tdmr_array, · line 930

Quoted 1 line
arch/x86/virt/vmx/tdx/tdx.c +1 -0
+			rsvd_area_cmp_func, NULL);

Ugh, and I guess we don't know where the PAMTs will be ordered with respect to holes, so sorting is the easiest way to do this.

Quoted 1 line

<snip>

Right.

author
#105 lore raw

Re: [PATCH v7 10/20] x86/virt/tdx: Use all system memory when initializing TDX module as TDX memory

In reply to David Hildenbrand
Quoted 65 lines · David Hildenbrand
Quoted 64 lines · Kai
Quoted 50 lines · David Hildenbrand
Quoted 49 lines · Kai
Quoted 5 lines · Dan Williams
Quoted 5 lines
arch/x86/mm/init_64.c +0 -0
@@ -968,6 +969,15 @@ int arch_add_memory(int nid, u64 start, u64 size,
    	unsigned long start_pfn = start >> PAGE_SHIFT;
    	unsigned long nr_pages = size >> PAGE_SHIFT;
 
Quoted 12 lines

arch/x86/mm/init_64.c int arch_add_memory(int nid, u64 start, u64 size, · line 979

Quoted 8 lines
arch/x86/mm/init_64.c +8 -0
+	/*
+	 * For now if TDX is enabled, all pages in the page allocator
+	 * must be TDX memory, which is a fixed set of memory regions
+	 * that are passed to the TDX module.  Reject the new region
+	 * if it is not TDX memory to guarantee above is true.
+	 */
+	if (!tdx_cc_memory_compatible(start_pfn, start_pfn + nr_pages))
+		return -EINVAL;

arch_add_memory() does not add memory to the page allocator.  For example, memremap_pages() uses arch_add_memory() and explicitly does not release the memory to the page allocator.

Indeed. Sorry I missed this.

Quoted 3 lines

This check belongs in
add_memory_resource() to prevent new memory that violates TDX from being onlined.

This would require adding another 'arch_cc_memory_compatible()' to the common add_memory_resource() (I actually long time ago had such patch to work with the memremap_pages() you mentioned above).

How about adding a memory_notifier to the TDX code, and reject online of TDX incompatible memory (something like below)? The benefit is this is TDX code self contained and won't pollute the common mm code:

(quoted diff) +16 -0
+static int tdx_memory_notifier(struct notifier_block *nb,
+                              unsigned long action, void *v)
+{
+       struct memory_notify *mn = v;
+
+       if (action != MEM_GOING_ONLINE)
+               return NOTIFY_OK;
+
+       /*
+        * Not all memory is compatible with TDX.  Reject
+        * online of any incompatible memory.
+        */
+       return tdx_cc_memory_compatible(mn->start_pfn,
+                       mn->start_pfn + mn->nr_pages) ? NOTIFY_OK : NOTIFY_BAD;
+}
+
Quoted 8 lines

Review

Quoted 3 lines
(quoted diff) +3 -0
+static struct notifier_block tdx_memory_nb = {
+       .notifier_call = tdx_memory_notifier,
+};

With mhp_memmap_on_memory() some memory might already be touched during add_memory() (because part of the hotplug memory is used for holding the memmap), not when actually onlining memory. So in that case, this would be too late.

Hi David,

Thanks for the review!

Quoted 8 lines
Quoted 4 lines

Right. The memmap pages are added to the zone before online_pages(), but IIUC those memmap pages will never be free pages thus won't be allocated by the page allocator, correct? Therefore in practice there won't be problem even they are not TDX compatible memory.

But that memory will be read/written. Isn't that an issue, for example, if memory doesn't get accepted etc?

Sorry I don't quite understand "if memory doesn't get accepted" mean. Do you mean accepted by the TDX module?

Only the host kernel will read/write those memmap pages. The TDX module won't (as they won't be allocated to be used as TDX guest memory or TDX module metadata). So it's fine.

#106 lore raw

Re: [PATCH v7 10/20] x86/virt/tdx: Use all system memory when initializing TDX module as TDX memory

Quoted 75 lines · Kai
Quoted 65 lines · David Hildenbrand
Quoted 64 lines · Kai
Quoted 50 lines · David Hildenbrand
Quoted 49 lines · Kai
Quoted 5 lines · Dan Williams
Quoted 5 lines
(quoted diff) +0 -0
@@ -968,6 +969,15 @@ int arch_add_memory(int nid, u64 start, u64 size,
     	unsigned long start_pfn = start >> PAGE_SHIFT;
     	unsigned long nr_pages = size >> PAGE_SHIFT;
 
Quoted 12 lines

Review int arch_add_memory(int nid, u64 start, u64 size, · line 979

Quoted 8 lines
(quoted diff) +8 -0
+	/*
+	 * For now if TDX is enabled, all pages in the page allocator
+	 * must be TDX memory, which is a fixed set of memory regions
+	 * that are passed to the TDX module.  Reject the new region
+	 * if it is not TDX memory to guarantee above is true.
+	 */
+	if (!tdx_cc_memory_compatible(start_pfn, start_pfn + nr_pages))
+		return -EINVAL;

arch_add_memory() does not add memory to the page allocator.  For example, memremap_pages() uses arch_add_memory() and explicitly does not release the memory to the page allocator.

Indeed. Sorry I missed this.

Quoted 3 lines

This check belongs in
add_memory_resource() to prevent new memory that violates TDX from being onlined.

This would require adding another 'arch_cc_memory_compatible()' to the common add_memory_resource() (I actually long time ago had such patch to work with the memremap_pages() you mentioned above).

How about adding a memory_notifier to the TDX code, and reject online of TDX incompatible memory (something like below)? The benefit is this is TDX code self contained and won't pollute the common mm code:

(quoted diff) +16 -0
+static int tdx_memory_notifier(struct notifier_block *nb,
+                              unsigned long action, void *v)
+{
+       struct memory_notify *mn = v;
+
+       if (action != MEM_GOING_ONLINE)
+               return NOTIFY_OK;
+
+       /*
+        * Not all memory is compatible with TDX.  Reject
+        * online of any incompatible memory.
+        */
+       return tdx_cc_memory_compatible(mn->start_pfn,
+                       mn->start_pfn + mn->nr_pages) ? NOTIFY_OK : NOTIFY_BAD;
+}
+
Quoted 8 lines

Review

Quoted 3 lines
(quoted diff) +3 -0
+static struct notifier_block tdx_memory_nb = {
+       .notifier_call = tdx_memory_notifier,
+};

With mhp_memmap_on_memory() some memory might already be touched during add_memory() (because part of the hotplug memory is used for holding the memmap), not when actually onlining memory. So in that case, this would be too late.

Hi David,

Thanks for the review!

Quoted 8 lines
Quoted 4 lines

Right. The memmap pages are added to the zone before online_pages(), but IIUC those memmap pages will never be free pages thus won't be allocated by the page allocator, correct? Therefore in practice there won't be problem even they are not TDX compatible memory.

But that memory will be read/written. Isn't that an issue, for example, if memory doesn't get accepted etc?

Quoted 6 lines

Sorry I don't quite understand "if memory doesn't get accepted" mean. Do you mean accepted by the TDX module?

Only the host kernel will read/write those memmap pages. The TDX module won't (as they won't be allocated to be used as TDX guest memory or TDX module metadata). So it's fine.

Oh, so we're not also considering hotplugging memory to a TDX VM that might not be backed by TDX. Got it.

So what you want to prevent is getting !TDX memory exposed to the buddy such that it won't accidentally get allocated for a TDX guest, correct?

In that case, memory notifiers would indeed be fine.

Thanks!

Signature · 3 lines
Thanks,

David / dhildenb
author
#107 lore raw

Re: [PATCH v7 10/20] x86/virt/tdx: Use all system memory when initializing TDX module as TDX memory

Quoted 83 lines · David Hildenbrand
Quoted 75 lines · Kai
Quoted 65 lines · David Hildenbrand
Quoted 64 lines · Kai
Quoted 50 lines · David Hildenbrand
Quoted 49 lines · Kai
Quoted 5 lines · Dan Williams
Quoted 5 lines
(quoted diff) +0 -0
@@ -968,6 +969,15 @@ int arch_add_memory(int nid, u64 start, u64 size,
     	unsigned long start_pfn = start >> PAGE_SHIFT;
     	unsigned long nr_pages = size >> PAGE_SHIFT;
 
Quoted 12 lines

Review int arch_add_memory(int nid, u64 start, u64 size, · line 979

Quoted 8 lines
(quoted diff) +8 -0
+	/*
+	 * For now if TDX is enabled, all pages in the page allocator
+	 * must be TDX memory, which is a fixed set of memory regions
+	 * that are passed to the TDX module.  Reject the new region
+	 * if it is not TDX memory to guarantee above is true.
+	 */
+	if (!tdx_cc_memory_compatible(start_pfn, start_pfn + nr_pages))
+		return -EINVAL;

arch_add_memory() does not add memory to the page allocator.  For example, memremap_pages() uses arch_add_memory() and explicitly does not release the memory to the page allocator.

Indeed. Sorry I missed this.

Quoted 3 lines

This check belongs in
add_memory_resource() to prevent new memory that violates TDX from being onlined.

This would require adding another 'arch_cc_memory_compatible()' to the common add_memory_resource() (I actually long time ago had such patch to work with the memremap_pages() you mentioned above).

How about adding a memory_notifier to the TDX code, and reject online of TDX incompatible memory (something like below)? The benefit is this is TDX code self contained and won't pollute the common mm code:

(quoted diff) +16 -0
+static int tdx_memory_notifier(struct notifier_block *nb,
+                              unsigned long action, void *v)
+{
+       struct memory_notify *mn = v;
+
+       if (action != MEM_GOING_ONLINE)
+               return NOTIFY_OK;
+
+       /*
+        * Not all memory is compatible with TDX.  Reject
+        * online of any incompatible memory.
+        */
+       return tdx_cc_memory_compatible(mn->start_pfn,
+                       mn->start_pfn + mn->nr_pages) ? NOTIFY_OK : NOTIFY_BAD;
+}
+
Quoted 8 lines

Review

Quoted 3 lines
(quoted diff) +3 -0
+static struct notifier_block tdx_memory_nb = {
+       .notifier_call = tdx_memory_notifier,
+};

With mhp_memmap_on_memory() some memory might already be touched during add_memory() (because part of the hotplug memory is used for holding the memmap), not when actually onlining memory. So in that case, this would be too late.

Hi David,

Thanks for the review!

Quoted 8 lines
Quoted 4 lines

Right. The memmap pages are added to the zone before online_pages(), but IIUC those memmap pages will never be free pages thus won't be allocated by the page allocator, correct? Therefore in practice there won't be problem even they are not TDX compatible memory.

But that memory will be read/written. Isn't that an issue, for example, if memory doesn't get accepted etc?

Quoted 6 lines

Sorry I don't quite understand "if memory doesn't get accepted" mean. Do you mean accepted by the TDX module?

Only the host kernel will read/write those memmap pages. The TDX module won't (as they won't be allocated to be used as TDX guest memory or TDX module metadata). So it's fine.

Quoted 5 lines

Oh, so we're not also considering hotplugging memory to a TDX VM that might not be backed by TDX. Got it.

So what you want to prevent is getting !TDX memory exposed to the buddy such that it won't accidentally get allocated for a TDX guest, correct?

Yes correct.

Quoted 5 lines

In that case, memory notifiers would indeed be fine.

Thanks!

Thanks.

#136 lore raw

Re: [PATCH v7 14/20] x86/virt/tdx: Set up reserved areas for all TDMRs

In reply to Huang, Kai
Quoted 1 line · Kai

On Wed, 2022-11-23 at 15:39 -0800, Dave Hansen wrote:

...

Quoted 9 lines
Quoted 8 lines

/*
 * Go through tdx_memlist to find holes between memory areas. If any of
 * those holes fall within @tdmr, set up a TDMR reserved area to cover
 * the hole.
 */
static int tdmr_populate_rsvd_holes(struct list_head *tdx_memlist,
struct tdmr_info *tdmr, int *rsvd_idx)

Quoted 8 lines

Thanks!

Should I also change below function 'tdmr_set_up_pamt_rsvd_areas()' to, i.e. tdmr_populate_rsvd_pamts()?

Actually, there are two more functions in this patch: tdmr_set_up_rsvd_areas() and tdmrs_set_up_rsvd_areas_all(). Should I also change them to tdmr_populate_rsvd_areas() and tdmrs_populate_rsvd_areas_all()?

I don't know. I'll look at the naming again once I see it all together.

Quoted 12 lines
Quoted 12 lines

but I also get the feeling that 'prev_end' is a crummy variable name. I don't have any better suggestions at the moment.

arch/x86/virt/vmx/tdx/tdx.c static unsigned long tdmrs_count_pamt_pages(struct tdmr_info *tdmr_array, · line 807

Quoted 6 lines
arch/x86/virt/vmx/tdx/tdx.c +6 -0
+	list_for_each_entry(tmb, &tdx_memlist, list) {
+		u64 start, end;
+
+		start = tmb->start_pfn << PAGE_SHIFT;
+		end = tmb->end_pfn << PAGE_SHIFT;
+

More alignment opportunities:

Quoted 4 lines
Quoted 2 lines
		start = tmb->start_pfn << PAGE_SHIFT;
		end   = tmb->end_pfn   << PAGE_SHIFT;

Should I use PFN_PHYS()? Then looks we don't need this alignment.

Sure.

#115 lore raw

Re: [PATCH v7 11/20] x86/virt/tdx: Add placeholder to construct TDMRs to cover all TDX memory regions

In reply to Huang, Kai
Quoted 9 lines · Kai
Quoted 3 lines · Dave Hansen

First, I think 'tdx_sysinfo' should probably be a local variable in init_tdx_module() and have its address passed in here. Having global variables always makes it more opaque about who is initializing it.

Sorry I missed to respond this.

Using local variable for 'tdx_sysinfo' will cause a build warning:

https://lore.kernel.org/lkml/[email protected]/

Having it be local scope is a lot more important than having it be on stack. Just declare it local to the function but keep it off the stack.
No need to dynamically allocate it, even.

#129 lore raw

Re: [PATCH v7 13/20] x86/virt/tdx: Allocate and set up PAMTs for TDMRs

In reply to Huang, Kai
Quoted 9 lines · Kai
Quoted 8 lines · Dave Hansen
Quoted 6 lines · Kai Huang

Use alloc_contig_pages() since PAMT must be a physically contiguous area and it may be potentially large (~1/256th of the size of the given TDMR). The downside is alloc_contig_pages() may fail at runtime. One (bad) mitigation is to launch a TD guest early during system boot to get those PAMTs allocated at early time, but the only way to fix is to add a boot option to allocate or reserve PAMTs during kernel boot.

Quoted 6 lines
Quoted 4 lines

FWIW, we all agree that this is a bad permanent way to leave things. You can call me out here as proposing that this wart be left in place while this series is merged and is a detail we can work on afterword with new module params, boot options, Kconfig or whatever.

Sorry do you mean to call out in the cover letter, or in this changelog?

Cover letter would be best. But, a note in the changelog that it is imperfect and will be improved on later would also be nice.

Quoted 7 lines
Quoted 7 lines
Quoted 6 lines
arch/x86/virt/vmx/tdx/tdx.c +6 -0
+   /*
+    * Fall back to allocating the TDMR's metadata from node 0 when
+    * no TDX memory block can be found.  This should never happen
+    * since TDMRs originate from TDX memory blocks.
+    */
+   WARN_ON_ONCE(1);
Quoted 7 lines
Quoted 2 lines

That's probably better a pr_warn() or something. A backtrace and all that jazz seems a bit overly dramatic for this.

How about below?

pr_warn("TDMR [0x%llx, 0x%llx): unable to find local NUMA node for PAMT allocation, fallback to use node 0.\n");

I actually try to make these somewhat mirror the code. For instance, if you are searching using *just* the start TDMR address, then the message should only talk about the start address. Also, it's not trying to find a *node* per se. It's trying to find a 'tmb'. So, if someone wanted to debug this problem, they would actually want to dump out the tmbs.

But, back to the loop that this message describes:

arch/x86/virt/vmx/tdx/tdx.c static int create_tdmrs(struct tdmr_info *tdmr_array, int *tdmr_num) · line 635

Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +5 -0
+	/* Find the first memory region covered by the TDMR */
+	list_for_each_entry(tmb, &tdx_memlist, list) {
+		if (tmb->end_pfn > (tdmr_start(tdmr) >> PAGE_SHIFT))
+			return tmb->nid;
+	}

That loop is funky. It's not obvious at *all* why it even works.

1. A 'tmb' describes "real" memory. It never covers holes.
2. This code is trying to find *a* 'tmb' to place a structure in. It needs real memory to place this, of course.
3. A 'tdmr' may include holes and may not have a 'tmb' at either its start or end address
4. A 'tdmr' is expected to cover one or more 'tmb's. If there were no 'tmb's, then the TDMR is going to be marked as all reserved and is effectively being wasted.
5. A 'tdmr' may cover more than one NUMA node. If this happens, it is ok to get memory from any of those nodes for that tdmr's PAMT.

I'd include this comment on the loop:

A TDMR must cover at least part of one TMB. That TMB will end after the TDMR begins. But, that TMB may have started before the TDMR. Find the next 'tmb' that _ends_ after this TDMR begins. Ignore 'tmb' start addresses. They are irrelevant.

Maybe even a little ASCII diagram about the different tmb configurations that this can find:

| TDMR1 | TDMR2 |
   |---tmb---|
          |tmb|
          |------tmb-------|
   |------tmb-------|

I'd also include this on the function:

/*
* Locate a NUMA node which should hold the allocation of the @tdmr
* PAMT. This node will have some memory covered by the TDMR. The
* relative amount of memory covered is not considered. */

author
#116 lore raw

Re: [PATCH v7 11/20] x86/virt/tdx: Add placeholder to construct TDMRs to cover all TDX memory regions

In reply to Dave Hansen
Quoted 7 lines · Dave Hansen
Quoted 6 lines · Kai
Quoted 3 lines · Dave Hansen

First, I think 'tdx_sysinfo' should probably be a local variable in init_tdx_module() and have its address passed in here. Having global variables always makes it more opaque about who is initializing it.

Sorry I missed to respond this.

Quoted 7 lines
Quoted 3 lines

Using local variable for 'tdx_sysinfo' will cause a build warning:

https://lore.kernel.org/lkml/[email protected]/

Having it be local scope is a lot more important than having it be on stack. Just declare it local to the function but keep it off the stack.
No need to dynamically allocate it, even.

Apologize I am not entirely sure whether I fully got your point. Do you mean something like below?

static struct tdsysinfo_struct tdx_sysinfo;

static int tdmr_size_single(int max_reserved_per_tdmr)

{
	...
}

static int tdmr_array_size(struct tdsysinfo_struct *sysinfo)

{
	return tdmr_size_single(sysinfo->max_reserved_per_tdmr) *
			sysinfo->max_tdmrs;
}

static int init_tdx_module(void)

{
	...
	tdx_get_sysinfo(&tdx_sysinfo, ...);
	...

	tdmr_array = alloc_pages_exact(tdmr_array_size(&tdx_sysinfo),
						GFP_KERNEL | __GFP_ZERO);
	...

	construct_tdmrs(tdmr_array, &nr_tdmrs, &tdx_sysinfo);
	...
}
#117 lore raw

Re: [PATCH v7 11/20] x86/virt/tdx: Add placeholder to construct TDMRs to cover all TDX memory regions

Quoted 2 lines · Kai

Apologize I am not entirely sure whether I fully got your point. Do you mean something like below?

...

No, something like this:

static int init_tdx_module(void)

{
	static struct tdsysinfo_struct tdx_sysinfo; /* too rotund for the stack */
        ...
        tdx_get_sysinfo(&tdx_sysinfo, ...);
        ...

But, also, seriously, 3k on the stack is *fine* if you can shut up the warnings. This isn't going to be a deep call stack to begin with.

author
#137 lore raw

Re: [PATCH v7 14/20] x86/virt/tdx: Set up reserved areas for all TDMRs

In reply to Dave Hansen
Quoted 14 lines · Dave Hansen
Quoted 1 line · Kai

On Wed, 2022-11-23 at 15:39 -0800, Dave Hansen wrote:

...

Quoted 11 lines
Quoted 8 lines

/*
 * Go through tdx_memlist to find holes between memory areas.  If any of
 * those holes fall within @tdmr, set up a TDMR reserved area to cover
 * the hole.
 */
static int tdmr_populate_rsvd_holes(struct list_head *tdx_memlist, struct tdmr_info *tdmr, int *rsvd_idx)

Thanks!

Quoted 8 lines
Quoted 6 lines

Should I also change below function 'tdmr_set_up_pamt_rsvd_areas()' to, i.e. tdmr_populate_rsvd_pamts()?

Actually, there are two more functions in this patch: tdmr_set_up_rsvd_areas() and tdmrs_set_up_rsvd_areas_all().  Should I also change them to tdmr_populate_rsvd_areas() and tdmrs_populate_rsvd_areas_all()?

I don't know.  I'll look at the naming again once I see it all together.

Sure. I'll only change the one you mentioned above and keep the others for the next version.

author
#130 lore raw

Re: [PATCH v7 13/20] x86/virt/tdx: Allocate and set up PAMTs for TDMRs

In reply to Dave Hansen
Quoted 15 lines · Dave Hansen
Quoted 14 lines · Kai
Quoted 12 lines · Dave Hansen
Quoted 6 lines · Kai Huang

Use alloc_contig_pages() since PAMT must be a physically contiguous area and it may be potentially large (~1/256th of the size of the given TDMR). The downside is alloc_contig_pages() may fail at runtime. One (bad) mitigation is to launch a TD guest early during system boot to get those PAMTs allocated at early time, but the only way to fix is to add a boot option to allocate or reserve PAMTs during kernel boot.

FWIW, we all agree that this is a bad permanent way to leave things. You can call me out here as proposing that this wart be left in place while this series is merged and is a detail we can work on afterword with new module params, boot options, Kconfig or whatever.

Quoted 4 lines
Quoted 1 line

Sorry do you mean to call out in the cover letter, or in this changelog?

Cover letter would be best. But, a note in the changelog that it is imperfect and will be improved on later would also be nice.

Thanks will do both.

Quoted 32 lines
Quoted 8 lines
Quoted 8 lines
Quoted 7 lines
arch/x86/virt/vmx/tdx/tdx.c +6 -0
+   /*
+    * Fall back to allocating the TDMR's metadata from node 0 when
+    * no TDX memory block can be found.  This should never happen
+    * since TDMRs originate from TDX memory blocks.
+    */
+   WARN_ON_ONCE(1);
Quoted 7 lines
Quoted 2 lines

That's probably better a pr_warn() or something. A backtrace and all that jazz seems a bit overly dramatic for this.

How about below?

pr_warn("TDMR [0x%llx, 0x%llx): unable to find local NUMA node for PAMT allocation, fallback to use node 0.\n");

I actually try to make these somewhat mirror the code. For instance, if you are searching using *just* the start TDMR address, then the message should only talk about the start address. Also, it's not trying to find a *node* per se. It's trying to find a 'tmb'. So, if someone wanted to debug this problem, they would actually want to dump out the tmbs.

But, back to the loop that this message describes:

arch/x86/virt/vmx/tdx/tdx.c static int create_tdmrs(struct tdmr_info *tdmr_array, int *tdmr_num) · line 635

Quoted 5 lines
arch/x86/virt/vmx/tdx/tdx.c +5 -0
+	/* Find the first memory region covered by the TDMR */
+	list_for_each_entry(tmb, &tdx_memlist, list) {
+		if (tmb->end_pfn > (tdmr_start(tdmr) >> PAGE_SHIFT))
+			return tmb->nid;
+	}

That loop is funky. It's not obvious at *all* why it even works.

Quoted 10 lines

1. A 'tmb' describes "real" memory. It never covers holes.
2. This code is trying to find *a* 'tmb' to place a structure in. It needs real memory to place this, of course.
3. A 'tdmr' may include holes and may not have a 'tmb' at either its start or end address
4. A 'tdmr' is expected to cover one or more 'tmb's. If there were no 'tmb's, then the TDMR is going to be marked as all reserved and is effectively being wasted.
5. A 'tdmr' may cover more than one NUMA node. If this happens, it is ok to get memory from any of those nodes for that tdmr's PAMT.

Right.

Quoted 7 lines

I'd include this comment on the loop:

A TDMR must cover at least part of one TMB. That TMB will end after the TDMR begins. But, that TMB may have started before the TDMR. Find the next 'tmb' that _ends_ after this TDMR begins. Ignore 'tmb' start addresses. They are irrelevant.

Thanks. Will do.

However, I am not sure I quite understand "the next 'tmb'" part?

Quoted 9 lines

Maybe even a little ASCII diagram about the different tmb configurations that this can find:

Quoted 1 line

TDMR1 | TDMR2 |

   |---tmb---|			
          |tmb|
          |------tmb-------|		<- case 3)
   |------tmb-------|			<- case 4

Thanks for the diagram!

But IIUC it seems the above case 3) and 4) are actually not possible, since when one TDMR is created, it's end is always rounded up to the end of TMB it tries to cover (the rounded-up end may cover the entire or only partial of other TMBs, though).

			1G		2G
	TDMR1		|	TDMR2	|

	|--tmb1--|  |--tmb2--|  |-tmb3-|

	node 0		     |  node 1
Quoted 10 lines

I'd also include this on the function:

/*
* Locate a NUMA node which should hold the allocation of the @tdmr
* PAMT. This node will have some memory covered by the TDMR. The
* relative amount of memory covered is not considered. */

Thanks. Will do.

author
#118 lore raw

Re: [PATCH v7 11/20] x86/virt/tdx: Add placeholder to construct TDMRs to cover all TDX memory regions

In reply to Dave Hansen
Quoted 8 lines · Dave Hansen
Quoted 2 lines · Kai

Apologize I am not entirely sure whether I fully got your point. Do you mean something like below?

...

No, something like this:

static int init_tdx_module(void)

Quoted 9 lines
{
	static struct tdsysinfo_struct tdx_sysinfo; /* too rotund for the stack */
        ...
        tdx_get_sysinfo(&tdx_sysinfo, ...);
        ...

But, also, seriously, 3k on the stack is *fine* if you can shut up the warnings. This isn't going to be a deep call stack to begin with.

Let me try to find out whether it is possible to silent the warning. If I cannot, then I'll use your above way. Thanks!

#131 lore raw

Re: [PATCH v7 13/20] x86/virt/tdx: Allocate and set up PAMTs for TDMRs

In reply to Huang, Kai
Quoted 8 lines · Kai
Quoted 8 lines

Maybe even a little ASCII diagram about the different tmb configurations that this can find:

Quoted 1 line

TDMR1 | TDMR2 |

   |---tmb---|
          |tmb|
          |------tmb-------|          <- case 3)
   |------tmb-------|                 <- case 4
Quoted 6 lines

Thanks for the diagram!

But IIUC it seems the above case 3) and 4) are actually not possible, since when one TDMR is created, it's end is always rounded up to the end of TMB it tries to cover (the rounded-up end may cover the entire or only partial of other TMBs, though).

OK, but at the same time, we shouldn't *STRICTLY* specialize every single little chunk of this code to be aware of every other tiny little implementation detail.

Let's say tomorrow's code has lots of TDMRs left, but fills up one TDMR's reserved areas and has to "split" it. Want to bet on whether the person that adds that patch will be able to find this code and fix it up?

Or, say that the TDMR creation algorithm changes and they're not done in order of ascending physical address.

This code actually gets easier and more obvious if you ignore the other details.

#138 lore raw

Re: [PATCH v7 14/20] x86/virt/tdx: Set up reserved areas for all TDMRs

In reply to Huang, Kai
Quoted 3 lines · Kai
Quoted 1 line

I don't know. I'll look at the naming again once I see it all together.

Sure. I'll only change the one you mentioned above and keep the others for the next version.

The alternative is that you can look at what I suggested, try and learn something from it, and try to apply that elsewhere in the series before you post again.

author
#139 lore raw

Re: [PATCH v7 14/20] x86/virt/tdx: Set up reserved areas for all TDMRs

Quoted 8 lines · Dave
Quoted 3 lines · Kai
Quoted 1 line

I don't know. I'll look at the naming again once I see it all together.

Sure. I'll only change the one you mentioned above and keep the others for the next version.

The alternative is that you can look at what I suggested, try and learn something from it, and try to apply that elsewhere in the series before you post again.

Yeah surely will do.

author
#132 lore raw

Re: [PATCH v7 13/20] x86/virt/tdx: Allocate and set up PAMTs for TDMRs

In reply to Dave Hansen
Quoted 16 lines · Dave
Quoted 8 lines · Kai
Quoted 8 lines

Maybe even a little ASCII diagram about the different tmb configurations that this can find:

Quoted 1 line

TDMR1 | TDMR2 |

   |---tmb---|
          |tmb|
          |------tmb-------|          <- case 3)
   |------tmb-------|                 <- case 4
Quoted 6 lines

Thanks for the diagram!

But IIUC it seems the above case 3) and 4) are actually not possible, since when one TDMR is created, it's end is always rounded up to the end of TMB it tries to cover (the rounded-up end may cover the entire or only partial of other TMBs, though).

Quoted 7 lines

OK, but at the same time, we shouldn't *STRICTLY* specialize every single little chunk of this code to be aware of every other tiny little implementation detail.

Let's say tomorrow's code has lots of TDMRs left, but fills up one TDMR's reserved areas and has to "split" it. Want to bet on whether the person that adds that patch will be able to find this code and fix it up?

Yeah good point.

Quoted 6 lines

Or, say that the TDMR creation algorithm changes and they're not done in order of ascending physical address.

This code actually gets easier and more obvious if you ignore the other details.

Agreed. Thanks.

#52 lore raw

Re: [PATCH v7 06/20] x86/virt/tdx: Shut down TDX module in case of error

In reply to Peter Zijlstra
Quoted 9 lines · Peter Zijlstra
Quoted 8 lines · Dave Hansen
Quoted 2 lines

Not intialize TDX on busy NOHZ_FULL cpus and hard-limit the cpumask of all TDX using tasks.

I don't think that works. As I mentioned to Thomas elsewhere, you don't just need to initialize TDX on the CPUs where it is used. Before the module will start working you need to initialize it on *all* the CPUs it knows about. The module itself has a little counter where it tracks this and will refuse to start being useful until it gets called thoroughly enough.

Quoted 8 lines

That's bloody terrible, that is. How are we going to make that work with the SMT mitigation crud that forces the SMT sibilng offline?

Then the counters don't match and TDX won't work.

Can we get this limitiation removed and simply let the module throw a wobbly (error) when someone tries and use TDX without that logical CPU having been properly initialized?

It sounds like we can at least punt the limitation away from the OS's purview.

There's actually a multi-step process to get a "real" TDX module loaded.
There's a fancy ACM (Authenticated Code Module) that's invoked via
GETSEC[ENTERACCS] and an intermediate module loader. That dance used to be done in the kernel, but we talked the BIOS guys into doing it instead.

I believe these per-logical-CPU checks _can_ also be punted out of the TDX module itself and delegated to one of these earlier module loading phases that the BIOS drives.

I'm still a _bit_ skeptical that the checks are needed in the first place. But, as long as they're hidden from the OS, I don't see a need to be too cranky about it.

In the end, we could just plain stop doing the TDH.SYS.LP.INIT code in the kernel.

Unless someone screams, I'll ask the BIOS and TDX module folks to look into this.

#152 lore raw

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

In reply to Kai Huang
Quoted 15 lines · Kai Huang

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

Quoted 8 lines

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel)

It seems not accurate to say MOVDIR64B changes the page's associated KeyID. It just uses the current KeyID for memory operations.

Quoted 2 lines

to clear
PMATs isn't needed, as the KeyID 0 doesn't support integrity check.

For integrity check, is KeyID 0 special or it just has the same behavior as non-zero shared KeyID (if any)?

By saying "KeyID 0 doesn't support integrity check", is it because of  the implementation of this patch set or hardware behavior?

According to Architecure Specification 1.0 of TDX Module (344425-004US), shared KeyID could also enable integrity check.

Quoted 147 lines

---

v6 -> v7:
- Improved changelong and comment to explain why MOVDIR64B isn't used when returning PAMTs back to the kernel.

---
  arch/x86/virt/vmx/tdx/tdx.c | 89 ++++++++++++++++++++++++++++++++++++-
  arch/x86/virt/vmx/tdx/tdx.h |  1 +
  2 files changed, 88 insertions(+), 2 deletions(-)
arch/x86/virt/vmx/tdx/tdx.c +87 -2
index 3a032930e58a..99d1be5941a7 100644
@@ -224,6 +224,46 @@ static void seamcall_on_each_cpu(struct seamcall_ctx *sc)
  	on_each_cpu(seamcall_smp_call_function, sc, true);
  }
 
+/*
+ * Call one SEAMCALL on one (any) cpu for each physical package in
+ * serialized way.  Return immediately in case of any error if
+ * SEAMCALL fails on any cpu.
+ *
+ * Note for serialized calls 'struct seamcall_ctx::err' doesn't have
+ * to be atomic, but for simplicity just reuse it instead of adding
+ * a new one.
+ */
+static int seamcall_on_each_package_serialized(struct seamcall_ctx *sc)
+{
+	cpumask_var_t packages;
+	int cpu, ret = 0;
+
+	if (!zalloc_cpumask_var(&packages, GFP_KERNEL))
+		return -ENOMEM;
+
+	for_each_online_cpu(cpu) {
+		if (cpumask_test_and_set_cpu(topology_physical_package_id(cpu),
+					packages))
+			continue;
+
+		ret = smp_call_function_single(cpu, seamcall_smp_call_function,
+				sc, true);
+		if (ret)
+			break;
+
+		/*
+		 * Doesn't have to use atomic_read(), but it doesn't
+		 * hurt either.
+		 */
+		ret = atomic_read(&sc->err);
+		if (ret)
+			break;
+	}
+
+	free_cpumask_var(packages);
+	return ret;
+}
+
  static int tdx_module_init_cpus(void)
  {
  	struct seamcall_ctx sc = { .fn = TDH_SYS_LP_INIT };
@@ -1010,6 +1050,22 @@ static int config_tdx_module(struct tdmr_info *tdmr_array, int tdmr_num,
  	return ret;
  }
 
+static int config_global_keyid(void)
+{
+	struct seamcall_ctx sc = { .fn = TDH_SYS_KEY_CONFIG };
+
+	/*
+	 * Configure the key of the global KeyID on all packages by
+	 * calling TDH.SYS.KEY.CONFIG on all packages in a serialized
+	 * way as it cannot run concurrently on different CPUs.
+	 *
+	 * TDH.SYS.KEY.CONFIG may fail with entropy error (which is
+	 * a recoverable error).  Assume this is exceedingly rare and
+	 * just return error if encountered instead of retrying.
+	 */
+	return seamcall_on_each_package_serialized(&sc);
+}
+
  /*
   * Detect and initialize the TDX module.
   *
@@ -1098,15 +1154,44 @@ static int init_tdx_module(void)
  	if (ret)
  		goto out_free_pamts;
 
+	/*
+	 * Hardware doesn't guarantee cache coherency across different
+	 * KeyIDs.  The kernel needs to flush PAMT's dirty cachelines
+	 * (associated with KeyID 0) before the TDX module can use the
+	 * global KeyID to access the PAMT.  Given PAMTs are potentially
+	 * large (~1/256th of system RAM), just use WBINVD on all cpus
+	 * to flush the cache.
+	 *
+	 * Follow the TDX spec to flush cache before configuring the
+	 * global KeyID on all packages.
+	 */
+	wbinvd_on_all_cpus();
+
+	/* Config the key of global KeyID on all packages */
+	ret = config_global_keyid();
+	if (ret)
+		goto out_free_pamts;
+
  	/*
  	 * Return -EINVAL until all steps of TDX module initialization
  	 * process are done.
  	 */
  	ret = -EINVAL;
  out_free_pamts:
-	if (ret)
+	if (ret) {
+		/*
+		 * Part of PAMT may already have been initialized by
+		 * TDX module.  Flush cache before returning PAMT back
+		 * to the kernel.
+		 *
+		 * Note there's no need to do MOVDIR64B (which changes
+		 * the page's associated KeyID from the old TDX private
+		 * KeyID back to KeyID 0, which is used by the kernel),
+		 * as KeyID 0 doesn't support integrity check.
+		 */
+		wbinvd_on_all_cpus();
  		tdmrs_free_pamt_all(tdmr_array, tdmr_num);
-	else
+	} else
  		pr_info("%lu pages allocated for PAMT.\n",
  				tdmrs_count_pamt_pages(tdmr_array, tdmr_num));
  out_free_tdmrs:
arch/x86/virt/vmx/tdx/tdx.h +1 -0
index c26bab2555ca..768d097412ab 100644
@@ -15,6 +15,7 @@
  /*
   * TDX module SEAMCALL leaf functions
   */
+#define TDH_SYS_KEY_CONFIG	31
  #define TDH_SYS_INFO		32
  #define TDH_SYS_INIT		33
  #define TDH_SYS_LP_INIT		35
author
#153 lore raw

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

Quoted 19 lines · Binbin Wu
Quoted 18 lines · Kai Huang

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

Quoted 8 lines
Quoted 5 lines

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel)

It seems not accurate to say MOVDIR64B changes the page's associated KeyID. It just uses the current KeyID for memory operations.

The "write" to the memory changes the page's associated KeyID to the KeyID that does the "write". A more accurate expression perhaps should be MOVDIR64B + MFENSE, but I think it doesn't matter in changelog.

Quoted 7 lines
Quoted 4 lines

to clear
PMATs isn't needed, as the KeyID 0 doesn't support integrity check.

For integrity check, is KeyID 0 special or it just has the same behavior as non-zero shared KeyID (if any)?

KeyID 0 is TME KeyID. It is special. Hardware treats the KeyID 0 differently.

Quoted 3 lines

By saying "KeyID 0 doesn't support integrity check", is it because of the implementation of this patch set or hardware behavior?

It's hardware behaviour.

Quoted 4 lines

According to Architecure Specification 1.0 of TDX Module (344425-004US), shared KeyID could also enable integrity check.

KeyID 0 is different from non-0 MKTME shared KeyID. For example, you cannot do PCONFIG on KeyID 0.

#53 lore raw

Re: [PATCH v7 06/20] x86/virt/tdx: Shut down TDX module in case of error

In reply to Dave Hansen
Quoted 13 lines · Dave Hansen
Quoted 3 lines · Peter Zijlstra

Can we get this limitiation removed and simply let the module throw a wobbly (error) when someone tries and use TDX without that logical CPU having been properly initialized?

It sounds like we can at least punt the limitation away from the OS's purview.

There's actually a multi-step process to get a "real" TDX module loaded.
There's a fancy ACM (Authenticated Code Module) that's invoked via
GETSEC[ENTERACCS] and an intermediate module loader. That dance used to be done in the kernel, but we talked the BIOS guys into doing it instead.

Quoted 7 lines

I believe these per-logical-CPU checks _can_ also be punted out of the TDX module itself and delegated to one of these earlier module loading phases that the BIOS drives.

I'm still a _bit_ skeptical that the checks are needed in the first place. But, as long as they're hidden from the OS, I don't see a need to be too cranky about it.

Right.

Quoted 2 lines

In the end, we could just plain stop doing the TDH.SYS.LP.INIT code in the kernel.

Which in turn makes all the problems we discussed go away.

Quoted 2 lines

Unless someone screams, I'll ask the BIOS and TDX module folks to look into this.

Yes, please.

Thanks,

tglx

#154 lore raw

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

In reply to Huang, Kai
Quoted 26 lines · Kai
Quoted 25 lines · Binbin Wu
Quoted 23 lines · Kai Huang

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel)

Quoted 6 lines
Quoted 2 lines

It seems not accurate to say MOVDIR64B changes the page's associated KeyID. It just uses the current KeyID for memory operations.

The "write" to the memory changes the page's associated KeyID to the KeyID that does the "write". A more accurate expression perhaps should be MOVDIR64B + MFENSE, but I think it doesn't matter in changelog.

MOVDIR64B KeyID for the cache line, not the page. Integrity tracked on per-cacheline basis.

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

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

In reply to Huang, Kai
Quoted 26 lines · Kai
Quoted 25 lines · Binbin Wu
Quoted 23 lines · Kai Huang

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel)

Quoted 6 lines
Quoted 2 lines

It seems not accurate to say MOVDIR64B changes the page's associated KeyID. It just uses the current KeyID for memory operations.

The "write" to the memory changes the page's associated KeyID to the KeyID that does the "write". A more accurate expression perhaps should be MOVDIR64B + MFENSE, but I think it doesn't matter in changelog.

Just delete it from the changelog. It's a distraction. I'm not even sure it's *necessary* to do any memory content conversion after the TDX module has written gunk.

There won't be any integrity issues because integrity errors don't do anything for KeyID-0 (no #MC).

I _think_ the reads of the page using KeyID-0 will see abort page semantics. That's *FINE*.

#157 lore raw

Re: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

In reply to Kai Huang
Quoted 3 lines · Kai Huang

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

I want to circle back to this because it potentially has the same class of issue that TDH.SYS.LP.INIT had. So, here's some more background followed by the key question: is TDH.SYS.KEY.CONFIG too strict? Should we explore relaxing it?

Here's the very long-winded way of asking the same thing:

This key is used to protect TDX module memory which is too large to fit into the limited range-register-protected (SMRR) areas that most of the module uses. Right now, that metadata includes the Physical Address Metadata Tables (PAMT) and "TD Root" (TDR) pages. Using this "global KeyID" provides stronger isolation and integrity protection for these structures than is provided by KeyID-0.

The "global KeyID" only strictly needs to be programmed into a memory controllers if a PAMT or TDR page is allocated in memory attached to that controller. However, the TDX module currently requires that TDH.SYS.KEY.CONFIG be executed on one processor in each package. This is true even if there is no TDX Memory Region (TDMR) attached to that package.

This was likely done for simplicity in the TDX module. It currently has no NUMA awareness (or even trusted NUMA metadata) and no ability to correlate processor packages with the memory attached to their memory controllers.

The TDH.SYS.KEY.CONFIG design is actually pretty similar to Kirill's MKTME implementation[1]. Basically blast the KeyID configuration out to one processor in each package, regardless of whether the KeyID will ever get used on that package.

While this requirement from the TDX module is _slightly_ too strict, I'm not quite as worried about it as I was about the *super* strict TDH.SYS.LP.INIT requirements. It's a lot harder and more rare to have an entire package of CPUs unavailable versus a single logical CPU. There is, for instance, no side-channel mitigation that disables an entire package worth of CPUs. I'm not even sure if we allow an entire package worth of NOHZ_FULL-indisposed processors.

I'm happy to go run the same drill for TDH.SYS.KEY.CONFIG that we did for TDH.SYS.LP.INIT. Basically, can we relax the too-strict restrictions? But, I'm not sure anyone will ever reap a practical benefit from it. I'm tempted to just leave it as-is.

Does anyone feel differently?

1.
https://lore.kernel.org/lkml/[email protected]/T/#m936f260a345284687f8e929675f68f3d514725f5

author
#156 lore raw

RE: [PATCH v7 17/20] x86/virt/tdx: Configure global KeyID on all packages

In reply to Dave Hansen
Quoted 40 lines · Kai
Quoted 20 lines · Binbin Wu
Quoted 19 lines · Kai Huang
Quoted 18 lines

After the array of TDMRs and the global KeyID are configured to the TDX module, use TDH.SYS.KEY.CONFIG to configure the key of the global KeyID on all packages.

TDH.SYS.KEY.CONFIG must be done on one (any) cpu for each package. And it cannot run concurrently on different CPUs. Implement a helper to run SEAMCALL on one cpu for each package one by one, and use it to configure the global KeyID on all packages.

Intel hardware doesn't guarantee cache coherency across different KeyIDs. The kernel needs to flush PAMT's dirty cachelines (associated with KeyID 0) before the TDX module uses the global KeyID to access the PAMT. Following the TDX module specification, flush cache before configuring the global KeyID on all packages.

Given the PAMT size can be large (~1/256th of system RAM), just use WBINVD on all CPUs to flush.

Quoted 8 lines
Quoted 8 lines
Quoted 6 lines

Note if any TDH.SYS.KEY.CONFIG fails, the TDX module may already have used the global KeyID to write any PAMT. Therefore, need to use WBINVD to flush cache before freeing the PAMTs back to the kernel. Note using MOVDIR64B (which changes the page's associated KeyID from the old TDX private KeyID back to KeyID 0, which is used by the kernel)

It seems not accurate to say MOVDIR64B changes the page's associated

KeyID.

Quoted 5 lines
Quoted 1 line

It just uses the current KeyID for memory operations.

The "write" to the memory changes the page's associated KeyID to the KeyID that does the "write". A more accurate expression perhaps should be MOVDIR64B + MFENSE, but I think it doesn't matter in changelog.

Just delete it from the changelog. It's a distraction. I'm not even sure it's *necessary* to do any memory content conversion after the TDX module has written gunk.

Quoted 5 lines

There won't be any integrity issues because integrity errors don't do anything for KeyID-0 (no #MC).

I _think_ the reads of the page using KeyID-0 will see abort page semantics. That's *FINE*.

I'll remove this from the changelog. Thanks!

#110 lore raw

Re: [PATCH v7 10/20] x86/virt/tdx: Use all system memory when initializing TDX module as TDX memory

In reply to Huang, Kai
Quoted 5 lines · Kai

Thanks for input. I am fine with 'tdx=force'.

Although, I'd like to point out KVM will have a module parameter 'enable_tdx'.

Hi Dave, Sean, do you have any comments?

That's fine. Just keep it out of the initial implementation. Ignore it for now,

author
#84 lore raw

Re: [PATCH v7 09/20] x86/virt/tdx: Get information about TDX module and TDX-capable memory

In reply to Dave Hansen
Quoted 45 lines · Dave Hansen
Quoted 31 lines
arch/x86/virt/vmx/tdx/tdx.h +31 -0
+#define TDSYSINFO_STRUCT_SIZE		1024
+#define TDSYSINFO_STRUCT_ALIGNMENT	1024
+
+struct tdsysinfo_struct {
+	/* TDX-SEAM Module Info */
+	u32	attributes;
+	u32	vendor_id;
+	u32	build_date;
+	u16	build_num;
+	u16	minor_version;
+	u16	major_version;
+	u8	reserved0[14];
+	/* Memory Info */
+	u16	max_tdmrs;
+	u16	max_reserved_per_tdmr;
+	u16	pamt_entry_size;
+	u8	reserved1[10];
+	/* Control Struct Info */
+	u16	tdcs_base_size;
+	u8	reserved2[2];
+	u16	tdvps_base_size;
+	u8	tdvps_xfam_dependent_size;
+	u8	reserved3[9];
+	/* TD Capabilities */
+	u64	attributes_fixed0;
+	u64	attributes_fixed1;
+	u64	xfam_fixed0;
+	u64	xfam_fixed1;
+	u8	reserved4[32];
+	u32	num_cpuid_config;
+	/*

arch/x86/virt/vmx/tdx/tdx.h line 80

Quoted 10 lines
arch/x86/virt/vmx/tdx/tdx.h +10 -0
+	 * The actual number of CPUID_CONFIG depends on above
+	 * 'num_cpuid_config'.  The size of 'struct tdsysinfo_struct'
+	 * is 1024B defined by TDX architecture.  Use a union with
+	 * specific padding to make 'sizeof(struct tdsysinfo_struct)'
+	 * equal to 1024.
+	 */
+	union {
+		struct cpuid_config	cpuid_configs[0];
+		u8			reserved5[892];
+	};

Can you double check what the "right" way to do variable arrays is these days?  I thought the [0] method was discouraged.

Quoted 3 lines

Also, it isn't *really* 892 bytes of reserved space, right?  Anything that's not cpuid_configs[] is reserved, I presume.  Could you try to be more precise there?

Hi Dave,

I did some search, and I think we should use DECLARE_FLEX_ARRAY() macro?

And also to address you concern that not all 892 bytes are reserved, how about below:

        union {
-               struct cpuid_config     cpuid_configs[0];
-               u8                      reserved5[892];
+               DECLARE_FLEX_ARRAY(struct cpuid_config, cpuid_configs);
+               u8 padding[892];
        };

} __packed __aligned(TDSYSINFO_STRUCT_ALIGNMENT);

The goal is to make the size of 'struct tdsysinfo_struct' to be 1024B so we can use a static variable for it, and at the meantime, it can still have 1024B (enough space) for the TDH.SYS.INFO to write to.

author
#81 lore raw

Re: [PATCH v7 09/20] x86/virt/tdx: Get information about TDX module and TDX-capable memory

In reply to Huang, Kai
Quoted 20 lines · Kai
Quoted 20 lines
Quoted 20 lines
Quoted 19 lines
Quoted 19 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
Quoted 7 lines
arch/x86/virt/vmx/tdx/tdx.c +7 -0
+
+   /*
+    * trim_empty_cmrs() updates the actual number of CMRs by
+    * dropping all tail empty CMRs.
+    */
+   return trim_empty_cmrs(tdx_cmr_array, &tdx_cmr_num);
+}
Quoted 8 lines
Quoted 8 lines

Why does this both need to respect the "tdx_cmr_num = out.r9" value
*and* trim the empty ones?  Couldn't it just ignore the "tdx_cmr_num =
out.r9" value and just trim the empty ones either way?  It's not like
there is a billion of them.  It would simplify the code for sure.

OK.  Since spec says MAX_CMRs is 32, so I can use 32 instead of reading out from
R9.

Quoted 7 lines
Quoted 4 lines
Quoted 4 lines

But then you still have the "trimming" code.  Why not just trust "r9" and then axe all the trimming code?  Heck, and most of the sanity checks.

This code could be a *lot* smaller.

As I said the only problem is there might be empty CMRs at the tail of the cmr_array[] following one or more valid CMRs.

Hi Dave,

Probably I forgot to mention the "r9" in practice always returns 32, so there will be empty CMRs at the tail of the cmr_array[].

Quoted 7 lines

But we can also do nothing here, but just skip empty CMRs when comparing the memory region to it (in next patch).

Or, we don't even need to explicitly check memory region against CMRs. If the memory regions that we provided in the TDMR doesn't fall into CMR, then TDH.SYS.CONFIG will fail. We can just depend on the SEAMCALL to do that.

Sorry to ping, but do you have any comments here?

How about we just don't do any check of TDX memory regions against CMRs, but just let the TDH.SYS.CONFIG SEAMCALL to determine?

#85 lore raw

Re: [PATCH v7 09/20] x86/virt/tdx: Get information about TDX module and TDX-capable memory

In reply to Huang, Kai
Quoted 11 lines · Kai

And also to address you concern that not all 892 bytes are reserved, how about below:

        union {
(quoted diff) +2 -2
-               struct cpuid_config     cpuid_configs[0];
-               u8                      reserved5[892];
+               DECLARE_FLEX_ARRAY(struct cpuid_config, cpuid_configs);
+               u8 padding[892];
        };
 } __packed __aligned(TDSYSINFO_STRUCT_ALIGNMENT);
Quoted 3 lines

The goal is to make the size of 'struct tdsysinfo_struct' to be 1024B so we can use a static variable for it, and at the meantime, it can still have 1024B (enough space) for the TDH.SYS.INFO to write to.

I just don't like the open-coded sizes.

For instance, wouldn't it be great if you didn't have to know the size of *ANYTHING* else to properly size the '892'?

Maybe we just need some helpers to hide the gunk:

#define DECLARE_PADDED_STRUCT(type, name, alignment) \

struct type##_padded {					\
	union {						\
		struct type name;			\
		u8 padding[alignment];			\
	}						\
} name##_padded;

#define PADDED_STRUCT(name) (name##_padded.name)

That can get used like this:

DECLARE_PADDED_STRUCT(struct tdsysinfo_struct, tdsysinfo,

		      TDSYSINFO_STRUCT_ALIGNMENT);


	struct tdsysinfo_struct sysinfo = PADDED_STRUCT(tdsysinfo)
#82 lore raw

Re: [PATCH v7 09/20] x86/virt/tdx: Get information about TDX module and TDX-capable memory

In reply to Huang, Kai
Quoted 2 lines · Kai

Probably I forgot to mention the "r9" in practice always returns 32, so there will be empty CMRs at the tail of the cmr_array[].

Right, so the r9 value is basically useless. I bet the code gets simpler if you just ignore it.

Quoted 11 lines
Quoted 6 lines

But we can also do nothing here, but just skip empty CMRs when comparing the memory region to it (in next patch).

Or, we don't even need to explicitly check memory region against CMRs. If the memory regions that we provided in the TDMR doesn't fall into CMR, then TDH.SYS.CONFIG will fail. We can just depend on the SEAMCALL to do that.

Sorry to ping, but do you have any comments here?

How about we just don't do any check of TDX memory regions against CMRs, but just let the TDH.SYS.CONFIG SEAMCALL to determine?

Right, if we screw it up TDH.SYS.CONFIG SEAMCALL will fail. We don't need to add more code to detect that failure ourselves. TDX is screwed either way.

author
#86 lore raw

Re: [PATCH v7 09/20] x86/virt/tdx: Get information about TDX module and TDX-capable memory

In reply to Dave Hansen
Quoted 33 lines · Dave Hansen
Quoted 11 lines · Kai

And also to address you concern that not all 892 bytes are reserved, how about below:

        union {
(quoted diff) +2 -2
-               struct cpuid_config     cpuid_configs[0];
-               u8                      reserved5[892];
+               DECLARE_FLEX_ARRAY(struct cpuid_config, cpuid_configs);
+               u8 padding[892];
        };
 } __packed __aligned(TDSYSINFO_STRUCT_ALIGNMENT);
Quoted 3 lines

The goal is to make the size of 'struct tdsysinfo_struct' to be 1024B so we can use a static variable for it, and at the meantime, it can still have 1024B (enough space) for the TDH.SYS.INFO to write to.

I just don't like the open-coded sizes.

For instance, wouldn't it be great if you didn't have to know the size of *ANYTHING* else to properly size the '892'?

Maybe we just need some helpers to hide the gunk:

#define DECLARE_PADDED_STRUCT(type, name, alignment) \

struct type##_padded {					\
	union {						\
		struct type name;			\
		u8 padding[alignment];			\
	}						\
} name##_padded;

#define PADDED_STRUCT(name) (name##_padded.name)

Quoted 7 lines

That can get used like this:

DECLARE_PADDED_STRUCT(struct tdsysinfo_struct, tdsysinfo,

		      TDSYSINFO_STRUCT_ALIGNMENT);


	struct tdsysinfo_struct sysinfo = PADDED_STRUCT(tdsysinfo)

Thanks. Will try out this way.

author
#83 lore raw

Re: [PATCH v7 09/20] x86/virt/tdx: Get information about TDX module and TDX-capable memory

In reply to Dave Hansen
Quoted 14 lines · Dave Hansen
Quoted 2 lines · Kai

Probably I forgot to mention the "r9" in practice always returns 32, so there will be empty CMRs at the tail of the cmr_array[].

Right, so the r9 value is basically useless. I bet the code gets simpler if you just ignore it.

Quoted 7 lines
Quoted 6 lines

But we can also do nothing here, but just skip empty CMRs when comparing the memory region to it (in next patch).

Or, we don't even need to explicitly check memory region against CMRs. If the memory regions that we provided in the TDMR doesn't fall into CMR, then TDH.SYS.CONFIG will fail. We can just depend on the SEAMCALL to do that.

Quoted 8 lines
Quoted 4 lines

Sorry to ping, but do you have any comments here?

How about we just don't do any check of TDX memory regions against CMRs, but just let the TDH.SYS.CONFIG SEAMCALL to determine?

Right, if we screw it up TDH.SYS.CONFIG SEAMCALL will fail. We don't need to add more code to detect that failure ourselves. TDX is screwed either way.

Will do. Thanks.

author
#119 lore raw

Re: [PATCH v7 11/20] x86/virt/tdx: Add placeholder to construct TDMRs to cover all TDX memory regions

In reply to Huang, Kai
Quoted 15 lines · Kai
Quoted 14 lines · Dave Hansen
Quoted 2 lines · Kai

Apologize I am not entirely sure whether I fully got your point. Do you mean something like below?

...

No, something like this:

static int init_tdx_module(void)

{
	static struct tdsysinfo_struct tdx_sysinfo; /* too rotund for the stack */
        ...
        tdx_get_sysinfo(&tdx_sysinfo, ...);
        ...
Quoted 6 lines
Quoted 3 lines

But, also, seriously, 3k on the stack is *fine* if you can shut up the warnings. This isn't going to be a deep call stack to begin with.

Let me try to find out whether it is possible to silent the warning. If I cannot, then I'll use your above way. Thanks!

Hi Dave,

Sorry to double asking.

Adding below build flag to Makefile can silent the warning:

index 38d534f2c113..f8a40d15fdfc 100644

arch/x86/virt/vmx/tdx/Makefile +1 -0
@@ -1,2 +1,3 @@
 # SPDX-License-Identifier: GPL-2.0-only
+CFLAGS_tdx.o += -Wframe-larger-than=4096
 

So to confirm you want to add this flag to Makefile and just make tdx_sysinfo and tdx_cmr_array as local variables?

Another reason I am double asking is, 'tdx_global_keyid' in this series can also be a local variable in init_tdx_module() but currently it is a static (as KVM will need it too). If I change to use local variable in the patch "x86/virt/tdx: Reserve TDX module global KeyID" like below:

arch/x86/virt/vmx/tdx/tdx.c +2 -4
@@ -50,9 +50,6 @@ static DEFINE_MUTEX(tdx_module_lock);
 /* All TDX-usable memory regions */
 static LIST_HEAD(tdx_memlist);
 
-/* TDX module global KeyID.  Used in TDH.SYS.CONFIG ABI. */
-static u32 tdx_global_keyid;
-
 /*
  * tdx_keyid_start and nr_tdx_keyids indicate that TDX is uninitialized.
  * This is used in TDX initialization error paths to take it from
@@ -928,6 +925,7 @@ static int init_tdx_module(void)
                __aligned(CMR_INFO_ARRAY_ALIGNMENT);
        struct tdsysinfo_struct *sysinfo = &PADDED_STRUCT(tdsysinfo);
        struct tdmr_info_list tdmr_list;
+       u32 global_keyid;
        int ret;
 
        ret = tdx_get_sysinfo(sysinfo, cmr_array);
@@ -964,7 +962,7 @@ static int init_tdx_module(void)
         * Pick the first TDX KeyID as global KeyID to protect
         * TDX module metadata.
         */
-       tdx_global_keyid = tdx_keyid_start;
+       global_keyid = tdx_keyid_start;
 

I got a warning for this particular patch:

arch/x86/virt/vmx/tdx/tdx.c: In function ‘init_tdx_module’:
arch/x86/virt/vmx/tdx/tdx.c:928:13: warning: variable ‘global_keyid’ set but not used [-Wunused-but-set-variable]

  928 |         u32 global_keyid;
      |             ^~~~~~~~~~~~

To get rid of this warning, we need to merge this patch to the later patch (which configures the TDMRs and global keyid to the TDX module).

Should I make the tdx_global_keyid as local variable too and merge patch "x86/virt/tdx: Reserve TDX module global KeyID" to the later patch?

author
#120 lore raw

Re: [PATCH v7 11/20] x86/virt/tdx: Add placeholder to construct TDMRs to cover all TDX memory regions

Quoted 36 lines · Kai
Quoted 15 lines · Kai
Quoted 14 lines · Dave Hansen
Quoted 2 lines · Kai

Apologize I am not entirely sure whether I fully got your point. Do you mean something like below?

...

No, something like this:

static int init_tdx_module(void)

{
	static struct tdsysinfo_struct tdx_sysinfo; /* too rotund for the stack */
        ...
        tdx_get_sysinfo(&tdx_sysinfo, ...);
        ...
Quoted 6 lines
Quoted 3 lines

But, also, seriously, 3k on the stack is *fine* if you can shut up the warnings. This isn't going to be a deep call stack to begin with.

Let me try to find out whether it is possible to silent the warning. If I cannot, then I'll use your above way. Thanks!

Hi Dave,

Sorry to double asking.

Adding below build flag to Makefile can silent the warning:

index 38d534f2c113..f8a40d15fdfc 100644

arch/x86/virt/vmx/tdx/Makefile +1 -0
@@ -1,2 +1,3 @@
 # SPDX-License-Identifier: GPL-2.0-only
+CFLAGS_tdx.o += -Wframe-larger-than=4096
 
Quoted 2 lines

So to confirm you want to add this flag to Makefile and just make tdx_sysinfo and tdx_cmr_array as local variables?

Hi Dave,

I found if I declare TDSYSINFO_STRUCT and CMR_ARRAY as local variable (on the stack), the TDH.SYS.INFO failed in my testing due to 'invalid operand' of the address of TDSYSINFO_STRUCT. If I declare them as static, the SEAMCALL works.

I haven't looked into the reason yet but I suspect the address isn't aligned (I used __pa() to get the physical address). I'll take a look and report back.

In the meantime, do you have any comments? Should I still pursue to keep them as local variable on the stack?

Thanks.

Quoted 38 lines

Another reason I am double asking is, 'tdx_global_keyid' in this series can also be a local variable in init_tdx_module() but currently it is a static (as KVM will need it too). If I change to use local variable in the patch "x86/virt/tdx: Reserve TDX module global KeyID" like below:

arch/x86/virt/vmx/tdx/tdx.c +2 -4
@@ -50,9 +50,6 @@ static DEFINE_MUTEX(tdx_module_lock);
 /* All TDX-usable memory regions */
 static LIST_HEAD(tdx_memlist);
 
-/* TDX module global KeyID.  Used in TDH.SYS.CONFIG ABI. */
-static u32 tdx_global_keyid;
-
 /*
  * tdx_keyid_start and nr_tdx_keyids indicate that TDX is uninitialized.
  * This is used in TDX initialization error paths to take it from
@@ -928,6 +925,7 @@ static int init_tdx_module(void)
                __aligned(CMR_INFO_ARRAY_ALIGNMENT);
        struct tdsysinfo_struct *sysinfo = &PADDED_STRUCT(tdsysinfo);
        struct tdmr_info_list tdmr_list;
+       u32 global_keyid;
        int ret;
 
        ret = tdx_get_sysinfo(sysinfo, cmr_array);
@@ -964,7 +962,7 @@ static int init_tdx_module(void)
         * Pick the first TDX KeyID as global KeyID to protect
         * TDX module metadata.
         */
-       tdx_global_keyid = tdx_keyid_start;
+       global_keyid = tdx_keyid_start;
 

I got a warning for this particular patch:

arch/x86/virt/vmx/tdx/tdx.c: In function ‘init_tdx_module’:
arch/x86/virt/vmx/tdx/tdx.c:928:13: warning: variable ‘global_keyid’ set but not used [-Wunused-but-set-variable]

Quoted 8 lines
  928 |         u32 global_keyid;
      |             ^~~~~~~~~~~~

To get rid of this warning, we need to merge this patch to the later patch (which configures the TDMRs and global keyid to the TDX module).

Should I make the tdx_global_keyid as local variable too and merge patch "x86/virt/tdx: Reserve TDX module global KeyID" to the later patch?

And for this one, if we merge the two patches then in fact we can just remove 'tdx_global_keyid' but use 'tdx_start_keyid' directly. I have already done in this way. Any comments please let me know. Thanks for your time.

#121 lore raw

Re: [PATCH v7 11/20] x86/virt/tdx: Add placeholder to construct TDMRs to cover all TDX memory regions

Quoted 5 lines · Kai

I haven't looked into the reason yet but I suspect the address isn't aligned (I used __pa() to get the physical address). I'll take a look and report back.

In the meantime, do you have any comments? Should I still pursue to keep them as local variable on the stack?

Yes, you should investigate the reason for the failure and try to understand both the success and the failure cases.

author
#122 lore raw

Re: [PATCH v7 11/20] x86/virt/tdx: Add placeholder to construct TDMRs to cover all TDX memory regions

Quoted 9 lines · Dave Hansen
Quoted 5 lines · Kai

I haven't looked into the reason yet but I suspect the address isn't aligned (I used __pa() to get the physical address). I'll take a look and report back.

In the meantime, do you have any comments? Should I still pursue to keep them as local variable on the stack?

Yes, you should investigate the reason for the failure and try to understand both the success and the failure cases.

Hi Dave,

Learned something new from Kirill today.

The reason is not the alignment, but it's wrong to use __pa() to get the physical address of function local variable on the stack. It is because Kirill told me kernel stack can now be allocated via vmalloc(), so use __pa() won't work.

I changed to use slow_virt_to_phys() and tried in my testing and it now works.

So I'll change to use slow_virt_to_phys() for the next version. We can take a look at the new version to see if that is what you wanted.

Thanks for your time.