Skip to contentSkip to conversation

x86/pv: #DB vs %dr6 fixes, part 2

PATCH Superseded Andrew Cooper 3 participants 22 messages Sep 12, 2023 – Sep 18, 2023

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore
#0 lore raw

cover x86/pv: #DB vs %dr6 fixes, part 2

Slightly RFC. This is the next chunk of debug fixes from the bug that Jinoh reported.

I've decided to tackle PV guests alone to simplify the problem (No introspection, get some of the core changes in place).

Patch 5 is still a bit chunky to follow, but I can't see any way to simplify it without transiently breaking something.

Patchs 1 and 3 are entirely new, relative to previous postings of this work. Others are rebased/shuffled.

There are still bugs/misfeatures:

1) Data breakpoints during emulation (copy to/from guest) are accounted against Xen and not given back to the guest.
2) Instruction breakpoints aren't calculated for FEP; CPUID. This may not matter, but like everything in PV, it's undocumented and unclear if it's intended behaviour or not.

that can be left to some other future to fix.

Andrew Cooper (5):
x86/pv: Fix the determiniation of whether to inject #DB
x86: Introduce x86_merge_dr6()
x86/emul: Add a pending_dbg field to x86_emulate_ctxt.retire x86/pv: Drop priv_op_ctxt.bpmatch and use pending_dbg instead x86/pv: Rewrite %dr6 handling

 xen/arch/x86/debug.c                   | 20 +++++++++++++++++
 xen/arch/x86/include/asm/debugreg.h    |  7 ++++++
 xen/arch/x86/include/asm/domain.h      | 12 ++++++++++
 xen/arch/x86/include/asm/x86-defns.h   |  7 ++++++
 xen/arch/x86/pv/emul-priv-op.c         | 31 +++++++++++++-------------
 xen/arch/x86/pv/emulate.c              |  6 ++---
 xen/arch/x86/pv/ro-page-fault.c        |  4 ++--
 xen/arch/x86/pv/traps.c                | 17 ++++++++++----
 xen/arch/x86/traps.c                   | 12 +++++-----
 xen/arch/x86/x86_emulate/x86_emulate.c |  6 ++++-
 xen/arch/x86/x86_emulate/x86_emulate.h | 22 ++++++++++++++----
 11 files changed, 109 insertions(+), 35 deletions(-)
Signature · 1 line
2.30.2
#1 lore raw

PATCH 1/5 x86/pv: Fix the determiniation of whether to inject #DB

We long ago fixed the emulator to not inject exceptions behind our back. Therefore, assert that that a PV event (including interrupts, because that would be buggy too) isn't pending, rather than skipping the #DB injection if one is.

On the other hand, the io_emul() stubs which use X86EMUL_DONE rather than X86EMUL_OKAY may have pending breakpoints to inject after the IO access is complete, not to mention a pending singlestep.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Wei Liu <[email protected]>
CC: Jinoh Kang <[email protected]>

---
 xen/arch/x86/pv/emul-priv-op.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
xen/arch/x86/pv/emul-priv-op.c +6 -2
index 142bc4818cb5..257891a2a2dd 100644
@@ -1358,14 +1358,18 @@ int pv_emulate_privileged_op(struct cpu_user_regs *regs)
     switch ( rc )
     {
     case X86EMUL_OKAY:
+    case X86EMUL_DONE:
+        ASSERT(!curr->arch.pv.trap_bounce.flags);
+
         if ( ctxt.ctxt.retire.singlestep )
             ctxt.bpmatch |= DR_STEP;
+
         if ( ctxt.bpmatch )
         {
             curr->arch.dr6 |= ctxt.bpmatch | DR_STATUS_RESERVED_ONE;
-            if ( !(curr->arch.pv.trap_bounce.flags & TBF_EXCEPTION) )
-                pv_inject_hw_exception(X86_EXC_DB, X86_EVENT_NO_EC);
+            pv_inject_hw_exception(X86_EXC_DB, X86_EVENT_NO_EC);
         }
+
         /* fall through */
     case X86EMUL_RETRY:
         return EXCRET_fault_fixed;
Signature · 1 line
2.30.2
Reviewed-by on v1 1/5
#2 lore raw

Re: [PATCH 1/5] x86/pv: Fix the determiniation of whether to inject #DB

Quoted 8 lines · Andrew Cooper

We long ago fixed the emulator to not inject exceptions behind our back. Therefore, assert that that a PV event (including interrupts, because that would be buggy too) isn't pending, rather than skipping the #DB injection if one is.

On the other hand, the io_emul() stubs which use X86EMUL_DONE rather than X86EMUL_OKAY may have pending breakpoints to inject after the IO access is complete, not to mention a pending singlestep.

If you look at the uses of X86EMUL_DONE you'll see that this error code is not intended to ever come back from the emulator. It's solely used to communicate between hooks and the core emulator. Therefore I think this part of the description and the added case label are wrong here. With them dropped again ...

Quoted 1 line

Jan

#3 lore raw

Re: [PATCH 1/5] x86/pv: Fix the determiniation of whether to inject #DB

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

We long ago fixed the emulator to not inject exceptions behind our back. Therefore, assert that that a PV event (including interrupts, because that would be buggy too) isn't pending, rather than skipping the #DB injection if one is.

Quoted 8 lines
Quoted 3 lines

On the other hand, the io_emul() stubs which use X86EMUL_DONE rather than X86EMUL_OKAY may have pending breakpoints to inject after the IO access is complete, not to mention a pending singlestep.

If you look at the uses of X86EMUL_DONE you'll see that this error code is not intended to ever come back from the emulator. It's solely used to communicate between hooks and the core emulator. Therefore I think this part of the description and the added case label are wrong here. With them dropped again ...

Oh.  I see that now you've pointed it out, but it's far from clear.

I'd suggest that we extend the the debug wrapper for x86_emulate() with an assertion to this effect.  It also has a knock-on effect in later patches.

With the DONE part dropped, this probably wants merging into patch 4. Thoughts?

~Andrew

#4 lore raw

Re: [PATCH 1/5] x86/pv: Fix the determiniation of whether to inject #DB

Quoted 16 lines · Andrew Cooper
Quoted 6 lines · Jan Beulich
Quoted 5 lines · Andrew Cooper

We long ago fixed the emulator to not inject exceptions behind our back. Therefore, assert that that a PV event (including interrupts, because that would be buggy too) isn't pending, rather than skipping the #DB injection if one is.

Quoted 8 lines
Quoted 3 lines

On the other hand, the io_emul() stubs which use X86EMUL_DONE rather than X86EMUL_OKAY may have pending breakpoints to inject after the IO access is complete, not to mention a pending singlestep.

If you look at the uses of X86EMUL_DONE you'll see that this error code is not intended to ever come back from the emulator. It's solely used to communicate between hooks and the core emulator. Therefore I think this part of the description and the added case label are wrong here. With them dropped again ...

Quoted 8 lines

Oh.  I see that now you've pointed it out, but it's far from clear.

I'd suggest that we extend the the debug wrapper for x86_emulate() with an assertion to this effect.  It also has a knock-on effect in later patches.

With the DONE part dropped, this probably wants merging into patch 4. Thoughts?

Not sure. Even then the patch here looks to still make sense on its own. I don't mind the folding, I guess, but for the moment the two R-b are only on the individual patches.

Jan

#5 lore raw

PATCH 2/5 x86: Introduce x86_merge_dr6()

In reply to Andrew Cooper

The current logic used to update %dr6 when injecting #DB is buggy. The architectural behaviour is to overwrite B{0..3} and accumulate all other bits.

Introduce x86_merge_dr6() to perform the operaton properly.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Wei Liu <[email protected]>
CC: Jinoh Kang <[email protected]>

---
 xen/arch/x86/debug.c                 | 20 ++++++++++++++++++++
 xen/arch/x86/include/asm/debugreg.h  |  7 +++++++
 xen/arch/x86/include/asm/x86-defns.h |  7 +++++++
 3 files changed, 34 insertions(+)
xen/arch/x86/debug.c +20 -0
index 127fe83021cd..bfcd83ea4d0b 100644
@@ -3,6 +3,7 @@
  * Copyright (C) 2023 XenServer.
  */
 #include <xen/kernel.h>
+#include <xen/lib.h>
 
 #include <xen/lib/x86/cpu-policy.h>
 
@@ -28,6 +29,25 @@ unsigned int x86_adj_dr6_rsvd(const struct cpu_policy *p, unsigned int dr6)
     return dr6;
 }
 
+unsigned int x86_merge_dr6(const struct cpu_policy *p, unsigned int dr6,
+                           unsigned int new)
+{
+    /* Flip dr6 to have positive polarity. */
+    dr6 ^= X86_DR6_DEFAULT;
+
+    /* Sanity check that only known values are passed in. */
+    ASSERT(!(dr6 & ~X86_DR6_KNOWN_MASK));
+    ASSERT(!(new & ~X86_DR6_KNOWN_MASK));
+
+    /* Breakpoint matches are overridden.  All other bits accumulate. */
+    dr6 = (dr6 & ~X86_DR6_BP_MASK) | new;
+
+    /* Flip dr6 back to having default polarity. */
+    dr6 ^= X86_DR6_DEFAULT;
+
+    return x86_adj_dr6_rsvd(p, dr6);
+}
+
 unsigned int x86_adj_dr7_rsvd(const struct cpu_policy *p, unsigned int dr7)
 {
     unsigned int zeros = X86_DR7_ZEROS;
xen/arch/x86/include/asm/debugreg.h +7 -0
index 39ba312b84ee..e98a9ce977fa 100644
@@ -89,4 +89,11 @@ struct cpu_policy;
 unsigned int x86_adj_dr6_rsvd(const struct cpu_policy *p, unsigned int dr6);
 unsigned int x86_adj_dr7_rsvd(const struct cpu_policy *p, unsigned int dr7);
 
+/*
+ * Merge new bits into dr6.  'new' is always given in positive polarity,
+ * matching the Intel VMCS PENDING_DBG semantics.
+ */
+unsigned int x86_merge_dr6(const struct cpu_policy *p, unsigned int dr6,
+                           unsigned int new);
+
 #endif /* _X86_DEBUGREG_H */
xen/arch/x86/include/asm/x86-defns.h +7 -0
index 5838631ef634..edfecc89bd08 100644
@@ -116,6 +116,13 @@
 #define X86_DR6_BT              (_AC(1, UL) << 15)   /* Task switch                 */
 #define X86_DR6_RTM             (_AC(1, UL) << 16)   /* #DB/#BP in RTM region (INV) */
 
+#define X86_DR6_BP_MASK                                 \
+    (X86_DR6_B0 | X86_DR6_B1 | X86_DR6_B2 | X86_DR6_B3)
+
+#define X86_DR6_KNOWN_MASK                                      \
+    (X86_DR6_BP_MASK | X86_DR6_BLD | X86_DR6_BD | X86_DR6_BS |  \
+     X86_DR6_BT | X86_DR6_RTM)
+
 #define X86_DR6_ZEROS           _AC(0x00001000, UL)  /* %dr6 bits forced to 0       */
 #define X86_DR6_DEFAULT         _AC(0xffff0ff0, UL)  /* Default %dr6 value          */
 
Signature · 1 line
2.30.2
#6 lore raw

Re: [PATCH 2/5] x86: Introduce x86_merge_dr6()

Quoted 2 lines · Andrew Cooper

The current logic used to update %dr6 when injecting #DB is buggy. The architectural behaviour is to overwrite B{0..3} and accumulate all other bits.

While I consider this behavior plausible, forever since the introduction of debug registers in i386 I have been missing a description in the manuals of how %dr6 updating works. Can you point me at where the above is actually spelled out?

Jan

#7 lore raw

Re: [PATCH 2/5] x86: Introduce x86_merge_dr6()

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

The current logic used to update %dr6 when injecting #DB is buggy. The architectural behaviour is to overwrite B{0..3} and accumulate all other bits.

While I consider this behavior plausible, forever since the introduction of debug registers in i386 I have been missing a description in the manuals of how %dr6 updating works. Can you point me at where the above is actually spelled out?

The documentation is very poor.  The comment in the code is based on my conversations with architects.

APM Vol2 13.1.1.3 Debug-Status Register (DR6) says

"Bits 15:13 of the DR6 register are not cleared by the processor and must be cleared by software after the contents have been read."

although this is buggy given the addition of BLD in the latest revision.  I've asked AMD to correct it.

SDM Vol3 18.2.3 Debug Status Register (DR6) says

"Certain debug exceptions may clear bits 0-3. The remaining contents of the DR6 register are never cleared by the processor."

~Andrew

#8 lore raw

Re: [PATCH 2/5] x86: Introduce x86_merge_dr6()

Quoted 11 lines · Andrew Cooper
Quoted 7 lines · Jan Beulich
Quoted 2 lines · Andrew Cooper

The current logic used to update %dr6 when injecting #DB is buggy. The architectural behaviour is to overwrite B{0..3} and accumulate all other bits.

While I consider this behavior plausible, forever since the introduction of debug registers in i386 I have been missing a description in the manuals of how %dr6 updating works. Can you point me at where the above is actually spelled out?

The documentation is very poor.  The comment in the code is based on my conversations with architects.

Especially in such a case, can you please make very explicit in the description what the origin of the information is? That way it's simply impossible for anyone to review properly without having had the same conversations.

Jan

Quoted 15 lines

APM Vol2 13.1.1.3 Debug-Status Register (DR6) says

"Bits 15:13 of the DR6 register are not cleared by the processor and must be cleared by software after the contents have been read."

although this is buggy given the addition of BLD in the latest revision.  I've asked AMD to correct it.

SDM Vol3 18.2.3 Debug Status Register (DR6) says

"Certain debug exceptions may clear bits 0-3. The remaining contents of the DR6 register are never cleared by the processor."

~Andrew

#9 lore raw

PATCH 3/5 x86/emul: Add a pending_dbg field to x86_emulate_ctxt.retire

In reply to Andrew Cooper

Lots of this is very very broken, but we need to start somewhere.

PENDING_DBG, INTERRUPTIBILITY and ACTIVITY are internal pipeline registers which Intel exposed to software in the VMCS, and AMD exposed a subset of in the VMCB. Importantly, bits set in PENDING_DBG can survive across multiple instruction boundaries if e.g. delivery of #DB is delayed by a MovSS.

For now, introduce a full pending_dbg field into the retire union. This keeps the sh_page_fault() and init_context() paths working but in due course the field will want to lose the "retire" infix.

In addition, set singlestep into pending_dbg as appropriate. Leave the old singlestep bitfield in place until we can adjust the callers to handle it properly.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Wei Liu <[email protected]>
CC: Jinoh Kang <[email protected]>

---
 xen/arch/x86/x86_emulate/x86_emulate.c |  6 +++++-
 xen/arch/x86/x86_emulate/x86_emulate.h | 17 ++++++++++++++---
 2 files changed, 19 insertions(+), 4 deletions(-)
xen/arch/x86/x86_emulate/x86_emulate.c +5 -1
index e88245eae9fb..de707c8ec211 100644
@@ -8379,7 +8379,10 @@ x86_emulate(
     if ( !mode_64bit() )
         _regs.r(ip) = (uint32_t)_regs.r(ip);
 
-    /* Should a singlestep #DB be raised? */
+    if ( singlestep )
+        ctxt->retire.pending_dbg |= X86_DR6_BS;
+
+    /* Should a singlestep #DB be raised? (BROKEN - TODO, merge into pending_dbg) */
     if ( rc == X86EMUL_OKAY && singlestep && !ctxt->retire.mov_ss )
     {
         ctxt->retire.singlestep = true;
@@ -8659,6 +8662,7 @@ int x86_emulate_wrapper(
     {
         typeof(ctxt->retire) retire = ctxt->retire;
 
+        retire.pending_dbg = 0;
         retire.unblock_nmi = false;
         ASSERT(!retire.raw);
     }
xen/arch/x86/x86_emulate/x86_emulate.h +14 -3
index 698750267a90..f0e74d23c378 100644
@@ -588,15 +588,26 @@ struct x86_emulate_ctxt
     /* Canonical opcode (see below) (valid only on X86EMUL_OKAY). */
     unsigned int opcode;
 
-    /* Retirement state, set by the emulator (valid only on X86EMUL_OKAY). */
+    /*
+     * Retirement state, set by the emulator (valid only on X86EMUL_OKAY/DONE).
+     *
+     * TODO: all this state should be input/output from the VMCS PENDING_DBG,
+     * INTERRUPTIBILITY and ACTIVITIY fields.
+     */
     union {
-        uint8_t raw;
+        unsigned long raw;
         struct {
+            /*
+             * Accumulated %dr6 trap bits, positive polarity.  Should only be
+             * interpreted in the case of X86EMUL_OKAY/DONE.
+             */
+            unsigned int pending_dbg;
+
             bool hlt:1;          /* Instruction HLTed. */
             bool mov_ss:1;       /* Instruction sets MOV-SS irq shadow. */
             bool sti:1;          /* Instruction sets STI irq shadow. */
             bool unblock_nmi:1;  /* Instruction clears NMI blocking. */
-            bool singlestep:1;   /* Singlestepping was active. */
+            bool singlestep:1;   /* Singlestepping was active. (TODO, merge into pending_dbg) */
         };
     } retire;
 
Signature · 1 line
2.30.2
#10 lore raw

Re: [PATCH 3/5] x86/emul: Add a pending_dbg field to x86_emulate_ctxt.retire

xen/arch/x86/x86_emulate/x86_emulate.c x86_emulate( · line 8383

Quoted 9 lines · Andrew Cooper
xen/arch/x86/x86_emulate/x86_emulate.c +2 -1
@@ -8379,7 +8379,10 @@ x86_emulate(
     if ( !mode_64bit() )
         _regs.r(ip) = (uint32_t)_regs.r(ip);
 
-    /* Should a singlestep #DB be raised? */
+    if ( singlestep )
+        ctxt->retire.pending_dbg |= X86_DR6_BS;

We set "singlestep" about first thing in the function. Is it really correct to latch that into pending_dbg without regard to rc? (Perhaps yes, seeing the comment next to the field declaration.)

Quoted 22 lines
xen/arch/x86/x86_emulate/x86_emulate.h +12 -2
@@ -588,15 +588,26 @@ struct x86_emulate_ctxt
     /* Canonical opcode (see below) (valid only on X86EMUL_OKAY). */
     unsigned int opcode;
 
-    /* Retirement state, set by the emulator (valid only on X86EMUL_OKAY). */
+    /*
+     * Retirement state, set by the emulator (valid only on X86EMUL_OKAY/DONE).
+     *
+     * TODO: all this state should be input/output from the VMCS PENDING_DBG,
+     * INTERRUPTIBILITY and ACTIVITIY fields.
+     */
     union {
-        uint8_t raw;
+        unsigned long raw;
         struct {
+            /*
+             * Accumulated %dr6 trap bits, positive polarity.  Should only be
+             * interpreted in the case of X86EMUL_OKAY/DONE.
+             */
+            unsigned int pending_dbg;

xen/arch/x86/x86_emulate/x86_emulate.h struct x86_emulate_ctxt · line 613

Quoted 10 lines
xen/arch/x86/x86_emulate/x86_emulate.h +2 -1
+
             bool hlt:1;          /* Instruction HLTed. */
             bool mov_ss:1;       /* Instruction sets MOV-SS irq shadow. */
             bool sti:1;          /* Instruction sets STI irq shadow. */
             bool unblock_nmi:1;  /* Instruction clears NMI blocking. */
-            bool singlestep:1;   /* Singlestepping was active. */
+            bool singlestep:1;   /* Singlestepping was active. (TODO, merge into pending_dbg) */
         };
     } retire;
 

DONE has wrongly made it into here, as pointed out for patch 1.

Jan

#11 lore raw

Re: [PATCH 3/5] x86/emul: Add a pending_dbg field to x86_emulate_ctxt.retire

Quoted 7 lines · Jan Beulich
Quoted 6 lines · Andrew Cooper
xen/arch/x86/x86_emulate/x86_emulate.c +0 -0
@@ -8379,7 +8379,10 @@ x86_emulate(
     if ( !mode_64bit() )
         _regs.r(ip) = (uint32_t)_regs.r(ip);
 
Quoted 6 lines

xen/arch/x86/x86_emulate/x86_emulate.c x86_emulate( · line 8383

Quoted 3 lines
xen/arch/x86/x86_emulate/x86_emulate.c +2 -1
-    /* Should a singlestep #DB be raised? */
+    if ( singlestep )
+        ctxt->retire.pending_dbg |= X86_DR6_BS;

We set "singlestep" about first thing in the function. Is it really correct to latch that into pending_dbg without regard to rc? (Perhaps yes, seeing the comment next to the field declaration.)

Honestly, without seeing some real RTL, I'm not sure.

The thing that is definitely buggy in this retire logic is saying "don't set singlestep if MovSS is pending".  The correct behaviour is to set both PENDING_DBG.BS and INTERRUPTIBILITY.MOVSS, the latter of which causes #DB to be skipped on this instruction boundary.

That's why we get the XSA-260 behaviour - when the SYSCALL/INT/etc completes and we hit the subsequent instruction boundary, PENDING_DBG still has values latched in it.

With the DONE path being removed, and with the plan to wire in the VMCS register for emulations that occur when something is already pending, then it probably does want to be restricted back to the OKAY case.

e.g. We shouldn't latch BS in EXCEPTION Case, or we'd create more XSA-260-like behaviour.

I'll adjust in light of this.

~Andrew

#12 lore raw

Re: [PATCH 3/5] x86/emul: Add a pending_dbg field to x86_emulate_ctxt.retire

In reply to Andrew Cooper
Quoted 8 lines · Andrew Cooper
xen/arch/x86/x86_emulate/x86_emulate.h +0 -0
index 698750267a90..f0e74d23c378 100644
@@ -588,15 +588,26 @@ struct x86_emulate_ctxt
     /* Canonical opcode (see below) (valid only on X86EMUL_OKAY). */
     unsigned int opcode;
 

xen/arch/x86/x86_emulate/x86_emulate.h struct x86_emulate_ctxt · line 598

Quoted 10 lines
xen/arch/x86/x86_emulate/x86_emulate.h +7 -2
-    /* Retirement state, set by the emulator (valid only on X86EMUL_OKAY). */
+    /*
+     * Retirement state, set by the emulator (valid only on X86EMUL_OKAY/DONE).
+     *
+     * TODO: all this state should be input/output from the VMCS PENDING_DBG,
+     * INTERRUPTIBILITY and ACTIVITIY fields.
+     */
     union {
-        uint8_t raw;
+        unsigned long raw;

Minor nit: this should be uint64_t for clarity. Otherwise, it's not at all clear that the raw field covers the entire union, unless you remind myself that Xen does not support 32-bit host.

Quoted 16 lines
xen/arch/x86/x86_emulate/x86_emulate.h +7 -1
         struct {
+            /*
+             * Accumulated %dr6 trap bits, positive polarity.  Should only be
+             * interpreted in the case of X86EMUL_OKAY/DONE.
+             */
+            unsigned int pending_dbg;
+
             bool hlt:1;          /* Instruction HLTed. */
             bool mov_ss:1;       /* Instruction sets MOV-SS irq shadow. */
             bool sti:1;          /* Instruction sets STI irq shadow. */
             bool unblock_nmi:1;  /* Instruction clears NMI blocking. */
-            bool singlestep:1;   /* Singlestepping was active. */
+            bool singlestep:1;   /* Singlestepping was active. (TODO, merge into pending_dbg) */
         };
     } retire;
 
Signature · 2 lines
Sincerely,
Jinoh Kang
#13 lore raw

Re: [PATCH 3/5] x86/emul: Add a pending_dbg field to x86_emulate_ctxt.retire

Quoted 9 lines · Jinoh Kang
Quoted 8 lines · Andrew Cooper
xen/arch/x86/x86_emulate/x86_emulate.h +0 -0
index 698750267a90..f0e74d23c378 100644
@@ -588,15 +588,26 @@ struct x86_emulate_ctxt
     /* Canonical opcode (see below) (valid only on X86EMUL_OKAY). */
     unsigned int opcode;
 
Quoted 14 lines

xen/arch/x86/x86_emulate/x86_emulate.h struct x86_emulate_ctxt · line 598

Quoted 10 lines
xen/arch/x86/x86_emulate/x86_emulate.h +7 -2
-    /* Retirement state, set by the emulator (valid only on X86EMUL_OKAY). */
+    /*
+     * Retirement state, set by the emulator (valid only on X86EMUL_OKAY/DONE).
+     *
+     * TODO: all this state should be input/output from the VMCS PENDING_DBG,
+     * INTERRUPTIBILITY and ACTIVITIY fields.
+     */
     union {
-        uint8_t raw;
+        unsigned long raw;

Minor nit: this should be uint64_t for clarity. Otherwise, it's not at all clear that the raw field covers the entire union, unless you remind myself that Xen does not support 32-bit host.

you remind yourself*. What a weird typo to make :-(

Signature · 2 lines
Sincerely,
Jinoh Kang
#14 lore raw

Re: [PATCH 3/5] x86/emul: Add a pending_dbg field to x86_emulate_ctxt.retire

Quoted 23 lines · Jinoh Kang
Quoted 9 lines · Jinoh Kang
Quoted 8 lines · Andrew Cooper
xen/arch/x86/x86_emulate/x86_emulate.h +0 -0
index 698750267a90..f0e74d23c378 100644
@@ -588,15 +588,26 @@ struct x86_emulate_ctxt
     /* Canonical opcode (see below) (valid only on X86EMUL_OKAY). */
     unsigned int opcode;
 
Quoted 13 lines

xen/arch/x86/x86_emulate/x86_emulate.h struct x86_emulate_ctxt · line 598

Quoted 10 lines
xen/arch/x86/x86_emulate/x86_emulate.h +7 -2
-    /* Retirement state, set by the emulator (valid only on X86EMUL_OKAY). */
+    /*
+     * Retirement state, set by the emulator (valid only on X86EMUL_OKAY/DONE).
+     *
+     * TODO: all this state should be input/output from the VMCS PENDING_DBG,
+     * INTERRUPTIBILITY and ACTIVITIY fields.
+     */
     union {
-        uint8_t raw;
+        unsigned long raw;

Minor nit: this should be uint64_t for clarity. Otherwise, it's not at all clear that the raw field covers the entire union, unless you remind myself that Xen does not support 32-bit host.

Quoted 1 line

you remind yourself*. What a weird typo to make :-(

For better or worse, this is form preferred by the Xen coding style.

We deleted the 32bit build of the Xen more than a decade ago, and have been 64bit-only ever since.

~Andrew

#15 lore raw

PATCH 4/5 x86/pv: Drop priv_op_ctxt.bpmatch and use pending_dbg instead

In reply to Andrew Cooper

With a full pending_dbg field in x86_emulate_ctxt, use it rather than using a local bpmatch field.

This simplifies the OKAY/DONE path as singlestep is already accumulated by x86_emulate() when appropriate.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Wei Liu <[email protected]>
CC: Jinoh Kang <[email protected]>

---
 xen/arch/x86/pv/emul-priv-op.c | 24 ++++++++++++------------
 1 file changed, 12 insertions(+), 12 deletions(-)
xen/arch/x86/pv/emul-priv-op.c +12 -12
index 257891a2a2dd..6963db35c960 100644
@@ -34,7 +34,6 @@ struct priv_op_ctxt {
         unsigned long base, limit;
     } cs;
     char *io_emul_stub;
-    unsigned int bpmatch;
 };
 
 /* I/O emulation helpers.  Use non-standard calling conventions. */
@@ -367,7 +366,8 @@ static int cf_check read_io(
     if ( !guest_io_okay(port, bytes, curr, ctxt->regs) )
         return X86EMUL_UNHANDLEABLE;
 
-    poc->bpmatch = check_guest_io_breakpoint(curr, port, bytes);
+    poc->ctxt.retire.pending_dbg |=
+        check_guest_io_breakpoint(curr, port, bytes);
 
     if ( admin_io_okay(port, bytes, currd) )
     {
@@ -472,7 +472,8 @@ static int cf_check write_io(
     if ( !guest_io_okay(port, bytes, curr, ctxt->regs) )
         return X86EMUL_UNHANDLEABLE;
 
-    poc->bpmatch = check_guest_io_breakpoint(curr, port, bytes);
+    poc->ctxt.retire.pending_dbg |=
+        check_guest_io_breakpoint(curr, port, bytes);
 
     if ( admin_io_okay(port, bytes, currd) )
     {
@@ -636,7 +637,8 @@ static int cf_check rep_ins(
         return X86EMUL_EXCEPTION;
     }
 
-    poc->bpmatch = check_guest_io_breakpoint(curr, port, bytes_per_rep);
+    poc->ctxt.retire.pending_dbg |=
+        check_guest_io_breakpoint(curr, port, bytes_per_rep);
 
     while ( *reps < goal )
     {
@@ -658,7 +660,7 @@ static int cf_check rep_ins(
 
         ++*reps;
 
-        if ( poc->bpmatch || hypercall_preempt_check() )
+        if ( poc->ctxt.retire.pending_dbg || hypercall_preempt_check() )
             break;
 
         /* x86_emulate() clips the repetition count to ensure we don't wrap. */
@@ -703,7 +705,8 @@ static int cf_check rep_outs(
         return X86EMUL_EXCEPTION;
     }
 
-    poc->bpmatch = check_guest_io_breakpoint(curr, port, bytes_per_rep);
+    poc->ctxt.retire.pending_dbg |=
+        check_guest_io_breakpoint(curr, port, bytes_per_rep);
 
     while ( *reps < goal )
     {
@@ -726,7 +729,7 @@ static int cf_check rep_outs(
 
         ++*reps;
 
-        if ( poc->bpmatch || hypercall_preempt_check() )
+        if ( poc->ctxt.retire.pending_dbg || hypercall_preempt_check() )
             break;
 
         /* x86_emulate() clips the repetition count to ensure we don't wrap. */
@@ -1361,12 +1364,9 @@ int pv_emulate_privileged_op(struct cpu_user_regs *regs)
     case X86EMUL_DONE:
         ASSERT(!curr->arch.pv.trap_bounce.flags);
 
-        if ( ctxt.ctxt.retire.singlestep )
-            ctxt.bpmatch |= DR_STEP;
-
-        if ( ctxt.bpmatch )
+        if ( ctxt.ctxt.retire.pending_dbg )
         {
-            curr->arch.dr6 |= ctxt.bpmatch | DR_STATUS_RESERVED_ONE;
+            curr->arch.dr6 |= ctxt.ctxt.retire.pending_dbg | DR_STATUS_RESERVED_ONE;
             pv_inject_hw_exception(X86_EXC_DB, X86_EVENT_NO_EC);
         }
 
Signature · 1 line
2.30.2
Reviewed-by on v1 4/5
#16 lore raw

Re: [PATCH 4/5] x86/pv: Drop priv_op_ctxt.bpmatch and use pending_dbg instead

Quoted 7 lines · Andrew Cooper

With a full pending_dbg field in x86_emulate_ctxt, use it rather than using a local bpmatch field.

This simplifies the OKAY/DONE path as singlestep is already accumulated by x86_emulate() when appropriate.

#17 lore raw

PATCH 5/5 x86/pv: Rewrite %dr6 handling

In reply to Andrew Cooper

All #DB exceptions result in an update of %dr6, but this isn't handled properly by Xen for any guest type.

To start with, add a new pending_dbg field to x86_event, sharing storage with cr2, and using the Intel VMCS PENDING_DBG semantics. Also introduce a pv_inject_DB() wrapper use this field nicely.

Remove all ad-hoc dr6 handling, leaving it to pv_inject_event() in most cases and using the new x86_merge_dr6() helper.

In do_debug(), adjust dr6 manually only when a debugger is attached. This maintains the old behaviour.

---
CC: Jan Beulich <[email protected]>
CC: Roger Pau Monné <[email protected]>
CC: Wei Liu <[email protected]>
CC: Jinoh Kang <[email protected]>

---
 xen/arch/x86/include/asm/domain.h      | 12 ++++++++++++
 xen/arch/x86/pv/emul-priv-op.c         |  5 +----
 xen/arch/x86/pv/emulate.c              |  6 ++----
 xen/arch/x86/pv/ro-page-fault.c        |  4 ++--
 xen/arch/x86/pv/traps.c                | 17 +++++++++++++----
 xen/arch/x86/traps.c                   | 12 +++++++-----
 xen/arch/x86/x86_emulate/x86_emulate.h |  5 ++++-
 7 files changed, 41 insertions(+), 20 deletions(-)
xen/arch/x86/include/asm/domain.h +12 -0
index c2d9fc333be5..5bf488437ce1 100644
@@ -729,6 +729,18 @@ static inline void pv_inject_hw_exception(unsigned int vector, int errcode)
     pv_inject_event(&event);
 }
 
+static inline void pv_inject_DB(unsigned long pending_dbg)
+{
+    struct x86_event event = {
+        .vector      = X86_EXC_DB,
+        .type        = X86_EVENTTYPE_HW_EXCEPTION,
+        .error_code  = X86_EVENT_NO_EC,
+        .pending_dbg = pending_dbg,
+    };
+
+    pv_inject_event(&event);
+}
+
 static inline void pv_inject_page_fault(int errcode, unsigned long cr2)
 {
     const struct x86_event event = {
xen/arch/x86/pv/emul-priv-op.c +1 -4
index 6963db35c960..437172ee0fc3 100644
@@ -1365,10 +1365,7 @@ int pv_emulate_privileged_op(struct cpu_user_regs *regs)
         ASSERT(!curr->arch.pv.trap_bounce.flags);
 
         if ( ctxt.ctxt.retire.pending_dbg )
-        {
-            curr->arch.dr6 |= ctxt.ctxt.retire.pending_dbg | DR_STATUS_RESERVED_ONE;
-            pv_inject_hw_exception(X86_EXC_DB, X86_EVENT_NO_EC);
-        }
+            pv_inject_DB(ctxt.ctxt.retire.pending_dbg);
 
         /* fall through */
     case X86EMUL_RETRY:
xen/arch/x86/pv/emulate.c +2 -4
index e7a1c0a2cc4f..e522e58533f1 100644
@@ -71,11 +71,9 @@ void pv_emul_instruction_done(struct cpu_user_regs *regs, unsigned long rip)
 {
     regs->rip = rip;
     regs->eflags &= ~X86_EFLAGS_RF;
+
     if ( regs->eflags & X86_EFLAGS_TF )
-    {
-        current->arch.dr6 |= DR_STEP | DR_STATUS_RESERVED_ONE;
-        pv_inject_hw_exception(X86_EXC_DB, X86_EVENT_NO_EC);
-    }
+        pv_inject_DB(X86_DR6_BS);
 }
 
 uint64_t pv_get_reg(struct vcpu *v, unsigned int reg)
xen/arch/x86/pv/ro-page-fault.c +2 -2
index cad28ef928ad..f6bb33556e72 100644
@@ -389,8 +389,8 @@ int pv_ro_page_fault(unsigned long addr, struct cpu_user_regs *regs)
 
         /* Fallthrough */
     case X86EMUL_OKAY:
-        if ( ctxt.retire.singlestep )
-            pv_inject_hw_exception(X86_EXC_DB, X86_EVENT_NO_EC);
+        if ( ctxt.retire.pending_dbg )
+            pv_inject_DB(ctxt.retire.pending_dbg);
 
         /* Fallthrough */
     case X86EMUL_RETRY:
xen/arch/x86/pv/traps.c +13 -4
index 74f333da7e1c..553b04bca956 100644
@@ -13,6 +13,7 @@
 #include <xen/softirq.h>
 
 #include <asm/pv/trace.h>
+#include <asm/debugreg.h>
 #include <asm/shared.h>
 #include <asm/traps.h>
 #include <irq_vectors.h>
@@ -50,9 +51,9 @@ void pv_inject_event(const struct x86_event *event)
     tb->cs    = ti->cs;
     tb->eip   = ti->address;
 
-    if ( event->type == X86_EVENTTYPE_HW_EXCEPTION &&
-         vector == X86_EXC_PF )
+    switch ( vector | -(event->type == X86_EVENTTYPE_SW_INTERRUPT) )
     {
+    case X86_EXC_PF:
         curr->arch.pv.ctrlreg[2] = event->cr2;
         arch_set_cr2(curr, event->cr2);
 
@@ -62,9 +63,17 @@ void pv_inject_event(const struct x86_event *event)
             error_code |= PFEC_user_mode;
 
         trace_pv_page_fault(event->cr2, error_code);
-    }
-    else
+        break;
+
+    case X86_EXC_DB:
+        curr->arch.dr6 = x86_merge_dr6(curr->domain->arch.cpu_policy,
+                                       curr->arch.dr6, event->pending_dbg);
+        /* Fallthrough */
+
+    default:
         trace_pv_trap(vector, regs->rip, use_error_code, error_code);
+        break;
+    }
 
     if ( use_error_code )
     {
xen/arch/x86/traps.c +7 -5
index dead728ce329..ae5d73abf557 100644
@@ -1887,7 +1887,7 @@ void do_device_not_available(struct cpu_user_regs *regs)
 /* SAF-1-safe */
 void do_debug(struct cpu_user_regs *regs)
 {
-    unsigned long dr6;
+    unsigned long dr6, pending_dbg;
     struct vcpu *v = current;
 
     /* Stash dr6 as early as possible. */
@@ -1997,17 +1997,19 @@ void do_debug(struct cpu_user_regs *regs)
         return;
     }
 
-    /* Save debug status register where guest OS can peek at it */
-    v->arch.dr6 |= (dr6 & ~X86_DR6_DEFAULT);
-    v->arch.dr6 &= (dr6 | ~X86_DR6_DEFAULT);
+    /* Flip dr6 to have positive polarity. */
+    pending_dbg = dr6 ^ X86_DR6_DEFAULT;
 
     if ( guest_kernel_mode(v, regs) && v->domain->debugger_attached )
     {
+        /* Save debug status register where gdbsx can peek at it */
+        v->arch.dr6 = x86_merge_dr6(v->domain->arch.cpu_policy,
+                                    v->arch.dr6, pending_dbg);
         domain_pause_for_debugger();
         return;
     }
 
-    pv_inject_hw_exception(X86_EXC_DB, X86_EVENT_NO_EC);
+    pv_inject_DB(pending_dbg);
 }
 
 /* SAF-1-safe */
xen/arch/x86/x86_emulate/x86_emulate.h +4 -1
index f0e74d23c378..81f99dfaa02f 100644
@@ -78,7 +78,10 @@ struct x86_event {
     uint8_t       type;         /* X86_EVENTTYPE_* */
     uint8_t       insn_len;     /* Instruction length */
     int32_t       error_code;   /* X86_EVENT_NO_EC if n/a */
-    unsigned long cr2;          /* Only for X86_EXC_PF h/w exception */
+    union {
+        unsigned long cr2;         /* #PF */
+        unsigned long pending_dbg; /* #DB (new DR6 bits, positive polarity) */
+    };
 };
 
 /*
Signature · 1 line
2.30.2
#18 lore raw

Re: [PATCH 5/5] x86/pv: Rewrite %dr6 handling

xen/arch/x86/include/asm/domain.h static inline void pv_inject_hw_exception(unsigned int vector, int errcode) · line 738

Quoted 13 lines · Andrew Cooper
xen/arch/x86/include/asm/domain.h +7 -0
@@ -729,6 +729,18 @@ static inline void pv_inject_hw_exception(unsigned int vector, int errcode)
     pv_inject_event(&event);
 }
 
+static inline void pv_inject_DB(unsigned long pending_dbg)
+{
+    struct x86_event event = {
+        .vector      = X86_EXC_DB,
+        .type        = X86_EVENTTYPE_HW_EXCEPTION,
+        .error_code  = X86_EVENT_NO_EC,
+        .pending_dbg = pending_dbg,

This being a sub-field of an unnamed union, the build will break (also in pv_inject_page_fault() then, for cr2 being switched at the same time) once again for old enough gcc.

Quoted 4 lines
xen/arch/x86/pv/emulate.c +0 -0
@@ -71,11 +71,9 @@ void pv_emul_instruction_done(struct cpu_user_regs *regs, unsigned long rip)
 {

xen/arch/x86/pv/emulate.c void pv_emul_instruction_done(struct cpu_user_regs *regs, unsigned long rip) · line 77

Quoted 10 lines
xen/arch/x86/pv/emulate.c +2 -4
     regs->rip = rip;
     regs->eflags &= ~X86_EFLAGS_RF;
+
     if ( regs->eflags & X86_EFLAGS_TF )
-    {
-        current->arch.dr6 |= DR_STEP | DR_STATUS_RESERVED_ONE;
-        pv_inject_hw_exception(X86_EXC_DB, X86_EVENT_NO_EC);
-    }
+        pv_inject_DB(X86_DR6_BS);
 }

This (not your change, the construct) looks bogus at the first and second glance, because of looking at EFLAGS.TF after emulation, when the initial state of TF matters. It is only correct (at the third, closer look) because the function presently is used only from paths not altering the guest's EFLAGS. Do you think it would make sense to add a comment at this occasion?

Jan

#19 lore raw

Re: [PATCH 5/5] x86/pv: Rewrite %dr6 handling

Quoted 7 lines · Jan Beulich
Quoted 6 lines · Andrew Cooper
xen/arch/x86/include/asm/domain.h +0 -0
@@ -729,6 +729,18 @@ static inline void pv_inject_hw_exception(unsigned int vector, int errcode)
     pv_inject_event(&event);
 }
 
Quoted 10 lines

xen/arch/x86/include/asm/domain.h static inline void pv_inject_hw_exception(unsigned int vector, int errcode) · line 738

Quoted 7 lines
xen/arch/x86/include/asm/domain.h +7 -0
+static inline void pv_inject_DB(unsigned long pending_dbg)
+{
+    struct x86_event event = {
+        .vector      = X86_EXC_DB,
+        .type        = X86_EVENTTYPE_HW_EXCEPTION,
+        .error_code  = X86_EVENT_NO_EC,
+        .pending_dbg = pending_dbg,

This being a sub-field of an unnamed union, the build will break (also in pv_inject_page_fault() then, for cr2 being switched at the same time) once again for old enough gcc.

I'm sick and tired of utterly obsolete compiler bugs stopping us writing good code.

It will break HVM #PF too, and I'll fix it for now as these patches need backporting, but I've got a very strong mind to intentionally break it next time this comes up in staging.

Quoted 11 lines
Quoted 11 lines
xen/arch/x86/pv/emulate.c +1 -3
@@ -71,11 +71,9 @@ void pv_emul_instruction_done(struct cpu_user_regs *regs, unsigned long rip)
 {
     regs->rip = rip;
     regs->eflags &= ~X86_EFLAGS_RF;
+
     if ( regs->eflags & X86_EFLAGS_TF )
-    {
-        current->arch.dr6 |= DR_STEP | DR_STATUS_RESERVED_ONE;
-        pv_inject_hw_exception(X86_EXC_DB, X86_EVENT_NO_EC);
Quoted 8 lines

xen/arch/x86/pv/emulate.c void pv_emul_instruction_done(struct cpu_user_regs *regs, unsigned long rip) · line 77

Quoted 3 lines
xen/arch/x86/pv/emulate.c +1 -1
-    }
+        pv_inject_DB(X86_DR6_BS);
 }

This (not your change, the construct) looks bogus at the first and second glance, because of looking at EFLAGS.TF after emulation, when the initial state of TF matters. It is only correct (at the third, closer look) because the function presently is used only from paths not altering the guest's EFLAGS. Do you think it would make sense to add a comment at this occasion?

It is buggy yes, but if you notice, so is SVM's __update_guest_eip() and VMX's update_guest_eip().

And remember that while for most instructions it's the initial state that matters, it's the final state that matters for SYSCALL/SYSRET, and each of LRET/IRET/ERET{U,S} have oddities that aren't currently expressed in the emulator.

I'll leave a todo for now.  This is a problem that can only reasonably be fixed by unifying the intercept and emulation paths into a coherent model of the instruction cycle.

~Andrew

#20 lore raw
In reply to Andrew Cooper
Quoted 2 lines · Andrew Cooper

Slightly RFC. This is the next chunk of debug fixes from the bug that Jinoh reported.

I was trying to do a bit of due diligence before posting v2, and have made some discoveries.

pv/emul-priv-op SingleStep vs Branch Step
  https://gitlab.com/xen-project/xen/-/work_items/170

HVM IO Breakpoints:
  https://gitlab.com/xen-project/xen/-/work_items/171

A third which I'm on the fence about is about PV guests and General Detect.  We firmly prohibit PV guests from setting DR7.GD, but we them play with the DR6.GD bit as if it had been asserted.

It would be easy to put GD back into the set of reserved bits for DR6, but it also wouldn't be hard to handle GD via dr7_emul and let the PV guest have a more-normal looking set of debug functionality.

Thoughts?

~Andrew

#21 lore raw
Quoted 7 lines · Andrew Cooper

A third which I'm on the fence about is about PV guests and General Detect.  We firmly prohibit PV guests from setting DR7.GD, but we them play with the DR6.GD bit as if it had been asserted.

It would be easy to put GD back into the set of reserved bits for DR6, but it also wouldn't be hard to handle GD via dr7_emul and let the PV guest have a more-normal looking set of debug functionality.

Anything "more-normal looking" is to be preferred, I would say. As long as, like you say here, it isn't overly hard.

Jan