Skip to contentSkip to conversation

x86/alternatives: Adjust all insn-relative fields

PATCH Superseded Andrew Cooper 2 participants 23 messages Apr 22, 2024 – Sep 26, 2024

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover x86/alternatives: Adjust all insn-relative fields

Alternatives have had a reasonably severe restriction since their introduction. This has been the source of several bugs, and several inefficiencies particularly in the speculative safety paths, and I've finally gotten bored enough to fixing it.

Introduce the new infrastructure, and adjust the BHB scrubbing logic to use it.

Andrew Cooper (6):
x86: Introduce x86_decode_lite() x86/alternative: Walk all replacements in debug builds x86/alternative: Intend the relocation logic x86/alternative: Replace a continue with a goto x86/alternative: Relocate all insn-relative fields x86/spec-ctrl: Introduce and use DO_COND_BHB_SEQ

 xen/arch/x86/alternative.c               | 210 +++++++++++++------
 xen/arch/x86/hvm/vmx/entry.S             |  12 +-
 xen/arch/x86/include/asm/spec_ctrl_asm.h |  43 ++--
 xen/arch/x86/x86_emulate/Makefile        |   1 +
 xen/arch/x86/x86_emulate/decode-lite.c   | 245 +++++++++++++++++++++++
 xen/arch/x86/x86_emulate/private.h       |   2 +
 xen/arch/x86/x86_emulate/x86_emulate.h   |  17 ++
 7 files changed, 445 insertions(+), 85 deletions(-)
 create mode 100644 xen/arch/x86/x86_emulate/decode-lite.c
Signature · 1 line
2.30.2
#1 lore raw

PATCH 1/6 x86: Introduce x86_decode_lite()

In order to relocate all IP-relative fields in an alternative replacement block, we need to decode the instructions enough to obtain their length and any relative fields.

Full x86_decode() is far too heavyweight, so introduce a minimal form which can make several simplifying assumptions.

This logic is sufficient to decode all alternative blocks that exist in Xen right now.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/x86_emulate/Makefile      |   1 +
 xen/arch/x86/x86_emulate/decode-lite.c | 245 +++++++++++++++++++++++++
 xen/arch/x86/x86_emulate/private.h     |   2 +
 xen/arch/x86/x86_emulate/x86_emulate.h |  17 ++
 4 files changed, 265 insertions(+)
 create mode 100644 xen/arch/x86/x86_emulate/decode-lite.c
xen/arch/x86/x86_emulate/Makefile +1 -0
index 2e20d65d788a..f06731913d67 100644
@@ -3,6 +3,7 @@ obj-y += 0fae.o
 obj-y += 0fc7.o
 obj-y += blk.o
 obj-y += decode.o
+obj-y += decode-lite.o
 obj-$(CONFIG_HVM) += fpu.o
 obj-y += util.o
 obj-y += util-xen.o
xen/arch/x86/x86_emulate/decode-lite.c new file +245 -0

245 lines not on this page · raw message

xen/arch/x86/x86_emulate/private.h +2 -0
index 0fa26ba00aa5..792b04889ce6 100644
@@ -9,7 +9,9 @@
 #ifdef __XEN__
 
 # include <xen/bug.h>
+# include <xen/init.h>
 # include <xen/kernel.h>
+# include <xen/livepatch.h>
 # include <asm/endbr.h>
 # include <asm/msr-index.h>
 # include <asm/x86-vendors.h>
xen/arch/x86/x86_emulate/x86_emulate.h +17 -0
index d92be69d84d9..b7cbcd8b70ba 100644
@@ -842,4 +842,21 @@ static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt)
     ctxt->event = (struct x86_event){};
 }
 
+/*
+ * x86_decode_lite().  Very minimal decoder for managing alternatives.
+ *
+ * @len is -1 on error, or positive on success.  If the instruction has a
+ * relative field, REL_TYPE_* gives the size, and @rel points at the field.
+ */
+typedef struct {
+    int8_t len;
+    uint8_t rel_type;
+#define REL_TYPE_NONE 0
+#define REL_TYPE_d8   1
+#define REL_TYPE_d32  2
+    void *rel;
+} x86_decode_lite_t;
+
+x86_decode_lite_t x86_decode_lite(void *ip, void *end);
+
 #endif /* __X86_EMULATE_H__ */
Signature · 1 line
2.30.2
#2 lore raw

Re: [PATCH 1/6] x86: Introduce x86_decode_lite()

Quoted 15 lines · Andrew Cooper

In order to relocate all IP-relative fields in an alternative replacement block, we need to decode the instructions enough to obtain their length and any relative fields.

Full x86_decode() is far too heavyweight, so introduce a minimal form which can make several simplifying assumptions.

This logic is sufficient to decode all alternative blocks that exist in Xen right now.

xen/arch/x86/x86_emulate/Makefile obj-y += 0fae.o · line 6

Quoted 4 lines
xen/arch/x86/x86_emulate/Makefile +1 -0
@@ -3,6 +3,7 @@ obj-y += 0fae.o
 obj-y += 0fc7.o
 obj-y += blk.o
 obj-y += decode.o
+obj-y += decode-lite.o

When LIVEPATCH=n, this could do with conversion to *.init.o, like is done in the parent directory for alternative.c as well.

Quoted 27 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +24 -0
@@ -0,0 +1,245 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#include "private.h"
+
+#define Imm8   (1 << 0)
+#define Imm    (1 << 1)
+#define Branch (1 << 5) /* ... that we care about */
+/*      ModRM  (1 << 6) */
+#define Known  (1 << 7)
+
+#define ALU_OPS                                 \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \
+    (Known|Imm8),                               \
+    (Known|Imm)
+
+static const uint8_t init_or_livepatch_const onebyte[256] = {
+    [0x00] = ALU_OPS, /* ADD */ [0x08] = ALU_OPS, /* OR  */
+    [0x10] = ALU_OPS, /* ADC */ [0x18] = ALU_OPS, /* SBB */
+    [0x20] = ALU_OPS, /* AND */ [0x28] = ALU_OPS, /* SUB */
+    [0x30] = ALU_OPS, /* XOR */ [0x38] = ALU_OPS, /* CMP */
+

xen/arch/x86/x86_emulate/decode-lite.c line 34

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+    [0x50 ... 0x5f] = (Known),             /* PUSH/POP %reg */
+
+    [0x70 ... 0x7f] = (Known|Branch|Imm8), /* Jcc disp8 */
+    [0x80]          = (Known|ModRM|Imm8),
+    [0x81]          = (Known|ModRM|Imm),
+
+    [0x83]          = (Known|ModRM|Imm8),
+    [0x84 ... 0x8e] = (Known|ModRM),       /* TEST/XCHG/MOV/MOV-SREG/LEA r/rm */
+
+    [0xb0 ... 0xb7] = (Known|Imm8),        /* MOV $imm8, %reg */

I'm surprised you get away without at least NOP also marked as known. Imo the whole 0x90 row should be marked so.

Similarly I'm not convinced that leaving the 0xA0 row unpopulated is a good idea. It's at best a trap set up for somebody to fall into rather sooner than later.

xen/arch/x86/x86_emulate/decode-lite.c line 38

Quoted 4 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +4 -0
+    [0xb8 ... 0xbf] = (Known|Imm),         /* MOV $imm32, %reg */
+
+    [0xcc]          = (Known),             /* INT3 */
+    [0xcd]          = (Known|Imm8),        /* INT $imm8 */

Like above, what about in particular any of the shifts/rotates and the MOV that's in the 0xC0 row?

While the last sentence in the description is likely meant to cover that, I think the description wants to go further as to any pretty common but omitted insns. Already "x86: re-work memset()" and "x86: re- work memcpy()" (v2 pending for, soon, 3 years) would make it necessary to touch this table, thus increasing complexity of those changes to an area they shouldn't be concerned about at all.

xen/arch/x86/x86_emulate/decode-lite.c line 41

Quoted 2 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +2 -0
+    [0xe8 ... 0xe9] = (Known|Branch|Imm),  /* CALL/JMP disp32 */
+    [0xeb]          = (Known|Branch|Imm8), /* JMP disp8 */

0xe0 ... 0xe7 and 0xec ... 0xef would imo also better be covered, as they easily can be (much like you also cover e.g. CMC despite it appearing pretty unlikely that we use that insn anywhere).

xen/arch/x86/x86_emulate/decode-lite.c line 51

Quoted 9 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +9 -0
+    [0xf1]          = (Known),             /* ICEBP */
+    [0xf4]          = (Known),             /* HLT */
+    [0xf5]          = (Known),             /* CMC */
+    [0xf6 ... 0xf7] = (Known|ModRM),       /* Grp3 */
+    [0xf8 ... 0xfd] = (Known),             /* CLC ... STD */
+    [0xfe ... 0xff] = (Known|ModRM),       /* Grp4 */
+};
+static const uint8_t init_or_livepatch_const twobyte[256] = {
+    [0x00 ... 0x01] = (Known|ModRM),       /* Grp6/Grp7 */

LAR / LSL? CLTS? WBINVD? UD2?

xen/arch/x86/x86_emulate/decode-lite.c line 57

Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +5 -0
+    [0x18 ... 0x1f] = (Known|ModRM),       /* Grp16 (Hint Nop) */
+
+    [0x20 ... 0x23] = (Known|ModRM),       /* MOV CR/DR */
+
+    [0x30 ... 0x34] = (Known),             /* WRMSR ... RDPMC */

0x34 is SYSENTER, isn't it?

xen/arch/x86/x86_emulate/decode-lite.c line 60

Quoted 3 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +3 -0
+    [0x40 ... 0x4f] = (Known|ModRM),       /* CMOVcc */
+
+    [0x80 ... 0x8f] = (Known|Branch|Imm),  /* Jcc disp32 */

What about things like VMREAD/VMWRITE?

xen/arch/x86/x86_emulate/decode-lite.c line 61

Quoted 1 line
xen/arch/x86/x86_emulate/decode-lite.c new file +1 -0
+    [0x90 ... 0x9f] = (Known|ModRM),       /* SETcc */

PUSH/POP fs/gs? CPUID?

xen/arch/x86/x86_emulate/decode-lite.c line 63

Quoted 1 line
xen/arch/x86/x86_emulate/decode-lite.c new file +1 -0
+    [0xab]          = (Known|ModRM),       /* BTS */

BTS (and BTC below) but not BT and BTR?

xen/arch/x86/x86_emulate/decode-lite.c line 65

Quoted 2 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +2 -0
+    [0xac]          = (Known|ModRM|Imm8),  /* SHRD $imm8 */
+    [0xad ... 0xaf] = (Known|ModRM),       /* SHRD %cl / Grp15 / IMUL */

SHRD but not SHLD?

CMPXCHG?

xen/arch/x86/x86_emulate/decode-lite.c line 69

Quoted 3 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +3 -0
+    [0xb8 ... 0xb9] = (Known|ModRM),       /* POPCNT/Grp10 (UD1) */
+    [0xba]          = (Known|ModRM|Imm8),  /* Grp8 */
+    [0xbb ... 0xbf] = (Known|ModRM),       /* BSR/BSF/BSR/MOVSX */

Nit (comment only): 0xbb is BTC.

MOVSX but not MOVZX and also not MOVSXD (in the 1-byte table)?

xen/arch/x86/x86_emulate/decode-lite.c line 65

Quoted 1 line
xen/arch/x86/x86_emulate/decode-lite.c new file +1 -0
+};

XADD, MOVNTI, and the whole 0xc7-based group?

xen/arch/x86/x86_emulate/decode-lite.c line 81

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+/*
+ * Bare minimum x86 instruction decoder to parse the alternative replacement
+ * instructions and locate the IP-relative references that may need updating.
+ *
+ * These are:
+ *  - disp8/32 from near branches
+ *  - RIP-relative memory references
+ *
+ * The following simplifications are used:
+ *  - All code is 64bit, and the instruction stream is safe to read.

This, in particular, is imo important to state already ahead of the tables above, to clarify why e.g. row 0x40 is unpopulated.

Quoted 44 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +44 -0
+ *  - The 67 prefix is not implemented, so the address size is only 64bit.
+ *
+ * Inputs:
+ *  @ip  The position to start decoding from.
+ *  @end End of the replacement block.  Exceeding this is considered an error.
+ *
+ * Returns: x86_decode_lite_t
+ *  - On failure, length of -1.
+ *  - On success, length > 0 and REL_TYPE_*.  For REL_TYPE != NONE, rel points
+ *    at the relative field in the instruction stream.
+ */
+x86_decode_lite_t init_or_livepatch x86_decode_lite(void *ip, void *end)
+{
+    void *start = ip, *rel = NULL;
+    unsigned int opc, type = REL_TYPE_NONE;
+    uint8_t b, d, osize = 4;
+
+#define OPC_TWOBYTE (1 << 8)
+
+    /* Mutates IP, uses END. */
+#define FETCH(ty)                                       \
+    ({                                                  \
+        ty _val;                                        \
+                                                        \
+        if ( (ip + sizeof(ty)) > end )                  \
+            goto overrun;                               \
+        _val = *(ty *)ip;                               \
+        ip += sizeof(ty);                               \
+        _val;                                           \
+    })
+
+    for ( ;; ) /* Prefixes */
+    {
+        switch ( b = FETCH(uint8_t) )
+        {
+        case 0x26: /* ES override */
+        case 0x2e: /* CS override */
+        case 0x36: /* DS override */
+        case 0x3e: /* SS override */
+        case 0x64: /* FS override */
+        case 0x65: /* GS override */
+        case 0xf0: /* Lock */
+        case 0xf2: /* REPNE */
+        case 0xf3: /* REP */

xen/arch/x86/x86_emulate/decode-lite.c line 135

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+            break;
+
+        case 0x66: /* Operand size override */
+            osize = 2;
+            break;
+
+        /* case 0x67: Address size override, not implemented */
+
+        case 0x40 ... 0x4f: /* REX */
+            continue;

Imo at least a comment is needed as to osize here: We don't use 0x66 followed by REX.W, I suppose, when 0x66 determines operand size. It may also be an opcode extension, though, in which case osize set to 2 is (latently) wrong. "Latently" because all you need osize for is to determine Imm's length.

However, what I again think need covering right away are opcodes 0xb8 ... 0xbc in combination with REX.W (osize needing to be 8 there).

Finally - why "continue" here, but "break" further up? Both (right now) have exactly the same effect.

Quoted 9 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +9 -0
+        default:
+            goto prefixes_done;
+        }
+    }
+ prefixes_done:
+
+    /* Fetch the main opcode byte(s) */
+    if ( b == 0x0f )
+    {

xen/arch/x86/x86_emulate/decode-lite.c line 155

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        b = FETCH(uint8_t);
+        opc = OPC_TWOBYTE | b;
+
+        d = twobyte[b];
+    }
+    else
+    {
+        opc = b;
+        d = onebyte[b];
+    }

IOW GPR insns in 0f38 and 0f3a spaces are left out, too. That's perhaps less of an issue than some of the other omissions (and would be more involved to cover when considering that some of them are VEX-encoded), but still not ideal.

Quoted 40 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +40 -0
+    if ( unlikely(!(d & Known)) )
+        goto unknown;
+
+    if ( d & ModRM )
+    {
+        uint8_t modrm = FETCH(uint8_t);
+        uint8_t mod = modrm >> 6;
+        uint8_t reg = (modrm >> 3) & 7;
+        uint8_t rm = modrm & 7;
+
+        /* ModRM/SIB decode */
+        if ( mod == 0 && rm == 5 ) /* RIP relative */
+        {
+            rel = ip;
+            type = REL_TYPE_d32;
+            FETCH(uint32_t);
+        }
+        else if ( mod != 3 && rm == 4 ) /* SIB */
+            FETCH(uint8_t);
+
+        if ( mod == 1 ) /* disp8 */
+            FETCH(uint8_t);
+        else if ( mod == 2 ) /* disp32 */
+            FETCH(uint32_t);
+
+        /* ModRM based decode adjustements */
+        switch ( opc )
+        {
+        case 0xf6: /* Grp3 TEST(s) have extra Imm8 */
+            if ( reg == 0 || reg == 1 )
+                d |= Imm8;
+            break;
+        case 0xf7: /* Grp3 TEST(s) have extra Imm */
+            if ( reg == 0 || reg == 1 )
+                d |= Imm;
+            break;
+        }
+    }
+
+    if ( d & Branch )

xen/arch/x86/x86_emulate/decode-lite.c line 206

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+    {
+        /*
+         * Don't tolerate 66-prefixed call/jmp in alternatives.  Some are
+         * genuinely decoded differently between Intel and AMD CPUs.
+         */
+        if ( osize != 4 )
+            goto bad_osize;
+
+        rel = ip;
+        type = (d & Imm8) ? REL_TYPE_d8 : REL_TYPE_d32;

Perhaps ASSERT(!rel) and/or ASSERT(!type) ahead of these?

Quoted 13 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +13 -0
+    }
+
+    if ( d & (Imm|Imm8) )
+    {
+        if ( d & Imm8 )
+            osize = 1;
+
+        switch ( osize )
+        {
+        case 1: FETCH(uint8_t);  break;
+        case 2: FETCH(uint16_t); break;
+        case 4: FETCH(uint32_t); break;
+        default: goto bad_osize;

xen/arch/x86/x86_emulate/decode-lite.c line 229

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+        }
+    }
+
+    return (x86_decode_lite_t){ ip - start, type, rel };
+
+ bad_osize:
+    printk(XENLOG_ERR "%s() Bad osize %u in %*ph\n",
+           __func__, osize,
+           (int)(unsigned long)(end - start), start);
+    return (x86_decode_lite_t){ -1, REL_TYPE_NONE, NULL };

Maybe limit opcode quoting to ip - start here?

xen/arch/x86/x86_emulate/private.h line 14

Quoted 9 lines
xen/arch/x86/x86_emulate/private.h +2 -0
@@ -9,7 +9,9 @@
 #ifdef __XEN__
 
 # include <xen/bug.h>
+# include <xen/init.h>
 # include <xen/kernel.h>
+# include <xen/livepatch.h>

Are both of these really needed here, rather than just in decode-lite.c?

Quoted 4 lines
xen/arch/x86/x86_emulate/x86_emulate.h +0 -0
@@ -842,4 +842,21 @@ static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt)
     ctxt->event = (struct x86_event){};

xen/arch/x86/x86_emulate/x86_emulate.h static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt) · line 852

Quoted 10 lines
xen/arch/x86/x86_emulate/x86_emulate.h +8 -0
 }
 
+/*
+ * x86_decode_lite().  Very minimal decoder for managing alternatives.
+ *
+ * @len is -1 on error, or positive on success.  If the instruction has a
+ * relative field, REL_TYPE_* gives the size, and @rel points at the field.
+ */
+typedef struct {
+    int8_t len;

Can't 0 be "error", thus permitting the field to be uint8_t?

xen/arch/x86/x86_emulate/x86_emulate.h static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt) · line 856

Quoted 4 lines
xen/arch/x86/x86_emulate/x86_emulate.h +4 -0
+    uint8_t rel_type;
+#define REL_TYPE_NONE 0
+#define REL_TYPE_d8   1
+#define REL_TYPE_d32  2

Why not call the field rel_size and truly pass back the size?

xen/arch/x86/x86_emulate/x86_emulate.h static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt) · line 857

Quoted 1 line
xen/arch/x86/x86_emulate/x86_emulate.h +1 -0
+    void *rel;

While I understand the goal of omitting const here and ...

xen/arch/x86/x86_emulate/x86_emulate.h static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt) · line 860

Quoted 3 lines
xen/arch/x86/x86_emulate/x86_emulate.h +3 -0
+} x86_decode_lite_t;
+
+x86_decode_lite_t x86_decode_lite(void *ip, void *end);

... here, I still find this fragile / misleading (the function itself, after all, only ever fetches from memory). Even with the goal in mind, surely at least "end" can be pointer-to-const?

The (struct) return type would also be easier for the compiler to deal with if it didn't have a pointer field (and hence needs to be 128-bit). How about returning an offset relative to "start"? That would then allow proper constifying of both function parameters as well.

Jan

#3 lore raw

Re: [PATCH 1/6] x86: Introduce x86_decode_lite()

Quoted 103 lines · Jan Beulich
Quoted 27 lines · Andrew Cooper
xen/arch/x86/x86_emulate/decode-lite.c new file +24 -0
@@ -0,0 +1,245 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#include "private.h"
+
+#define Imm8   (1 << 0)
+#define Imm    (1 << 1)
+#define Branch (1 << 5) /* ... that we care about */
+/*      ModRM  (1 << 6) */
+#define Known  (1 << 7)
+
+#define ALU_OPS                                 \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \
+    (Known|Imm8),                               \
+    (Known|Imm)
+
+static const uint8_t init_or_livepatch_const onebyte[256] = {
+    [0x00] = ALU_OPS, /* ADD */ [0x08] = ALU_OPS, /* OR  */
+    [0x10] = ALU_OPS, /* ADC */ [0x18] = ALU_OPS, /* SBB */
+    [0x20] = ALU_OPS, /* AND */ [0x28] = ALU_OPS, /* SUB */
+    [0x30] = ALU_OPS, /* XOR */ [0x38] = ALU_OPS, /* CMP */
+

xen/arch/x86/x86_emulate/decode-lite.c line 34

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+    [0x50 ... 0x5f] = (Known),             /* PUSH/POP %reg */
+
+    [0x70 ... 0x7f] = (Known|Branch|Imm8), /* Jcc disp8 */
+    [0x80]          = (Known|ModRM|Imm8),
+    [0x81]          = (Known|ModRM|Imm),
+
+    [0x83]          = (Known|ModRM|Imm8),
+    [0x84 ... 0x8e] = (Known|ModRM),       /* TEST/XCHG/MOV/MOV-SREG/LEA r/rm */
+
+    [0xb0 ... 0xb7] = (Known|Imm8),        /* MOV $imm8, %reg */

I'm surprised you get away without at least NOP also marked as known. Imo the whole 0x90 row should be marked so.

Similarly I'm not convinced that leaving the 0xA0 row unpopulated is a good idea. It's at best a trap set up for somebody to fall into rather sooner than later.

xen/arch/x86/x86_emulate/decode-lite.c line 38

Quoted 4 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +4 -0
+    [0xb8 ... 0xbf] = (Known|Imm),         /* MOV $imm32, %reg */
+
+    [0xcc]          = (Known),             /* INT3 */
+    [0xcd]          = (Known|Imm8),        /* INT $imm8 */

Like above, what about in particular any of the shifts/rotates and the MOV that's in the 0xC0 row?

While the last sentence in the description is likely meant to cover that, I think the description wants to go further as to any pretty common but omitted insns. Already "x86: re-work memset()" and "x86: re- work memcpy()" (v2 pending for, soon, 3 years) would make it necessary to touch this table, thus increasing complexity of those changes to an area they shouldn't be concerned about at all.

xen/arch/x86/x86_emulate/decode-lite.c line 41

Quoted 2 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +2 -0
+    [0xe8 ... 0xe9] = (Known|Branch|Imm),  /* CALL/JMP disp32 */
+    [0xeb]          = (Known|Branch|Imm8), /* JMP disp8 */

0xe0 ... 0xe7 and 0xec ... 0xef would imo also better be covered, as they easily can be (much like you also cover e.g. CMC despite it appearing pretty unlikely that we use that insn anywhere).

xen/arch/x86/x86_emulate/decode-lite.c line 51

Quoted 9 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +9 -0
+    [0xf1]          = (Known),             /* ICEBP */
+    [0xf4]          = (Known),             /* HLT */
+    [0xf5]          = (Known),             /* CMC */
+    [0xf6 ... 0xf7] = (Known|ModRM),       /* Grp3 */
+    [0xf8 ... 0xfd] = (Known),             /* CLC ... STD */
+    [0xfe ... 0xff] = (Known|ModRM),       /* Grp4 */
+};
+static const uint8_t init_or_livepatch_const twobyte[256] = {
+    [0x00 ... 0x01] = (Known|ModRM),       /* Grp6/Grp7 */

LAR / LSL? CLTS? WBINVD? UD2?

xen/arch/x86/x86_emulate/decode-lite.c line 57

Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +5 -0
+    [0x18 ... 0x1f] = (Known|ModRM),       /* Grp16 (Hint Nop) */
+
+    [0x20 ... 0x23] = (Known|ModRM),       /* MOV CR/DR */
+
+    [0x30 ... 0x34] = (Known),             /* WRMSR ... RDPMC */

0x34 is SYSENTER, isn't it?

xen/arch/x86/x86_emulate/decode-lite.c line 60

Quoted 3 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +3 -0
+    [0x40 ... 0x4f] = (Known|ModRM),       /* CMOVcc */
+
+    [0x80 ... 0x8f] = (Known|Branch|Imm),  /* Jcc disp32 */

What about things like VMREAD/VMWRITE?

xen/arch/x86/x86_emulate/decode-lite.c line 61

Quoted 1 line
xen/arch/x86/x86_emulate/decode-lite.c new file +1 -0
+    [0x90 ... 0x9f] = (Known|ModRM),       /* SETcc */

PUSH/POP fs/gs? CPUID?

xen/arch/x86/x86_emulate/decode-lite.c line 63

Quoted 1 line
xen/arch/x86/x86_emulate/decode-lite.c new file +1 -0
+    [0xab]          = (Known|ModRM),       /* BTS */

BTS (and BTC below) but not BT and BTR?

xen/arch/x86/x86_emulate/decode-lite.c line 65

Quoted 2 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +2 -0
+    [0xac]          = (Known|ModRM|Imm8),  /* SHRD $imm8 */
+    [0xad ... 0xaf] = (Known|ModRM),       /* SHRD %cl / Grp15 / IMUL */

SHRD but not SHLD?

CMPXCHG?

xen/arch/x86/x86_emulate/decode-lite.c line 69

Quoted 3 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +3 -0
+    [0xb8 ... 0xb9] = (Known|ModRM),       /* POPCNT/Grp10 (UD1) */
+    [0xba]          = (Known|ModRM|Imm8),  /* Grp8 */
+    [0xbb ... 0xbf] = (Known|ModRM),       /* BSR/BSF/BSR/MOVSX */
Quoted 6 lines

Nit (comment only): 0xbb is BTC.

MOVSX but not MOVZX and also not MOVSXD (in the 1-byte table)?

xen/arch/x86/x86_emulate/decode-lite.c line 65

Quoted 1 line
xen/arch/x86/x86_emulate/decode-lite.c new file +1 -0
+};

XADD, MOVNTI, and the whole 0xc7-based group?

As you may have guessed, I filled in the opcode table until I could parse all replacements.

When, at the end of this, I didn't need the osize=8 movs, I took the decoding complexity back out.

In an ideal world I would have finished the userspace harness too, but I ran out of time.  Where it's just populating the table, that's fine. Where it complicates the decoding logic, that needs more thought.

Quoted 10 lines

xen/arch/x86/x86_emulate/decode-lite.c line 81

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+/*
+ * Bare minimum x86 instruction decoder to parse the alternative replacement
+ * instructions and locate the IP-relative references that may need updating.
+ *
+ * These are:
+ *  - disp8/32 from near branches
+ *  - RIP-relative memory references
+ *
+ * The following simplifications are used:
+ *  - All code is 64bit, and the instruction stream is safe to read.
Quoted 2 lines

This, in particular, is imo important to state already ahead of the tables above, to clarify why e.g. row 0x40 is unpopulated.

I initially had that, but took it out.  I can put it back in.

Quoted 61 lines
Quoted 45 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +44 -0
+ *  - The 67 prefix is not implemented, so the address size is only 64bit.
+ *
+ * Inputs:
+ *  @ip  The position to start decoding from.
+ *  @end End of the replacement block.  Exceeding this is considered an error.
+ *
+ * Returns: x86_decode_lite_t
+ *  - On failure, length of -1.
+ *  - On success, length > 0 and REL_TYPE_*.  For REL_TYPE != NONE, rel points
+ *    at the relative field in the instruction stream.
+ */
+x86_decode_lite_t init_or_livepatch x86_decode_lite(void *ip, void *end)
+{
+    void *start = ip, *rel = NULL;
+    unsigned int opc, type = REL_TYPE_NONE;
+    uint8_t b, d, osize = 4;
+
+#define OPC_TWOBYTE (1 << 8)
+
+    /* Mutates IP, uses END. */
+#define FETCH(ty)                                       \
+    ({                                                  \
+        ty _val;                                        \
+                                                        \
+        if ( (ip + sizeof(ty)) > end )                  \
+            goto overrun;                               \
+        _val = *(ty *)ip;                               \
+        ip += sizeof(ty);                               \
+        _val;                                           \
+    })
+
+    for ( ;; ) /* Prefixes */
+    {
+        switch ( b = FETCH(uint8_t) )
+        {
+        case 0x26: /* ES override */
+        case 0x2e: /* CS override */
+        case 0x36: /* DS override */
+        case 0x3e: /* SS override */
+        case 0x64: /* FS override */
+        case 0x65: /* GS override */
+        case 0xf0: /* Lock */
+        case 0xf2: /* REPNE */
+        case 0xf3: /* REP */

xen/arch/x86/x86_emulate/decode-lite.c line 135

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+            break;
+
+        case 0x66: /* Operand size override */
+            osize = 2;
+            break;
+
+        /* case 0x67: Address size override, not implemented */
+
+        case 0x40 ... 0x4f: /* REX */
+            continue;

Imo at least a comment is needed as to osize here: We don't use 0x66 followed by REX.W, I suppose, when 0x66 determines operand size. It may also be an opcode extension, though, in which case osize set to 2 is (latently) wrong. "Latently" because all you need osize for is to determine Imm's length.

Quoted 5 lines

However, what I again think need covering right away are opcodes 0xb8 ... 0xbc in combination with REX.W (osize needing to be 8 there).

Finally - why "continue" here, but "break" further up? Both (right now) have exactly the same effect.

They're not the same when ...

Quoted 4 lines

xen/arch/x86/x86_emulate/decode-lite.c line 139

Quoted 4 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +3 -0
+        default:
+            goto prefixes_done;
+        }

... this has "cancel the REX prefix" in it.

I started by decoding REX, only to find I didn't need it, so took it back out.

Quoted 12 lines
Quoted 12 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +12 -0
+    }
+ prefixes_done:
+
+    /* Fetch the main opcode byte(s) */
+    if ( b == 0x0f )
+    {
+        b = FETCH(uint8_t);
+        opc = OPC_TWOBYTE | b;
+
+        d = twobyte[b];
+    }
+    else
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 155

Quoted 4 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +4 -0
+    {
+        opc = b;
+        d = onebyte[b];
+    }

IOW GPR insns in 0f38 and 0f3a spaces are left out, too. That's perhaps less of an issue than some of the other omissions (and would be more involved to cover when considering that some of them are VEX-encoded), but still not ideal.

They can all be added if needed, but right now they're not.

This decoder only need to cover instructions likely to be used in alternatives, and that pretty limits us to simple integer operations.

Any extra complexity here makes the function less and less "lite".

Quoted 16 lines
Quoted 16 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +16 -0
+    }
+
+    if ( d & (Imm|Imm8) )
+    {
+        if ( d & Imm8 )
+            osize = 1;
+
+        switch ( osize )
+        {
+        case 1: FETCH(uint8_t);  break;
+        case 2: FETCH(uint16_t); break;
+        case 4: FETCH(uint32_t); break;
+        default: goto bad_osize;
+        }
+    }
+
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 229

Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+    return (x86_decode_lite_t){ ip - start, type, rel };
+
+ bad_osize:
+    printk(XENLOG_ERR "%s() Bad osize %u in %*ph\n",
+           __func__, osize,
+           (int)(unsigned long)(end - start), start);
+    return (x86_decode_lite_t){ -1, REL_TYPE_NONE, NULL };

Maybe limit opcode quoting to ip - start here?

In the case that we've taken the bad_osize path, we've not decoded the full instruction.  The bytes beyond ip are useful for diagnostics.

Quoted 11 lines

xen/arch/x86/x86_emulate/private.h line 14

Quoted 10 lines
xen/arch/x86/x86_emulate/private.h +2 -0
@@ -9,7 +9,9 @@
 #ifdef __XEN__
 
 # include <xen/bug.h>
+# include <xen/init.h>
 # include <xen/kernel.h>
+# include <xen/livepatch.h>

Are both of these really needed here, rather than just in decode-lite.c?

Yes, for the userpsace harness.

Quoted 7 lines
Quoted 7 lines
xen/arch/x86/x86_emulate/x86_emulate.h +0 -0
@@ -842,4 +842,21 @@ static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt)
     ctxt->event = (struct x86_event){};
 }
 
Quoted 9 lines

xen/arch/x86/x86_emulate/x86_emulate.h static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt) · line 852

Quoted 8 lines
xen/arch/x86/x86_emulate/x86_emulate.h +8 -0
+/*
+ * x86_decode_lite().  Very minimal decoder for managing alternatives.
+ *
+ * @len is -1 on error, or positive on success.  If the instruction has a
+ * relative field, REL_TYPE_* gives the size, and @rel points at the field.
+ */
+typedef struct {
+    int8_t len;

Can't 0 be "error", thus permitting the field to be uint8_t?

Hmm, yes I think it can.  -1 is a leftover from an older scheme.

Quoted 6 lines

xen/arch/x86/x86_emulate/x86_emulate.h static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt) · line 856

Quoted 5 lines
xen/arch/x86/x86_emulate/x86_emulate.h +4 -0
+    uint8_t rel_type;
+#define REL_TYPE_NONE 0
+#define REL_TYPE_d8   1
+#define REL_TYPE_d32  2

Why not call the field rel_size and truly pass back the size?

Ok.

Quoted 11 lines

xen/arch/x86/x86_emulate/x86_emulate.h static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt) · line 857

Quoted 2 lines
xen/arch/x86/x86_emulate/x86_emulate.h +1 -0
+    void *rel;

While I understand the goal of omitting const here and ...

xen/arch/x86/x86_emulate/x86_emulate.h static inline void x86_emul_reset_event(struct x86_emulate_ctxt *ctxt) · line 860

Quoted 3 lines
xen/arch/x86/x86_emulate/x86_emulate.h +3 -0
+} x86_decode_lite_t;
+
+x86_decode_lite_t x86_decode_lite(void *ip, void *end);

... here, I still find this fragile / misleading (the function itself, after all, only ever fetches from memory). Even with the goal in mind, surely at least "end" can be pointer-to-const?

Quoted 4 lines

The (struct) return type would also be easier for the compiler to deal with if it didn't have a pointer field (and hence needs to be 128-bit). How about returning an offset relative to "start"? That would then allow proper constifying of both function parameters as well.

Quite the contrary.

I did initially pack it all into a single GPR, but both the written C and code generation of this form is better.

This is what the code generation looks like:

<xdl>:
55                      push   %rbp
48 89 e5                mov    %rsp,%rbp
e8 77 fd ff ff          callq  ffff82d04033c580 <x86_decode_lite> 5d                      pop    %rbp
88 05 01 77 2f 00       mov    %al,0x2f7701(%rip)        # <xdl_len> 0f b6 c4                movzbl %ah,%eax
88 05 f7 76 2f 00       mov    %al,0x2f76f7(%rip)        # <xdl_type> 48 89 15 e8 76 2f 00    mov    %rdx,0x2f76e8(%rip)       # <xdl_rel> c3                      retq

and keeping rel as a full pointer simplifies both sides of the function.

(Again, I have no idea why GCC is setting up a frame pointer in this case .  It's not needed given our preferred alignment setting.)

~Andrew

#4 lore raw

Re: [PATCH 1/6] x86: Introduce x86_decode_lite()

Quoted 108 lines · Andrew Cooper
Quoted 107 lines · Jan Beulich
Quoted 27 lines · Andrew Cooper
xen/arch/x86/x86_emulate/decode-lite.c new file +24 -0
@@ -0,0 +1,245 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#include "private.h"
+
+#define Imm8   (1 << 0)
+#define Imm    (1 << 1)
+#define Branch (1 << 5) /* ... that we care about */
+/*      ModRM  (1 << 6) */
+#define Known  (1 << 7)
+
+#define ALU_OPS                                 \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \
+    (Known|ModRM),                              \
+    (Known|Imm8),                               \
+    (Known|Imm)
+
+static const uint8_t init_or_livepatch_const onebyte[256] = {
+    [0x00] = ALU_OPS, /* ADD */ [0x08] = ALU_OPS, /* OR  */
+    [0x10] = ALU_OPS, /* ADC */ [0x18] = ALU_OPS, /* SBB */
+    [0x20] = ALU_OPS, /* AND */ [0x28] = ALU_OPS, /* SUB */
+    [0x30] = ALU_OPS, /* XOR */ [0x38] = ALU_OPS, /* CMP */
+

xen/arch/x86/x86_emulate/decode-lite.c line 34

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+    [0x50 ... 0x5f] = (Known),             /* PUSH/POP %reg */
+
+    [0x70 ... 0x7f] = (Known|Branch|Imm8), /* Jcc disp8 */
+    [0x80]          = (Known|ModRM|Imm8),
+    [0x81]          = (Known|ModRM|Imm),
+
+    [0x83]          = (Known|ModRM|Imm8),
+    [0x84 ... 0x8e] = (Known|ModRM),       /* TEST/XCHG/MOV/MOV-SREG/LEA r/rm */
+
+    [0xb0 ... 0xb7] = (Known|Imm8),        /* MOV $imm8, %reg */

I'm surprised you get away without at least NOP also marked as known. Imo the whole 0x90 row should be marked so.

Similarly I'm not convinced that leaving the 0xA0 row unpopulated is a good idea. It's at best a trap set up for somebody to fall into rather sooner than later.

xen/arch/x86/x86_emulate/decode-lite.c line 38

Quoted 4 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +4 -0
+    [0xb8 ... 0xbf] = (Known|Imm),         /* MOV $imm32, %reg */
+
+    [0xcc]          = (Known),             /* INT3 */
+    [0xcd]          = (Known|Imm8),        /* INT $imm8 */

Like above, what about in particular any of the shifts/rotates and the MOV that's in the 0xC0 row?

While the last sentence in the description is likely meant to cover that, I think the description wants to go further as to any pretty common but omitted insns. Already "x86: re-work memset()" and "x86: re- work memcpy()" (v2 pending for, soon, 3 years) would make it necessary to touch this table, thus increasing complexity of those changes to an area they shouldn't be concerned about at all.

xen/arch/x86/x86_emulate/decode-lite.c line 41

Quoted 2 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +2 -0
+    [0xe8 ... 0xe9] = (Known|Branch|Imm),  /* CALL/JMP disp32 */
+    [0xeb]          = (Known|Branch|Imm8), /* JMP disp8 */

0xe0 ... 0xe7 and 0xec ... 0xef would imo also better be covered, as they easily can be (much like you also cover e.g. CMC despite it appearing pretty unlikely that we use that insn anywhere).

xen/arch/x86/x86_emulate/decode-lite.c line 51

Quoted 9 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +9 -0
+    [0xf1]          = (Known),             /* ICEBP */
+    [0xf4]          = (Known),             /* HLT */
+    [0xf5]          = (Known),             /* CMC */
+    [0xf6 ... 0xf7] = (Known|ModRM),       /* Grp3 */
+    [0xf8 ... 0xfd] = (Known),             /* CLC ... STD */
+    [0xfe ... 0xff] = (Known|ModRM),       /* Grp4 */
+};
+static const uint8_t init_or_livepatch_const twobyte[256] = {
+    [0x00 ... 0x01] = (Known|ModRM),       /* Grp6/Grp7 */

LAR / LSL? CLTS? WBINVD? UD2?

xen/arch/x86/x86_emulate/decode-lite.c line 57

Quoted 5 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +5 -0
+    [0x18 ... 0x1f] = (Known|ModRM),       /* Grp16 (Hint Nop) */
+
+    [0x20 ... 0x23] = (Known|ModRM),       /* MOV CR/DR */
+
+    [0x30 ... 0x34] = (Known),             /* WRMSR ... RDPMC */

0x34 is SYSENTER, isn't it?

xen/arch/x86/x86_emulate/decode-lite.c line 60

Quoted 3 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +3 -0
+    [0x40 ... 0x4f] = (Known|ModRM),       /* CMOVcc */
+
+    [0x80 ... 0x8f] = (Known|Branch|Imm),  /* Jcc disp32 */

What about things like VMREAD/VMWRITE?

xen/arch/x86/x86_emulate/decode-lite.c line 61

Quoted 1 line
xen/arch/x86/x86_emulate/decode-lite.c new file +1 -0
+    [0x90 ... 0x9f] = (Known|ModRM),       /* SETcc */

PUSH/POP fs/gs? CPUID?

xen/arch/x86/x86_emulate/decode-lite.c line 63

Quoted 1 line
xen/arch/x86/x86_emulate/decode-lite.c new file +1 -0
+    [0xab]          = (Known|ModRM),       /* BTS */

BTS (and BTC below) but not BT and BTR?

xen/arch/x86/x86_emulate/decode-lite.c line 65

Quoted 2 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +2 -0
+    [0xac]          = (Known|ModRM|Imm8),  /* SHRD $imm8 */
+    [0xad ... 0xaf] = (Known|ModRM),       /* SHRD %cl / Grp15 / IMUL */

SHRD but not SHLD?

CMPXCHG?

xen/arch/x86/x86_emulate/decode-lite.c line 69

Quoted 3 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +3 -0
+    [0xb8 ... 0xb9] = (Known|ModRM),       /* POPCNT/Grp10 (UD1) */
+    [0xba]          = (Known|ModRM|Imm8),  /* Grp8 */
+    [0xbb ... 0xbf] = (Known|ModRM),       /* BSR/BSF/BSR/MOVSX */

Nit (comment only): 0xbb is BTC.

MOVSX but not MOVZX and also not MOVSXD (in the 1-byte table)?

Quoted 8 lines
Quoted 2 lines

xen/arch/x86/x86_emulate/decode-lite.c line 65

Quoted 1 line
xen/arch/x86/x86_emulate/decode-lite.c new file +1 -0
+};

XADD, MOVNTI, and the whole 0xc7-based group?

As you may have guessed, I filled in the opcode table until I could parse all replacements.

When, at the end of this, I didn't need the osize=8 movs, I took the decoding complexity back out.

While I can see that this requiring extra logic makes it desirable to leave out, it'll easily be a surprise when, eventually, someone adds an alternative using such. Please may I ask that for any "simple" integer insn left out, that be clearly mentioned in or ahead of the tables?

Quoted 69 lines
Quoted 60 lines
Quoted 44 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +44 -0
+ *  - The 67 prefix is not implemented, so the address size is only 64bit.
+ *
+ * Inputs:
+ *  @ip  The position to start decoding from.
+ *  @end End of the replacement block.  Exceeding this is considered an error.
+ *
+ * Returns: x86_decode_lite_t
+ *  - On failure, length of -1.
+ *  - On success, length > 0 and REL_TYPE_*.  For REL_TYPE != NONE, rel points
+ *    at the relative field in the instruction stream.
+ */
+x86_decode_lite_t init_or_livepatch x86_decode_lite(void *ip, void *end)
+{
+    void *start = ip, *rel = NULL;
+    unsigned int opc, type = REL_TYPE_NONE;
+    uint8_t b, d, osize = 4;
+
+#define OPC_TWOBYTE (1 << 8)
+
+    /* Mutates IP, uses END. */
+#define FETCH(ty)                                       \
+    ({                                                  \
+        ty _val;                                        \
+                                                        \
+        if ( (ip + sizeof(ty)) > end )                  \
+            goto overrun;                               \
+        _val = *(ty *)ip;                               \
+        ip += sizeof(ty);                               \
+        _val;                                           \
+    })
+
+    for ( ;; ) /* Prefixes */
+    {
+        switch ( b = FETCH(uint8_t) )
+        {
+        case 0x26: /* ES override */
+        case 0x2e: /* CS override */
+        case 0x36: /* DS override */
+        case 0x3e: /* SS override */
+        case 0x64: /* FS override */
+        case 0x65: /* GS override */
+        case 0xf0: /* Lock */
+        case 0xf2: /* REPNE */
+        case 0xf3: /* REP */

xen/arch/x86/x86_emulate/decode-lite.c line 135

Quoted 10 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +10 -0
+            break;
+
+        case 0x66: /* Operand size override */
+            osize = 2;
+            break;
+
+        /* case 0x67: Address size override, not implemented */
+
+        case 0x40 ... 0x4f: /* REX */
+            continue;

Imo at least a comment is needed as to osize here: We don't use 0x66 followed by REX.W, I suppose, when 0x66 determines operand size. It may also be an opcode extension, though, in which case osize set to 2 is (latently) wrong. "Latently" because all you need osize for is to determine Imm's length.

Quoted 5 lines

However, what I again think need covering right away are opcodes 0xb8 ... 0xbc in combination with REX.W (osize needing to be 8 there).

Finally - why "continue" here, but "break" further up? Both (right now) have exactly the same effect.

They're not the same when ...

Quoted 1 line
Quoted 6 lines
Quoted 3 lines

xen/arch/x86/x86_emulate/decode-lite.c line 139

Quoted 3 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +3 -0
+        default:
+            goto prefixes_done;
+        }

... this has "cancel the REX prefix" in it.

Of course.

Quoted 2 lines

I started by decoding REX, only to find I didn't need it, so took it back out.

At which point imo they want to all be "break". Once the cancellation needs adding, where necessary "break" can be switched to "continue". (Interestingly REX2 is different from REX in this regard, and hence wouldn't need such cancellation, if ever we end up patching APX insns.)

Quoted 21 lines
Quoted 12 lines
Quoted 12 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +12 -0
+    }
+ prefixes_done:
+
+    /* Fetch the main opcode byte(s) */
+    if ( b == 0x0f )
+    {
+        b = FETCH(uint8_t);
+        opc = OPC_TWOBYTE | b;
+
+        d = twobyte[b];
+    }
+    else
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 155

Quoted 4 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +4 -0
+    {
+        opc = b;
+        d = onebyte[b];
+    }

IOW GPR insns in 0f38 and 0f3a spaces are left out, too. That's perhaps less of an issue than some of the other omissions (and would be more involved to cover when considering that some of them are VEX-encoded), but still not ideal.

Quoted 6 lines

They can all be added if needed, but right now they're not.

This decoder only need to cover instructions likely to be used in alternatives, and that pretty limits us to simple integer operations.

Any extra complexity here makes the function less and less "lite".

I understand this. At the same time to me anything pending and anything previously submitted but disliked for whatever reason wants at least considering to cover. In that context please recall that once there was BMI2 patching (that you didn't like) ...

Quoted 25 lines
Quoted 16 lines
Quoted 16 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +16 -0
+    }
+
+    if ( d & (Imm|Imm8) )
+    {
+        if ( d & Imm8 )
+            osize = 1;
+
+        switch ( osize )
+        {
+        case 1: FETCH(uint8_t);  break;
+        case 2: FETCH(uint16_t); break;
+        case 4: FETCH(uint32_t); break;
+        default: goto bad_osize;
+        }
+    }
+
Quoted 8 lines

xen/arch/x86/x86_emulate/decode-lite.c line 229

Quoted 7 lines
xen/arch/x86/x86_emulate/decode-lite.c new file +7 -0
+    return (x86_decode_lite_t){ ip - start, type, rel };
+
+ bad_osize:
+    printk(XENLOG_ERR "%s() Bad osize %u in %*ph\n",
+           __func__, osize,
+           (int)(unsigned long)(end - start), start);
+    return (x86_decode_lite_t){ -1, REL_TYPE_NONE, NULL };

Maybe limit opcode quoting to ip - start here?

Quoted 2 lines

In the case that we've taken the bad_osize path, we've not decoded the full instruction.  The bytes beyond ip are useful for diagnostics.

Hmm. The reason for the reported failure lies within the [start,ip) range. Yet I agree that would not be a complete insn. Otoh what is being patched may be a meaningfully long series of insns, which aren't useful to all log. If you think including the immediate (the value of which is of no interest) is relevant, may I then please ask that you bound logging at the insn size limit of 15?

Quoted 5 lines
Quoted 5 lines
Quoted 5 lines
xen/arch/x86/x86_emulate/private.h +0 -0
@@ -9,7 +9,9 @@
 #ifdef __XEN__
 
Quoted 7 lines
Quoted 5 lines

xen/arch/x86/x86_emulate/private.h line 14

Quoted 4 lines
xen/arch/x86/x86_emulate/private.h +2 -0
 # include <xen/bug.h>
+# include <xen/init.h>
 # include <xen/kernel.h>
+# include <xen/livepatch.h>

Are both of these really needed here, rather than just in decode-lite.c?

Yes, for the userpsace harness.

The user space harness shouldn't include any Xen headers. Patch context (the #ifdef at the top) even shows that this Xen-only code.

Quoted 22 lines
Quoted 10 lines

xen/arch/x86/x86_emulate/private.h line 15

Quoted 1 line
xen/arch/x86/x86_emulate/private.h +1 -0
+    void *rel;

While I understand the goal of omitting const here and ...

xen/arch/x86/x86_emulate/private.h

Quoted 3 lines
xen/arch/x86/x86_emulate/private.h +3 -0
+} x86_decode_lite_t;
+
+x86_decode_lite_t x86_decode_lite(void *ip, void *end);

... here, I still find this fragile / misleading (the function itself, after all, only ever fetches from memory). Even with the goal in mind, surely at least "end" can be pointer-to-const?

Quoted 4 lines

The (struct) return type would also be easier for the compiler to deal with if it didn't have a pointer field (and hence needs to be 128-bit). How about returning an offset relative to "start"? That would then allow proper constifying of both function parameters as well.

Quite the contrary.

I did initially pack it all into a single GPR, but both the written C and code generation of this form is better.

This is what the code generation looks like:

Quoted 10 lines

<xdl>:
55                      push   %rbp
48 89 e5                mov    %rsp,%rbp
e8 77 fd ff ff          callq  ffff82d04033c580 <x86_decode_lite> 5d                      pop    %rbp
88 05 01 77 2f 00       mov    %al,0x2f7701(%rip)        # <xdl_len> 0f b6 c4                movzbl %ah,%eax
88 05 f7 76 2f 00       mov    %al,0x2f76f7(%rip)        # <xdl_type> 48 89 15 e8 76 2f 00    mov    %rdx,0x2f76e8(%rip)       # <xdl_rel> c3                      retq

Well, "easier" in my earlier reply wasn't referring to the complexity of generated code. Instead I'm slightly wary of compiler issues with the calling convention for 128-bit struct returns.

Quoted 1 line

and keeping rel as a full pointer simplifies both sides of the function.

Hmm, I can see that being the case. I wonder whether const-correctness doesn't weigh higher, though. But I'm also not going to insist.

Jan

#5 lore raw

PATCH 2/6 x86/alternative: Walk all replacements in debug builds

In reply to Andrew Cooper

In debug builds, walk all alternative replacements with x86_decode_lite().

This checks that we can decode all instructions, and also lets us check that disp8's don't leave the replacement block.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/alternative.c | 49 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 49 insertions(+)
xen/arch/x86/alternative.c +49 -0
index 2e7ba6e0b833..5bd256365def 100644
@@ -15,6 +15,7 @@
 #include <asm/traps.h>
 #include <asm/nmi.h>
 #include <asm/nops.h>
+#include <asm/x86_emulate.h>
 #include <xen/livepatch.h>
 
 #define MAX_PATCH_LEN (255-1)
@@ -464,6 +465,54 @@ static void __init _alternative_instructions(bool force)
 void __init alternative_instructions(void)
 {
     arch_init_ideal_nops();
+
+    /*
+     * Walk all replacement instructions with x86_decode_lite().  This checks
+     * both that we can decode all instructions within the replacement, and
+     * that any near branch with a disp8 stays within the alternative itself.
+     */
+    if ( IS_ENABLED(CONFIG_DEBUG) )
+    {
+        struct alt_instr *a;
+
+        for ( a = __alt_instructions;
+              a < __alt_instructions_end; ++a )
+        {
+            void *repl = ALT_REPL_PTR(a);
+            void *ip = repl, *end = ip + a->repl_len;
+
+            if ( !a->repl_len )
+                continue;
+
+            for ( x86_decode_lite_t res; ip < end; ip += res.len )
+            {
+                res = x86_decode_lite(ip, end);
+
+                if ( res.len <= 0 )
+                {
+                    printk("Alternative for %ps [%*ph]\n",
+                           ALT_ORIG_PTR(a), a->repl_len, repl);
+                    panic("Unable to decode instruction at +%u in alternative\n",
+                          (unsigned int)(unsigned long)(ip - repl));
+                }
+
+                if ( res.rel_type == REL_TYPE_d8 )
+                {
+                    int8_t *d8 = res.rel;
+                    void *target = ip + res.len + *d8;
+
+                    if ( target < repl || target > end )
+                    {
+                        printk("Alternative for %ps [%*ph]\n",
+                               ALT_ORIG_PTR(a), a->repl_len, repl);
+                        panic("'JMP/Jcc disp8' at +%u leaves alternative block\n",
+                              (unsigned int)(unsigned long)(ip - repl));
+                    }
+                }
+            }
+        }
+    }
+
     _alternative_instructions(false);
 }
 
Signature · 1 line
2.30.2
Reviewed-by on v1 2/6
#6 lore raw

Re: [PATCH 2/6] x86/alternative: Walk all replacements in debug builds

Quoted 6 lines · Andrew Cooper

In debug builds, walk all alternative replacements with x86_decode_lite().

This checks that we can decode all instructions, and also lets us check that disp8's don't leave the replacement block.

With pointed-to types consistently constified, technically:

One further suggestion and a question, though:

Quoted 23 lines
xen/arch/x86/alternative.c +19 -0
@@ -464,6 +465,54 @@ static void __init _alternative_instructions(bool force)
 void __init alternative_instructions(void)
 {
     arch_init_ideal_nops();
+
+    /*
+     * Walk all replacement instructions with x86_decode_lite().  This checks
+     * both that we can decode all instructions within the replacement, and
+     * that any near branch with a disp8 stays within the alternative itself.
+     */
+    if ( IS_ENABLED(CONFIG_DEBUG) )
+    {
+        struct alt_instr *a;
+
+        for ( a = __alt_instructions;
+              a < __alt_instructions_end; ++a )
+        {
+            void *repl = ALT_REPL_PTR(a);
+            void *ip = repl, *end = ip + a->repl_len;
+
+            if ( !a->repl_len )
+                continue;
+

xen/arch/x86/alternative.c static void __init _alternative_instructions(bool force) · line 496

Quoted 10 lines
xen/arch/x86/alternative.c +10 -0
+            for ( x86_decode_lite_t res; ip < end; ip += res.len )
+            {
+                res = x86_decode_lite(ip, end);
+
+                if ( res.len <= 0 )
+                {
+                    printk("Alternative for %ps [%*ph]\n",
+                           ALT_ORIG_PTR(a), a->repl_len, repl);
+                    panic("Unable to decode instruction at +%u in alternative\n",
+                          (unsigned int)(unsigned long)(ip - repl));

Instead of the double cast, maybe better use +%lu? And really we ought to have support for %tu, allowing the other cast t be dropped here, too.

Quoted 5 lines
xen/arch/x86/alternative.c +5 -0
+                }
+
+                if ( res.rel_type == REL_TYPE_d8 )
+                {
+                    int8_t *d8 = res.rel;

xen/arch/x86/alternative.c static void __init _alternative_instructions(bool force) · line 511

Quoted 10 lines
xen/arch/x86/alternative.c +10 -0
+                    void *target = ip + res.len + *d8;
+
+                    if ( target < repl || target > end )
+                    {
+                        printk("Alternative for %ps [%*ph]\n",
+                               ALT_ORIG_PTR(a), a->repl_len, repl);
+                        panic("'JMP/Jcc disp8' at +%u leaves alternative block\n",
+                              (unsigned int)(unsigned long)(ip - repl));
+                    }
+                }

Why's Disp8 more important to check than Disp32? A bad CALL in a replacement can't possibly be encoded with Disp8, and both JMP and Jcc are also more likely to be encoded with Disp32 when their target isn't in the same blob (but e.g. in a different section).

Jan

#7 lore raw

Re: [PATCH 2/6] x86/alternative: Walk all replacements in debug builds

Quoted 9 lines · Jan Beulich
Quoted 6 lines · Andrew Cooper

In debug builds, walk all alternative replacements with x86_decode_lite().

This checks that we can decode all instructions, and also lets us check that disp8's don't leave the replacement block.

With pointed-to types consistently constified, technically:

Thanks.

Quoted 11 lines

xen/arch/x86/alternative.c static void __init _alternative_instructions(bool force) · line 474

Quoted 11 lines
xen/arch/x86/alternative.c +7 -0
@@ -464,6 +465,54 @@ static void __init _alternative_instructions(bool force)
 void __init alternative_instructions(void)
 {
     arch_init_ideal_nops();
+
+    /*
+     * Walk all replacement instructions with x86_decode_lite().  This checks
+     * both that we can decode all instructions within the replacement, and
+     * that any near branch with a disp8 stays within the alternative itself.
+     */
+    if ( IS_ENABLED(CONFIG_DEBUG) )

I've swapped this for SELF_TESTS now it exists.

Quoted 11 lines
Quoted 11 lines
xen/arch/x86/alternative.c +11 -0
+                }
+
+                if ( res.rel_type == REL_TYPE_d8 )
+                {
+                    int8_t *d8 = res.rel;
+                    void *target = ip + res.len + *d8;
+
+                    if ( target < repl || target > end )
+                    {
+                        printk("Alternative for %ps [%*ph]\n",
+                               ALT_ORIG_PTR(a), a->repl_len, repl);
Quoted 8 lines

xen/arch/x86/alternative.c static void __init _alternative_instructions(bool force) · line 511

Quoted 4 lines
xen/arch/x86/alternative.c +4 -0
+                        panic("'JMP/Jcc disp8' at +%u leaves alternative block\n",
+                              (unsigned int)(unsigned long)(ip - repl));
+                    }
+                }

Why's Disp8 more important to check than Disp32? A bad CALL in a replacement can't possibly be encoded with Disp8, and both JMP and Jcc are also more likely to be encoded with Disp32 when their target isn't in the same blob (but e.g. in a different section).

Whatever the likelihood of them existing, Disp8's cannot possibly be correct if they cross the boundary of the replacement.  Checking for them has the side effect of running decode_lite() over all replacements.

Disp32's do exist in both external and internal forms (retpoline), and the point of this series is to make all external cases usable. Therefore, there are no invalid cases.

~Andrew

#8 lore raw

Re: [PATCH 2/6] x86/alternative: Walk all replacements in debug builds

Quoted 20 lines · Andrew Cooper
Quoted 14 lines · Jan Beulich

xen/arch/x86/alternative.c static void __init _alternative_instructions(bool force) · line 511

Quoted 13 lines · Andrew Cooper
xen/arch/x86/alternative.c +13 -0
+                if ( res.rel_type == REL_TYPE_d8 )
+                {
+                    int8_t *d8 = res.rel;
+                    void *target = ip + res.len + *d8;
+
+                    if ( target < repl || target > end )
+                    {
+                        printk("Alternative for %ps [%*ph]\n",
+                               ALT_ORIG_PTR(a), a->repl_len, repl);
+                        panic("'JMP/Jcc disp8' at +%u leaves alternative block\n",
+                              (unsigned int)(unsigned long)(ip - repl));
+                    }
+                }
Quoted 4 lines

Why's Disp8 more important to check than Disp32? A bad CALL in a replacement can't possibly be encoded with Disp8, and both JMP and Jcc are also more likely to be encoded with Disp32 when their target isn't in the same blob (but e.g. in a different section).

Quoted 6 lines

Whatever the likelihood of them existing, Disp8's cannot possibly be correct if they cross the boundary of the replacement.  Checking for them has the side effect of running decode_lite() over all replacements.

Disp32's do exist in both external and internal forms (retpoline), and the point of this series is to make all external cases usable.

Okay, fine then.

Quoted 1 line

Therefore, there are no invalid cases.

There definitely are: Any pointing outside of the present replacement block, into another replacement block. Which can in principle happen if a label was used wrongly. Anything pointing outside the block really needs to be covered by logic adjusting the displacement when the alternative is being put in place.

Jan

#9 lore raw

PATCH 3/6 x86/alternative: Intend the relocation logic

In reply to Andrew Cooper

... to make subsequent patches legible.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/alternative.c | 126 +++++++++++++++++++------------------
 1 file changed, 64 insertions(+), 62 deletions(-)
xen/arch/x86/alternative.c +64 -62
index 5bd256365def..2ca4dfd569bc 100644
@@ -244,78 +244,80 @@ static void init_or_livepatch _apply_alternatives(struct alt_instr *start,
 
         memcpy(buf, repl, a->repl_len);
 
-        /* 0xe8/0xe9 are relative branches; fix the offset. */
-        if ( a->repl_len >= 5 && (*buf & 0xfe) == 0xe8 )
         {
-            /*
-             * Detect the special case of indirect-to-direct branch patching:
-             * - replacement is a direct CALL/JMP (opcodes 0xE8/0xE9; already
-             *   checked above),
-             * - replacement's displacement is -5 (pointing back at the very
-             *   insn, which makes no sense in a real replacement insn),
-             * - original is an indirect CALL/JMP (opcodes 0xFF/2 or 0xFF/4)
-             *   using RIP-relative addressing.
-             * Some branch destinations may still be NULL when we come here
-             * the first time. Defer patching of those until the post-presmp-
-             * initcalls re-invocation (with force set to true). If at that
-             * point the branch destination is still NULL, insert "UD2; UD0"
-             * (for ease of recognition) instead of CALL/JMP.
-             */
-            if ( a->cpuid == X86_FEATURE_ALWAYS &&
-                 *(int32_t *)(buf + 1) == -5 &&
-                 a->orig_len >= 6 &&
-                 orig[0] == 0xff &&
-                 orig[1] == (*buf & 1 ? 0x25 : 0x15) )
+            /* 0xe8/0xe9 are relative branches; fix the offset. */
+            if ( a->repl_len >= 5 && (*buf & 0xfe) == 0xe8 )
             {
-                long disp = *(int32_t *)(orig + 2);
-                const uint8_t *dest = *(void **)(orig + 6 + disp);
-
-                if ( dest )
+                /*
+                 * Detect the special case of indirect-to-direct branch patching:
+                 * - replacement is a direct CALL/JMP (opcodes 0xE8/0xE9; already
+                 *   checked above),
+                 * - replacement's displacement is -5 (pointing back at the very
+                 *   insn, which makes no sense in a real replacement insn),
+                 * - original is an indirect CALL/JMP (opcodes 0xFF/2 or 0xFF/4)
+                 *   using RIP-relative addressing.
+                 * Some branch destinations may still be NULL when we come here
+                 * the first time. Defer patching of those until the post-presmp-
+                 * initcalls re-invocation (with force set to true). If at that
+                 * point the branch destination is still NULL, insert "UD2; UD0"
+                 * (for ease of recognition) instead of CALL/JMP.
+                 */
+                if ( a->cpuid == X86_FEATURE_ALWAYS &&
+                     *(int32_t *)(buf + 1) == -5 &&
+                     a->orig_len >= 6 &&
+                     orig[0] == 0xff &&
+                     orig[1] == (*buf & 1 ? 0x25 : 0x15) )
                 {
-                    /*
-                     * When building for CET-IBT, all function pointer targets
-                     * should have an endbr64 instruction.
-                     *
-                     * If this is not the case, leave a warning because
-                     * something is probably wrong with the build.  A CET-IBT
-                     * enabled system might have exploded already.
-                     *
-                     * Otherwise, skip the endbr64 instruction.  This is a
-                     * marginal perf improvement which saves on instruction
-                     * decode bandwidth.
-                     */
-                    if ( IS_ENABLED(CONFIG_XEN_IBT) )
+                    long disp = *(int32_t *)(orig + 2);
+                    const uint8_t *dest = *(void **)(orig + 6 + disp);
+
+                    if ( dest )
                     {
-                        if ( is_endbr64(dest) )
-                            dest += ENDBR64_LEN;
-                        else
-                            printk(XENLOG_WARNING
-                                   "altcall %ps dest %ps has no endbr64\n",
-                                   orig, dest);
+                        /*
+                         * When building for CET-IBT, all function pointer targets
+                         * should have an endbr64 instruction.
+                         *
+                         * If this is not the case, leave a warning because
+                         * something is probably wrong with the build.  A CET-IBT
+                         * enabled system might have exploded already.
+                         *
+                         * Otherwise, skip the endbr64 instruction.  This is a
+                         * marginal perf improvement which saves on instruction
+                         * decode bandwidth.
+                         */
+                        if ( IS_ENABLED(CONFIG_XEN_IBT) )
+                        {
+                            if ( is_endbr64(dest) )
+                                dest += ENDBR64_LEN;
+                            else
+                                printk(XENLOG_WARNING
+                                       "altcall %ps dest %ps has no endbr64\n",
+                                       orig, dest);
+                        }
+
+                        disp = dest - (orig + 5);
+                        ASSERT(disp == (int32_t)disp);
+                        *(int32_t *)(buf + 1) = disp;
                     }
-
-                    disp = dest - (orig + 5);
-                    ASSERT(disp == (int32_t)disp);
-                    *(int32_t *)(buf + 1) = disp;
-                }
-                else if ( force )
-                {
-                    buf[0] = 0x0f;
-                    buf[1] = 0x0b;
-                    buf[2] = 0x0f;
-                    buf[3] = 0xff;
-                    buf[4] = 0xff;
+                    else if ( force )
+                    {
+                        buf[0] = 0x0f;
+                        buf[1] = 0x0b;
+                        buf[2] = 0x0f;
+                        buf[3] = 0xff;
+                        buf[4] = 0xff;
+                    }
+                    else
+                        continue;
                 }
+                else if ( force && system_state < SYS_STATE_active )
+                    ASSERT_UNREACHABLE();
                 else
-                    continue;
+                    *(int32_t *)(buf + 1) += repl - orig;
             }
-            else if ( force && system_state < SYS_STATE_active )
+            else if ( force && system_state < SYS_STATE_active  )
                 ASSERT_UNREACHABLE();
-            else
-                *(int32_t *)(buf + 1) += repl - orig;
         }
-        else if ( force && system_state < SYS_STATE_active  )
-            ASSERT_UNREACHABLE();
 
         a->priv = 1;
 
Signature · 1 line
2.30.2
#10 lore raw

Re: [PATCH 3/6] x86/alternative: Intend the relocation logic

This of course intended to say indent...

~Andrew

Acked-by on v1 3/6
#11 lore raw

Re: [PATCH 3/6] x86/alternative: Intend the relocation logic

In reply to Andrew Cooper
Quoted 5 lines · Andrew Cooper

... to make subsequent patches legible.

No functional change.

even if (perhaps due to changes in the "real" patch) some of this re- indenting wants doing differently, just with ...

Quoted 126 lines
xen/arch/x86/alternative.c +59 -56
@@ -244,78 +244,80 @@ static void init_or_livepatch _apply_alternatives(struct alt_instr *start,
 
         memcpy(buf, repl, a->repl_len);
 
-        /* 0xe8/0xe9 are relative branches; fix the offset. */
-        if ( a->repl_len >= 5 && (*buf & 0xfe) == 0xe8 )
         {
-            /*
-             * Detect the special case of indirect-to-direct branch patching:
-             * - replacement is a direct CALL/JMP (opcodes 0xE8/0xE9; already
-             *   checked above),
-             * - replacement's displacement is -5 (pointing back at the very
-             *   insn, which makes no sense in a real replacement insn),
-             * - original is an indirect CALL/JMP (opcodes 0xFF/2 or 0xFF/4)
-             *   using RIP-relative addressing.
-             * Some branch destinations may still be NULL when we come here
-             * the first time. Defer patching of those until the post-presmp-
-             * initcalls re-invocation (with force set to true). If at that
-             * point the branch destination is still NULL, insert "UD2; UD0"
-             * (for ease of recognition) instead of CALL/JMP.
-             */
-            if ( a->cpuid == X86_FEATURE_ALWAYS &&
-                 *(int32_t *)(buf + 1) == -5 &&
-                 a->orig_len >= 6 &&
-                 orig[0] == 0xff &&
-                 orig[1] == (*buf & 1 ? 0x25 : 0x15) )
+            /* 0xe8/0xe9 are relative branches; fix the offset. */
+            if ( a->repl_len >= 5 && (*buf & 0xfe) == 0xe8 )
             {
-                long disp = *(int32_t *)(orig + 2);
-                const uint8_t *dest = *(void **)(orig + 6 + disp);
-
-                if ( dest )
+                /*
+                 * Detect the special case of indirect-to-direct branch patching:
+                 * - replacement is a direct CALL/JMP (opcodes 0xE8/0xE9; already
+                 *   checked above),
+                 * - replacement's displacement is -5 (pointing back at the very
+                 *   insn, which makes no sense in a real replacement insn),
+                 * - original is an indirect CALL/JMP (opcodes 0xFF/2 or 0xFF/4)
+                 *   using RIP-relative addressing.
+                 * Some branch destinations may still be NULL when we come here
+                 * the first time. Defer patching of those until the post-presmp-
+                 * initcalls re-invocation (with force set to true). If at that
+                 * point the branch destination is still NULL, insert "UD2; UD0"
+                 * (for ease of recognition) instead of CALL/JMP.
+                 */
+                if ( a->cpuid == X86_FEATURE_ALWAYS &&
+                     *(int32_t *)(buf + 1) == -5 &&
+                     a->orig_len >= 6 &&
+                     orig[0] == 0xff &&
+                     orig[1] == (*buf & 1 ? 0x25 : 0x15) )
                 {
-                    /*
-                     * When building for CET-IBT, all function pointer targets
-                     * should have an endbr64 instruction.
-                     *
-                     * If this is not the case, leave a warning because
-                     * something is probably wrong with the build.  A CET-IBT
-                     * enabled system might have exploded already.
-                     *
-                     * Otherwise, skip the endbr64 instruction.  This is a
-                     * marginal perf improvement which saves on instruction
-                     * decode bandwidth.
-                     */
-                    if ( IS_ENABLED(CONFIG_XEN_IBT) )
+                    long disp = *(int32_t *)(orig + 2);
+                    const uint8_t *dest = *(void **)(orig + 6 + disp);
+
+                    if ( dest )
                     {
-                        if ( is_endbr64(dest) )
-                            dest += ENDBR64_LEN;
-                        else
-                            printk(XENLOG_WARNING
-                                   "altcall %ps dest %ps has no endbr64\n",
-                                   orig, dest);
+                        /*
+                         * When building for CET-IBT, all function pointer targets
+                         * should have an endbr64 instruction.
+                         *
+                         * If this is not the case, leave a warning because
+                         * something is probably wrong with the build.  A CET-IBT
+                         * enabled system might have exploded already.
+                         *
+                         * Otherwise, skip the endbr64 instruction.  This is a
+                         * marginal perf improvement which saves on instruction
+                         * decode bandwidth.
+                         */
+                        if ( IS_ENABLED(CONFIG_XEN_IBT) )
+                        {
+                            if ( is_endbr64(dest) )
+                                dest += ENDBR64_LEN;
+                            else
+                                printk(XENLOG_WARNING
+                                       "altcall %ps dest %ps has no endbr64\n",
+                                       orig, dest);
+                        }
+
+                        disp = dest - (orig + 5);
+                        ASSERT(disp == (int32_t)disp);
+                        *(int32_t *)(buf + 1) = disp;
                     }
-
-                    disp = dest - (orig + 5);
-                    ASSERT(disp == (int32_t)disp);
-                    *(int32_t *)(buf + 1) = disp;
-                }
-                else if ( force )
-                {
-                    buf[0] = 0x0f;
-                    buf[1] = 0x0b;
-                    buf[2] = 0x0f;
-                    buf[3] = 0xff;
-                    buf[4] = 0xff;
+                    else if ( force )
+                    {
+                        buf[0] = 0x0f;
+                        buf[1] = 0x0b;
+                        buf[2] = 0x0f;
+                        buf[3] = 0xff;
+                        buf[4] = 0xff;
+                    }
+                    else

xen/arch/x86/alternative.c static void init_or_livepatch _apply_alternatives(struct alt_instr *start, · line 318

Quoted 10 lines
xen/arch/x86/alternative.c +5 -2
+                        continue;
                 }
+                else if ( force && system_state < SYS_STATE_active )
+                    ASSERT_UNREACHABLE();
                 else
-                    continue;
+                    *(int32_t *)(buf + 1) += repl - orig;
             }
-            else if ( force && system_state < SYS_STATE_active )
+            else if ( force && system_state < SYS_STATE_active  )

... this undone.

Jan

#12 lore raw

PATCH 4/6 x86/alternative: Replace a continue with a goto

In reply to Andrew Cooper

A subsequent patch is going to insert a loop, which interferes with the continue in the devirtualisation logic.

Replace it with a goto, and a paragraph explaining why we intentionally avoid setting a->priv = 1.

No functional change.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/alternative.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
xen/arch/x86/alternative.c +10 -1
index 2ca4dfd569bc..c86ea235e865 100644
@@ -308,7 +308,15 @@ static void init_or_livepatch _apply_alternatives(struct alt_instr *start,
                         buf[4] = 0xff;
                     }
                     else
-                        continue;
+                    {
+                        /*
+                         * The function pointer we're wanting to devirtualise
+                         * is still NULL, and we're not sealing yet.  Leave
+                         * the alternative fully un-processed, in order to
+                         * process it the next time around.
+                         */
+                        goto skip_this_alternative;
+                    }
                 }
                 else if ( force && system_state < SYS_STATE_active )
                     ASSERT_UNREACHABLE();
@@ -323,6 +331,7 @@ static void init_or_livepatch _apply_alternatives(struct alt_instr *start,
 
         add_nops(buf + a->repl_len, total_len - a->repl_len);
         text_poke(orig, buf, total_len);
+    skip_this_alternative:;
     }
 
     /*
Signature · 1 line
2.30.2
Acked-by on v1 4/6
#13 lore raw

Re: [PATCH 4/6] x86/alternative: Replace a continue with a goto

Quoted 9 lines · Andrew Cooper

A subsequent patch is going to insert a loop, which interferes with the continue in the devirtualisation logic.

Replace it with a goto, and a paragraph explaining why we intentionally avoid setting a->priv = 1.

No functional change.

#14 lore raw

PATCH 5/6 x86/alternative: Relocate all insn-relative fields

In reply to Andrew Cooper

Right now, relocation of displacements is restricted to finding 0xe8/e9 as the first byte of the replacement, but this is overly restrictive.

Use x86_decode_lite() to find and adjust all insn-relative fields.

As with disp8's not leaving the replacemnet block, some disp32's don't either. e.g. the RSB stuffing loop. These stay unmodified.

For now, leave the altcall devirtualisation alone. These require more care to transform into the new scheme.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/alternative.c | 46 +++++++++++++++++++++++++++++++-------
 1 file changed, 38 insertions(+), 8 deletions(-)
xen/arch/x86/alternative.c +38 -8
index c86ea235e865..4d7dc9418cf0 100644
@@ -244,10 +244,31 @@ static void init_or_livepatch _apply_alternatives(struct alt_instr *start,
 
         memcpy(buf, repl, a->repl_len);
 
+        /* Walk buf[] and adjust any insn-relative operands. */
+        if ( a->repl_len )
         {
-            /* 0xe8/0xe9 are relative branches; fix the offset. */
-            if ( a->repl_len >= 5 && (*buf & 0xfe) == 0xe8 )
+            uint8_t *ip = buf, *end = ip + a->repl_len;
+
+            for ( x86_decode_lite_t res; ip < end; ip += res.len )
             {
+                int32_t *d32;
+                uint8_t *target;
+
+                res = x86_decode_lite(ip, end);
+
+                if ( res.len <= 0 )
+                {
+                    printk("Alternative for %ps [%*ph]\n",
+                           ALT_ORIG_PTR(a), a->repl_len, repl);
+                    printk("Unable to decode instruction in alternative - ignoring.\n");
+                    goto skip_this_alternative;
+                }
+
+                if ( res.rel_type != REL_TYPE_d32 )
+                    continue;
+
+                d32 = res.rel;
+
                 /*
                  * Detect the special case of indirect-to-direct branch patching:
                  * - replacement is a direct CALL/JMP (opcodes 0xE8/0xE9; already
@@ -317,14 +338,23 @@ static void init_or_livepatch _apply_alternatives(struct alt_instr *start,
                          */
                         goto skip_this_alternative;
                     }
+
+                    continue;
                 }
-                else if ( force && system_state < SYS_STATE_active )
-                    ASSERT_UNREACHABLE();
-                else
-                    *(int32_t *)(buf + 1) += repl - orig;
+
+                target = ip + res.len + *d32;
+
+                if ( target >= buf && target <= end )
+                {
+                    /*
+                     * Target doesn't leave the replacement block.  e.g. RSB
+                     * stuffing.  Leave it unmodified.
+                     */
+                    continue;
+                }
+
+                *d32 += repl - orig;
             }
-            else if ( force && system_state < SYS_STATE_active  )
-                ASSERT_UNREACHABLE();
         }
 
         a->priv = 1;
Signature · 1 line
2.30.2
#15 lore raw

Re: [PATCH 5/6] x86/alternative: Relocate all insn-relative fields

Quoted 16 lines · Andrew Cooper
xen/arch/x86/alternative.c +6 -2
@@ -244,10 +244,31 @@ static void init_or_livepatch _apply_alternatives(struct alt_instr *start,
 
         memcpy(buf, repl, a->repl_len);
 
+        /* Walk buf[] and adjust any insn-relative operands. */
+        if ( a->repl_len )
         {
-            /* 0xe8/0xe9 are relative branches; fix the offset. */
-            if ( a->repl_len >= 5 && (*buf & 0xfe) == 0xe8 )
+            uint8_t *ip = buf, *end = ip + a->repl_len;
+
+            for ( x86_decode_lite_t res; ip < end; ip += res.len )
             {
+                int32_t *d32;

xen/arch/x86/alternative.c static void init_or_livepatch _apply_alternatives(struct alt_instr *start, · line 264

Quoted 10 lines
xen/arch/x86/alternative.c +10 -0
+                uint8_t *target;
+
+                res = x86_decode_lite(ip, end);
+
+                if ( res.len <= 0 )
+                {
+                    printk("Alternative for %ps [%*ph]\n",
+                           ALT_ORIG_PTR(a), a->repl_len, repl);
+                    printk("Unable to decode instruction in alternative - ignoring.\n");
+                    goto skip_this_alternative;

Can this really be just a log message? There are cases where patching has to happen for things to operate correctly. Hence if not panic()ing, I'd say we at least want to taint the hypervisor.

xen/arch/x86/alternative.c static void init_or_livepatch _apply_alternatives(struct alt_instr *start, · line 322

Quoted 9 lines
xen/arch/x86/alternative.c +2 -2
@@ -317,14 +338,23 @@ static void init_or_livepatch _apply_alternatives(struct alt_instr *start,
                          */
                         goto skip_this_alternative;
                     }
+
+                    continue;
                 }
-                else if ( force && system_state < SYS_STATE_active )
-                    ASSERT_UNREACHABLE();

This (and the other one below) is related to altcall patching, which you say you mean to leave alone: During the 2nd pass, no un-processed CALL / JMP should occur anymore that aren't altcall related.

Jan

#16 lore raw

Re: [PATCH 5/6] x86/alternative: Relocate all insn-relative fields

Quoted 23 lines · Jan Beulich
Quoted 22 lines · Andrew Cooper
xen/arch/x86/alternative.c +12 -2
@@ -244,10 +244,31 @@ static void init_or_livepatch _apply_alternatives(struct alt_instr *start,
 
         memcpy(buf, repl, a->repl_len);
 
+        /* Walk buf[] and adjust any insn-relative operands. */
+        if ( a->repl_len )
         {
-            /* 0xe8/0xe9 are relative branches; fix the offset. */
-            if ( a->repl_len >= 5 && (*buf & 0xfe) == 0xe8 )
+            uint8_t *ip = buf, *end = ip + a->repl_len;
+
+            for ( x86_decode_lite_t res; ip < end; ip += res.len )
             {
+                int32_t *d32;
+                uint8_t *target;
+
+                res = x86_decode_lite(ip, end);
+
+                if ( res.len <= 0 )
+                {
Quoted 8 lines

xen/arch/x86/alternative.c static void init_or_livepatch _apply_alternatives(struct alt_instr *start, · line 264

Quoted 4 lines
xen/arch/x86/alternative.c +4 -0
+                    printk("Alternative for %ps [%*ph]\n",
+                           ALT_ORIG_PTR(a), a->repl_len, repl);
+                    printk("Unable to decode instruction in alternative - ignoring.\n");
+                    goto skip_this_alternative;

Can this really be just a log message? There are cases where patching has to happen for things to operate correctly. Hence if not panic()ing, I'd say we at least want to taint the hypervisor.

Actually, after some further thought, I don't even think we should skip such alternatives. Think of e.g. cases where in principle we could get away with just patching the prefix of an insn. Yet even without such trickery - there's a fair chance that the alternative doesn't need fiddling with, and hence putting it in unaltered is likely the best we can do here.

Jan

#17 lore raw

Re: [PATCH 5/6] x86/alternative: Relocate all insn-relative fields

Quoted 31 lines · Jan Beulich
Quoted 22 lines · Jan Beulich
Quoted 21 lines · Andrew Cooper
xen/arch/x86/alternative.c +11 -2
@@ -244,10 +244,31 @@ static void init_or_livepatch _apply_alternatives(struct alt_instr *start,
 
         memcpy(buf, repl, a->repl_len);
 
+        /* Walk buf[] and adjust any insn-relative operands. */
+        if ( a->repl_len )
         {
-            /* 0xe8/0xe9 are relative branches; fix the offset. */
-            if ( a->repl_len >= 5 && (*buf & 0xfe) == 0xe8 )
+            uint8_t *ip = buf, *end = ip + a->repl_len;
+
+            for ( x86_decode_lite_t res; ip < end; ip += res.len )
             {
+                int32_t *d32;
+                uint8_t *target;
+
+                res = x86_decode_lite(ip, end);
+
+                if ( res.len <= 0 )
Quoted 8 lines

xen/arch/x86/alternative.c static void init_or_livepatch _apply_alternatives(struct alt_instr *start, · line 264

Quoted 5 lines
xen/arch/x86/alternative.c +5 -0
+                {
+                    printk("Alternative for %ps [%*ph]\n",
+                           ALT_ORIG_PTR(a), a->repl_len, repl);
+                    printk("Unable to decode instruction in alternative - ignoring.\n");
+                    goto skip_this_alternative;

Can this really be just a log message? There are cases where patching has to happen for things to operate correctly. Hence if not panic()ing, I'd say we at least want to taint the hypervisor.

Quoted 6 lines

Actually, after some further thought, I don't even think we should skip such alternatives. Think of e.g. cases where in principle we could get away with just patching the prefix of an insn. Yet even without such trickery - there's a fair chance that the alternative doesn't need fiddling with, and hence putting it in unaltered is likely the best we can do here.

Following Roger's series, it needs to be a return -Exx and non-fatal in livepatch context.

That said, the point of the SELF_TESTS, and the userspace harness I didn't finish for v1, is to avoid (as far as possible) getting into the situation where we can't decode the replacements.

~Andrew

#18 lore raw

Re: [PATCH 5/6] x86/alternative: Relocate all insn-relative fields

In reply to Jan Beulich
Quoted 13 lines · Jan Beulich

xen/arch/x86/alternative.c static void init_or_livepatch _apply_alternatives(struct alt_instr *start, · line 322

Quoted 9 lines · Andrew Cooper
xen/arch/x86/alternative.c +2 -2
@@ -317,14 +338,23 @@ static void init_or_livepatch _apply_alternatives(struct alt_instr *start,
                          */
                         goto skip_this_alternative;
                     }
+
+                    continue;
                 }
-                else if ( force && system_state < SYS_STATE_active )
-                    ASSERT_UNREACHABLE();

This (and the other one below) is related to altcall patching, which you say you mean to leave alone: During the 2nd pass, no un-processed CALL / JMP should occur anymore that aren't altcall related.

Calling the parameter "force" was a mistake and I regret not asking for it to change.  It should be a SEAL_ALTCALL flag of some form or another.

But, that's not what this ASSERT() is doing.  This assert is only checking that you don't try sealing a still-NULL altcall early, which is only doing nothing more than checking that the caller of _apply_alternatives() passed a parameter correctly.

~Andrew

#19 lore raw

PATCH 6/6 x86/spec-ctrl: Introduce and use DO_COND_BHB_SEQ

In reply to Andrew Cooper

Now that alternatives can fix up call displacements even when they're not the first instruction of the replacement, move the SCF_entry_bhb conditional inside the replacement block.

This removes a conditional branch from the fastpaths of BHI-unaffected hardware.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>

---
 xen/arch/x86/hvm/vmx/entry.S             | 12 +++----
 xen/arch/x86/include/asm/spec_ctrl_asm.h | 43 +++++++++++++-----------
 2 files changed, 30 insertions(+), 25 deletions(-)
xen/arch/x86/hvm/vmx/entry.S +6 -6
index 7233e771d88a..77bf9ea564ea 100644
@@ -62,12 +62,12 @@ ENTRY(vmx_asm_vmexit_handler)
          * Clear the BHB to mitigate BHI.  Used on eIBRS parts, and uses RETs
          * itself so must be after we've perfomed all the RET-safety we can.
          */
-        testb $SCF_entry_bhb, CPUINFO_scf(%rsp)
-        jz .L_skip_bhb
-        ALTERNATIVE_2 "",                                    \
-            "call clear_bhb_loops", X86_SPEC_BHB_LOOPS,      \
-            "call clear_bhb_tsx", X86_SPEC_BHB_TSX
-.L_skip_bhb:
+        .macro VMX_BHB_SEQ fn:req
+            DO_COND_BHB_SEQ \fn scf=CPUINFO_scf(%rsp)
+        .endm
+        ALTERNATIVE_2 "",                                         \
+            "VMX_BHB_SEQ fn=clear_bhb_loops", X86_SPEC_BHB_LOOPS, \
+            "VMX_BHB_SEQ fn=clear_bhb_tsx",   X86_SPEC_BHB_TSX
 
         ALTERNATIVE "lfence", "", X86_SPEC_NO_LFENCE_ENTRY_VMX
         /* WARNING! `ret`, `call *`, `jmp *` not safe before this point. */
xen/arch/x86/include/asm/spec_ctrl_asm.h +24 -19

67 lines not on this page · raw message

Signature · 1 line
2.30.2
Reviewed-by on v1 6/6
#20 lore raw

Re: [PATCH 6/6] x86/spec-ctrl: Introduce and use DO_COND_BHB_SEQ

Quoted 4 lines · Andrew Cooper
xen/arch/x86/hvm/vmx/entry.S +0 -0
@@ -62,12 +62,12 @@ ENTRY(vmx_asm_vmexit_handler)
          * Clear the BHB to mitigate BHI.  Used on eIBRS parts, and uses RETs

xen/arch/x86/hvm/vmx/entry.S ENTRY(vmx_asm_vmexit_handler) · line 66

Quoted 10 lines
xen/arch/x86/hvm/vmx/entry.S +2 -6
          * itself so must be after we've perfomed all the RET-safety we can.
          */
-        testb $SCF_entry_bhb, CPUINFO_scf(%rsp)
-        jz .L_skip_bhb
-        ALTERNATIVE_2 "",                                    \
-            "call clear_bhb_loops", X86_SPEC_BHB_LOOPS,      \
-            "call clear_bhb_tsx", X86_SPEC_BHB_TSX
-.L_skip_bhb:
+        .macro VMX_BHB_SEQ fn:req
+            DO_COND_BHB_SEQ \fn scf=CPUINFO_scf(%rsp)

While the assembler permits this, can we please avoid mixing positional and named macro arguments? Instead, ...

xen/arch/x86/hvm/vmx/entry.S ENTRY(vmx_asm_vmexit_handler) · line 70

Quoted 4 lines
xen/arch/x86/hvm/vmx/entry.S +4 -0
+        .endm
+        ALTERNATIVE_2 "",                                         \
+            "VMX_BHB_SEQ fn=clear_bhb_loops", X86_SPEC_BHB_LOOPS, \
+            "VMX_BHB_SEQ fn=clear_bhb_tsx",   X86_SPEC_BHB_TSX

... as done further down, named arguments don't need using here. With the former addressed and preferably with the latter in consistent shape with what's below (which way round I don't care as much, albeit with a slight preference for "shorter"):

Jan

Quoted 73 lines
xen/arch/x86/include/asm/spec_ctrl_asm.h +24 -19
@@ -92,6 +92,21 @@
 .L\@_skip:
 .endm
 
+.macro DO_COND_BHB_SEQ fn:req, scf=%bl
+/*
+ * Requires SCF (defaults to %rbx), fn=clear_bhb_{loops,tsx}
+ * Clobbers %rax, %rcx
+ *
+ * Conditionally use a BHB clearing software sequence.
+ */
+    testb  $SCF_entry_bhb, \scf
+    jz     .L\@_skip_bhb
+
+    call   \fn
+
+.L\@_skip_bhb:
+.endm
+
 .macro DO_OVERWRITE_RSB tmp=rax, xu
 /*
  * Requires nothing
@@ -277,12 +292,9 @@
      * Clear the BHB to mitigate BHI.  Used on eIBRS parts, and uses RETs
      * itself so must be after we've perfomed all the RET-safety we can.
      */
-    testb $SCF_entry_bhb, %bl
-    jz .L\@_skip_bhb
-    ALTERNATIVE_2 "",                                    \
-        "call clear_bhb_loops", X86_SPEC_BHB_LOOPS,      \
-        "call clear_bhb_tsx", X86_SPEC_BHB_TSX
-.L\@_skip_bhb:
+    ALTERNATIVE_2 "",                                          \
+        "DO_COND_BHB_SEQ clear_bhb_loops", X86_SPEC_BHB_LOOPS, \
+        "DO_COND_BHB_SEQ clear_bhb_tsx",   X86_SPEC_BHB_TSX
 
     ALTERNATIVE "lfence", "", X86_SPEC_NO_LFENCE_ENTRY_PV
 .endm
@@ -322,12 +334,9 @@
     ALTERNATIVE "", __stringify(DO_SPEC_CTRL_ENTRY maybexen=1),         \
         X86_FEATURE_SC_MSR_PV
 
-    testb $SCF_entry_bhb, %bl
-    jz .L\@_skip_bhb
-    ALTERNATIVE_2 "",                                    \
-        "call clear_bhb_loops", X86_SPEC_BHB_LOOPS,      \
-        "call clear_bhb_tsx", X86_SPEC_BHB_TSX
-.L\@_skip_bhb:
+    ALTERNATIVE_2 "",                                          \
+        "DO_COND_BHB_SEQ clear_bhb_loops", X86_SPEC_BHB_LOOPS, \
+        "DO_COND_BHB_SEQ clear_bhb_tsx",   X86_SPEC_BHB_TSX
 
     ALTERNATIVE "lfence", "", X86_SPEC_NO_LFENCE_ENTRY_INTR
 .endm
@@ -433,13 +442,9 @@
      * Clear the BHB to mitigate BHI.  Used on eIBRS parts, and uses RETs
      * itself so must be after we've perfomed all the RET-safety we can.
      */
-    testb $SCF_entry_bhb, %bl
-    jz .L\@_skip_bhb
-
-    ALTERNATIVE_2 "",                                    \
-        "call clear_bhb_loops", X86_SPEC_BHB_LOOPS,      \
-        "call clear_bhb_tsx", X86_SPEC_BHB_TSX
-.L\@_skip_bhb:
+    ALTERNATIVE_2 "",                                          \
+        "DO_COND_BHB_SEQ clear_bhb_loops", X86_SPEC_BHB_LOOPS, \
+        "DO_COND_BHB_SEQ clear_bhb_tsx",   X86_SPEC_BHB_TSX
 
     lfence
 .endm
#21 lore raw

Re: [PATCH 6/6] x86/spec-ctrl: Introduce and use DO_COND_BHB_SEQ

In reply to Andrew Cooper
Quoted 8 lines · Andrew Cooper
xen/arch/x86/hvm/vmx/entry.S +0 -2
@@ -62,12 +62,12 @@ ENTRY(vmx_asm_vmexit_handler)
          * Clear the BHB to mitigate BHI.  Used on eIBRS parts, and uses RETs
          * itself so must be after we've perfomed all the RET-safety we can.
          */
-        testb $SCF_entry_bhb, CPUINFO_scf(%rsp)
-        jz .L_skip_bhb

xen/arch/x86/hvm/vmx/entry.S ENTRY(vmx_asm_vmexit_handler) · line 70

Quoted 10 lines
xen/arch/x86/hvm/vmx/entry.S +6 -4
-        ALTERNATIVE_2 "",                                    \
-            "call clear_bhb_loops", X86_SPEC_BHB_LOOPS,      \
-            "call clear_bhb_tsx", X86_SPEC_BHB_TSX
-.L_skip_bhb:
+        .macro VMX_BHB_SEQ fn:req
+            DO_COND_BHB_SEQ \fn scf=CPUINFO_scf(%rsp)
+        .endm
+        ALTERNATIVE_2 "",                                         \
+            "VMX_BHB_SEQ fn=clear_bhb_loops", X86_SPEC_BHB_LOOPS, \
+            "VMX_BHB_SEQ fn=clear_bhb_tsx",   X86_SPEC_BHB_TSX

Oh, and just to mention it since we were discussing this before: The variant of this that I had been thinking of without decode-lite would have been to transform this (readable)

        testb $SCF_entry_bhb, CPUINFO_scf(%rsp)
        ALTERNATIVE_2 "jmp .L_skip_bhb",                     \
            "jz .L_skip_bhb", X86_SPEC_BHB_LOOPS,            \
            "jz .L_skip_bhb", X86_SPEC_BHB_TSX
        ALTERNATIVE_2 "",                                    \
            "call clear_bhb_loops", X86_SPEC_BHB_LOOPS,      \
            "call clear_bhb_tsx", X86_SPEC_BHB_TSX

.L_skip_bhb:

into (untested, and hence perhaps slightly off) the (less readable)

        testb $SCF_entry_bhb, CPUINFO_scf(%rsp)
        ALTERNATIVE_2 ".byte 0xeb" /* jmp */,                \
            ".byte 0x74" /* jz */, X86_SPEC_BHB_LOOPS,       \
            ".byte 0x74" /* jz */, X86_SPEC_BHB_TSX
        .byte .L_skip_bhb - (. + 1)
        ALTERNATIVE_2 "",                                    \
            "call clear_bhb_loops", X86_SPEC_BHB_LOOPS,      \
            "call clear_bhb_tsx", X86_SPEC_BHB_TSX

.L_skip_bhb:

Of course yours (dropping the branch altogether) is better, but also comes at a higher price.

Jan

#22 lore raw

Re: [PATCH 6/6] x86/spec-ctrl: Introduce and use DO_COND_BHB_SEQ

In reply to Andrew Cooper

xen/arch/x86/include/asm/spec_ctrl_asm.h line 339

Quoted 13 lines · Andrew Cooper
xen/arch/x86/include/asm/spec_ctrl_asm.h +3 -6
@@ -322,12 +334,9 @@
     ALTERNATIVE "", __stringify(DO_SPEC_CTRL_ENTRY maybexen=1),         \
         X86_FEATURE_SC_MSR_PV
 
-    testb $SCF_entry_bhb, %bl
-    jz .L\@_skip_bhb
-    ALTERNATIVE_2 "",                                    \
-        "call clear_bhb_loops", X86_SPEC_BHB_LOOPS,      \
-        "call clear_bhb_tsx", X86_SPEC_BHB_TSX
-.L\@_skip_bhb:
+    ALTERNATIVE_2 "",                                          \
+        "DO_COND_BHB_SEQ clear_bhb_loops", X86_SPEC_BHB_LOOPS, \
+        "DO_COND_BHB_SEQ clear_bhb_tsx",   X86_SPEC_BHB_TSX

Only spotting this while doing the 456 backport to 4.9: While this is all usual and fine, ...

Quoted 6 lines
xen/arch/x86/include/asm/spec_ctrl_asm.h +0 -2
@@ -433,13 +442,9 @@
      * Clear the BHB to mitigate BHI.  Used on eIBRS parts, and uses RETs
      * itself so must be after we've perfomed all the RET-safety we can.
      */
-    testb $SCF_entry_bhb, %bl
-    jz .L\@_skip_bhb

xen/arch/x86/include/asm/spec_ctrl_asm.h line 449

Quoted 10 lines
xen/arch/x86/include/asm/spec_ctrl_asm.h +3 -5
-
-    ALTERNATIVE_2 "",                                    \
-        "call clear_bhb_loops", X86_SPEC_BHB_LOOPS,      \
-        "call clear_bhb_tsx", X86_SPEC_BHB_TSX
-.L\@_skip_bhb:
+    ALTERNATIVE_2 "",                                          \
+        "DO_COND_BHB_SEQ clear_bhb_loops", X86_SPEC_BHB_LOOPS, \
+        "DO_COND_BHB_SEQ clear_bhb_tsx",   X86_SPEC_BHB_TSX
 
     lfence

... the original use of ALTERNATIVE_2 here is safe only because for the idle domain SCF_entry_bhb will not be set, and hence any patching done here will not affect NMI or #MC taken while doing the patching. Therefore I think this hunk needs dropping.

Jan