Skip to contentSkip to conversation

x86/HVM: emulation (MMIO) improvements

PATCH Superseded Jan Beulich 2 participants 12 messages Sep 4, 2024 – Sep 9, 2024

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore
#0 lore raw

cover x86/HVM: emulation (MMIO) improvements

The main fix is patch 3, with the earlier patches setting the stage and the latter ones simplifying other things at least a little in exchange.

1: reduce recursion in linear_{read,write}()
2: allocate emulation cache entries dynamically
3: correct read/write split at page boundaries
4: slightly improve CMPXCHG16B emulation
5: drop redundant access splitting

Jan

#1 lore raw

PATCH 1/5 x86/HVM: reduce recursion in linear_{read,write}()

Let's make explicit what the compiler may or may not do on our behalf:
The 2nd of the recursive invocations each can fall through rather than re-invoking the function. This will save us from adding yet another parameter (or more) to the function, just for the recursive invocations.

xen/arch/x86/hvm/emulate.c +18 -10
@@ -1146,7 +1146,7 @@ static int linear_read(unsigned long add
     pagefault_info_t pfinfo;
     struct hvm_vcpu_io *hvio = &current->arch.hvm.hvm_io;
     unsigned int offset = addr & ~PAGE_MASK;
-    int rc = HVMTRANS_bad_gfn_to_mfn;
+    int rc;
 
     if ( offset + bytes > PAGE_SIZE )
     {
@@ -1154,12 +1154,16 @@ static int linear_read(unsigned long add
 
         /* Split the access at the page boundary. */
         rc = linear_read(addr, part1, p_data, pfec, hvmemul_ctxt);
-        if ( rc == X86EMUL_OKAY )
-            rc = linear_read(addr + part1, bytes - part1, p_data + part1,
-                             pfec, hvmemul_ctxt);
-        return rc;
+        if ( rc != X86EMUL_OKAY )
+            return rc;
+
+        addr += part1;
+        bytes -= part1;
+        p_data += part1;
     }
 
+    rc = HVMTRANS_bad_gfn_to_mfn;
+
     /*
      * If there is an MMIO cache entry for the access then we must be re-issuing
      * an access that was previously handled as MMIO. Thus it is imperative that
@@ -1201,7 +1205,7 @@ static int linear_write(unsigned long ad
     pagefault_info_t pfinfo;
     struct hvm_vcpu_io *hvio = &current->arch.hvm.hvm_io;
     unsigned int offset = addr & ~PAGE_MASK;
-    int rc = HVMTRANS_bad_gfn_to_mfn;
+    int rc;
 
     if ( offset + bytes > PAGE_SIZE )
     {
@@ -1209,12 +1213,16 @@ static int linear_write(unsigned long ad
 
         /* Split the access at the page boundary. */
         rc = linear_write(addr, part1, p_data, pfec, hvmemul_ctxt);
-        if ( rc == X86EMUL_OKAY )
-            rc = linear_write(addr + part1, bytes - part1, p_data + part1,
-                              pfec, hvmemul_ctxt);
-        return rc;
+        if ( rc != X86EMUL_OKAY )
+            return rc;
+
+        addr += part1;
+        bytes -= part1;
+        p_data += part1;
     }
 
+    rc = HVMTRANS_bad_gfn_to_mfn;
+
     /*
      * If there is an MMIO cache entry for the access then we must be re-issuing
      * an access that was previously handled as MMIO. Thus it is imperative that
Reviewed-by on v1 1/5
#2 lore raw

Re: [PATCH 1/5] x86/HVM: reduce recursion in linear_{read,write}()

Quoted 6 lines · Jan Beulich

Let's make explicit what the compiler may or may not do on our behalf:
The 2nd of the recursive invocations each can fall through rather than re-invoking the function. This will save us from adding yet another parameter (or more) to the function, just for the recursive invocations.

#3 lore raw

PATCH 2/5 x86/HVM: allocate emulation cache entries dynamically

In reply to Jan Beulich

Both caches may need higher capacity, and the upper bound will need to be determined dynamically based on CPUID policy (for AMX at least).

While touching the check in hvmemul_phys_mmio_access() anyway, also tighten it: To avoid overrunning the internal buffer we need to take the offset into the buffer into account.

---
This is a patch taken from the AMX series, which was part of the v3 submission. All I did is strip out the actual AMX bits (from hvmemul_cache_init()), plus of course change the description. As a result some local variables there may look unnecessary, but this way it's going to be less churn when the AMX bits are added. The next patch pretty strongly depends on the changed approach (contextually, not so much functionally), and I'd really like to avoid rebasing that one ahead of this one, and then this one on top of that.

TBD: For AMX hvmemul_cache_init() will become CPUID policy dependent. We
could of course take the opportunity and also reduce overhead when AVX-512 (and maybe even AVX) is unavailable (in the future: to the guest).

xen/arch/x86/hvm/emulate.c +39 -12
@@ -26,6 +26,18 @@
 #include <asm/iocap.h>
 #include <asm/vm_event.h>
 
+/*
+ * We may read or write up to m512 or up to a tile row as a number of
+ * device-model transactions.
+ */
+struct hvm_mmio_cache {
+    unsigned long gla;
+    unsigned int size;
+    unsigned int space:31;
+    unsigned int dir:1;
+    uint8_t buffer[] __aligned(sizeof(long));
+};
+
 struct hvmemul_cache
 {
     /* The cache is disabled as long as num_ents > max_ents. */
@@ -935,7 +947,7 @@ static int hvmemul_phys_mmio_access(
     }
 
     /* Accesses must not overflow the cache's buffer. */
-    if ( size > sizeof(cache->buffer) )
+    if ( offset + size > cache->space )
     {
         ASSERT_UNREACHABLE();
         return X86EMUL_UNHANDLEABLE;
@@ -1011,7 +1023,7 @@ static struct hvm_mmio_cache *hvmemul_fi
 
     for ( i = 0; i < hvio->mmio_cache_count; i ++ )
     {
-        cache = &hvio->mmio_cache[i];
+        cache = hvio->mmio_cache[i];
 
         if ( gla == cache->gla &&
              dir == cache->dir )
@@ -1027,10 +1039,11 @@ static struct hvm_mmio_cache *hvmemul_fi
 
     ++hvio->mmio_cache_count;
 
-    cache = &hvio->mmio_cache[i];
-    memset(cache, 0, sizeof (*cache));
+    cache = hvio->mmio_cache[i];
+    memset(cache->buffer, 0, cache->space);
 
     cache->gla = gla;
+    cache->size = 0;
     cache->dir = dir;
 
     return cache;
@@ -2978,16 +2991,21 @@ void hvm_dump_emulation_state(const char
 int hvmemul_cache_init(struct vcpu *v)
 {
     /*
-     * No insn can access more than 16 independent linear addresses (AVX512F
-     * scatters/gathers being the worst). Each such linear range can span a
-     * page boundary, i.e. may require two page walks. Account for each insn
-     * byte individually, for simplicity.
+     * AVX512F scatter/gather insns can access up to 16 independent linear
+     * addresses, up to 8 bytes size. Each such linear range can span a page
+     * boundary, i.e. may require two page walks.
+     */
+    unsigned int nents = 16 * 2 * (CONFIG_PAGING_LEVELS + 1);
+    unsigned int i, max_bytes = 64;
+    struct hvmemul_cache *cache;
+
+    /*
+     * Account for each insn byte individually, both for simplicity and to
+     * leave some slack space.
      */
-    const unsigned int nents = (CONFIG_PAGING_LEVELS + 1) *
-                               (MAX_INST_LEN + 16 * 2);
-    struct hvmemul_cache *cache = xmalloc_flex_struct(struct hvmemul_cache,
-                                                      ents, nents);
+    nents += MAX_INST_LEN * (CONFIG_PAGING_LEVELS + 1);
 
+    cache = xvmalloc_flex_struct(struct hvmemul_cache, ents, nents);
     if ( !cache )
         return -ENOMEM;
 
@@ -2997,6 +3015,15 @@ int hvmemul_cache_init(struct vcpu *v)
 
     v->arch.hvm.hvm_io.cache = cache;
 
+    for ( i = 0; i < ARRAY_SIZE(v->arch.hvm.hvm_io.mmio_cache); ++i )
+    {
+        v->arch.hvm.hvm_io.mmio_cache[i] =
+            xmalloc_flex_struct(struct hvm_mmio_cache, buffer, max_bytes);
+        if ( !v->arch.hvm.hvm_io.mmio_cache[i] )
+            return -ENOMEM;
+        v->arch.hvm.hvm_io.mmio_cache[i]->space = max_bytes;
+    }
+
     return 0;
 }
 
xen/arch/x86/include/asm/hvm/emulate.h +6 -1
@@ -15,6 +15,7 @@
 #include <xen/err.h>
 #include <xen/mm.h>
 #include <xen/sched.h>
+#include <xen/xvmalloc.h>
 #include <asm/hvm/hvm.h>
 #include <asm/x86_emulate.h>
 
@@ -119,7 +120,11 @@ int hvmemul_do_pio_buffer(uint16_t port,
 int __must_check hvmemul_cache_init(struct vcpu *v);
 static inline void hvmemul_cache_destroy(struct vcpu *v)
 {
-    XFREE(v->arch.hvm.hvm_io.cache);
+    unsigned int i;
+
+    for ( i = 0; i < ARRAY_SIZE(v->arch.hvm.hvm_io.mmio_cache); ++i )
+        XFREE(v->arch.hvm.hvm_io.mmio_cache[i]);
+    XVFREE(v->arch.hvm.hvm_io.cache);
 }
 bool hvmemul_read_cache(const struct vcpu *v, paddr_t gpa,
                         void *buffer, unsigned int size);
xen/arch/x86/include/asm/hvm/vcpu.h +1 -12
@@ -22,17 +22,6 @@ struct hvm_vcpu_asid {
     uint32_t asid;
 };
 
-/*
- * We may read or write up to m512 as a number of device-model
- * transactions.
- */
-struct hvm_mmio_cache {
-    unsigned long gla;
-    unsigned int size;
-    uint8_t dir;
-    uint8_t buffer[64] __aligned(sizeof(long));
-};
-
 struct hvm_vcpu_io {
     /*
      * HVM emulation:
@@ -48,7 +37,7 @@ struct hvm_vcpu_io {
      * We may need to handle up to 3 distinct memory accesses per
      * instruction.
      */
-    struct hvm_mmio_cache mmio_cache[3];
+    struct hvm_mmio_cache *mmio_cache[3];
     unsigned int mmio_cache_count;
 
     /* For retries we shouldn't re-fetch the instruction. */
#4 lore raw

Re: [PATCH 2/5] x86/HVM: allocate emulation cache entries dynamically

Quoted 2 lines · Jan Beulich

Both caches may need higher capacity, and the upper bound will need to be determined dynamically based on CPUID policy (for AMX at least).

Is this to cope with TILE{LOAD,STORE}, or something else?

It's not exactly clear, even when looking at prior AMX series.

Quoted 3 lines

While touching the check in hvmemul_phys_mmio_access() anyway, also tighten it: To avoid overrunning the internal buffer we need to take the offset into the buffer into account.

Does this really want to be mixed with a prep patch ?

Quoted 11 lines

---
This is a patch taken from the AMX series, which was part of the v3 submission. All I did is strip out the actual AMX bits (from hvmemul_cache_init()), plus of course change the description. As a result some local variables there may look unnecessary, but this way it's going to be less churn when the AMX bits are added. The next patch pretty strongly depends on the changed approach (contextually, not so much functionally), and I'd really like to avoid rebasing that one ahead of this one, and then this one on top of that.

Fine by me.

Quoted 6 lines
xen/arch/x86/hvm/emulate.c +0 -0
@@ -26,6 +26,18 @@
 #include <asm/iocap.h>
 #include <asm/vm_event.h>
 

xen/arch/x86/hvm/emulate.c line 38

Quoted 10 lines
xen/arch/x86/hvm/emulate.c +10 -0
+/*
+ * We may read or write up to m512 or up to a tile row as a number of
+ * device-model transactions.
+ */
+struct hvm_mmio_cache {
+    unsigned long gla;
+    unsigned int size;
+    unsigned int space:31;
+    unsigned int dir:1;
+    uint8_t buffer[] __aligned(sizeof(long));

I know this is a minor tangent, but you are turning a regular struct into a flexible one.

Could we introduce __counted_by() and start using it here?

At the toolchain level, it lets the compiler understand the real size of the object, so e.g. the sanitisers can spot out-of-bounds accesses through the flexible member.

But, even in the short term, having

    /* TODO */

    # define __counted_by(member)

in compiler.h still leaves us with better code, because

    struct hvm_mmio_cache {
        unsigned long gla;
        unsigned int size;
        unsigned int space:31;
        unsigned int dir:1;
        uint8_t buffer[] __aligned(sizeof(long)) __counted_by(size); };

is explicitly clear in a case where the "space" field creates some ambiguity.

Quoted 10 lines
xen/arch/x86/hvm/emulate.c +2 -4
@@ -2978,16 +2991,21 @@ void hvm_dump_emulation_state(const char
 int hvmemul_cache_init(struct vcpu *v)
 {
     /*
-     * No insn can access more than 16 independent linear addresses (AVX512F
-     * scatters/gathers being the worst). Each such linear range can span a
-     * page boundary, i.e. may require two page walks. Account for each insn
-     * byte individually, for simplicity.
+     * AVX512F scatter/gather insns can access up to 16 independent linear
+     * addresses, up to 8 bytes size. Each such linear range can span a page

xen/arch/x86/hvm/emulate.c void hvm_dump_emulation_state(const char · line 3005

Quoted 10 lines
xen/arch/x86/hvm/emulate.c +9 -0
+     * boundary, i.e. may require two page walks.
+     */
+    unsigned int nents = 16 * 2 * (CONFIG_PAGING_LEVELS + 1);
+    unsigned int i, max_bytes = 64;
+    struct hvmemul_cache *cache;
+
+    /*
+     * Account for each insn byte individually, both for simplicity and to
+     * leave some slack space.
      */

Hang on.  Do we seriously use a separate cache entry for each instruction byte ?

~Andrew

#5 lore raw

Re: [PATCH 2/5] x86/HVM: allocate emulation cache entries dynamically

Quoted 5 lines · Andrew Cooper
Quoted 2 lines · Jan Beulich

Both caches may need higher capacity, and the upper bound will need to be determined dynamically based on CPUID policy (for AMX at least).

Is this to cope with TILE{LOAD,STORE}, or something else?

These two, yes.

Quoted 1 line

It's not exactly clear, even when looking at prior AMX series.

I've added mention of them.

Quoted 5 lines
Quoted 3 lines

While touching the check in hvmemul_phys_mmio_access() anyway, also tighten it: To avoid overrunning the internal buffer we need to take the offset into the buffer into account.

Does this really want to be mixed with a prep patch ?

Taking the offset into account becomes more important with subsequent patches. If needed, I can certainly split this out into its own prereq patch.

Quoted 41 lines
Quoted 6 lines
xen/arch/x86/hvm/emulate.c +0 -0
@@ -26,6 +26,18 @@
 #include <asm/iocap.h>
 #include <asm/vm_event.h>
 

xen/arch/x86/hvm/emulate.c line 38

Quoted 10 lines
xen/arch/x86/hvm/emulate.c +10 -0
+/*
+ * We may read or write up to m512 or up to a tile row as a number of
+ * device-model transactions.
+ */
+struct hvm_mmio_cache {
+    unsigned long gla;
+    unsigned int size;
+    unsigned int space:31;
+    unsigned int dir:1;
+    uint8_t buffer[] __aligned(sizeof(long));

I know this is a minor tangent, but you are turning a regular struct into a flexible one.

Could we introduce __counted_by() and start using it here?

At the toolchain level, it lets the compiler understand the real size of the object, so e.g. the sanitisers can spot out-of-bounds accesses through the flexible member.

But, even in the short term, having

    /* TODO */

    # define __counted_by(member)

in compiler.h still leaves us with better code, because

    struct hvm_mmio_cache {
        unsigned long gla;
        unsigned int size;
        unsigned int space:31;
        unsigned int dir:1;
        uint8_t buffer[] __aligned(sizeof(long)) __counted_by(size); };

Quoted 2 lines

is explicitly clear in a case where the "space" field creates some ambiguity.

Which raises a question here: Is it really "size" that you mean, not "space"? It's the latter that describes the capacity after all.

As to __counted_by() (or counted_by()) introduction: While is seems pretty orthogonal, I could of course add a prereq patch to introduce it. Yet - even if I had it expand to nothing for now, what do you expect it to expand to going forward? I've just gone through docs trying to find something to match, yet with no success.

Quoted 15 lines
Quoted 15 lines
xen/arch/x86/hvm/emulate.c +7 -4
@@ -2978,16 +2991,21 @@ void hvm_dump_emulation_state(const char
 int hvmemul_cache_init(struct vcpu *v)
 {
     /*
-     * No insn can access more than 16 independent linear addresses (AVX512F
-     * scatters/gathers being the worst). Each such linear range can span a
-     * page boundary, i.e. may require two page walks. Account for each insn
-     * byte individually, for simplicity.
+     * AVX512F scatter/gather insns can access up to 16 independent linear
+     * addresses, up to 8 bytes size. Each such linear range can span a page
+     * boundary, i.e. may require two page walks.
+     */
+    unsigned int nents = 16 * 2 * (CONFIG_PAGING_LEVELS + 1);
+    unsigned int i, max_bytes = 64;
+    struct hvmemul_cache *cache;
Quoted 8 lines

xen/arch/x86/hvm/emulate.c void hvm_dump_emulation_state(const char · line 3005

Quoted 5 lines
xen/arch/x86/hvm/emulate.c +4 -0
+
+    /*
+     * Account for each insn byte individually, both for simplicity and to
+     * leave some slack space.
      */

Hang on.  Do we seriously use a separate cache entry for each instruction byte ?

We don't _use_ one, but we set up one. Already prior to this patch; the comment merely moves (and is extended to mention the slack space aspect). Also note that it is only the other (read) cache this is relevant for, not the (MMIO) cache this series as a whole is about.

Jan

#6 lore raw

PATCH 3/5 x86/HVM: correct read/write split at page boundaries

In reply to Jan Beulich

The MMIO cache is intended to have one entry used per independent memory access that an insn does. This, in particular, is supposed to be ignoring any page boundary crossing. Therefore when looking up a cache entry, the access'es starting (linear) address is relevant, not the one possibly advanced past a page boundary.

In order for the same offset-into-buffer variable to be usable in hvmemul_phys_mmio_access() for both the caller's buffer and the cache entry's it is further necessary to have the un-adjusted caller buffer passed into there.

Fixes 2d527ba310dc ("x86/hvm: split all linear reads and writes at page boundary")

---
This way problematic overlaps are only reduced (to ones starting at the same address), not eliminated: Assumptions in hvmemul_phys_mmio_access() go further - if a subsequent access is larger than an earlier one, but the splitting results in a chunk to cross the end "boundary" of the earlier access, an assertion will still trigger. Explicit memory accesses (ones encoded in an insn by explicit or implicit memory operands) match the assumption afaict (i.e. all those accesses are of uniform size, and hence they either fully overlap or are mapped to distinct cache entries).

Insns accessing descriptor tables, otoh, don't fulfill these
expectations: The selector read (if coming from memory) will always be smaller than the descriptor being read, and if both (insanely) start at the same linear address (in turn mapping MMIO), said assertion will kick in. (The same would be true for an insn trying to access itself as data, as long as certain size "restrictions" between insn and memory operand are met. Except that linear_read() disallows insn fetches from MMIO.) To deal with such, I expect we will need to further qualify (tag) cache entries, such that reads/writes won't use insn fetch entries, and implicit-supervisor-mode accesses won't use entries of ordinary accesses. (Page table accesses don't need considering here for now, as our page walking code demands page tables to be mappable, implying they're in guest RAM; such accesses also don't take the path here.) Thoughts anyone, before I get to making another patch?

Considering the insn fetch aspect mentioned above I'm having trouble following why the cache has 3 entries. With insn fetches permitted, descriptor table accesses where the accessed bit needs setting may also fail because of that limited capacity of the cache, due to the way the accesses are done. The read and write (cmpxchg) are independent accesses from the cache's perspective, and hence we'd need another entry there. If, otoh, the 3 entries are there to account for precisely this (which seems unlikely with commit e101123463d2 ["x86/hvm: track large memory mapped accesses by buffer offset"] not saying anything at all), then we should be fine in this regard. If we were to permit insn fetches, which way to overcome this (possibly by allowing the write to re-use the earlier read's entry in this special situation) would remain to be determined.

xen/arch/x86/hvm/emulate.c +59 -29
@@ -31,8 +31,9 @@
  * device-model transactions.
  */
 struct hvm_mmio_cache {
-    unsigned long gla;
-    unsigned int size;
+    unsigned long gla;     /* Start of original access (e.g. insn operand) */
+    unsigned int skip;     /* Offset to start of MMIO */
+    unsigned int size;     /* Populated space, including @skip */
     unsigned int space:31;
     unsigned int dir:1;
     uint8_t buffer[] __aligned(sizeof(long));
@@ -953,6 +954,13 @@ static int hvmemul_phys_mmio_access(
         return X86EMUL_UNHANDLEABLE;
     }
 
+    /* Accesses must not be to the unused leading space. */
+    if ( offset < cache->skip )
+    {
+        ASSERT_UNREACHABLE();
+        return X86EMUL_UNHANDLEABLE;
+    }
+
     /*
      * hvmemul_do_io() cannot handle non-power-of-2 accesses or
      * accesses larger than sizeof(long), so choose the highest power
@@ -1010,13 +1018,15 @@ static int hvmemul_phys_mmio_access(
 
 /*
  * Multi-cycle MMIO handling is based upon the assumption that emulation
- * of the same instruction will not access the same MMIO region more
- * than once. Hence we can deal with re-emulation (for secondary or
- * subsequent cycles) by looking up the result or previous I/O in a
- * cache indexed by linear MMIO address.
+ * of the same instruction will not access the exact same MMIO region
+ * more than once in exactly the same way (if it does, the accesses will
+ * be "folded"). Hence we can deal with re-emulation (for secondary or
+ * subsequent cycles) by looking up the result of previous I/O in a cache
+ * indexed by linear address and access type.
  */
 static struct hvm_mmio_cache *hvmemul_find_mmio_cache(
-    struct hvm_vcpu_io *hvio, unsigned long gla, uint8_t dir, bool create)
+    struct hvm_vcpu_io *hvio, unsigned long gla, uint8_t dir,
+    unsigned int skip)
 {
     unsigned int i;
     struct hvm_mmio_cache *cache;
@@ -1030,7 +1040,11 @@ static struct hvm_mmio_cache *hvmemul_fi
             return cache;
     }
 
-    if ( !create )
+    /*
+     * Bail if a new entry shouldn't be allocated, utilizing that ->space has
+     * the same value for all entries.
+     */
+    if ( skip >= hvio->mmio_cache[0]->space )
         return NULL;
 
     i = hvio->mmio_cache_count;
@@ -1043,7 +1057,8 @@ static struct hvm_mmio_cache *hvmemul_fi
     memset(cache->buffer, 0, cache->space);
 
     cache->gla = gla;
-    cache->size = 0;
+    cache->skip = skip;
+    cache->size = skip;
     cache->dir = dir;
 
     return cache;
@@ -1064,12 +1079,14 @@ static void latch_linear_to_phys(struct
 
 static int hvmemul_linear_mmio_access(
     unsigned long gla, unsigned int size, uint8_t dir, void *buffer,
-    uint32_t pfec, struct hvm_emulate_ctxt *hvmemul_ctxt, bool known_gpfn)
+    uint32_t pfec, struct hvm_emulate_ctxt *hvmemul_ctxt,
+    unsigned long start, bool known_gpfn)
 {
     struct hvm_vcpu_io *hvio = &current->arch.hvm.hvm_io;
     unsigned long offset = gla & ~PAGE_MASK;
-    struct hvm_mmio_cache *cache = hvmemul_find_mmio_cache(hvio, gla, dir, true);
-    unsigned int chunk, buffer_offset = 0;
+    unsigned int chunk, buffer_offset = gla - start;
+    struct hvm_mmio_cache *cache = hvmemul_find_mmio_cache(hvio, start, dir,
+                                                           buffer_offset);
     paddr_t gpa;
     unsigned long one_rep = 1;
     int rc;
@@ -1117,19 +1134,19 @@ static int hvmemul_linear_mmio_access(
 static inline int hvmemul_linear_mmio_read(
     unsigned long gla, unsigned int size, void *buffer,
     uint32_t pfec, struct hvm_emulate_ctxt *hvmemul_ctxt,
-    bool translate)
+    unsigned long start, bool translate)
 {
     return hvmemul_linear_mmio_access(gla, size, IOREQ_READ, buffer,
-                                      pfec, hvmemul_ctxt, translate);
+                                      pfec, hvmemul_ctxt, start, translate);
 }
 
 static inline int hvmemul_linear_mmio_write(
     unsigned long gla, unsigned int size, void *buffer,
     uint32_t pfec, struct hvm_emulate_ctxt *hvmemul_ctxt,
-    bool translate)
+    unsigned long start, bool translate)
 {
     return hvmemul_linear_mmio_access(gla, size, IOREQ_WRITE, buffer,
-                                      pfec, hvmemul_ctxt, translate);
+                                      pfec, hvmemul_ctxt, start, translate);
 }
 
 static bool known_gla(unsigned long addr, unsigned int bytes, uint32_t pfec)
@@ -1158,7 +1175,10 @@ static int linear_read(unsigned long add
 {
     pagefault_info_t pfinfo;
     struct hvm_vcpu_io *hvio = &current->arch.hvm.hvm_io;
+    void *buffer = p_data;
+    unsigned long start = addr;
     unsigned int offset = addr & ~PAGE_MASK;
+    const struct hvm_mmio_cache *cache;
     int rc;
 
     if ( offset + bytes > PAGE_SIZE )
@@ -1182,8 +1202,17 @@ static int linear_read(unsigned long add
      * an access that was previously handled as MMIO. Thus it is imperative that
      * we handle this access in the same way to guarantee completion and hence
      * clean up any interim state.
+     *
+     * Care must be taken, however, to correctly deal with crossing RAM/MMIO or
+     * MMIO/RAM boundaries. While we want to use a single cache entry (tagged
+     * by the starting linear address), we need to continue issuing (i.e. also
+     * upon replay) the RAM access for anything that's ahead of or past MMIO,
+     * i.e. in RAM.
      */
-    if ( !hvmemul_find_mmio_cache(hvio, addr, IOREQ_READ, false) )
+    cache = hvmemul_find_mmio_cache(hvio, start, IOREQ_READ, ~0);
+    if ( !cache ||
+         addr + bytes <= start + cache->skip ||
+         addr >= start + cache->size )
         rc = hvm_copy_from_guest_linear(p_data, addr, bytes, pfec, &pfinfo);
 
     switch ( rc )
@@ -1199,8 +1228,8 @@ static int linear_read(unsigned long add
         if ( pfec & PFEC_insn_fetch )
             return X86EMUL_UNHANDLEABLE;
 
-        return hvmemul_linear_mmio_read(addr, bytes, p_data, pfec,
-                                        hvmemul_ctxt,
+        return hvmemul_linear_mmio_read(addr, bytes, buffer, pfec,
+                                        hvmemul_ctxt, start,
                                         known_gla(addr, bytes, pfec));
 
     case HVMTRANS_gfn_paged_out:
@@ -1217,7 +1246,10 @@ static int linear_write(unsigned long ad
 {
     pagefault_info_t pfinfo;
     struct hvm_vcpu_io *hvio = &current->arch.hvm.hvm_io;
+    void *buffer = p_data;
+    unsigned long start = addr;
     unsigned int offset = addr & ~PAGE_MASK;
+    const struct hvm_mmio_cache *cache;
     int rc;
 
     if ( offset + bytes > PAGE_SIZE )
@@ -1236,13 +1268,11 @@ static int linear_write(unsigned long ad
 
     rc = HVMTRANS_bad_gfn_to_mfn;
 
-    /*
-     * If there is an MMIO cache entry for the access then we must be re-issuing
-     * an access that was previously handled as MMIO. Thus it is imperative that
-     * we handle this access in the same way to guarantee completion and hence
-     * clean up any interim state.
-     */
-    if ( !hvmemul_find_mmio_cache(hvio, addr, IOREQ_WRITE, false) )
+    /* See commentary in linear_read(). */
+    cache = hvmemul_find_mmio_cache(hvio, start, IOREQ_WRITE, ~0);
+    if ( !cache ||
+         addr + bytes <= start + cache->skip ||
+         addr >= start + cache->size )
         rc = hvm_copy_to_guest_linear(addr, p_data, bytes, pfec, &pfinfo);
 
     switch ( rc )
@@ -1255,8 +1285,8 @@ static int linear_write(unsigned long ad
         return X86EMUL_EXCEPTION;
 
     case HVMTRANS_bad_gfn_to_mfn:
-        return hvmemul_linear_mmio_write(addr, bytes, p_data, pfec,
-                                         hvmemul_ctxt,
+        return hvmemul_linear_mmio_write(addr, bytes, buffer, pfec,
+                                         hvmemul_ctxt, start,
                                          known_gla(addr, bytes, pfec));
 
     case HVMTRANS_gfn_paged_out:
@@ -1643,7 +1673,7 @@ static int cf_check hvmemul_cmpxchg(
     {
         /* Fix this in case the guest is really relying on r-m-w atomicity. */
         return hvmemul_linear_mmio_write(addr, bytes, p_new, pfec,
-                                         hvmemul_ctxt,
+                                         hvmemul_ctxt, addr,
                                          hvio->mmio_access.write_access &&
                                          hvio->mmio_gla == (addr & PAGE_MASK));
     }
#7 lore raw

PATCH 4/5 x86/HVM: slightly improve CMPXCHG16B emulation

In reply to Jan Beulich

Using hvmemul_linear_mmio_write() directly (as fallback when mapping the memory operand isn't possible) won't work properly when the access crosses a RAM/MMIO boundary. Use linear_write() instead, which splits at such boundaries as necessary.

xen/arch/x86/hvm/emulate.c +1 -6
@@ -1645,10 +1645,8 @@ static int cf_check hvmemul_cmpxchg(
 {
     struct hvm_emulate_ctxt *hvmemul_ctxt =
         container_of(ctxt, struct hvm_emulate_ctxt, ctxt);
-    struct vcpu *curr = current;
     unsigned long addr;
     uint32_t pfec = PFEC_page_present | PFEC_write_access;
-    struct hvm_vcpu_io *hvio = &curr->arch.hvm.hvm_io;
     int rc;
     void *mapping = NULL;
 
@@ -1672,10 +1670,7 @@ static int cf_check hvmemul_cmpxchg(
     if ( !mapping )
     {
         /* Fix this in case the guest is really relying on r-m-w atomicity. */
-        return hvmemul_linear_mmio_write(addr, bytes, p_new, pfec,
-                                         hvmemul_ctxt, addr,
-                                         hvio->mmio_access.write_access &&
-                                         hvio->mmio_gla == (addr & PAGE_MASK));
+        return linear_write(addr, bytes, p_new, pfec, hvmemul_ctxt);
     }
 
     switch ( bytes )
Acked-by on v1 4/5
#8 lore raw

Re: [PATCH 4/5] x86/HVM: slightly improve CMPXCHG16B emulation

Quoted 6 lines · Jan Beulich

Using hvmemul_linear_mmio_write() directly (as fallback when mapping the memory operand isn't possible) won't work properly when the access crosses a RAM/MMIO boundary. Use linear_write() instead, which splits at such boundaries as necessary.

#9 lore raw

PATCH 5/5 x86/HVM: drop redundant access splitting

In reply to Jan Beulich

With all paths into hvmemul_linear_mmio_access() coming through linear_{read,write}(), there's no need anymore to split accesses at page boundaries there. Leave an assertion, though.

xen/arch/x86/hvm/emulate.c +5 -24
@@ -1084,7 +1084,7 @@ static int hvmemul_linear_mmio_access(
 {
     struct hvm_vcpu_io *hvio = &current->arch.hvm.hvm_io;
     unsigned long offset = gla & ~PAGE_MASK;
-    unsigned int chunk, buffer_offset = gla - start;
+    unsigned int buffer_offset = gla - start;
     struct hvm_mmio_cache *cache = hvmemul_find_mmio_cache(hvio, start, dir,
                                                            buffer_offset);
     paddr_t gpa;
@@ -1094,13 +1094,13 @@ static int hvmemul_linear_mmio_access(
     if ( cache == NULL )
         return X86EMUL_UNHANDLEABLE;
 
-    chunk = min_t(unsigned int, size, PAGE_SIZE - offset);
+    ASSERT(size <= PAGE_SIZE - offset);
 
     if ( known_gpfn )
         gpa = pfn_to_paddr(hvio->mmio_gpfn) | offset;
     else
     {
-        rc = hvmemul_linear_to_phys(gla, &gpa, chunk, &one_rep, pfec,
+        rc = hvmemul_linear_to_phys(gla, &gpa, size, &one_rep, pfec,
                                     hvmemul_ctxt);
         if ( rc != X86EMUL_OKAY )
             return rc;
@@ -1108,27 +1108,8 @@ static int hvmemul_linear_mmio_access(
         latch_linear_to_phys(hvio, gla, gpa, dir == IOREQ_WRITE);
     }
 
-    for ( ;; )
-    {
-        rc = hvmemul_phys_mmio_access(cache, gpa, chunk, dir, buffer, buffer_offset);
-        if ( rc != X86EMUL_OKAY )
-            break;
-
-        gla += chunk;
-        buffer_offset += chunk;
-        size -= chunk;
-
-        if ( size == 0 )
-            break;
-
-        chunk = min_t(unsigned int, size, PAGE_SIZE);
-        rc = hvmemul_linear_to_phys(gla, &gpa, chunk, &one_rep, pfec,
-                                    hvmemul_ctxt);
-        if ( rc != X86EMUL_OKAY )
-            return rc;
-    }
-
-    return rc;
+    return hvmemul_phys_mmio_access(cache, gpa, size, dir, buffer,
+                                    buffer_offset);
 }
 
 static inline int hvmemul_linear_mmio_read(
#10 lore raw

Re: [PATCH 5/5] x86/HVM: drop redundant access splitting

xen/arch/x86/hvm/emulate.c static int hvmemul_linear_mmio_access( · line 1097

Quoted 6 lines · Jan Beulich
xen/arch/x86/hvm/emulate.c +1 -1
@@ -1094,13 +1094,13 @@ static int hvmemul_linear_mmio_access(
     if ( cache == NULL )
         return X86EMUL_UNHANDLEABLE;
 
-    chunk = min_t(unsigned int, size, PAGE_SIZE - offset);
+    ASSERT(size <= PAGE_SIZE - offset);

Do we really want a plain assert, or should we go with

    if ( size > PAGE_SIZE - offset )
    {
        /* Callers should have arranged not to cross a page boundary */ ASSERT_UNREACHABLE();
        return X86EMUL_UNHANDLEABLE;
    }

This is hardly a fastpath, and it's rather safer.

~Andrew

#11 lore raw

Re: [PATCH 5/5] x86/HVM: drop redundant access splitting

Quoted 10 lines · Andrew Cooper

xen/arch/x86/hvm/emulate.c static int hvmemul_linear_mmio_access( · line 1097

Quoted 6 lines · Jan Beulich
xen/arch/x86/hvm/emulate.c +1 -1
@@ -1094,13 +1094,13 @@ static int hvmemul_linear_mmio_access(
     if ( cache == NULL )
         return X86EMUL_UNHANDLEABLE;
 
-    chunk = min_t(unsigned int, size, PAGE_SIZE - offset);
+    ASSERT(size <= PAGE_SIZE - offset);

Do we really want a plain assert, or should we go with

Quoted 8 lines

    if ( size > PAGE_SIZE - offset )
    {
        /* Callers should have arranged not to cross a page boundary */ ASSERT_UNREACHABLE();
        return X86EMUL_UNHANDLEABLE;
    }

This is hardly a fastpath, and it's rather safer.

I can switch, sure, yet to be honest it was already feeling a little like going too far to have the assertion, considering the obviousness of all callers guaranteeing this. The only reason I decided to add one is the remaining concern of there, at some point, possibly being single memory operands exceeding PAGE_SIZE. Yet nothing comes anywhere near that right now; whole AMX tiles are 1k "only", and tile rows / columns are even further restricted. Of course, if and when we add XSAVE/XRSTORE emulation ...

Jan