Re: [PATCH v3 06/16] x86/virt/tdx: Improve PAMT refcounters allocation for sparse memory

Huang, Kai
2025-09-24T06:50:13Z

On Tue, 2025-09-23 at 17:38 +0800, Binbin Wu wrote:
> > > +/*
> > > + * Allocate PAMT reference counters for the given PFN range.
> > > + *
> > > + * It consumes 2MiB for every 1TiB of physical memory.
> > > + */
> > > +static int alloc_pamt_refcount(unsigned long start_pfn, unsigned long end_pfn)
> > > +{
> > > + unsigned long start, end;
> > > +
> > > + start = (unsigned long)tdx_find_pamt_refcount(PFN_PHYS(start_pfn));
> > > + end   = (unsigned long)tdx_find_pamt_refcount(PFN_PHYS(end_pfn + 1));
> > (sorry didn't notice this in last version)
> >
> > I don't quite follow why we need "end_pfn + 1" instead of just "end_pfn"?
> >
> > IIUC this could result in an additional 2M range being populated
> > unnecessarily when the end_pfn is 2M aligned.
>
> IIUC, this will not happen.
> The +1 page will be converted to 4KB, and will be ignored since in
> tdx_find_pamt_refcount() the address is divided by 2M.
>
> To handle the address unaligned to 2M, +511 should be used instead of +1?

OK. Thanks for catching. But I still don't get why we need end_pfn + 1.

Also, when end_pfn == 511, would this result in the second refcount being
returned for the @end, while the intention should be the first refcount?

For example, assuming we have a range [0, 2M), we only need one refcount.
And the PFN range (which comes from for_each_mem_pfn_range()) would be:

start_pfn == 0
end_pfn == 512

This will results in @start pointing to the first refcount and @end
pointing to the second, IIUC.

So it seems we need:

start = (unsigned long)tdx_find_pamt_refcount(PFN_PHYS(start_pfn));
end = (unsigned long)tdx_find_pamt_refcount(PFN_PHYS(end_pfn) - 1));
start = round_down(start, PAGE_SIZE);
end = round_up(end, PAGE_SIZE);

?