On Wed, Sep 17, 2025 at 02:48:37PM -0700, Jim Mattson wrote: > Walk the guest page tables via a loop when creating new mappings, > instead of using unique variables for each level of the page tables. > > This simplifies the code and makes it easier to support 5-level paging > in the future. > > Signed-off-by: Jim Mattson <[email protected]> > --- > .../testing/selftests/kvm/lib/x86/processor.c | 22 +++++++------------ > 1 file changed, 8 insertions(+), 14 deletions(-) > > diff --git a/tools/testing/selftests/kvm/lib/x86/processor.c > b/tools/testing/selftests/kvm/lib/x86/processor.c > index d4c19ac885a9..0238e674709d 100644 > --- a/tools/testing/selftests/kvm/lib/x86/processor.c > +++ b/tools/testing/selftests/kvm/lib/x86/processor.c > @@ -184,8 +184,8 @@ static uint64_t *virt_create_upper_pte(struct kvm_vm *vm, > void __virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr, int > level) > { > const uint64_t pg_size = PG_LEVEL_SIZE(level); > - uint64_t *pml4e, *pdpe, *pde; > - uint64_t *pte; > + uint64_t *pte = &vm->pgd; > + int current_level; > > TEST_ASSERT(vm->mode == VM_MODE_PXXV48_4K, > "Unknown or unsupported guest mode, mode: 0x%x", vm->mode); > @@ -209,20 +209,14 @@ void __virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, > uint64_t paddr, int level) > * Allocate upper level page tables, if not already present. Return > * early if a hugepage was created. > */ > - pml4e = virt_create_upper_pte(vm, &vm->pgd, vaddr, paddr, > PG_LEVEL_512G, level); > - if (*pml4e & PTE_LARGE_MASK) > - return; > - > - pdpe = virt_create_upper_pte(vm, pml4e, vaddr, paddr, PG_LEVEL_1G, > level); > - if (*pdpe & PTE_LARGE_MASK) > - return; > - > - pde = virt_create_upper_pte(vm, pdpe, vaddr, paddr, PG_LEVEL_2M, level); > - if (*pde & PTE_LARGE_MASK) > - return; > + for (current_level = vm->pgtable_levels; current_level > 0; > current_level--) {
I think the condition here should be: "current_level > PG_LEVEL_4K" or "current_level >= PG_LEVEL_2M". PG_LEVEL_4K is 1, so right now we will call virt_create_upper_pte() for PG_LEVEL_4K and skip the logic after the logic after the loop. I think it still accidentally works for most cases, but we shouldn't rely on that. > + pte = virt_create_upper_pte(vm, pte, vaddr, paddr, > current_level, level); > + if (*pte & PTE_LARGE_MASK) > + return; > + } > > /* Fill in page table entry. */ > - pte = virt_get_pte(vm, pde, vaddr, PG_LEVEL_4K); > + pte = virt_get_pte(vm, pte, vaddr, PG_LEVEL_4K); > TEST_ASSERT(!(*pte & PTE_PRESENT_MASK), > "PTE already present for 4k page at vaddr: 0x%lx", vaddr); > *pte = PTE_PRESENT_MASK | PTE_WRITABLE_MASK | (paddr & > PHYSICAL_PAGE_MASK); > -- > 2.51.0.470.ga7dc726c21-goog >

