Skip to contentSkip to conversation

Rework x86 page table walks

PATCH In review Don Porter 3 participants 16 messages Jul 23, 2024 – Aug 2, 2024

lore
Share & tools
lore

Don Porter

author
#0 lore raw

v4 cover Rework x86 page table walks

This version of the 'info pg' command adopts Peter Maydell's request to write guest-agnostic page table iterator and accessor code, along with architecture-specific hooks. The first patch in this series contributes a generic page table iterator and an x86 instantiation. As a client, we first introduce an 'info pg' monitor command, as well as a compressing callback hook for creating succinct page table representations.

After this, each successive patch replaces an exisitng x86 page table walker with a use of common iterator code.

I could use advice on how to ensure this is sufficiently well tested. I used 'make check', 'make check-avocado', and 'make check-tcg' which all behave comparably to master branch on my test system; what is the typical standard for testing something like a page table related change?

As far as generality, I have only attempted this on x86, but I expect the design would work for any similar radix-tree style page table.

Per David Gilbert's suggestion, I was careful to ensure that monitor calls do not perturb TLB state (see the read-only flag in some functions).

Version 3 of this patch series moves 'info pg' into common monitor code and implements the architecture-specific code hooks. I did not do this with the 'info mem' and 'info tlb' commands, since they have implementations on other ISAs.

Version 4 of this patch series adopts significant feedback on both the monitor side and the page table hooks. I believe this addresses all of the feedback from Richard Henderson on this, and considerably reworked the code to use fewer hooks, recur on nested paging, and hoist permission and reserved bit checking into common code.

Unfortunately, this exposes issues with nested paging and internal virtualization APIs (or lack thereof). AMD and Intel have some architectural differences in how VM state is accessed; similarly, each accelerator backend on qemu stores virtualization state in different ways. Since I cannot test the transitive closure of these configurations, I focused on the test cases I had at hand (tcg and kvm, with a guest that issues Intel-style EPT pages), and to detect and warn on an unsupported configuration.

Finally, the only way to reliably get some architectural state from kvm involved importing the vmcs12 definition from Linux. I wasn't sure whether to put this under the linux headers, or somewhere else, since this definition is not in the standard Linux headers.

Thank you,
Don

Don Porter (7):
Code motion: expose some TCG definitions for page table walk
consolidation.
Import vmcs12 definition from Linux/KVM
Add an "info pg" command that prints the current page tables Convert 'info tlb' to use generic iterator.
Convert 'info mem' to use generic iterator
Convert x86_cpu_get_memory_mapping() to use generic iterators Convert x86_mmu_translate() to use common code.

 hmp-commands-info.hx                 |   13 +
 hw/core/cpu-sysemu.c                 |  168 +++-
 hw/core/machine-qmp-cmds.c           |  243 ++++++
 include/hw/core/cpu.h                |   78 +-
 include/hw/core/sysemu-cpu-ops.h     |  157 +++-
 include/monitor/hmp-target.h         |    1 +
 qapi/machine.json                    |   17 +
 system/memory_mapping.c              |    2 +-
 target/i386/arch_memory_mapping.c    | 1195 +++++++++++++++++++++-----
 target/i386/cpu.c                    |   25 +-
 target/i386/cpu.h                    |   64 +-
 target/i386/helper.c                 |   36 +
 target/i386/kvm/kvm.c                |   68 ++
 target/i386/kvm/vmcs12.h             |  213 +++++
 target/i386/monitor.c                |  797 +++++++----------
 target/i386/tcg/helper-tcg.h         |   32 +
 target/i386/tcg/seg_helper.c         |   36 -
 target/i386/tcg/sysemu/excp_helper.c |  454 +---------
 18 files changed, 2423 insertions(+), 1176 deletions(-)
 create mode 100644 target/i386/kvm/vmcs12.h

--
2.34.1

author
#1 lore raw

PATCH v4 1/7 Code motion: expose some TCG definitions for page table walk consolidation.

---
 include/hw/core/sysemu-cpu-ops.h     |  6 +++++
 target/i386/cpu.h                    |  5 ++--
 target/i386/helper.c                 | 36 +++++++++++++++++++++++++++
 target/i386/tcg/helper-tcg.h         | 32 ++++++++++++++++++++++++
 target/i386/tcg/seg_helper.c         | 36 ---------------------------
 target/i386/tcg/sysemu/excp_helper.c | 37 +---------------------------
 6 files changed, 77 insertions(+), 75 deletions(-)
include/hw/core/sysemu-cpu-ops.h +6 -0
index 24d003fe04..4c94e51267 100644
@@ -12,6 +12,12 @@
 
 #include "hw/core/cpu.h"
 
+typedef enum TranslateFaultStage2 {
+    S2_NONE,
+    S2_GPA,
+    S2_GPT,
+} TranslateFaultStage2;
+
 /*
  * struct SysemuCPUOps: System operations specific to a CPU class
  */
target/i386/cpu.h +2 -3
index 1e121acef5..d899644cb8 100644
@@ -21,6 +21,7 @@
 #define I386_CPU_H
 
 #include "sysemu/tcg.h"
+#include "hw/core/sysemu-cpu-ops.h"
 #include "cpu-qom.h"
 #include "kvm/hyperv-proto.h"
 #include "exec/cpu-defs.h"
@@ -2362,6 +2363,7 @@ void host_cpuid(uint32_t function, uint32_t count,
 bool cpu_has_x2apic_feature(CPUX86State *env);
 
 /* helper.c */
+int get_pg_mode(CPUX86State *env);
 void x86_cpu_set_a20(X86CPU *cpu, int a20_state);
 void cpu_sync_avx_hflag(CPUX86State *env);
 
@@ -2540,9 +2542,6 @@ static inline bool cpu_vmx_maybe_enabled(CPUX86State *env)
            ((env->cr[4] & CR4_VMXE_MASK) || (env->hflags & HF_SMM_MASK));
 }
 
-/* excp_helper.c */
-int get_pg_mode(CPUX86State *env);
-
 /* fpu_helper.c */
 void update_fp_status(CPUX86State *env);
 void update_mxcsr_status(CPUX86State *env);
target/i386/helper.c +36 -0
index 01a268a30b..9cb6e51426 100644
@@ -721,3 +721,39 @@ void x86_stq_phys(CPUState *cs, hwaddr addr, uint64_t val)
     address_space_stq(as, addr, val, attrs, NULL);
 }
 #endif
+
+int get_pg_mode(CPUX86State *env)
+{
+    int pg_mode = 0;
+    if (!(env->cr[0] & CR0_PG_MASK)) {
+        return 0;
+    }
+    if (env->cr[0] & CR0_WP_MASK) {
+        pg_mode |= PG_MODE_WP;
+    }
+    if (env->cr[4] & CR4_PAE_MASK) {
+        pg_mode |= PG_MODE_PAE;
+        if (env->efer & MSR_EFER_NXE) {
+            pg_mode |= PG_MODE_NXE;
+        }
+    }
+    if (env->cr[4] & CR4_PSE_MASK) {
+        pg_mode |= PG_MODE_PSE;
+    }
+    if (env->cr[4] & CR4_SMEP_MASK) {
+        pg_mode |= PG_MODE_SMEP;
+    }
+    if (env->hflags & HF_LMA_MASK) {
+        pg_mode |= PG_MODE_LMA;
+        if (env->cr[4] & CR4_PKE_MASK) {
+            pg_mode |= PG_MODE_PKE;
+        }
+        if (env->cr[4] & CR4_PKS_MASK) {
+            pg_mode |= PG_MODE_PKS;
+        }
+        if (env->cr[4] & CR4_LA57_MASK) {
+            pg_mode |= PG_MODE_LA57;
+        }
+    }
+    return pg_mode;
+}
target/i386/tcg/helper-tcg.h +32 -0
index 15d6c6f8b4..1cbeab9161 100644
@@ -92,6 +92,38 @@ extern const uint8_t parity_table[256];
 /* misc_helper.c */
 void cpu_load_eflags(CPUX86State *env, int eflags, int update_mask);
 
+/* sysemu/excp_helper.c */
+typedef struct TranslateFault {
+    int exception_index;
+    int error_code;
+    target_ulong cr2;
+    TranslateFaultStage2 stage2;
+} TranslateFault;
+
+typedef struct PTETranslate {
+    CPUX86State *env;
+    TranslateFault *err;
+    int ptw_idx;
+    void *haddr;
+    hwaddr gaddr;
+} PTETranslate;
+
+bool ptw_setl_slow(const PTETranslate *in, uint32_t old, uint32_t new);
+
+static inline bool ptw_setl(const PTETranslate *in, uint32_t old, uint32_t set)
+{
+    if (set & ~old) {
+        uint32_t new = old | set;
+        if (likely(in->haddr)) {
+            old = cpu_to_le32(old);
+            new = cpu_to_le32(new);
+            return qatomic_cmpxchg((uint32_t *)in->haddr, old, new) == old;
+        }
+        return ptw_setl_slow(in, old, new);
+    }
+    return true;
+}
+
 /* sysemu/svm_helper.c */
 #ifndef CONFIG_USER_ONLY
 G_NORETURN void cpu_vmexit(CPUX86State *nenv, uint32_t exit_code,
target/i386/tcg/seg_helper.c +0 -36
index aac092a356..90f01180d9 100644
@@ -92,42 +92,6 @@ static uint32_t popl(StackAccess *sa)
     return ret;
 }
 
-int get_pg_mode(CPUX86State *env)
-{
-    int pg_mode = 0;
-    if (!(env->cr[0] & CR0_PG_MASK)) {
-        return 0;
-    }
-    if (env->cr[0] & CR0_WP_MASK) {
-        pg_mode |= PG_MODE_WP;
-    }
-    if (env->cr[4] & CR4_PAE_MASK) {
-        pg_mode |= PG_MODE_PAE;
-        if (env->efer & MSR_EFER_NXE) {
-            pg_mode |= PG_MODE_NXE;
-        }
-    }
-    if (env->cr[4] & CR4_PSE_MASK) {
-        pg_mode |= PG_MODE_PSE;
-    }
-    if (env->cr[4] & CR4_SMEP_MASK) {
-        pg_mode |= PG_MODE_SMEP;
-    }
-    if (env->hflags & HF_LMA_MASK) {
-        pg_mode |= PG_MODE_LMA;
-        if (env->cr[4] & CR4_PKE_MASK) {
-            pg_mode |= PG_MODE_PKE;
-        }
-        if (env->cr[4] & CR4_PKS_MASK) {
-            pg_mode |= PG_MODE_PKS;
-        }
-        if (env->cr[4] & CR4_LA57_MASK) {
-            pg_mode |= PG_MODE_LA57;
-        }
-    }
-    return pg_mode;
-}
-
 /* return non zero if error */
 static inline int load_segment_ra(CPUX86State *env, uint32_t *e1_ptr,
                                uint32_t *e2_ptr, int selector,
target/i386/tcg/sysemu/excp_helper.c +1 -36
index 8fb05b1f53..3ebb67d65b 100644
@@ -39,27 +39,6 @@ typedef struct TranslateResult {
     int page_size;
 } TranslateResult;
 
-typedef enum TranslateFaultStage2 {
-    S2_NONE,
-    S2_GPA,
-    S2_GPT,
-} TranslateFaultStage2;
-
-typedef struct TranslateFault {
-    int exception_index;
-    int error_code;
-    target_ulong cr2;
-    TranslateFaultStage2 stage2;
-} TranslateFault;
-
-typedef struct PTETranslate {
-    CPUX86State *env;
-    TranslateFault *err;
-    int ptw_idx;
-    void *haddr;
-    hwaddr gaddr;
-} PTETranslate;
-
 static bool ptw_translate(PTETranslate *inout, hwaddr addr, uint64_t ra)
 {
     CPUTLBEntryFull *full;
@@ -104,7 +83,7 @@ static inline uint64_t ptw_ldq(const PTETranslate *in, uint64_t ra)
  * even 64-bit ones, because PG_PRESENT_MASK, PG_ACCESSED_MASK and
  * PG_DIRTY_MASK are all in the low 32 bits.
  */
-static bool ptw_setl_slow(const PTETranslate *in, uint32_t old, uint32_t new)
+bool ptw_setl_slow(const PTETranslate *in, uint32_t old, uint32_t new)
 {
     uint32_t cmp;
 
@@ -118,20 +97,6 @@ static bool ptw_setl_slow(const PTETranslate *in, uint32_t old, uint32_t new)
     return cmp == old;
 }
 
-static inline bool ptw_setl(const PTETranslate *in, uint32_t old, uint32_t set)
-{
-    if (set & ~old) {
-        uint32_t new = old | set;
-        if (likely(in->haddr)) {
-            old = cpu_to_le32(old);
-            new = cpu_to_le32(new);
-            return qatomic_cmpxchg((uint32_t *)in->haddr, old, new) == old;
-        }
-        return ptw_setl_slow(in, old, new);
-    }
-    return true;
-}
-
 static bool mmu_translate(CPUX86State *env, const TranslateParams *in,
                           TranslateResult *out, TranslateFault *err,
                           uint64_t ra)
Signature · 1 line
2.34.1
#2 lore raw

Re: [PATCH v4 1/7] Code motion: expose some TCG definitions for page table walk consolidation.

Quoted 15 lines · Don Porter
---
  include/hw/core/sysemu-cpu-ops.h     |  6 +++++
  target/i386/cpu.h                    |  5 ++--
  target/i386/helper.c                 | 36 +++++++++++++++++++++++++++
  target/i386/tcg/helper-tcg.h         | 32 ++++++++++++++++++++++++
  target/i386/tcg/seg_helper.c         | 36 ---------------------------
  target/i386/tcg/sysemu/excp_helper.c | 37 +---------------------------
  6 files changed, 77 insertions(+), 75 deletions(-)
include/hw/core/sysemu-cpu-ops.h +0 -0
index 24d003fe04..4c94e51267 100644

include/hw/core/sysemu-cpu-ops.h line 19

Quoted 8 lines
include/hw/core/sysemu-cpu-ops.h +5 -0
@@ -12,6 +12,12 @@
 
  #include "hw/core/cpu.h"
 
+typedef enum TranslateFaultStage2 {
+    S2_NONE,
+    S2_GPA,
+    S2_GPT,
+} TranslateFaultStage2;

No, you can't move an x86-specific item like this into common code. You're doing something wrong in the abstraction.

r~

author
#3 lore raw

PATCH v4 2/7 Import vmcs12 definition from Linux/KVM

In reply to Don Porter
---
 target/i386/kvm/vmcs12.h | 213 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 213 insertions(+)
 create mode 100644 target/i386/kvm/vmcs12.h
target/i386/kvm/vmcs12.h new file +213 -0
new file mode 100644
index 0000000000..c7b139f4db
@@ -0,0 +1,213 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef QEMU_KVM_X86_VMX_VMCS12_H
+#define QEMU_KVM_X86_VMX_VMCS12_H
+
+#include <linux/kvm.h>
+
+/* XXX: Stolen from Linux with light edits, for now */
+
+typedef uint64_t u64;
+typedef uint32_t u32;
+typedef uint16_t u16;
+
+/*
+ * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
+ * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
+ * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
+ * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
+ * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
+ * More than one of these structures may exist, if L1 runs multiple L2 guests.
+ * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
+ * underlying hardware which will be used to run L2.
+ * This structure is packed to ensure that its layout is identical across
+ * machines (necessary for live migration).
+ *
+ * IMPORTANT: Changing the layout of existing fields in this structure
+ * will break save/restore compatibility with older kvm releases. When
+ * adding new fields, either use space in the reserved padding* arrays
+ * or add the new fields to the end of the structure.
+ */
+typedef u64 natural_width;
+
+
+struct vmcs_hdr {
+    u32 revision_id : 31;
+    u32 shadow_vmcs : 1;
+};
+
+struct __attribute__ ((__packed__)) vmcs12 {
+        /*
+         * According to the Intel spec, a VMCS region must start with the
+         * following two fields. Then follow implementation-specific data.
+         */
+        struct vmcs_hdr hdr;
+        u32 abort;
+
+        u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
+        u32 padding[7]; /* room for future expansion */
+
+        u64 io_bitmap_a;
+        u64 io_bitmap_b;
+        u64 msr_bitmap;
+        u64 vm_exit_msr_store_addr;
+        u64 vm_exit_msr_load_addr;
+        u64 vm_entry_msr_load_addr;
+        u64 tsc_offset;
+        u64 virtual_apic_page_addr;
+        u64 apic_access_addr;
+        u64 posted_intr_desc_addr;
+        u64 ept_pointer;
+        u64 eoi_exit_bitmap0;
+        u64 eoi_exit_bitmap1;
+        u64 eoi_exit_bitmap2;
+        u64 eoi_exit_bitmap3;
+        u64 xss_exit_bitmap;
+        u64 guest_physical_address;
+        u64 vmcs_link_pointer;
+        u64 guest_ia32_debugctl;
+        u64 guest_ia32_pat;
+        u64 guest_ia32_efer;
+        u64 guest_ia32_perf_global_ctrl;
+        u64 guest_pdptr0;
+        u64 guest_pdptr1;
+        u64 guest_pdptr2;
+        u64 guest_pdptr3;
+        u64 guest_bndcfgs;
+        u64 host_ia32_pat;
+        u64 host_ia32_efer;
+        u64 host_ia32_perf_global_ctrl;
+        u64 vmread_bitmap;
+        u64 vmwrite_bitmap;
+        u64 vm_function_control;
+        u64 eptp_list_address;
+        u64 pml_address;
+        u64 encls_exiting_bitmap;
+        u64 tsc_multiplier;
+        u64 padding64[1]; /* room for future expansion */
+        /*
+         * To allow migration of L1 (complete with its L2 guests) between
+         * machines of different natural widths (32 or 64 bit), we cannot have
+         * unsigned long fields with no explicit size. We use u64 (aliased
+         * natural_width) instead. Luckily, x86 is little-endian.
+         */
+        natural_width cr0_guest_host_mask;
+        natural_width cr4_guest_host_mask;
+        natural_width cr0_read_shadow;
+        natural_width cr4_read_shadow;
+        /* Last remnants of cr3_target_value[0-3]. */
+        natural_width dead_space[4];
+        natural_width exit_qualification;
+        natural_width guest_linear_address;
+        natural_width guest_cr0;
+        natural_width guest_cr3;
+        natural_width guest_cr4;
+        natural_width guest_es_base;
+        natural_width guest_cs_base;
+        natural_width guest_ss_base;
+        natural_width guest_ds_base;
+        natural_width guest_fs_base;
+        natural_width guest_gs_base;
+        natural_width guest_ldtr_base;
+        natural_width guest_tr_base;
+        natural_width guest_gdtr_base;
+        natural_width guest_idtr_base;
+        natural_width guest_dr7;
+        natural_width guest_rsp;
+        natural_width guest_rip;
+        natural_width guest_rflags;
+        natural_width guest_pending_dbg_exceptions;
+        natural_width guest_sysenter_esp;
+        natural_width guest_sysenter_eip;
+        natural_width host_cr0;
+        natural_width host_cr3;
+        natural_width host_cr4;
+        natural_width host_fs_base;
+        natural_width host_gs_base;
+        natural_width host_tr_base;
+        natural_width host_gdtr_base;
+        natural_width host_idtr_base;
+        natural_width host_ia32_sysenter_esp;
+        natural_width host_ia32_sysenter_eip;
+        natural_width host_rsp;
+        natural_width host_rip;
+        natural_width paddingl[8]; /* room for future expansion */
+        u32 pin_based_vm_exec_control;
+        u32 cpu_based_vm_exec_control;
+        u32 exception_bitmap;
+        u32 page_fault_error_code_mask;
+        u32 page_fault_error_code_match;
+        u32 cr3_target_count;
+        u32 vm_exit_controls;
+        u32 vm_exit_msr_store_count;
+        u32 vm_exit_msr_load_count;
+        u32 vm_entry_controls;
+        u32 vm_entry_msr_load_count;
+        u32 vm_entry_intr_info_field;
+        u32 vm_entry_exception_error_code;
+        u32 vm_entry_instruction_len;
+        u32 tpr_threshold;
+        u32 secondary_vm_exec_control;
+        u32 vm_instruction_error;
+        u32 vm_exit_reason;
+        u32 vm_exit_intr_info;
+        u32 vm_exit_intr_error_code;
+        u32 idt_vectoring_info_field;
+        u32 idt_vectoring_error_code;
+        u32 vm_exit_instruction_len;
+        u32 vmx_instruction_info;
+        u32 guest_es_limit;
+        u32 guest_cs_limit;
+        u32 guest_ss_limit;
+        u32 guest_ds_limit;
+        u32 guest_fs_limit;
+        u32 guest_gs_limit;
+        u32 guest_ldtr_limit;
+        u32 guest_tr_limit;
+        u32 guest_gdtr_limit;
+        u32 guest_idtr_limit;
+        u32 guest_es_ar_bytes;
+        u32 guest_cs_ar_bytes;
+        u32 guest_ss_ar_bytes;
+        u32 guest_ds_ar_bytes;
+        u32 guest_fs_ar_bytes;
+        u32 guest_gs_ar_bytes;
+        u32 guest_ldtr_ar_bytes;
+        u32 guest_tr_ar_bytes;
+        u32 guest_interruptibility_info;
+        u32 guest_activity_state;
+        u32 guest_sysenter_cs;
+        u32 host_ia32_sysenter_cs;
+        u32 vmx_preemption_timer_value;
+        u32 padding32[7]; /* room for future expansion */
+        u16 virtual_processor_id;
+        u16 posted_intr_nv;
+        u16 guest_es_selector;
+        u16 guest_cs_selector;
+        u16 guest_ss_selector;
+        u16 guest_ds_selector;
+        u16 guest_fs_selector;
+        u16 guest_gs_selector;
+        u16 guest_ldtr_selector;
+        u16 guest_tr_selector;
+        u16 guest_intr_status;
+        u16 host_es_selector;
+        u16 host_cs_selector;
+        u16 host_ss_selector;
+        u16 host_ds_selector;
+        u16 host_fs_selector;
+        u16 host_gs_selector;
+        u16 host_tr_selector;
+        u16 guest_pml_index;
+};
+
+/*
+ * VMCS12_REVISION is an arbitrary id that should be changed if the content or
+ * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
+ * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
+ *
+ * IMPORTANT: Changing this value will break save/restore compatibility with
+ * older kvm releases.
+ */
+#define VMCS12_REVISION 0x11e57ed0
+
+#endif
Signature · 1 line
2.34.1
#4 lore raw

Re: [PATCH v4 2/7] Import vmcs12 definition from Linux/KVM

Quoted 13 lines · * Don Porter ([email protected]) wrote:
---
 target/i386/kvm/vmcs12.h | 213 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 213 insertions(+)
 create mode 100644 target/i386/kvm/vmcs12.h
target/i386/kvm/vmcs12.h new file +1 -0
new file mode 100644
index 0000000000..c7b139f4db
@@ -0,0 +1,213 @@
+/* SPDX-License-Identifier: GPL-2.0 */

target/i386/kvm/vmcs12.h line 11

Quoted 10 lines
target/i386/kvm/vmcs12.h new file +10 -0
+#ifndef QEMU_KVM_X86_VMX_VMCS12_H
+#define QEMU_KVM_X86_VMX_VMCS12_H
+
+#include <linux/kvm.h>
+
+/* XXX: Stolen from Linux with light edits, for now */
+
+typedef uint64_t u64;
+typedef uint32_t u32;
+typedef uint16_t u16;

Hmm, it's a pity that scripts/update-linux-headers.sh can't be used for this file; I don't think there are any cases of it doing things out side linux's include?
Anyway, it has a big scary sed for fixing all of the kernel types, so it's probably best to use that at least if you're copying it.

Dave

Quoted 204 lines
target/i386/kvm/vmcs12.h new file +201 -0
+/*
+ * struct vmcs12 describes the state that our guest hypervisor (L1) keeps for a
+ * single nested guest (L2), hence the name vmcs12. Any VMX implementation has
+ * a VMCS structure, and vmcs12 is our emulated VMX's VMCS. This structure is
+ * stored in guest memory specified by VMPTRLD, but is opaque to the guest,
+ * which must access it using VMREAD/VMWRITE/VMCLEAR instructions.
+ * More than one of these structures may exist, if L1 runs multiple L2 guests.
+ * nested_vmx_run() will use the data here to build the vmcs02: a VMCS for the
+ * underlying hardware which will be used to run L2.
+ * This structure is packed to ensure that its layout is identical across
+ * machines (necessary for live migration).
+ *
+ * IMPORTANT: Changing the layout of existing fields in this structure
+ * will break save/restore compatibility with older kvm releases. When
+ * adding new fields, either use space in the reserved padding* arrays
+ * or add the new fields to the end of the structure.
+ */
+typedef u64 natural_width;
+
+
+struct vmcs_hdr {
+    u32 revision_id : 31;
+    u32 shadow_vmcs : 1;
+};
+
+struct __attribute__ ((__packed__)) vmcs12 {
+        /*
+         * According to the Intel spec, a VMCS region must start with the
+         * following two fields. Then follow implementation-specific data.
+         */
+        struct vmcs_hdr hdr;
+        u32 abort;
+
+        u32 launch_state; /* set to 0 by VMCLEAR, to 1 by VMLAUNCH */
+        u32 padding[7]; /* room for future expansion */
+
+        u64 io_bitmap_a;
+        u64 io_bitmap_b;
+        u64 msr_bitmap;
+        u64 vm_exit_msr_store_addr;
+        u64 vm_exit_msr_load_addr;
+        u64 vm_entry_msr_load_addr;
+        u64 tsc_offset;
+        u64 virtual_apic_page_addr;
+        u64 apic_access_addr;
+        u64 posted_intr_desc_addr;
+        u64 ept_pointer;
+        u64 eoi_exit_bitmap0;
+        u64 eoi_exit_bitmap1;
+        u64 eoi_exit_bitmap2;
+        u64 eoi_exit_bitmap3;
+        u64 xss_exit_bitmap;
+        u64 guest_physical_address;
+        u64 vmcs_link_pointer;
+        u64 guest_ia32_debugctl;
+        u64 guest_ia32_pat;
+        u64 guest_ia32_efer;
+        u64 guest_ia32_perf_global_ctrl;
+        u64 guest_pdptr0;
+        u64 guest_pdptr1;
+        u64 guest_pdptr2;
+        u64 guest_pdptr3;
+        u64 guest_bndcfgs;
+        u64 host_ia32_pat;
+        u64 host_ia32_efer;
+        u64 host_ia32_perf_global_ctrl;
+        u64 vmread_bitmap;
+        u64 vmwrite_bitmap;
+        u64 vm_function_control;
+        u64 eptp_list_address;
+        u64 pml_address;
+        u64 encls_exiting_bitmap;
+        u64 tsc_multiplier;
+        u64 padding64[1]; /* room for future expansion */
+        /*
+         * To allow migration of L1 (complete with its L2 guests) between
+         * machines of different natural widths (32 or 64 bit), we cannot have
+         * unsigned long fields with no explicit size. We use u64 (aliased
+         * natural_width) instead. Luckily, x86 is little-endian.
+         */
+        natural_width cr0_guest_host_mask;
+        natural_width cr4_guest_host_mask;
+        natural_width cr0_read_shadow;
+        natural_width cr4_read_shadow;
+        /* Last remnants of cr3_target_value[0-3]. */
+        natural_width dead_space[4];
+        natural_width exit_qualification;
+        natural_width guest_linear_address;
+        natural_width guest_cr0;
+        natural_width guest_cr3;
+        natural_width guest_cr4;
+        natural_width guest_es_base;
+        natural_width guest_cs_base;
+        natural_width guest_ss_base;
+        natural_width guest_ds_base;
+        natural_width guest_fs_base;
+        natural_width guest_gs_base;
+        natural_width guest_ldtr_base;
+        natural_width guest_tr_base;
+        natural_width guest_gdtr_base;
+        natural_width guest_idtr_base;
+        natural_width guest_dr7;
+        natural_width guest_rsp;
+        natural_width guest_rip;
+        natural_width guest_rflags;
+        natural_width guest_pending_dbg_exceptions;
+        natural_width guest_sysenter_esp;
+        natural_width guest_sysenter_eip;
+        natural_width host_cr0;
+        natural_width host_cr3;
+        natural_width host_cr4;
+        natural_width host_fs_base;
+        natural_width host_gs_base;
+        natural_width host_tr_base;
+        natural_width host_gdtr_base;
+        natural_width host_idtr_base;
+        natural_width host_ia32_sysenter_esp;
+        natural_width host_ia32_sysenter_eip;
+        natural_width host_rsp;
+        natural_width host_rip;
+        natural_width paddingl[8]; /* room for future expansion */
+        u32 pin_based_vm_exec_control;
+        u32 cpu_based_vm_exec_control;
+        u32 exception_bitmap;
+        u32 page_fault_error_code_mask;
+        u32 page_fault_error_code_match;
+        u32 cr3_target_count;
+        u32 vm_exit_controls;
+        u32 vm_exit_msr_store_count;
+        u32 vm_exit_msr_load_count;
+        u32 vm_entry_controls;
+        u32 vm_entry_msr_load_count;
+        u32 vm_entry_intr_info_field;
+        u32 vm_entry_exception_error_code;
+        u32 vm_entry_instruction_len;
+        u32 tpr_threshold;
+        u32 secondary_vm_exec_control;
+        u32 vm_instruction_error;
+        u32 vm_exit_reason;
+        u32 vm_exit_intr_info;
+        u32 vm_exit_intr_error_code;
+        u32 idt_vectoring_info_field;
+        u32 idt_vectoring_error_code;
+        u32 vm_exit_instruction_len;
+        u32 vmx_instruction_info;
+        u32 guest_es_limit;
+        u32 guest_cs_limit;
+        u32 guest_ss_limit;
+        u32 guest_ds_limit;
+        u32 guest_fs_limit;
+        u32 guest_gs_limit;
+        u32 guest_ldtr_limit;
+        u32 guest_tr_limit;
+        u32 guest_gdtr_limit;
+        u32 guest_idtr_limit;
+        u32 guest_es_ar_bytes;
+        u32 guest_cs_ar_bytes;
+        u32 guest_ss_ar_bytes;
+        u32 guest_ds_ar_bytes;
+        u32 guest_fs_ar_bytes;
+        u32 guest_gs_ar_bytes;
+        u32 guest_ldtr_ar_bytes;
+        u32 guest_tr_ar_bytes;
+        u32 guest_interruptibility_info;
+        u32 guest_activity_state;
+        u32 guest_sysenter_cs;
+        u32 host_ia32_sysenter_cs;
+        u32 vmx_preemption_timer_value;
+        u32 padding32[7]; /* room for future expansion */
+        u16 virtual_processor_id;
+        u16 posted_intr_nv;
+        u16 guest_es_selector;
+        u16 guest_cs_selector;
+        u16 guest_ss_selector;
+        u16 guest_ds_selector;
+        u16 guest_fs_selector;
+        u16 guest_gs_selector;
+        u16 guest_ldtr_selector;
+        u16 guest_tr_selector;
+        u16 guest_intr_status;
+        u16 host_es_selector;
+        u16 host_cs_selector;
+        u16 host_ss_selector;
+        u16 host_ds_selector;
+        u16 host_fs_selector;
+        u16 host_gs_selector;
+        u16 host_tr_selector;
+        u16 guest_pml_index;
+};
+
+/*
+ * VMCS12_REVISION is an arbitrary id that should be changed if the content or
+ * layout of struct vmcs12 is changed. MSR_IA32_VMX_BASIC returns this id, and
+ * VMPTRLD verifies that the VMCS region that L1 is loading contains this id.
+ *
+ * IMPORTANT: Changing this value will break save/restore compatibility with
+ * older kvm releases.
+ */
+#define VMCS12_REVISION 0x11e57ed0
+
+#endif
Signature · 1 line
2.34.1
Signature · 4 lines
 -----Open up your eyes, open up your mind, open up your code -------   
/ Dr. David Alan Gilbert    |       Running GNU/Linux       | Happy  \ 
\        dave @ treblig.org |                               | In Hex /
 \ _________________________|_____ http://www.treblig.org   |_______/
#5 lore raw

Re: [PATCH v4 2/7] Import vmcs12 definition from Linux/KVM

In reply to Don Porter
Quoted 5 lines · Don Porter
---
  target/i386/kvm/vmcs12.h | 213 +++++++++++++++++++++++++++++++++++++++
  1 file changed, 213 insertions(+)

create mode 100644 target/i386/kvm/vmcs12.h

I don't think you actually need this.
I'll comment on that vs patch 3.

r~

author
#6 lore raw

PATCH v4 3/7 Add an "info pg" command that prints the current page tables

In reply to Don Porter

The new "info pg" monitor command prints the current page table, including virtual address ranges, flag bits, and snippets of physical page numbers. Completely filled regions of the page table with compatible flags are "folded", with the result that the complete output for a freshly booted x86-64 Linux VM can fit in a single terminal window. The output looks like this:

Info pg for CPU 0
VPN range Entry Flags Physical page
[7f0000000-7f0000000] PML4[0fe] ---DA--UWP
[7f28c0000-7f28fffff] PDP[0a3] ---DA--UWP

    [7f28c4600-7f28c47ff]  PDE[023]     ---DA--UWP
      [7f28c4655-7f28c4656]  PTE[055-056] X--D---U-P 0000007f14-0000007f15
      [7f28c465b-7f28c465b]  PTE[05b]     ----A--U-P 0000001cfc
...
[ff8000000-ff8000000] PML4[1ff]     ---DA--UWP
  [ffff80000-ffffbffff]  PDP[1fe]     ---DA---WP
    [ffff81000-ffff81dff]  PDE[008-00e] -GSDA---WP 0000001000-0000001dff
  [ffffc0000-fffffffff]  PDP[1ff]     ---DA--UWP
    [ffffff400-ffffff5ff]  PDE[1fa]     ---DA--UWP
      [ffffff5fb-ffffff5fc]  PTE[1fb-1fc] XG-DACT-WP 00000fec00 00000fee00
    [ffffff600-ffffff7ff]  PDE[1fb]     ---DA--UWP
      [ffffff600-ffffff600]  PTE[000]     -G-DA--U-P 0000001467

This draws heavy inspiration from Austin Clements' original patch.

For nested paging, it does a recursive walk:

Info pg for CPU 0, guest mode
VPN range Entry Flags Physical page(s)
[008000000-00fffffff] PML4[001] -------UWP
[008000000-00803ffff] PDP[000] -------UWP

    [008000800-0080009ff]  PDE[004]     -------UWP
      [008000800-00800085b]  PTE[000-05b] -------U-P 000000076a-00000007c5
    [008000a00-008000bff]  PDE[005]     -------UWP
      [008000a00-008000a0f]  PTE[000-00f] -------U-P 000000075a-0000000769
    [008003e00-008003fff]  PDE[01f]     -------UWP
      [008003fa8-008003fb7]  PTE[1a8-1b7] --------WP 000000054b-000000055a
      [008003fc0-008003fcf]  PTE[1c0-1cf] --------WP 000000053b-000000054a
      [008003fd8-008003fe7]  PTE[1d8-1e7] --------WP 000000052b-000000053a
      [008003ff0-008003fff]  PTE[1f0-1ff] --------WP 000000051b-000000052a
    [008004000-008004fff]  PDE[020-027] -------UWP
      [008004000-008004fff]  PTE[000-1ff] --------WP 0000000000-0000000fff

Info pg for CPU 0, host mode
VPN range Entry Flags Physical page(s)
[000000000-007ffffff] PML4[000] ----XWR
[000000000-00003ffff] PDP[000] ----XWR

    [000000000-0000001ff]  PDE[000]     ----XWR
      [000000001-000000005]  PTE[001-005] ----XWR    0000001b24-0000001b28
      [000000006-000000006]  PTE[006]     ----XWR    0000001ab6
      [000000007-000000007]  PTE[007]     ----XWR    00000012ab
      [000000008-00000000e]  PTE[008-00e] ----XWR    0000001b29-0000001b2f

...

This also adds a generic page table walker, which other monitor and execution commands will be migrated to in subsequent patches.

Finally, this patch adds some fields to the x86 architectural state that are necessary to implement nested page table walks, but are not standardized across acclerator back-ends. Because I cannot test on all of these accelerators, the goal of this patch set is to detect if the accelerator and page table format can be walked, and fail gracefully if not.

---
 hmp-commands-info.hx              |  13 +
 hw/core/cpu-sysemu.c              | 168 ++++-
 hw/core/machine-qmp-cmds.c        | 243 ++++++++
 include/hw/core/cpu.h             |  78 ++-
 include/hw/core/sysemu-cpu-ops.h  | 138 ++++-
 include/monitor/hmp-target.h      |   1 +
 qapi/machine.json                 |  17 +
 system/memory_mapping.c           |   2 +-
 target/i386/arch_memory_mapping.c | 994 +++++++++++++++++++++++++++++-
 target/i386/cpu.c                 |  23 +-
 target/i386/cpu.h                 |  58 +-
 target/i386/kvm/kvm.c             |  68 ++
 target/i386/monitor.c             | 175 ++++++
 13 files changed, 1967 insertions(+), 11 deletions(-)
hmp-commands-info.hx +13 -0
index c59cd6637b..8f178193e3 100644
@@ -242,6 +242,19 @@ SRST
     Show memory tree.
 ERST
 
+    {
+        .name         = "pg",
+        .args_type    = "",
+        .params       = "",
+        .help         = "show the page table",
+        .cmd_info_hrt = qmp_x_query_pg,
+    },
+
+SRST
+  ``info pg``
+    Show the active page table.
+ERST
+
 #if defined(CONFIG_TCG)
     {
         .name       = "jit",
hw/core/cpu-sysemu.c +166 -2

181 lines not on this page · raw message

hw/core/machine-qmp-cmds.c +243 -0

252 lines not on this page · raw message

include/hw/core/cpu.h +76 -2

95 lines not on this page · raw message

include/hw/core/sysemu-cpu-ops.h +137 -1

156 lines not on this page · raw message

include/monitor/hmp-target.h +1 -0
index b679aaebbf..9af72ea58d 100644
@@ -50,6 +50,7 @@ CPUState *mon_get_cpu(Monitor *mon);
 void hmp_info_mem(Monitor *mon, const QDict *qdict);
 void hmp_info_tlb(Monitor *mon, const QDict *qdict);
 void hmp_mce(Monitor *mon, const QDict *qdict);
+void hmp_info_pg(Monitor *mon, const QDict *qdict);
 void hmp_info_local_apic(Monitor *mon, const QDict *qdict);
 void hmp_info_sev(Monitor *mon, const QDict *qdict);
 void hmp_info_sgx(Monitor *mon, const QDict *qdict);
qapi/machine.json +17 -0
index f9ea6b3e97..2a259588dc 100644
@@ -1771,6 +1771,23 @@
   'if': 'CONFIG_TCG',
   'features': [ 'unstable' ] }
 
+##
+# @x-query-pg:
+#
+# Query current page tables
+#
+# Features:
+#
+# @unstable: This command is meant for debugging.
+#
+# Returns: Compressed summary of page tables.
+#
+# Since: 9.0
+##
+{ 'command': 'x-query-pg',
+  'returns': 'HumanReadableText',
+  'features': [ 'unstable' ] }
+
 ##
 # @x-query-ramblock:
 #
system/memory_mapping.c +1 -1
index 6f884c5b90..78499ae607 100644
@@ -296,7 +296,7 @@ static CPUState *find_paging_enabled_cpu(void)
     CPUState *cpu;
 
     CPU_FOREACH(cpu) {
-        if (cpu_paging_enabled(cpu)) {
+        if (cpu_paging_enabled(cpu, 0)) {
             return cpu;
         }
     }
target/i386/arch_memory_mapping.c +992 -2

1,009 lines not on this page · raw message

target/i386/cpu.c +21 -2
index 4688d140c2..ec419e0ef0 100644
@@ -8050,11 +8050,25 @@ static int64_t x86_cpu_get_arch_id(CPUState *cs)
 }
 
 #if !defined(CONFIG_USER_ONLY)
-static bool x86_cpu_get_paging_enabled(const CPUState *cs)
+static bool x86_cpu_get_paging_enabled(const CPUState *cs, int mmu_idx)
 {
     X86CPU *cpu = X86_CPU(cs);
 
-    return cpu->env.cr[0] & CR0_PG_MASK;
+    if (mmu_idx == 0) {
+        return cpu->env.cr[0] & CR0_PG_MASK;
+    } else if (mmu_idx == 1) {
+        if (cpu->env.hflags & HF_GUEST_MASK) {
+            if (!cpu->env.vm_state_valid) {
+                warn_report_once("Attempt to query virtualization state on an"
+                                 "unsupported accelerator.  This operation will"
+                                 "not work properly on this configuration.");
+                return false;
+            }
+
+            return cpu->env.nested_paging;
+        }
+    }
+    return false;
 }
 #endif /* !CONFIG_USER_ONLY */
 
@@ -8369,6 +8383,11 @@ static const struct SysemuCPUOps i386_sysemu_ops = {
     .write_elf32_qemunote = x86_cpu_write_elf32_qemunote,
     .write_elf64_qemunote = x86_cpu_write_elf64_qemunote,
     .legacy_vmsd = &vmstate_x86_cpu,
+    .page_table_root = &x86_page_table_root,
+    .get_pte = &x86_get_pte,
+    .mon_init_page_table_iterator = &x86_mon_init_page_table_iterator,
+    .mon_info_pg_print_header = &x86_mon_info_pg_print_header,
+    .mon_flush_page_print_state = &x86_mon_flush_print_pg_state,
 };
 #endif
 
target/i386/cpu.h +57 -1

96 lines not on this page · raw message

target/i386/kvm/kvm.c +68 -0

80 lines not on this page · raw message

target/i386/monitor.c +175 -0

181 lines not on this page · raw message

Signature · 1 line
2.34.1
#7 lore raw

Re: [PATCH v4 3/7] Add an "info pg" command that prints the current page tables

Quoted 5 lines · Don Porter
include/hw/core/cpu.h +0 -0
index d946161717..c70d31433d 100644

include/hw/core/cpu.h extern bool mttcg_enabled; · line 612

Quoted 9 lines
include/hw/core/cpu.h +2 -1
@@ -605,10 +605,11 @@ extern bool mttcg_enabled;
  /**
   * cpu_paging_enabled:
   * @cpu: The CPU whose state is to be inspected.
+ * @mmu_idx: 0 == traditional paging, 1 == nested paging
   *
   * Returns: %true if paging is enabled, %false otherwise.
   */
-bool cpu_paging_enabled(const CPUState *cpu);
+bool cpu_paging_enabled(const CPUState *cpu, int mmu_idx);

mmu_idx already means something very different to TCG.
You will only confuse matters by using this name for a different concept here.

Quoted 71 lines
include/hw/core/cpu.h +64 -1
@@ -671,9 +672,82 @@ int cpu_write_elf32_qemunote(WriteCoreDumpFunction f, CPUState *cpu,
   * Caller is responsible for freeing the data.
   */
  GuestPanicInformation *cpu_get_crash_info(CPUState *cpu);
-
  #endif /* !CONFIG_USER_ONLY */
 
+/* Maximum supported page table height - currently x86 at 5 */
+#define MAX_HEIGHT 5
+
+typedef struct PageTableLayout {
+    int height; /* Height of the page table */
+    int entries_per_node[MAX_HEIGHT + 1];
+} PageTableLayout;
+
+typedef struct DecodedPTE {
+    int prot; /* Always populated, arch-specific, decoded flags */
+    bool present;
+    bool leaf; /* Only valid if present */
+    bool reserved_bits_ok;
+    bool user_read_ok;
+    bool user_write_ok;
+    bool user_exec_ok;
+    bool super_read_ok;
+    bool super_write_ok;
+    bool super_exec_ok;
+    bool dirty;
+    hwaddr child; /* Only valid if present and !leaf */
+    uint64_t leaf_page_size; /* Only valid if present and leaf */
+    uint64_t nested_page_size; /*
+                                * If nested paging, the page size of the host
+                                * page storing the data, versus the size of the
+                                * guest page frame in leaf_page_size
+                                */
+    vaddr bits_translated; /*
+                            * The virtual address bits translated in walking
+                            * the page table to node[i].
+                            */
+    hwaddr pte_addr; /* (guest) physical address of the PTE */
+    hwaddr pte_host_addr; /* (host) physical address of the PTE */
+    uint64_t pte_contents; /* Raw contents of the pte */
+} DecodedPTE;
+
+typedef int (*qemu_page_walker_for_each)(CPUState *cs, void *data,
+                                         DecodedPTE *pte,
+                                         int height, int offset, int mmu_idx,
+                                         const PageTableLayout *layout);
+
+/**
+ * for_each_pte - iterate over a page table, and
+ *                call fn on each entry
+ *
+ * @cs - CPU state
+ * @fn(cs, data, pte, height, offset, layout) - User-provided function to call
+ *                                              on each pte.
+ *   * @cs - pass through cs
+ *   * @data - user-provided, opaque pointer
+ *   * @pte - current pte, decoded
+ *   * @height - height in the tree of pte
+ *   * @offset - offset within the page tabe node
+ *   * @layout - pointer to a PageTableLayout for this tree
+ * @data - opaque pointer; passed through to fn
+ * @visit_interior_nodes - if true, call fn() on interior entries in
+ *                         page table; if false, visit only leaf entries.
+ * @visit_not_present - if true, call fn() on entries that are not present.
+ *                         if false, visit only present entries.
+ * @mmu_idx - Which level of the mmu we are interested in:
+ *            0 == user mode, 1 == nested page table
+ *            Note that MMU_*_IDX macros are not consistent across
+ *            architectures.
+ *

include/hw/core/cpu.h int cpu_write_elf32_qemunote(WriteCoreDumpFunction f, CPUState *cpu, · line 750

Quoted 10 lines
include/hw/core/cpu.h +10 -0
+ * Returns true on success, false on error.
+ *
+ * We assume all callers of this function are in debug mode, and do not
+ * want to synthesize, say, a user-mode load, on each page in the address
+ * space.
+ */
+bool for_each_pte(CPUState *cs, qemu_page_walker_for_each fn, void *data,
+                  bool visit_interior_nodes, bool visit_not_present,
+                  bool visit_malformed, int mmu_idx);
+

None of this should be in hw/core/cpu.h. Isolate it somewhere else, not included by 80% of QEMU.

Quoted 34 lines
include/hw/core/sysemu-cpu-ops.h +26 -0
index 4c94e51267..d0e939def8 100644
@@ -12,6 +12,43 @@
 
  #include "hw/core/cpu.h"
 
+/*
+ * struct mem_print_state: Used by qmp in walking page tables.
+ */
+struct mem_print_state {
+    GString *buf;
+    CPUArchState *env;
+    int vaw, paw; /* VA and PA width in characters */
+    int max_height;
+    int mmu_idx; /* 0 == user mode, 1 == nested page table */
+    bool (*flusher)(CPUState *cs, struct mem_print_state *state);
+    bool flush_interior; /* If false, only call flusher() on leaves */
+    bool require_physical_contiguity;
+    /*
+     * The height at which we started accumulating ranges, i.e., the
+     * next height we need to print once we hit the end of a
+     * contiguous range.
+     */
+    int start_height;
+    int leaf_height; /* The height at which we found a leaf, or -1 */
+    /*
+     * For compressing contiguous ranges, track the
+     * start and end of the range
+     */
+    hwaddr vstart[MAX_HEIGHT + 1]; /* Starting virt. addr. of open pte range */
+    hwaddr vend[MAX_HEIGHT + 1]; /* Ending virtual address of open pte range */
+    hwaddr pstart; /* Starting physical address of open pte range */

include/hw/core/sysemu-cpu-ops.h line 50

Quoted 10 lines
include/hw/core/sysemu-cpu-ops.h +10 -0
+    hwaddr pend; /* Ending physical address of open pte range */
+
+    /* PTE protection flags current root->leaf path */
+    uint64_t prot[MAX_HEIGHT + 1];
+
+    /* Page size (leaf) or address range covered (non-leaf). */
+    uint64_t pg_size[MAX_HEIGHT + 1];
+    int offset[MAX_HEIGHT + 1]; /* PTE range starting offsets */
+    int last_offset[MAX_HEIGHT + 1]; /* PTE range ending offsets */
+};

Likewise.
Also, CamelCase for typedefs, per coding style.

include/hw/core/sysemu-cpu-ops.h

Quoted 6 lines
include/hw/core/sysemu-cpu-ops.h +6 -0
+    if (env->hflags & HF_GUEST_MASK) {
+
+        /* Extract the EPTP value from vmcs12 structure, store in arch state */
+        if (env->nested_state->format == KVM_STATE_NESTED_FORMAT_VMX) {
+            struct vmcs12 *vmcs =
+                (struct vmcs12 *) env->nested_state->data.vmx->vmcs12;

This is not required. You appear to be confused by nested paging.

First: nested paging is how hardware virtualization works. When we are *using* hardware virtualization, all of that is the kernel's job. Our job as hypervisor is to give a bag of pages to the kernel and have it map them into the guest intermediate address space.

When we are *using* hardware virtualization, we are only ever concerned with one level of paging: from the guest to the intermediate address space. From there we use QEMU data structures to map to QEMU virtual address space (address_space_ld/st, etc).

This is all we will ever see from KVM, HVF etc.

With TCG, we can *emulate* hardware virtualization. It is at this point where we are concerned about two levels of paging, because QEMU is handling both.

r~

author
#8 lore raw

Re: [PATCH v4 3/7] Add an "info pg" command that prints the current page tables

Hi Richard,

Thank you for the feedback.

Quoted 13 lines · Richard Henderson
Quoted 7 lines · Don Porter

+    if (env->hflags & HF_GUEST_MASK) {
+
+        /* Extract the EPTP value from vmcs12 structure, store in arch state */
+        if (env->nested_state->format == KVM_STATE_NESTED_FORMAT_VMX) { +            struct vmcs12 *vmcs =
+                (struct vmcs12 *) env->nested_state->data.vmx->vmcs12;

This is not required.  You appear to be confused by nested paging.

Quoted 7 lines

First: nested paging is how hardware virtualization works.  When we are *using* hardware virtualization, all of that is the kernel's job.  Our job as hypervisor is to give a bag of pages to the kernel and have it map them into the guest intermediate address space.

When we are *using* hardware virtualization, we are only ever concerned with one level of paging: from the guest to the intermediate address space.  From there we use QEMU data structures to map to QEMU virtual address space (address_space_ld/st, etc).

This is all we will ever see from KVM, HVF etc.

With TCG, we can *emulate* hardware virtualization.  It is at this point where we are concerned about two levels of paging, because QEMU is handling both.

I actually think we are close to the same understanding, except that one can use KVM to emulate (well, pass through to) Intel's virtualization hardware for a guest (TCG does only appears to support AMD's hardware virtualization interfaces), which is a use case I care about for my course.

One of my test cases for these debugging features was to have a simple guest/nested hypervisor running on emulated VT-x hardware. As in, the "guest" code enters VT root mode and sets up a VMCS and EPT, and launches a guest, etc.

My understanding is that when one uses kvm in this way, in the kernel kvm creates shadow page tables to merge the guest hypervisor and host hypervisor's tables transparently to the guest.

My reading of the KVM code is that this ioctl is the way that emulated architectural state (like the vmcs) is synced from the kernel back to qemu.  I don't see another KVM API for getting things like the extended page table root and certain VMCS configuration flags that one needs to walk the page tables.  Most of this state is not currently exposed to debugging features in qemu, which is why this definition was not needed.

I am open to other suggestions how to get that state, like the EPT root pointer, from KVM.  Perhaps I am missing something.

----

I will admit the intermediate address space is a lot to get one's head around.  I believe I have consistently used appropriate address_space_ld/st and friends at this point.

Thanks again,

Don

author
#9 lore raw

PATCH v4 4/7 Convert 'info tlb' to use generic iterator.

In reply to Don Porter

If the the guest is using nested page tables, change the output format slightly, to first show guest virtual to guest physical, then guest physical to host physical, as below:

(qemu) info tlb
Info guest TLB (guest virtual to guest physical):

0000008000800000: 000000000076a000  -------U-P
0000008000801000: 000000000076b000  -------U-P
0000008000802000: 000000000076c000  -------U-P
0000008000803000: 000000000076d000  -------U-P
[...]
0000008004ffd000: 0000000000ffd000  --------WP
0000008004ffe000: 0000000000ffe000  --------WP
0000008004fff000: 0000000000fff000  --------WP
Info host TLB, (guest physical to host physical):
0000000000001000: 0000000001b20000  ----XWR
0000000000002000: 0000000001b21000  ----XWR
0000000000003000: 0000000001b22000  ----XWR
0000000000004000: 0000000001b23000  ----XWR
0000000000005000: 0000000001b24000  ----XWR

[...]

---
 include/hw/core/sysemu-cpu-ops.h |   7 +
 target/i386/cpu.c                |   1 +
 target/i386/cpu.h                |   2 +
 target/i386/monitor.c            | 233 +++++++++----------------------
 4 files changed, 75 insertions(+), 168 deletions(-)
include/hw/core/sysemu-cpu-ops.h +7 -0
index d0e939def8..083df4717c 100644
@@ -225,6 +225,13 @@ typedef struct SysemuCPUOps {
     bool (*mon_flush_page_print_state)(CPUState *cs,
                                        struct mem_print_state *state);
 
+    /**
+     * @mon_print_pte: Hook called by the monitor to print a page
+     * table entry at address addr, with contents pte.
+     */
+    void (*mon_print_pte) (CPUState *cs, GString *buf, hwaddr addr,
+                           hwaddr pte, uint64_t prot, int mmu_idx);
+
 } SysemuCPUOps;
 
 int compressing_iterator(CPUState *cs, void *data, DecodedPTE *pte,
target/i386/cpu.c +1 -0
index ec419e0ef0..030198497a 100644
@@ -8388,6 +8388,7 @@ static const struct SysemuCPUOps i386_sysemu_ops = {
     .mon_init_page_table_iterator = &x86_mon_init_page_table_iterator,
     .mon_info_pg_print_header = &x86_mon_info_pg_print_header,
     .mon_flush_page_print_state = &x86_mon_flush_print_pg_state,
+    .mon_print_pte = &x86_mon_print_pte,
 };
 #endif
 
target/i386/cpu.h +2 -0
index 4e5877f41d..413c743c1a 100644
@@ -2264,6 +2264,8 @@ bool x86_mon_init_page_table_iterator(CPUState *cpu, GString *buf, int mmu_idx,
                                       struct mem_print_state *state);
 void x86_mon_info_pg_print_header(struct mem_print_state *state);
 bool x86_mon_flush_print_pg_state(CPUState *cs, struct mem_print_state *state);
+void x86_mon_print_pte(CPUState *cs, GString *out_buf, hwaddr addr,
+                       hwaddr child, uint64_t prot, int mmu_idx);
 bool x86_ptw_translate(CPUState *cs, vaddr vaddress, hwaddr *hpa,
                        bool debug, int mmu_idx, bool user_access,
                        const MMUAccessType access_type, uint64_t *page_size,
target/i386/monitor.c +65 -168

266 lines not on this page · raw message

Signature · 1 line
2.34.1
#10 lore raw

Re: [PATCH v4 4/7] Convert 'info tlb' to use generic iterator.

Quoted 3 lines · * Don Porter ([email protected]) wrote:

If the the guest is using nested page tables, change the output format slightly, to first show guest virtual to guest physical, then guest physical to host physical, as below:

This surprises me from the title; the title made me think this was a change purely to the implementation.

Quoted 2 lines

(qemu) info tlb
Info guest TLB (guest virtual to guest physical):

It's a shame that the code that prints this has no way to know the column widths, since it would be nice to have:

   guest virt           guest phys    ???????????
> 0000008000800000: 000000000076a000  -------U-P
> 0000008000801000: 000000000076b000  -------U-P
> 0000008000802000: 000000000076c000  -------U-P
> 0000008000803000: 000000000076d000  -------U-P
Quoted 6 lines

[...]

0000008004ffd000: 0000000000ffd000  --------WP
0000008004ffe000: 0000000000ffe000  --------WP
0000008004fff000: 0000000000fff000  --------WP

Info host TLB, (guest physical to host physical):

Do you actually want this to happen in the same operation, or do you want info tlb -h (e.g.) to get the host info?

Quoted 91 lines
0000000000001000: 0000000001b20000  ----XWR
0000000000002000: 0000000001b21000  ----XWR
0000000000003000: 0000000001b22000  ----XWR
0000000000004000: 0000000001b23000  ----XWR
0000000000005000: 0000000001b24000  ----XWR

[...]

---
 include/hw/core/sysemu-cpu-ops.h |   7 +
 target/i386/cpu.c                |   1 +
 target/i386/cpu.h                |   2 +
 target/i386/monitor.c            | 233 +++++++++----------------------
 4 files changed, 75 insertions(+), 168 deletions(-)
include/hw/core/sysemu-cpu-ops.h +7 -0
index d0e939def8..083df4717c 100644
@@ -225,6 +225,13 @@ typedef struct SysemuCPUOps {
     bool (*mon_flush_page_print_state)(CPUState *cs,
                                        struct mem_print_state *state);
 
+    /**
+     * @mon_print_pte: Hook called by the monitor to print a page
+     * table entry at address addr, with contents pte.
+     */
+    void (*mon_print_pte) (CPUState *cs, GString *buf, hwaddr addr,
+                           hwaddr pte, uint64_t prot, int mmu_idx);
+
 } SysemuCPUOps;
 
 int compressing_iterator(CPUState *cs, void *data, DecodedPTE *pte,
target/i386/cpu.c +1 -0
index ec419e0ef0..030198497a 100644
@@ -8388,6 +8388,7 @@ static const struct SysemuCPUOps i386_sysemu_ops = {
     .mon_init_page_table_iterator = &x86_mon_init_page_table_iterator,
     .mon_info_pg_print_header = &x86_mon_info_pg_print_header,
     .mon_flush_page_print_state = &x86_mon_flush_print_pg_state,
+    .mon_print_pte = &x86_mon_print_pte,
 };
 #endif
 
target/i386/cpu.h +2 -0
index 4e5877f41d..413c743c1a 100644
@@ -2264,6 +2264,8 @@ bool x86_mon_init_page_table_iterator(CPUState *cpu, GString *buf, int mmu_idx,
                                       struct mem_print_state *state);
 void x86_mon_info_pg_print_header(struct mem_print_state *state);
 bool x86_mon_flush_print_pg_state(CPUState *cs, struct mem_print_state *state);
+void x86_mon_print_pte(CPUState *cs, GString *out_buf, hwaddr addr,
+                       hwaddr child, uint64_t prot, int mmu_idx);
 bool x86_ptw_translate(CPUState *cs, vaddr vaddress, hwaddr *hpa,
                        bool debug, int mmu_idx, bool user_access,
                        const MMUAccessType access_type, uint64_t *page_size,
target/i386/monitor.c +6 -16
index 8ef92e7c42..d88347684b 100644
@@ -224,201 +224,98 @@ static hwaddr addr_canonical(CPUArchState *env, hwaddr addr)
     return addr;
 }
 
-static void print_pte(Monitor *mon, CPUArchState *env, hwaddr addr,
-                      hwaddr pte, hwaddr mask)
+void x86_mon_print_pte(CPUState *cs, GString *out_buf, hwaddr addr,
+                       hwaddr child, uint64_t prot, int mmu_idx)
 {
+    CPUX86State *env = cpu_env(cs);
+    g_autoptr(GString) buf = g_string_new("");
+
     addr = addr_canonical(env, addr);
 
-    monitor_printf(mon, HWADDR_FMT_plx ": " HWADDR_FMT_plx
-                   " %c%c%c%c%c%c%c%c%c\n",
-                   addr,
-                   pte & mask,
-                   pte & PG_NX_MASK ? 'X' : '-',
-                   pte & PG_GLOBAL_MASK ? 'G' : '-',
-                   pte & PG_PSE_MASK ? 'P' : '-',
-                   pte & PG_DIRTY_MASK ? 'D' : '-',
-                   pte & PG_ACCESSED_MASK ? 'A' : '-',
-                   pte & PG_PCD_MASK ? 'C' : '-',
-                   pte & PG_PWT_MASK ? 'T' : '-',
-                   pte & PG_USER_MASK ? 'U' : '-',
-                   pte & PG_RW_MASK ? 'W' : '-');
-}
+    g_string_append_printf(buf, HWADDR_FMT_plx ": " HWADDR_FMT_plx " ",

target/i386/monitor.c static hwaddr addr_canonical(CPUArchState *env, hwaddr addr) · line 253

Quoted 10 lines
target/i386/monitor.c +2 -6
+                           addr, child);
 
-static void tlb_info_32(Monitor *mon, CPUArchState *env)
-{
-    unsigned int l1, l2;
-    uint32_t pgd, pde, pte;
+    g_string_append_printf(buf, " %s", pg_bits(cs, prot, mmu_idx));
 
-    pgd = env->cr[3] & ~0xfff;
-    for(l1 = 0; l1 < 1024; l1++) {

It's nice to see all this hairy code disappearing.

Quoted 18 lines
target/i386/monitor.c +0 -18
-        cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);
-        pde = le32_to_cpu(pde);
-        if (pde & PG_PRESENT_MASK) {
-            if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {
-                /* 4M pages */
-                print_pte(mon, env, (l1 << 22), pde, ~((1 << 21) - 1));
-            } else {
-                for(l2 = 0; l2 < 1024; l2++) {
-                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);
-                    pte = le32_to_cpu(pte);
-                    if (pte & PG_PRESENT_MASK) {
-                        print_pte(mon, env, (l1 << 22) + (l2 << 12),
-                                  pte & ~PG_PSE_MASK,
-                                  ~0xfff);
-                    }
-                }
-            }
-        }

target/i386/monitor.c static hwaddr addr_canonical(CPUArchState *env, hwaddr addr) · line 241

Quoted 10 lines
target/i386/monitor.c +2 -8
-    }
-}
-
-static void tlb_info_pae32(Monitor *mon, CPUArchState *env)
-{
-    unsigned int l1, l2, l3;
-    uint64_t pdpe, pde, pte;
-    uint64_t pdp_addr, pd_addr, pt_addr;
+    /* Trim line to fit screen */
+    g_string_truncate(buf, 79);

Do we need that? It's a pretty arbitrary limit these days.

Quoted 121 lines
target/i386/monitor.c +14 -98
-    pdp_addr = env->cr[3] & ~0x1f;
-    for (l1 = 0; l1 < 4; l1++) {
-        cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);
-        pdpe = le64_to_cpu(pdpe);
-        if (pdpe & PG_PRESENT_MASK) {
-            pd_addr = pdpe & 0x3fffffffff000ULL;
-            for (l2 = 0; l2 < 512; l2++) {
-                cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);
-                pde = le64_to_cpu(pde);
-                if (pde & PG_PRESENT_MASK) {
-                    if (pde & PG_PSE_MASK) {
-                        /* 2M pages with PAE, CR4.PSE is ignored */
-                        print_pte(mon, env, (l1 << 30) + (l2 << 21), pde,
-                                  ~((hwaddr)(1 << 20) - 1));
-                    } else {
-                        pt_addr = pde & 0x3fffffffff000ULL;
-                        for (l3 = 0; l3 < 512; l3++) {
-                            cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);
-                            pte = le64_to_cpu(pte);
-                            if (pte & PG_PRESENT_MASK) {
-                                print_pte(mon, env, (l1 << 30) + (l2 << 21)
-                                          + (l3 << 12),
-                                          pte & ~PG_PSE_MASK,
-                                          ~(hwaddr)0xfff);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-    }
+    g_string_append_printf(out_buf, "%s\n", buf->str);
 }
 
-#ifdef TARGET_X86_64
-static void tlb_info_la48(Monitor *mon, CPUArchState *env,
-        uint64_t l0, uint64_t pml4_addr)
+static
+int mem_print_tlb(CPUState *cs, void *data, DecodedPTE *pte, int height,
+                  int offset, int mmu_idx, const PageTableLayout *layout)
 {
-    uint64_t l1, l2, l3, l4;
-    uint64_t pml4e, pdpe, pde, pte;
-    uint64_t pdp_addr, pd_addr, pt_addr;
-
-    for (l1 = 0; l1 < 512; l1++) {
-        cpu_physical_memory_read(pml4_addr + l1 * 8, &pml4e, 8);
-        pml4e = le64_to_cpu(pml4e);
-        if (!(pml4e & PG_PRESENT_MASK)) {
-            continue;
-        }
-
-        pdp_addr = pml4e & 0x3fffffffff000ULL;
-        for (l2 = 0; l2 < 512; l2++) {
-            cpu_physical_memory_read(pdp_addr + l2 * 8, &pdpe, 8);
-            pdpe = le64_to_cpu(pdpe);
-            if (!(pdpe & PG_PRESENT_MASK)) {
-                continue;
-            }
+    struct mem_print_state *state = (struct mem_print_state *) data;
+    CPUClass *cc = CPU_GET_CLASS(cs);
 
-            if (pdpe & PG_PSE_MASK) {
-                /* 1G pages, CR4.PSE is ignored */
-                print_pte(mon, env, (l0 << 48) + (l1 << 39) + (l2 << 30),
-                        pdpe, 0x3ffffc0000000ULL);
-                continue;
-            }
-
-            pd_addr = pdpe & 0x3fffffffff000ULL;
-            for (l3 = 0; l3 < 512; l3++) {
-                cpu_physical_memory_read(pd_addr + l3 * 8, &pde, 8);
-                pde = le64_to_cpu(pde);
-                if (!(pde & PG_PRESENT_MASK)) {
-                    continue;
-                }
+    cc->sysemu_ops->mon_print_pte(cs, state->buf, pte->bits_translated,
+                                  pte->child, pte->prot, mmu_idx);
 
-                if (pde & PG_PSE_MASK) {
-                    /* 2M pages, CR4.PSE is ignored */
-                    print_pte(mon, env, (l0 << 48) + (l1 << 39) + (l2 << 30) +
-                            (l3 << 21), pde, 0x3ffffffe00000ULL);
-                    continue;
-                }
-
-                pt_addr = pde & 0x3fffffffff000ULL;
-                for (l4 = 0; l4 < 512; l4++) {
-                    cpu_physical_memory_read(pt_addr
-                            + l4 * 8,
-                            &pte, 8);
-                    pte = le64_to_cpu(pte);
-                    if (pte & PG_PRESENT_MASK) {
-                        print_pte(mon, env, (l0 << 48) + (l1 << 39) +
-                                (l2 << 30) + (l3 << 21) + (l4 << 12),
-                                pte & ~PG_PSE_MASK, 0x3fffffffff000ULL);
-                    }
-                }
-            }
-        }
-    }
+    return 0;
 }
 
-static void tlb_info_la57(Monitor *mon, CPUArchState *env)
+static
+void helper_hmp_info_tlb(CPUState *cs, Monitor *mon, int mmu_idx)
 {
-    uint64_t l0;
-    uint64_t pml5e;
-    uint64_t pml5_addr;
+    struct mem_print_state state;
+    g_autoptr(GString) buf = g_string_new("");
+    CPUClass *cc = CPU_GET_CLASS(cs);
 
-    pml5_addr = env->cr[3] & 0x3fffffffff000ULL;
-    for (l0 = 0; l0 < 512; l0++) {
-        cpu_physical_memory_read(pml5_addr + l0 * 8, &pml5e, 8);
-        pml5e = le64_to_cpu(pml5e);
-        if (pml5e & PG_PRESENT_MASK) {
-            tlb_info_la48(mon, env, l0, pml5e & 0x3fffffffff000ULL);

target/i386/monitor.c static hwaddr addr_canonical(CPUArchState *env, hwaddr addr) · line 274

Quoted 10 lines
target/i386/monitor.c +8 -1
-        }
+    if (!cc->sysemu_ops->mon_init_page_table_iterator(cs, buf, mmu_idx,
+                                                      &state)) {
+        monitor_printf(mon, "Unable to initialize page table iterator\n");
+        return;
     }
+
+    /**
+     * 'info tlb' visits only leaf PTEs marked present.
+     * It does not check other protection bits.

(What happens if the guest is using huge pages inside the guest?)

Quoted 8 lines
target/i386/monitor.c +4 -1
+     */
+    for_each_pte(cs, &mem_print_tlb, &state, false, false, false,  mmu_idx);
+
+    monitor_printf(mon, "%s", buf->str);
 }
-#endif /* TARGET_X86_64 */
 
 void hmp_info_tlb(Monitor *mon, const QDict *qdict)

target/i386/monitor.c static hwaddr addr_canonical(CPUArchState *env, hwaddr addr) · line 287

Quoted 10 lines
target/i386/monitor.c +4 -4
 {
-    CPUArchState *env;
+    CPUState *cs = mon_get_cpu(mon);
+    bool nested;
 
-    env = mon_get_cpu_env(mon);
-    if (!env) {
-        monitor_printf(mon, "No CPU available\n");
+    if (!cs) {
+        monitor_printf(mon, "Unable to get CPUState.  Internal error\n");

I wouldn't bother saying ' Internal error'.

Quoted 53 lines
target/i386/monitor.c +25 -16
         return;
     }
 
-    if (!(env->cr[0] & CR0_PG_MASK)) {
+    if (!cpu_paging_enabled(cs, 0)) {
         monitor_printf(mon, "PG disabled\n");
         return;
     }
-    if (env->cr[4] & CR4_PAE_MASK) {
-#ifdef TARGET_X86_64
-        if (env->hflags & HF_LMA_MASK) {
-            if (env->cr[4] & CR4_LA57_MASK) {
-                tlb_info_la57(mon, env);
-            } else {
-                tlb_info_la48(mon, env, 0, env->cr[3] & 0x3fffffffff000ULL);
-            }
-        } else
-#endif
-        {
-            tlb_info_pae32(mon, env);
-        }
-    } else {
-        tlb_info_32(mon, env);
+
+    CPUClass *cc = CPU_GET_CLASS(cs);
+
+    if (!cc->sysemu_ops->mon_print_pte
+        || !cc->sysemu_ops->mon_init_page_table_iterator) {
+        monitor_printf(mon, "Info tlb unsupported on this ISA\n");
+        return;
+    }
+
+    nested = cpu_paging_enabled(cs, 1);
+
+    if (nested) {
+        monitor_printf(mon,
+                       "Info guest TLB (guest virtual to guest physical):\n");
+    }
+
+    helper_hmp_info_tlb(cs, mon, 0);
+
+    if (nested) {
+        monitor_printf(mon,
+                       "Info host TLB, (guest physical to host physical):\n");
+
+        helper_hmp_info_tlb(cs, mon, 1);
+
     }
 }
 
Signature · 1 line
2.34.1
Signature · 4 lines
 -----Open up your eyes, open up your mind, open up your code -------   
/ Dr. David Alan Gilbert    |       Running GNU/Linux       | Happy  \ 
\        dave @ treblig.org |                               | In Hex /
 \ _________________________|_____ http://www.treblig.org   |_______/
author
#11 lore raw

PATCH v4 5/7 Convert 'info mem' to use generic iterator

In reply to Don Porter

In the case of nested paging, change the output slightly to show both the guest's and host's view.

For example:

(qemu) info mem
Info guest mem (guest virtual to guest physical mappings):
0000008000800000-000000800085c000 000000000005c000 ur- 0000008000a00000-0000008000a10000 0000000000010000 ur- 0000008003fa8000-0000008003fb8000 0000000000010000 -rw 0000008003fc0000-0000008003fd0000 0000000000010000 -rw 0000008003fd8000-0000008003fe8000 0000000000010000 -rw 0000008003ff0000-0000008005000000 0000000001010000 -rw Info host mem (guest physical to host physical mappings):
0000000000001000-000000000000f000 000000000000e000 -xwr 00000000000b8000-00000000000b9000 0000000000001000 -xwr 0000000000100000-0000000000108000 0000000000008000 -xwr 0000000000200000-00000000007c6000 00000000005c6000 -xwr

---
 include/hw/core/sysemu-cpu-ops.h |   6 +
 target/i386/cpu.c                |   1 +
 target/i386/cpu.h                |   1 +
 target/i386/monitor.c            | 387 +++++++------------------------
 4 files changed, 95 insertions(+), 300 deletions(-)
include/hw/core/sysemu-cpu-ops.h +6 -0
index 083df4717c..f8b71fb60d 100644
@@ -232,6 +232,12 @@ typedef struct SysemuCPUOps {
     void (*mon_print_pte) (CPUState *cs, GString *buf, hwaddr addr,
                            hwaddr pte, uint64_t prot, int mmu_idx);
 
+    /**
+     * @mon_print_mem: Hook called by the monitor to print a range
+     * of memory mappings in 'info mem'
+     */
+    bool (*mon_print_mem)(CPUState *cs, struct mem_print_state *state);
+
 } SysemuCPUOps;
 
 int compressing_iterator(CPUState *cs, void *data, DecodedPTE *pte,
target/i386/cpu.c +1 -0
index 030198497a..f9ca2cddd3 100644
@@ -8389,6 +8389,7 @@ static const struct SysemuCPUOps i386_sysemu_ops = {
     .mon_info_pg_print_header = &x86_mon_info_pg_print_header,
     .mon_flush_page_print_state = &x86_mon_flush_print_pg_state,
     .mon_print_pte = &x86_mon_print_pte,
+    .mon_print_mem = &x86_mon_print_mem,
 };
 #endif
 
target/i386/cpu.h +1 -0
index 413c743c1a..da565bb7da 100644
@@ -2266,6 +2266,7 @@ void x86_mon_info_pg_print_header(struct mem_print_state *state);
 bool x86_mon_flush_print_pg_state(CPUState *cs, struct mem_print_state *state);
 void x86_mon_print_pte(CPUState *cs, GString *out_buf, hwaddr addr,
                        hwaddr child, uint64_t prot, int mmu_idx);
+bool x86_mon_print_mem(CPUState *cs, struct mem_print_state *state);
 bool x86_ptw_translate(CPUState *cs, vaddr vaddress, hwaddr *hpa,
                        bool debug, int mmu_idx, bool user_access,
                        const MMUAccessType access_type, uint64_t *page_size,
target/i386/monitor.c +87 -300

418 lines not on this page · raw message

Signature · 1 line
2.34.1
author
#12 lore raw

PATCH v4 6/7 Convert x86_cpu_get_memory_mapping() to use generic iterators

In reply to Don Porter
---
 target/i386/arch_memory_mapping.c | 305 ++----------------------------
 1 file changed, 19 insertions(+), 286 deletions(-)
target/i386/arch_memory_mapping.c +19 -286
index ef29e4b42f..bb97443f0f 100644
@@ -1006,301 +1006,34 @@ bool x86_ptw_translate(CPUState *cs, vaddr vaddress, hwaddr *hpa,
 
 }
 
-/* PAE Paging or IA-32e Paging */
-static void walk_pte(MemoryMappingList *list, AddressSpace *as,
-                     hwaddr pte_start_addr,
-                     int32_t a20_mask, target_ulong start_line_addr)
-{
-    hwaddr pte_addr, start_paddr;
-    uint64_t pte;
-    target_ulong start_vaddr;
-    int i;
-
-    for (i = 0; i < 512; i++) {
-        pte_addr = (pte_start_addr + i * 8) & a20_mask;
-        pte = address_space_ldq(as, pte_addr, MEMTXATTRS_UNSPECIFIED, NULL);
-        if (!(pte & PG_PRESENT_MASK)) {
-            /* not present */
-            continue;
-        }
-
-        start_paddr = (pte & ~0xfff) & ~(0x1ULL << 63);
-        if (cpu_physical_memory_is_io(start_paddr)) {
-            /* I/O region */
-            continue;
-        }
-
-        start_vaddr = start_line_addr | ((i & 0x1ff) << 12);
-        memory_mapping_list_add_merge_sorted(list, start_paddr,
-                                             start_vaddr, 1 << 12);
-    }
-}
-
-/* 32-bit Paging */
-static void walk_pte2(MemoryMappingList *list, AddressSpace *as,
-                      hwaddr pte_start_addr, int32_t a20_mask,
-                      target_ulong start_line_addr)
-{
-    hwaddr pte_addr, start_paddr;
-    uint32_t pte;
-    target_ulong start_vaddr;
-    int i;
-
-    for (i = 0; i < 1024; i++) {
-        pte_addr = (pte_start_addr + i * 4) & a20_mask;
-        pte = address_space_ldl(as, pte_addr, MEMTXATTRS_UNSPECIFIED, NULL);
-        if (!(pte & PG_PRESENT_MASK)) {
-            /* not present */
-            continue;
-        }
-
-        start_paddr = pte & ~0xfff;
-        if (cpu_physical_memory_is_io(start_paddr)) {
-            /* I/O region */
-            continue;
-        }
-
-        start_vaddr = start_line_addr | ((i & 0x3ff) << 12);
-        memory_mapping_list_add_merge_sorted(list, start_paddr,
-                                             start_vaddr, 1 << 12);
-    }
-}
-
-/* PAE Paging or IA-32e Paging */
-#define PLM4_ADDR_MASK 0xffffffffff000ULL /* selects bits 51:12 */
-
-static void walk_pde(MemoryMappingList *list, AddressSpace *as,
-                     hwaddr pde_start_addr,
-                     int32_t a20_mask, target_ulong start_line_addr)
-{
-    hwaddr pde_addr, pte_start_addr, start_paddr;
-    uint64_t pde;
-    target_ulong line_addr, start_vaddr;
-    int i;
-
-    for (i = 0; i < 512; i++) {
-        pde_addr = (pde_start_addr + i * 8) & a20_mask;
-        pde = address_space_ldq(as, pde_addr, MEMTXATTRS_UNSPECIFIED, NULL);
-        if (!(pde & PG_PRESENT_MASK)) {
-            /* not present */
-            continue;
-        }
-
-        line_addr = start_line_addr | ((i & 0x1ff) << 21);
-        if (pde & PG_PSE_MASK) {
-            /* 2 MB page */
-            start_paddr = (pde & ~0x1fffff) & ~(0x1ULL << 63);
-            if (cpu_physical_memory_is_io(start_paddr)) {
-                /* I/O region */
-                continue;
-            }
-            start_vaddr = line_addr;
-            memory_mapping_list_add_merge_sorted(list, start_paddr,
-                                                 start_vaddr, 1 << 21);
-            continue;
-        }
-
-        pte_start_addr = (pde & PLM4_ADDR_MASK) & a20_mask;
-        walk_pte(list, as, pte_start_addr, a20_mask, line_addr);
-    }
-}
-
-/* 32-bit Paging */
-static void walk_pde2(MemoryMappingList *list, AddressSpace *as,
-                      hwaddr pde_start_addr, int32_t a20_mask,
-                      bool pse)
-{
-    hwaddr pde_addr, pte_start_addr, start_paddr, high_paddr;
-    uint32_t pde;
-    target_ulong line_addr, start_vaddr;
-    int i;
-
-    for (i = 0; i < 1024; i++) {
-        pde_addr = (pde_start_addr + i * 4) & a20_mask;
-        pde = address_space_ldl(as, pde_addr, MEMTXATTRS_UNSPECIFIED, NULL);
-        if (!(pde & PG_PRESENT_MASK)) {
-            /* not present */
-            continue;
-        }
-
-        line_addr = (((unsigned int)i & 0x3ff) << 22);
-        if ((pde & PG_PSE_MASK) && pse) {
-            /*
-             * 4 MB page:
-             * bits 39:32 are bits 20:13 of the PDE
-             * bit3 31:22 are bits 31:22 of the PDE
-             */
-            high_paddr = ((hwaddr)(pde & 0x1fe000) << 19);
-            start_paddr = (pde & ~0x3fffff) | high_paddr;
-            if (cpu_physical_memory_is_io(start_paddr)) {
-                /* I/O region */
-                continue;
-            }
-            start_vaddr = line_addr;
-            memory_mapping_list_add_merge_sorted(list, start_paddr,
-                                                 start_vaddr, 1 << 22);
-            continue;
-        }
-
-        pte_start_addr = (pde & ~0xfff) & a20_mask;
-        walk_pte2(list, as, pte_start_addr, a20_mask, line_addr);
-    }
-}
-
-/* PAE Paging */
-static void walk_pdpe2(MemoryMappingList *list, AddressSpace *as,
-                       hwaddr pdpe_start_addr, int32_t a20_mask)
-{
-    hwaddr pdpe_addr, pde_start_addr;
-    uint64_t pdpe;
-    target_ulong line_addr;
-    int i;
-
-    for (i = 0; i < 4; i++) {
-        pdpe_addr = (pdpe_start_addr + i * 8) & a20_mask;
-        pdpe = address_space_ldq(as, pdpe_addr, MEMTXATTRS_UNSPECIFIED, NULL);
-        if (!(pdpe & PG_PRESENT_MASK)) {
-            /* not present */
-            continue;
-        }
-
-        line_addr = (((unsigned int)i & 0x3) << 30);
-        pde_start_addr = (pdpe & ~0xfff) & a20_mask;
-        walk_pde(list, as, pde_start_addr, a20_mask, line_addr);
-    }
-}
+struct memory_mapping_data {
+    MemoryMappingList *list;
+};
 
-#ifdef TARGET_X86_64
-/* IA-32e Paging */
-static void walk_pdpe(MemoryMappingList *list, AddressSpace *as,
-                      hwaddr pdpe_start_addr, int32_t a20_mask,
-                      target_ulong start_line_addr)
+static int add_memory_mapping_to_list(CPUState *cs, void *data, DecodedPTE *pte,
+                                      int height, int offset, int mmu_idx,
+                                      const PageTableLayout *layout)
 {
-    hwaddr pdpe_addr, pde_start_addr, start_paddr;
-    uint64_t pdpe;
-    target_ulong line_addr, start_vaddr;
-    int i;
-
-    for (i = 0; i < 512; i++) {
-        pdpe_addr = (pdpe_start_addr + i * 8) & a20_mask;
-        pdpe = address_space_ldq(as, pdpe_addr, MEMTXATTRS_UNSPECIFIED, NULL);
-        if (!(pdpe & PG_PRESENT_MASK)) {
-            /* not present */
-            continue;
-        }
-
-        line_addr = start_line_addr | ((i & 0x1ffULL) << 30);
-        if (pdpe & PG_PSE_MASK) {
-            /* 1 GB page */
-            start_paddr = (pdpe & ~0x3fffffff) & ~(0x1ULL << 63);
-            if (cpu_physical_memory_is_io(start_paddr)) {
-                /* I/O region */
-                continue;
-            }
-            start_vaddr = line_addr;
-            memory_mapping_list_add_merge_sorted(list, start_paddr,
-                                                 start_vaddr, 1 << 30);
-            continue;
-        }
-
-        pde_start_addr = (pdpe & PLM4_ADDR_MASK) & a20_mask;
-        walk_pde(list, as, pde_start_addr, a20_mask, line_addr);
-    }
-}
+    struct memory_mapping_data *mm_data = (struct memory_mapping_data *) data;
 
-/* IA-32e Paging */
-static void walk_pml4e(MemoryMappingList *list, AddressSpace *as,
-                       hwaddr pml4e_start_addr, int32_t a20_mask,
-                       target_ulong start_line_addr)
-{
-    hwaddr pml4e_addr, pdpe_start_addr;
-    uint64_t pml4e;
-    target_ulong line_addr;
-    int i;
-
-    for (i = 0; i < 512; i++) {
-        pml4e_addr = (pml4e_start_addr + i * 8) & a20_mask;
-        pml4e = address_space_ldq(as, pml4e_addr, MEMTXATTRS_UNSPECIFIED,
-                                  NULL);
-        if (!(pml4e & PG_PRESENT_MASK)) {
-            /* not present */
-            continue;
-        }
+    /* In the case of nested paging, give the real, host-physical mapping. */
+    hwaddr start_paddr = pte->pte_host_addr;
+    size_t pg_size = pte->leaf_page_size;
 
-        line_addr = start_line_addr | ((i & 0x1ffULL) << 39);
-        pdpe_start_addr = (pml4e & PLM4_ADDR_MASK) & a20_mask;
-        walk_pdpe(list, as, pdpe_start_addr, a20_mask, line_addr);
+    /* This hook skips mappings for the I/O region */
+    if (cpu_physical_memory_is_io(start_paddr)) {
+        /* I/O region */
+        return 0;
     }
-}
-
-static void walk_pml5e(MemoryMappingList *list, AddressSpace *as,
-                       hwaddr pml5e_start_addr, int32_t a20_mask)
-{
-    hwaddr pml5e_addr, pml4e_start_addr;
-    uint64_t pml5e;
-    target_ulong line_addr;
-    int i;
-
-    for (i = 0; i < 512; i++) {
-        pml5e_addr = (pml5e_start_addr + i * 8) & a20_mask;
-        pml5e = address_space_ldq(as, pml5e_addr, MEMTXATTRS_UNSPECIFIED,
-                                  NULL);
-        if (!(pml5e & PG_PRESENT_MASK)) {
-            /* not present */
-            continue;
-        }
 
-        line_addr = (0x7fULL << 57) | ((i & 0x1ffULL) << 48);
-        pml4e_start_addr = (pml5e & PLM4_ADDR_MASK) & a20_mask;
-        walk_pml4e(list, as, pml4e_start_addr, a20_mask, line_addr);
-    }
+    memory_mapping_list_add_merge_sorted(mm_data->list, start_paddr,
+                                         pte->bits_translated, pg_size);
+    return 0;
 }
-#endif
 
 bool x86_cpu_get_memory_mapping(CPUState *cs, MemoryMappingList *list,
                                 Error **errp)
 {
-    X86CPU *cpu = X86_CPU(cs);
-    CPUX86State *env = &cpu->env;
-    int32_t a20_mask;
-
-    if (!cpu_paging_enabled(cs, 0)) {
-        /* paging is disabled */
-        return true;
-    }
-
-    a20_mask = x86_get_a20_mask(env);
-    if (env->cr[4] & CR4_PAE_MASK) {
-#ifdef TARGET_X86_64
-        if (env->hflags & HF_LMA_MASK) {
-            if (env->cr[4] & CR4_LA57_MASK) {
-                hwaddr pml5e_addr;
-
-                pml5e_addr = (env->cr[3] & PLM4_ADDR_MASK) & a20_mask;
-                walk_pml5e(list, cs->as, pml5e_addr, a20_mask);
-            } else {
-                hwaddr pml4e_addr;
-
-                pml4e_addr = (env->cr[3] & PLM4_ADDR_MASK) & a20_mask;
-                walk_pml4e(list, cs->as, pml4e_addr, a20_mask,
-                        0xffffULL << 48);
-            }
-        } else
-#endif
-        {
-            hwaddr pdpe_addr;
-
-            pdpe_addr = (env->cr[3] & ~0x1f) & a20_mask;
-            walk_pdpe2(list, cs->as, pdpe_addr, a20_mask);
-        }
-    } else {
-        hwaddr pde_addr;
-        bool pse;
-
-        pde_addr = (env->cr[3] & ~0xfff) & a20_mask;
-        pse = !!(env->cr[4] & CR4_PSE_MASK);
-        walk_pde2(list, cs->as, pde_addr, a20_mask, pse);
-    }
-
-    return true;
+    return for_each_pte(cs, &add_memory_mapping_to_list, list, false, false,
+                        false, 0);
 }
Signature · 1 line
2.34.1
author
#13 lore raw

PATCH v4 7/7 Convert x86_mmu_translate() to use common code.

In reply to Don Porter
---
 target/i386/tcg/helper-tcg.h         |   2 +-
 target/i386/tcg/sysemu/excp_helper.c | 417 ++-------------------------
 2 files changed, 30 insertions(+), 389 deletions(-)
target/i386/tcg/helper-tcg.h +1 -1
index 1cbeab9161..8f63280359 100644
@@ -96,7 +96,7 @@ void cpu_load_eflags(CPUX86State *env, int eflags, int update_mask);
 typedef struct TranslateFault {
     int exception_index;
     int error_code;
-    target_ulong cr2;
+    uint64_t cr2;
     TranslateFaultStage2 stage2;
 } TranslateFault;
 
target/i386/tcg/sysemu/excp_helper.c +29 -388

457 lines not on this page · raw message

Signature · 1 line
2.34.1
#14 lore raw
In reply to Don Porter

Hi Don.

In addition to the other issues, this really needs to be broken up into many more patches.

Every patch should do *one* thing:

- Code motion
- Introduce an API
- Introduce target-specific support for an API
- Use an API to implement a monitor command
- etc

Patch 3, 'Add an "info pg" command ...' attempts to do all of these at once, and so is at least 2000 lines too long, which makes the whole thing extraordinarily hard to review.

r~

author
#15 lore raw
Quoted 12 lines · Richard Henderson

Hi Don.

In addition to the other issues, this really needs to be broken up into many more patches.

Every patch should do *one* thing:

  - Code motion
  - Introduce an API
  - Introduce target-specific support for an API
  - Use an API to implement a monitor command
  - etc

Quoted 4 lines

Patch 3, 'Add an "info pg" command ...' attempts to do all of these at once, and so is at least 2000 lines too long, which makes the whole thing extraordinarily hard to review.

r~

Hi Richard (and others),

I just wanted to acknowledge that this and the other feedback makes sense and I can apply them and send a new version, with the exception of what to do about KVM guest register state for Intel VT.

Thanks,

Don