Skip to contentSkip to conversation

virtual interrupt controller (vAPLIC/vIMSIC) support

PATCH Superseded Oleksii Kurochko 5 participants 251 messages Aug 27 – Sep 28 RISC-V Page 2 of 3

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#118 lore raw

Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest

In reply to Oleksii Kurochko
Quoted 7 lines

Some traps taken by Xen on behalf of a guest can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead: the access faults which handle_guest_page_fault() injects for a fault that can never become an emulated access, and, later on, a fault taken by the hlv/hlvx sequences of riscv_read_guest() while accessing guest memory on a vCPU's behalf.

Access faults from handle_guest_page_fault() aren't "taken by Xen on behalf of a guest" as those are guest-page faults taken directly from the guest's own execution. Xen just decides they can't be emulated and reflects them back as access faults. Only the hlv/hlvx case is Xen trapping on the guest's behalf (Xen itself executes the faulting access). Conflating the two under one description makes the paragraph confusing.

Suggest splitting into two:

Two kinds of traps can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead:

- Traps Xen takes on the guest's behalf: the hlv/hlvx sequences riscv_read_guest() uses to access guest memory.
- Access faults handle_guest_page_fault() injects for a guest-page fault that can never become an emulated access.

Quoted 32 lines

Implement trap_redirect(), until now a BUG_ON() placeholder, for that purpose. It makes the trap appear to the guest as if it had been taken directly in VS-mode: the trap information is transferred to the guest's virtual supervisor CSRs and the vCPU is resumed at its exception vector in supervisor mode, following the trap entry rules of the RISC-V privileged specification.

Add the STVEC_* definitions needed to tell the BASE and MODE fields of vstvec apart.

The implementation is based on kvm_riscv_vcpu_trap_redirect() from Linux, with a few deviations:
- The function reads and writes physical VS-mode CSRs, so it is only meaningful for the currently running vCPU. Instead of taking a struct vcpu argument, it always operates on current.
- The MODE field of vstvec is masked off explicitly when computing the exception target PC (exceptions always vector to BASE), rather than relying on the hardwired zero bit of sepc to drop it on VM entry.
- Assertions document the preconditions: the trap must have been taken from virtualized mode (hstatus.SPV set), and only synchronous exceptions may be redirected - interrupts must be injected via hvip instead, so that the hardware performs VS-mode trap entry itself, respecting vsstatus.SIE and vectored vstvec dispatch.

xen/arch/riscv/include/asm/riscv_encoding.h +0 -0
index 2d2e7e11b3..b2071f4758 100644

xen/arch/riscv/include/asm/riscv_encoding.h line 116

Quoted 8 lines
xen/arch/riscv/include/asm/riscv_encoding.h +5 -0
@@ -109,6 +109,12 @@
 #define SIP_SSIP			MIP_SSIP
 #define SIP_STIP			MIP_STIP
 
+/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */
+#define STVEC_MODE_MASK			_UL(0x3)
+#define STVEC_MODE_DIRECT		_UL(0x0)
+#define STVEC_MODE_VECTORED		_UL(0x1)
+#define STVEC_BASE_MASK			(~STVEC_MODE_MASK)

Nit: STVEC_MODE_DIRECT and STVEC_MODE_VECTORED aren't used anywhere in this patch (only STVEC_BASE_MASK is). Either use them where you decide exceptions always target BASE regardless of MODE, or drop them until a patch that needs them.

Signature · 1 line
Baptiste Le Duc <[email protected]>
#119 lore raw

Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest

Quoted 15 lines · Baptiste Le Duc
Quoted 7 lines

Some traps taken by Xen on behalf of a guest can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead: the access faults which handle_guest_page_fault() injects for a fault that can never become an emulated access, and, later on, a fault taken by the hlv/hlvx sequences of riscv_read_guest() while accessing guest memory on a vCPU's behalf.

Access faults from handle_guest_page_fault() aren't "taken by Xen on
behalf of a guest" as those are guest-page faults taken directly from the
guest's own execution. Xen just decides they can't be emulated and
reflects them back as access faults. Only the hlv/hlvx case is Xen
trapping on the guest's behalf (Xen itself executes the faulting access).> Conflating the two under one description makes the paragraph confusing.

Suggest splitting into two:

Quoted 7 lines

Two kinds of traps can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead:

- Traps Xen takes on the guest's behalf: the hlv/hlvx sequences riscv_read_guest() uses to access guest memory.
- Access faults handle_guest_page_fault() injects for a guest-page fault that can never become an emulated access.

Thanks, I'll update original paragraph with what you suggested.>

Quoted 35 lines
Quoted 35 lines

Implement trap_redirect(), until now a BUG_ON() placeholder, for that purpose. It makes the trap appear to the guest as if it had been taken directly in VS-mode: the trap information is transferred to the guest's virtual supervisor CSRs and the vCPU is resumed at its exception vector in supervisor mode, following the trap entry rules of the RISC-V privileged specification.

Add the STVEC_* definitions needed to tell the BASE and MODE fields of vstvec apart.

The implementation is based on kvm_riscv_vcpu_trap_redirect() from Linux, with a few deviations:
- The function reads and writes physical VS-mode CSRs, so it is only meaningful for the currently running vCPU. Instead of taking a struct vcpu argument, it always operates on current.
- The MODE field of vstvec is masked off explicitly when computing the exception target PC (exceptions always vector to BASE), rather than relying on the hardwired zero bit of sepc to drop it on VM entry.
- Assertions document the preconditions: the trap must have been taken from virtualized mode (hstatus.SPV set), and only synchronous exceptions may be redirected - interrupts must be injected via hvip instead, so that the hardware performs VS-mode trap entry itself, respecting vsstatus.SIE and vectored vstvec dispatch.

xen/arch/riscv/include/asm/riscv_encoding.h +0 -0
index 2d2e7e11b3..b2071f4758 100644
@@ -109,6 +109,12 @@
  #define SIP_SSIP			MIP_SSIP
  #define SIP_STIP			MIP_STIP
 
Quoted 9 lines

xen/arch/riscv/include/asm/riscv_encoding.h line 116

Quoted 5 lines
xen/arch/riscv/include/asm/riscv_encoding.h +5 -0
+/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */
+#define STVEC_MODE_MASK			_UL(0x3)
+#define STVEC_MODE_DIRECT		_UL(0x0)
+#define STVEC_MODE_VECTORED		_UL(0x1)
+#define STVEC_BASE_MASK			(~STVEC_MODE_MASK)

Nit: STVEC_MODE_DIRECT and STVEC_MODE_VECTORED aren't used anywhere in this patch (only STVEC_BASE_MASK is). Either use them where you decide exceptions always target BASE regardless of MODE, or drop them until a patch that needs them.

IMO it is fine to introduce *_DIRECT/VECORED here as they are used implicitly through STVEC_BASE_MASK and thereby it will be better to introduce them here now instead of open-code them and then just update STVEC_BASE_MASK again when *_DIRECT/VECORED will be re-introduced.

Thanks for review.

~ Oleksii

#120 lore raw

Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest

Quoted 71 lines · Oleksii Kurochko
Quoted 15 lines · Baptiste Le Duc
Quoted 7 lines

Some traps taken by Xen on behalf of a guest can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead: the access faults which handle_guest_page_fault() injects for a fault that can never become an emulated access, and, later on, a fault taken by the hlv/hlvx sequences of riscv_read_guest() while accessing guest memory on a vCPU's behalf.

Access faults from handle_guest_page_fault() aren't "taken by Xen on
behalf of a guest" as those are guest-page faults taken directly from the
guest's own execution. Xen just decides they can't be emulated and
reflects them back as access faults. Only the hlv/hlvx case is Xen
trapping on the guest's behalf (Xen itself executes the faulting access).> Conflating the two under one description makes the paragraph confusing.

Suggest splitting into two:

Quoted 7 lines

     Two kinds of traps can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead:

     - Traps Xen takes on the guest's behalf: the hlv/hlvx sequences riscv_read_guest() uses to access guest memory.
     - Access faults handle_guest_page_fault() injects for a guest-page fault that can never become an emulated access.

Thanks, I'll update original paragraph with what you suggested.>

Quoted 27 lines
Quoted 27 lines

Implement trap_redirect(), until now a BUG_ON() placeholder, for that purpose. It makes the trap appear to the guest as if it had been taken directly in VS-mode: the trap information is transferred to the guest's virtual supervisor CSRs and the vCPU is resumed at its exception vector in supervisor mode, following the trap entry rules of the RISC-V privileged specification.

Add the STVEC_* definitions needed to tell the BASE and MODE fields of vstvec apart.

The implementation is based on kvm_riscv_vcpu_trap_redirect() from Linux, with a few deviations:
  - The function reads and writes physical VS-mode CSRs, so it is only meaningful for the currently running vCPU. Instead of taking a struct vcpu argument, it always operates on current.
  - The MODE field of vstvec is masked off explicitly when computing the exception target PC (exceptions always vector to BASE), rather than relying on the hardwired zero bit of sepc to drop it on VM entry.
  - Assertions document the preconditions: the trap must have been taken from virtualized mode (hstatus.SPV set), and only synchronous exceptions may be redirected - interrupts must be injected via hvip instead, so that the hardware performs VS-mode trap entry itself, respecting vsstatus.SIE and vectored vstvec dispatch.

Quoted 16 lines

xen/arch/riscv/include/asm/riscv_encoding.h line 115

Quoted 12 lines
xen/arch/riscv/include/asm/riscv_encoding.h +5 -0
index 2d2e7e11b3..b2071f4758 100644
@@ -109,6 +109,12 @@
   #define SIP_SSIP            MIP_SSIP
   #define SIP_STIP            MIP_STIP
+/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */
+#define STVEC_MODE_MASK            _UL(0x3)
+#define STVEC_MODE_DIRECT        _UL(0x0)
+#define STVEC_MODE_VECTORED        _UL(0x1)
+#define STVEC_BASE_MASK            (~STVEC_MODE_MASK)

Nit: STVEC_MODE_DIRECT and STVEC_MODE_VECTORED aren't used anywhere in this patch (only STVEC_BASE_MASK is). Either use them where you decide exceptions always target BASE regardless of MODE, or drop them until a patch that needs them.

Quoted 2 lines

IMO it is fine to introduce *_DIRECT/VECORED here as they are used implicitly through STVEC_BASE_MASK and thereby it will be better to introduce them here now instead of open-code them and then just update STVEC_BASE_MASK again when *_DIRECT/VECORED will be re-introduced.

Oh, sorry, you are right. STVEC_MODE_DIRECT and STVEC_MODE_VECTORED are really not used here (in this implementation). I planned to do:

#define STVEC_MODE_MASK (STVEC_MODE_DIRECT | STVEC_MODE_VECTORED)

But I missed to do in that way.

I will update the defintion of STVEC_MODE_MASK in suggested above way.

~ Oleksii

#121 lore raw

Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest

Quoted 23 lines · Oleksii Kurochko
Quoted 16 lines · Oleksii Kurochko
Quoted 6 lines · Baptiste Le Duc
Quoted 6 lines
xen/arch/riscv/include/asm/riscv_encoding.h +1 -0
@@ -109,6 +109,12 @@
   #define SIP_SSIP            MIP_SSIP
   #define SIP_STIP            MIP_STIP
+/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */
Quoted 8 lines

xen/arch/riscv/include/asm/riscv_encoding.h line 116

Quoted 4 lines
xen/arch/riscv/include/asm/riscv_encoding.h +4 -0
+#define STVEC_MODE_MASK            _UL(0x3)
+#define STVEC_MODE_DIRECT        _UL(0x0)
+#define STVEC_MODE_VECTORED        _UL(0x1)
+#define STVEC_BASE_MASK            (~STVEC_MODE_MASK)

Nit: STVEC_MODE_DIRECT and STVEC_MODE_VECTORED aren't used anywhere in this patch (only STVEC_BASE_MASK is). Either use them where you decide exceptions always target BASE regardless of MODE, or drop them until a patch that needs them.

Quoted 5 lines

IMO it is fine to introduce *_DIRECT/VECORED here as they are used implicitly through STVEC_BASE_MASK and thereby it will be better to introduce them here now instead of open-code them and then just update STVEC_BASE_MASK again when *_DIRECT/VECORED will be re-introduced.

Quoted 8 lines

Oh, sorry, you are right. STVEC_MODE_DIRECT and STVEC_MODE_VECTORED are really not used here (in this implementation). I planned to do:

#define STVEC_MODE_MASK (STVEC_MODE_DIRECT | STVEC_MODE_VECTORED)

But I missed to do in that way.

I will update the defintion of STVEC_MODE_MASK in suggested above way.

But that's yield a mask value of 1, when you want it to be 3. That ORing together looks bogus to me anyway.

Jan

#122 lore raw

Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest

Quoted 27 lines · Jan Beulich
Quoted 26 lines · Oleksii Kurochko
Quoted 16 lines · Oleksii Kurochko
Quoted 6 lines · Baptiste Le Duc
Quoted 6 lines
xen/arch/riscv/include/asm/riscv_encoding.h +1 -0
@@ -109,6 +109,12 @@
   #define SIP_SSIP            MIP_SSIP
   #define SIP_STIP            MIP_STIP
+/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */
Quoted 8 lines

xen/arch/riscv/include/asm/riscv_encoding.h line 116

Quoted 4 lines
xen/arch/riscv/include/asm/riscv_encoding.h +4 -0
+#define STVEC_MODE_MASK            _UL(0x3)
+#define STVEC_MODE_DIRECT        _UL(0x0)
+#define STVEC_MODE_VECTORED        _UL(0x1)
+#define STVEC_BASE_MASK            (~STVEC_MODE_MASK)

Nit: STVEC_MODE_DIRECT and STVEC_MODE_VECTORED aren't used anywhere in this patch (only STVEC_BASE_MASK is). Either use them where you decide exceptions always target BASE regardless of MODE, or drop them until a patch that needs them.

Quoted 5 lines

IMO it is fine to introduce *_DIRECT/VECORED here as they are used implicitly through STVEC_BASE_MASK and thereby it will be better to introduce them here now instead of open-code them and then just update STVEC_BASE_MASK again when *_DIRECT/VECORED will be re-introduced.

Oh, sorry, you are right. STVEC_MODE_DIRECT and STVEC_MODE_VECTORED are really not used here (in this implementation). I planned to do:

Quoted 9 lines
Quoted 5 lines

#define STVEC_MODE_MASK (STVEC_MODE_DIRECT | STVEC_MODE_VECTORED)

But I missed to do in that way.

I will update the defintion of STVEC_MODE_MASK in suggested above way.

But that's yield a mask value of 1, when you want it to be 3. That ORing together looks bogus to me anyway.

Yes I agree. It might be enough, for the moment, to only keep #define STVEC_MODE_MASK _UL(3) and drop the others defines (even STVEC_BASE_MASK as Jan mentioned the comment in the caller is already precise enough).

Quoted 4 lines

Jan

#123 lore raw

Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest

Quoted 32 lines · Baptiste Le Duc
Quoted 31 lines · Jan Beulich
Quoted 30 lines · Oleksii Kurochko
Quoted 16 lines · Oleksii Kurochko
Quoted 6 lines · Baptiste Le Duc
Quoted 6 lines
xen/arch/riscv/include/asm/riscv_encoding.h +1 -0
@@ -109,6 +109,12 @@
   #define SIP_SSIP            MIP_SSIP
   #define SIP_STIP            MIP_STIP
+/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */
Quoted 8 lines

xen/arch/riscv/include/asm/riscv_encoding.h line 116

Quoted 4 lines
xen/arch/riscv/include/asm/riscv_encoding.h +4 -0
+#define STVEC_MODE_MASK            _UL(0x3)
+#define STVEC_MODE_DIRECT        _UL(0x0)
+#define STVEC_MODE_VECTORED        _UL(0x1)
+#define STVEC_BASE_MASK            (~STVEC_MODE_MASK)

Nit: STVEC_MODE_DIRECT and STVEC_MODE_VECTORED aren't used anywhere in this patch (only STVEC_BASE_MASK is). Either use them where you decide exceptions always target BASE regardless of MODE, or drop them until a patch that needs them.

Quoted 5 lines

IMO it is fine to introduce *_DIRECT/VECORED here as they are used implicitly through STVEC_BASE_MASK and thereby it will be better to introduce them here now instead of open-code them and then just update STVEC_BASE_MASK again when *_DIRECT/VECORED will be re-introduced.

Oh, sorry, you are right. STVEC_MODE_DIRECT and STVEC_MODE_VECTORED are really not used here (in this implementation). I planned to do:

#define STVEC_MODE_MASK (STVEC_MODE_DIRECT | STVEC_MODE_VECTORED)

But I missed to do in that way.

Quoted 8 lines
Quoted 5 lines
Quoted 1 line

I will update the defintion of STVEC_MODE_MASK in suggested above way.

But that's yield a mask value of 1, when you want it to be 3. That ORing together looks bogus to me anyway.

Yes I agree. It might be enough, for the moment, to only keep #define STVEC_MODE_MASK _UL(3) and drop the others defines (even STVEC_BASE_MASK as Jan mentioned the comment in the caller is already precise enough).

To me having STVEC_MODE_MASK without at least one of STVEC_MODE_{DIRECT,VECTORED} would feel odd / incomplete.

Jan

#124 lore raw

Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest

In reply to Oleksii Kurochko

xen/arch/riscv/include/asm/riscv_encoding.h line 115

Quoted 10 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/riscv_encoding.h +4 -0
@@ -109,6 +109,12 @@
 #define SIP_SSIP			MIP_SSIP
 #define SIP_STIP			MIP_STIP
 
+/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */
+#define STVEC_MODE_MASK			_UL(0x3)
+#define STVEC_MODE_DIRECT		_UL(0x0)
+#define STVEC_MODE_VECTORED		_UL(0x1)

As on earlier occasions: Do the 0x here actually add any value? There are none ...

xen/arch/riscv/include/asm/riscv_encoding.h line 120

Quoted 5 lines
xen/arch/riscv/include/asm/riscv_encoding.h +2 -0
+#define STVEC_BASE_MASK			(~STVEC_MODE_MASK)
+
 #define PRV_U				_UL(0)
 #define PRV_S				_UL(1)
 #define PRV_M				_UL(3)

... here, for example.

Quoted 43 lines
xen/arch/riscv/traps.c +36 -1
@@ -294,5 +294,53 @@ enum mc_disposition arch_do_multicall_call(struct mc_state *state)
 /* Redirect trap to Guest. */
 void trap_redirect(const struct trap_info *trap)
 {
-    BUG_ON("unimplemented");
+    struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);
+    unsigned long vsstatus = csr_read(CSR_VSSTATUS);
+
+    /*
+     * Redirecting a trap makes sense only if the trap was taken from
+     * virtualized mode, i.e. sret is going to return to VS-mode.
+     */
+    ASSERT(regs->hstatus & HSTATUS_SPV);
+
+    /*
+     * Only synchronous exceptions can be redirected. Interrupts must be
+     * injected via hvip instead, so that the hardware itself performs
+     * VS-mode trap entry, respecting vsstatus.SIE and the vectored
+     * dispatch (BASE + 4 * cause) if vstvec is configured so.
+     */
+    ASSERT(!(trap->scause & CAUSE_IRQ_FLAG));
+
+    /* Change Guest SSTATUS.SPP bit */
+    vsstatus &= ~SSTATUS_SPP;
+    if ( regs->sstatus & SSTATUS_SPP )
+        vsstatus |= SSTATUS_SPP;
+
+    /* Change Guest SSTATUS.SPIE bit */
+    vsstatus &= ~SSTATUS_SPIE;
+    if ( vsstatus & SSTATUS_SIE )
+        vsstatus |= SSTATUS_SPIE;
+
+    /* Clear Guest SSTATUS.SIE bit */
+    vsstatus &= ~SSTATUS_SIE;
+
+    /* Update Guest SSTATUS */
+    csr_write(CSR_VSSTATUS, vsstatus);
+
+    /* Update Guest SCAUSE, STVAL, and SEPC */
+    csr_write(CSR_VSCAUSE, trap->scause);
+    csr_write(CSR_VSTVAL, trap->stval);

xen/arch/riscv/traps.c enum mc_disposition arch_do_multicall_call(struct mc_state *state) · line 342

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+    csr_write(CSR_VSEPC, trap->sepc);
+
+    /*
+     * Set Guest PC to Guest exception vector.
+     *
+     * vstvec's MODE field is not part of the address. Exceptions always
+     * target BASE regardless of MODE, so mask it off explicitly instead of
+     * relying on the hardwired zero bit of sepc to drop it.
+     */
+    regs->sepc = csr_read(CSR_VSTVEC) & STVEC_BASE_MASK;

Nit: Given how much the comment talks about MODE, imo using ~STVEC_MODE_MASK here directly (and dropping STVEC_BASE_MASK) might be better.

Jan

#125 lore raw

Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest

Quoted 15 lines · Jan Beulich

xen/arch/riscv/include/asm/riscv_encoding.h line 115

Quoted 10 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/riscv_encoding.h +4 -0
@@ -109,6 +109,12 @@
  #define SIP_SSIP			MIP_SSIP
  #define SIP_STIP			MIP_STIP
 
+/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */
+#define STVEC_MODE_MASK			_UL(0x3)
+#define STVEC_MODE_DIRECT		_UL(0x0)
+#define STVEC_MODE_VECTORED		_UL(0x1)

As on earlier occasions: Do the 0x here actually add any value? There are none ...

Quoted 7 lines

xen/arch/riscv/include/asm/riscv_encoding.h line 120

Quoted 5 lines
xen/arch/riscv/include/asm/riscv_encoding.h +2 -0
+#define STVEC_BASE_MASK			(~STVEC_MODE_MASK)
+
  #define PRV_U				_UL(0)
  #define PRV_S				_UL(1)
  #define PRV_M				_UL(3)

... here, for example.

Agree, not too much sense.

Quoted 49 lines
Quoted 49 lines
xen/arch/riscv/traps.c +41 -1
@@ -294,5 +294,53 @@ enum mc_disposition arch_do_multicall_call(struct mc_state *state)
  /* Redirect trap to Guest. */
  void trap_redirect(const struct trap_info *trap)
  {
-    BUG_ON("unimplemented");
+    struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);
+    unsigned long vsstatus = csr_read(CSR_VSSTATUS);
+
+    /*
+     * Redirecting a trap makes sense only if the trap was taken from
+     * virtualized mode, i.e. sret is going to return to VS-mode.
+     */
+    ASSERT(regs->hstatus & HSTATUS_SPV);
+
+    /*
+     * Only synchronous exceptions can be redirected. Interrupts must be
+     * injected via hvip instead, so that the hardware itself performs
+     * VS-mode trap entry, respecting vsstatus.SIE and the vectored
+     * dispatch (BASE + 4 * cause) if vstvec is configured so.
+     */
+    ASSERT(!(trap->scause & CAUSE_IRQ_FLAG));
+
+    /* Change Guest SSTATUS.SPP bit */
+    vsstatus &= ~SSTATUS_SPP;
+    if ( regs->sstatus & SSTATUS_SPP )
+        vsstatus |= SSTATUS_SPP;
+
+    /* Change Guest SSTATUS.SPIE bit */
+    vsstatus &= ~SSTATUS_SPIE;
+    if ( vsstatus & SSTATUS_SIE )
+        vsstatus |= SSTATUS_SPIE;
+
+    /* Clear Guest SSTATUS.SIE bit */
+    vsstatus &= ~SSTATUS_SIE;
+
+    /* Update Guest SSTATUS */
+    csr_write(CSR_VSSTATUS, vsstatus);
+
+    /* Update Guest SCAUSE, STVAL, and SEPC */
+    csr_write(CSR_VSCAUSE, trap->scause);
+    csr_write(CSR_VSTVAL, trap->stval);
+    csr_write(CSR_VSEPC, trap->sepc);
+
+    /*
+     * Set Guest PC to Guest exception vector.
+     *
Quoted 9 lines

xen/arch/riscv/traps.c enum mc_disposition arch_do_multicall_call(struct mc_state *state) · line 342

Quoted 5 lines
xen/arch/riscv/traps.c +5 -0
+     * vstvec's MODE field is not part of the address. Exceptions always
+     * target BASE regardless of MODE, so mask it off explicitly instead of
+     * relying on the hardwired zero bit of sepc to drop it.
+     */
+    regs->sepc = csr_read(CSR_VSTVEC) & STVEC_BASE_MASK;

Nit: Given how much the comment talks about MODE, imo using ~STVEC_MODE_MASK here directly (and dropping STVEC_BASE_MASK) might be better.

Agree, it could be dropped. I will update that in v3.

Thanks.

~ Oleksii

#126 lore raw

Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest

In reply to Oleksii Kurochko

xen/arch/riscv/include/asm/riscv_encoding.h line 115

Quoted 10 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/riscv_encoding.h +4 -0
@@ -109,6 +109,12 @@
 #define SIP_SSIP			MIP_SSIP
 #define SIP_STIP			MIP_STIP
 
+/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */
+#define STVEC_MODE_MASK			_UL(0x3)
+#define STVEC_MODE_DIRECT		_UL(0x0)
+#define STVEC_MODE_VECTORED		_UL(0x1)

As on earlier occasions: Do the 0x here actually add any value? There are none ...

xen/arch/riscv/include/asm/riscv_encoding.h line 120

Quoted 5 lines
xen/arch/riscv/include/asm/riscv_encoding.h +2 -0
+#define STVEC_BASE_MASK			(~STVEC_MODE_MASK)
+
 #define PRV_U				_UL(0)
 #define PRV_S				_UL(1)
 #define PRV_M				_UL(3)

... here, for example.

Quoted 43 lines
xen/arch/riscv/traps.c +36 -1
@@ -294,5 +294,53 @@ enum mc_disposition arch_do_multicall_call(struct mc_state *state)
 /* Redirect trap to Guest. */
 void trap_redirect(const struct trap_info *trap)
 {
-    BUG_ON("unimplemented");
+    struct cpu_user_regs *regs = vcpu_guest_cpu_user_regs(current);
+    unsigned long vsstatus = csr_read(CSR_VSSTATUS);
+
+    /*
+     * Redirecting a trap makes sense only if the trap was taken from
+     * virtualized mode, i.e. sret is going to return to VS-mode.
+     */
+    ASSERT(regs->hstatus & HSTATUS_SPV);
+
+    /*
+     * Only synchronous exceptions can be redirected. Interrupts must be
+     * injected via hvip instead, so that the hardware itself performs
+     * VS-mode trap entry, respecting vsstatus.SIE and the vectored
+     * dispatch (BASE + 4 * cause) if vstvec is configured so.
+     */
+    ASSERT(!(trap->scause & CAUSE_IRQ_FLAG));
+
+    /* Change Guest SSTATUS.SPP bit */
+    vsstatus &= ~SSTATUS_SPP;
+    if ( regs->sstatus & SSTATUS_SPP )
+        vsstatus |= SSTATUS_SPP;
+
+    /* Change Guest SSTATUS.SPIE bit */
+    vsstatus &= ~SSTATUS_SPIE;
+    if ( vsstatus & SSTATUS_SIE )
+        vsstatus |= SSTATUS_SPIE;
+
+    /* Clear Guest SSTATUS.SIE bit */
+    vsstatus &= ~SSTATUS_SIE;
+
+    /* Update Guest SSTATUS */
+    csr_write(CSR_VSSTATUS, vsstatus);
+
+    /* Update Guest SCAUSE, STVAL, and SEPC */
+    csr_write(CSR_VSCAUSE, trap->scause);
+    csr_write(CSR_VSTVAL, trap->stval);

xen/arch/riscv/traps.c enum mc_disposition arch_do_multicall_call(struct mc_state *state) · line 342

Quoted 10 lines
xen/arch/riscv/traps.c +10 -0
+    csr_write(CSR_VSEPC, trap->sepc);
+
+    /*
+     * Set Guest PC to Guest exception vector.
+     *
+     * vstvec's MODE field is not part of the address. Exceptions always
+     * target BASE regardless of MODE, so mask it off explicitly instead of
+     * relying on the hardwired zero bit of sepc to drop it.
+     */
+    regs->sepc = csr_read(CSR_VSTVEC) & STVEC_BASE_MASK;

Nit: Given how much the comment talks about MODE, imo using ~STVEC_MODE_MASK here directly (and dropping STVEC_BASE_MASK) might be better.

Jan

#127 lore raw

PATCH v2 20/39 xen/riscv: detect Shtvala

In reply to Oleksii Kurochko

Shtvala says that htval is written with the faulting guest physical address on a guest-page fault. The H extension itself allows an implementation to write htval with either that address or with zero, so where the extension is absent a zero htval cannot be told apart from a genuine fault on guest physical address 0-3.

It is not offered to guests. Shtvala describes the HS-mode trap interface, which a VS-mode guest never sees, and the H extension it belongs to is already withheld from guests. Its guest-facing counterpart is a separate extension, Shvstvala.

---
Change in v2:
- New patch.
---

---
 xen/arch/riscv/cpufeature.c             | 1 +
 xen/arch/riscv/include/asm/cpufeature.h | 1 +
 2 files changed, 2 insertions(+)
xen/arch/riscv/cpufeature.c +1 -0
index 4bcbf56cb694..09a06f12318c 100644
@@ -195,6 +195,7 @@ static const struct riscv_isa_ext_entry __initconstrel riscv_isa_ext[] = {
     RISCV_ISA_EXT_ENTRY(zba,          RISCV_ISA_EXT_GUEST_ANY),
     RISCV_ISA_EXT_ENTRY(zbb,          RISCV_ISA_EXT_GUEST_ANY),
     RISCV_ISA_EXT_ENTRY(zbs,          RISCV_ISA_EXT_GUEST_ANY),
+    RISCV_ISA_EXT_ENTRY(shtvala,      RISCV_ISA_EXT_GUEST_NONE),
     RISCV_ISA_EXT_ENTRY(smaia,        RISCV_ISA_EXT_GUEST_ANY),
     RISCV_ISA_EXT_ENTRY(smstateen,    RISCV_ISA_EXT_GUEST_ANY),
     RISCV_ISA_EXT_ENTRY(ssaia,        RISCV_ISA_EXT_GUEST_ANY),
xen/arch/riscv/include/asm/cpufeature.h +1 -0
index 2973eb13a513..ac8c68007072 100644
@@ -36,6 +36,7 @@ enum riscv_isa_ext_id {
     RISCV_ISA_EXT_zba,
     RISCV_ISA_EXT_zbb,
     RISCV_ISA_EXT_zbs,
+    RISCV_ISA_EXT_shtvala,
     RISCV_ISA_EXT_smaia,
     RISCV_ISA_EXT_smstateen,
     RISCV_ISA_EXT_ssaia,
Signature · 1 line
2.55.0
#128 lore raw

Re: [PATCH v2 20/39] xen/riscv: detect Shtvala

Quoted 6 lines

Shtvala says that htval is written with the faulting guest physical address on a guest-page fault. The H extension itself allows an implementation to write htval with either that address or with zero, so where the extension is absent a zero htval cannot be told apart from a genuine fault on guest physical address 0-3.

Quoted 7 lines

It is not offered to guests. Shtvala describes the HS-mode trap interface, which a VS-mode guest never sees, and the H extension it belongs to is already withheld from guests. Its guest-facing counterpart is a separate extension, Shvstvala.

I thought this commit message is not very clear. Here is a more direct suggestion:

```
The H extension allows htval, on a guest-page fault, to be written with
either the faulting guest physical address or zero. Shtvala extension
removes the ambiguity of this zero-write by guaranteeing that htval is
written with the faulting guest physical address in every circumstance
permitted by the ISA.

Not offered to guests: Shtvala describes htval, an HS-mode-only trap
register a VS-mode guest never touches and the H extension it belongs to
is already hidden from guests. The guest-visible equivalent is a
separate extension, Shvstvala, covering vstval instead.
```

Btw, I saw Linux has Documentation/devicetree/bindings/riscv/extensions.yaml which describes all of the extensions supported, don't you think it would be useful to have the same in docs/misc/devicetree/...?

Signature · 1 line
Baptiste Le Duc <[email protected]>
#129 lore raw

Re: [PATCH v2 20/39] xen/riscv: detect Shtvala

Quoted 16 lines · Baptiste Le Duc
Quoted 6 lines

Shtvala says that htval is written with the faulting guest physical address on a guest-page fault. The H extension itself allows an implementation to write htval with either that address or with zero, so where the extension is absent a zero htval cannot be told apart from a genuine fault on guest physical address 0-3.

Quoted 7 lines

It is not offered to guests. Shtvala describes the HS-mode trap interface, which a VS-mode guest never sees, and the H extension it belongs to is already withheld from guests. Its guest-facing counterpart is a separate extension, Shvstvala.

I thought this commit message is not very clear. Here is a more direct suggestion:

Quoted 12 lines
```
The H extension allows htval, on a guest-page fault, to be written with
either the faulting guest physical address or zero. Shtvala extension
removes the ambiguity of this zero-write by guaranteeing that htval is
written with the faulting guest physical address in every circumstance
permitted by the ISA.

Not offered to guests: Shtvala describes htval, an HS-mode-only trap
register a VS-mode guest never touches and the H extension it belongs to
is already hidden from guests. The guest-visible equivalent is a
separate extension, Shvstvala, covering vstval instead.
```

Sounds good to me. I will apply your suggestion.

Quoted 4 lines

Btw, I saw Linux has Documentation/devicetree/bindings/riscv/extensions.yaml which describes all of the extensions supported, don't you think it would be useful to have the same in docs/misc/devicetree/...?

I think it could be useful.

I think also about booting.txt already exitsted in the codebase. Would you be okay with that? I think I will add the section to booting.txt and pointing to riscv_isa_ext[] in cpufeature.c and so we won't miss an update of doc if we will add or remove support of an extension. Does it sound good to you?

~ Oleksii

#130 lore raw

Re: [PATCH v2 20/39] xen/riscv: detect Shtvala

Quoted 39 lines · Oleksii Kurochko
Quoted 16 lines · Baptiste Le Duc
Quoted 6 lines

Shtvala says that htval is written with the faulting guest physical address on a guest-page fault. The H extension itself allows an implementation to write htval with either that address or with zero, so where the extension is absent a zero htval cannot be told apart from a genuine fault on guest physical address 0-3.

Quoted 7 lines

It is not offered to guests. Shtvala describes the HS-mode trap interface, which a VS-mode guest never sees, and the H extension it belongs to is already withheld from guests. Its guest-facing counterpart is a separate extension, Shvstvala.

I thought this commit message is not very clear. Here is a more direct suggestion:

Quoted 12 lines
```
The H extension allows htval, on a guest-page fault, to be written with
either the faulting guest physical address or zero. Shtvala extension
removes the ambiguity of this zero-write by guaranteeing that htval is
written with the faulting guest physical address in every circumstance
permitted by the ISA.

Not offered to guests: Shtvala describes htval, an HS-mode-only trap
register a VS-mode guest never touches and the H extension it belongs to
is already hidden from guests. The guest-visible equivalent is a
separate extension, Shvstvala, covering vstval instead.
```

Sounds good to me. I will apply your suggestion.

Quoted 4 lines

Btw, I saw Linux has Documentation/devicetree/bindings/riscv/extensions.yaml which describes all of the extensions supported, don't you think it would be useful to have the same in docs/misc/devicetree/...?

Quoted 8 lines

I think it could be useful.

I think also about booting.txt already exitsted in the codebase. Would you be okay with that? I think I will add the section to booting.txt and pointing to riscv_isa_ext[] in cpufeature.c and so we won't miss an update of doc if we will add or remove support of an extension. Does it sound good to you?

Yes it sounds okay!
Thanks

Quoted 5 lines

~ Oleksii

#131 lore raw

PATCH v2 21/39 xen/riscv: resolve the faulting guest physical address

In reply to Oleksii Kurochko

Take the guest physical address from htval and stval: on a guest-page fault htval holds it shifted right by 2, so that an address wider than XLEN fits, and stval holds the faulting guest virtual address, whose two least significant bits are those of the guest physical address. The shift is done on paddr_t rather than on the raw register: a guest physical address is 34 bits wide on RV32 with Sv32x4, so shifting an XLEN-wide value would drop its top two bits.

Those two low bits come from stval only for a fault on an explicit access. Where one is taken on an implicit access made for VS-stage translation htval holds the address of the VS-stage PTE which could not be read, while stval still holds the guest virtual address which started the walk, and the low bits of the address written to htval are zero instead. htinst tells the two apart, which is what the spec points at it for.

stval needs no check against an ISA extension: a guest-page fault writes it with the faulting guest virtual address regardless. Sstvala would not be the right thing to test for either (it covers stval across every trap type which writes it, a wider guarantee than what is needed here).

htval does need one. The H extension lets an implementation write it with either the faulting address or zero, so without Shtvala a zero htval cannot be told apart from a genuine fault on guest physical address 0-3, and the address has to be recovered by decoding the access and walking the VS-stage page tables in software instead. That is left as a TODO, and until it is written such hardware panics rather than acting on an address which may not be the one which faulted.

---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/emulate.c | 23 +++++++++++++++++++++--
 1 file changed, 21 insertions(+), 2 deletions(-)
xen/arch/riscv/emulate.c +21 -2
index f9da0751049c..ff530ef2df74 100644
@@ -9,6 +9,7 @@
 #include <xen/sched.h>
 #include <xen/types.h>
 
+#include <asm/cpufeature.h>
 #include <asm/csr.h>
 #include <asm/current.h>
 #include <asm/emulate.h>
@@ -62,10 +63,28 @@ static bool htinst_is_pseudo(unsigned long htinst)
     }
 }
 
-/* Reconstruct the guest physical address of the access which faulted. */
+/* Resolves the guest physical address the access faulted on into @gf->gpa. */
 static void resolve_faulting_gpa(struct guest_fault *gf)
 {
-    BUG_ON("unimplemented");
+    /*
+     * A zero htval is either a genuine fault on guest physical address 0-3, or
+     * an implementation which does not report the address at all; only Shtvala
+     * tells the two apart.
+     *
+     * TODO: where it is absent, recover the address in software rather than
+     * giving up.
+     */
+    if ( !gf->htval &&
+         !riscv_isa_extension_available(NULL, RISCV_ISA_EXT_shtvala) )
+        panic("Shtvala isn't supported by h/w; s/w VS-stage walk required\n");
+
+    /*
+     * htval does not carry the two low bits of the address: for an explicit
+     * access they are those of the faulting guest virtual address in stval,
+     * and for an implicit access made for VS-stage translation they are zero.
+     */
+    gf->gpa = ((paddr_t)gf->htval << 2) |
+              (htinst_is_pseudo(gf->htinst) ? 0 : (gf->stval & 3));
 }
 
 static int emulate_load(const struct guest_fault *gf)
Signature · 1 line
2.55.0
#132 lore raw

Re: [PATCH v2 21/39] xen/riscv: resolve the faulting guest physical address

Quoted 8 lines

Take the guest physical address from htval and stval: on a guest-page fault htval holds it shifted right by 2, so that an address wider than XLEN fits, and stval holds the faulting guest virtual address, whose two least significant bits are those of the guest physical address. The shift is done on paddr_t rather than on the raw register: a guest physical address is 34 bits wide on RV32 with Sv32x4, so shifting an XLEN-wide value would drop its top two bits.

Quoted 7 lines

Those two low bits come from stval only for a fault on an explicit access. Where one is taken on an implicit access made for VS-stage translation htval holds the address of the VS-stage PTE which could not be read, while stval still holds the guest virtual address which started the walk, and the low bits of the address written to htval are zero instead. htinst tells the two apart, which is what the spec points at it for.

I'd just precise (the spec is also not clear on this point though), what is "current XLEN" here, clearly indicate that htval holds the GPA >> 2 and stval holds VGA and also put the two different cases we need to distinguish clearly:

```
Recover the guest physical address from htval and stval. On a guest-page
fault to hypervisor, htval holds the guest physical address shifted
right by 2, so that an address wider than HSXLEN fits, and stval holds
the faulting guest virtual address. The shift is done on paddr_t rather
than on the raw register: a guest physical address is 34 bits wide on
RV32 with Sv32x4, so shifting an XLEN-wide value would drop its top two
bits.

However, there are two cases to distinguish when recovering the
faulting GPA:
    - Explicit memory access: we use the two least significant bits of
    stval, which are the same as those of the guest physical
    address.
    - Implicit memory access for VS-stage translation: the two least
    significant bits of htval are zero.

These two cases can be distinguished using the value provided in
register htinst.
```
Quoted 29 lines

stval needs no check against an ISA extension: a guest-page fault writes it with the faulting guest virtual address regardless. Sstvala would not be the right thing to test for either (it covers stval across every trap type which writes it, a wider guarantee than what is needed here).

htval does need one. The H extension lets an implementation write it with either the faulting address or zero, so without Shtvala a zero htval cannot be told apart from a genuine fault on guest physical address 0-3, and the address has to be recovered by decoding the access and walking the VS-stage page tables in software instead. That is left as a TODO, and until it is written such hardware panics rather than acting on an address which may not be the one which faulted.

xen/arch/riscv/emulate.c +1 -0
index f9da075104..ff530ef2df 100644
@@ -9,6 +9,7 @@
 #include <xen/sched.h>
 #include <xen/types.h>
 
+#include <asm/cpufeature.h>
 #include <asm/csr.h>
 #include <asm/current.h>
 #include <asm/emulate.h>

xen/arch/riscv/emulate.c static bool htinst_is_pseudo(unsigned long htinst) · line 66

Quoted 5 lines
xen/arch/riscv/emulate.c +1 -1
@@ -62,10 +63,28 @@ static bool htinst_is_pseudo(unsigned long htinst)
     }
 }
 
-/* Reconstruct the guest physical address of the access which faulted. */
+/* Resolves the guest physical address the access faulted on into @gf->gpa. */

Why did you change the comment apart for adding @gf->gpa? I think the "reconstruct" is more clear but there might be another reason why you changed it.

Signature · 1 line
Baptiste Le Duc <[email protected]>
#133 lore raw

Re: [PATCH v2 21/39] xen/riscv: resolve the faulting guest physical address

Quoted 15 lines · Baptiste Le Duc
Quoted 8 lines

Take the guest physical address from htval and stval: on a guest-page fault htval holds it shifted right by 2, so that an address wider than XLEN fits, and stval holds the faulting guest virtual address, whose two least significant bits are those of the guest physical address. The shift is done on paddr_t rather than on the raw register: a guest physical address is 34 bits wide on RV32 with Sv32x4, so shifting an XLEN-wide value would drop its top two bits.

Quoted 7 lines

Those two low bits come from stval only for a fault on an explicit access. Where one is taken on an implicit access made for VS-stage translation htval holds the address of the VS-stage PTE which could not be read, while stval still holds the guest virtual address which started the walk, and the low bits of the address written to htval are zero instead. htinst tells the two apart, which is what the spec points at it for.

Quoted 2 lines

I'd just precise (the spec is also not clear on this point though), what is "current XLEN" here, clearly indicate that htval holds the GPA >> 2 and

My understanding was that "current XLEN" == hypervisor XLEN as htval is hypervisor register and has HSXLEN size so it was okay for me to have just XLEN in the original commit message. But I am okay to use your suggestion ...

Quoted 6 lines

stval holds VGA and also put the two different cases we need to distinguish clearly:
```
Recover the guest physical address from htval and stval. On a guest-page fault to hypervisor, htval holds the guest physical address shifted right by 2, so that an address wider than HSXLEN fits, and stval holds

... here.

Quoted 5 lines

the faulting guest virtual address. The shift is done on paddr_t rather than on the raw register: a guest physical address is 34 bits wide on RV32 with Sv32x4, so shifting an XLEN-wide value would drop its top two bits.

Quoted 7 lines

However, there are two cases to distinguish when recovering the faulting GPA:
- Explicit memory access: we use the two least significant bits of stval, which are the same as those of the guest physical address.
- Implicit memory access for VS-stage translation: the two least significant bits of htval are zero.

The original phrasing "the two least significant bits of htval are zero" is inaccurate for the following reasons:
- htval holds a shifted address (GPA >> 2): The htval CSR stores the faulting Guest Physical Address (GPA) shifted right by 2 bits. As a result, the two least significant bits of htval (htval[1:0]) actually correspond to bits 2 and 3 of the original GPA (GPA[3:2]).

- htval bits are not guaranteed to be zero: Implicit memory accesses during VS-stage address translation fetch PTEs that are 4-byte aligned (Sv32) or 8-byte aligned (Sv39/Sv48/Sv57). Since PTEs can reside at offsets like 0x04, 0x08, or 0x0C, GPA (and therefore htval[1:0]) can be non-zero.

- What is actually guaranteed to be zero: Because all VS-stage PTE accesses are at least 4-byte aligned, it is the lowest two bits of the unshifted Guest Physical Address (GPA[1:0]) that are guaranteed to be 00, not the low bits of htval.

So here I think we want to clarify then:

```
Implicit memory access for VS-stage translation: the two least significant bits of the guest physical address (GPA[1:0]) are zero
```
Quoted 36 lines

These two cases can be distinguished using the value provided in register htinst.
```

Quoted 32 lines

stval needs no check against an ISA extension: a guest-page fault writes it with the faulting guest virtual address regardless. Sstvala would not be the right thing to test for either (it covers stval across every trap type which writes it, a wider guarantee than what is needed here).

htval does need one. The H extension lets an implementation write it with either the faulting address or zero, so without Shtvala a zero htval cannot be told apart from a genuine fault on guest physical address 0-3, and the address has to be recovered by decoding the access and walking the VS-stage page tables in software instead. That is left as a TODO, and until it is written such hardware panics rather than acting on an address which may not be the one which faulted.

xen/arch/riscv/emulate.c +1 -0
index f9da075104..ff530ef2df 100644
@@ -9,6 +9,7 @@
  #include <xen/sched.h>
  #include <xen/types.h>
 
+#include <asm/cpufeature.h>
  #include <asm/csr.h>
  #include <asm/current.h>
  #include <asm/emulate.h>
@@ -62,10 +63,28 @@ static bool htinst_is_pseudo(unsigned long htinst)
      }
  }
 
Quoted 6 lines

xen/arch/riscv/emulate.c static bool htinst_is_pseudo(unsigned long htinst) · line 66

Quoted 2 lines
xen/arch/riscv/emulate.c +1 -1
-/* Reconstruct the guest physical address of the access which faulted. */
+/* Resolves the guest physical address the access faulted on into @gf->gpa. */

Why did you change the comment apart for adding @gf->gpa? I think the "reconstruct" is more clear but there might be another reason why you changed it.

I thought that it will just a little bit clearer (and anyway it should a part of another patch...) so I will revert the change here and go with "reconstruct".

Thanks.

~ Oleksii

Acked-by on v2 21/39
#134 lore raw

Re: [PATCH v2 21/39] xen/riscv: resolve the faulting guest physical address

In reply to Oleksii Kurochko
Quoted 28 lines · Oleksii Kurochko

Take the guest physical address from htval and stval: on a guest-page fault htval holds it shifted right by 2, so that an address wider than XLEN fits, and stval holds the faulting guest virtual address, whose two least significant bits are those of the guest physical address. The shift is done on paddr_t rather than on the raw register: a guest physical address is 34 bits wide on RV32 with Sv32x4, so shifting an XLEN-wide value would drop its top two bits.

Those two low bits come from stval only for a fault on an explicit access. Where one is taken on an implicit access made for VS-stage translation htval holds the address of the VS-stage PTE which could not be read, while stval still holds the guest virtual address which started the walk, and the low bits of the address written to htval are zero instead. htinst tells the two apart, which is what the spec points at it for.

stval needs no check against an ISA extension: a guest-page fault writes it with the faulting guest virtual address regardless. Sstvala would not be the right thing to test for either (it covers stval across every trap type which writes it, a wider guarantee than what is needed here).

htval does need one. The H extension lets an implementation write it with either the faulting address or zero, so without Shtvala a zero htval cannot be told apart from a genuine fault on guest physical address 0-3, and the address has to be recovered by decoding the access and walking the VS-stage page tables in software instead. That is left as a TODO, and until it is written such hardware panics rather than acting on an address which may not be the one which faulted.

Quoted 1 line
#135 lore raw

PATCH v2 22/39 xen/riscv: add guest memory read helper

In reply to Oleksii Kurochko

Introduce riscv_read_guest() to allow Xen to safely read guest memory using HLV/HLVX instructions while reliably capturing trap context.

This is required for instruction fetch emulation and MMIO decoding, where Xen must inspect guest memory that may not be directly accessible and may fault.

The implementation is based on kvm_riscv_vcpu_unpriv_read() from Linux, with one deviation: the hlv/hlvx instructions translate the guest address through the live vsatp/hgatp CSRs, i.e. through the address space of the currently running vCPU, so the function can only be called safely for current. Instead of taking a struct vcpu argument, it always operates on current directly.

---
Changes in v2:
- Rename riscv_vcpu_unpriv_read() to riscv_read_guest() and make the guest address the first parameter. "unprivileged" described how hlv/hlvx perform the access rather than what the helper is for, and "unprivileged guest" reads as a synonym for DomU although the helper works for any domain.
- Drop the hstatus save/restore and the local_irq_save() protecting it:
hstatus already belongs to the vCPU which trapped, as Xen never installs a value of its own and does not reschedule before returning to the guest. ASSERT() hstatus.SPV in the saved copy instead, which also documents that the helper is only usable while handling a trap from a guest.
- Poison val with ~0UL and make [val] "+&r": the fixup for the first access resumes past the loads without writing it, so a caller which checks trap->scause is no longer handed an uninitialized value.
- Describe the trap_info write with a "+m" (*trap) operand instead of a "memory" clobber; the exception handler writes that structure and nothing else.
- Combine the two halfwords with slli/or instead of sll/add, and use bnez for the instruction length check.
- Turn the hlv.d/hlv.w selection into #if/#elif with an #error default, rather than silently using hlv.w for anything that is not RV64.
- Document that at most two halfwords are fetched, i.e. that encodings wider than 32 bits are unsupported and cannot be completed by calling the helper again at guest_addr + 4, since the length check would then be applied to a continuation halfword.
---

---
 xen/arch/riscv/guestcopy.c | 87 ++++++++++++++++++++++++++++++++++++++
 1 file changed, 87 insertions(+)
xen/arch/riscv/guestcopy.c +87 -0
index 8a89212e0bea..b2327822acaa 100644
@@ -6,6 +6,7 @@
 #include <xen/string.h>
 
 #include <asm/guest_access.h>
+#include <asm/traps.h>
 
 #define COPY_from_guest     0U
 #define COPY_to_guest       BIT(0, U)
@@ -114,3 +115,89 @@ unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,
     return copy_guest(buf, gpa, len, GPA_INFO(d),
                       COPY_to_guest | COPY_gpa);
 }
+
+/*
+ * Read machine word from guest memory
+ *
+ * @guest_addr: Guest address to read
+ * @read_insn: Flag representing whether we are reading instruction
+ * @trap: Output pointer to trap details if something went wrong during read
+ *
+ * The hlv/hlvx instructions translate guest_addr through the live
+ * vsatp/hgatp CSRs, so the read is only meaningful for the address
+ * space of the currently running vCPU.
+ *
+ * At most two halfwords are fetched when @read_insn is true, i.e. encodings
+ * wider than 32 bits are not supported. Such an encoding cannot be completed
+ * by calling this function again at @guest_addr + 4: the length check is
+ * applied to the first halfword read, which would then be a continuation of
+ * the instruction rather than its opcode. It is up to the caller to reject
+ * anything that is neither a 16- nor a 32-bit encoding.
+ */
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap)
+{
+    /*
+     * Poison the result: if the very first access faults, the fixup skips
+     * over the loads without writing it. Callers must check trap->scause.
+     */
+    unsigned long val = ~0UL, tmp;
+
+    /*
+     * hlv/hlvx use hstatus.SPVP for the privilege of the access, and the
+     * live vsatp/hgatp for the translation. Xen never installs a value of
+     * its own in hstatus (it is only saved on trap entry and restored
+     * before sret) and it doesn't reschedule before returning to the
+     * guest, so all three still belong to the vCPU which trapped.
+     *
+     * Check the saved copy rather than the live CSR: a nested trap taken
+     * from HS-mode clears hstatus.SPV in the CSR (but leaves SPVP alone).
+     */
+    ASSERT(vcpu_guest_cpu_user_regs(current)->hstatus & HSTATUS_SPV);
+
+    if ( read_insn )
+    {
+        asm volatile ( "\n"
+            "1: hlvx.hu %[val], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti])
+            "   andi %[tmp], %[val], 3\n"
+            "   addi %[tmp], %[tmp], -3\n"
+            "   bnez %[tmp], 3f\n"
+            "   addi %[addr], %[addr], 2\n"
+            "\n"
+            "2: hlvx.hu %[tmp], (%[addr])\n"
+            ASM_EXTABLE_TRAP_INFO(2b, 3f, %[ti])
+            "   slli %[tmp], %[tmp], 16\n"
+            "   or %[val], %[val], %[tmp]\n"
+            "3:\n"
+        : [val] "+&r" (val), [tmp] "=&r" (tmp), [addr] "+&r" (guest_addr),
+          "+m" (*trap)
+        : [ti] "r" (trap) );
+
+        /*
+         * Although HLVX instructions' explicit memory accesses require execute
+         * permissions, they still raise the same exceptions as other load
+         * instructions, rather than raising fetch exceptions instead.
+         */
+        if ( trap->scause == CAUSE_LOAD_PAGE_FAULT )
+            trap->scause = CAUSE_FETCH_PAGE_FAULT;
+    }
+    else
+    {
+        asm volatile ( "\n"
+            "1: "
+#if defined(CONFIG_RISCV_64)
+            "hlv.d %[val], (%[addr])\n"
+#elif defined(CONFIG_RISCV_32)
+            "hlv.w %[val], (%[addr])\n"
+#else
+# error "unsupported RISC-V variant: no hlv for a machine word"
+#endif
+            "2:\n"
+            ASM_EXTABLE_TRAP_INFO(1b, 2b, %[ti])
+        : [val] "+&r" (val), "+m" (*trap)
+        : [addr] "r" (guest_addr), [ti] "r" (trap) );
+    }
+
+    return val;
+}
Signature · 1 line
2.55.0
#136 lore raw

Re: [PATCH v2 22/39] xen/riscv: add guest memory read helper

Quoted 43 lines

Introduce riscv_read_guest() to allow Xen to safely read guest memory using HLV/HLVX instructions while reliably capturing trap context.

This is required for instruction fetch emulation and MMIO decoding, where Xen must inspect guest memory that may not be directly accessible and may fault.

The implementation is based on kvm_riscv_vcpu_unpriv_read() from Linux, with one deviation: the hlv/hlvx instructions translate the guest address through the live vsatp/hgatp CSRs, i.e. through the address space of the currently running vCPU, so the function can only be called safely for current. Instead of taking a struct vcpu argument, it always operates on current directly.

xen/arch/riscv/guestcopy.c +12 -0
index 8a89212e0b..b2327822ac 100644
@@ -6,6 +6,7 @@
 #include <xen/string.h>
 
 #include <asm/guest_access.h>
+#include <asm/traps.h>
 
 #define COPY_from_guest     0U
 #define COPY_to_guest       BIT(0, U)
@@ -114,3 +115,89 @@ unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,
     return copy_guest(buf, gpa, len, GPA_INFO(d),
                       COPY_to_guest | COPY_gpa);
 }
+
+/*
+ * Read machine word from guest memory
+ *
+ * @guest_addr: Guest address to read
+ * @read_insn: Flag representing whether we are reading instruction
+ * @trap: Output pointer to trap details if something went wrong during read
+ *
+ * The hlv/hlvx instructions translate guest_addr through the live
+ * vsatp/hgatp CSRs, so the read is only meaningful for the address
+ * space of the currently running vCPU.

xen/arch/riscv/guestcopy.c unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf, · line 138

Quoted 10 lines
xen/arch/riscv/guestcopy.c +10 -0
+ *
+ * At most two halfwords are fetched when @read_insn is true, i.e. encodings
+ * wider than 32 bits are not supported. Such an encoding cannot be completed
+ * by calling this function again at @guest_addr + 4: the length check is
+ * applied to the first halfword read, which would then be a continuation of
+ * the instruction rather than its opcode. It is up to the caller to reject
+ * anything that is neither a 16- nor a 32-bit encoding.
+ */
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap)

Nit: every other function in this file / declared in this header (raw_copy_from_guest, copy_to_guest_phys, ...) has no riscv_ prefix. Why does this one get it?

xen/arch/riscv/guestcopy.c unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf, · line 144

Quoted 7 lines
xen/arch/riscv/guestcopy.c +6 -0
+{
+    /*
+     * Poison the result: if the very first access faults, the fixup skips
+     * over the loads without writing it. Callers must check trap->scause.
+     */
+    unsigned long val = ~0UL, tmp;

The actual "did a trap happen" contract callers rely on is trap->scause == 0. If the very first access faults, fixup_exception() will write scause accordingly to a non-zero value, but nothing in this function clears trap->scause on the success path.

xen/arch/riscv/guestcopy.c unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf, · line 156

Quoted 12 lines
xen/arch/riscv/guestcopy.c +12 -0
+
+    /*
+     * hlv/hlvx use hstatus.SPVP for the privilege of the access, and the
+     * live vsatp/hgatp for the translation. Xen never installs a value of
+     * its own in hstatus (it is only saved on trap entry and restored
+     * before sret) and it doesn't reschedule before returning to the
+     * guest, so all three still belong to the vCPU which trapped.
+     *
+     * Check the saved copy rather than the live CSR: a nested trap taken
+     * from HS-mode clears hstatus.SPV in the CSR (but leaves SPVP alone).
+     */
+    ASSERT(vcpu_guest_cpu_user_regs(current)->hstatus & HSTATUS_SPV);

Just to understand, what is the aim of this check? Is it to be sure this function has been called during a guest fault and not a nested HS fault?

Signature · 1 line
Baptiste Le Duc <[email protected]>
#137 lore raw

Re: [PATCH v2 22/39] xen/riscv: add guest memory read helper

Quoted 63 lines · Baptiste Le Duc
Quoted 43 lines

Introduce riscv_read_guest() to allow Xen to safely read guest memory using HLV/HLVX instructions while reliably capturing trap context.

This is required for instruction fetch emulation and MMIO decoding, where Xen must inspect guest memory that may not be directly accessible and may fault.

The implementation is based on kvm_riscv_vcpu_unpriv_read() from Linux, with one deviation: the hlv/hlvx instructions translate the guest address through the live vsatp/hgatp CSRs, i.e. through the address space of the currently running vCPU, so the function can only be called safely for current. Instead of taking a struct vcpu argument, it always operates on current directly.

xen/arch/riscv/guestcopy.c +12 -0
index 8a89212e0b..b2327822ac 100644
@@ -6,6 +6,7 @@
 #include <xen/string.h>
 
 #include <asm/guest_access.h>
+#include <asm/traps.h>
 
 #define COPY_from_guest     0U
 #define COPY_to_guest       BIT(0, U)
@@ -114,3 +115,89 @@ unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,
     return copy_guest(buf, gpa, len, GPA_INFO(d),
                       COPY_to_guest | COPY_gpa);
 }
+
+/*
+ * Read machine word from guest memory
+ *
+ * @guest_addr: Guest address to read
+ * @read_insn: Flag representing whether we are reading instruction
+ * @trap: Output pointer to trap details if something went wrong during read
+ *
+ * The hlv/hlvx instructions translate guest_addr through the live
+ * vsatp/hgatp CSRs, so the read is only meaningful for the address
+ * space of the currently running vCPU.

xen/arch/riscv/guestcopy.c unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf, · line 138

Quoted 10 lines
xen/arch/riscv/guestcopy.c +10 -0
+ *
+ * At most two halfwords are fetched when @read_insn is true, i.e. encodings
+ * wider than 32 bits are not supported. Such an encoding cannot be completed
+ * by calling this function again at @guest_addr + 4: the length check is
+ * applied to the first halfword read, which would then be a continuation of
+ * the instruction rather than its opcode. It is up to the caller to reject
+ * anything that is neither a 16- nor a 32-bit encoding.
+ */
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap)

Nit: every other function in this file / declared in this header (raw_copy_from_guest, copy_to_guest_phys, ...) has no riscv_ prefix. Why does this one get it?

xen/arch/riscv/guestcopy.c unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf, · line 144

Quoted 7 lines
xen/arch/riscv/guestcopy.c +6 -0
+{
+    /*
+     * Poison the result: if the very first access faults, the fixup skips
+     * over the loads without writing it. Callers must check trap->scause.
+     */
+    unsigned long val = ~0UL, tmp;
Quoted 4 lines

The actual "did a trap happen" contract callers rely on is trap->scause == 0. If the very first access faults, fixup_exception() will write scause accordingly to a non-zero value, but nothing in this function clears trap->scause on the success path.

So perhaps the assumption is that callers pass in a zero-filled struct? Would want (need) spelling out, though.

Jan

#138 lore raw

Re: [PATCH v2 22/39] xen/riscv: add guest memory read helper

In reply to Baptiste Le Duc
Quoted 48 lines · Baptiste Le Duc
Quoted 48 lines

Introduce riscv_read_guest() to allow Xen to safely read guest memory using HLV/HLVX instructions while reliably capturing trap context.

This is required for instruction fetch emulation and MMIO decoding, where Xen must inspect guest memory that may not be directly accessible and may fault.

The implementation is based on kvm_riscv_vcpu_unpriv_read() from Linux, with one deviation: the hlv/hlvx instructions translate the guest address through the live vsatp/hgatp CSRs, i.e. through the address space of the currently running vCPU, so the function can only be called safely for current. Instead of taking a struct vcpu argument, it always operates on current directly.

xen/arch/riscv/guestcopy.c +17 -0
index 8a89212e0b..b2327822ac 100644
@@ -6,6 +6,7 @@
  #include <xen/string.h>
 
  #include <asm/guest_access.h>
+#include <asm/traps.h>
 
  #define COPY_from_guest     0U
  #define COPY_to_guest       BIT(0, U)
@@ -114,3 +115,89 @@ unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,
      return copy_guest(buf, gpa, len, GPA_INFO(d),
                        COPY_to_guest | COPY_gpa);
  }
+
+/*
+ * Read machine word from guest memory
+ *
+ * @guest_addr: Guest address to read
+ * @read_insn: Flag representing whether we are reading instruction
+ * @trap: Output pointer to trap details if something went wrong during read
+ *
+ * The hlv/hlvx instructions translate guest_addr through the live
+ * vsatp/hgatp CSRs, so the read is only meaningful for the address
+ * space of the currently running vCPU.
+ *
+ * At most two halfwords are fetched when @read_insn is true, i.e. encodings
+ * wider than 32 bits are not supported. Such an encoding cannot be completed
+ * by calling this function again at @guest_addr + 4: the length check is
+ * applied to the first halfword read, which would then be a continuation of
Quoted 8 lines

xen/arch/riscv/guestcopy.c unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf, · line 138

Quoted 5 lines
xen/arch/riscv/guestcopy.c +5 -0
+ * the instruction rather than its opcode. It is up to the caller to reject
+ * anything that is neither a 16- nor a 32-bit encoding.
+ */
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap)

Nit: every other function in this file / declared in this header (raw_copy_from_guest, copy_to_guest_phys, ...) has no riscv_ prefix. Why does this one get it?

Agree not to much sense. I will drop it.

Quoted 11 lines

xen/arch/riscv/guestcopy.c unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf, · line 144

Quoted 7 lines
xen/arch/riscv/guestcopy.c +6 -0
+{
+    /*
+     * Poison the result: if the very first access faults, the fixup skips
+     * over the loads without writing it. Callers must check trap->scause.
+     */
+    unsigned long val = ~0UL, tmp;

The actual "did a trap happen" contract callers rely on is trap->scause == 0. If the very first access faults, fixup_exception() will write scause accordingly to a non-zero value, but nothing in this function clears trap->scause on the success path.

It is because caller is expected to zero-fill trap as it is happening now. I will mention that explicitly. I will do the following:

- * @trap: Output pointer to trap details if something went wrong during read
+ * @trap: Output pointer to trap details if something went wrong during read.

+ *        It must be zero-initialised by the caller: it is written only when
+ *        an access faults, so trap->scause == 0 on return is what tells the
+ *        caller that the read succeeded.
Quoted 12 lines

xen/arch/riscv/guestcopy.c unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf, · line 156

Quoted 12 lines
xen/arch/riscv/guestcopy.c +12 -0
+
+    /*
+     * hlv/hlvx use hstatus.SPVP for the privilege of the access, and the
+     * live vsatp/hgatp for the translation. Xen never installs a value of
+     * its own in hstatus (it is only saved on trap entry and restored
+     * before sret) and it doesn't reschedule before returning to the
+     * guest, so all three still belong to the vCPU which trapped.
+     *
+     * Check the saved copy rather than the live CSR: a nested trap taken
+     * from HS-mode clears hstatus.SPV in the CSR (but leaves SPVP alone).
+     */
+    ASSERT(vcpu_guest_cpu_user_regs(current)->hstatus & HSTATUS_SPV);
Quoted 3 lines

Just to understand, what is the aim of this check? Is it to be sure this function has been called during a guest fault and not a nested HS fault?

Yes.

~ Oleksii

#139 lore raw

Re: [PATCH v2 22/39] xen/riscv: add guest memory read helper

Quoted 64 lines · Oleksii Kurochko
Quoted 54 lines · Baptiste Le Duc
Quoted 54 lines

Introduce riscv_read_guest() to allow Xen to safely read guest memory using HLV/HLVX instructions while reliably capturing trap context.

This is required for instruction fetch emulation and MMIO decoding, where Xen must inspect guest memory that may not be directly accessible and may fault.

The implementation is based on kvm_riscv_vcpu_unpriv_read() from Linux, with one deviation: the hlv/hlvx instructions translate the guest address through the live vsatp/hgatp CSRs, i.e. through the address space of the currently running vCPU, so the function can only be called safely for current. Instead of taking a struct vcpu argument, it always operates on current directly.

xen/arch/riscv/guestcopy.c +1 -0
index 8a89212e0b..b2327822ac 100644
@@ -6,6 +6,7 @@
   #include <xen/string.h>
   #include <asm/guest_access.h>
+#include <asm/traps.h>
   #define COPY_from_guest     0U
   #define COPY_to_guest       BIT(0, U)
@@ -114,3 +115,89 @@ unsigned long copy_to_guest_phys(struct domain 
 *d, paddr_t gpa, void *buf,
       return copy_guest(buf, gpa, len, GPA_INFO(d),
                         COPY_to_guest | COPY_gpa);

  }

xen/arch/riscv/guestcopy.c +7 -0
+
+/*
+ * Read machine word from guest memory
+ *
+ * @guest_addr: Guest address to read
+ * @read_insn: Flag representing whether we are reading instruction
+ * @trap: Output pointer to trap details if something went wrong 

during read
+ *
+ * The hlv/hlvx instructions translate guest_addr through the live
+ * vsatp/hgatp CSRs, so the read is only meaningful for the address
+ * space of the currently running vCPU.
+ *
+ * At most two halfwords are fetched when @read_insn is true, i.e. encodings
+ * wider than 32 bits are not supported. Such an encoding cannot be completed
+ * by calling this function again at @guest_addr + 4: the length check is
+ * applied to the first halfword read, which would then be a continuation of
+ * the instruction rather than its opcode. It is up to the caller to reject

Quoted 8 lines
Quoted 5 lines

+ * anything that is neither a 16- nor a 32-bit encoding.
+ */
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap)

Nit: every other function in this file / declared in this header (raw_copy_from_guest, copy_to_guest_phys, ...) has no riscv_ prefix. Why does this one get it?

Quoted 1 line

Agree not to much sense. I will drop it.

Probably we still want to have riscv_ prefix to show that this read_guest() is specific to RISC-V but others (raw_copy_from_guest, copy_to_guest_phys, ...) could be used in Xen common code too.

So I think we could keep riscv_ prefix.

~ Oleksii

#140 lore raw

Re: [PATCH v2 22/39] xen/riscv: add guest memory read helper

Quoted 68 lines · Oleksii Kurochko
Quoted 67 lines · Oleksii Kurochko
Quoted 65 lines · Baptiste Le Duc
Quoted 54 lines

Introduce riscv_read_guest() to allow Xen to safely read guest memory using HLV/HLVX instructions while reliably capturing trap context.

This is required for instruction fetch emulation and MMIO decoding, where
Xen must inspect guest memory that may not be directly accessible and may
fault.

The implementation is based on kvm_riscv_vcpu_unpriv_read() from Linux, with one deviation: the hlv/hlvx instructions translate the guest address
through the live vsatp/hgatp CSRs, i.e. through the address space of the currently running vCPU, so the function can only be called safely for current. Instead of taking a struct vcpu argument, it always operates on current directly.

xen/arch/riscv/guestcopy.c +1 -0
index 8a89212e0b..b2327822ac 100644
@@ -6,6 +6,7 @@
   #include <xen/string.h>
   #include <asm/guest_access.h>
+#include <asm/traps.h>
   #define COPY_from_guest     0U
   #define COPY_to_guest       BIT(0, U)
@@ -114,3 +115,89 @@ unsigned long copy_to_guest_phys(struct domain 
 *d, paddr_t gpa, void *buf,
       return copy_guest(buf, gpa, len, GPA_INFO(d),
                         COPY_to_guest | COPY_gpa);

  }

xen/arch/riscv/guestcopy.c +7 -0
+
+/*
+ * Read machine word from guest memory
+ *
+ * @guest_addr: Guest address to read
+ * @read_insn: Flag representing whether we are reading instruction
+ * @trap: Output pointer to trap details if something went wrong 

during read
+ *
+ * The hlv/hlvx instructions translate guest_addr through the live
+ * vsatp/hgatp CSRs, so the read is only meaningful for the address
+ * space of the currently running vCPU.
+ *
+ * At most two halfwords are fetched when @read_insn is true, i.e. encodings
+ * wider than 32 bits are not supported. Such an encoding cannot be completed
+ * by calling this function again at @guest_addr + 4: the length check is
+ * applied to the first halfword read, which would then be a

Quoted 8 lines

continuation of
+ * the instruction rather than its opcode. It is up to the caller to reject
+ * anything that is neither a 16- nor a 32-bit encoding.
+ */
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap)

Nit: every other function in this file / declared in this header (raw_copy_from_guest, copy_to_guest_phys, ...) has no riscv_ prefix. Why does this one get it?

Quoted 7 lines
Quoted 1 line

Agree not to much sense. I will drop it.

Probably we still want to have riscv_ prefix to show that this read_guest() is specific to RISC-V but others (raw_copy_from_guest, copy_to_guest_phys, ...) could be used in Xen common code too.

So I think we could keep riscv_ prefix.

Please may I suggest to avoid unnecessary prefixes?

Jan

#141 lore raw

Re: [PATCH v2 22/39] xen/riscv: add guest memory read helper

Quoted 71 lines · Jan Beulich
Quoted 70 lines · Oleksii Kurochko
Quoted 68 lines · Oleksii Kurochko
Quoted 57 lines · Baptiste Le Duc
Quoted 57 lines

Introduce riscv_read_guest() to allow Xen to safely read guest memory using HLV/HLVX instructions while reliably capturing trap context.

This is required for instruction fetch emulation and MMIO decoding, where
Xen must inspect guest memory that may not be directly accessible and may
fault.

The implementation is based on kvm_riscv_vcpu_unpriv_read() from Linux, with one deviation: the hlv/hlvx instructions translate the guest address
through the live vsatp/hgatp CSRs, i.e. through the address space of the currently running vCPU, so the function can only be called safely for current. Instead of taking a struct vcpu argument, it always operates on current directly.

xen/arch/riscv/guestcopy.c +8 -0
index 8a89212e0b..b2327822ac 100644
@@ -6,6 +6,7 @@
   #include <xen/string.h>
   #include <asm/guest_access.h>
+#include <asm/traps.h>
   #define COPY_from_guest     0U
   #define COPY_to_guest       BIT(0, U)
@@ -114,3 +115,89 @@ unsigned long copy_to_guest_phys(struct domain
 *d, paddr_t gpa, void *buf,
       return copy_guest(buf, gpa, len, GPA_INFO(d),
                         COPY_to_guest | COPY_gpa);
   }
+
+/*
+ * Read machine word from guest memory
+ *
+ * @guest_addr: Guest address to read
+ * @read_insn: Flag representing whether we are reading instruction
+ * @trap: Output pointer to trap details if something went wrong

during read
+ *
+ * The hlv/hlvx instructions translate guest_addr through the live
+ * vsatp/hgatp CSRs, so the read is only meaningful for the address
+ * space of the currently running vCPU.
+ *
+ * At most two halfwords are fetched when @read_insn is true, i.e. encodings
+ * wider than 32 bits are not supported. Such an encoding cannot be completed
+ * by calling this function again at @guest_addr + 4: the length check is
+ * applied to the first halfword read, which would then be a continuation of
+ * the instruction rather than its opcode. It is up to the caller to reject

Quoted 8 lines
Quoted 5 lines

+ * anything that is neither a 16- nor a 32-bit encoding.
+ */
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap)

Nit: every other function in this file / declared in this header (raw_copy_from_guest, copy_to_guest_phys, ...) has no riscv_ prefix. Why does this one get it?

Agree not to much sense. I will drop it.

Quoted 7 lines
Quoted 5 lines

Probably we still want to have riscv_ prefix to show that this read_guest() is specific to RISC-V but others (raw_copy_from_guest, copy_to_guest_phys, ...) could be used in Xen common code too.

So I think we could keep riscv_ prefix.

Please may I suggest to avoid unnecessary prefixes?

Sure then I will drop it as originally suggested.

~ Oleksii

#142 lore raw

Re: [PATCH v2 22/39] xen/riscv: add guest memory read helper

In reply to Oleksii Kurochko
Quoted 43 lines · Oleksii Kurochko
xen/arch/riscv/guestcopy.c +30 -0
@@ -6,6 +6,7 @@
 #include <xen/string.h>
 
 #include <asm/guest_access.h>
+#include <asm/traps.h>
 
 #define COPY_from_guest     0U
 #define COPY_to_guest       BIT(0, U)
@@ -114,3 +115,89 @@ unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,
     return copy_guest(buf, gpa, len, GPA_INFO(d),
                       COPY_to_guest | COPY_gpa);
 }
+
+/*
+ * Read machine word from guest memory
+ *
+ * @guest_addr: Guest address to read
+ * @read_insn: Flag representing whether we are reading instruction
+ * @trap: Output pointer to trap details if something went wrong during read
+ *
+ * The hlv/hlvx instructions translate guest_addr through the live
+ * vsatp/hgatp CSRs, so the read is only meaningful for the address
+ * space of the currently running vCPU.
+ *
+ * At most two halfwords are fetched when @read_insn is true, i.e. encodings
+ * wider than 32 bits are not supported. Such an encoding cannot be completed
+ * by calling this function again at @guest_addr + 4: the length check is
+ * applied to the first halfword read, which would then be a continuation of
+ * the instruction rather than its opcode. It is up to the caller to reject
+ * anything that is neither a 16- nor a 32-bit encoding.
+ */
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap)
+{
+    /*
+     * Poison the result: if the very first access faults, the fixup skips
+     * over the loads without writing it. Callers must check trap->scause.
+     */
+    unsigned long val = ~0UL, tmp;
+
+    /*

xen/arch/riscv/guestcopy.c unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf, · line 156

Quoted 10 lines
xen/arch/riscv/guestcopy.c +10 -0
+     * hlv/hlvx use hstatus.SPVP for the privilege of the access, and the
+     * live vsatp/hgatp for the translation. Xen never installs a value of
+     * its own in hstatus (it is only saved on trap entry and restored
+     * before sret) and it doesn't reschedule before returning to the
+     * guest, so all three still belong to the vCPU which trapped.
+     *
+     * Check the saved copy rather than the live CSR: a nested trap taken
+     * from HS-mode clears hstatus.SPV in the CSR (but leaves SPVP alone).
+     */
+    ASSERT(vcpu_guest_cpu_user_regs(current)->hstatus & HSTATUS_SPV);

The first paragraph talks of just hstatus.SPVP. The second paragraph then starting "Check ..." means that still refers to hstatus.SPVP, when - aiui - hstatus.SPV is meant.

Furthermore, instead of special casing nested faults here, but otherwise saying "Xen doesn't modify", wouldn't it be better to word things such that they remain correct if Xen ends up having a need to touch some other part of hstatus (including, potentially, SPV)? IOW - I think it is natural that the original guest value is checked. Question being of how much value that checking is: vcpu_guest_cpu_user_regs(current)->hstatus can't possibly have SPV clear, can it? Only nested exception frames could.

Jan

#143 lore raw

Re: [PATCH v2 22/39] xen/riscv: add guest memory read helper

Quoted 59 lines · Jan Beulich
Quoted 43 lines · Oleksii Kurochko
xen/arch/riscv/guestcopy.c +30 -0
@@ -6,6 +6,7 @@
  #include <xen/string.h>
 
  #include <asm/guest_access.h>
+#include <asm/traps.h>
 
  #define COPY_from_guest     0U
  #define COPY_to_guest       BIT(0, U)
@@ -114,3 +115,89 @@ unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,
      return copy_guest(buf, gpa, len, GPA_INFO(d),
                        COPY_to_guest | COPY_gpa);
  }
+
+/*
+ * Read machine word from guest memory
+ *
+ * @guest_addr: Guest address to read
+ * @read_insn: Flag representing whether we are reading instruction
+ * @trap: Output pointer to trap details if something went wrong during read
+ *
+ * The hlv/hlvx instructions translate guest_addr through the live
+ * vsatp/hgatp CSRs, so the read is only meaningful for the address
+ * space of the currently running vCPU.
+ *
+ * At most two halfwords are fetched when @read_insn is true, i.e. encodings
+ * wider than 32 bits are not supported. Such an encoding cannot be completed
+ * by calling this function again at @guest_addr + 4: the length check is
+ * applied to the first halfword read, which would then be a continuation of
+ * the instruction rather than its opcode. It is up to the caller to reject
+ * anything that is neither a 16- nor a 32-bit encoding.
+ */
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap)
+{
+    /*
+     * Poison the result: if the very first access faults, the fixup skips
+     * over the loads without writing it. Callers must check trap->scause.
+     */
+    unsigned long val = ~0UL, tmp;
+
+    /*

xen/arch/riscv/guestcopy.c unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf, · line 156

Quoted 10 lines
xen/arch/riscv/guestcopy.c +10 -0
+     * hlv/hlvx use hstatus.SPVP for the privilege of the access, and the
+     * live vsatp/hgatp for the translation. Xen never installs a value of
+     * its own in hstatus (it is only saved on trap entry and restored
+     * before sret) and it doesn't reschedule before returning to the
+     * guest, so all three still belong to the vCPU which trapped.
+     *
+     * Check the saved copy rather than the live CSR: a nested trap taken
+     * from HS-mode clears hstatus.SPV in the CSR (but leaves SPVP alone).
+     */
+    ASSERT(vcpu_guest_cpu_user_regs(current)->hstatus & HSTATUS_SPV);

The first paragraph talks of just hstatus.SPVP. The second paragraph then starting "Check ..." means that still refers to hstatus.SPVP, when - aiui - hstatus.SPV is meant.

Quoted 5 lines

Furthermore, instead of special casing nested faults here, but otherwise saying "Xen doesn't modify", wouldn't it be better to word things such that they remain correct if Xen ends up having a need to touch some other part of hstatus (including, potentially, SPV)? IOW - I think it is natural that the original guest value is checked.

You are right:
1. The transition between the two paragraphs was confusing regarding SPVP vs SPV. I will update the comment to clearly distinguish that hlv/hlvx rely on SPVP, whereas the ASSERT verifies SPV.

2. Re-phrasing this around the invariant that vcpu_guest_cpu_user_regs represents the guest state at trap entry makes much more sense and is future-proof against any potential changes to live hstatus manipulation in Xen.

3. Regarding the value of the ASSERT: yes, for any valid guest trap frame SPV must be set. The ASSERT serves as a sanity check to ensure riscv_read_guest() is never accidentally invoked outside a valid guest vCPU trap context.I will update the comment as follows in v3:

/*
* hlv/hlvx instructions use the live hstatus.SPVP for access
privilege,
* and live vsatp/hgatp for translation. Since Xen does not reschedule
* before returning to the guest, these CSRs still belong to current. *
* Check SPV in the saved guest registers rather than the live CSR:
* the saved copy reflects the guest virtualization mode (V=1) at
the time
* of trap entry, which remains invariant even if nested traps or
HS-mode

     * execution modify the live CSR.
     */
    ASSERT(vcpu_guest_cpu_user_regs(current)->hstatus & HSTATUS_SPV);
Quoted 3 lines

Question being of how much value
that checking is: vcpu_guest_cpu_user_regs(current)->hstatus can't possibly have SPV clear, can it? Only nested exception frames could.

Given that vcpu_guest_cpu_user_regs(current)->hstatus will always have SPV set for any valid guest trap frame, the ASSERT is purely a defensive sanity check to ensure riscv_read_guest() is never called outside a guest trap context. Would you prefer to keep this defensive ASSERT (with the updated comment), or drop it as redundant?

Thanks.

~ Oleksii

#144 lore raw

Re: [PATCH v2 22/39] xen/riscv: add guest memory read helper

Quoted 52 lines · Oleksii Kurochko
Quoted 40 lines · Jan Beulich
Quoted 39 lines · Oleksii Kurochko
xen/arch/riscv/guestcopy.c +35 -0
@@ -114,3 +115,89 @@ unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,
      return copy_guest(buf, gpa, len, GPA_INFO(d),
                        COPY_to_guest | COPY_gpa);
  }
+
+/*
+ * Read machine word from guest memory
+ *
+ * @guest_addr: Guest address to read
+ * @read_insn: Flag representing whether we are reading instruction
+ * @trap: Output pointer to trap details if something went wrong during read
+ *
+ * The hlv/hlvx instructions translate guest_addr through the live
+ * vsatp/hgatp CSRs, so the read is only meaningful for the address
+ * space of the currently running vCPU.
+ *
+ * At most two halfwords are fetched when @read_insn is true, i.e. encodings
+ * wider than 32 bits are not supported. Such an encoding cannot be completed
+ * by calling this function again at @guest_addr + 4: the length check is
+ * applied to the first halfword read, which would then be a continuation of
+ * the instruction rather than its opcode. It is up to the caller to reject
+ * anything that is neither a 16- nor a 32-bit encoding.
+ */
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap)
+{
+    /*
+     * Poison the result: if the very first access faults, the fixup skips
+     * over the loads without writing it. Callers must check trap->scause.
+     */
+    unsigned long val = ~0UL, tmp;
+
+    /*
+     * hlv/hlvx use hstatus.SPVP for the privilege of the access, and the
+     * live vsatp/hgatp for the translation. Xen never installs a value of
+     * its own in hstatus (it is only saved on trap entry and restored
+     * before sret) and it doesn't reschedule before returning to the
+     * guest, so all three still belong to the vCPU which trapped.
+     *
Quoted 8 lines

xen/arch/riscv/guestcopy.c unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf, · line 156

Quoted 4 lines
xen/arch/riscv/guestcopy.c +4 -0
+     * Check the saved copy rather than the live CSR: a nested trap taken
+     * from HS-mode clears hstatus.SPV in the CSR (but leaves SPVP alone).
+     */
+    ASSERT(vcpu_guest_cpu_user_regs(current)->hstatus & HSTATUS_SPV);

[...]
Question being of how much value
that checking is: vcpu_guest_cpu_user_regs(current)->hstatus can't possibly have SPV clear, can it? Only nested exception frames could.

Quoted 4 lines

Given that vcpu_guest_cpu_user_regs(current)->hstatus will always have SPV set for any valid guest trap frame, the ASSERT is purely a defensive sanity check to ensure riscv_read_guest() is never called outside a guest trap context.

It is not, afaict: vcpu_guest_cpu_user_regs(current) will give you the guest frame no matter what context you're in. For what you want, you'd need to pass struct cpu_user_regs * into here.

Jan

Quoted 7 lines

Would you prefer to keep this defensive ASSERT (with the updated comment), or drop it as redundant?

Thanks.

~ Oleksii

#145 lore raw

Re: [PATCH v2 22/39] xen/riscv: add guest memory read helper

Quoted 53 lines · Jan Beulich
Quoted 52 lines · Oleksii Kurochko
Quoted 48 lines · Jan Beulich
Quoted 33 lines · Oleksii Kurochko
xen/arch/riscv/guestcopy.c +29 -0
@@ -114,3 +115,89 @@ unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,
       return copy_guest(buf, gpa, len, GPA_INFO(d),
                         COPY_to_guest | COPY_gpa);
   }
+
+/*
+ * Read machine word from guest memory
+ *
+ * @guest_addr: Guest address to read
+ * @read_insn: Flag representing whether we are reading instruction
+ * @trap: Output pointer to trap details if something went wrong during read
+ *
+ * The hlv/hlvx instructions translate guest_addr through the live
+ * vsatp/hgatp CSRs, so the read is only meaningful for the address
+ * space of the currently running vCPU.
+ *
+ * At most two halfwords are fetched when @read_insn is true, i.e. encodings
+ * wider than 32 bits are not supported. Such an encoding cannot be completed
+ * by calling this function again at @guest_addr + 4: the length check is
+ * applied to the first halfword read, which would then be a continuation of
+ * the instruction rather than its opcode. It is up to the caller to reject
+ * anything that is neither a 16- nor a 32-bit encoding.
+ */
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap)
+{
+    /*
+     * Poison the result: if the very first access faults, the fixup skips
+     * over the loads without writing it. Callers must check trap->scause.
+     */
+    unsigned long val = ~0UL, tmp;
+
+    /*

xen/arch/riscv/guestcopy.c unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf, · line 156

Quoted 10 lines
xen/arch/riscv/guestcopy.c +10 -0
+     * hlv/hlvx use hstatus.SPVP for the privilege of the access, and the
+     * live vsatp/hgatp for the translation. Xen never installs a value of
+     * its own in hstatus (it is only saved on trap entry and restored
+     * before sret) and it doesn't reschedule before returning to the
+     * guest, so all three still belong to the vCPU which trapped.
+     *
+     * Check the saved copy rather than the live CSR: a nested trap taken
+     * from HS-mode clears hstatus.SPV in the CSR (but leaves SPVP alone).
+     */
+    ASSERT(vcpu_guest_cpu_user_regs(current)->hstatus & HSTATUS_SPV);

[...]
Question being of how much value
that checking is: vcpu_guest_cpu_user_regs(current)->hstatus can't possibly have SPV clear, can it? Only nested exception frames could.

Quoted 8 lines
Quoted 4 lines

Given that vcpu_guest_cpu_user_regs(current)->hstatus will always have SPV set for any valid guest trap frame, the ASSERT is purely a defensive sanity check to ensure riscv_read_guest() is never called outside a guest trap context.

It is not, afaict: vcpu_guest_cpu_user_regs(current) will give you the guest frame no matter what context you're in. For what you want, you'd need to pass struct cpu_user_regs * into here.

Agree, struct cpu_user_regs * will be required.

But I am looking at how read_guest() is used and it shouldn't be used when nested HS trap happen never and it seems like it is too much to pass struct cpu_user_regs * just to check that.

I think it is enough just to have:

case CAUSE_FETCH_GUEST_PAGE_FAULT:
case CAUSE_LOAD_GUEST_PAGE_FAULT:
case CAUSE_STORE_GUEST_PAGE_FAULT:
/*
* A guest page fault taken in Xen context comes from an hlv/hlvx
* access made on a vCPU's behalf and is dealt with by the
* fixup_exception() above, so only a guest can get here. */
BUG_ON(!from_guest);

where we already checked that when riscv_read_guest() is used then it isn't nested HS trap.

So it looks like we could just drop the ASSERT() and probably update the comment above function and mention that riscv_read_guest() shouldn't be called in nested HS trap.

~ Oleksii

#146 lore raw

PATCH v2 23/39 xen/riscv: look up the exception table for any trap taken in Xen context

In reply to Oleksii Kurochko

do_trap() consulted the exception table only for CAUSE_ILLEGAL_INSTRUCTION, which covers csr_read_safe() but not the hlv/hlvx sequences reading guest
memory: those fault with load/store (guest) page fault causes and would reach do_unexpected_trap() instead of their fixup.

Move the lookup ahead of the cause switch, and gate it on the trap having been taken in Xen context and not being an interrupt:

- sepc of a trap taken from the guest is a guest VA/PA, which the guest can point at an address listed in the exception table; Xen would then act on that entry and, for EX_TYPE_TRAP_INFO, write through a pointer fully under guest control. Entries are matched by exact address, so this needs no more than a numerical collision.

- an interrupt taken at an address listed in the table would otherwise be "fixed up" as if the access itself had faulted, silently skipping it and handing the caller the interrupt's scause as a fault cause.

Returning early skips check_for_pcpu_work(), which is correct: that only runs for traps taken from the guest.

With that in place a G-stage fault reaching the switch can no longer have been caused by an hlv/hlvx covered by an entry, so anything left must have come from the guest; assert as much.

Cache the "trap came from the guest" test in a local, it is now used four times.

---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/traps.c | 28 ++++++++++++++++++++++++----
 1 file changed, 24 insertions(+), 4 deletions(-)
xen/arch/riscv/traps.c +24 -4
index 8372f34497ad..f5f83fce10ba 100644
@@ -196,11 +196,34 @@ void do_trap(struct cpu_user_regs *cpu_regs)
     unsigned long cause = csr_read(CSR_SCAUSE);
     bool from_guest = cpu_regs->hstatus & HSTATUS_SPV;
 
+    /*
+     * A synchronous trap taken in Xen context may come from an access done on
+     * a vCPU's behalf, e.g. the hlv/hlvx sequences in riscv_read_guest(),
+     * or from a probing access like csr_read_safe(). Both are covered by
+     * exception table entries which record the fault details for the caller
+     * and resume execution past the faulting instruction.
+     *
+     * Traps taken from the guest must never be fixed up: sepc is then a guest
+     * address, which the guest could point at an address listed in the
+     * exception table, making Xen act on an entry (and, for EX_TYPE_TRAP_INFO,
+     * write through a pointer) fully under guest control.
+     *
+     * Interrupts must be excluded too: one taken at an address which happens
+     * to be listed in the exception table would otherwise be "fixed up" as if
+     * the access itself had faulted, silently skipping it.
+     *
+     * Returning early skips check_for_pcpu_work() below, which is correct:
+     * that only runs for traps taken from the guest.
+     */
+    if ( !from_guest && !(cause & CAUSE_IRQ_FLAG) &&
+         fixup_exception(cpu_regs, cause) )
+        return;
+
     switch ( cause )
     {
     case CAUSE_VIRTUAL_SUPERVISOR_ECALL:
         /* CAUSE_VIRTUAL_SUPERVISOR_ECALL should come from VS-mode */
-        BUG_ON(!(cpu_regs->hstatus & HSTATUS_SPV));
+        BUG_ON(!from_guest);
 
         vsbi_handle_ecall(cpu_regs);
         break;
@@ -232,9 +255,6 @@ void do_trap(struct cpu_user_regs *cpu_regs)
             break;
         }
 
-        if ( fixup_exception(cpu_regs, cause) )
-            break;
-
         fallthrough;
     default:
         if ( cause & CAUSE_IRQ_FLAG )
Signature · 1 line
2.55.0
Acked-by on v2 23/39
#147 lore raw

Re: [PATCH v2 23/39] xen/riscv: look up the exception table for any trap taken in Xen context

Quoted 21 lines · Oleksii Kurochko

do_trap() consulted the exception table only for CAUSE_ILLEGAL_INSTRUCTION, which covers csr_read_safe() but not the hlv/hlvx sequences reading guest
memory: those fault with load/store (guest) page fault causes and would reach do_unexpected_trap() instead of their fixup.

Move the lookup ahead of the cause switch, and gate it on the trap having been taken in Xen context and not being an interrupt:

- sepc of a trap taken from the guest is a guest VA/PA, which the guest can point at an address listed in the exception table; Xen would then act on that entry and, for EX_TYPE_TRAP_INFO, write through a pointer fully under guest control. Entries are matched by exact address, so this needs no more than a numerical collision.

- an interrupt taken at an address listed in the table would otherwise be "fixed up" as if the access itself had faulted, silently skipping it and handing the caller the interrupt's scause as a fault cause.

Returning early skips check_for_pcpu_work(), which is correct: that only runs for traps taken from the guest.

Quoted 8 lines

With that in place a G-stage fault reaching the switch can no longer have been caused by an hlv/hlvx covered by an entry, so anything left must have come from the guest; assert as much.

Cache the "trap came from the guest" test in a local, it is now used four times.

#148 lore raw

Re: [PATCH v2 23/39] xen/riscv: look up the exception table for any trap taken in Xen context

In reply to Oleksii Kurochko
Quoted 18 lines

do_trap() consulted the exception table only for CAUSE_ILLEGAL_INSTRUCTION, which covers csr_read_safe() but not the hlv/hlvx sequences reading guest
memory: those fault with load/store (guest) page fault causes and would reach do_unexpected_trap() instead of their fixup.

Move the lookup ahead of the cause switch, and gate it on the trap having been taken in Xen context and not being an interrupt:

- sepc of a trap taken from the guest is a guest VA/PA, which the guest can point at an address listed in the exception table; Xen would then act on that entry and, for EX_TYPE_TRAP_INFO, write through a pointer fully under guest control. Entries are matched by exact address, so this needs no more than a numerical collision.

- an interrupt taken at an address listed in the table would otherwise be "fixed up" as if the access itself had faulted, silently skipping it and handing the caller the interrupt's scause as a fault cause.

Quoted 6 lines

Returning early skips check_for_pcpu_work(), which is correct: that only runs for traps taken from the guest.

With that in place a G-stage fault reaching the switch can no longer have been caused by an hlv/hlvx covered by an entry, so anything left must have come from the guest; assert as much.

What means assert as much here? As you referencing any assert in the code, because in this patch, I couldn't find any.

Quoted 3 lines

Cache the "trap came from the guest" test in a local, it is now used four times.

Nit: By reading this sentence, I would expect to have the introduction of from_guest local here instead of in patch cc2d3b97e8 xen/riscv: add guest page fault handling stub

Signature · 1 line
Baptiste Le Duc <[email protected]>
#149 lore raw

Re: [PATCH v2 23/39] xen/riscv: look up the exception table for any trap taken in Xen context

Quoted 18 lines · Baptiste Le Duc
Quoted 18 lines

do_trap() consulted the exception table only for CAUSE_ILLEGAL_INSTRUCTION, which covers csr_read_safe() but not the hlv/hlvx sequences reading guest
memory: those fault with load/store (guest) page fault causes and would reach do_unexpected_trap() instead of their fixup.

Move the lookup ahead of the cause switch, and gate it on the trap having been taken in Xen context and not being an interrupt:

- sepc of a trap taken from the guest is a guest VA/PA, which the guest can point at an address listed in the exception table; Xen would then act on that entry and, for EX_TYPE_TRAP_INFO, write through a pointer fully under guest control. Entries are matched by exact address, so this needs no more than a numerical collision.

- an interrupt taken at an address listed in the table would otherwise be "fixed up" as if the access itself had faulted, silently skipping it and handing the caller the interrupt's scause as a fault cause.

Quoted 8 lines
Quoted 6 lines

Returning early skips check_for_pcpu_work(), which is correct: that only runs for traps taken from the guest.

With that in place a G-stage fault reaching the switch can no longer have been caused by an hlv/hlvx covered by an entry, so anything left must have come from the guest; assert as much.

What means assert as much here? As you referencing any assert in the code, because in this patch, I couldn't find any.

It refers to the BUG_ON(!from_guest) in the guest page fault case of do_trap(). That BUG_ON() (and the comment above it) ended up in "xen/riscv: add guest page fault handling stub" when the series was reordered, so this sentence is stale.

I will drop 'assert as much' from commit message.

Quoted 7 lines
Quoted 3 lines

Cache the "trap came from the guest" test in a local, it is now used four times.

Nit: By reading this sentence, I would expect to have the introduction of from_guest local here instead of in patch cc2d3b97e8 xen/riscv: add guest page fault handling stub

from_guest is introduced in "xen/riscv: add guest page fault handling stub" so it is a stale part of the commit message.

Thanks!

~ Oleksii

#150 lore raw

PATCH v2 24/39 xen/riscv: add helpers for decoding a trapped load or store

In reply to Oleksii Kurochko

emulate_load() and emulate_store() will both need to obtain the instruction which caused a guest MMIO trap, decode it, and locate the register operand it names. Add what the two share, ahead of either of them being implemented: struct decoded_insn, insn_fetch_faulted(), decode_ldst_insn(), guest_xlen(), guest_gpr() and advance_pc().

The mask/match chain is adapted from Linux's KVM RISC-V implementation.

Nothing calls any of this yet, so tag the functions __maybe_unused to keep the build going; the tags go away once emulate_load() and emulate_store() gain their bodies later.

---
How this function could be used can be seen in the next patch.
---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/emulate.c                    | 330 ++++++++++++++++++++
 xen/arch/riscv/include/asm/guest_access.h   |   4 +
 xen/arch/riscv/include/asm/riscv_encoding.h |  10 +
 3 files changed, 344 insertions(+)
xen/arch/riscv/emulate.c +330 -0
index ff530ef2df74..81a50643a5ec 100644
@@ -5,6 +5,7 @@
  */
 
 #include <xen/bug.h>
+#include <xen/compiler.h>
 #include <xen/errno.h>
 #include <xen/sched.h>
 #include <xen/types.h>
@@ -13,9 +14,29 @@
 #include <asm/csr.h>
 #include <asm/current.h>
 #include <asm/emulate.h>
+#include <asm/guest_access.h>
+#include <asm/processor.h>
 #include <asm/riscv_encoding.h>
 #include <asm/traps.h>
 
+/*
+ * Determine the trapped load or store instruction which caused a guest MMIO
+ * trap.
+ */
+struct decoded_insn {
+    /* The instruction itself, and its length in bytes. */
+    unsigned long insn;
+    unsigned int insn_len;
+    /* Width of the memory access, in bytes. */
+    unsigned int len;
+    /* Number of the register operand: rd for a load, rs2 for a store. */
+    unsigned int reg;
+    /* The access is a store rather than a load. */
+    bool is_write;
+    /* The load zero-extends its result rather than sign-extending it. */
+    bool is_unsigned;
+};
+
 /*
  * The hardware-reported details of a guest page fault, gathered once by
  * handle_guest_page_fault() and passed down to the emulation of the faulted
@@ -39,6 +60,71 @@ struct guest_fault {
     paddr_t gpa;
 };
 
+static bool is_load_guest_page_fault(unsigned long scause)
+{
+    return scause == CAUSE_LOAD_GUEST_PAGE_FAULT;
+}
+
+static __maybe_unused void advance_pc(struct cpu_user_regs *regs,
+                                      unsigned int step)
+{
+    regs->sepc += step;
+}
+
+/*
+ * The effective XLEN of the guest at the point of the trap: hstatus.VSXL for a
+ * trap taken from VS-mode, vsstatus.UXL for one taken from VU-mode.
+ *
+ * VSXL is consulted whichever mode the trap came from, as it also gives the
+ * width of vsstatus itself: where VSXL says 32, that register has no UXL field
+ * to consult and VU-mode is 32-bit as well, there being nothing to configure.
+ *
+ * It is needed to decode a trapped instruction: the encodings which exist only
+ * for XLEN=64 must not be recognized for a 32-bit guest. Besides those simply
+ * being reserved there, the compressed ones are ambiguous: C.LD and C.FLW
+ * share the encoding 0x6000 (mask 0xe003), and likewise C.SD/C.FSW,
+ * C.LDSP/C.FLWSP and C.SDSP/C.FSWSP.
+ *
+ * IS_ENABLED() can't be used here as HSTATUS_VSXL is defined for
+ * __riscv_xlen == 64 only, the field not existing on RV32 in the first place.
+ */
+static __maybe_unused unsigned int guest_xlen(const struct cpu_user_regs *regs)
+{
+#ifdef CONFIG_RISCV_32
+    return 32;
+#else
+    unsigned long xl = MASK_EXTR(regs->hstatus, HSTATUS_VSXL);
+
+    if ( (xl == XLEN_FIELD_64) && !(regs->sstatus & SSTATUS_SPP) )
+        xl = MASK_EXTR(csr_read(CSR_VSSTATUS), SSTATUS64_UXL);
+
+    switch ( xl )
+    {
+    case XLEN_FIELD_32:
+        return 32;
+
+    case XLEN_FIELD_64:
+        return 64;
+
+    default:
+        /*
+         * The field holds nothing else in practice: XLEN_FIELD_128 would mean
+         * RV128, which no implementation provides, and the only value left is
+         * reserved. ASSERT_UNREACHABLE() being debug-only, a width still has
+         * to be answered in release builds.
+         *
+         * Answer 32, that being the safe way to be wrong: the decoder then
+         * fails to recognize the RV64-only encodings and emulation gives up.
+         * Answering 64 for what may well be a 32-bit guest would instead have
+         * it take C.FLW for C.LD and C.FSW for C.SD (see above), i.e. quietly
+         * emulate an access of the wrong width against the wrong register.
+         */
+        ASSERT_UNREACHABLE();
+        return 32;
+    }
+#endif
+}
+
 /*
  * Is @htinst one of the pseudoinstructions reported for a guest page fault
  * taken on an implicit memory access done for VS-stage address translation?
@@ -87,6 +173,250 @@ static void resolve_faulting_gpa(struct guest_fault *gf)
               (htinst_is_pseudo(gf->htinst) ? 0 : (gf->stval & 3));
 }
 
+/*
+ * Where the value of a decoded instruction's register operand is held.
+ *
+ * Relies on x0..x31 being laid out at the start of struct cpu_user_regs in
+ * architectural register-number order; see the comment there.
+ */
+static __maybe_unused unsigned long *guest_gpr(struct cpu_user_regs *regs,
+                                               unsigned int reg)
+{
+    ASSERT(reg < 32);
+
+    return REG_PTR(reg, 0, regs);
+}
+
+/*
+ * Obtain the instruction which caused a guest MMIO trap, filling in
+ * @di->insn and @di->insn_len. It either comes transformed in htinst, or has
+ * to be fetched from guest memory.
+ *
+ * Returns true if the fetch faulted in turn; the resulting trap has then
+ * already been redirected to the guest and there is nothing further for the
+ * caller to do. Where it returns false, @di has been filled in and emulation
+ * is to continue.
+ */
+static bool __maybe_unused insn_fetch_faulted(const struct guest_fault *gf,
+                                              struct decoded_insn *di)
+{
+    unsigned long htinst = gf->htinst;
+
+    /*
+     * A pseudoinstruction says nothing about the instruction the guest was
+     * executing, and comes with a guest physical address which isn't the one
+     * that instruction accessed. handle_guest_page_fault() deals with such a
+     * fault on its own, so no emulation can ever start for one.
+     */
+    ASSERT(!htinst_is_pseudo(htinst));
+
+    if ( htinst & BIT(0, UL) )
+    {
+        /*
+         * Bit[0] == 1 implies trapped instruction value is
+         * transformed instruction or custom instruction.
+         *
+         * The transformation always yields the 32-bit format, with bits[1:0]
+         * holding a marker instead of the original opcode bits: bit[0] set to
+         * flag the transformation, bit[1] clear if the trapped instruction
+         * was a compressed one. Restoring the opcode bits makes the value the
+         * valid 32-bit encoding decode_ldst_insn() matches against. Its
+         * INSN_MASK_C_* cases exist for the branch below, where a compressed
+         * instruction is read from guest memory as is: a trapped one arrives
+         * here already expanded to its 32-bit equivalent, and the opcode bits
+         * just restored keep it from matching those cases anyway.
+         *
+         * The length then cannot come from the value anymore, only from
+         * bit[1]. And only a 16- or a 32-bit instruction is ever reported
+         * this way: the standard load and store instructions the hardware
+         * transforms are all of one of these two lengths, anything else comes
+         * as the zero special value handled below.
+         */
+        di->insn = htinst | INSN_16BIT_MASK;
+        di->insn_len = (htinst & BIT(1, UL)) ? 4 : 2;
+    }
+    else
+    {
+        const struct cpu_user_regs *regs = gf->regs;
+        struct trap_info utrap = {};
+
+        /*
+         * Bit[0] == 0 implies trapped instruction value is
+         * zero or special value. With the pseudoinstructions ruled out
+         * above, only zero is left: the instruction has to be read from
+         * guest memory.
+         */
+
+        di->insn = riscv_read_guest(regs->sepc, true, &utrap);
+        if ( utrap.scause )
+        {
+            /*
+             * If during getting of trapped instruction a fault happen in
+             * G-stage translation then CAUSE_LOAD_GUEST_PAGE_FAULT is
+             * generated. Such faults during this operation is considered as
+             * bus error.
+             */
+            if ( is_load_guest_page_fault(utrap.scause) )
+                utrap.scause = CAUSE_FETCH_ACCESS;
+
+            utrap.sepc = regs->sepc;
+
+            trap_redirect(&utrap);
+
+            return true;
+        }
+
+        /*
+         * riscv_read_guest() fetches at most two halfwords, so a wider
+         * encoding has been read in part only and cannot be decoded here.
+         *
+         * Report an illegal instruction, which is what the guest would have
+         * got for such an encoding anyway: the ISA defines no instruction
+         * wider than 32 bits.
+         */
+        if ( !INSN_IS_16BIT(di->insn) && !INSN_IS_32BIT(di->insn) )
+        {
+            utrap.sepc = regs->sepc;
+            utrap.scause = CAUSE_ILLEGAL_INSTRUCTION;
+            /*
+             * stval is left zero: the spec allows that for an illegal
+             * instruction, and only part of the instruction is in hand.
+             */
+
+            trap_redirect(&utrap);
+
+            return true;
+        }
+
+        di->insn_len = INSN_LEN(di->insn);
+    }
+
+    return false;
+}
+
+/*
+ * Decode the load or store instruction fetched into @di, filling in the
+ * remaining fields of it (@di->insn and @di->insn_len are filled by
+ * insn_fetch_faulted()).
+ *
+ * @xlen is the effective XLEN of the guest, needed as
+ * the encodings which exist for XLEN=64 only must not be recognized for a
+ * 32-bit guest.
+ *
+ * Returns false if the instruction is not a load or store which can be
+ * emulated here.
+ */
+static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di,
+                                            unsigned int xlen)
+{
+    unsigned long insn = di->insn;
+    /* Register fields of the uncompressed forms ... */
+    unsigned int rd = RV_RD(insn);
+    unsigned int rs2 = RV_RS2(insn);
+    /*
+     * ... and of the compressed ones, where the 3-bit field selects one of
+     * x8..x15, while the stack-pointer-relative forms have a full-width one.
+     */
+    unsigned int rs2s = RVC_RS2S(insn);
+    unsigned int rs2c = RVC_RS2(insn);
+
+    di->is_write = false;
+    di->is_unsigned = false;
+    di->reg = rd;
+
+    if ( (insn & INSN_MASK_LB) == INSN_MATCH_LB )
+        di->len = 1;
+    else if ( (insn & INSN_MASK_LBU) == INSN_MATCH_LBU )
+    {
+        di->len = 1;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LH) == INSN_MATCH_LH )
+        di->len = 2;
+    else if ( (insn & INSN_MASK_LHU) == INSN_MATCH_LHU )
+    {
+        di->len = 2;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LW) == INSN_MATCH_LW )
+        di->len = 4;
+    else if ( xlen == 64 && (insn & INSN_MASK_LWU) == INSN_MATCH_LWU )
+    {
+        di->len = 4;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_C_LW) == INSN_MATCH_C_LW )
+    {
+        di->len = 4;
+        di->reg = rs2s;
+    }
+    /* c.lwsp and c.ldsp are reserved with rd being x0. */
+    else if ( (insn & INSN_MASK_C_LWSP) == INSN_MATCH_C_LWSP && rd )
+        di->len = 4;
+    else if ( xlen == 64 && (insn & INSN_MASK_LD) == INSN_MATCH_LD )
+        di->len = 8;
+    else if ( xlen == 64 && (insn & INSN_MASK_C_LD) == INSN_MATCH_C_LD )
+    {
+        di->len = 8;
+        di->reg = rs2s;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_C_LDSP) == INSN_MATCH_C_LDSP &&
+              rd )
+        di->len = 8;
+    else if ( (insn & INSN_MASK_SB) == INSN_MATCH_SB )
+    {
+        di->len = 1;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( (insn & INSN_MASK_SH) == INSN_MATCH_SH )
+    {
+        di->len = 2;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( (insn & INSN_MASK_SW) == INSN_MATCH_SW )
+    {
+        di->len = 4;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( (insn & INSN_MASK_C_SW) == INSN_MATCH_C_SW )
+    {
+        di->len = 4;
+        di->is_write = true;
+        di->reg = rs2s;
+    }
+    else if ( (insn & INSN_MASK_C_SWSP) == INSN_MATCH_C_SWSP )
+    {
+        di->len = 4;
+        di->is_write = true;
+        di->reg = rs2c;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_SD) == INSN_MATCH_SD )
+    {
+        di->len = 8;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_C_SD) == INSN_MATCH_C_SD )
+    {
+        di->len = 8;
+        di->is_write = true;
+        di->reg = rs2s;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_C_SDSP) == INSN_MATCH_C_SDSP )
+    {
+        di->len = 8;
+        di->is_write = true;
+        di->reg = rs2c;
+    }
+    else
+        return false;
+
+    return true;
+}
+
 static int emulate_load(const struct guest_fault *gf)
 {
     return -EOPNOTSUPP;
xen/arch/riscv/include/asm/guest_access.h +4 -0
index 8d679319ded0..39c28dd2ecaa 100644
@@ -5,6 +5,7 @@
 #include <xen/types.h>
 
 struct domain;
+struct trap_info;
 
 unsigned long raw_copy_to_guest(void *to, const void *from, unsigned len);
 unsigned long raw_copy_from_guest(void *to, const void *from, unsigned len);
@@ -25,6 +26,9 @@ unsigned long raw_clear_guest(void *to, unsigned int len);
 unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,
                                  unsigned long len);
 
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap);
+
 #endif /* ASM__RISCV__GUEST_ACCESS_H */
 /*
  * Local variables:
xen/arch/riscv/include/asm/riscv_encoding.h +10 -0
index b2071f47587c..656a5fcccb0e 100644
@@ -65,6 +65,14 @@
 #define SSTATUS64_UXL			MSTATUS_UXL
 #define SSTATUS64_SD			MSTATUS64_SD
 
+/*
+ * Width encoded by the MXL, SXL, UXL and VSXL fields, all of which share one
+ * encoding. 0 is reserved.
+ */
+#define XLEN_FIELD_32			_UL(1)
+#define XLEN_FIELD_64			_UL(2)
+#define XLEN_FIELD_128			_UL(3)
+
 #if __riscv_xlen == 64
 #define HSTATUS_VSXL			_UL(0x300000000)
 #define HSTATUS_VSXL_SHIFT		32
@@ -896,6 +904,8 @@
 					 (RV_X(x, 7, 2) << 6))
 #define RVC_SDSP_IMM(x)			((RV_X(x, 10, 3) << 3) | \
 					 (RV_X(x, 7, 3) << 6))
+#define RV_RD(insn)			RV_X(insn, SH_RD, 5)
+#define RV_RS2(insn)			RV_X(insn, SH_RS2, 5)
 #define RVC_RS1S(insn)			(8 + RV_X(insn, SH_RD, 3))
 #define RVC_RS2S(insn)			(8 + RV_X(insn, SH_RS2C, 3))
 #define RVC_RS2(insn)			RV_X(insn, SH_RS2C, 5)
Signature · 1 line
2.55.0
#151 lore raw

Re: [PATCH v2 24/39] xen/riscv: add helpers for decoding a trapped load or store

Quoted 11 lines · Oleksii Kurochko

emulate_load() and emulate_store() will both need to obtain the instruction which caused a guest MMIO trap, decode it, and locate the register operand it names. Add what the two share, ahead of either of them being implemented: struct decoded_insn, insn_fetch_faulted(), decode_ldst_insn(), guest_xlen(), guest_gpr() and advance_pc().

The mask/match chain is adapted from Linux's KVM RISC-V implementation.

Nothing calls any of this yet, so tag the functions __maybe_unused to keep the build going; the tags go away once emulate_load() and emulate_store() gain their bodies later.

That'll be a lot of churn to drop those __maybe_unused again. As this is merely transient, did you consider putting

   (void)is_load_guest_page_fault;

etc in e.g. emulate_load()?

Quoted 16 lines
xen/arch/riscv/emulate.c +9 -0
@@ -13,9 +14,29 @@
 #include <asm/csr.h>
 #include <asm/current.h>
 #include <asm/emulate.h>
+#include <asm/guest_access.h>
+#include <asm/processor.h>
 #include <asm/riscv_encoding.h>
 #include <asm/traps.h>
 
+/*
+ * Determine the trapped load or store instruction which caused a guest MMIO
+ * trap.
+ */
+struct decoded_insn {
+    /* The instruction itself, and its length in bytes. */
+    unsigned long insn;

xen/arch/riscv/emulate.c line 38

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+    unsigned int insn_len;
+    /* Width of the memory access, in bytes. */
+    unsigned int len;
+    /* Number of the register operand: rd for a load, rs2 for a store. */
+    unsigned int reg;
+    /* The access is a store rather than a load. */
+    bool is_write;
+    /* The load zero-extends its result rather than sign-extending it. */
+    bool is_unsigned;
+};

I wonder how efficient this is. With use of bitfield the size of this struct can likely be more than halved. With suitable choice of widths this may not even cause significantly worse generated code.

One thing in any event: Why would the insn field need to be wider than 32 bits?

xen/arch/riscv/emulate.c struct guest_fault { · line 66

Quoted 8 lines
xen/arch/riscv/emulate.c +4 -0
@@ -39,6 +60,71 @@ struct guest_fault {
     paddr_t gpa;
 };
 
+static bool is_load_guest_page_fault(unsigned long scause)
+{
+    return scause == CAUSE_LOAD_GUEST_PAGE_FAULT;
+}

With no "store" counterpart this may end up being a little fragile (at the use site(s)).

Quoted 15 lines
xen/arch/riscv/emulate.c +15 -0
+/*
+ * The effective XLEN of the guest at the point of the trap: hstatus.VSXL for a
+ * trap taken from VS-mode, vsstatus.UXL for one taken from VU-mode.
+ *
+ * VSXL is consulted whichever mode the trap came from, as it also gives the
+ * width of vsstatus itself: where VSXL says 32, that register has no UXL field
+ * to consult and VU-mode is 32-bit as well, there being nothing to configure.
+ *
+ * It is needed to decode a trapped instruction: the encodings which exist only
+ * for XLEN=64 must not be recognized for a 32-bit guest. Besides those simply
+ * being reserved there, the compressed ones are ambiguous: C.LD and C.FLW
+ * share the encoding 0x6000 (mask 0xe003), and likewise C.SD/C.FSW,
+ * C.LDSP/C.FLWSP and C.SDSP/C.FSWSP.
+ *
+ * IS_ENABLED() can't be used here as HSTATUS_VSXL is defined for

xen/arch/riscv/emulate.c struct guest_fault { · line 98

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+ * __riscv_xlen == 64 only, the field not existing on RV32 in the first place.
+ */
+static __maybe_unused unsigned int guest_xlen(const struct cpu_user_regs *regs)
+{
+#ifdef CONFIG_RISCV_32
+    return 32;
+#else
+    unsigned long xl = MASK_EXTR(regs->hstatus, HSTATUS_VSXL);
+
+    if ( (xl == XLEN_FIELD_64) && !(regs->sstatus & SSTATUS_SPP) )

How about xl > XLEN_FIELD_32 here, to be RV128-compatible?

Quoted 7 lines
xen/arch/riscv/emulate.c +3 -0
@@ -87,6 +173,250 @@ static void resolve_faulting_gpa(struct guest_fault *gf)
               (htinst_is_pseudo(gf->htinst) ? 0 : (gf->stval & 3));
 }
 
+/*
+ * Where the value of a decoded instruction's register operand is held.
+ *

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 188

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+ * Relies on x0..x31 being laid out at the start of struct cpu_user_regs in
+ * architectural register-number order; see the comment there.
+ */
+static __maybe_unused unsigned long *guest_gpr(struct cpu_user_regs *regs,
+                                               unsigned int reg)
+{
+    ASSERT(reg < 32);
+
+    return REG_PTR(reg, 0, regs);
+}

For future callers of this: For 32-bit environments hardware guarantees upper halves of registers to be zero?

Quoted 37 lines
xen/arch/riscv/emulate.c +37 -0
+/*
+ * Obtain the instruction which caused a guest MMIO trap, filling in
+ * @di->insn and @di->insn_len. It either comes transformed in htinst, or has
+ * to be fetched from guest memory.
+ *
+ * Returns true if the fetch faulted in turn; the resulting trap has then
+ * already been redirected to the guest and there is nothing further for the
+ * caller to do. Where it returns false, @di has been filled in and emulation
+ * is to continue.
+ */
+static bool __maybe_unused insn_fetch_faulted(const struct guest_fault *gf,
+                                              struct decoded_insn *di)
+{
+    unsigned long htinst = gf->htinst;
+
+    /*
+     * A pseudoinstruction says nothing about the instruction the guest was
+     * executing, and comes with a guest physical address which isn't the one
+     * that instruction accessed. handle_guest_page_fault() deals with such a
+     * fault on its own, so no emulation can ever start for one.
+     */
+    ASSERT(!htinst_is_pseudo(htinst));
+
+    if ( htinst & BIT(0, UL) )
+    {
+        /*
+         * Bit[0] == 1 implies trapped instruction value is
+         * transformed instruction or custom instruction.
+         *
+         * The transformation always yields the 32-bit format, with bits[1:0]
+         * holding a marker instead of the original opcode bits: bit[0] set to
+         * flag the transformation, bit[1] clear if the trapped instruction
+         * was a compressed one. Restoring the opcode bits makes the value the
+         * valid 32-bit encoding decode_ldst_insn() matches against. Its
+         * INSN_MASK_C_* cases exist for the branch below, where a compressed
+         * instruction is read from guest memory as is: a trapped one arrives
+         * here already expanded to its 32-bit equivalent, and the opcode bits

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 236

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+         * just restored keep it from matching those cases anyway.
+         *
+         * The length then cannot come from the value anymore, only from
+         * bit[1]. And only a 16- or a 32-bit instruction is ever reported
+         * this way: the standard load and store instructions the hardware
+         * transforms are all of one of these two lengths, anything else comes
+         * as the zero special value handled below.
+         */
+        di->insn = htinst | INSN_16BIT_MASK;
+        di->insn_len = (htinst & BIT(1, UL)) ? 4 : 2;

Hmm, so ->insn_len doesn't describe ->insn, as suggested by the comment in the struct. That wants clarifying there.

Quoted 16 lines
xen/arch/riscv/emulate.c +16 -0
+    }
+    else
+    {
+        const struct cpu_user_regs *regs = gf->regs;
+        struct trap_info utrap = {};
+
+        /*
+         * Bit[0] == 0 implies trapped instruction value is
+         * zero or special value. With the pseudoinstructions ruled out
+         * above, only zero is left: the instruction has to be read from
+         * guest memory.
+         */
+
+        di->insn = riscv_read_guest(regs->sepc, true, &utrap);
+        if ( utrap.scause )
+        {

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 262

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+            /*
+             * If during getting of trapped instruction a fault happen in
+             * G-stage translation then CAUSE_LOAD_GUEST_PAGE_FAULT is
+             * generated. Such faults during this operation is considered as
+             * bus error.
+             */
+            if ( is_load_guest_page_fault(utrap.scause) )
+                utrap.scause = CAUSE_FETCH_ACCESS;
+
+            utrap.sepc = regs->sepc;

Couldn't this be part of the initializer of utrap? Or does read_guest() alter the field?

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 276

Quoted 13 lines
xen/arch/riscv/emulate.c +13 -0
+            trap_redirect(&utrap);
+
+            return true;
+        }
+
+        /*
+         * riscv_read_guest() fetches at most two halfwords, so a wider
+         * encoding has been read in part only and cannot be decoded here.
+         *
+         * Report an illegal instruction, which is what the guest would have
+         * got for such an encoding anyway: the ISA defines no instruction
+         * wider than 32 bits.
+         */

Such wording is at risk of going stale. Better say that no guest-exposed extensions have wider than 32-bit insns.

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 279

Quoted 3 lines
xen/arch/riscv/emulate.c +3 -0
+        if ( !INSN_IS_16BIT(di->insn) && !INSN_IS_32BIT(di->insn) )
+        {
+            utrap.sepc = regs->sepc;

With the earlier remark this may then also not be needed here.

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 284

Quoted 5 lines
xen/arch/riscv/emulate.c +5 -0
+            utrap.scause = CAUSE_ILLEGAL_INSTRUCTION;
+            /*
+             * stval is left zero: the spec allows that for an illegal
+             * instruction, and only part of the instruction is in hand.
+             */

Not just this - stval may also not be wide enough to hold the full insn.

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 291

Quoted 6 lines
xen/arch/riscv/emulate.c +6 -0
+            trap_redirect(&utrap);
+
+            return true;
+        }
+
+        di->insn_len = INSN_LEN(di->insn);

If you moved this up a little, you could avoid the separate use of INSN_{32,64}BIT_MASK above, by going from the value calculated here.

Quoted 23 lines
xen/arch/riscv/emulate.c +23 -0
+    }
+
+    return false;
+}
+
+/*
+ * Decode the load or store instruction fetched into @di, filling in the
+ * remaining fields of it (@di->insn and @di->insn_len are filled by
+ * insn_fetch_faulted()).
+ *
+ * @xlen is the effective XLEN of the guest, needed as
+ * the encodings which exist for XLEN=64 only must not be recognized for a
+ * 32-bit guest.
+ *
+ * Returns false if the instruction is not a load or store which can be
+ * emulated here.
+ */
+static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di,
+                                            unsigned int xlen)
+{
+    unsigned long insn = di->insn;
+    /* Register fields of the uncompressed forms ... */
+    unsigned int rd = RV_RD(insn);

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 324

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+    unsigned int rs2 = RV_RS2(insn);
+    /*
+     * ... and of the compressed ones, where the 3-bit field selects one of
+     * x8..x15, while the stack-pointer-relative forms have a full-width one.
+     */
+    unsigned int rs2s = RVC_RS2S(insn);
+    unsigned int rs2c = RVC_RS2(insn);
+
+    di->is_write = false;
+    di->is_unsigned = false;

Elsewhere we established that the whole struct has to start out zeroed. Why not leverage that also here?

Quoted 18 lines
xen/arch/riscv/emulate.c +18 -0
+    di->reg = rd;
+
+    if ( (insn & INSN_MASK_LB) == INSN_MATCH_LB )
+        di->len = 1;
+    else if ( (insn & INSN_MASK_LBU) == INSN_MATCH_LBU )
+    {
+        di->len = 1;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LH) == INSN_MATCH_LH )
+        di->len = 2;
+    else if ( (insn & INSN_MASK_LHU) == INSN_MATCH_LHU )
+    {
+        di->len = 2;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LW) == INSN_MATCH_LW )
+        di->len = 4;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 352

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+    else if ( xlen == 64 && (insn & INSN_MASK_LWU) == INSN_MATCH_LWU )
+    {
+        di->len = 4;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_C_LW) == INSN_MATCH_C_LW )
+    {
+        di->len = 4;
+        di->reg = rs2s;
+    }

These insns encode the access width uniformly, i.e. doing things the way done above is rather inefficient.

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 355

Quoted 3 lines
xen/arch/riscv/emulate.c +3 -0
+    /* c.lwsp and c.ldsp are reserved with rd being x0. */
+    else if ( (insn & INSN_MASK_C_LWSP) == INSN_MATCH_C_LWSP && rd )
+        di->len = 4;

Careful with insns not part of the base ISA: Between the trap and you getting to fetch and decode, the in-memory insn may have changed. You posibly set yourself up for vulnerabilities if you permit C encodings for guests not having C exposed to them.

Jan

#152 lore raw

Re: [PATCH v2 24/39] xen/riscv: add helpers for decoding a trapped load or store

Quoted 13 lines · Jan Beulich
Quoted 11 lines · Oleksii Kurochko

emulate_load() and emulate_store() will both need to obtain the instruction which caused a guest MMIO trap, decode it, and locate the register operand it names. Add what the two share, ahead of either of them being implemented: struct decoded_insn, insn_fetch_faulted(), decode_ldst_insn(), guest_xlen(), guest_gpr() and advance_pc().

The mask/match chain is adapted from Linux's KVM RISC-V implementation.

Nothing calls any of this yet, so tag the functions __maybe_unused to keep the build going; the tags go away once emulate_load() and emulate_store() gain their bodies later.

Quoted 6 lines

That'll be a lot of churn to drop those __maybe_unused again. As this is merely transient, did you consider putting

    (void)is_load_guest_page_fault;

etc in e.g. emulate_load()?

I think it could be really an option. I will rework in that way.

Quoted 23 lines
Quoted 23 lines
xen/arch/riscv/emulate.c +15 -0
@@ -13,9 +14,29 @@
  #include <asm/csr.h>
  #include <asm/current.h>
  #include <asm/emulate.h>
+#include <asm/guest_access.h>
+#include <asm/processor.h>
  #include <asm/riscv_encoding.h>
  #include <asm/traps.h>
 
+/*
+ * Determine the trapped load or store instruction which caused a guest MMIO
+ * trap.
+ */
+struct decoded_insn {
+    /* The instruction itself, and its length in bytes. */
+    unsigned long insn;
+    unsigned int insn_len;
+    /* Width of the memory access, in bytes. */
+    unsigned int len;
+    /* Number of the register operand: rd for a load, rs2 for a store. */
+    unsigned int reg;
+    /* The access is a store rather than a load. */
Quoted 9 lines

xen/arch/riscv/emulate.c line 38

Quoted 4 lines
xen/arch/riscv/emulate.c +4 -0
+    bool is_write;
+    /* The load zero-extends its result rather than sign-extending it. */
+    bool is_unsigned;
+};

I wonder how efficient this is. With use of bitfield the size of this struct can likely be more than halved. With suitable choice of widths this may not even cause significantly worse generated code.

We could compress the structure into 8 bytes:

struct decoded_insn {
    /*
     * The instruction itself: no ratified extension defines one wider than
     * 32 bits, and insn_fetch_faulted() rejects anything longer.
     */
    uint32_t insn;
    /* Length of the instruction in bytes: 2 or 4. */
    unsigned int insn_len:3;
    /* Width of the memory access, in bytes: 1, 2, 4 or 8. */
    unsigned int len:4;
    /* Number of the register operand: rd for a load, rs2 for a store. */
    unsigned int reg:5;
    /* The access is a store rather than a load. */
    bool is_write:1;
    /* The load zero-extends its result rather than sign-extending it. */
    bool is_unsigned:1;
};
Quoted 2 lines

One thing in any event: Why would the insn field need to be wider than 32 bits?

Initial idea was that htinst register is HSXLEN so here it will be nice to emphasize this.

But considering that read_guest() can read maximum 32-bit instructions and no ratified extension defines one wider than 32 bits, and insn_fetch_faulted() rejects anything longer then we could really use here uint32_t for insn + the comment will be useful:

struct decoded_insn {
/*
* The trapped instruction: as read from guest memory, or the 32-bit
* equivalent the hardware transformed it into (see
insn_fetch_faulted()).
* None of the extensions exposed to guests has instructions wider than
* 32 bits, and insn_fetch_faulted() rejects anything longer. */
uint32_t insn;

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/emulate.c +0 -0
@@ -39,6 +60,71 @@ struct guest_fault {
      paddr_t gpa;
  };
 
Quoted 7 lines

xen/arch/riscv/emulate.c struct guest_fault { · line 66

Quoted 4 lines
xen/arch/riscv/emulate.c +4 -0
+static bool is_load_guest_page_fault(unsigned long scause)
+{
+    return scause == CAUSE_LOAD_GUEST_PAGE_FAULT;
+}

With no "store" counterpart this may end up being a little fragile (at the use site(s)).

I will drop then function and just open-code where it is used.

Quoted 20 lines
Quoted 20 lines
xen/arch/riscv/emulate.c +19 -0
+/*
+ * The effective XLEN of the guest at the point of the trap: hstatus.VSXL for a
+ * trap taken from VS-mode, vsstatus.UXL for one taken from VU-mode.
+ *
+ * VSXL is consulted whichever mode the trap came from, as it also gives the
+ * width of vsstatus itself: where VSXL says 32, that register has no UXL field
+ * to consult and VU-mode is 32-bit as well, there being nothing to configure.
+ *
+ * It is needed to decode a trapped instruction: the encodings which exist only
+ * for XLEN=64 must not be recognized for a 32-bit guest. Besides those simply
+ * being reserved there, the compressed ones are ambiguous: C.LD and C.FLW
+ * share the encoding 0x6000 (mask 0xe003), and likewise C.SD/C.FSW,
+ * C.LDSP/C.FLWSP and C.SDSP/C.FSWSP.
+ *
+ * IS_ENABLED() can't be used here as HSTATUS_VSXL is defined for
+ * __riscv_xlen == 64 only, the field not existing on RV32 in the first place.
+ */
+static __maybe_unused unsigned int guest_xlen(const struct cpu_user_regs *regs)
+{
Quoted 8 lines

xen/arch/riscv/emulate.c struct guest_fault { · line 98

Quoted 6 lines
xen/arch/riscv/emulate.c +6 -0
+#ifdef CONFIG_RISCV_32
+    return 32;
+#else
+    unsigned long xl = MASK_EXTR(regs->hstatus, HSTATUS_VSXL);
+
+    if ( (xl == XLEN_FIELD_64) && !(regs->sstatus & SSTATUS_SPP) )

How about xl > XLEN_FIELD_32 here, to be RV128-compatible?

good point. I'll apply.

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/emulate.c +0 -0
@@ -87,6 +173,250 @@ static void resolve_faulting_gpa(struct guest_fault *gf)
                (htinst_is_pseudo(gf->htinst) ? 0 : (gf->stval & 3));
  }
 
Quoted 16 lines

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 188

Quoted 13 lines
xen/arch/riscv/emulate.c +13 -0
+/*
+ * Where the value of a decoded instruction's register operand is held.
+ *
+ * Relies on x0..x31 being laid out at the start of struct cpu_user_regs in
+ * architectural register-number order; see the comment there.
+ */
+static __maybe_unused unsigned long *guest_gpr(struct cpu_user_regs *regs,
+                                               unsigned int reg)
+{
+    ASSERT(reg < 32);
+
+    return REG_PTR(reg, 0, regs);
+}

For future callers of this: For 32-bit environments hardware guarantees upper halves of registers to be zero?

I think that no as according to the spec:

Whenever XLEN in any mode is set to a value less than the widest supported XLEN, all operations must ignore source operand register bits above the configured XLEN, and must sign-extend results to fill the entire widest supported XLEN in the destination register. Similarly, pc bits above XLEN are ignored, and when the pc is written, it is sign-extended to fill the widest supported XLEN.

I think we want to add the following to the comment above guest_gpr():

* The register is held at its full width, whatever the guest's XLEN is (see
* guest_xlen()). Where XLEN is narrower, the bits above it are not
guaranteed
* to be zero, nor even a sign extension: hardware only ignores them in
source
* operands, so they may have been left there by more privileged code
running
* at a wider XLEN. Hence callers must not rely on those bits when
reading a
* value, and must sign-extend what they write from bit XLEN-1, as hardware
* does for the result of an operation.

Quoted 43 lines
Quoted 43 lines
xen/arch/riscv/emulate.c +42 -0
+/*
+ * Obtain the instruction which caused a guest MMIO trap, filling in
+ * @di->insn and @di->insn_len. It either comes transformed in htinst, or has
+ * to be fetched from guest memory.
+ *
+ * Returns true if the fetch faulted in turn; the resulting trap has then
+ * already been redirected to the guest and there is nothing further for the
+ * caller to do. Where it returns false, @di has been filled in and emulation
+ * is to continue.
+ */
+static bool __maybe_unused insn_fetch_faulted(const struct guest_fault *gf,
+                                              struct decoded_insn *di)
+{
+    unsigned long htinst = gf->htinst;
+
+    /*
+     * A pseudoinstruction says nothing about the instruction the guest was
+     * executing, and comes with a guest physical address which isn't the one
+     * that instruction accessed. handle_guest_page_fault() deals with such a
+     * fault on its own, so no emulation can ever start for one.
+     */
+    ASSERT(!htinst_is_pseudo(htinst));
+
+    if ( htinst & BIT(0, UL) )
+    {
+        /*
+         * Bit[0] == 1 implies trapped instruction value is
+         * transformed instruction or custom instruction.
+         *
+         * The transformation always yields the 32-bit format, with bits[1:0]
+         * holding a marker instead of the original opcode bits: bit[0] set to
+         * flag the transformation, bit[1] clear if the trapped instruction
+         * was a compressed one. Restoring the opcode bits makes the value the
+         * valid 32-bit encoding decode_ldst_insn() matches against. Its
+         * INSN_MASK_C_* cases exist for the branch below, where a compressed
+         * instruction is read from guest memory as is: a trapped one arrives
+         * here already expanded to its 32-bit equivalent, and the opcode bits
+         * just restored keep it from matching those cases anyway.
+         *
+         * The length then cannot come from the value anymore, only from
+         * bit[1]. And only a 16- or a 32-bit instruction is ever reported
+         * this way: the standard load and store instructions the hardware
Quoted 8 lines

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 236

Quoted 5 lines
xen/arch/riscv/emulate.c +5 -0
+         * transforms are all of one of these two lengths, anything else comes
+         * as the zero special value handled below.
+         */
+        di->insn = htinst | INSN_16BIT_MASK;
+        di->insn_len = (htinst & BIT(1, UL)) ? 4 : 2;

Hmm, so ->insn_len doesn't describe ->insn, as suggested by the comment in the struct. That wants clarifying there.

Right, insn_len is the length of the trapped instruction in guest memory, which is what advance_pc() needs, whereas insn may hold its 32-bit transformed equivalent. I'll clarify both comments in the struct.:

struct decoded_insn {
/*
* The trapped instruction: as read from guest memory, or the 32-bit
* equivalent the hardware transformed it into (see
insn_fetch_faulted()).
* None of the extensions exposed to guests has instructions wider than
* 32 bits, and insn_fetch_faulted() rejects anything longer. */
uint32_t insn;
/*
* Length in bytes of the trapped instruction in guest memory: 2 or 4.
* This need not be the length of the encoding in insn, as a compressed
* instruction may have been transformed into its 32-bit equivalent. */
unsigned int insn_len:3;

Quoted 22 lines
Quoted 22 lines
xen/arch/riscv/emulate.c +21 -0
+    }
+    else
+    {
+        const struct cpu_user_regs *regs = gf->regs;
+        struct trap_info utrap = {};
+
+        /*
+         * Bit[0] == 0 implies trapped instruction value is
+         * zero or special value. With the pseudoinstructions ruled out
+         * above, only zero is left: the instruction has to be read from
+         * guest memory.
+         */
+
+        di->insn = riscv_read_guest(regs->sepc, true, &utrap);
+        if ( utrap.scause )
+        {
+            /*
+             * If during getting of trapped instruction a fault happen in
+             * G-stage translation then CAUSE_LOAD_GUEST_PAGE_FAULT is
+             * generated. Such faults during this operation is considered as
+             * bus error.
Quoted 8 lines

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 262

Quoted 5 lines
xen/arch/riscv/emulate.c +5 -0
+             */
+            if ( is_load_guest_page_fault(utrap.scause) )
+                utrap.scause = CAUSE_FETCH_ACCESS;
+
+            utrap.sepc = regs->sepc;

Couldn't this be part of the initializer of utrap? Or does read_guest() alter the field?

It can't: on a fault read_guest() overwrites it. The exception table fixup records the sepc of the nested trap, i.e. Xen's own PC at the faulting hlvx, while the trap is to be reported to the guest at its instruction. I'll add a comment saying so:

/*
* Not set in the initializer: on a fault read_guest()
leaves in
* utrap.sepc the address of its own faulting access,
whereas the

             * trap is to be reported at the guest instruction.
             */
            utrap.sepc = regs->sepc;
Quoted 17 lines
Quoted 4 lines
xen/arch/riscv/emulate.c +3 -0
+            trap_redirect(&utrap);
+
+            return true;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 276

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+        }
+
+        /*
+         * riscv_read_guest() fetches at most two halfwords, so a wider
+         * encoding has been read in part only and cannot be decoded here.
+         *
+         * Report an illegal instruction, which is what the guest would have
+         * got for such an encoding anyway: the ISA defines no instruction
+         * wider than 32 bits.
+         */

Such wording is at risk of going stale. Better say that no guest-exposed extensions have wider than 32-bit insns.

I will re-word in the following way:

/*
* read_guest() fetches at most two halfwords, so a wider
encoding has
* been read in part only and cannot be decoded here.
*
* Report an illegal instruction: none of the extensions exposed to
* guests has instructions wider than 32 bits, so such an
encoding is
* not a valid instruction for the guest in the first place. */

Quoted 7 lines

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 279

Quoted 4 lines
xen/arch/riscv/emulate.c +3 -0
+        if ( !INSN_IS_16BIT(di->insn) && !INSN_IS_32BIT(di->insn) )
+        {
+            utrap.sepc = regs->sepc;

With the earlier remark this may then also not be needed here.

Quoted 7 lines

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 284

Quoted 5 lines
xen/arch/riscv/emulate.c +5 -0
+            utrap.scause = CAUSE_ILLEGAL_INSTRUCTION;
+            /*
+             * stval is left zero: the spec allows that for an illegal
+             * instruction, and only part of the instruction is in hand.
+             */

Not just this - stval may also not be wide enough to hold the full insn.

Right, I'll mention that as well:

/*
* stval is left zero, which the spec allows for an illegal
* instruction: only part of the instruction is in hand,
and stval,
* being only XLEN bits wide, may not be able to hold all of it
* anyway.
*/

Quoted 11 lines

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 291

Quoted 7 lines
xen/arch/riscv/emulate.c +6 -0
+            trap_redirect(&utrap);
+
+            return true;
+        }
+
+        di->insn_len = INSN_LEN(di->insn);

If you moved this up a little, you could avoid the separate use of INSN_{32,64}BIT_MASK above, by going from the value calculated here.

I will do in this way as INSN_LEN() will (after a conversation in another thread) return zero if insn is something not 16 or 32:

        di->insn_len = INSN_LEN(di->insn);
...
        if ( !di->insn_len )
Quoted 28 lines
Quoted 28 lines
xen/arch/riscv/emulate.c +28 -0
+    }
+
+    return false;
+}
+
+/*
+ * Decode the load or store instruction fetched into @di, filling in the
+ * remaining fields of it (@di->insn and @di->insn_len are filled by
+ * insn_fetch_faulted()).
+ *
+ * @xlen is the effective XLEN of the guest, needed as
+ * the encodings which exist for XLEN=64 only must not be recognized for a
+ * 32-bit guest.
+ *
+ * Returns false if the instruction is not a load or store which can be
+ * emulated here.
+ */
+static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di,
+                                            unsigned int xlen)
+{
+    unsigned long insn = di->insn;
+    /* Register fields of the uncompressed forms ... */
+    unsigned int rd = RV_RD(insn);
+    unsigned int rs2 = RV_RS2(insn);
+    /*
+     * ... and of the compressed ones, where the 3-bit field selects one of
+     * x8..x15, while the stack-pointer-relative forms have a full-width one.
+     */
Quoted 8 lines

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 324

Quoted 5 lines
xen/arch/riscv/emulate.c +5 -0
+    unsigned int rs2s = RVC_RS2S(insn);
+    unsigned int rs2c = RVC_RS2(insn);
+
+    di->is_write = false;
+    di->is_unsigned = false;

Elsewhere we established that the whole struct has to start out zeroed. Why not leverage that also here?

The callers don't actually zero it at present: di is declared without an initializer in both emulate_load() and emulate_store(), which is why these two fields get reset here. But I agree that's the better way: I'll have both callers initialize di with {} and drop the resets, stating in the comment that @di is expected to start out zeroed:

"
... insn_fetch_faulted()). Fields which don't apply to the instruction are left
* alone, so @di is expected to start out zeroed.
"

Quoted 30 lines
Quoted 19 lines
xen/arch/riscv/emulate.c +18 -0
+    di->reg = rd;
+
+    if ( (insn & INSN_MASK_LB) == INSN_MATCH_LB )
+        di->len = 1;
+    else if ( (insn & INSN_MASK_LBU) == INSN_MATCH_LBU )
+    {
+        di->len = 1;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LH) == INSN_MATCH_LH )
+        di->len = 2;
+    else if ( (insn & INSN_MASK_LHU) == INSN_MATCH_LHU )
+    {
+        di->len = 2;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LW) == INSN_MATCH_LW )
+        di->len = 4;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 352

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+    else if ( xlen == 64 && (insn & INSN_MASK_LWU) == INSN_MATCH_LWU )
+    {
+        di->len = 4;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_C_LW) == INSN_MATCH_C_LW )
+    {
+        di->len = 4;
+        di->reg = rs2s;
+    }
Quoted 2 lines

These insns encode the access width uniformly, i.e. doing things the way done above is rather inefficient.

I think that I don't know how to do that better at the moment.

It could be less of if/else if to do in this way:

static bool decode_ldst_insn(struct decoded_insn *di, unsigned int xlen)

{
    uint32_t insn = di->insn;
    unsigned int funct3, width_log2;

    if ( INSN_IS_16BIT(insn) )
    {
        /*
         * C.LW, C.LD, C.SW and C.SD (bits[1:0] == 00), and their 
sp-relative
         * C.*SP forms (bits[1:0] == 10), have bits[15:13] of the form x1y:
         * x is set for a store, and y selects a width of 4 or 8 bytes.
         */
        funct3 = RV_X(insn, 13, 3);

        if ( (insn & 1) || !(funct3 & 2) )
            return false;

        di->is_write = funct3 & 4;
        width_log2 = 2 + (funct3 & 1);

        if ( !(insn & 2) )
            di->reg = RVC_RS2S(insn);
        else if ( di->is_write )
            di->reg = RVC_RS2(insn);
        else
        {
            di->reg = RV_RD(insn);
            /* C.LWSP and C.LDSP are reserved with rd being x0. */
            if ( !di->reg )
                return false;
        }
    }
    else
    {
        /*
         * funct3[1:0] is log2 of the width in bytes, and funct3[2] selects
         * zero-extension for a load, while being reserved for a store.
         */
        funct3 = RV_X(insn, 12, 3);
        width_log2 = funct3 & 3;

        switch ( insn & INSN_OPCODE_MASK )
        {
        case INSN_OPCODE_LOAD:
            di->is_unsigned = funct3 & 4;
            di->reg = RV_RD(insn);
            break;

        case INSN_OPCODE_STORE:
            if ( funct3 & 4 )
                return false;
            di->is_write = true;
            di->reg = RV_RS2(insn);
            break;

        default:
            return false;
        }
    }

    di->len = 1U << width_log2;

    /*
     * No access is wider than XLEN, and one as wide as XLEN exists only in
     * its sign-extending form: this rules out the encodings which 
exist for
     * XLEN=64 only on a 32-bit guest, including C.FLW for C.LD (and 
alike).
     */
    if ( (di->len * BITS_PER_BYTE > xlen) ||
         (di->is_unsigned && di->len * BITS_PER_BYTE == xlen) )
        return false;

    return true;


    return true;
}

But I am not sure this is what you meant.

Quoted 9 lines

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 355

Quoted 4 lines
xen/arch/riscv/emulate.c +3 -0
+    /* c.lwsp and c.ldsp are reserved with rd being x0. */
+    else if ( (insn & INSN_MASK_C_LWSP) == INSN_MATCH_C_LWSP && rd )
+        di->len = 4;

Careful with insns not part of the base ISA: Between the trap and you getting to fetch and decode, the in-memory insn may have changed. You posibly set yourself up for vulnerabilities if you permit C encodings for guests not having C exposed to them.

I think then it will be better to reject it duing instruction fetch in insn_fetch_faulted():

        di->insn_len = INSN_LEN(di->insn);

        /*
         * read_guest() fetches at most two halfwords, so a wider 

encoding has
* been read in part only and cannot be decoded here.
*
* Report an illegal instruction: none of the extensions exposed to
* guests has instructions wider than 32 bits, so such an
encoding is
* not a valid instruction for the guest in the first place.
The same
* goes for a compressed encoding where C isn't exposed to the
guest:
* the instruction in memory may have been changed since the
trap, so

         * what is read back must not be taken to be what trapped.
         */
        if ( !di->insn_len ||
             (di->insn_len == 2 &&
              !riscv_isa_extension_available(current->domain->arch.isa,
                                             RISCV_ISA_EXT_c)) )
        {
            ...

Would it be better?

Thanks.

~ Oleksii

#153 lore raw

Re: [PATCH v2 24/39] xen/riscv: add helpers for decoding a trapped load or store

Quoted 45 lines · Oleksii Kurochko
Quoted 23 lines · Jan Beulich
Quoted 22 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c +15 -0
@@ -13,9 +14,29 @@
  #include <asm/csr.h>
  #include <asm/current.h>
  #include <asm/emulate.h>
+#include <asm/guest_access.h>
+#include <asm/processor.h>
  #include <asm/riscv_encoding.h>
  #include <asm/traps.h>
 
+/*
+ * Determine the trapped load or store instruction which caused a guest MMIO
+ * trap.
+ */
+struct decoded_insn {
+    /* The instruction itself, and its length in bytes. */
+    unsigned long insn;
+    unsigned int insn_len;
+    /* Width of the memory access, in bytes. */
+    unsigned int len;
+    /* Number of the register operand: rd for a load, rs2 for a store. */
+    unsigned int reg;
+    /* The access is a store rather than a load. */
Quoted 9 lines

xen/arch/riscv/emulate.c line 38

Quoted 4 lines
xen/arch/riscv/emulate.c +4 -0
+    bool is_write;
+    /* The load zero-extends its result rather than sign-extending it. */
+    bool is_unsigned;
+};

I wonder how efficient this is. With use of bitfield the size of this struct can likely be more than halved. With suitable choice of widths this may not even cause significantly worse generated code.

We could compress the structure into 8 bytes:

struct decoded_insn {
     /*
      * The instruction itself: no ratified extension defines one wider than
      * 32 bits, and insn_fetch_faulted() rejects anything longer.
      */
     uint32_t insn;
     /* Length of the instruction in bytes: 2 or 4. */
     unsigned int insn_len:3;
     /* Width of the memory access, in bytes: 1, 2, 4 or 8. */
Quoted 8 lines
     unsigned int len:4;
     /* Number of the register operand: rd for a load, rs2 for a store. */
     unsigned int reg:5;
     /* The access is a store rather than a load. */
     bool is_write:1;
     /* The load zero-extends its result rather than sign-extending it. */
     bool is_unsigned:1;
};

Likely this is going a little too far: The non-bool fields may want to be 8 bits wide, for better code gen.

Quoted 114 lines
Quoted 27 lines
Quoted 16 lines
xen/arch/riscv/emulate.c +16 -0
+    if ( (insn & INSN_MASK_LB) == INSN_MATCH_LB )
+        di->len = 1;
+    else if ( (insn & INSN_MASK_LBU) == INSN_MATCH_LBU )
+    {
+        di->len = 1;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LH) == INSN_MATCH_LH )
+        di->len = 2;
+    else if ( (insn & INSN_MASK_LHU) == INSN_MATCH_LHU )
+    {
+        di->len = 2;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LW) == INSN_MATCH_LW )
+        di->len = 4;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 352

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+    else if ( xlen == 64 && (insn & INSN_MASK_LWU) == INSN_MATCH_LWU )
+    {
+        di->len = 4;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_C_LW) == INSN_MATCH_C_LW )
+    {
+        di->len = 4;
+        di->reg = rs2s;
+    }
Quoted 2 lines

These insns encode the access width uniformly, i.e. doing things the way done above is rather inefficient.

I think that I don't know how to do that better at the moment.

It could be less of if/else if to do in this way:

static bool decode_ldst_insn(struct decoded_insn *di, unsigned int xlen)

{
     uint32_t insn = di->insn;
     unsigned int funct3, width_log2;

     if ( INSN_IS_16BIT(insn) )
     {
         /*
          * C.LW, C.LD, C.SW and C.SD (bits[1:0] == 00), and their 
sp-relative
          * C.*SP forms (bits[1:0] == 10), have bits[15:13] of the form x1y:
          * x is set for a store, and y selects a width of 4 or 8 bytes.
          */
         funct3 = RV_X(insn, 13, 3);

         if ( (insn & 1) || !(funct3 & 2) )
             return false;

         di->is_write = funct3 & 4;
         width_log2 = 2 + (funct3 & 1);

         if ( !(insn & 2) )
             di->reg = RVC_RS2S(insn);
         else if ( di->is_write )
             di->reg = RVC_RS2(insn);
         else
         {
             di->reg = RV_RD(insn);
             /* C.LWSP and C.LDSP are reserved with rd being x0. */
             if ( !di->reg )
                 return false;
         }
     }
     else
     {
         /*
          * funct3[1:0] is log2 of the width in bytes, and funct3[2] selects
          * zero-extension for a load, while being reserved for a store.
          */
         funct3 = RV_X(insn, 12, 3);
         width_log2 = funct3 & 3;

         switch ( insn & INSN_OPCODE_MASK )
         {
         case INSN_OPCODE_LOAD:
             di->is_unsigned = funct3 & 4;
             di->reg = RV_RD(insn);
             break;

         case INSN_OPCODE_STORE:
             if ( funct3 & 4 )
                 return false;
             di->is_write = true;
             di->reg = RV_RS2(insn);
             break;

         default:
             return false;
         }
     }

     di->len = 1U << width_log2;

     /*
      * No access is wider than XLEN, and one as wide as XLEN exists only in
      * its sign-extending form: this rules out the encodings which 
exist for
      * XLEN=64 only on a 32-bit guest, including C.FLW for C.LD (and 
alike).
      */
     if ( (di->len * BITS_PER_BYTE > xlen) ||
          (di->is_unsigned && di->len * BITS_PER_BYTE == xlen) )
         return false;

     return true;


     return true;
}
Quoted 1 line

But I am not sure this is what you meant.

Yes, this goes along the lines of what I was thinking of.

Quoted 37 lines
Quoted 8 lines

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 355

Quoted 3 lines
xen/arch/riscv/emulate.c +3 -0
+    /* c.lwsp and c.ldsp are reserved with rd being x0. */
+    else if ( (insn & INSN_MASK_C_LWSP) == INSN_MATCH_C_LWSP && rd )
+        di->len = 4;

Careful with insns not part of the base ISA: Between the trap and you getting to fetch and decode, the in-memory insn may have changed. You posibly set yourself up for vulnerabilities if you permit C encodings for guests not having C exposed to them.

I think then it will be better to reject it duing instruction fetch in insn_fetch_faulted():

         di->insn_len = INSN_LEN(di->insn);

         /*
          * read_guest() fetches at most two halfwords, so a wider 

encoding has
* been read in part only and cannot be decoded here.
*
* Report an illegal instruction: none of the extensions exposed to
* guests has instructions wider than 32 bits, so such an
encoding is
* not a valid instruction for the guest in the first place.
The same
* goes for a compressed encoding where C isn't exposed to the
guest:
* the instruction in memory may have been changed since the
trap, so

          * what is read back must not be taken to be what trapped.
          */
         if ( !di->insn_len ||
              (di->insn_len == 2 &&
               !riscv_isa_extension_available(current->domain->arch.isa,
                                              RISCV_ISA_EXT_c)) )
         {
             ...
Quoted 1 line

Would it be better?

It's an option. Where exactly the check is best placed I can't easily say.

Jan

#154 lore raw

Re: [PATCH v2 24/39] xen/riscv: add helpers for decoding a trapped load or store

In reply to Oleksii Kurochko
Quoted 7 lines

emulate_load() and emulate_store() will both need to obtain the instruction which caused a guest MMIO trap, decode it, and locate the register operand it names. Add what the two share, ahead of either of them being implemented: struct decoded_insn, insn_fetch_faulted(), decode_ldst_insn(), guest_xlen(), guest_gpr() and advance_pc().

The mask/match chain is adapted from Linux's KVM RISC-V implementation.

Nit: maybe you could add the Origin: trailer as mentioned in the sending-patches.adoc.

Quoted 284 lines

Nothing calls any of this yet, so tag the functions __maybe_unused to keep the build going; the tags go away once emulate_load() and emulate_store() gain their bodies later.

xen/arch/riscv/emulate.c +21 -0
index ff530ef2df..81a50643a5 100644
@@ -5,6 +5,7 @@
  */
 
 #include <xen/bug.h>
+#include <xen/compiler.h>
 #include <xen/errno.h>
 #include <xen/sched.h>
 #include <xen/types.h>
@@ -13,9 +14,29 @@
 #include <asm/csr.h>
 #include <asm/current.h>
 #include <asm/emulate.h>
+#include <asm/guest_access.h>
+#include <asm/processor.h>
 #include <asm/riscv_encoding.h>
 #include <asm/traps.h>
 
+/*
+ * Determine the trapped load or store instruction which caused a guest MMIO
+ * trap.
+ */
+struct decoded_insn {
+    /* The instruction itself, and its length in bytes. */
+    unsigned long insn;
+    unsigned int insn_len;
+    /* Width of the memory access, in bytes. */
+    unsigned int len;
+    /* Number of the register operand: rd for a load, rs2 for a store. */
+    unsigned int reg;
+    /* The access is a store rather than a load. */
+    bool is_write;
+    /* The load zero-extends its result rather than sign-extending it. */
+    bool is_unsigned;
+};
 
 
+
 /*

* The hardware-reported details of a guest page fault, gathered once by
* handle_guest_page_fault() and passed down to the emulation of the faulted

xen/arch/riscv/emulate.c +202 -0
@@ -39,6 +60,71 @@ struct guest_fault {
     paddr_t gpa;
 };
 
+static bool is_load_guest_page_fault(unsigned long scause)
+{
+    return scause == CAUSE_LOAD_GUEST_PAGE_FAULT;
+}
 
 
+
+static __maybe_unused void advance_pc(struct cpu_user_regs *regs,
+                                      unsigned int step)
+{
+    regs->sepc += step;
+}
+
+/*
+ * The effective XLEN of the guest at the point of the trap: hstatus.VSXL for a
+ * trap taken from VS-mode, vsstatus.UXL for one taken from VU-mode.
+ *
+ * VSXL is consulted whichever mode the trap came from, as it also gives the
+ * width of vsstatus itself: where VSXL says 32, that register has no UXL field
+ * to consult and VU-mode is 32-bit as well, there being nothing to configure.
+ *
+ * It is needed to decode a trapped instruction: the encodings which exist only
+ * for XLEN=64 must not be recognized for a 32-bit guest. Besides those simply
+ * being reserved there, the compressed ones are ambiguous: C.LD and C.FLW
+ * share the encoding 0x6000 (mask 0xe003), and likewise C.SD/C.FSW,
+ * C.LDSP/C.FLWSP and C.SDSP/C.FSWSP.
+ *
+ * IS_ENABLED() can't be used here as HSTATUS_VSXL is defined for
+ * __riscv_xlen == 64 only, the field not existing on RV32 in the first place.
+ */
+static __maybe_unused unsigned int guest_xlen(const struct cpu_user_regs *regs)
+{
+#ifdef CONFIG_RISCV_32
+    return 32;
+#else
+    unsigned long xl = MASK_EXTR(regs->hstatus, HSTATUS_VSXL);
+
+    if ( (xl == XLEN_FIELD_64) && !(regs->sstatus & SSTATUS_SPP) )
 
 
+        xl = MASK_EXTR(csr_read(CSR_VSSTATUS), SSTATUS64_UXL);
+
+    switch ( xl )
+    {
+    case XLEN_FIELD_32:
+        return 32;
+
+    case XLEN_FIELD_64:
+        return 64;
+
+    default:
+        /*
+         * The field holds nothing else in practice: XLEN_FIELD_128 would mean
+         * RV128, which no implementation provides, and the only value left is
+         * reserved. ASSERT_UNREACHABLE() being debug-only, a width still has
+         * to be answered in release builds.
+         *
+         * Answer 32, that being the safe way to be wrong: the decoder then
+         * fails to recognize the RV64-only encodings and emulation gives up.
+         * Answering 64 for what may well be a 32-bit guest would instead have
+         * it take C.FLW for C.LD and C.FSW for C.SD (see above), i.e. quietly
+         * emulate an access of the wrong width against the wrong register.
+         */
+        ASSERT_UNREACHABLE();
+        return 32;
+    }
+#endif
+}
+
 /*
  * Is @htinst one of the pseudoinstructions reported for a guest page fault
  * taken on an implicit memory access done for VS-stage address translation?
@@ -87,6 +173,250 @@ static void resolve_faulting_gpa(struct guest_fault *gf)
               (htinst_is_pseudo(gf->htinst) ? 0 : (gf->stval & 3));
 }
 
+/*
+ * Where the value of a decoded instruction's register operand is held.
+ *
+ * Relies on x0..x31 being laid out at the start of struct cpu_user_regs in
+ * architectural register-number order; see the comment there.
+ */
+static __maybe_unused unsigned long *guest_gpr(struct cpu_user_regs *regs,
+                                               unsigned int reg)
+{
+    ASSERT(reg < 32);
+
+    return REG_PTR(reg, 0, regs);
+}
 
 
+
+/*
+ * Obtain the instruction which caused a guest MMIO trap, filling in
+ * @di->insn and @di->insn_len. It either comes transformed in htinst, or has
+ * to be fetched from guest memory.
+ *
+ * Returns true if the fetch faulted in turn; the resulting trap has then
+ * already been redirected to the guest and there is nothing further for the
+ * caller to do. Where it returns false, @di has been filled in and emulation
+ * is to continue.
+ */
+static bool __maybe_unused insn_fetch_faulted(const struct guest_fault *gf,
+                                              struct decoded_insn *di)
+{
+    unsigned long htinst = gf->htinst;
+
+    /*
+     * A pseudoinstruction says nothing about the instruction the guest was
+     * executing, and comes with a guest physical address which isn't the one
+     * that instruction accessed. handle_guest_page_fault() deals with such a
+     * fault on its own, so no emulation can ever start for one.
+     */
+    ASSERT(!htinst_is_pseudo(htinst));
+
+    if ( htinst & BIT(0, UL) )
+    {
+        /*
+         * Bit[0] == 1 implies trapped instruction value is
+         * transformed instruction or custom instruction.
+         *
+         * The transformation always yields the 32-bit format, with bits[1:0]
+         * holding a marker instead of the original opcode bits: bit[0] set to
+         * flag the transformation, bit[1] clear if the trapped instruction
+         * was a compressed one. Restoring the opcode bits makes the value the
+         * valid 32-bit encoding decode_ldst_insn() matches against. Its
+         * INSN_MASK_C_* cases exist for the branch below, where a compressed
+         * instruction is read from guest memory as is: a trapped one arrives
+         * here already expanded to its 32-bit equivalent, and the opcode bits
+         * just restored keep it from matching those cases anyway.
+         *
+         * The length then cannot come from the value anymore, only from
+         * bit[1]. And only a 16- or a 32-bit instruction is ever reported
+         * this way: the standard load and store instructions the hardware
+         * transforms are all of one of these two lengths, anything else comes
+         * as the zero special value handled below.
+         */
+        di->insn = htinst | INSN_16BIT_MASK;
+        di->insn_len = (htinst & BIT(1, UL)) ? 4 : 2;
 
 
+    }
+    else
+    {
+        const struct cpu_user_regs *regs = gf->regs;
+        struct trap_info utrap = {};
+
+        /*
+         * Bit[0] == 0 implies trapped instruction value is
+         * zero or special value. With the pseudoinstructions ruled out
+         * above, only zero is left: the instruction has to be read from
+         * guest memory.
+         */
+
+        di->insn = riscv_read_guest(regs->sepc, true, &utrap);
+        if ( utrap.scause )
+        {
+            /*
+             * If during getting of trapped instruction a fault happen in
+             * G-stage translation then CAUSE_LOAD_GUEST_PAGE_FAULT is
+             * generated. Such faults during this operation is considered as
+             * bus error.
+             */
+            if ( is_load_guest_page_fault(utrap.scause) )
+                utrap.scause = CAUSE_FETCH_ACCESS;
+
+            utrap.sepc = regs->sepc;
 
 
+
+            trap_redirect(&utrap);
+
+            return true;
+        }
+
+        /*
+         * riscv_read_guest() fetches at most two halfwords, so a wider
+         * encoding has been read in part only and cannot be decoded here.
+         *
+         * Report an illegal instruction, which is what the guest would have
+         * got for such an encoding anyway: the ISA defines no instruction
+         * wider than 32 bits.
+         */
 
 
+        if ( !INSN_IS_16BIT(di->insn) && !INSN_IS_32BIT(di->insn) )
+        {
+            utrap.sepc = regs->sepc;
 
 
+            utrap.scause = CAUSE_ILLEGAL_INSTRUCTION;
+            /*
+             * stval is left zero: the spec allows that for an illegal
+             * instruction, and only part of the instruction is in hand.
+             */
 
 
+
+            trap_redirect(&utrap);
+
+            return true;
+        }
+
+        di->insn_len = INSN_LEN(di->insn);
 
 
+    }
+
+    return false;
+}
+
+/*
+ * Decode the load or store instruction fetched into @di, filling in the
+ * remaining fields of it (@di->insn and @di->insn_len are filled by
+ * insn_fetch_faulted()).
+ *
+ * @xlen is the effective XLEN of the guest, needed as
+ * the encodings which exist for XLEN=64 only must not be recognized for a
+ * 32-bit guest.
+ *
+ * Returns false if the instruction is not a load or store which can be
+ * emulated here.
+ */
+static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di,
+                                            unsigned int xlen)
+{
+    unsigned long insn = di->insn;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 322

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+    /* Register fields of the uncompressed forms ... */
+    unsigned int rd = RV_RD(insn);
+    unsigned int rs2 = RV_RS2(insn);
+    /*
+     * ... and of the compressed ones, where the 3-bit field selects one of
+     * x8..x15, while the stack-pointer-relative forms have a full-width one.
+     */
+    unsigned int rs2s = RVC_RS2S(insn);
+    unsigned int rs2c = RVC_RS2(insn);
+

This naming are confusing because above you described di->reg to be rd for load and rs2 for store but here ...

Quoted 25 lines
xen/arch/riscv/emulate.c +23 -0
+    di->is_write = false;
+    di->is_unsigned = false;
 
 
+    di->reg = rd;
+
+    if ( (insn & INSN_MASK_LB) == INSN_MATCH_LB )
+        di->len = 1;
+    else if ( (insn & INSN_MASK_LBU) == INSN_MATCH_LBU )
+    {
+        di->len = 1;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LH) == INSN_MATCH_LH )
+        di->len = 2;
+    else if ( (insn & INSN_MASK_LHU) == INSN_MATCH_LHU )
+    {
+        di->len = 2;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LW) == INSN_MATCH_LW )
+        di->len = 4;
+    else if ( xlen == 64 && (insn & INSN_MASK_LWU) == INSN_MATCH_LWU )
+    {
+        di->len = 4;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 351

Quoted 10 lines
xen/arch/riscv/emulate.c +6 -0
+        di->is_unsigned = true;
+    }
 
 
+    else if ( (insn & INSN_MASK_C_LW) == INSN_MATCH_C_LW )
+    {
+        di->len = 4;
 
 
+        di->reg = rs2s;

... you assigned rs2s for a load. According to the spec, it should be rd'.

I would suggest something generic to load and store. Maybe rxs with a comment to explain it concerns rs2' for store and rd' for load.

/*
* ... and of the compressed ones, where the 3-bit field selects one of
* x8..x15, while the stack-pointer-relative forms have a full-width one.
* rxs is named after that field's spec mnemonic, rd'/rs2': rd' for
* compressed loads, rs2' for compressed stores.
*/
unsigned int rxs = RVC_RS2S(insn);

Quoted 113 lines
xen/arch/riscv/emulate.c +68 -0
+    }
+    /* c.lwsp and c.ldsp are reserved with rd being x0. */
+    else if ( (insn & INSN_MASK_C_LWSP) == INSN_MATCH_C_LWSP && rd )
+        di->len = 4;
+    else if ( xlen == 64 && (insn & INSN_MASK_LD) == INSN_MATCH_LD )
+        di->len = 8;
+    else if ( xlen == 64 && (insn & INSN_MASK_C_LD) == INSN_MATCH_C_LD )
+    {
+        di->len = 8;
+        di->reg = rs2s;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_C_LDSP) == INSN_MATCH_C_LDSP &&
+              rd )
+        di->len = 8;
+    else if ( (insn & INSN_MASK_SB) == INSN_MATCH_SB )
+    {
+        di->len = 1;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( (insn & INSN_MASK_SH) == INSN_MATCH_SH )
+    {
+        di->len = 2;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( (insn & INSN_MASK_SW) == INSN_MATCH_SW )
+    {
+        di->len = 4;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( (insn & INSN_MASK_C_SW) == INSN_MATCH_C_SW )
+    {
+        di->len = 4;
+        di->is_write = true;
+        di->reg = rs2s;
+    }
+    else if ( (insn & INSN_MASK_C_SWSP) == INSN_MATCH_C_SWSP )
+    {
+        di->len = 4;
+        di->is_write = true;
+        di->reg = rs2c;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_SD) == INSN_MATCH_SD )
+    {
+        di->len = 8;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_C_SD) == INSN_MATCH_C_SD )
+    {
+        di->len = 8;
+        di->is_write = true;
+        di->reg = rs2s;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_C_SDSP) == INSN_MATCH_C_SDSP )
+    {
+        di->len = 8;
+        di->is_write = true;
+        di->reg = rs2c;
+    }
+    else
+        return false;
+
+    return true;
+}
+
 static int emulate_load(const struct guest_fault *gf)
 {
     return -EOPNOTSUPP;
xen/arch/riscv/include/asm/guest_access.h +4 -0
index 8d679319de..39c28dd2ec 100644
@@ -5,6 +5,7 @@
 #include <xen/types.h>
 
 struct domain;
+struct trap_info;
 
 unsigned long raw_copy_to_guest(void *to, const void *from, unsigned len);
 unsigned long raw_copy_from_guest(void *to, const void *from, unsigned len);
@@ -25,6 +26,9 @@ unsigned long raw_clear_guest(void *to, unsigned int len);
 unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,
                                  unsigned long len);
 
+unsigned long riscv_read_guest(unsigned long guest_addr, bool read_insn,
+                               struct trap_info *trap);
+
 #endif /* ASM__RISCV__GUEST_ACCESS_H */
 /*
  * Local variables:
xen/arch/riscv/include/asm/riscv_encoding.h +8 -0
index b2071f4758..656a5fcccb 100644
@@ -65,6 +65,14 @@
 #define SSTATUS64_UXL			MSTATUS_UXL
 #define SSTATUS64_SD			MSTATUS64_SD
 
+/*
+ * Width encoded by the MXL, SXL, UXL and VSXL fields, all of which share one
+ * encoding. 0 is reserved.
+ */
+#define XLEN_FIELD_32			_UL(1)
+#define XLEN_FIELD_64			_UL(2)
+#define XLEN_FIELD_128			_UL(3)
+
 #if __riscv_xlen == 64
 #define HSTATUS_VSXL			_UL(0x300000000)
 #define HSTATUS_VSXL_SHIFT		32

xen/arch/riscv/include/asm/riscv_encoding.h line 908

Quoted 5 lines
xen/arch/riscv/include/asm/riscv_encoding.h +2 -0
@@ -896,6 +904,8 @@
 					 (RV_X(x, 7, 2) << 6))
 #define RVC_SDSP_IMM(x)			((RV_X(x, 10, 3) << 3) | \
 					 (RV_X(x, 7, 3) << 6))
+#define RV_RD(insn)			RV_X(insn, SH_RD, 5)
+#define RV_RS2(insn)			RV_X(insn, SH_RS2, 5)

Nit: format

Signature · 1 line
Baptiste Le Duc <[email protected]>
#155 lore raw

Re: [PATCH v2 24/39] xen/riscv: add helpers for decoding a trapped load or store

Quoted 9 lines · Baptiste Le Duc
Quoted 7 lines

emulate_load() and emulate_store() will both need to obtain the instruction which caused a guest MMIO trap, decode it, and locate the register operand it names. Add what the two share, ahead of either of them being implemented: struct decoded_insn, insn_fetch_faulted(), decode_ldst_insn(), guest_xlen(), guest_gpr() and advance_pc().

The mask/match chain is adapted from Linux's KVM RISC-V implementation.

Nit: maybe you could add the Origin: trailer as mentioned in the sending-patches.adoc.

I think that I will drop that sentense as the code in v3 is changed pretty significantly so it doesn't too much sense to mention that it was derived from Linux's KVM RISC-V.

Basically even if I will put Origin: now here then it will be still pretty hard to undestand what was used or not as I mentioned above there are a lot of changes done in comparison with original.

I will take it in mind for my future patches.

[...]

Quoted 68 lines
Quoted 17 lines
xen/arch/riscv/emulate.c +17 -0
+
+/*
+ * Decode the load or store instruction fetched into @di, filling in the
+ * remaining fields of it (@di->insn and @di->insn_len are filled by
+ * insn_fetch_faulted()).
+ *
+ * @xlen is the effective XLEN of the guest, needed as
+ * the encodings which exist for XLEN=64 only must not be recognized for a
+ * 32-bit guest.
+ *
+ * Returns false if the instruction is not a load or store which can be
+ * emulated here.
+ */
+static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di,
+                                            unsigned int xlen)
+{
+    unsigned long insn = di->insn;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 322

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+    /* Register fields of the uncompressed forms ... */
+    unsigned int rd = RV_RD(insn);
+    unsigned int rs2 = RV_RS2(insn);
+    /*
+     * ... and of the compressed ones, where the 3-bit field selects one of
+     * x8..x15, while the stack-pointer-relative forms have a full-width one.
+     */
+    unsigned int rs2s = RVC_RS2S(insn);
+    unsigned int rs2c = RVC_RS2(insn);
+

This naming are confusing because above you described di->reg to be rd for load and rs2 for store but here ...

Quoted 25 lines
xen/arch/riscv/emulate.c +23 -0
+    di->is_write = false;
+    di->is_unsigned = false;
 
 
+    di->reg = rd;
+
+    if ( (insn & INSN_MASK_LB) == INSN_MATCH_LB )
+        di->len = 1;
+    else if ( (insn & INSN_MASK_LBU) == INSN_MATCH_LBU )
+    {
+        di->len = 1;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LH) == INSN_MATCH_LH )
+        di->len = 2;
+    else if ( (insn & INSN_MASK_LHU) == INSN_MATCH_LHU )
+    {
+        di->len = 2;
+        di->is_unsigned = true;
+    }
+    else if ( (insn & INSN_MASK_LW) == INSN_MATCH_LW )
+        di->len = 4;
+    else if ( xlen == 64 && (insn & INSN_MASK_LWU) == INSN_MATCH_LWU )
+    {
+        di->len = 4;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 351

Quoted 10 lines
xen/arch/riscv/emulate.c +6 -0
+        di->is_unsigned = true;
+    }
 
 
+    else if ( (insn & INSN_MASK_C_LW) == INSN_MATCH_C_LW )
+    {
+        di->len = 4;
 
 
+        di->reg = rs2s;

... you assigned rs2s for a load. According to the spec, it should be rd'.

I would suggest something generic to load and store. Maybe rxs with a comment to explain it concerns rs2' for store and rd' for load.

Quoted 7 lines

/*
* ... and of the compressed ones, where the 3-bit field selects one of
* x8..x15, while the stack-pointer-relative forms have a full-width one.
* rxs is named after that field's spec mnemonic, rd'/rs2': rd' for
* compressed loads, rs2' for compressed stores.
*/
unsigned int rxs = RVC_RS2S(insn);

Good point. It isn't partly applied to what I suggested in one of the reply to Jan B. but I will try to re-use part of your suggestion there.

It will look like:

static bool decode_ldst_insn(struct decoded_insn *di, unsigned int xlen)

{
    uint32_t insn = di->insn;
    unsigned int funct3, width_log2;

    if ( INSN_IS_16BIT(insn) )
    {
        /*
         * C.LW, C.LD, C.SW and C.SD (bits[1:0] == 00), and their 
sp-relative
         * C.*SP forms (bits[1:0] == 10), have bits[15:13] of the form x1y:
         * x is set for a store, and y selects a width of 4 or 8 bytes.
         */
        funct3 = RV_X(insn, 13, 3);

        if ( (insn & 1) || !(funct3 & 2) )
            return false;

        di->is_write = funct3 & 4;
        width_log2 = 2 + (funct3 & 1);

        /*
         * The register operand is rd' of a load or rs2' of a store for the
         * register-relative forms, both being bits[4:2], and rs2 of a 
store
         * or rd of a load for the sp-relative ones.
         */
        if ( !(insn & 2) )
            /* Quadrant 0: bits[4:2] encode rd' (load) or rs2' (store) */
            di->reg = RVC_RS2S(insn);
        else if ( di->is_write )
            /* Quadrant 2 (CSS): bits[6:2] encode rs2 for C.SWSP / 
C.SDSP */
            di->reg = RVC_RS2(insn);
        else
        {
            /* Quadrant 2 (CI): bits[11:7] encode rd for C.LWSP / C.LDSP */
            di->reg = RV_RD(insn);

            /* C.LWSP and C.LDSP are reserved with rd being x0. */
            if ( !di->reg )
                return false;
        }
    }
    else
    {
        /*
         * funct3[1:0] is log2 of the width in bytes, and funct3[2] selects
         * zero-extension for a load, while being reserved for a store.
         */
        funct3 = RV_X(insn, 12, 3);
        width_log2 = funct3 & 3;

        switch ( insn & INSN_OPCODE_MASK )
        {
        case INSN_OPCODE_LOAD:
            di->is_unsigned = funct3 & 4;
            di->reg = RV_RD(insn);
            break;

        case INSN_OPCODE_STORE:
            if ( funct3 & 4 )
                return false;
            di->is_write = true;
            di->reg = RV_RS2(insn);
            break;

        default:
            return false;
        }
    }

    di->len = 1U << width_log2;

    /*
     * No access is wider than XLEN, and one as wide as XLEN exists only in
     * its sign-extending form: this rules out the encodings which 
exist for
     * XLEN=64 only on a 32-bit guest, including C.FLW for C.LD (and 
alike).
     */
    if ( (di->len * BITS_PER_BYTE > xlen) ||
         (di->is_unsigned && di->len * BITS_PER_BYTE == xlen) )
        return false;

    return true;
}
Quoted 69 lines
Quoted 69 lines
xen/arch/riscv/emulate.c +68 -0
+    }
+    /* c.lwsp and c.ldsp are reserved with rd being x0. */
+    else if ( (insn & INSN_MASK_C_LWSP) == INSN_MATCH_C_LWSP && rd )
+        di->len = 4;
+    else if ( xlen == 64 && (insn & INSN_MASK_LD) == INSN_MATCH_LD )
+        di->len = 8;
+    else if ( xlen == 64 && (insn & INSN_MASK_C_LD) == INSN_MATCH_C_LD )
+    {
+        di->len = 8;
+        di->reg = rs2s;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_C_LDSP) == INSN_MATCH_C_LDSP &&
+              rd )
+        di->len = 8;
+    else if ( (insn & INSN_MASK_SB) == INSN_MATCH_SB )
+    {
+        di->len = 1;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( (insn & INSN_MASK_SH) == INSN_MATCH_SH )
+    {
+        di->len = 2;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( (insn & INSN_MASK_SW) == INSN_MATCH_SW )
+    {
+        di->len = 4;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( (insn & INSN_MASK_C_SW) == INSN_MATCH_C_SW )
+    {
+        di->len = 4;
+        di->is_write = true;
+        di->reg = rs2s;
+    }
+    else if ( (insn & INSN_MASK_C_SWSP) == INSN_MATCH_C_SWSP )
+    {
+        di->len = 4;
+        di->is_write = true;
+        di->reg = rs2c;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_SD) == INSN_MATCH_SD )
+    {
+        di->len = 8;
+        di->is_write = true;
+        di->reg = rs2;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_C_SD) == INSN_MATCH_C_SD )
+    {
+        di->len = 8;
+        di->is_write = true;
+        di->reg = rs2s;
+    }
+    else if ( xlen == 64 && (insn & INSN_MASK_C_SDSP) == INSN_MATCH_C_SDSP )
+    {
+        di->len = 8;
+        di->is_write = true;
+        di->reg = rs2c;
+    }
+    else
+        return false;
+
+    return true;
+}
+

[...]

Quoted 10 lines
Quoted 10 lines
xen/arch/riscv/include/asm/riscv_encoding.h +8 -0
+/*
+ * Width encoded by the MXL, SXL, UXL and VSXL fields, all of which share one
+ * encoding. 0 is reserved.
+ */
+#define XLEN_FIELD_32			_UL(1)
+#define XLEN_FIELD_64			_UL(2)
+#define XLEN_FIELD_128			_UL(3)
+
  #if __riscv_xlen == 64
  #define HSTATUS_VSXL			_UL(0x300000000)
Quoted 9 lines

xen/arch/riscv/include/asm/riscv_encoding.h line 908

Quoted 7 lines
  #define HSTATUS_VSXL_SHIFT		32
xen/arch/riscv/include/asm/riscv_encoding.h +2 -0
@@ -896,6 +904,8 @@
  					 (RV_X(x, 7, 2) << 6))
  #define RVC_SDSP_IMM(x)			((RV_X(x, 10, 3) << 3) | \
  					 (RV_X(x, 7, 3) << 6))
+#define RV_RD(insn)			RV_X(insn, SH_RD, 5)
+#define RV_RS2(insn)			RV_X(insn, SH_RS2, 5)

Nit: format

I think it looks like that because tabs are used there instead of spaces and tabs are there because it was orignally taken from the project which uses tabs.

Thanks!

~ Oleksii

#156 lore raw

PATCH v2 25/39 xen/riscv: add guest load emulation for trapped MMIO accesses

In reply to Oleksii Kurochko

Implement emulate_load() on top of the decoding interface introduced by the previous patch: fetch the trapped instruction, decode it, dispatch the access to a registered MMIO handler via do_mmio(), write the result back into the destination register and step over the instruction.

Xen dispatches MMIO synchronously to an in-hypervisor handler, so unlike KVM RISC-V there is no userspace exit/return step and no equivalent of the kvm_io_bus_read() / KVM_EXIT_MMIO / kvm_riscv_vcpu_mmio_return() split; the result is consumed in place.

Sign extension is done here rather than in the handlers: a signed load is normalized by a shift pair, so a handler need only report the value it read.

At the moment vINTC is the only backend registered with the MMIO dispatch, so in practice this only covers vINTC traps. An access which no handler claims currently crashes the domain; injecting an access fault into the guest instead is left for later.

---
Changes in v2:
- Move the emulation code to the new arch/riscv/emulate.c, leaving traps.c with trap dispatch only.
- Split the patch up: struct decoded_insn and the decoding helpers are introduced by "xen/riscv: introduce the interface for trapped instruction decoding" and filled in by "xen/riscv: implement trapped instruction decoding", so only emulate_load() itself is left here.
- do_mmio() is no longer defined alongside emulate_load(); it now lives in mmio.c, next to the dispatch it drives.
- Don't write the result of a load into x0. SET_RD() wrote rd unconditionally, so a load into x0 clobbered regs->zero and broke the invariant that it reads as zero when x0 is a source operand elsewhere.
- Recognize the XLEN=64-only encodings by the guest's effective XLEN (guest_xlen()) rather than by Xen's own (CONFIG_RISCV_32). Besides those encodings simply being reserved on RV32, the compressed ones are ambiguous
there: C.LD and C.FLW share the encoding 0x6000 (mask 0xe003), and likewise C.SD/C.FSW, C.LDSP/C.FLWSP and C.SDSP/C.FSWSP.
- Take the faulting address from struct guest_fault, filled in by resolve_faulting_gpa(), rather than from get_faulting_gpa().
- Drop the description of a fault taken while re-reading the trapped
instruction: that code is now in the patch implementing fetch_trapped_insn(), where a G-stage fault is reported to the guest as CAUSE_FETCH_ACCESS instead of hitting a BUG_ON().
- Update the commit message accordingly.
---

---
 xen/arch/riscv/emulate.c | 53 +++++++++++++++++++++++++++++++---------
 1 file changed, 42 insertions(+), 11 deletions(-)
xen/arch/riscv/emulate.c +42 -11
index 81a50643a5ec..e52f2851800c 100644
@@ -5,7 +5,6 @@
  */
 
 #include <xen/bug.h>
-#include <xen/compiler.h>
 #include <xen/errno.h>
 #include <xen/sched.h>
 #include <xen/types.h>
@@ -15,6 +14,7 @@
 #include <asm/current.h>
 #include <asm/emulate.h>
 #include <asm/guest_access.h>
+#include <asm/mmio.h>
 #include <asm/processor.h>
 #include <asm/riscv_encoding.h>
 #include <asm/traps.h>
@@ -65,8 +65,7 @@ static bool is_load_guest_page_fault(unsigned long scause)
     return scause == CAUSE_LOAD_GUEST_PAGE_FAULT;
 }
 
-static __maybe_unused void advance_pc(struct cpu_user_regs *regs,
-                                      unsigned int step)
+static void advance_pc(struct cpu_user_regs *regs, unsigned int step)
 {
     regs->sepc += step;
 }
@@ -88,7 +87,7 @@ static __maybe_unused void advance_pc(struct cpu_user_regs *regs,
  * IS_ENABLED() can't be used here as HSTATUS_VSXL is defined for
  * __riscv_xlen == 64 only, the field not existing on RV32 in the first place.
  */
-static __maybe_unused unsigned int guest_xlen(const struct cpu_user_regs *regs)
+static unsigned int guest_xlen(const struct cpu_user_regs *regs)
 {
 #ifdef CONFIG_RISCV_32
     return 32;
@@ -179,8 +178,7 @@ static void resolve_faulting_gpa(struct guest_fault *gf)
  * Relies on x0..x31 being laid out at the start of struct cpu_user_regs in
  * architectural register-number order; see the comment there.
  */
-static __maybe_unused unsigned long *guest_gpr(struct cpu_user_regs *regs,
-                                               unsigned int reg)
+static unsigned long *guest_gpr(struct cpu_user_regs *regs, unsigned int reg)
 {
     ASSERT(reg < 32);
 
@@ -197,8 +195,8 @@ static __maybe_unused unsigned long *guest_gpr(struct cpu_user_regs *regs,
  * caller to do. Where it returns false, @di has been filled in and emulation
  * is to continue.
  */
-static bool __maybe_unused insn_fetch_faulted(const struct guest_fault *gf,
-                                              struct decoded_insn *di)
+static bool insn_fetch_faulted(const struct guest_fault *gf,
+                               struct decoded_insn *di)
 {
     unsigned long htinst = gf->htinst;
 
@@ -306,8 +304,7 @@ static bool __maybe_unused insn_fetch_faulted(const struct guest_fault *gf,
  * Returns false if the instruction is not a load or store which can be
  * emulated here.
  */
-static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di,
-                                            unsigned int xlen)
+static bool decode_ldst_insn(struct decoded_insn *di, unsigned int xlen)
 {
     unsigned long insn = di->insn;
     /* Register fields of the uncompressed forms ... */
@@ -419,7 +416,41 @@ static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di,
 
 static int emulate_load(const struct guest_fault *gf)
 {
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = gf->regs;
+    mmio_info_t info = { .is_write = false };
+    struct decoded_insn di;
+    unsigned int shift = 0;
+    int rc;
+
+    /* A fault taken re-reading the instruction is redirected to the guest. */
+    if ( insn_fetch_faulted(gf, &di) )
+        return 0;
+
+    if ( !decode_ldst_insn(&di, guest_xlen(regs)) || di.is_write )
+        return -EOPNOTSUPP;
+
+    if ( !di.is_unsigned )
+        shift = BITS_PER_BYTE * (sizeof(unsigned long) - di.len);
+
+#ifdef EMULATE_LOAD_DEBUG
+    gdprintk(XENLOG_DEBUG, "pc=%#lx, addr=%#"PRIpaddr", len=%u, shift=%u\n",
+             regs->sepc, gf->gpa, di.len, shift);
+#endif
+
+    rc = do_mmio(&info, gf->gpa, di.len);
+    if ( rc )
+        return rc;
+
+    /*
+     * A load into x0 discards its result: writing regs->zero would break the
+     * invariant that it reads as zero when x0 is a source operand elsewhere.
+     */
+    if ( di.reg )
+        *guest_gpr(regs, di.reg) = (long)(info.data << shift) >> shift;
+
+    advance_pc(regs, di.insn_len);
+
+    return 0;
 }
 
 static int emulate_store(struct guest_fault *gf)
Signature · 1 line
2.55.0
#157 lore raw

Re: [PATCH v2 25/39] xen/riscv: add guest load emulation for trapped MMIO accesses

Quoted 10 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c +5 -1
@@ -419,7 +416,41 @@ static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di,
 
 static int emulate_load(const struct guest_fault *gf)
 {
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = gf->regs;
+    mmio_info_t info = { .is_write = false };
+    struct decoded_insn di;
+    unsigned int shift = 0;
+    int rc;

xen/arch/riscv/emulate.c static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di, · line 433

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+
+    /* A fault taken re-reading the instruction is redirected to the guest. */
+    if ( insn_fetch_faulted(gf, &di) )
+        return 0;
+
+    if ( !decode_ldst_insn(&di, guest_xlen(regs)) || di.is_write )
+        return -EOPNOTSUPP;
+
+    if ( !di.is_unsigned )
+        shift = BITS_PER_BYTE * (sizeof(unsigned long) - di.len);

This is one of the cases where sizeof(<type>) is not only unclear to read, but actively risky: Which variable(s) of that type does this refer to? What if those variable(s)' type(s) change? Aha, ...

Quoted 5 lines
xen/arch/riscv/emulate.c +5 -0
+#ifdef EMULATE_LOAD_DEBUG
+    gdprintk(XENLOG_DEBUG, "pc=%#lx, addr=%#"PRIpaddr", len=%u, shift=%u\n",
+             regs->sepc, gf->gpa, di.len, shift);
+#endif
+

xen/arch/riscv/emulate.c static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di, · line 449

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+    rc = do_mmio(&info, gf->gpa, di.len);
+    if ( rc )
+        return rc;
+
+    /*
+     * A load into x0 discards its result: writing regs->zero would break the
+     * invariant that it reads as zero when x0 is a source operand elsewhere.
+     */
+    if ( di.reg )
+        *guest_gpr(regs, di.reg) = (long)(info.data << shift) >> shift;

... you apparently mean sizeof(info.data) there.

The comment is (nit) also too long for my taste. Everything from the colon onwards is imo redundant.

Jan

#158 lore raw

Re: [PATCH v2 25/39] xen/riscv: add guest load emulation for trapped MMIO accesses

Quoted 35 lines · Jan Beulich
Quoted 10 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c +5 -1
@@ -419,7 +416,41 @@ static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di,
 
  static int emulate_load(const struct guest_fault *gf)
  {
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = gf->regs;
+    mmio_info_t info = { .is_write = false };
+    struct decoded_insn di;
+    unsigned int shift = 0;
+    int rc;

xen/arch/riscv/emulate.c static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di, · line 433

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+
+    /* A fault taken re-reading the instruction is redirected to the guest. */
+    if ( insn_fetch_faulted(gf, &di) )
+        return 0;
+
+    if ( !decode_ldst_insn(&di, guest_xlen(regs)) || di.is_write )
+        return -EOPNOTSUPP;
+
+    if ( !di.is_unsigned )
+        shift = BITS_PER_BYTE * (sizeof(unsigned long) - di.len);

This is one of the cases where sizeof(<type>) is not only unclear to read, but actively risky: Which variable(s) of that type does this refer to? What if those variable(s)' type(s) change? Aha, ...

Quoted 9 lines
xen/arch/riscv/emulate.c +9 -0
+#ifdef EMULATE_LOAD_DEBUG
+    gdprintk(XENLOG_DEBUG, "pc=%#lx, addr=%#"PRIpaddr", len=%u, shift=%u\n",
+             regs->sepc, gf->gpa, di.len, shift);
+#endif
+
+    rc = do_mmio(&info, gf->gpa, di.len);
+    if ( rc )
+        return rc;
+
Quoted 8 lines

xen/arch/riscv/emulate.c static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di, · line 449

Quoted 6 lines
xen/arch/riscv/emulate.c +6 -0
+    /*
+     * A load into x0 discards its result: writing regs->zero would break the
+     * invariant that it reads as zero when x0 is a source operand elsewhere.
+     */
+    if ( di.reg )
+        *guest_gpr(regs, di.reg) = (long)(info.data << shift) >> shift;

... you apparently mean sizeof(info.data) there.

Good point. I will try to follow such approach in future and use the variable name instead of a type.

Quoted 3 lines

The comment is (nit) also too long for my taste. Everything from the colon onwards is imo redundant.

Probably you are right. It is a little bit obvious just from the defintion of x0 that it should be always zero. I will drop that part of the comment after the colon.

THanks.

~ Oleksii

#159 lore raw

Re: [PATCH v2 25/39] xen/riscv: add guest load emulation for trapped MMIO accesses

In reply to Oleksii Kurochko
Quoted 61 lines

Implement emulate_load() on top of the decoding interface introduced by the previous patch: fetch the trapped instruction, decode it, dispatch the access to a registered MMIO handler via do_mmio(), write the result back into the destination register and step over the instruction.

Xen dispatches MMIO synchronously to an in-hypervisor handler, so unlike KVM RISC-V there is no userspace exit/return step and no equivalent of the kvm_io_bus_read() / KVM_EXIT_MMIO / kvm_riscv_vcpu_mmio_return() split; the result is consumed in place.

Sign extension is done here rather than in the handlers: a signed load is normalized by a shift pair, so a handler need only report the value it read.

At the moment vINTC is the only backend registered with the MMIO dispatch, so in practice this only covers vINTC traps. An access which no handler claims currently crashes the domain; injecting an access fault into the guest instead is left for later.

xen/arch/riscv/emulate.c +3 -4
index 81a50643a5..e52f285180 100644
@@ -5,7 +5,6 @@
  */
 
 #include <xen/bug.h>
-#include <xen/compiler.h>
 #include <xen/errno.h>
 #include <xen/sched.h>
 #include <xen/types.h>
@@ -15,6 +14,7 @@
 #include <asm/current.h>
 #include <asm/emulate.h>
 #include <asm/guest_access.h>
+#include <asm/mmio.h>
 #include <asm/processor.h>
 #include <asm/riscv_encoding.h>
 #include <asm/traps.h>
@@ -65,8 +65,7 @@ static bool is_load_guest_page_fault(unsigned long scause)
     return scause == CAUSE_LOAD_GUEST_PAGE_FAULT;
 }
 
-static __maybe_unused void advance_pc(struct cpu_user_regs *regs,
-                                      unsigned int step)
+static void advance_pc(struct cpu_user_regs *regs, unsigned int step)
 {
     regs->sepc += step;
 }
@@ -88,7 +87,7 @@ static __maybe_unused void advance_pc(struct cpu_user_regs *regs,
  * IS_ENABLED() can't be used here as HSTATUS_VSXL is defined for
  * __riscv_xlen == 64 only, the field not existing on RV32 in the first place.
  */
-static __maybe_unused unsigned int guest_xlen(const struct cpu_user_regs *regs)
+static unsigned int guest_xlen(const struct cpu_user_regs *regs)
 {
 #ifdef CONFIG_RISCV_32
     return 32;

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 183

Quoted 5 lines
xen/arch/riscv/emulate.c +0 -2
@@ -179,8 +178,7 @@ static void resolve_faulting_gpa(struct guest_fault *gf)
  * Relies on x0..x31 being laid out at the start of struct cpu_user_regs in
  * architectural register-number order; see the comment there.
  */
-static __maybe_unused unsigned long *guest_gpr(struct cpu_user_regs *regs,
-                                               unsigned int reg)

Could we unified this function with regs_get_gpr()?

Signature · 1 line
Baptiste Le Duc <[email protected]>
#160 lore raw

Re: [PATCH v2 25/39] xen/riscv: add guest load emulation for trapped MMIO accesses

Quoted 8 lines

xen/arch/riscv/emulate.c static void resolve_faulting_gpa(struct guest_fault *gf) · line 183

Quoted 6 lines
xen/arch/riscv/emulate.c +0 -2
@@ -179,8 +178,7 @@ static void resolve_faulting_gpa(struct guest_fault *gf)
   * Relies on x0..x31 being laid out at the start of struct cpu_user_regs in
   * architectural register-number order; see the comment there.
   */
-static __maybe_unused unsigned long *guest_gpr(struct cpu_user_regs *regs,
-                                               unsigned int reg)

Could we unified this function with regs_get_gpr()?

I think it could. I will try to do in the unified way.

Thanks!

~ Oleksii

#161 lore raw

PATCH v2 26/39 xen/riscv: add guest store emulation for trapped MMIO accesses

In reply to Oleksii Kurochko

Extend the guest page fault handler with store emulation to support MMIO write accesses.

The instruction decode mirrors emulate_load() and, like it, is adapted from Linux's KVM RISC-V implementation. As with the load path, the completion is synchronous through try_handle_mmio() rather than KVM's userspace exit/return split, since Xen's MMIO handlers run in the hypervisor. Faults taken while re-reading the trapped instruction are handled by decode_ldst_insn(), shared with the load path.

When a guest store instruction faults, the trapped instruction is decoded using HTINST or, if unavailable, fetched via unprivileged access. At the moment only virtual interrupt controller (vINTC) traps are expected to occur, since it is currently the only backend registered with the MMIO handler dispatch, so in practice the store is emulated via the vINTC backend.

Together with load emulation, this completes the basic MMIO handling path needed for virtual interrupt controller support on RISC-V.

---
Changes in v2:
- Move the emulation code to the new arch/riscv/emulate.c, leaving traps.c with trap dispatch only.
- Split the patch up: the instruction fetch and the mask/match chain now live in "xen/riscv: add helpers for decoding a trapped load or store" (struct decoded_insn, insn_fetch_faulted(), decode_ldst_insn(), guest_gpr(), advance_pc()), so only emulate_store() itself is left here.
- Since the decoder is now shared with the load path, reject an encoding which is not a store (!di.is_write) explicitly; in v2 the mask/match chain was store-only and could not match a load.
- Recognize the XLEN=64-only encodings by the guest's effective XLEN (guest_xlen()) rather than by Xen's own (CONFIG_RISCV_32). Besides those encodings simply being reserved on RV32, the compressed ones are ambiguous
there: C.SD and C.FSW share an encoding, and likewise C.SDSP and C.FSWSP.
- Read the source register through guest_gpr() instead of the GET_RS2()/GET_RS2S()/GET_RS2C() macros; which of the three register fields an encoding names is now decided by decode_ldst_insn().
- Take the faulting address from struct guest_fault, filled in by resolve_faulting_gpa(), rather than from the fault_addr parameter.
- Drop the description of a fault taken while re-reading the trapped
instruction: that code is now in the patch adding the decoding helpers, where a G-stage fault is reported to the guest as CAUSE_FETCH_ACCESS.
- Update the commit message accordingly.
---

---
 xen/arch/riscv/emulate.c | 23 +++++++++++++++++++++--
 1 file changed, 21 insertions(+), 2 deletions(-)
xen/arch/riscv/emulate.c +21 -2
index e52f2851800c..1535b843525e 100644
@@ -453,9 +453,28 @@ static int emulate_load(const struct guest_fault *gf)
     return 0;
 }
 
-static int emulate_store(struct guest_fault *gf)
+static int emulate_store(const struct guest_fault *gf)
 {
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = gf->regs;
+    mmio_info_t info = { .is_write = true };
+    struct decoded_insn di;
+    int rc;
+
+    if ( insn_fetch_faulted(gf, &di) )
+        return 0;
+
+    if ( !decode_ldst_insn(&di, guest_xlen(regs)) || !di.is_write )
+        return -EOPNOTSUPP;
+
+    info.data = *guest_gpr(regs, di.reg);
+
+    rc = do_mmio(&info, gf->gpa, di.len);
+    if ( rc )
+        return rc;
+
+    advance_pc(regs, di.insn_len);
+
+    return 0;
 }
 
 static void inject_access_fault(const struct guest_fault *gf)
Signature · 1 line
2.55.0
#162 lore raw

Re: [PATCH v2 26/39] xen/riscv: add guest store emulation for trapped MMIO accesses

Quoted 12 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c +3 -2
@@ -453,9 +453,28 @@ static int emulate_load(const struct guest_fault *gf)
     return 0;
 }
 
-static int emulate_store(struct guest_fault *gf)
+static int emulate_store(const struct guest_fault *gf)
 {
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = gf->regs;
+    mmio_info_t info = { .is_write = true };

xen/arch/riscv/emulate.c static int emulate_load(const struct guest_fault *gf) · line 469

Quoted 10 lines
xen/arch/riscv/emulate.c +10 -0
+    struct decoded_insn di;
+    int rc;
+
+    if ( insn_fetch_faulted(gf, &di) )
+        return 0;
+
+    if ( !decode_ldst_insn(&di, guest_xlen(regs)) || !di.is_write )
+        return -EOPNOTSUPP;
+
+    info.data = *guest_gpr(regs, di.reg);

This came to mind only here, but applies to the earlier patch as well:
There's no checking of di.len, not even by an assertion. The above is fragile as to extensions like Zilsd. Zilsd itself may still be okay as the overrun of the register field will hit the correct one, but the general concern remains (plus of course that moving across fields is UB).

Jan

#163 lore raw

Re: [PATCH v2 26/39] xen/riscv: add guest store emulation for trapped MMIO accesses

Quoted 22 lines · Jan Beulich
Quoted 21 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c +12 -2
@@ -453,9 +453,28 @@ static int emulate_load(const struct guest_fault *gf)
      return 0;
  }
 
-static int emulate_store(struct guest_fault *gf)
+static int emulate_store(const struct guest_fault *gf)
  {
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = gf->regs;
+    mmio_info_t info = { .is_write = true };
+    struct decoded_insn di;
+    int rc;
+
+    if ( insn_fetch_faulted(gf, &di) )
+        return 0;
+
+    if ( !decode_ldst_insn(&di, guest_xlen(regs)) || !di.is_write )
+        return -EOPNOTSUPP;
+
Quoted 8 lines

xen/arch/riscv/emulate.c static int emulate_load(const struct guest_fault *gf) · line 469

Quoted 1 line
xen/arch/riscv/emulate.c +1 -0
+    info.data = *guest_gpr(regs, di.reg);

This came to mind only here, but applies to the earlier patch as well:
There's no checking of di.len, not even by an assertion. The above is fragile as to extensions like Zilsd. Zilsd itself may still be okay as the overrun of the register field will hit the correct one, but the general concern remains (plus of course that moving across fields is UB).

Nothing can produce di.len > sizeof(register_t) today, as the 8-byte cases are all gated on xlen == 64, so I'd add the assertion at the point where the lengths are assigned, covering both emulate_load() (where the shift calculation would underflow) and emulate_store() at once:
ASSERT(di->len <= sizeof(register_t));
right before decode_ldst_insn()'s final "return true".

Probably it makes sense to have just "if (di->len >= sizeof(register_t) )" with the comment and then return false in deocde_lst_insn():

+ /*

+     * An access wider than a register could not be carried through: the
+     * register operand guest_gpr() hands out is register_t-wide, as is the
+     * value an emulated access moves. None of the encodings above yields
+     * such an access, the 8-byte ones all being gated on XLEN=64, but a
+     * future extension might (Zilsd, say, whose 8-byte accesses exist for a
+     * 32-bit guest).
+     */

+ if ( di->len > sizeof(register_t) )
+ return false;

(i think that the same could be also true for D and Zdinx but I will mention only Zilsd as an example)

Also, I think it make sense to add the comment to guest_gpr() than di->len is checked in decode_ldst_insn(). Alternative will be to update the proto of guest_gpr() and pass di and then have extra ASSERT() in guest_gpr() for the case if someone will try to use guest_gpr() without using insn_fetch_faulted() & decode_ldst_insn() before guest_gpr(). I will apply this alternative way, it looks to me better for now and then will add the following ASSERT:

    /*
     * decode_ldst_insn() is what fills @di in, and it rejects an access
     * wider than a register.
     */
    ASSERT(di->len <= sizeof(register_t));

Thanks.

~ Oleksii

#164 lore raw

Re: [PATCH v2 26/39] xen/riscv: add guest store emulation for trapped MMIO accesses

Quoted 54 lines · Oleksii Kurochko
Quoted 22 lines · Jan Beulich
Quoted 21 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c +12 -2
@@ -453,9 +453,28 @@ static int emulate_load(const struct guest_fault *gf)
      return 0;
  }
 
-static int emulate_store(struct guest_fault *gf)
+static int emulate_store(const struct guest_fault *gf)
  {
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = gf->regs;
+    mmio_info_t info = { .is_write = true };
+    struct decoded_insn di;
+    int rc;
+
+    if ( insn_fetch_faulted(gf, &di) )
+        return 0;
+
+    if ( !decode_ldst_insn(&di, guest_xlen(regs)) || !di.is_write )
+        return -EOPNOTSUPP;
+
Quoted 8 lines

xen/arch/riscv/emulate.c static int emulate_load(const struct guest_fault *gf) · line 469

Quoted 1 line
xen/arch/riscv/emulate.c +1 -0
+    info.data = *guest_gpr(regs, di.reg);

This came to mind only here, but applies to the earlier patch as well:
There's no checking of di.len, not even by an assertion. The above is fragile as to extensions like Zilsd. Zilsd itself may still be okay as the overrun of the register field will hit the correct one, but the general concern remains (plus of course that moving across fields is UB).

Nothing can produce di.len > sizeof(register_t) today, as the 8-byte cases are all gated on xlen == 64, so I'd add the assertion at the point where the lengths are assigned, covering both emulate_load() (where the shift calculation would underflow) and emulate_store() at once:

   ASSERT(di->len <= sizeof(register_t));

right before decode_ldst_insn()'s final "return true".

Probably it makes sense to have just "if (di->len >= sizeof(register_t) )" with the comment and then return false in deocde_lst_insn():

(quoted diff) +6 -0
+    /*
+     * An access wider than a register could not be carried through: the
+     * register operand guest_gpr() hands out is register_t-wide, as is the
+     * value an emulated access moves. None of the encodings above yields
+     * such an access, the 8-byte ones all being gated on XLEN=64, but a
+     * future extension might (Zilsd, say, whose 8-byte accesses exist 

for a

(quoted diff) +4 -0
+     * 32-bit guest).
+     */
+    if ( di->len > sizeof(register_t) )
+        return false;
Quoted 2 lines

(i think that the same could be also true for D and Zdinx but I will mention only Zilsd as an example)

Since you don't support floating point extensions so far, that's probably best. I don't quite understand the mentioning of Zdinx, though: That extension (by itself) doesn't add any memory access insns.

Quoted 8 lines

Also, I think it make sense to add the comment to guest_gpr() than di->len is checked in decode_ldst_insn(). Alternative will be to update the proto of guest_gpr() and pass di and then have extra ASSERT() in guest_gpr() for the case if someone will try to use guest_gpr() without using insn_fetch_faulted() & decode_ldst_insn() before guest_gpr(). I will apply this alternative way, it looks to me better for now and then will add the following ASSERT:

Quoted 5 lines
     /*
      * decode_ldst_insn() is what fills @di in, and it rejects an access
      * wider than a register.
      */
     ASSERT(di->len <= sizeof(register_t));

Here and above using register_t won't help with Zilsd. The type is tied to Xen's xlen, but you mean to check against the guest's here.

Jan

#165 lore raw

Re: [PATCH v2 26/39] xen/riscv: add guest store emulation for trapped MMIO accesses

Quoted 70 lines · Jan Beulich
Quoted 54 lines · Oleksii Kurochko
Quoted 22 lines · Jan Beulich
Quoted 21 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c +12 -2
@@ -453,9 +453,28 @@ static int emulate_load(const struct guest_fault *gf)
       return 0;
   }
 
-static int emulate_store(struct guest_fault *gf)
+static int emulate_store(const struct guest_fault *gf)
   {
-    return -EOPNOTSUPP;
+    struct cpu_user_regs *regs = gf->regs;
+    mmio_info_t info = { .is_write = true };
+    struct decoded_insn di;
+    int rc;
+
+    if ( insn_fetch_faulted(gf, &di) )
+        return 0;
+
+    if ( !decode_ldst_insn(&di, guest_xlen(regs)) || !di.is_write )
+        return -EOPNOTSUPP;
+
Quoted 8 lines

xen/arch/riscv/emulate.c static int emulate_load(const struct guest_fault *gf) · line 469

Quoted 1 line
xen/arch/riscv/emulate.c +1 -0
+    info.data = *guest_gpr(regs, di.reg);

This came to mind only here, but applies to the earlier patch as well:
There's no checking of di.len, not even by an assertion. The above is fragile as to extensions like Zilsd. Zilsd itself may still be okay as the overrun of the register field will hit the correct one, but the general concern remains (plus of course that moving across fields is UB).

Nothing can produce di.len > sizeof(register_t) today, as the 8-byte cases are all gated on xlen == 64, so I'd add the assertion at the point where the lengths are assigned, covering both emulate_load() (where the shift calculation would underflow) and emulate_store() at once:

    ASSERT(di->len <= sizeof(register_t));

right before decode_ldst_insn()'s final "return true".

Probably it makes sense to have just "if (di->len >= sizeof(register_t) )" with the comment and then return false in deocde_lst_insn():

(quoted diff) +6 -0
+    /*
+     * An access wider than a register could not be carried through: the
+     * register operand guest_gpr() hands out is register_t-wide, as is the
+     * value an emulated access moves. None of the encodings above yields
+     * such an access, the 8-byte ones all being gated on XLEN=64, but a
+     * future extension might (Zilsd, say, whose 8-byte accesses exist

for a

(quoted diff) +4 -0
+     * 32-bit guest).
+     */
+    if ( di->len > sizeof(register_t) )
+        return false;
Quoted 2 lines

(i think that the same could be also true for D and Zdinx but I will mention only Zilsd as an example)

Since you don't support floating point extensions so far, that's probably best. I don't quite understand the mentioning of Zdinx, though: That extension (by itself) doesn't add any memory access insns.

Quoted 8 lines

Also, I think it make sense to add the comment to guest_gpr() than di->len is checked in decode_ldst_insn(). Alternative will be to update the proto of guest_gpr() and pass di and then have extra ASSERT() in guest_gpr() for the case if someone will try to use guest_gpr() without using insn_fetch_faulted() & decode_ldst_insn() before guest_gpr(). I will apply this alternative way, it looks to me better for now and then will add the following ASSERT:

Quoted 8 lines
Quoted 5 lines
      /*
       * decode_ldst_insn() is what fills @di in, and it rejects an access
       * wider than a register.
       */
      ASSERT(di->len <= sizeof(register_t));

Here and above using register_t won't help with Zilsd. The type is tied to Xen's xlen, but you mean to check against the guest's here.

Oh, you are right, it should be guest's xlen.

Thanks.

~ Oleksii

#166 lore raw

Re: [PATCH v2 26/39] xen/riscv: add guest store emulation for trapped MMIO accesses

In reply to Oleksii Kurochko
Quoted 10 lines

Extend the guest page fault handler with store emulation to support MMIO write accesses.

The instruction decode mirrors emulate_load() and, like it, is adapted from Linux's KVM RISC-V implementation. As with the load path, the completion is synchronous through try_handle_mmio() rather than KVM's userspace exit/return split, since Xen's MMIO handlers run in the hypervisor. Faults taken while re-reading the trapped instruction are handled by decode_ldst_insn(), shared with the load path.

Quoted 2 lines

When a guest store instruction faults, the trapped instruction is decoded using HTINST or, if unavailable, fetched via unprivileged access. At the

Nit: commit message restates the HTINST-or-unprivileged-fetch decode mechanism, which is already described in the prep patch introducing decode_ldst_insn()/insn_fetch_faulted(), and isn't repeated in emulate_load()'s commit message. Suggest trimming for symmetry with the load commit, e.g.:

When a guest store instruction faults, the trapped instruction is decoded via decode_ldst_insn(), shared with the load path. At the moment only virtual interrupt controller (vINTC) traps are expected to occur, since it is currently the only backend registered with the MMIO handler dispatch, so in practice the store is emulated via the vINTC backend.

Signature · 1 line
Baptiste Le Duc <[email protected]>
#167 lore raw

Re: [PATCH v2 26/39] xen/riscv: add guest store emulation for trapped MMIO accesses

Quoted 18 lines · Baptiste Le Duc
Quoted 10 lines

Extend the guest page fault handler with store emulation to support MMIO write accesses.

The instruction decode mirrors emulate_load() and, like it, is adapted from Linux's KVM RISC-V implementation. As with the load path, the completion is synchronous through try_handle_mmio() rather than KVM's userspace exit/return split, since Xen's MMIO handlers run in the hypervisor. Faults taken while re-reading the trapped instruction are handled by decode_ldst_insn(), shared with the load path.

Quoted 2 lines

When a guest store instruction faults, the trapped instruction is decoded using HTINST or, if unavailable, fetched via unprivileged access. At the

Nit: commit message restates the HTINST-or-unprivileged-fetch decode mechanism, which is already described in the prep patch introducing decode_ldst_insn()/insn_fetch_faulted(), and isn't repeated in emulate_load()'s commit message. Suggest trimming for symmetry with the load commit, e.g.:

Quoted 7 lines

When a guest store instruction faults, the trapped instruction is decoded via decode_ldst_insn(), shared with the load path. At the moment only virtual interrupt controller (vINTC) traps are expected to occur, since it is currently the only backend registered with the MMIO handler dispatch, so in practice the store is emulated via the vINTC backend.

I will update the commit message.

Thanks.

~ Oleksii

#168 lore raw

PATCH v2 27/39 xen/riscv: introduce arch_move_irqs()

In reply to Oleksii Kurochko

When migrating a vCPU between pCPUs the hypervisor must also migrate the associated virtual interrupt state. arch_move_irqs() is the per-arch hook called by generic code to trigger that.

Replace the static inline BUG_ON placeholder in asm/irq.h with a real implementation in intc.c dispatching through a new move_irqs vintc_ops callback. Wire it up in vAPLIC, which delegates to imsic_migrate_vcpu() which itself still a stub to be implemented in follow-up patches.

Note that technically ASSERT() in arch_move_irqs() could be skipped as it will be anyway NULL pointer dereference (and a trap will occur) if something isn't properly initialized but sometimes it is harder to find place where NULL pointer derefence happened as it isn't guaraunted that all necessary registers will be filled with something useful.
As at the moment I don't find any case when ->move_irqs() could be skipped, the check that ->move_irq isn't NULL is added to ASSERT() instead of adding "if ( ...->move_irq) vitnc->ops->move_irqs(v)".

---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/imsic.c             | 5 +++++
 xen/arch/riscv/include/asm/imsic.h | 2 ++
 xen/arch/riscv/include/asm/intc.h  | 3 +++
 xen/arch/riscv/include/asm/irq.h   | 5 +----
 xen/arch/riscv/intc.c              | 8 ++++++++
 xen/arch/riscv/vaplic.c            | 1 +
 6 files changed, 20 insertions(+), 4 deletions(-)
xen/arch/riscv/imsic.c +5 -0
index 3787f270d8e3..b0c4a9e2d728 100644
@@ -686,3 +686,8 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
     return fdt_end_node(fdt);
 }
+
+void imsic_migrate_vcpu(struct vcpu *v)
+{
+    BUG_ON("unimplemented");
+}
xen/arch/riscv/include/asm/imsic.h +2 -0
index 73129c3c9ea7..57d8c729ac0d 100644
@@ -112,4 +112,6 @@ int vimsic_make_domu_dt_node(struct kernel_info *kinfo, unsigned int *phandle);
 void imsic_ctxt_switch_from(struct vcpu *v);
 void imsic_ctxt_switch_to(struct vcpu *v);
 
+void imsic_migrate_vcpu(struct vcpu *v);
+
 #endif /* ASM_RISCV_IMSIC_H */
xen/arch/riscv/include/asm/intc.h +3 -0
index 62e1410156c7..b5ab39aa2b39 100644
@@ -70,6 +70,9 @@ struct vintc_ops {
 
     /* Restore vINTC state of the vCPU being switched in */
     void (*ctxt_switch_to)(struct vcpu *v);
+
+    /* Move interrupts of vCPU to a different pCPU */
+    void (*move_irqs)(struct vcpu *v);
 };
 
 struct vintc {
xen/arch/riscv/include/asm/irq.h +1 -4
index 66067747dc0f..314b8ee0e00c 100644
@@ -41,10 +41,7 @@ struct irq_desc *irq_to_desc(unsigned int irq);
 struct cpu_user_regs;
 struct dt_device_node;
 
-static inline void arch_move_irqs(struct vcpu *v)
-{
-    BUG_ON("unimplemented");
-}
+void arch_move_irqs(struct vcpu *v);
 
 int platform_get_irq(const struct dt_device_node *device, int index);
 
xen/arch/riscv/intc.c +8 -0
index 9fff501b9c25..b3a16ae9be67 100644
@@ -192,3 +192,11 @@ void vintc_ctxt_switch_to(struct vcpu *v)
 
     ops->ctxt_switch_to(v);
 }
+
+/* Move vCPU's IRQs from one pCPU to another */
+void arch_move_irqs(struct vcpu *v)
+{
+    const struct vintc_ops *ops = v->domain->arch.vintc->ops;
+
+    ops->move_irqs(v);
+}
xen/arch/riscv/vaplic.c +1 -0
index 6c60fe2baf0c..0c75ba2fb2fe 100644
@@ -429,6 +429,7 @@ static const struct vintc_ops vintc_ops = {
      */
     .ctxt_switch_from = imsic_ctxt_switch_from,
     .ctxt_switch_to = imsic_ctxt_switch_to,
+    .move_irqs = imsic_migrate_vcpu,
 };
 
 int domain_vaplic_init(struct domain *d)
Signature · 1 line
2.55.0
Acked-by on v2 27/39
#169 lore raw

Re: [PATCH v2 27/39] xen/riscv: introduce arch_move_irqs()

Quoted 9 lines · Oleksii Kurochko

When migrating a vCPU between pCPUs the hypervisor must also migrate the associated virtual interrupt state. arch_move_irqs() is the per-arch hook called by generic code to trigger that.

Replace the static inline BUG_ON placeholder in asm/irq.h with a real implementation in intc.c dispatching through a new move_irqs vintc_ops callback. Wire it up in vAPLIC, which delegates to imsic_migrate_vcpu() which itself still a stub to be implemented in follow-up patches.

Quoted 9 lines

Note that technically ASSERT() in arch_move_irqs() could be skipped as it will be anyway NULL pointer dereference (and a trap will occur) if something isn't properly initialized but sometimes it is harder to find place where NULL pointer derefence happened as it isn't guaraunted that all necessary registers will be filled with something useful.
As at the moment I don't find any case when ->move_irqs() could be skipped, the check that ->move_irq isn't NULL is added to ASSERT() instead of adding "if ( ...->move_irq) vitnc->ops->move_irqs(v)".

All of these two paragraphs look stale / inapllicable; ...

Quoted 4 lines
xen/arch/riscv/intc.c +0 -0
@@ -192,3 +192,11 @@ void vintc_ctxt_switch_to(struct vcpu *v)
 

xen/arch/riscv/intc.c void vintc_ctxt_switch_to(struct vcpu *v) · line 202

Quoted 10 lines
xen/arch/riscv/intc.c +8 -0
     ops->ctxt_switch_to(v);
 }
+
+/* Move vCPU's IRQs from one pCPU to another */
+void arch_move_irqs(struct vcpu *v)
+{
+    const struct vintc_ops *ops = v->domain->arch.vintc->ops;
+
+    ops->move_irqs(v);
+}

There's no ASSERT() here (and I'd prefer if none was added). With the description pruned:

Jan

#170 lore raw

Re: [PATCH v2 27/39] xen/riscv: introduce arch_move_irqs()

Quoted 26 lines · Jan Beulich
Quoted 9 lines · Oleksii Kurochko

When migrating a vCPU between pCPUs the hypervisor must also migrate the associated virtual interrupt state. arch_move_irqs() is the per-arch hook called by generic code to trigger that.

Replace the static inline BUG_ON placeholder in asm/irq.h with a real implementation in intc.c dispatching through a new move_irqs vintc_ops callback. Wire it up in vAPLIC, which delegates to imsic_migrate_vcpu() which itself still a stub to be implemented in follow-up patches.

Quoted 9 lines

Note that technically ASSERT() in arch_move_irqs() could be skipped as it will be anyway NULL pointer dereference (and a trap will occur) if something isn't properly initialized but sometimes it is harder to find place where NULL pointer derefence happened as it isn't guaraunted that all necessary registers will be filled with something useful.
As at the moment I don't find any case when ->move_irqs() could be skipped, the check that ->move_irq isn't NULL is added to ASSERT() instead of adding "if ( ...->move_irq) vitnc->ops->move_irqs(v)".

All of these two paragraphs look stale / inapllicable; ...

Quoted 4 lines
xen/arch/riscv/intc.c +0 -0
@@ -192,3 +192,11 @@ void vintc_ctxt_switch_to(struct vcpu *v)
 
Quoted 13 lines

xen/arch/riscv/intc.c void vintc_ctxt_switch_to(struct vcpu *v) · line 202

Quoted 10 lines
xen/arch/riscv/intc.c +8 -0
      ops->ctxt_switch_to(v);
  }
+
+/* Move vCPU's IRQs from one pCPU to another */
+void arch_move_irqs(struct vcpu *v)
+{
+    const struct vintc_ops *ops = v->domain->arch.vintc->ops;
+
+    ops->move_irqs(v);
+}

There's no ASSERT() here (and I'd prefer if none was added). With the description pruned:

I will drop last two paragraphs. They are really stale.

Quoted 1 line

Thanks.

~ Oleksii

Quoted 2 lines

Jan

Reviewed-by on v2 27/39
#171 lore raw

Re: [PATCH v2 27/39] xen/riscv: introduce arch_move_irqs()

In reply to Oleksii Kurochko
Quoted 10 lines · Oleksii Kurochko

When migrating a vCPU between pCPUs the hypervisor must also migrate the associated virtual interrupt state. arch_move_irqs() is the per-arch hook called by generic code to trigger that.

Replace the static inline BUG_ON placeholder in asm/irq.h with a real implementation in intc.c dispatching through a new move_irqs vintc_ops callback. Wire it up in vAPLIC, which delegates to imsic_migrate_vcpu() which itself still a stub to be implemented in follow-up patches.

[...]

Signature · 1 line
Baptiste Le Duc <[email protected]>
#172 lore raw

PATCH v2 28/39 xen/riscv: handle the case when no vCPU migration is needed

In reply to Oleksii Kurochko

The IMSIC vsfile mapping is performed in continue_new_vcpu(), since the target pCPU must be known at that point. It is therefore possible for imsic_migrate_vcpu() to be called before continue_new_vcpu() has executed, in which case v->arch.last_pcpu is NR_CPUS and there is nothing to migrate.

Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/imsic.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
xen/arch/riscv/imsic.c +10 -0
index b0c4a9e2d728..ad7fbe708bfd 100644
@@ -689,5 +689,15 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
 void imsic_migrate_vcpu(struct vcpu *v)
 {
+    /*
+     * The scheduler can mark a freshly created vCPU's unit as migrated and
+     * invoke this before the vCPU has ever run (see the migrated branch in
+     * schedule()). No need to do migration for such vCPUs as they aren't fully
+     * initialized (for example, context_switch() will be called after
+     * imsic_migrate_vcpu()).
+     */
+    if ( v->arch.last_cpu == NR_CPUS )
+        return;
+
     BUG_ON("unimplemented");
 }
Signature · 1 line
2.55.0
#173 lore raw

Re: [PATCH v2 28/39] xen/riscv: handle the case when no vCPU migration is needed

Quoted 9 lines · Oleksii Kurochko

The IMSIC vsfile mapping is performed in continue_new_vcpu(), since the target pCPU must be known at that point. It is therefore possible for imsic_migrate_vcpu() to be called before continue_new_vcpu() has executed, in which case v->arch.last_pcpu is NR_CPUS and there is nothing to migrate.

Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

This doesn't adequately describe the change made: The BUG_ON() was already there.

Quoted 4 lines
xen/arch/riscv/imsic.c +0 -0
@@ -689,5 +689,15 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 699

Quoted 10 lines
xen/arch/riscv/imsic.c +8 -0
 void imsic_migrate_vcpu(struct vcpu *v)
 {
+    /*
+     * The scheduler can mark a freshly created vCPU's unit as migrated and
+     * invoke this before the vCPU has ever run (see the migrated branch in
+     * schedule()). No need to do migration for such vCPUs as they aren't fully
+     * initialized (for example, context_switch() will be called after
+     * imsic_migrate_vcpu()).
+     */
+    if ( v->arch.last_cpu == NR_CPUS )

May I suggest to use >= ? I'm still somewhat unconvinced of NR_CPUS being a good sentinel. If we/you decided to switch to ~0, >= here would continue to be correct.

Jan

Quoted 4 lines
xen/arch/riscv/imsic.c +2 -0
+        return;
+
     BUG_ON("unimplemented");
 }
#174 lore raw

Re: [PATCH v2 28/39] xen/riscv: handle the case when no vCPU migration is needed

Quoted 7 lines · Jan Beulich
Quoted 6 lines · Oleksii Kurochko

The IMSIC vsfile mapping is performed in continue_new_vcpu(), since the target pCPU must be known at that point. It is therefore possible for imsic_migrate_vcpu() to be called before continue_new_vcpu() has executed, in which case v->arch.last_pcpu is NR_CPUS and there is nothing to migrate.

Quoted 6 lines
Quoted 3 lines

Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

This doesn't adequately describe the change made: The BUG_ON() was already there.

Agree, it should be just:

Keep the BUG_ON() at the end of the function until imsic_migrate_vcpu() is fully implemented, to avoid ending up with a vCPU which isn't fully migrated to the new IMSIC interrupt file.

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/imsic.c +0 -0
@@ -689,5 +689,15 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
Quoted 14 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 699

Quoted 10 lines
xen/arch/riscv/imsic.c +8 -0
  void imsic_migrate_vcpu(struct vcpu *v)
  {
+    /*
+     * The scheduler can mark a freshly created vCPU's unit as migrated and
+     * invoke this before the vCPU has ever run (see the migrated branch in
+     * schedule()). No need to do migration for such vCPUs as they aren't fully
+     * initialized (for example, context_switch() will be called after
+     * imsic_migrate_vcpu()).
+     */
+    if ( v->arch.last_cpu == NR_CPUS )

May I suggest to use >= ? I'm still somewhat unconvinced of NR_CPUS being a good sentinel. If we/you decided to switch to ~0, >= here would continue to be correct.

I agree with >= but I am not quite sure that I fully understand what is wrong with NR_CPUS. We have for example the following:

static inline unsigned int smp_processor_id(void)

{
    unsigned int id = tp->processor_id;

    BUG_ON(id >= NR_CPUS);

    return id;
}

So it is guaranteed that NR_CPUS what be used as cpu id and so it still could be considered as a good sentinel.

Thanks.

~ Oleksii

#175 lore raw

Re: [PATCH v2 28/39] xen/riscv: handle the case when no vCPU migration is needed

Quoted 33 lines · Oleksii Kurochko
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +0 -0
@@ -689,5 +689,15 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
Quoted 14 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 699

Quoted 10 lines
xen/arch/riscv/imsic.c +8 -0
  void imsic_migrate_vcpu(struct vcpu *v)
  {
+    /*
+     * The scheduler can mark a freshly created vCPU's unit as migrated and
+     * invoke this before the vCPU has ever run (see the migrated branch in
+     * schedule()). No need to do migration for such vCPUs as they aren't fully
+     * initialized (for example, context_switch() will be called after
+     * imsic_migrate_vcpu()).
+     */
+    if ( v->arch.last_cpu == NR_CPUS )

May I suggest to use >= ? I'm still somewhat unconvinced of NR_CPUS being a good sentinel. If we/you decided to switch to ~0, >= here would continue to be correct.

I agree with >= but I am not quite sure that I fully understand what is wrong with NR_CPUS. We have for example the following:

static inline unsigned int smp_processor_id(void)

{
     unsigned int id = tp->processor_id;

     BUG_ON(id >= NR_CPUS);

     return id;
}
Quoted 2 lines

So it is guaranteed that NR_CPUS what be used as cpu id and so it still could be considered as a good sentinel.

Arbitrary numbers can be problematic when used as a sentinel. If you look at disassembly, you may not recognize that number as a sentinel. Further there's also a code-gen concern: ~0, aiui, will always generate the same code (to e.g. load into a register). NR_CPUS, depending on .config, may not. The value may not be loadable by a single insn.

Jan

#176 lore raw

Re: [PATCH v2 28/39] xen/riscv: handle the case when no vCPU migration is needed

Quoted 34 lines · Jan Beulich
Quoted 33 lines · Oleksii Kurochko
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +0 -0
@@ -689,5 +689,15 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
Quoted 14 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 699

Quoted 10 lines
xen/arch/riscv/imsic.c +8 -0
   void imsic_migrate_vcpu(struct vcpu *v)
   {
+    /*
+     * The scheduler can mark a freshly created vCPU's unit as migrated and
+     * invoke this before the vCPU has ever run (see the migrated branch in
+     * schedule()). No need to do migration for such vCPUs as they aren't fully
+     * initialized (for example, context_switch() will be called after
+     * imsic_migrate_vcpu()).
+     */
+    if ( v->arch.last_cpu == NR_CPUS )

May I suggest to use >= ? I'm still somewhat unconvinced of NR_CPUS being a good sentinel. If we/you decided to switch to ~0, >= here would continue to be correct.

I agree with >= but I am not quite sure that I fully understand what is wrong with NR_CPUS. We have for example the following:

static inline unsigned int smp_processor_id(void)

{
      unsigned int id = tp->processor_id;

      BUG_ON(id >= NR_CPUS);

      return id;
}
Quoted 8 lines
Quoted 2 lines

So it is guaranteed that NR_CPUS what be used as cpu id and so it still could be considered as a good sentinel.

Arbitrary numbers can be problematic when used as a sentinel. If you look at disassembly, you may not recognize that number as a sentinel. Further there's also a code-gen concern: ~0, aiui, will always generate the same code (to e.g. load into a register). NR_CPUS, depending on .config, may not. The value may not be loadable by a single insn.

Witch such explanation it started to be more sense in it.

I will introduce then

/* Value of arch_vcpu.last_cpu for a vCPU which hasn't run yet. */ #define VCPU_NEVER_RAN (~0U)

and use it to work with v->arch.last_cpu.

Just to be sure that I understand correctly your suggestion with ~0U is only for the case of ->last_cpu and check if vcpu was ran or not.

For

struct pcpu_info pcpu_info[NR_CPUS] = { [0 ... NR_CPUS - 1] = {
.processor_id = NR_CPUS,
}};

and

struct vimsic_state {
...

    /*
     * s/w IMSIC VS-file -> vsfile_cpu == NR_CPUS
     * h/w IMSIC VS-file -> vsfile_cpu < NR_CPUS
     */
    unsigned int vsfile_cpu;
};

I can continue to use NR_CPUS, right?

~ Oleksii

#177 lore raw

Re: [PATCH v2 28/39] xen/riscv: handle the case when no vCPU migration is needed

Quoted 68 lines · Oleksii Kurochko
Quoted 34 lines · Jan Beulich
Quoted 33 lines · Oleksii Kurochko
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +0 -0
@@ -689,5 +689,15 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
Quoted 14 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 699

Quoted 10 lines
xen/arch/riscv/imsic.c +8 -0
   void imsic_migrate_vcpu(struct vcpu *v)
   {
+    /*
+     * The scheduler can mark a freshly created vCPU's unit as migrated and
+     * invoke this before the vCPU has ever run (see the migrated branch in
+     * schedule()). No need to do migration for such vCPUs as they aren't fully
+     * initialized (for example, context_switch() will be called after
+     * imsic_migrate_vcpu()).
+     */
+    if ( v->arch.last_cpu == NR_CPUS )

May I suggest to use >= ? I'm still somewhat unconvinced of NR_CPUS being a good sentinel. If we/you decided to switch to ~0, >= here would continue to be correct.

I agree with >= but I am not quite sure that I fully understand what is wrong with NR_CPUS. We have for example the following:

static inline unsigned int smp_processor_id(void)

{
      unsigned int id = tp->processor_id;

      BUG_ON(id >= NR_CPUS);

      return id;
}
Quoted 8 lines
Quoted 2 lines

So it is guaranteed that NR_CPUS what be used as cpu id and so it still could be considered as a good sentinel.

Arbitrary numbers can be problematic when used as a sentinel. If you look at disassembly, you may not recognize that number as a sentinel. Further there's also a code-gen concern: ~0, aiui, will always generate the same code (to e.g. load into a register). NR_CPUS, depending on .config, may not. The value may not be loadable by a single insn.

Witch such explanation it started to be more sense in it.

I will introduce then

/* Value of arch_vcpu.last_cpu for a vCPU which hasn't run yet. */ #define VCPU_NEVER_RAN (~0U)

and use it to work with v->arch.last_cpu.

Just to be sure that I understand correctly your suggestion with ~0U is only for the case of ->last_cpu and check if vcpu was ran or not.

For

struct pcpu_info pcpu_info[NR_CPUS] = { [0 ... NR_CPUS - 1] = {
.processor_id = NR_CPUS,
}};

and

struct vimsic_state {
...

Quoted 8 lines
     /*
      * s/w IMSIC VS-file -> vsfile_cpu == NR_CPUS
      * h/w IMSIC VS-file -> vsfile_cpu < NR_CPUS
      */
     unsigned int vsfile_cpu;
};

I can continue to use NR_CPUS, right?

You _can_ everywhere. It may merely be beneficial to use ~0 instead, at least in some cases. The "how to load value into a register" aspect of course doesn't affect static initializers. The "easy to recognize" one, otoh, may apply there as well. You get to judge...

Jan

#178 lore raw

Re: [PATCH v2 28/39] xen/riscv: handle the case when no vCPU migration is needed

Quoted 76 lines · Jan Beulich
Quoted 75 lines · Oleksii Kurochko
Quoted 34 lines · Jan Beulich
Quoted 33 lines · Oleksii Kurochko
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +0 -0
@@ -689,5 +689,15 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
Quoted 14 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 699

Quoted 10 lines
xen/arch/riscv/imsic.c +8 -0
    void imsic_migrate_vcpu(struct vcpu *v)
    {
+    /*
+     * The scheduler can mark a freshly created vCPU's unit as migrated and
+     * invoke this before the vCPU has ever run (see the migrated branch in
+     * schedule()). No need to do migration for such vCPUs as they aren't fully
+     * initialized (for example, context_switch() will be called after
+     * imsic_migrate_vcpu()).
+     */
+    if ( v->arch.last_cpu == NR_CPUS )

May I suggest to use >= ? I'm still somewhat unconvinced of NR_CPUS being a good sentinel. If we/you decided to switch to ~0, >= here would continue to be correct.

I agree with >= but I am not quite sure that I fully understand what is wrong with NR_CPUS. We have for example the following:

static inline unsigned int smp_processor_id(void)

{
       unsigned int id = tp->processor_id;

       BUG_ON(id >= NR_CPUS);

       return id;
}
Quoted 8 lines
Quoted 2 lines

So it is guaranteed that NR_CPUS what be used as cpu id and so it still could be considered as a good sentinel.

Arbitrary numbers can be problematic when used as a sentinel. If you look at disassembly, you may not recognize that number as a sentinel. Further there's also a code-gen concern: ~0, aiui, will always generate the same code (to e.g. load into a register). NR_CPUS, depending on .config, may not. The value may not be loadable by a single insn.

Witch such explanation it started to be more sense in it.

I will introduce then

/* Value of arch_vcpu.last_cpu for a vCPU which hasn't run yet. */ #define VCPU_NEVER_RAN (~0U)

and use it to work with v->arch.last_cpu.

Just to be sure that I understand correctly your suggestion with ~0U is only for the case of ->last_cpu and check if vcpu was ran or not.

For

struct pcpu_info pcpu_info[NR_CPUS] = { [0 ... NR_CPUS - 1] = {
.processor_id = NR_CPUS,
}};

and

struct vimsic_state {
...

      /*
       * s/w IMSIC VS-file -> vsfile_cpu == NR_CPUS
       * h/w IMSIC VS-file -> vsfile_cpu < NR_CPUS
       */
      unsigned int vsfile_cpu;
};
Quoted 7 lines
Quoted 1 line

I can continue to use NR_CPUS, right?

You _can_ everywhere. It may merely be beneficial to use ~0 instead, at least in some cases. The "how to load value into a register" aspect of course doesn't affect static initializers. The "easy to recognize" one, otoh, may apply there as well. You get to judge...

I checked how NR_CPUS is used and it is okay to change to ~0U for vsfile_cpu mentioned above as it could really affect how to load value into a register but I am not sure about .processor_id as it is just static initializer (maybe just for consistency).

Also as hartid_to_cpuid() returning NR_CPUS to follow the common convention of returning an out-of-range CPU number when nothing was found (like cpumask_first() / cpumask_next() do), so callers check the result with >= rather than against a specific sentinel.

If to use ~0U for vsfile_cpu then suggested name VCPU_NEVER_RAN isn't good. Then probably CPU_NONE will be better.

If we will start to use ~0 instead of NR_CPUS then IIUC it won't be any sense to use ">=" suggested above and "==" could be continue to be used, right?

~ Oleksii

#179 lore raw

Re: [PATCH v2 28/39] xen/riscv: handle the case when no vCPU migration is needed

Quoted 92 lines · Oleksii Kurochko
Quoted 74 lines · Jan Beulich
Quoted 73 lines · Oleksii Kurochko
Quoted 34 lines · Jan Beulich
Quoted 33 lines · Oleksii Kurochko
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +0 -0
@@ -689,5 +689,15 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
Quoted 14 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 699

Quoted 10 lines
xen/arch/riscv/imsic.c +8 -0
    void imsic_migrate_vcpu(struct vcpu *v)
    {
+    /*
+     * The scheduler can mark a freshly created vCPU's unit as migrated and
+     * invoke this before the vCPU has ever run (see the migrated branch in
+     * schedule()). No need to do migration for such vCPUs as they aren't fully
+     * initialized (for example, context_switch() will be called after
+     * imsic_migrate_vcpu()).
+     */
+    if ( v->arch.last_cpu == NR_CPUS )

May I suggest to use >= ? I'm still somewhat unconvinced of NR_CPUS being a good sentinel. If we/you decided to switch to ~0, >= here would continue to be correct.

I agree with >= but I am not quite sure that I fully understand what is wrong with NR_CPUS. We have for example the following:

static inline unsigned int smp_processor_id(void)

{
       unsigned int id = tp->processor_id;

       BUG_ON(id >= NR_CPUS);

       return id;
}
Quoted 8 lines
Quoted 2 lines

So it is guaranteed that NR_CPUS what be used as cpu id and so it still could be considered as a good sentinel.

Arbitrary numbers can be problematic when used as a sentinel. If you look at disassembly, you may not recognize that number as a sentinel. Further there's also a code-gen concern: ~0, aiui, will always generate the same code (to e.g. load into a register). NR_CPUS, depending on .config, may not. The value may not be loadable by a single insn.

Witch such explanation it started to be more sense in it.

I will introduce then

/* Value of arch_vcpu.last_cpu for a vCPU which hasn't run yet. */ #define VCPU_NEVER_RAN (~0U)

and use it to work with v->arch.last_cpu.

Just to be sure that I understand correctly your suggestion with ~0U is only for the case of ->last_cpu and check if vcpu was ran or not.

For

struct pcpu_info pcpu_info[NR_CPUS] = { [0 ... NR_CPUS - 1] = {
.processor_id = NR_CPUS,
}};

and

struct vimsic_state {
...

      /*
       * s/w IMSIC VS-file -> vsfile_cpu == NR_CPUS
       * h/w IMSIC VS-file -> vsfile_cpu < NR_CPUS
       */
      unsigned int vsfile_cpu;
};
Quoted 7 lines
Quoted 1 line

I can continue to use NR_CPUS, right?

You _can_ everywhere. It may merely be beneficial to use ~0 instead, at least in some cases. The "how to load value into a register" aspect of course doesn't affect static initializers. The "easy to recognize" one, otoh, may apply there as well. You get to judge...

I checked how NR_CPUS is used and it is okay to change to ~0U for vsfile_cpu mentioned above as it could really affect how to load value into a register but I am not sure about .processor_id as it is just static initializer (maybe just for consistency).

Also as hartid_to_cpuid() returning NR_CPUS to follow the common convention of returning an out-of-range CPU number when nothing was found (like cpumask_first() / cpumask_next() do), so callers check the result with >= rather than against a specific sentinel.

Quoted 6 lines

If to use ~0U for vsfile_cpu then suggested name VCPU_NEVER_RAN isn't good. Then probably CPU_NONE will be better.

If we will start to use ~0 instead of NR_CPUS then IIUC it won't be any sense to use ">=" suggested above and "==" could be continue to be used, right?

I fear you may not like the answer: Depends. IOW I can't give a concrete reply unless seeing the concrete use(s).

Jan

#180 lore raw

Re: [PATCH v2 28/39] xen/riscv: handle the case when no vCPU migration is needed

In reply to Jan Beulich
Quoted 19 lines · Jan Beulich
Quoted 9 lines · Oleksii Kurochko

The IMSIC vsfile mapping is performed in continue_new_vcpu(), since the target pCPU must be known at that point. It is therefore possible for imsic_migrate_vcpu() to be called before continue_new_vcpu() has executed, in which case v->arch.last_pcpu is NR_CPUS and there is nothing to migrate.

Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

This doesn't adequately describe the change made: The BUG_ON() was already there.

Quoted 4 lines
xen/arch/riscv/imsic.c +0 -0
@@ -689,5 +689,15 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
Quoted 14 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 699

Quoted 10 lines
xen/arch/riscv/imsic.c +8 -0
 void imsic_migrate_vcpu(struct vcpu *v)
 {
+    /*
+     * The scheduler can mark a freshly created vCPU's unit as migrated and
+     * invoke this before the vCPU has ever run (see the migrated branch in
+     * schedule()). No need to do migration for such vCPUs as they aren't fully
+     * initialized (for example, context_switch() will be called after
+     * imsic_migrate_vcpu()).
+     */
+    if ( v->arch.last_cpu == NR_CPUS )

May I suggest to use >= ? I'm still somewhat unconvinced of NR_CPUS being a good sentinel. If we/you decided to switch to ~0, >= here would continue to be correct.

I also agree that ~0 would be better.

Quoted 2 lines

Jan

#181 lore raw

PATCH v2 29/39 xen/riscv: introduce aplic_reconfigure_target()

In reply to Oleksii Kurochko

When a vCPU is migrated to a different pCPU, its IMSIC guest interrupt file changes. Any APLIC interrupt previously configured to deliver an MSI to the old interrupt file must be retargeted to the new one.

Implement aplic_reconfigure_target() to scan all interrupts allocated to the domain and update their APLIC TARGET registers accordingly.

---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/aplic.c             | 42 ++++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/aplic.h |  4 +++
 2 files changed, 46 insertions(+)
xen/arch/riscv/aplic.c +42 -0
index b4c419755ac3..0af13f28e467 100644
@@ -138,6 +138,48 @@ uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
     return base_val;
 }
 
+void aplic_reconfigure_target(const struct vcpu *v,
+                              unsigned int old_guest_file_id,
+                              unsigned int old_cpu)
+{
+    const struct vintc *vintc = v->domain->arch.vintc;
+    const unsigned long *auth_irq_bmp = vintc->used_irqs;
+    unsigned long old_hart_field = aplic_hart_field(old_cpu);
+    unsigned long flags;
+    unsigned int irqn;
+
+    /* Support only MSI mode at the moment */
+    BUG_ON(!aplic_msi_mode());
+
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    bitmap_for_each ( irqn, auth_irq_bmp, vintc->nr_virqs )
+    {
+        volatile uint32_t __iomem *ptarget;
+        uint32_t target_val;
+        unsigned int guest_index, hart_index;
+
+        if ( !irqn )
+            continue;
+
+        ptarget = &aplic.regs->target[irqn - 1];
+        target_val = readl(ptarget);
+
+        guest_index = MASK_EXTR(target_val, APLIC_TARGET_GUEST_IDX);
+        hart_index = MASK_EXTR(target_val, APLIC_TARGET_HART_IDX);
+
+        if ( (guest_index != old_guest_file_id) ||
+             (hart_index != old_hart_field) )
+            continue;
+
+        target_val = aplic_msi_target_gen(v, target_val);
+
+        writel(target_val, ptarget);
+    }
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+
 uint32_t aplic_hw_read_reg(unsigned int offset)
 {
     unsigned long flags;
xen/arch/riscv/include/asm/aplic.h +4 -0
index d629e1c83887..8564f5954b6b 100644
@@ -174,4 +174,8 @@ struct aplic_regs {
 uint32_t aplic_hw_read_reg(unsigned int offset);
 void aplic_hw_write_reg(unsigned int offset, uint32_t value);
 
+void aplic_reconfigure_target(const struct vcpu *v,
+                              unsigned int old_guest_file_id,
+                              unsigned int old_cpu);
+
 #endif /* ASM_RISCV_APLIC_H */
Signature · 1 line
2.55.0
#182 lore raw

Re: [PATCH v2 29/39] xen/riscv: introduce aplic_reconfigure_target()

Quoted 8 lines · Oleksii Kurochko

When a vCPU is migrated to a different pCPU, its IMSIC guest interrupt file changes. Any APLIC interrupt previously configured to deliver an MSI to the old interrupt file must be retargeted to the new one.

Implement aplic_reconfigure_target() to scan all interrupts allocated to the domain and update their APLIC TARGET registers accordingly.

First of all I'd like to understand how this "reconfigure" works without losing interrupts and at the same time without other possible races. An interrupt can be raised at any time, after all.

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 147

Quoted 13 lines
xen/arch/riscv/aplic.c +7 -0
@@ -138,6 +138,48 @@ uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
     return base_val;
 }
 
+void aplic_reconfigure_target(const struct vcpu *v,
+                              unsigned int old_guest_file_id,
+                              unsigned int old_cpu)
+{
+    const struct vintc *vintc = v->domain->arch.vintc;
+    const unsigned long *auth_irq_bmp = vintc->used_irqs;
+    unsigned long old_hart_field = aplic_hart_field(old_cpu);

Once again a question you may already recognize: What extra value does "field" in the variable name add?

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 154

Quoted 7 lines
xen/arch/riscv/aplic.c +7 -0
+    unsigned long flags;
+    unsigned int irqn;
+
+    /* Support only MSI mode at the moment */
+    BUG_ON(!aplic_msi_mode());
+
+    spin_lock_irqsave(&aplic.lock, flags);

Taking a global lock for a per-vCPU operation isn't going to scale very well. Even more so when then ...

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 156

Quoted 1 line
xen/arch/riscv/aplic.c +1 -0
+    bitmap_for_each ( irqn, auth_irq_bmp, vintc->nr_virqs )

... you run a loop with perhaps many (hundreds? thousands?) iterations.

Quoted 7 lines
xen/arch/riscv/aplic.c +7 -0
+    {
+        volatile uint32_t __iomem *ptarget;
+        uint32_t target_val;
+        unsigned int guest_index, hart_index;
+
+        if ( !irqn )
+            continue;

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 173

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+
+        ptarget = &aplic.regs->target[irqn - 1];
+        target_val = readl(ptarget);
+
+        guest_index = MASK_EXTR(target_val, APLIC_TARGET_GUEST_IDX);
+        hart_index = MASK_EXTR(target_val, APLIC_TARGET_HART_IDX);
+
+        if ( (guest_index != old_guest_file_id) ||
+             (hart_index != old_hart_field) )
+            continue;

Along the lines of the naming comment above: This would be more logical to follow if it was

        if ( (guest_id != old_guest_id) ||
             (hart != old_hart) )
            continue;

i.e. names on each side of the != suitably matching up.

Jan

#183 lore raw

Re: [PATCH v2 29/39] xen/riscv: introduce aplic_reconfigure_target()

Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko

When a vCPU is migrated to a different pCPU, its IMSIC guest interrupt file changes. Any APLIC interrupt previously configured to deliver an MSI to the old interrupt file must be retargeted to the new one.

Quoted 8 lines
Quoted 4 lines

Implement aplic_reconfigure_target() to scan all interrupts allocated to the domain and update their APLIC TARGET registers accordingly.

First of all I'd like to understand how this "reconfigure" works without losing interrupts and at the same time without other possible races. An interrupt can be raised at any time, after all.

The RISC-V AIA specification relies on this separation for the 6-step vCPU migration sequence:

Step 1. Setting eidelivery = 0 at the old interrupt file stops new traps on the host CPU.

Step 3: Reconfiguring APLIC/IOMMU and flushing the interconnect forces all in-flight "straggler" MSIs to reach the old interrupt file.

Step 4: Because eidelivery = 0 did not block incoming MSIs from setting bits in eip, those straggler MSIs safely landed in the old eip array.

Step 5: The hypervisor reads/dumps the old eip array and bitwise ORs it into the new interrupt file, guaranteeing that no in-flight MSIs are lost during the transition.

(Note that I re-word some steps and skipped some for simplicity. Here you can find full text: https://github.com/riscv/riscv-aia/blob/main/src/VSLevel.adoc?plain=1#L134)

Does it make sense now?

Quoted 7 lines
Quoted 7 lines
xen/arch/riscv/aplic.c +0 -0
@@ -138,6 +138,48 @@ uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
      return base_val;
  }
 
Quoted 10 lines

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 147

Quoted 7 lines
xen/arch/riscv/aplic.c +7 -0
+void aplic_reconfigure_target(const struct vcpu *v,
+                              unsigned int old_guest_file_id,
+                              unsigned int old_cpu)
+{
+    const struct vintc *vintc = v->domain->arch.vintc;
+    const unsigned long *auth_irq_bmp = vintc->used_irqs;
+    unsigned long old_hart_field = aplic_hart_field(old_cpu);

Once again a question you may already recognize: What extra value does "field" in the variable name add?

Because aplic_hart_field() construct target's part of hart field which isn't contains only pure hart value (apparently, thanks to the way how spec is written and things are done).

Note that based on other reviews from this patch series it is renamed to:
unsigned long old_hart_index = aplic_hart_index(old_cpu);
(and here _index for the same reason it is basically how AIA spec calls this part of the target register)

Quoted 12 lines

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 154

Quoted 8 lines
xen/arch/riscv/aplic.c +7 -0
+    unsigned long flags;
+    unsigned int irqn;
+
+    /* Support only MSI mode at the moment */
+    BUG_ON(!aplic_msi_mode());
+
+    spin_lock_irqsave(&aplic.lock, flags);

Taking a global lock for a per-vCPU operation isn't going to scale very well. Even more so when then ...

Quoted 4 lines

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 156

Quoted 1 line
xen/arch/riscv/aplic.c +1 -0
+    bitmap_for_each ( irqn, auth_irq_bmp, vintc->nr_virqs )

... you run a loop with perhaps many (hundreds? thousands?) iterations.

I agree.

Then per vcpu's target register lock (or per-irq lock) + APLIC's global lock mention here only for a short period when APLIC register would be needed.

I've done such change for support of IMSIC software interrupt file but it seems like it is started to need earlier.

Quoted 22 lines
Quoted 8 lines
xen/arch/riscv/aplic.c +7 -0
+    {
+        volatile uint32_t __iomem *ptarget;
+        uint32_t target_val;
+        unsigned int guest_index, hart_index;
+
+        if ( !irqn )
+            continue;

xen/arch/riscv/aplic.c uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu, · line 173

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+
+        ptarget = &aplic.regs->target[irqn - 1];
+        target_val = readl(ptarget);
+
+        guest_index = MASK_EXTR(target_val, APLIC_TARGET_GUEST_IDX);
+        hart_index = MASK_EXTR(target_val, APLIC_TARGET_HART_IDX);
+
+        if ( (guest_index != old_guest_file_id) ||
+             (hart_index != old_hart_field) )
+            continue;

Along the lines of the naming comment above: This would be more logical to follow if it was

Quoted 5 lines
         if ( (guest_id != old_guest_id) ||
              (hart != old_hart) )
             continue;

i.e. names on each side of the != suitably matching up.

I agree with guest_id suggestion but hart_index should be left as according to the spec what is stored in hart index field of target register isn't pure hart cpu id but it is a combination of hart cpu id + group index (check the comment above aplic_hart_field() for better context).

Thanks.

~ Oleksii

#184 lore raw

PATCH v2 30/39 xen/riscv: prepare new IMSIC VS-file

In reply to Oleksii Kurochko

Implement first steps of migration a vCPU to a different guest interrupt file procedure:
- At the old interrupt file, save to memory the values of registers eidelivery and eithreshold, and set eidelivery = 0.
- At the new interrupt file, set eidelivery = 0, and zero all implemented interrupt-pending bits (the eip array).

The following steps will be introduced in follow-up patches.

Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_assign() will be introduced later in a separate patch, for not it is only stub.

---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/aia.c             |   9 ++
 xen/arch/riscv/imsic.c           | 159 +++++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/aia.h |   4 +
 xen/include/xen/config.h         |   1 +
 4 files changed, 173 insertions(+)
xen/arch/riscv/aia.c +9 -0
index e31c9c2d24b6..75c82bcfa1b3 100644
@@ -1,8 +1,10 @@
 /* SPDX-License-Identifier: GPL-2.0-only */
 
+#include <xen/bug.h>
 #include <xen/errno.h>
 #include <xen/init.h>
 #include <xen/sections.h>
+#include <xen/sched.h>
 #include <xen/types.h>
 
 #include <asm/cpufeature.h>
@@ -21,3 +23,10 @@ void __init aia_init(void)
 
     _aia_usable = true;
 }
+
+unsigned int vgein_assign(struct vcpu *v)
+{
+    BUG_ON("unimplemented\n");
+
+    return 0;
+}
xen/arch/riscv/imsic.c +159 -0

188 lines not on this page · raw message

xen/arch/riscv/include/asm/aia.h +4 -0
index aaa4bf91fc75..53a1efb042f8 100644
@@ -3,8 +3,12 @@
 #ifndef RISCV_AIA_H
 #define RISCV_AIA_H
 
+struct vcpu;
+
 bool aia_usable(void);
 
 void aia_init(void);
 
+unsigned int vgein_assign(struct vcpu *v);
+
 #endif /* RISCV_AIA_H */
xen/include/xen/config.h +1 -0
index dddc8e1920fe..0e29976e8203 100644
@@ -100,6 +100,7 @@
 #define BITS_PER_INT    (BITS_PER_BYTE * __SIZEOF_INT__)
 #define BITS_PER_LONG   (BITS_PER_BYTE * BYTES_PER_LONG)
 #define BITS_PER_LLONG  (BITS_PER_BYTE * __SIZEOF_LONG_LONG__)
+#define BITS_PER_TYPE(type) (sizeof(type) * BITS_PER_BYTE)
 
 /* It is assumed that sizeof(void *) == __alignof(void *) */
 #define POINTER_ALIGN   __SIZEOF_POINTER__
Signature · 1 line
2.55.0
#185 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

xen/arch/riscv/imsic.c do { \ · line 84

Quoted 8 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +4 -0
@@ -77,6 +78,64 @@ do {                            \
     csr_clear(CSR_SIREG, v);    \
 } while (0)
 
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_write(CSR_VSIREG, (v));     \

As patch context also tells: Excess parentheses.

xen/arch/riscv/imsic.c do { \ · line 91

Quoted 7 lines
xen/arch/riscv/imsic.c +7 -0
+} while ( 0 )
+
+/*
+ * Generic switchcase expansion pyramid.
+ * F is the per-operation leaf macro, ireg is the base register index.
+ * Optional extra args (e.g. an operation and/or a value) are forwarded to F
+ * via __VA_ARGS__.

Just that there's no F below.

Quoted 7 lines
xen/arch/riscv/imsic.c +7 -0
+ * imsic_switchcase_break(ireg, op, v) - emit "case ireg: op(ireg,v); break;"
+ * imsic_switchcase_ret(ireg, op, ...) - emit "case ireg: return op(ireg[,v]);"
+ *   The variadic tail is optional so the same leaf works for both read (no v)
+ *   and swap (with v).
+ */
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \

xen/arch/riscv/imsic.c do { \ · line 109

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+        op(ireg, v);                        \
+        break;
+
+#define imsic_switchcase_ret(ireg, op, ...) \
+    case ireg:                              \
+        return op(ireg, ##__VA_ARGS__);
+
+#define imsic_switchcase_2(F, ireg, ...)    \
+    F(ireg + 0, ##__VA_ARGS__)              \
+    F(ireg + 1, ##__VA_ARGS__)

Ah, there is an F here.

This (recurring below) shows another problem: The two F invocations look syntacticlly incorrect, due to the missing semicolon. Semicolon use wants redoing everywhere here.

Further (and again throughout) I think we'd be better off using either standard C constructs (e.g. __VA_ARGS__) or the gcc extension permitting use of ## after a comma. A mix of both always looks odd (to me at least).

Finally, unlike further up, here (and below) ireg wants parenthesizing.

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 458

Quoted 12 lines
xen/arch/riscv/imsic.c +8 -0
@@ -389,6 +448,76 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
     return 0;
 }
 
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which are executed by the
+ * pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ */
+struct imsic_vsfile_data {
+    unsigned int hgei;
+    unsigned int nr_eix;
+    struct imsic_mrif *mrif;

I can't spot any use of this field (and hence I also can't judge whether const wants adding).

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+};
+
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file func() is
+ * going to work with.
+ *

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 474

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
+ * handler.
+ */
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              void *data)

If this is supposed to be passed struct imsic_vsfile_data *, why not say so here? Be as type-safe as possible. Of course the callback function has to use void *.

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 496

Quoted 9 lines
xen/arch/riscv/imsic.c +9 -0
+static void cf_check imsic_vsfile_local_clear(void *data)
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */
+    if ( !idata->hgei )
+        return;

Wouldn't it make sense to avoid the call here altogether then?

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 498

Quoted 1 line
xen/arch/riscv/imsic.c +1 -0
+    old_vsiselect = csr_read(CSR_VSISELECT);

Likely obvious to you, but I can't spot why vsiselect would need saving here. If you want me to ack such code, please add at least brief comments.

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 514

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
+#endif

In asm/imsic.h I see

#define IMSIC_EIPx_BITS 32

Why is the number of CSR writes different here for RV32 vs RV64? And if so, why would you not use the 64-bit write function, allowing the #ifdef to be omitted?

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 824

Quoted 8 lines
xen/arch/riscv/imsic.c +4 -0
@@ -689,6 +818,14 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
 void imsic_migrate_vcpu(struct vcpu *v)
 {
+    unsigned int new_vsfile_hgei;
+    unsigned int new_vsfile_cpu;
+    unsigned int nr_hw_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1,
+                                          BITS_PER_TYPE(uint64_t));

As written, this could also be 64. uint64_t is a fixed-width type after all. The question here is: Which variable's type do you really mean here?

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 826

Quoted 2 lines
xen/arch/riscv/imsic.c +2 -0
+    struct imsic_vsfile_data vsfile_data = {
+        .nr_eix = nr_hw_eix,

The local variable looks to be used only here. Is there really a need for such a local variable?

Quoted 5 lines
xen/arch/riscv/imsic.c +1 -0
@@ -699,5 +836,27 @@ void imsic_migrate_vcpu(struct vcpu *v)
     if ( v->arch.last_cpu == NR_CPUS )
         return;
 
+    /*

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 849

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+     * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file.
+     */
+
+    /*
+     * Latch the pCPU the new interrupt file is taken from: vgein_assign()
+     * allocates it from v->processor's pool of guest interrupt files, and
+     * only that hart can access the file afterwards.
+     */
+    new_vsfile_cpu = v->processor;

Same here: Is this variable really needed? And what exactly is the comment telling me?

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 856

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+    new_vsfile_hgei = vgein_assign(v);
+
+    /* We don't support SW interrupt files at the moment. */
+    BUG_ON(!new_vsfile_hgei);
+
+    vsfile_data.hgei = new_vsfile_hgei;

And again - any real need for the separate local variable?

Jan

#186 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

Quoted 11 lines · Jan Beulich

Review do { \ · line 84

Quoted 8 lines · Oleksii Kurochko
(quoted diff) +4 -0
@@ -77,6 +78,64 @@ do {                            \
      csr_clear(CSR_SIREG, v);    \
  } while (0)
 
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_write(CSR_VSIREG, (v));     \

As patch context also tells: Excess parentheses.

I will drop them then.

Quoted 10 lines

Review do { \ · line 91

Quoted 8 lines
(quoted diff) +7 -0
+} while ( 0 )
+
+/*
+ * Generic switchcase expansion pyramid.
+ * F is the per-operation leaf macro, ireg is the base register index.
+ * Optional extra args (e.g. an operation and/or a value) are forwarded to F
+ * via __VA_ARGS__.

Just that there's no F below.

Oh, right. I will move this comment a little bit down.

Quoted 21 lines
Quoted 8 lines
(quoted diff) +7 -0
+ * imsic_switchcase_break(ireg, op, v) - emit "case ireg: op(ireg,v); break;"
+ * imsic_switchcase_ret(ireg, op, ...) - emit "case ireg: return op(ireg[,v]);"
+ *   The variadic tail is optional so the same leaf works for both read (no v)
+ *   and swap (with v).
+ */
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \

Review do { \ · line 108

Quoted 10 lines
(quoted diff) +10 -0
+        op(ireg, v);                        \
+        break;
+
+#define imsic_switchcase_ret(ireg, op, ...) \
+    case ireg:                              \
+        return op(ireg, ##__VA_ARGS__);
+
+#define imsic_switchcase_2(F, ireg, ...)    \
+    F(ireg + 0, ##__VA_ARGS__)              \
+    F(ireg + 1, ##__VA_ARGS__)

Ah, there is an F here.

Quoted 3 lines

This (recurring below) shows another problem: The two F invocations look syntacticlly incorrect, due to the missing semicolon. Semicolon use wants redoing everywhere here.

I will drop then ';' from imsic_switchcase_{break,ret}.

Quoted 5 lines

Further (and again throughout) I think we'd be better off using either standard C constructs (e.g. __VA_ARGS__) or the gcc extension permitting use of ## after a comma. A mix of both always looks odd (to me at least).

I will follow C standard here.

Quoted 2 lines

Finally, unlike further up, here (and below) ireg wants parenthesizing.

I will add some.

Quoted 5 lines
Quoted 5 lines
(quoted diff) +0 -0
@@ -389,6 +448,76 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
      return 0;
  }
 
Quoted 11 lines

Review int cf_check vcpu_imsic_init(struct vcpu *v) · line 458

Quoted 8 lines
(quoted diff) +8 -0
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which are executed by the
+ * pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ */
+struct imsic_vsfile_data {
+    unsigned int hgei;
+    unsigned int nr_eix;
+    struct imsic_mrif *mrif;

I can't spot any use of this field (and hence I also can't judge whether const wants adding).

It should be introduced later in the another patch.

Quoted 13 lines
Quoted 13 lines
(quoted diff) +12 -0
+};
+
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file func() is
+ * going to work with.
+ *
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
Quoted 8 lines

Review int cf_check vcpu_imsic_init(struct vcpu *v) · line 474

Quoted 4 lines
(quoted diff) +4 -0
+ * handler.
+ */
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              void *data)

If this is supposed to be passed struct imsic_vsfile_data *, why not say so here? Be as type-safe as possible. Of course the callback function has to use void *.

At the moment, I don't see where I am using void * so I will use struct imsic_vsfile_data * instead.

Quoted 12 lines

Review int cf_check vcpu_imsic_init(struct vcpu *v) · line 483

Quoted 10 lines
(quoted diff) +9 -0
+static void cf_check imsic_vsfile_local_clear(void *data)
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */
+    if ( !idata->hgei )
+        return;

Wouldn't it make sense to avoid the call here altogether then?

I think it is better to have this if () here instead of the caller side as this function one day could be just directly (w/ imsic_call_on_cpu) and even the way how it is called now and in the case of imsic_call_on_cpu() is executed on local cpu then it will be basically just direct call of imsic_vsfile_local_clear(). So in the case I am not missing something I prefer to have a check here.

Quoted 5 lines

Review int cf_check vcpu_imsic_init(struct vcpu *v) · line 484

Quoted 2 lines
(quoted diff) +1 -0
+    old_vsiselect = csr_read(CSR_VSISELECT);

Likely obvious to you, but I can't spot why vsiselect would need saving here. If you want me to ack such code, please add at least brief comments.

I think then it will be better to put the comment once above struct imsic_vsfile_data and then just point here to that comment as basically it will be needed for all imsic_vsfile_local_* helpers.

So basically I am suggesting:

xen/arch/riscv/imsic.c +0 -0
@@ ... @@
 /*
  * Arguments of the imsic_vsfile_local_*() helpers, which are executed 

by the
* pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ *
+ * The helpers interrupt whatever vCPU context is loaded on that pCPU, which
+ * generally isn't the vCPU the interrupt file belongs to. To reach the file
+ * they retarget hstatus.VGEIN and select the file's registers through
+ * vsiselect. Both CSRs are live state of the interrupted vCPU (vsiselect is
+ * saved to struct arch_vcpu only on context switch, but the interrupted vCPU
+ * may resume guest execution without one), hence the helpers have to restore
+ * them before returning.
*/

 struct imsic_vsfile_data {
     unsigned int hgei;
     unsigned int nr_eix;
     struct imsic_mrif *mrif;
 };
@@ ... @@ static void cf_check imsic_vsfile_local_clear(void *data)
     /* We can only zero-out if we have a IMSIC VS-file */
     if ( !idata->hgei )
         return;

+ /* See the comment ahead of struct imsic_vsfile_data. */

     old_vsiselect = csr_read(CSR_VSISELECT);
     old_hstatus = csr_read(CSR_HSTATUS);
@@ ... @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
     csr_clear(CSR_HGEIE, BIT(idata->hgei, UL));

+ /* See the comment ahead of struct imsic_vsfile_data. */

     old_vsiselect = csr_read(CSR_VSISELECT);
     old_hstatus = csr_read(CSR_HSTATUS);

@@ ... @@ static void cf_check imsic_vsfile_local_update(void *data)
* stack.
*/

+ /* See the comment ahead of struct imsic_vsfile_data. */

     old_vsiselect = csr_read(CSR_VSISELECT);
     old_hstatus = csr_read(CSR_HSTATUS);

Does it look clear now?

Quoted 20 lines
Quoted 7 lines
(quoted diff) +6 -0
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);

Review int cf_check vcpu_imsic_init(struct vcpu *v) · line 500

Quoted 10 lines
(quoted diff) +10 -0
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
+#endif

In asm/imsic.h I see

Quoted 3 lines

#define IMSIC_EIPx_BITS 32

Why is the number of CSR writes different here for RV32 vs RV64?

IMSIC_EIPx_BITS is the unit the AIA spec numbers the eip<k>/eie<k> registers by. On RV32 all of eip0..eip63 exist and are 32 bits wide. On RV64 only the even-numbered ones exist, each being 64 bits wide and covering what eip<k> and eip<k+1> cover on RV32; accessing an odd-numbered one is an illegal instruction. Hence one 64-bit group of interrupt identities takes one register on RV64, but two on RV32.

I will add some small comments:

    for ( i = 0; i < idata->nr_eix; i++ )
    {
        /* On RV64 a 64-bit EIx group is the even-numbered register 
alone. */
        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
#ifdef CONFIG_RISCV_32
        /*
         * On RV32 it is split into the even-numbered (low half) and the
         * following odd-numbered (high half) register.
         */
        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
#endif
    }
Quoted 3 lines

And
if so, why would you not use the 64-bit write function, allowing the #ifdef to be omitted?

I can introduce something like:

/*
* On RV64 a 64-bit EIx group is the even-numbered register alone, whereas
* on RV32 it is split into the even-numbered (low half) and the following
* odd-numbered (high half) register.
*/
static void imsic_eix_write64(unsigned int ireg, uint64_t val)

{
    imsic_eix_write(ireg, val);
    if ( IS_ENABLED(CONFIG_RISCV_32) )
        imsic_eix_write(ireg + 1, val >> 32);
}

And then:

    for ( i = 0; i < idata->nr_eix; i++ )
    {
        imsic_eix_write64(IMSIC_EIP0 + i * 2, 0);
        imsic_eix_write64(IMSIC_EIE0 + i * 2, 0);
    }

Would it be better?

Or instead of imsic_eix_write64() I could just have a combination of imisc_vsfile_local_clear():

    imsic_eix_write(ireg, 0);
    if ( IS_ENABLED(CONFIG_RISCV_32) )
        imsic_eix_write(ireg + 1, 0);
Quoted 13 lines

Review int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 824

Quoted 9 lines
(quoted diff) +4 -0
@@ -689,6 +818,14 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
  void imsic_migrate_vcpu(struct vcpu *v)
  {
+    unsigned int new_vsfile_hgei;
+    unsigned int new_vsfile_cpu;
+    unsigned int nr_hw_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1,
+                                          BITS_PER_TYPE(uint64_t));

As written, this could also be 64. uint64_t is a fixed-width type after all. The question here is: Which variable's type do you really mean here?

The minimum number of hardware EIx groups is 1 (for the minimum 63 supported interrupt identities, i.e. DIV_ROUND_UP(63 + 1, 64) = 1), and the maximum is 32 (for 2047 identities), on both RV32 and RV64.You are right regarding BITS_PER_TYPE(uint64_t). Since an architectural EIx group always covers 64 interrupt identities regardless of XLEN, using BITS_PER_TYPE(uint64_t) is unnecessarily indirect when we mean a constant 64-bit group size.I will simplify this in v3 to use 64.

Quoted 6 lines

Review int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 826

Quoted 3 lines
(quoted diff) +2 -0
+    struct imsic_vsfile_data vsfile_data = {
+        .nr_eix = nr_hw_eix,

The local variable looks to be used only here. Is there really a need for such a local variable?

No, I will drop nr_hw_eix.

Quoted 5 lines
Quoted 5 lines
(quoted diff) +0 -0
@@ -699,5 +836,27 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
Quoted 13 lines

Review void imsic_migrate_vcpu(struct vcpu *v) · line 849

Quoted 11 lines
(quoted diff) +11 -0
+    /*
+     * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file.
+     */
+
+    /*
+     * Latch the pCPU the new interrupt file is taken from: vgein_assign()
+     * allocates it from v->processor's pool of guest interrupt files, and
+     * only that hart can access the file afterwards.
+     */
+    new_vsfile_cpu = v->processor;

Same here: Is this variable really needed?

Technically no, it could be used v->processor everywhere but just for readability (to how spec is wording migration process) I think I will prefer to have new_vsfile_cpu here. But if it doesn't make sense I can agree to drop it.

Quoted 2 lines

And what exactly is the comment
telling me?

I am re-reading it now and it looks just useless.

I think that initially I thought that for some reason v->processor could change during the end of migration and so by that I wanted to fix new vsfile cpu so all the interrupts will go there before migration functon for that vcpu will be called again and reschedule all the interrupt to new v->processor.

I think it isn't real case so the comment could be dropped.

Quoted 9 lines

Review void imsic_migrate_vcpu(struct vcpu *v) · line 855

Quoted 7 lines
(quoted diff) +6 -0
+    new_vsfile_hgei = vgein_assign(v);
+
+    /* We don't support SW interrupt files at the moment. */
+    BUG_ON(!new_vsfile_hgei);
+
+    vsfile_data.hgei = new_vsfile_hgei;

And again - any real need for the separate local variable?

Here I agree, we could have only vsfile_data.hgei.

Thanks.

~ Oleksii

#187 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

Quoted 17 lines · Oleksii Kurochko
Quoted 16 lines · Jan Beulich

Review

Quoted 12 lines · Oleksii Kurochko
(quoted diff) +12 -0
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \
+        op(ireg, v);                        \
+        break;
+
+#define imsic_switchcase_ret(ireg, op, ...) \
+    case ireg:                              \
+        return op(ireg, ##__VA_ARGS__);
+
+#define imsic_switchcase_2(F, ireg, ...)    \
+    F(ireg + 0, ##__VA_ARGS__)              \
+    F(ireg + 1, ##__VA_ARGS__)

Ah, there is an F here.

Quoted 5 lines
Quoted 3 lines

This (recurring below) shows another problem: The two F invocations look syntacticlly incorrect, due to the missing semicolon. Semicolon use wants redoing everywhere here.

I will drop then ';' from imsic_switchcase_{break,ret}.

Provided that works, i.e. you have no cae where __VA_ARGS__ expands to nothing.

Quoted 75 lines
Quoted 11 lines

Review

Quoted 9 lines
(quoted diff) +9 -0
+static void cf_check imsic_vsfile_local_clear(void *data)
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */
+    if ( !idata->hgei )
+        return;

Wouldn't it make sense to avoid the call here altogether then?

I think it is better to have this if () here instead of the caller side as this function one day could be just directly (w/ imsic_call_on_cpu) and even the way how it is called now and in the case of imsic_call_on_cpu() is executed on local cpu then it will be basically just direct call of imsic_vsfile_local_clear(). So in the case I am not missing something I prefer to have a check here.

Quoted 5 lines
Quoted 2 lines

+ old_vsiselect = csr_read(CSR_VSISELECT);

Likely obvious to you, but I can't spot why vsiselect would need saving here. If you want me to ack such code, please add at least brief comments.

I think then it will be better to put the comment once above struct imsic_vsfile_data and then just point here to that comment as basically it will be needed for all imsic_vsfile_local_* helpers.

So basically I am suggesting:

xen/arch/riscv/imsic.c +0 -0

@@ ... @@
/*
* Arguments of the imsic_vsfile_local_*() helpers, which are executed
by the
* pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ *
+ * The helpers interrupt whatever vCPU context is loaded on that pCPU, which
+ * generally isn't the vCPU the interrupt file belongs to. To reach the file
+ * they retarget hstatus.VGEIN and select the file's registers through
+ * vsiselect. Both CSRs are live state of the interrupted vCPU (vsiselect is
+ * saved to struct arch_vcpu only on context switch, but the interrupted vCPU
+ * may resume guest execution without one), hence the helpers have to restore
+ * them before returning.
*/

  struct imsic_vsfile_data {
      unsigned int hgei;
      unsigned int nr_eix;
      struct imsic_mrif *mrif;
  };
@@ ... @@ static void cf_check imsic_vsfile_local_clear(void *data)
      /* We can only zero-out if we have a IMSIC VS-file */
      if ( !idata->hgei )
          return;

+ /* See the comment ahead of struct imsic_vsfile_data. */

      old_vsiselect = csr_read(CSR_VSISELECT);
      old_hstatus = csr_read(CSR_HSTATUS);
@@ ... @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
      csr_clear(CSR_HGEIE, BIT(idata->hgei, UL));

+ /* See the comment ahead of struct imsic_vsfile_data. */

      old_vsiselect = csr_read(CSR_VSISELECT);
      old_hstatus = csr_read(CSR_HSTATUS);

@@ ... @@ static void cf_check imsic_vsfile_local_update(void *data)
* stack.
*/

Quoted 6 lines

+ /* See the comment ahead of struct imsic_vsfile_data. */

      old_vsiselect = csr_read(CSR_VSISELECT);
      old_hstatus = csr_read(CSR_HSTATUS);

Does it look clear now?

Not really, I'm afraid. A much shorter comment mentioning that imsic_..._write() alter vsiselect (if I got things right) would imo be both more direct, more clear, and could easily live at all three sites individually.

Quoted 68 lines
Quoted 19 lines
Quoted 6 lines
(quoted diff) +6 -0
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);

Review

Quoted 10 lines
(quoted diff) +10 -0
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
+#endif

In asm/imsic.h I see

Quoted 3 lines

#define IMSIC_EIPx_BITS 32

Why is the number of CSR writes different here for RV32 vs RV64?

IMSIC_EIPx_BITS is the unit the AIA spec numbers the eip<k>/eie<k> registers by. On RV32 all of eip0..eip63 exist and are 32 bits wide. On RV64 only the even-numbered ones exist, each being 64 bits wide and covering what eip<k> and eip<k+1> cover on RV32; accessing an odd-numbered one is an illegal instruction. Hence one 64-bit group of interrupt identities takes one register on RV64, but two on RV32.

I will add some small comments:

     for ( i = 0; i < idata->nr_eix; i++ )
     {
         /* On RV64 a 64-bit EIx group is the even-numbered register 
alone. */
         imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
         imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
#ifdef CONFIG_RISCV_32
         /*
          * On RV32 it is split into the even-numbered (low half) and the
          * following odd-numbered (high half) register.
          */
         imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
         imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
#endif
     }
Quoted 3 lines

And
if so, why would you not use the 64-bit write function, allowing the #ifdef to be omitted?

I can introduce something like:

/*
* On RV64 a 64-bit EIx group is the even-numbered register alone, whereas
* on RV32 it is split into the even-numbered (low half) and the following
* odd-numbered (high half) register.
*/
static void imsic_eix_write64(unsigned int ireg, uint64_t val)

{
     imsic_eix_write(ireg, val);
     if ( IS_ENABLED(CONFIG_RISCV_32) )
         imsic_eix_write(ireg + 1, val >> 32);
}

And then:

Quoted 7 lines
     for ( i = 0; i < idata->nr_eix; i++ )
     {
         imsic_eix_write64(IMSIC_EIP0 + i * 2, 0);
         imsic_eix_write64(IMSIC_EIE0 + i * 2, 0);
     }

Would it be better?

Imo yes. That said, when making the original comment, I was (apparently wrongly, as per the stuff further up) assuming these are direct CSR writes.

Jan

#188 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 163 lines · Oleksii Kurochko

Implement first steps of migration a vCPU to a different guest interrupt file procedure:
- At the old interrupt file, save to memory the values of registers eidelivery and eithreshold, and set eidelivery = 0.
- At the new interrupt file, set eidelivery = 0, and zero all implemented interrupt-pending bits (the eip array).

The following steps will be introduced in follow-up patches.

Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_assign() will be introduced later in a separate patch, for not it is only stub.

---
Changes in v2:
- New patch.
---

---
  xen/arch/riscv/aia.c             |   9 ++
  xen/arch/riscv/imsic.c           | 159 +++++++++++++++++++++++++++++++
  xen/arch/riscv/include/asm/aia.h |   4 +
  xen/include/xen/config.h         |   1 +
  4 files changed, 173 insertions(+)
xen/arch/riscv/aia.c +9 -0
index e31c9c2d24b6..75c82bcfa1b3 100644
@@ -1,8 +1,10 @@
  /* SPDX-License-Identifier: GPL-2.0-only */
 
+#include <xen/bug.h>
  #include <xen/errno.h>
  #include <xen/init.h>
  #include <xen/sections.h>
+#include <xen/sched.h>
  #include <xen/types.h>
 
  #include <asm/cpufeature.h>
@@ -21,3 +23,10 @@ void __init aia_init(void)
 
      _aia_usable = true;
  }
+
+unsigned int vgein_assign(struct vcpu *v)
+{
+    BUG_ON("unimplemented\n");
+
+    return 0;
+}
xen/arch/riscv/imsic.c +87 -0
index ad7fbe708bfd..516f0105352a 100644
@@ -26,6 +26,7 @@
  #include <xen/spinlock.h>
  #include <xen/xvmalloc.h>
 
+#include <asm/aia.h>
  #include <asm/imsic.h>
 
  #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -77,6 +78,64 @@ do {                            \
      csr_clear(CSR_SIREG, v);    \
  } while (0)
 
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_write(CSR_VSIREG, (v));     \
+} while ( 0 )
+
+/*
+ * Generic switchcase expansion pyramid.
+ * F is the per-operation leaf macro, ireg is the base register index.
+ * Optional extra args (e.g. an operation and/or a value) are forwarded to F
+ * via __VA_ARGS__.
+ *
+ * imsic_switchcase_break(ireg, op, v) - emit "case ireg: op(ireg,v); break;"
+ * imsic_switchcase_ret(ireg, op, ...) - emit "case ireg: return op(ireg[,v]);"
+ *   The variadic tail is optional so the same leaf works for both read (no v)
+ *   and swap (with v).
+ */
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \
+        op(ireg, v);                        \
+        break;
+
+#define imsic_switchcase_ret(ireg, op, ...) \
+    case ireg:                              \
+        return op(ireg, ##__VA_ARGS__);
+
+#define imsic_switchcase_2(F, ireg, ...)    \
+    F(ireg + 0, ##__VA_ARGS__)              \
+    F(ireg + 1, ##__VA_ARGS__)
+#define imsic_switchcase_4(F, ireg, ...)    \
+    imsic_switchcase_2(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_2(F, ireg + 2, ##__VA_ARGS__)
+#define imsic_switchcase_8(F, ireg, ...)    \
+    imsic_switchcase_4(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_4(F, ireg + 4, ##__VA_ARGS__)
+#define imsic_switchcase_16(F, ireg, ...)   \
+    imsic_switchcase_8(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_8(F, ireg + 8, ##__VA_ARGS__)
+#define imsic_switchcase_32(F, ireg, ...)   \
+    imsic_switchcase_16(F, ireg + 0, ##__VA_ARGS__) \
+    imsic_switchcase_16(F, ireg + 16, ##__VA_ARGS__)
+#define imsic_switchcase_64(F, ireg, ...)   \
+    imsic_switchcase_32(F, ireg + 0, ##__VA_ARGS__) \
+    imsic_switchcase_32(F, ireg + 32, ##__VA_ARGS__)
+
+static void imsic_eix_write(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_write, val)
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_write, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }
+}
+
  unsigned int vcpu_guest_file_id(const struct vcpu *v)
  {
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
@@ -389,6 +448,76 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
      return 0;
  }
 
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which are executed by the
+ * pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ */
+struct imsic_vsfile_data {
+    unsigned int hgei;
+    unsigned int nr_eix;
+    struct imsic_mrif *mrif;
+};
+
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file func() is
+ * going to work with.
+ *
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
+ * handler.
+ */
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              void *data)
+{
+    if ( cpu == smp_processor_id() )
+    {
+        unsigned long flags;

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 488

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+
+        local_irq_save(flags);
+        func(data);
+        local_irq_restore(flags);
+    }
+    else
+        on_selected_cpus(cpumask_of(cpu), func, data, 1);
+}
+
+static void cf_check imsic_vsfile_local_clear(void *data)

I think the remark from Jan to direclty pass the type instead of void could be applied here.

Quoted 36 lines
xen/arch/riscv/imsic.c +32 -0
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */
+    if ( !idata->hgei )
+        return;
+
+    old_vsiselect = csr_read(CSR_VSISELECT);
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
+#endif
+    }
+
+    csr_write(CSR_HSTATUS, old_hstatus);
+    csr_write(CSR_VSISELECT, old_vsiselect);
+}
+
  void cf_check vcpu_imsic_deinit(struct vcpu *v)
  {
      XVFREE(v->arch.vimsic_state);

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 824

Quoted 7 lines
xen/arch/riscv/imsic.c +4 -0
@@ -689,6 +818,14 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
 
  void imsic_migrate_vcpu(struct vcpu *v)
  {
+    unsigned int new_vsfile_hgei;
+    unsigned int new_vsfile_cpu;
+    unsigned int nr_hw_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1,
+                                          BITS_PER_TYPE(uint64_t));

This value appears to remain constant after initialization, since it depends directly on the hw, so it is not necessary to calculate it each time.

Quoted 64 lines
xen/arch/riscv/imsic.c +26 -0
+    struct imsic_vsfile_data vsfile_data = {
+        .nr_eix = nr_hw_eix,
+    };
+
      /*
       * The scheduler can mark a freshly created vCPU's unit as migrated and
       * invoke this before the vCPU has ever run (see the migrated branch in
@@ -699,5 +836,27 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    /*
+     * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file.
+     */
+
+    /*
+     * Latch the pCPU the new interrupt file is taken from: vgein_assign()
+     * allocates it from v->processor's pool of guest interrupt files, and
+     * only that hart can access the file afterwards.
+     */
+    new_vsfile_cpu = v->processor;
+
+    new_vsfile_hgei = vgein_assign(v);
+
+    /* We don't support SW interrupt files at the moment. */
+    BUG_ON(!new_vsfile_hgei);
+
+    vsfile_data.hgei = new_vsfile_hgei;
+
+    /* Zero-out new IMSIC VS-file */
+    imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);
+
      BUG_ON("unimplemented");
  }
xen/arch/riscv/include/asm/aia.h +4 -0
index aaa4bf91fc75..53a1efb042f8 100644
@@ -3,8 +3,12 @@
  #ifndef RISCV_AIA_H
  #define RISCV_AIA_H
 
+struct vcpu;
+
  bool aia_usable(void);
 
  void aia_init(void);
 
+unsigned int vgein_assign(struct vcpu *v);
+
  #endif /* RISCV_AIA_H */
xen/include/xen/config.h +1 -0
index dddc8e1920fe..0e29976e8203 100644
@@ -100,6 +100,7 @@
  #define BITS_PER_INT    (BITS_PER_BYTE * __SIZEOF_INT__)
  #define BITS_PER_LONG   (BITS_PER_BYTE * BYTES_PER_LONG)
  #define BITS_PER_LLONG  (BITS_PER_BYTE * __SIZEOF_LONG_LONG__)
+#define BITS_PER_TYPE(type) (sizeof(type) * BITS_PER_BYTE)
 
  /* It is assumed that sizeof(void *) == __alignof(void *) */
  #define POINTER_ALIGN   __SIZEOF_POINTER__
#189 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

Quoted 37 lines · Baptiste Le Duc
Quoted 36 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +32 -0
@@ -389,6 +448,76 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
      return 0;
  }
 
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which are executed by the
+ * pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ */
+struct imsic_vsfile_data {
+    unsigned int hgei;
+    unsigned int nr_eix;
+    struct imsic_mrif *mrif;
+};
+
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file func() is
+ * going to work with.
+ *
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
+ * handler.
+ */
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              void *data)
+{
+    if ( cpu == smp_processor_id() )
+    {
+        unsigned long flags;
+
+        local_irq_save(flags);
+        func(data);
+        local_irq_restore(flags);
Quoted 8 lines

xen/arch/riscv/imsic.c int cf_check vcpu_imsic_init(struct vcpu *v) · line 488

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+    }
+    else
+        on_selected_cpus(cpumask_of(cpu), func, data, 1);
+}
+
+static void cf_check imsic_vsfile_local_clear(void *data)

I think the remark from Jan to direclty pass the type instead of void could be applied here.

No, the function pointer is passed to ...

Quoted 17 lines
Quoted 17 lines
xen/arch/riscv/imsic.c +13 -0
@@ -699,5 +836,27 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    /*
+     * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file.
+     */
+
+    /*
+     * Latch the pCPU the new interrupt file is taken from: vgein_assign()
+     * allocates it from v->processor's pool of guest interrupt files, and
+     * only that hart can access the file afterwards.
+     */
+    new_vsfile_cpu = v->processor;
+
+    new_vsfile_hgei = vgein_assign(v);
Quoted 8 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 859

Quoted 8 lines
xen/arch/riscv/imsic.c +8 -0
+
+    /* We don't support SW interrupt files at the moment. */
+    BUG_ON(!new_vsfile_hgei);
+
+    vsfile_data.hgei = new_vsfile_hgei;
+
+    /* Zero-out new IMSIC VS-file */
+    imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);

... imsic_call_on_cpu() here, which in turn passes it to on_selected_cpus().

Jan

#190 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

In reply to Baptiste Le Duc
Quoted 172 lines · Baptiste Le Duc
Quoted 169 lines · Oleksii Kurochko

Implement first steps of migration a vCPU to a different guest interrupt file procedure:
- At the old interrupt file, save to memory the values of registers eidelivery and eithreshold, and set eidelivery = 0.
- At the new interrupt file, set eidelivery = 0, and zero all implemented interrupt-pending bits (the eip array).

The following steps will be introduced in follow-up patches.

Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_assign() will be introduced later in a separate patch, for not it is only stub.

---
Changes in v2:
  - New patch.
---
---
  xen/arch/riscv/aia.c             |   9 ++ xen/arch/riscv/imsic.c           | 159 +++++++++++++++++++++++++++++++ xen/arch/riscv/include/asm/aia.h |   4 + xen/include/xen/config.h         |   1 +

  4 files changed, 173 insertions(+)
xen/arch/riscv/aia.c +9 -0
index e31c9c2d24b6..75c82bcfa1b3 100644
@@ -1,8 +1,10 @@
   /* SPDX-License-Identifier: GPL-2.0-only */
+#include <xen/bug.h>
   #include <xen/errno.h>
   #include <xen/init.h>
   #include <xen/sections.h>
+#include <xen/sched.h>
   #include <xen/types.h>
   #include <asm/cpufeature.h>
@@ -21,3 +23,10 @@ void __init aia_init(void)
       _aia_usable = true;
   }
+
+unsigned int vgein_assign(struct vcpu *v)
+{
+    BUG_ON("unimplemented\n");
+
+    return 0;
+}
xen/arch/riscv/imsic.c +11 -0
index ad7fbe708bfd..516f0105352a 100644
@@ -26,6 +26,7 @@
   #include <xen/spinlock.h>
   #include <xen/xvmalloc.h>
+#include <asm/aia.h>
   #include <asm/imsic.h>
   #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -77,6 +78,64 @@ do {                            \
       csr_clear(CSR_SIREG, v);    \
   } while (0)
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_write(CSR_VSIREG, (v));     \
+} while ( 0 )
+
+/*
+ * Generic switchcase expansion pyramid.
+ * F is the per-operation leaf macro, ireg is the base register index.
+ * Optional extra args (e.g. an operation and/or a value) are 

forwarded to F
+ * via __VA_ARGS__.
+ *
+ * imsic_switchcase_break(ireg, op, v) - emit "case ireg: op(ireg,v); break;"
+ * imsic_switchcase_ret(ireg, op, ...) - emit "case ireg: return op(ireg[,v]);"
+ *   The variadic tail is optional so the same leaf works for both read (no v)
+ *   and swap (with v).
+ */

xen/arch/riscv/imsic.c +41 -0
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \
+        op(ireg, v);                        \
+        break;
+
+#define imsic_switchcase_ret(ireg, op, ...) \
+    case ireg:                              \
+        return op(ireg, ##__VA_ARGS__);
+
+#define imsic_switchcase_2(F, ireg, ...)    \
+    F(ireg + 0, ##__VA_ARGS__)              \
+    F(ireg + 1, ##__VA_ARGS__)
+#define imsic_switchcase_4(F, ireg, ...)    \
+    imsic_switchcase_2(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_2(F, ireg + 2, ##__VA_ARGS__)
+#define imsic_switchcase_8(F, ireg, ...)    \
+    imsic_switchcase_4(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_4(F, ireg + 4, ##__VA_ARGS__)
+#define imsic_switchcase_16(F, ireg, ...)   \
+    imsic_switchcase_8(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_8(F, ireg + 8, ##__VA_ARGS__)
+#define imsic_switchcase_32(F, ireg, ...)   \
+    imsic_switchcase_16(F, ireg + 0, ##__VA_ARGS__) \
+    imsic_switchcase_16(F, ireg + 16, ##__VA_ARGS__)
+#define imsic_switchcase_64(F, ireg, ...)   \
+    imsic_switchcase_32(F, ireg + 0, ##__VA_ARGS__) \
+    imsic_switchcase_32(F, ireg + 32, ##__VA_ARGS__)
+
+static void imsic_eix_write(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_write, val)
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_write, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }
+}
+

  unsigned int vcpu_guest_file_id(const struct vcpu *v) {
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);

xen/arch/riscv/imsic.c +2 -0
@@ -389,6 +448,76 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
       return 0;
   }
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which are 

executed by the
+ * pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ */

xen/arch/riscv/imsic.c +8 -0
+struct imsic_vsfile_data {
+    unsigned int hgei;
+    unsigned int nr_eix;
+    struct imsic_mrif *mrif;
+};
+
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file 

func() is
+ * going to work with.
+ *
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
+ * handler.
+ */

xen/arch/riscv/imsic.c +10 -0
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              void *data)
+{
+    if ( cpu == smp_processor_id() )
+    {
+        unsigned long flags;
+
+        local_irq_save(flags);
+        func(data);
+        local_irq_restore(flags);
Quoted 8 lines

xen/arch/riscv/imsic.c

Quoted 6 lines

+    }
+    else
+        on_selected_cpus(cpumask_of(cpu), func, data, 1);

xen/arch/riscv/imsic.c +3 -0
+}
+
+static void cf_check imsic_vsfile_local_clear(void *data)

I think the remark from Jan to direclty pass the type instead of void could be applied here.

I think it can't because of how function pointer is passed to on_selected_cpus() through imsic_call_on_cpu().

Quoted 37 lines
Quoted 37 lines
xen/arch/riscv/imsic.c +32 -0
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */
+    if ( !idata->hgei )
+        return;
+
+    old_vsiselect = csr_read(CSR_VSISELECT);
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
+#endif
+    }
+
+    csr_write(CSR_HSTATUS, old_hstatus);
+    csr_write(CSR_VSISELECT, old_vsiselect);
+}
+

  void cf_check vcpu_imsic_deinit(struct vcpu *v)
  {
      XVFREE(v->arch.vimsic_state);

xen/arch/riscv/imsic.c +0 -0
@@ -689,6 +818,14 @@ int __init vimsic_make_domu_dt_node(struct 
 kernel_info *kinfo,
Quoted 8 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct · line 824

Quoted 6 lines
xen/arch/riscv/imsic.c +4 -0
   void imsic_migrate_vcpu(struct vcpu *v)
   {
+    unsigned int new_vsfile_hgei;
+    unsigned int new_vsfile_cpu;
+    unsigned int nr_hw_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1,
+                                          BITS_PER_TYPE(uint64_t));

This value appears to remain constant after initialization, since it depends directly on the hw, so it is not necessary to calculate it each time.

I will add then:

xen/arch/riscv/include/asm/imsic.h +0 -0
@@ struct imsic_config {
     /* Number off interrupt identities */
     unsigned int nr_ids;

+ /*

+     * Number of 64-bit EIx groups needed to cover all the interrupt
+     * identities, which are 0 (never valid, but it still occupies a bit) up
+     * to and including nr_ids.
+     */

+ unsigned int nr_eix;
+

and init it once in imsic_parse_node().

Thanks.

~ Oleksii

#191 lore raw

Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file

Quoted 249 lines · Oleksii Kurochko
Quoted 177 lines · Baptiste Le Duc
Quoted 174 lines · Oleksii Kurochko

Implement first steps of migration a vCPU to a different guest interrupt file
procedure:
- At the old interrupt file, save to memory the values of registers eidelivery and eithreshold, and set eidelivery = 0.
- At the new interrupt file, set eidelivery = 0, and zero all implemented interrupt-pending bits (the eip array).

The following steps will be introduced in follow-up patches.

Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard
against silent incorrect behaviour or unexpected panics in guest VMs until
the function is fully implemented.

vgein_assign() will be introduced later in a separate patch, for not it is
only stub.

---
Changes in v2:
  - New patch.
---
---
  xen/arch/riscv/aia.c             |   9 ++ xen/arch/riscv/imsic.c           | 159 +++++++++++++++++++++++++++++++ xen/arch/riscv/include/asm/aia.h |   4 + xen/include/xen/config.h         |   1 +

  4 files changed, 173 insertions(+)
xen/arch/riscv/aia.c +9 -0
index e31c9c2d24b6..75c82bcfa1b3 100644
@@ -1,8 +1,10 @@
   /* SPDX-License-Identifier: GPL-2.0-only */
+#include <xen/bug.h>
   #include <xen/errno.h>
   #include <xen/init.h>
   #include <xen/sections.h>
+#include <xen/sched.h>
   #include <xen/types.h>
   #include <asm/cpufeature.h>
@@ -21,3 +23,10 @@ void __init aia_init(void)
       _aia_usable = true;
   }
+
+unsigned int vgein_assign(struct vcpu *v)
+{
+    BUG_ON("unimplemented\n");
+
+    return 0;
+}
xen/arch/riscv/imsic.c +11 -0
index ad7fbe708bfd..516f0105352a 100644
@@ -26,6 +26,7 @@
   #include <xen/spinlock.h>
   #include <xen/xvmalloc.h>
+#include <asm/aia.h>
   #include <asm/imsic.h>
   #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * 
 IMSIC_MMIO_PAGE_SZ)
@@ -77,6 +78,64 @@ do {                            \
       csr_clear(CSR_SIREG, v);    \
   } while (0)
+#define imsic_vs_csr_write(c, v)    \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_write(CSR_VSIREG, (v));     \
+} while ( 0 )
+
+/*
+ * Generic switchcase expansion pyramid.
+ * F is the per-operation leaf macro, ireg is the base register index.
+ * Optional extra args (e.g. an operation and/or a value) are 

forwarded to F
+ * via __VA_ARGS__.
+ *
+ * imsic_switchcase_break(ireg, op, v) - emit "case ireg: op(ireg,v); break;"
+ * imsic_switchcase_ret(ireg, op, ...) - emit "case ireg: return op(ireg[,v]);"
+ *   The variadic tail is optional so the same leaf works for both read (no v)
+ *   and swap (with v).
+ */

xen/arch/riscv/imsic.c +41 -0
+#define imsic_switchcase_break(ireg, op, v) \
+    case ireg:                              \
+        op(ireg, v);                        \
+        break;
+
+#define imsic_switchcase_ret(ireg, op, ...) \
+    case ireg:                              \
+        return op(ireg, ##__VA_ARGS__);
+
+#define imsic_switchcase_2(F, ireg, ...)    \
+    F(ireg + 0, ##__VA_ARGS__)              \
+    F(ireg + 1, ##__VA_ARGS__)
+#define imsic_switchcase_4(F, ireg, ...)    \
+    imsic_switchcase_2(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_2(F, ireg + 2, ##__VA_ARGS__)
+#define imsic_switchcase_8(F, ireg, ...)    \
+    imsic_switchcase_4(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_4(F, ireg + 4, ##__VA_ARGS__)
+#define imsic_switchcase_16(F, ireg, ...)   \
+    imsic_switchcase_8(F, ireg + 0, ##__VA_ARGS__)  \
+    imsic_switchcase_8(F, ireg + 8, ##__VA_ARGS__)
+#define imsic_switchcase_32(F, ireg, ...)   \
+    imsic_switchcase_16(F, ireg + 0, ##__VA_ARGS__) \
+    imsic_switchcase_16(F, ireg + 16, ##__VA_ARGS__)
+#define imsic_switchcase_64(F, ireg, ...)   \
+    imsic_switchcase_32(F, ireg + 0, ##__VA_ARGS__) \
+    imsic_switchcase_32(F, ireg + 32, ##__VA_ARGS__)
+
+static void imsic_eix_write(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_write, val)
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_write, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }
+}
+

  unsigned int vcpu_guest_file_id(const struct vcpu *v) {
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);

xen/arch/riscv/imsic.c +2 -0
@@ -389,6 +448,76 @@ int cf_check vcpu_imsic_init(struct vcpu *v)
       return 0;
   }
+/*
+ * Arguments of the imsic_vsfile_local_*() helpers, which are 

executed by the
+ * pCPU owning the interrupt file, thereby through imsic_call_on_cpu().
+ */

xen/arch/riscv/imsic.c +8 -0
+struct imsic_vsfile_data {
+    unsigned int hgei;
+    unsigned int nr_eix;
+    struct imsic_mrif *mrif;
+};
+
+/*
+ * Execute func() on the pCPU which owns the IMSIC interrupt file 

func() is
+ * going to work with.
+ *
+ * An IMSIC VS-file is reachable only through hstatus.VGEIN of the hart the
+ * file belongs to, and a guest interrupt file index is meaningless on any
+ * other hart, so such work always has to be done by that very hart.
+ *
+ * The local case runs with IRQs disabled to provide func() with the same
+ * environment it is given when it is called from the function call IPI
+ * handler.
+ */

xen/arch/riscv/imsic.c +10 -0
+static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
+                              void *data)
+{
+    if ( cpu == smp_processor_id() )
+    {
+        unsigned long flags;
+
+        local_irq_save(flags);
+        func(data);
+        local_irq_restore(flags);
Quoted 8 lines

xen/arch/riscv/imsic.c

Quoted 6 lines

+    }
+    else
+        on_selected_cpus(cpumask_of(cpu), func, data, 1);

xen/arch/riscv/imsic.c +3 -0
+}
+
+static void cf_check imsic_vsfile_local_clear(void *data)

I think the remark from Jan to direclty pass the type instead of void could be applied here.

I think it can't because of how function pointer is passed to on_selected_cpus() through imsic_call_on_cpu().

Quoted 38 lines
Quoted 38 lines
xen/arch/riscv/imsic.c +32 -0
+{
+    unsigned int i;
+    const struct imsic_vsfile_data *idata = data;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only zero-out if we have a IMSIC VS-file */
+    if ( !idata->hgei )
+        return;
+
+    old_vsiselect = csr_read(CSR_VSISELECT);
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, 0);
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, 0);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        imsic_eix_write(IMSIC_EIP0 + i * 2, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2, 0);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_write(IMSIC_EIP0 + i * 2 + 1, 0);
+        imsic_eix_write(IMSIC_EIE0 + i * 2 + 1, 0);
+#endif
+    }
+
+    csr_write(CSR_HSTATUS, old_hstatus);
+    csr_write(CSR_VSISELECT, old_vsiselect);
+}
+

  void cf_check vcpu_imsic_deinit(struct vcpu *v)
  {
      XVFREE(v->arch.vimsic_state);

xen/arch/riscv/imsic.c +0 -0
@@ -689,6 +818,14 @@ int __init vimsic_make_domu_dt_node(struct 
 kernel_info *kinfo,
   void imsic_migrate_vcpu(struct vcpu *v)
Quoted 8 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct · line 824

Quoted 5 lines
xen/arch/riscv/imsic.c +4 -0
   {
+    unsigned int new_vsfile_hgei;
+    unsigned int new_vsfile_cpu;
+    unsigned int nr_hw_eix = DIV_ROUND_UP(imsic_cfg.nr_ids + 1,
+                                          BITS_PER_TYPE(uint64_t));

This value appears to remain constant after initialization, since it depends directly on the hw,
so it is not necessary to calculate it each time.

I will add then:

xen/arch/riscv/include/asm/imsic.h +0 -0
@@ struct imsic_config {
      /* Number off interrupt identities */
      unsigned int nr_ids;
xen/arch/riscv/include/asm/imsic.h +3 -0
+    /*
+     * Number of 64-bit EIx groups needed to cover all the interrupt
+     * identities, which are 0 (never valid, but it still occupies a 

bit) up

xen/arch/riscv/include/asm/imsic.h

Quoted 4 lines
xen/arch/riscv/include/asm/imsic.h +4 -0
+     * to and including nr_ids.
+     */
+    unsigned int nr_eix;
+

Thanks! Maybe use registers instead of groups wording.

Quoted 5 lines

and init it once in imsic_parse_node().

Thanks.

~ Oleksii

#192 lore raw

PATCH v2 31/39 xen/riscv: implement APLIC-hart sync barrier for vCPU migration

In reply to Oleksii Kurochko

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/aplic.c             | 26 ++++++++++++++++++++++++++
 xen/arch/riscv/imsic.c             | 12 ++++++++++++
 xen/arch/riscv/include/asm/aplic.h |  3 +++
 xen/arch/riscv/include/asm/imsic.h |  8 ++++++++
 4 files changed, 49 insertions(+)
xen/arch/riscv/aplic.c +26 -0
index 0af13f28e467..cb11d6aeaaa9 100644
@@ -27,7 +27,9 @@
 #include <asm/imsic.h>
 #include <asm/intc.h>
 #include <asm/io.h>
+#include <asm/processor.h>
 #include <asm/riscv_encoding.h>
+#include <asm/smp.h>
 
 static struct aplic_priv aplic = {
     .lock = SPIN_LOCK_UNLOCKED,
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, uint32_t value)
     spin_unlock_irqrestore(&aplic.lock, flags);
 }
 
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this step.
+ */
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);
+
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    writel(val, &aplic.regs->genmsi);
+
+    while ( readl(&aplic.regs->genmsi) & APLIC_GENMSI_BUSY )
+        cpu_relax();
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+
 static void __init aplic_init_hw_interrupts(void)
 {
     unsigned int i;
xen/arch/riscv/imsic.c +12 -0
index 516f0105352a..5de45949610d 100644
@@ -195,6 +195,15 @@ void imsic_irq_enable(unsigned int irq)
      */
     ASSERT(!local_irq_is_enabled());
 
+    if ( irq == imsic_cfg.sync_id )
+    {
+        printk(XENLOG_WARNING
+               "irq%u is reserved for APLIC sync so shouldn't be set by %s\n",
+               irq, __func__);
+
+        return;
+    }
+
     spin_lock(&imsic_cfg.lock);
     /*
      * There is no irq - 1 here (look at aplic_set_irq_type()) because:
@@ -377,6 +386,9 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
         return -ENOENT;
     }
 
+    /* Reserve last identity for APLIC-to-hart synchronization */
+    imsic_cfg.sync_id = imsic_cfg.nr_ids;
+
     /* Compute base address */
     *nr_mmios = 0;
     rc = dt_device_get_address(node, *nr_mmios, &base_addr, NULL);
xen/arch/riscv/include/asm/aplic.h +3 -0
index 8564f5954b6b..e4f4dfd241cc 100644
@@ -88,6 +88,7 @@
 #define APLIC_SETIPNUM_LE               0x2000
 
 #define APLIC_GENMSI                    0x3000
+#define APLIC_GENMSI_BUSY               BIT(12, U)
 
 #define APLIC_TARGET_BASE               0x3004
 #define APLIC_TARGET_LAST               0x3ffc
@@ -178,4 +179,6 @@ void aplic_reconfigure_target(const struct vcpu *v,
                               unsigned int old_guest_file_id,
                               unsigned int old_cpu);
 
+void aplic_genmsi_barrier(void);
+
 #endif /* ASM_RISCV_APLIC_H */
xen/arch/riscv/include/asm/imsic.h +8 -0
index 57d8c729ac0d..6ea2e4b8ca12 100644
@@ -68,6 +68,14 @@ struct imsic_config {
     /* Number off interrupt identities */
     unsigned int nr_ids;
 
+    /*
+     * Interrupt identity reserved exclusively for APLIC-to-hart
+     * synchronization.
+     *
+     * Must not be allocated to any interrupt source.
+     */
+    unsigned int sync_id;
+
     /* MSI */
     const struct imsic_msi *msi;
 
Signature · 1 line
2.55.0
#193 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

Quoted 8 lines · Oleksii Kurochko

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

Hmm. As indicated, I'm learning RISC-V as I'm reviewing patches. This paragraph, if left as is, would make sure I simply can't ack the patch. I just don't understand what is being talked about. I can guess parts, but for example I don't know what "genmsi" is.

Quoted 7 lines
xen/arch/riscv/aplic.c +3 -0
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, uint32_t value)
     spin_unlock_irqrestore(&aplic.lock, flags);
 }
 
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this step.

xen/arch/riscv/aplic.c void aplic_hw_write_reg(unsigned int offset, uint32_t value) · line 222

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+ */
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);

Along the lines of a question on an earlier patch: What if this ANDing actually chops off bits?

Jan

#194 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

Quoted 10 lines · Jan Beulich
Quoted 8 lines · Oleksii Kurochko

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

Quoted 4 lines

Hmm. As indicated, I'm learning RISC-V as I'm reviewing patches. This paragraph, if left as is, would make sure I simply can't ack the patch. I just don't understand what is being talked about. I can guess parts, but for example I don't know what "genmsi" is.

I will reword then commit message in the following way:

```
When a vCPU is moved to a different guest interrupt file, MSIs that the
APLIC has already sent towards the old file may still be in flight. They
must land before the old file's state is saved and the switch is done,
otherwise they would be lost.

To wait for them, use the APLIC's genmsi register. Writing it makes the
APLIC itself send an MSI (an "extempore" MSI) with a given interrupt
identity to a given hart. genmsi can only target the hart's supervisor-
level interrupt file, not a guest one, but the AIA spec guarantees that
all MSIs previously sent by the same APLIC to the same hart become
visible at the hart's IMSIC before the extempore MSI does. So once the
extempore MSI has been delivered, no older MSI from this APLIC to the
hart can still be in flight, whichever interrupt file it targets.

The last interrupt identity (nr_ids) is reserved for this purpose.
```
Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/aplic.c +0 -0
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, uint32_t value)
      spin_unlock_irqrestore(&aplic.lock, flags);
  }
 
Quoted 16 lines

xen/arch/riscv/aplic.c void aplic_hw_write_reg(unsigned int offset, uint32_t value) · line 222

Quoted 13 lines
xen/arch/riscv/aplic.c +13 -0
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this step.
+ */
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);

Along the lines of a question on an earlier patch: What if this ANDing actually chops off bits?

I will do then the same as I did in aplic_set_irq_affinity() (i mentioned that in the one of the replies connected to this function in this patch series):

    /*
     * sync_id is nr_ids, which imsic_parse_node() limits to IMSIC_MAX_ID,
     * so it always fits into the EIID field.
     */
    BUILD_BUG_ON(IMSIC_MAX_ID > MASK_EXTR(~0U, APLIC_TARGET_EIID));
    ASSERT(imsic->sync_id <= IMSIC_MAX_ID);

    val = MASK_INSR(aplic_hart_index(cpu), APLIC_TARGET_HART_IDX) |
          imsic->sync_id;

Thanks.

~ Oleksii

#195 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

Quoted 17 lines · Oleksii Kurochko
Quoted 6 lines · Jan Beulich

On 27.08.2026 17:21, Oleksii Kurochko wrote:

Hmm. As indicated, I'm learning RISC-V as I'm reviewing patches. This paragraph, if left as is, would make sure I simply can't ack the patch. I just don't understand what is being talked about. I can guess parts, but for example I don't know what "genmsi" is.

I will reword then commit message in the following way:

```
When a vCPU is moved to a different guest interrupt file, MSIs that the APLIC has already sent towards the old file may still be in flight. They must land before the old file's state is saved and the switch is done, otherwise they would be lost.

Quoted 3 lines

To wait for them, use the APLIC's genmsi register. Writing it makes the APLIC itself send an MSI (an "extempore" MSI) with a given interrupt identity to a given hart. genmsi can only target the hart's supervisor-

Nit: supervisor = hypervisor in our pov

Quoted 29 lines

level interrupt file, not a guest one, but the AIA spec guarantees that all MSIs previously sent by the same APLIC to the same hart become visible at the hart's IMSIC before the extempore MSI does. So once the extempore MSI has been delivered, no older MSI from this APLIC to the hart can still be in flight, whichever interrupt file it targets.

The last interrupt identity (nr_ids) is reserved for this purpose. ```

Quoted 2 lines

Along the lines of a question on an earlier patch: What if this ANDing actually chops off bits?

I will do then the same as I did in aplic_set_irq_affinity() (i mentioned that in the one of the replies connected to this function in this patch series):

     /*
      * sync_id is nr_ids, which imsic_parse_node() limits to IMSIC_MAX_ID,
      * so it always fits into the EIID field.
      */
     BUILD_BUG_ON(IMSIC_MAX_ID > MASK_EXTR(~0U, APLIC_TARGET_EIID));
     ASSERT(imsic->sync_id <= IMSIC_MAX_ID);

     val = MASK_INSR(aplic_hart_index(cpu), APLIC_TARGET_HART_IDX) |
           imsic->sync_id;

Thanks.

~ Oleksii

#196 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

In reply to Oleksii Kurochko
Quoted 47 lines

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

xen/arch/riscv/aplic.c +16 -0
index 0af13f28e4..cb11d6aeaa 100644
@@ -27,7 +27,9 @@
 #include <asm/imsic.h>
 #include <asm/intc.h>
 #include <asm/io.h>
+#include <asm/processor.h>
 #include <asm/riscv_encoding.h>
+#include <asm/smp.h>
 
 static struct aplic_priv aplic = {
     .lock = SPIN_LOCK_UNLOCKED,
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, uint32_t value)
     spin_unlock_irqrestore(&aplic.lock, flags);
 }
 
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this step.
+ */
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);
 
 
+

xen/arch/riscv/aplic.c void aplic_hw_write_reg(unsigned int offset, uint32_t value) · line 235

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    writel(val, &aplic.regs->genmsi);
+
+    while ( readl(&aplic.regs->genmsi) & APLIC_GENMSI_BUSY )
+        cpu_relax();
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+

According to AIA spec §4.9.3 (Synchronizing interactions between a hart and the APLIC), the sequence needs 6 steps; this implements only steps 2-5:

- Step 1: clear the pending bit for sync_id at the hart's IMSIC before writing genmsi.
- Step 6: after releasing the lock, poll the pending bit for sync_id at the hart's IMSIC until it's set.

Step 4 (Busy clear) only means the APLIC has accepted/sent the MSI, not that it has arrived at the hart (the spec notes an unspecified travel delay). Without step 6, aplic_genmsi_barrier() returns before the MSI (and thus prior MSIs) actually reach the hart, so it doesn't achieve the barrier it's meant to provide.

Signature · 1 line
Baptiste Le Duc <[email protected]>
#197 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

Quoted 59 lines · Baptiste Le Duc
Quoted 47 lines

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

xen/arch/riscv/aplic.c +16 -0
index 0af13f28e4..cb11d6aeaa 100644
@@ -27,7 +27,9 @@
  #include <asm/imsic.h>
  #include <asm/intc.h>
  #include <asm/io.h>
+#include <asm/processor.h>
  #include <asm/riscv_encoding.h>
+#include <asm/smp.h>
 
  static struct aplic_priv aplic = {
      .lock = SPIN_LOCK_UNLOCKED,
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, uint32_t value)
      spin_unlock_irqrestore(&aplic.lock, flags);
  }
 
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this step.
+ */
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);
 
 
+

xen/arch/riscv/aplic.c void aplic_hw_write_reg(unsigned int offset, uint32_t value) · line 235

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    writel(val, &aplic.regs->genmsi);
+
+    while ( readl(&aplic.regs->genmsi) & APLIC_GENMSI_BUSY )
+        cpu_relax();
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+

According to AIA spec §4.9.3 (Synchronizing interactions between a hart and the APLIC), the sequence needs 6 steps; this implements only steps 2-5:

Quoted 7 lines

- Step 1: clear the pending bit for sync_id at the hart's IMSIC before writing genmsi.
- Step 6: after releasing the lock, poll the pending bit for sync_id at the hart's IMSIC until it's set.

Step 4 (Busy clear) only means the APLIC has accepted/sent the MSI, not that it has arrived at the hart (the spec notes an unspecified travel delay). Without step 6, aplic_genmsi_barrier() returns before the MSI (and thus prior MSIs) actually reach the hart, so it doesn't achieve the barrier it's meant to provide.

It is really missed but it exists in riscv-next-upstream branch (https://gitlab.com/xen-project/people/olkur/xen/-/blob/riscv-next-upstreaming/xen/arch/riscv/imsic.c#L723).

I will re-check why it is missed here.

Thanks for noticing that.

~ Oleksii

#198 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

Quoted 67 lines · Oleksii Kurochko
Quoted 64 lines · Baptiste Le Duc
Quoted 47 lines

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

xen/arch/riscv/aplic.c +5 -0
index 0af13f28e4..cb11d6aeaa 100644
@@ -27,7 +27,9 @@
   #include <asm/imsic.h>
   #include <asm/intc.h>
   #include <asm/io.h>
+#include <asm/processor.h>
   #include <asm/riscv_encoding.h>
+#include <asm/smp.h>
   static struct aplic_priv aplic = {
       .lock = SPIN_LOCK_UNLOCKED,
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, 
 uint32_t value)
       spin_unlock_irqrestore(&aplic.lock, flags);
   }
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this 

step.
+ */

xen/arch/riscv/aplic.c +10 -0
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);
 
 
+

xen/arch/riscv/aplic.c void aplic_hw_write_reg(unsigned int offset, uint32_t value) · line 233

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    writel(val, &aplic.regs->genmsi);
+
+    while ( readl(&aplic.regs->genmsi) & APLIC_GENMSI_BUSY )
+        cpu_relax();
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+

According to AIA spec §4.9.3 (Synchronizing interactions between a hart and the APLIC), the sequence needs 6 steps; this implements only steps 2-5:

- Step 1: clear the pending bit for sync_id at the hart's IMSIC before writing genmsi.
- Step 6: after releasing the lock, poll the pending bit for sync_id at the hart's IMSIC until it's set.

Quoted 8 lines
Quoted 4 lines

Step 4 (Busy clear) only means the APLIC has accepted/sent the MSI, not that it has arrived at the hart (the spec notes an unspecified travel delay). Without step 6, aplic_genmsi_barrier() returns before the MSI (and thus prior MSIs) actually reach the hart, so it doesn't achieve the barrier it's meant to provide.

It is really missed but it exists in riscv-next-upstream branch (https://gitlab.com/xen-project/people/olkur/xen/-/blob/riscv-next- upstreaming/xen/arch/riscv/imsic.c#L723).

I will re-check why it is missed here.

Step 1 and step 6 are not missing, they are just not part of
aplic_genmsi_barrier() itself. They are done by its caller, which is added in "xen/riscv: remap interrupts to new IMSIC VS-file":

    static void cf_check imsic_aplic_sync(void *unused)
    {
        imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);

        aplic_genmsi_barrier();

        while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
            cpu_relax();
    }

I did consider doing all six steps inside aplic_genmsi_barrier(), but that would make aplic.c reach into IMSIC internals (the local EIx CSR accessors, which are private to imsic.c), and I would rather not add that dependency. Keeping the APLIC half (write genmsi, wait for Busy to clear) in aplic.c and the IMSIC half (clear the pending bit of sync_id before, poll it until set afterwards) in imsic.c keeps the layering clean.

You are right, though, that nothing in this patch says so, and that the
helper on its own is not the full barrier its name suggests. I will spell the split out in the commit message and in the comment above the function.

Probably it will be better to introduce function imsic_aplic_sync() as a part of this patch.

~ Oleksii

#199 lore raw

Re: [PATCH v2 31/39] xen/riscv: implement APLIC-hart sync barrier for vCPU migration

Quoted 108 lines · Oleksii Kurochko
Quoted 78 lines · Oleksii Kurochko
Quoted 66 lines · Baptiste Le Duc
Quoted 47 lines

During migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.

genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.

xen/arch/riscv/aplic.c +5 -0
index 0af13f28e4..cb11d6aeaa 100644
@@ -27,7 +27,9 @@
   #include <asm/imsic.h>
   #include <asm/intc.h>
   #include <asm/io.h>
+#include <asm/processor.h>
   #include <asm/riscv_encoding.h>
+#include <asm/smp.h>
   static struct aplic_priv aplic = {
       .lock = SPIN_LOCK_UNLOCKED,
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, 
 uint32_t value)
       spin_unlock_irqrestore(&aplic.lock, flags);
   }
+/*
+ * As needed, synchronize with all IOMMUs and APLICs to ensure that no
+ * straggler MSIs will arrive at the old interrupt file after this 

step.
+ */

xen/arch/riscv/aplic.c +10 -0
+void aplic_genmsi_barrier(void)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    unsigned int cpu = smp_processor_id();
+    unsigned long flags;
+    uint32_t val;
+
+    val = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+          (imsic->sync_id & APLIC_TARGET_EIID);
 
 
+

xen/arch/riscv/aplic.c void aplic_hw_write_reg(unsigned int offset, uint32_t value) · line 233

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+    spin_lock_irqsave(&aplic.lock, flags);
+
+    writel(val, &aplic.regs->genmsi);
+
+    while ( readl(&aplic.regs->genmsi) & APLIC_GENMSI_BUSY )
+        cpu_relax();
+
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+

According to AIA spec §4.9.3 (Synchronizing interactions between a hart and the APLIC), the sequence needs 6 steps; this implements only steps 2-5:

- Step 1: clear the pending bit for sync_id at the hart's IMSIC before writing genmsi.
- Step 6: after releasing the lock, poll the pending bit for sync_id at the hart's IMSIC until it's set.

Quoted 8 lines

Step 4 (Busy clear) only means the APLIC has accepted/sent the MSI, not that it has arrived at the hart (the spec notes an unspecified travel delay).
Without step 6, aplic_genmsi_barrier() returns before the MSI (and thus prior MSIs) actually reach the hart, so it doesn't achieve the barrier it's meant to
provide.

Quoted 5 lines

It is really missed but it exists in riscv-next-upstream branch
(https://gitlab.com/xen-project/people/olkur/xen/-/blob/riscv-next-
upstreaming/xen/arch/riscv/imsic.c#L723).

I will re-check why it is missed here.

Step 1 and step 6 are not missing, they are just not part of aplic_genmsi_barrier() itself. They are done by its caller, which is added in "xen/riscv: remap interrupts to new IMSIC VS-file":

     static void cf_check imsic_aplic_sync(void *unused)
     {
         imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);

         aplic_genmsi_barrier();

         while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
             cpu_relax();
     }

I did consider doing all six steps inside aplic_genmsi_barrier(), but that would make aplic.c reach into IMSIC internals (the local EIx CSR accessors, which are private to imsic.c), and I would rather not add that dependency. Keeping the APLIC half (write genmsi, wait for Busy to clear) in aplic.c and the IMSIC half (clear the pending bit of sync_id before, poll it until set afterwards) in imsic.c keeps the layering clean.

Quoted 7 lines

You are right, though, that nothing in this patch says so, and that the helper on its own is not the full barrier its name suggests. I will spell the split out in the commit message and in the comment above the function.

Probably it will be better to introduce function imsic_aplic_sync() as a part of this patch.

Yes it would make sense as function imsic_aplic_sync() is introduced in next patch so reviewer couldn't know the existence of it when reading this patch. Thanks for that!

Quoted 5 lines

~ Oleksii

#200 lore raw

PATCH v2 32/39 xen/riscv: remap interrupts to new IMSIC VS-file

In reply to Oleksii Kurochko

After new IMSIC VS-file is zeroed-out it is necessary to do G-stage remaping fo new IMSIC VS-file. Also, if any interrupts at an APLIC are forwarded by MSIs to the old interrupt file, reconfigure the APLIC to send them to the new interrupt file.

Generally it is needed also to modify the relevant translation tables at all IOMMUs so that MSIs for this virtual interrupt file are now sent to the new physical interrupt file but it is skipped for now there is no IOMMU support for RISC-V.

Synchronize with APLIC to ensure that no straggler MSIs will arrive at the old interrupt file by using of aplic_genmsi_barrier().

Technically there is no need for read_lock_irqsave() and read_unlock_irqrestore() around reading of ->guest_file_id, as a write cannot happen in parallel: any update to ->guest_file_id for a vCPU will happen either in imsic_migrate_vcpu() itself or before the vCPU first gains control (in continue_new_vcpu()), so there is no concurrent access to it in imsic_migrate_vcpu(). The lock is added here for potential future cases.

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

imsic_map_guest_file() and imsic_update_state() are stubs for now and will be introduced later in a separate patch.

---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/imsic.c             | 103 +++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/imsic.h |   3 +
 2 files changed, 106 insertions(+)
xen/arch/riscv/imsic.c +103 -0
index 5de45949610d..5e9f6995e443 100644
@@ -27,6 +27,7 @@
 #include <xen/xvmalloc.h>
 
 #include <asm/aia.h>
+#include <asm/aplic.h>
 #include <asm/imsic.h>
 
 #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
 #define IMSIC_DISABLE_EITHRESHOLD   1
 #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)           \
+({                                  \
+    csr_write(CSR_SISELECT, (c));   \
+    csr_read(CSR_SIREG);            \
+})
+
 #define imsic_csr_write(c, v)   \
 do {                            \
     csr_write(CSR_SISELECT, c); \
@@ -141,6 +148,11 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v)
     return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
 }
 
+void imsic_update_state(struct vcpu *v, unsigned int guest_file_id)
+{
+    BUG_ON("unimplemented\n");
+}
+
 void __init imsic_ids_local_delivery(bool enable)
 {
     if ( enable )
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
     spin_unlock(&imsic_cfg.lock);
 }
 
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);
+
+    return !!(imsic_csr_read(isel) & bit);
+}
+
 /* Callers aren't intended to changed imsic_cfg so return const. */
 const struct imsic_config *imsic_get_config(void)
 {
@@ -436,6 +457,11 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
     /* Nothing to do */
 }
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
+{
+    return -EOPNOTSUPP;
+}
+
 int cf_check vcpu_imsic_init(struct vcpu *v)
 {
     struct vimsic_state *imsic_state;
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
         on_selected_cpus(cpumask_of(cpu), func, data, 1);
 }
 
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *data)
+{
+    imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);
+
+    aplic_genmsi_barrier();
+
+    while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
+        cpu_relax();
+}
+
 static void cf_check imsic_vsfile_local_clear(void *data)
 {
     unsigned int i;
@@ -837,6 +884,10 @@ void imsic_migrate_vcpu(struct vcpu *v)
     struct imsic_vsfile_data vsfile_data = {
         .nr_eix = nr_hw_eix,
     };
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+    unsigned int old_vsfile_id;
+    unsigned int old_vsfile_cpu;
 
     /*
      * The scheduler can mark a freshly created vCPU's unit as migrated and
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
     if ( v->arch.last_cpu == NR_CPUS )
         return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
     /*
      * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
      * VS-file.
      */
 
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
     /* Zero-out new IMSIC VS-file */
     imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);
 
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+
+    /*
+     * TODO: Modify the relevant translation tables at all IOMMUs so that MSIs
+     *       for this virtual interrupt file are now sent to the new physical
+     *       interrupt file.
+     */
+    if ( iommu_enabled )
+        printk_once("IMSIC: IOMMU MSI retargeting is not implemented\n");
+
+    /*
+     * If any interrupts at an APLIC are forwarded by MSIs to the old interrupt
+     * file, reconfigure the APLIC to send them to the new interrupt file.
+     */
+    aplic_reconfigure_target(v, old_vsfile_id, old_vsfile_cpu);
+
+    /*
+     * Synchronizing interactions between a hart and the APLIC.
+     *
+     * The MSIs to be flushed are the ones still on their way to the old
+     * interrupt file, so the barrier has to be done by the pCPU which owns
+     * that file.
+     */
+    imsic_call_on_cpu(old_vsfile_cpu, imsic_aplic_sync, NULL);
+
+    /*
+     * At this point, all interrupt producers have been moved
+     * to the new IMSIC VS-file.
+     */
+
     BUG_ON("unimplemented");
 }
xen/arch/riscv/include/asm/imsic.h +3 -0
index 6ea2e4b8ca12..6395b539c52d 100644
@@ -114,12 +114,15 @@ void imsic_ids_local_delivery(bool enable);
 int vcpu_imsic_init(struct vcpu *v);
 void vcpu_imsic_deinit(struct vcpu *v);
 unsigned int vcpu_guest_file_id(const struct vcpu *v);
+void imsic_update_state(struct vcpu *v, unsigned int guest_file_id);
 
 int vimsic_make_domu_dt_node(struct kernel_info *kinfo, unsigned int *phandle);
 
 void imsic_ctxt_switch_from(struct vcpu *v);
 void imsic_ctxt_switch_to(struct vcpu *v);
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id);
+
 void imsic_migrate_vcpu(struct vcpu *v);
 
 #endif /* ASM_RISCV_IMSIC_H */
Signature · 1 line
2.55.0
#201 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 66

Quoted 7 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +3 -0
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
 #define IMSIC_DISABLE_EITHRESHOLD   1
 #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)           \
+({                                  \
+    csr_write(CSR_SISELECT, (c));   \

Nit: Excess parentheses again.

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 261

Quoted 9 lines
xen/arch/riscv/imsic.c +5 -0
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
     spin_unlock(&imsic_cfg.lock);
 }
 
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);

Both can be unsigned int, can't they?

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 264

Quoted 2 lines
xen/arch/riscv/imsic.c +2 -0
+    return !!(imsic_csr_read(isel) & bit);
+}

No need for !! here.

What about endianness, btw? Does the IMSIC always match the CPU (and its setting)?

Overall, what does "local" in the function name signify? (For a static function, the "imsic" prefix may also be unnecessary.)

Quoted 6 lines
xen/arch/riscv/imsic.c +2 -0
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
         on_selected_cpus(cpumask_of(cpu), func, data, 1);
 }
 
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this

xen/arch/riscv/imsic.c static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *), · line 537

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *data)

If the parameter isn't used, maybe best to name it "unused"?

Quoted 12 lines
xen/arch/riscv/imsic.c +8 -0
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
     if ( v->arch.last_cpu == NR_CPUS )
         return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 919

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
     /*
      * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
      * VS-file.
      */

Isn't the new part of the comment premature? Moving doesn't start until ...

Quoted 17 lines
xen/arch/riscv/imsic.c +13 -0
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
     /* Zero-out new IMSIC VS-file */
     imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);
 
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+
+    /*
+     * TODO: Modify the relevant translation tables at all IOMMUs so that MSIs
+     *       for this virtual interrupt file are now sent to the new physical

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 960

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+     *       interrupt file.
+     */
+    if ( iommu_enabled )
+        printk_once("IMSIC: IOMMU MSI retargeting is not implemented\n");
+
+    /*
+     * If any interrupts at an APLIC are forwarded by MSIs to the old interrupt
+     * file, reconfigure the APLIC to send them to the new interrupt file.
+     */
+    aplic_reconfigure_target(v, old_vsfile_id, old_vsfile_cpu);

... here, as it looks.

Jan

#202 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

Quoted 10 lines · Jan Beulich

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 66

Quoted 7 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +3 -0
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
  #define IMSIC_DISABLE_EITHRESHOLD   1
  #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)           \
+({                                  \
+    csr_write(CSR_SISELECT, (c));   \

Nit: Excess parentheses again.

I will drop them.

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/imsic.c +0 -0
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
      spin_unlock(&imsic_cfg.lock);
  }
 
Quoted 7 lines

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 261

Quoted 5 lines
xen/arch/riscv/imsic.c +5 -0
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);

Both can be unsigned int, can't they?

Yes, agreed. Both isel and bit fit within unsigned int. I will update them in the next version.

Quoted 8 lines

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 264

Quoted 3 lines
xen/arch/riscv/imsic.c +2 -0
+    return !!(imsic_csr_read(isel) & bit);
+}

No need for !! here.

What about endianness, btw? Does the IMSIC always match the CPU (and its setting)?

No, the IMSIC does not dynamically adapt its register interfaces based on the CPU's runtime endianness configuration (e.g. mstatus.SBE/MBE):

- CSR Accesses (imsic_csr_read): Indirect CSR accesses (siselect/sireg or miselect/mireg) operate using standard RISC-V CSR instructions at current XLEN width. Values are read and written directly into architectural GPRs without byte-swapping.

- MMIO Ports: For incoming device MSIs, IMSIC uses fixed memory-mapped offsets: offset 0x000 (seteipnum_le) always expects Little-Endian, while offset 0x004 (seteipnum_be) expects Big-Endian.

- Memory-Resident Interrupt Files (MRIF): For virtualized environments, MRIF structures in memory are strictly defined in Little-Endian byte order regardless of whether the CPU harts operate in Big-Endian or Little-Endian mode.

Quoted 3 lines

Overall, what does "local" in the function name signify? (For a static function, the "imsic" prefix may also be unnecessary.)

It signifies that local (on which code is executed now) hart's IMSIC CSRs (isel and ireg in the case of imsic_csr_read()) are touched.

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/imsic.c +0 -0
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
          on_selected_cpus(cpumask_of(cpu), func, data, 1);
  }
 
Quoted 14 lines

xen/arch/riscv/imsic.c static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *), · line 537

Quoted 12 lines
xen/arch/riscv/imsic.c +12 -0
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *data)

If the parameter isn't used, maybe best to name it "unused"?

Makes sense to me. I will do that in the next version + I will update the type to 'struct imsic_vsfile_data *' as it was suggested for imsic_call_on_cpu() in "Re: [PATCH v2 30/39] xen/riscv: prepare new IMSIC VS-file".

Quoted 47 lines
Quoted 13 lines
xen/arch/riscv/imsic.c +8 -0
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 919

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
      /*
       * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
       * VS-file.
       */

Isn't the new part of the comment premature? Moving doesn't start until ...

Quoted 21 lines
xen/arch/riscv/imsic.c +17 -0
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Zero-out new IMSIC VS-file */
      imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);
 
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+
+    /*
+     * TODO: Modify the relevant translation tables at all IOMMUs so that MSIs
+     *       for this virtual interrupt file are now sent to the new physical
+     *       interrupt file.
+     */
+    if ( iommu_enabled )
+        printk_once("IMSIC: IOMMU MSI retargeting is not implemented\n");
Quoted 8 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 960

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+
+    /*
+     * If any interrupts at an APLIC are forwarded by MSIs to the old interrupt
+     * file, reconfigure the APLIC to send them to the new interrupt file.
+     */
+    aplic_reconfigure_target(v, old_vsfile_id, old_vsfile_cpu);

... here, as it looks.

At some point I agree but the steps before are preparation of moving and is a part of moving process.

Then probably it make sense to reword the comment to:

/*
* At this point, all interrupt producers are still using the old IMSIC
* VS-file. Allocate and clear the new one before redirecting anything
* to it.
*/

Would it be better?

~ Oleksii

#203 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

Quoted 26 lines · Oleksii Kurochko
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +0 -0
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
      spin_unlock(&imsic_cfg.lock);
  }
 
Quoted 7 lines

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 261

Quoted 5 lines
xen/arch/riscv/imsic.c +5 -0
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);

Both can be unsigned int, can't they?

Yes, agreed. Both isel and bit fit within unsigned int. I will update them in the next version.

Quoted 8 lines

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 264

Quoted 3 lines
xen/arch/riscv/imsic.c +2 -0
+    return !!(imsic_csr_read(isel) & bit);
+}

No need for !! here.

What about endianness, btw? Does the IMSIC always match the CPU (and its setting)?

Quoted 7 lines

No, the IMSIC does not dynamically adapt its register interfaces based on the CPU's runtime endianness configuration (e.g. mstatus.SBE/MBE):

- CSR Accesses (imsic_csr_read): Indirect CSR accesses (siselect/sireg or miselect/mireg) operate using standard RISC-V CSR instructions at current XLEN width. Values are read and written directly into architectural GPRs without byte-swapping.

I.e. you need you add endianness conversion.

Quoted 5 lines
Quoted 2 lines

Overall, what does "local" in the function name signify? (For a static function, the "imsic" prefix may also be unnecessary.)

It signifies that local (on which code is executed now) hart's IMSIC CSRs (isel and ireg in the case of imsic_csr_read()) are touched.

That's the expected thing for CSR access, though.

Quoted 60 lines
Quoted 46 lines
Quoted 12 lines
xen/arch/riscv/imsic.c +8 -0
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 919

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
      /*
       * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
       * VS-file.
       */

Isn't the new part of the comment premature? Moving doesn't start until ...

Quoted 21 lines
xen/arch/riscv/imsic.c +17 -0
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Zero-out new IMSIC VS-file */
      imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);
 
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+
+    /*
+     * TODO: Modify the relevant translation tables at all IOMMUs so that MSIs
+     *       for this virtual interrupt file are now sent to the new physical
+     *       interrupt file.
+     */
+    if ( iommu_enabled )
+        printk_once("IMSIC: IOMMU MSI retargeting is not implemented\n");
Quoted 8 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 960

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+
+    /*
+     * If any interrupts at an APLIC are forwarded by MSIs to the old interrupt
+     * file, reconfigure the APLIC to send them to the new interrupt file.
+     */
+    aplic_reconfigure_target(v, old_vsfile_id, old_vsfile_cpu);

... here, as it looks.

At some point I agree but the steps before are preparation of moving and is a part of moving process.

Then probably it make sense to reword the comment to:

Quoted 7 lines

/*
* At this point, all interrupt producers are still using the old IMSIC
* VS-file. Allocate and clear the new one before redirecting anything
* to it.
*/

Would it be better?

Imo yes.

Jan

#204 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

Quoted 7 lines · Jan Beulich
Quoted 6 lines · Oleksii Kurochko
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +0 -0
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
       spin_unlock(&imsic_cfg.lock);
   }
 
Quoted 8 lines
Quoted 8 lines
Quoted 6 lines

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 261

Quoted 5 lines
xen/arch/riscv/imsic.c +5 -0
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);

Both can be unsigned int, can't they?

Yes, agreed. Both isel and bit fit within unsigned int. I will update them in the next version.

Sorry for not noticing that in first reply but local variable bit should be unsigned long as if id % 64 >= 32 we will have overflow of 'unsigned int'.

Quoted 7 lines
Quoted 7 lines
Quoted 7 lines

xen/arch/riscv/imsic.c void imsic_irq_disable(unsigned int irq) · line 264

Quoted 3 lines
xen/arch/riscv/imsic.c +2 -0
+    return !!(imsic_csr_read(isel) & bit);
+}

No need for !! here.

What about endianness, btw? Does the IMSIC always match the CPU (and its setting)?

Quoted 8 lines
Quoted 7 lines

No, the IMSIC does not dynamically adapt its register interfaces based on the CPU's runtime endianness configuration (e.g. mstatus.SBE/MBE):

- CSR Accesses (imsic_csr_read): Indirect CSR accesses (siselect/sireg or miselect/mireg) operate using standard RISC-V CSR instructions at current XLEN width. Values are read and written directly into architectural GPRs without byte-swapping.

I.e. you need you add endianness conversion.

I think I don't really get why. My understanding is that endianness is about an access to memory. We don't have here load/store instruction or an explicit access to memory. We have here only CSR instruction which loads value from IMSIC register to GPR w/ an access to any memory.

Probably I wasn't clear here "he IMSIC does not dynamically adapt its register interfaces based on the CPU's runtime endianness configuration (e.g. mstatus.SBE/MBE):" and it would be better to reply as:

```
endianness (mstatus.SBE/MBE) only governs memory accesses, whereas
eipK is accessed via CSR instructions, which transfer an XLEN-wide
value between the CSR and a GPR with no notion of byte order. The AIA
spec defines eipK in terms of bit significance (bit i of eipK is
identity K*32+i), so BIT(id % BITS_PER_LONG) is correct regardless of
the CPU's data endianness. Endianness only matters for the memory-mapped
seteipnum register, which is why the spec provides both seteipnum_le
and seteipnum_be.
```
Quoted 6 lines
Quoted 5 lines
Quoted 3 lines

Overall, what does "local" in the function name signify? (For a static function, the "imsic" prefix may also be unnecessary.)

It signifies that local (on which code is executed now) hart's IMSIC CSRs (isel and ireg in the case of imsic_csr_read()) are touched.

That's the expected thing for CSR access, though.

Fair enough. I'll drop both the "imsic_" prefix and "local" and rename it to irq_is_pending().

~ Oleksii

#205 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 25 lines

After new IMSIC VS-file is zeroed-out it is necessary to do G-stage remaping fo new IMSIC VS-file. Also, if any interrupts at an APLIC are forwarded by MSIs to the old interrupt file, reconfigure the APLIC to send them to the new interrupt file.

Generally it is needed also to modify the relevant translation tables at all IOMMUs so that MSIs for this virtual interrupt file are now sent to the new physical interrupt file but it is skipped for now there is no IOMMU support for RISC-V.

Synchronize with APLIC to ensure that no straggler MSIs will arrive at the old interrupt file by using of aplic_genmsi_barrier().

Technically there is no need for read_lock_irqsave() and read_unlock_irqrestore() around reading of ->guest_file_id, as a write cannot happen in parallel: any update to ->guest_file_id for a vCPU will happen either in imsic_migrate_vcpu() itself or before the vCPU

first gains control (in continue_new_vcpu()), so there is no concurrent access to it in imsic_migrate_vcpu(). The lock is added here for potential future cases.

Quoted 6 lines

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

imsic_map_guest_file() and imsic_update_state() are stubs for now and will be introduced later in a separate patch.

"will be introduced later" would be stale in the future.

Quoted 76 lines
xen/arch/riscv/imsic.c +28 -0
index 5de4594961..5e9f6995e4 100644
@@ -27,6 +27,7 @@
 #include <xen/xvmalloc.h>
 
 #include <asm/aia.h>
+#include <asm/aplic.h>
 #include <asm/imsic.h>
 
 #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
 #define IMSIC_DISABLE_EITHRESHOLD   1
 #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)           \
+({                                  \
+    csr_write(CSR_SISELECT, (c));   \
+    csr_read(CSR_SIREG);            \
+})
+
 #define imsic_csr_write(c, v)   \
 do {                            \
     csr_write(CSR_SISELECT, c); \
@@ -141,6 +148,11 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v)
     return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
 }
 
+void imsic_update_state(struct vcpu *v, unsigned int guest_file_id)
+{
+    BUG_ON("unimplemented\n");
+}
+
 void __init imsic_ids_local_delivery(bool enable)
 {
     if ( enable )
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
     spin_unlock(&imsic_cfg.lock);
 }
 
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);
+
+    return !!(imsic_csr_read(isel) & bit);
+}
+
 /* Callers aren't intended to changed imsic_cfg so return const. */
 const struct imsic_config *imsic_get_config(void)
 {
@@ -436,6 +457,11 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
     /* Nothing to do */
 }
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
+{
+    return -EOPNOTSUPP;
+}
+
 int cf_check vcpu_imsic_init(struct vcpu *v)
 {
     struct vimsic_state *imsic_state;
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
         on_selected_cpus(cpumask_of(cpu), func, data, 1);
 }
 
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this

xen/arch/riscv/imsic.c static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *), · line 537

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *data)

It seems data arg is not used here

Quoted 49 lines
xen/arch/riscv/imsic.c +27 -0
+{
+    imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);
+
+    aplic_genmsi_barrier();
+
+    while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
+        cpu_relax();
+}
+
 static void cf_check imsic_vsfile_local_clear(void *data)
 {
     unsigned int i;
@@ -837,6 +884,10 @@ void imsic_migrate_vcpu(struct vcpu *v)
     struct imsic_vsfile_data vsfile_data = {
         .nr_eix = nr_hw_eix,
     };
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+    unsigned int old_vsfile_id;
+    unsigned int old_vsfile_cpu;
 
     /*
      * The scheduler can mark a freshly created vCPU's unit as migrated and
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
     if ( v->arch.last_cpu == NR_CPUS )
         return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
     /*
      * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
      * VS-file.
      */
 
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
     /* Zero-out new IMSIC VS-file */
     imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 946

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+

This gets rewritten later in the series by "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu", which moves the clear/map/update sequence into imsic_vsfile_acquire() (and adds vgein_release() on the error path).

Could imsic_vsfile_acquire() be introduced here (or in a prep patch) instead, so that the later patch only adds imsic_vsfile_attach()? That would avoid the churn.

Signature · 1 line
Baptiste Le Duc <[email protected]>
#206 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

Quoted 25 lines · Baptiste Le Duc
Quoted 25 lines

After new IMSIC VS-file is zeroed-out it is necessary to do G-stage remaping fo new IMSIC VS-file. Also, if any interrupts at an APLIC are forwarded by MSIs to the old interrupt file, reconfigure the APLIC to send them to the new interrupt file.

Generally it is needed also to modify the relevant translation tables at all IOMMUs so that MSIs for this virtual interrupt file are now sent to the new physical interrupt file but it is skipped for now there is no IOMMU support for RISC-V.

Synchronize with APLIC to ensure that no straggler MSIs will arrive at the old interrupt file by using of aplic_genmsi_barrier().

Technically there is no need for read_lock_irqsave() and read_unlock_irqrestore() around reading of ->guest_file_id, as a write cannot happen in parallel: any update to ->guest_file_id for a vCPU will happen either in imsic_migrate_vcpu() itself or before the vCPU

first gains control (in continue_new_vcpu()), so there is no concurrent access to it in imsic_migrate_vcpu(). The lock is added here for potential future cases.

Quoted 7 lines
Quoted 6 lines

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

imsic_map_guest_file() and imsic_update_state() are stubs for now and will be introduced later in a separate patch.

"will be introduced later" would be stale in the future.

I will drop that part from the commit message.

Quoted 74 lines
Quoted 74 lines
xen/arch/riscv/imsic.c +26 -0
index 5de4594961..5e9f6995e4 100644
@@ -27,6 +27,7 @@
  #include <xen/xvmalloc.h>
 
  #include <asm/aia.h>
+#include <asm/aplic.h>
  #include <asm/imsic.h>
 
  #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
  #define IMSIC_DISABLE_EITHRESHOLD   1
  #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)           \
+({                                  \
+    csr_write(CSR_SISELECT, (c));   \
+    csr_read(CSR_SIREG);            \
+})
+
  #define imsic_csr_write(c, v)   \
  do {                            \
      csr_write(CSR_SISELECT, c); \
@@ -141,6 +148,11 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v)
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
  }
 
+void imsic_update_state(struct vcpu *v, unsigned int guest_file_id)
+{
+    BUG_ON("unimplemented\n");
+}
+
  void __init imsic_ids_local_delivery(bool enable)
  {
      if ( enable )
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
      spin_unlock(&imsic_cfg.lock);
  }
 
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);
+
+    return !!(imsic_csr_read(isel) & bit);
+}
+
  /* Callers aren't intended to changed imsic_cfg so return const. */
  const struct imsic_config *imsic_get_config(void)
  {
@@ -436,6 +457,11 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
      /* Nothing to do */
  }
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
+{
+    return -EOPNOTSUPP;
+}
+
  int cf_check vcpu_imsic_init(struct vcpu *v)
  {
      struct vimsic_state *imsic_state;
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
          on_selected_cpus(cpumask_of(cpu), func, data, 1);
  }
 
Quoted 13 lines

xen/arch/riscv/imsic.c static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *), · line 537

Quoted 12 lines
xen/arch/riscv/imsic.c +12 -0
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *data)

It seems data arg is not used here

It will be renamed to unused in the v3 but we still need to have it becuase how this function is called through imsic_call_on_cpu().

Quoted 63 lines
Quoted 49 lines
xen/arch/riscv/imsic.c +27 -0
+{
+    imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);
+
+    aplic_genmsi_barrier();
+
+    while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
+        cpu_relax();
+}
+
  static void cf_check imsic_vsfile_local_clear(void *data)
  {
      unsigned int i;
@@ -837,6 +884,10 @@ void imsic_migrate_vcpu(struct vcpu *v)
      struct imsic_vsfile_data vsfile_data = {
          .nr_eix = nr_hw_eix,
      };
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+    unsigned int old_vsfile_id;
+    unsigned int old_vsfile_cpu;
 
      /*
       * The scheduler can mark a freshly created vCPU's unit as migrated and
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
      /*
       * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
       * VS-file.
       */
 
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Zero-out new IMSIC VS-file */
      imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 946

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+

This gets rewritten later in the series by "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu", which moves the clear/map/update sequence into imsic_vsfile_acquire() (and adds vgein_release() on the error path).

Quoted 4 lines

Could imsic_vsfile_acquire() be introduced here (or in a prep patch) instead, so that the later patch only adds imsic_vsfile_attach()? That would avoid the churn.

It could, I just thought that it will be easier to justify necessity of it by introduction in "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu". But I am okay to move it to this patch.

Thanks.

~ Oleksii

#207 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

Quoted 192 lines · Oleksii Kurochko
Quoted 25 lines · Baptiste Le Duc
Quoted 25 lines

After new IMSIC VS-file is zeroed-out it is necessary to do G-stage remaping fo new IMSIC VS-file. Also, if any interrupts at an APLIC are forwarded by MSIs to the old interrupt file, reconfigure the APLIC to send them to the new interrupt file.

Generally it is needed also to modify the relevant translation tables at all IOMMUs so that MSIs for this virtual interrupt file are now sent to the new physical interrupt file but it is skipped for now there is no IOMMU support for RISC-V.

Synchronize with APLIC to ensure that no straggler MSIs will arrive at the old interrupt file by using of aplic_genmsi_barrier().

Technically there is no need for read_lock_irqsave() and read_unlock_irqrestore() around reading of ->guest_file_id, as a write cannot happen in parallel: any update to ->guest_file_id for a vCPU will happen either in imsic_migrate_vcpu() itself or before the vCPU

first gains control (in continue_new_vcpu()), so there is no concurrent access to it in imsic_migrate_vcpu(). The lock is added here for potential future cases.

Quoted 7 lines
Quoted 6 lines

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

imsic_map_guest_file() and imsic_update_state() are stubs for now and will be introduced later in a separate patch.

"will be introduced later" would be stale in the future.

I will drop that part from the commit message.

Quoted 74 lines
Quoted 74 lines
xen/arch/riscv/imsic.c +26 -0
index 5de4594961..5e9f6995e4 100644
@@ -27,6 +27,7 @@
  #include <xen/xvmalloc.h>
 
  #include <asm/aia.h>
+#include <asm/aplic.h>
  #include <asm/imsic.h>
 
  #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
  #define IMSIC_DISABLE_EITHRESHOLD   1
  #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)           \
+({                                  \
+    csr_write(CSR_SISELECT, (c));   \
+    csr_read(CSR_SIREG);            \
+})
+
  #define imsic_csr_write(c, v)   \
  do {                            \
      csr_write(CSR_SISELECT, c); \
@@ -141,6 +148,11 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v)
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
  }
 
+void imsic_update_state(struct vcpu *v, unsigned int guest_file_id)
+{
+    BUG_ON("unimplemented\n");
+}
+
  void __init imsic_ids_local_delivery(bool enable)
  {
      if ( enable )
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
      spin_unlock(&imsic_cfg.lock);
  }
 
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);
+
+    return !!(imsic_csr_read(isel) & bit);
+}
+
  /* Callers aren't intended to changed imsic_cfg so return const. */
  const struct imsic_config *imsic_get_config(void)
  {
@@ -436,6 +457,11 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
      /* Nothing to do */
  }
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
+{
+    return -EOPNOTSUPP;
+}
+
  int cf_check vcpu_imsic_init(struct vcpu *v)
  {
      struct vimsic_state *imsic_state;
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
          on_selected_cpus(cpumask_of(cpu), func, data, 1);
  }
 
Quoted 13 lines

xen/arch/riscv/imsic.c static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *), · line 537

Quoted 12 lines
xen/arch/riscv/imsic.c +12 -0
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *data)

It seems data arg is not used here

It will be renamed to unused in the v3 but we still need to have it becuase how this function is called through imsic_call_on_cpu().

Quoted 63 lines
Quoted 49 lines
xen/arch/riscv/imsic.c +27 -0
+{
+    imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);
+
+    aplic_genmsi_barrier();
+
+    while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
+        cpu_relax();
+}
+
  static void cf_check imsic_vsfile_local_clear(void *data)
  {
      unsigned int i;
@@ -837,6 +884,10 @@ void imsic_migrate_vcpu(struct vcpu *v)
      struct imsic_vsfile_data vsfile_data = {
          .nr_eix = nr_hw_eix,
      };
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+    unsigned int old_vsfile_id;
+    unsigned int old_vsfile_cpu;
 
      /*
       * The scheduler can mark a freshly created vCPU's unit as migrated and
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
      /*
       * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
       * VS-file.
       */
 
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Zero-out new IMSIC VS-file */
      imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 946

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+

This gets rewritten later in the series by "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu", which moves the clear/map/update sequence into imsic_vsfile_acquire() (and adds vgein_release() on the error path).

Quoted 8 lines
Quoted 4 lines

Could imsic_vsfile_acquire() be introduced here (or in a prep patch) instead, so that the later patch only adds imsic_vsfile_attach()? That would avoid the churn.

It could, I just thought that it will be easier to justify necessity of it by introduction in "xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu". But I am okay to move it to this patch.

Hum, finally I don't know if it's the good solution. First time I'm saw this, so I was suprised, but if it's common practice, let's keep it here for clarity.

Quoted 6 lines

Thanks.

~ Oleksii

#208 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 1 line

xen/riscv: remap interrupts to new IMSIC VS-file

Nit: The next patch uses "restore" in its title, we might want to use "save" terminology here for symmetry? e.g.:
"xen/riscv: save old interrupt file state to memory"

Quoted 229 lines · Oleksii Kurochko

After new IMSIC VS-file is zeroed-out it is necessary to do G-stage remaping fo new IMSIC VS-file. Also, if any interrupts at an APLIC are forwarded by MSIs to the old interrupt file, reconfigure the APLIC to send them to the new interrupt file.

Generally it is needed also to modify the relevant translation tables at all IOMMUs so that MSIs for this virtual interrupt file are now sent to the new physical interrupt file but it is skipped for now there is no IOMMU support for RISC-V.

Synchronize with APLIC to ensure that no straggler MSIs will arrive at the old interrupt file by using of aplic_genmsi_barrier().

Technically there is no need for read_lock_irqsave() and read_unlock_irqrestore() around reading of ->guest_file_id, as a write cannot happen in parallel: any update to ->guest_file_id for a vCPU will happen either in imsic_migrate_vcpu() itself or before the vCPU first gains control (in continue_new_vcpu()), so there is no concurrent access to it in imsic_migrate_vcpu(). The lock is added here for potential future cases.

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

imsic_map_guest_file() and imsic_update_state() are stubs for now and will be introduced later in a separate patch.

---
Changes in v2:
- New patch.
---

---
  xen/arch/riscv/imsic.c             | 103 +++++++++++++++++++++++++++++
  xen/arch/riscv/include/asm/imsic.h |   3 +
  2 files changed, 106 insertions(+)
xen/arch/riscv/imsic.c +103 -0
index 5de45949610d..5e9f6995e443 100644
@@ -27,6 +27,7 @@
  #include <xen/xvmalloc.h>
 
  #include <asm/aia.h>
+#include <asm/aplic.h>
  #include <asm/imsic.h>
 
  #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;
  #define IMSIC_DISABLE_EITHRESHOLD   1
  #define IMSIC_ENABLE_EITHRESHOLD    0
 
+#define imsic_csr_read(c)           \
+({                                  \
+    csr_write(CSR_SISELECT, (c));   \
+    csr_read(CSR_SIREG);            \
+})
+
  #define imsic_csr_write(c, v)   \
  do {                            \
      csr_write(CSR_SISELECT, c); \
@@ -141,6 +148,11 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v)
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
  }
 
+void imsic_update_state(struct vcpu *v, unsigned int guest_file_id)
+{
+    BUG_ON("unimplemented\n");
+}
+
  void __init imsic_ids_local_delivery(bool enable)
  {
      if ( enable )
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)
      spin_unlock(&imsic_cfg.lock);
  }
 
+static bool imsic_local_is_pending(unsigned int id)
+{
+    unsigned long isel =
+        (id / BITS_PER_LONG) * (BITS_PER_LONG / IMSIC_EIPx_BITS) + IMSIC_EIP0;
+    unsigned long bit = BIT(id % BITS_PER_LONG, UL);
+
+    return !!(imsic_csr_read(isel) & bit);
+}
+
  /* Callers aren't intended to changed imsic_cfg so return const. */
  const struct imsic_config *imsic_get_config(void)
  {
@@ -436,6 +457,11 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
      /* Nothing to do */
  }
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
+{
+    return -EOPNOTSUPP;
+}
+
  int cf_check vcpu_imsic_init(struct vcpu *v)
  {
      struct vimsic_state *imsic_state;
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),
          on_selected_cpus(cpumask_of(cpu), func, data, 1);
  }
 
+/*
+ * Ensure that all the MSIs the APLIC has already generated for the hart this
+ * runs on have really reached the hart's IMSIC.
+ *
+ * The barrier is the one described by the AIA specification in
+ * "Synchronizing interactions between a hart and the APLIC": ask the APLIC to
+ * send an MSI to the hart itself and wait until it shows up as pending in the
+ * hart's own interrupt file. As it says nothing about MSIs on their way to
+ * any other hart, it has to be executed by the pCPU owning the interrupt file
+ * the MSIs were being sent to.
+ */
+static void cf_check imsic_aplic_sync(void *data)
+{
+    imsic_local_eix_update(imsic_cfg.sync_id, 1, true, false);
+
+    aplic_genmsi_barrier();
+
+    while ( !imsic_local_is_pending(imsic_cfg.sync_id) )
+        cpu_relax();
+}
+
  static void cf_check imsic_vsfile_local_clear(void *data)
  {
      unsigned int i;
@@ -837,6 +884,10 @@ void imsic_migrate_vcpu(struct vcpu *v)
      struct imsic_vsfile_data vsfile_data = {
          .nr_eix = nr_hw_eix,
      };
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+    unsigned int old_vsfile_id;
+    unsigned int old_vsfile_cpu;
 
      /*
       * The scheduler can mark a freshly created vCPU's unit as migrated and
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)
      if ( v->arch.last_cpu == NR_CPUS )
          return;
 
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    old_vsfile_id = imsic_state->guest_file_id;
+    old_vsfile_cpu = imsic_state->vsfile_cpu;
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+
+    /*
+     * We don't support SW interrupt files at the moment. Bail out before
+     * anything is touched, as the old file has no owning pCPU in that case
+     * and there is nothing to retarget the producers away from.
+     */
+    if ( old_vsfile_cpu == NR_CPUS )
+        panic("IMSIC SW-file isn't supported\n");
+
      /*
       * At this point, all interrupt producers are still using the old IMSIC
+     * VS-file so we first move all interrupt producers to the new IMSIC
       * VS-file.
       */
 
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Zero-out new IMSIC VS-file */
      imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data);
 
+    /* Update G-stage mapping for the new IMSIC VS-file */
+    if ( imsic_map_guest_file(v, new_vsfile_hgei) )
+    {
+        domain_crash(v->domain, "Migration to hw interrupt file failed\n");
+
+        return;
+    }
+
+    imsic_update_state(v, new_vsfile_hgei);
+
+    /*
+     * TODO: Modify the relevant translation tables at all IOMMUs so that MSIs
+     *       for this virtual interrupt file are now sent to the new physical
+     *       interrupt file.
+     */
+    if ( iommu_enabled )
+        printk_once("IMSIC: IOMMU MSI retargeting is not implemented\n");
+
+    /*
+     * If any interrupts at an APLIC are forwarded by MSIs to the old interrupt
+     * file, reconfigure the APLIC to send them to the new interrupt file.
+     */
+    aplic_reconfigure_target(v, old_vsfile_id, old_vsfile_cpu);
+
+    /*
+     * Synchronizing interactions between a hart and the APLIC.
+     *
+     * The MSIs to be flushed are the ones still on their way to the old
+     * interrupt file, so the barrier has to be done by the pCPU which owns
+     * that file.
+     */
+    imsic_call_on_cpu(old_vsfile_cpu, imsic_aplic_sync, NULL);
+
+    /*
+     * At this point, all interrupt producers have been moved
+     * to the new IMSIC VS-file.
+     */
+
      BUG_ON("unimplemented");
  }
xen/arch/riscv/include/asm/imsic.h +3 -0
index 6ea2e4b8ca12..6395b539c52d 100644
@@ -114,12 +114,15 @@ void imsic_ids_local_delivery(bool enable);
  int vcpu_imsic_init(struct vcpu *v);
  void vcpu_imsic_deinit(struct vcpu *v);
  unsigned int vcpu_guest_file_id(const struct vcpu *v);
+void imsic_update_state(struct vcpu *v, unsigned int guest_file_id);
 
  int vimsic_make_domu_dt_node(struct kernel_info *kinfo, unsigned int *phandle);
 
  void imsic_ctxt_switch_from(struct vcpu *v);
  void imsic_ctxt_switch_to(struct vcpu *v);
 
+int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id);
+
  void imsic_migrate_vcpu(struct vcpu *v);
 
  #endif /* ASM_RISCV_IMSIC_H */
#209 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

Quoted 5 lines · Baptiste Le Duc
Quoted 1 line

xen/riscv: remap interrupts to new IMSIC VS-file

Nit: The next patch uses "restore" in its title, we might want to use "save" terminology here for symmetry? e.g.:
    "xen/riscv: save old interrupt file state to memory"

Not only saving old interrupt file state happens here but also moving of all interrupts to new IMSIC VS-file. That why remap sounds okay here to me. If it is Nit: and no one else are against that I prefer to still have the commit subject as it is written now.

~ Oleksii

#210 lore raw

Re: [PATCH v2 32/39] xen/riscv: remap interrupts to new IMSIC VS-file

Quoted 5 lines · Oleksii Kurochko
Quoted 2 lines · Baptiste Le Duc
Quoted 1 line

xen/riscv: remap interrupts to new IMSIC VS-file

Quoted 8 lines
Quoted 3 lines

Nit: The next patch uses "restore" in its title, we might want to use "save" terminology here for symmetry? e.g.:
    "xen/riscv: save old interrupt file state to memory"

Not only saving old interrupt file state happens here but also moving of all interrupts to new IMSIC VS-file. That why remap sounds okay here to me. If it is Nit: and no one else are against that I prefer to still have the commit subject as it is written now.

Ok lets keep the original.

Quoted 4 lines

~ Oleksii

#211 lore raw

PATCH v2 33/39 xen/riscv: dump old interrupt file to memory

In reply to Oleksii Kurochko

At the old interrupt file, dump to memory all the eip and eie arrays). After this step is done, the old interrupt file is no longer in use so old intrrupt file VGEIN could be released.

Restoring of old interrupt file state will be done in follow-up patch.

There are cases where it is needed to specify on which cpu it is necessary to VGEIN should be released so update vgein_release() to deal with that.

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_release() is stub for now and will be introduced later.

---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/aia.c             |   5 ++
 xen/arch/riscv/imsic.c           | 104 +++++++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/aia.h |   1 +
 3 files changed, 110 insertions(+)
xen/arch/riscv/aia.c +5 -0
index 75c82bcfa1b3..be3901ec0cfa 100644
@@ -30,3 +30,8 @@ unsigned int vgein_assign(struct vcpu *v)
 
     return 0;
 }
+
+void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
+{
+    BUG_ON("unimplemented\n");
+}
xen/arch/riscv/imsic.c +104 -0

139 lines not on this page · raw message

xen/arch/riscv/include/asm/aia.h +1 -0
index 53a1efb042f8..8e4eb2f6b14e 100644
@@ -10,5 +10,6 @@ bool aia_usable(void);
 void aia_init(void);
 
 unsigned int vgein_assign(struct vcpu *v);
+void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu);
 
 #endif /* RISCV_AIA_H */
Signature · 1 line
2.55.0
#212 lore raw

Re: [PATCH v2 33/39] xen/riscv: dump old interrupt file to memory

Quoted 10 lines · Oleksii Kurochko

At the old interrupt file, dump to memory all the eip and eie arrays). After this step is done, the old interrupt file is no longer in use so old intrrupt file VGEIN could be released.

Restoring of old interrupt file state will be done in follow-up patch.

There are cases where it is needed to specify on which cpu it is necessary to VGEIN should be released so update vgein_release() to deal with that.

Beside this being difficult to parse, it looks like it is inapplicable? As said ...

Quoted 5 lines

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_release() is stub for now and will be introduced later.

... also here?

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 64

Quoted 12 lines
xen/arch/riscv/imsic.c +6 -0
@@ -56,6 +56,24 @@ static unsigned int __ro_after_init guest_num_msis;
  */
 #define GUEST_IMSIC_MAX_MSIS 255U
 
+/*
+ * The interrupt identities an IMSIC interrupt file provides are 0 (which is
+ * never valid, but still occupies a bit) up to IMSIC_MAX_ID inclusive, so
+ * IMSIC_MAX_ID + 1 bits have to be covered.
+ */
+#define IMSIC_MAX_EIX DIV_ROUND_UP(IMSIC_MAX_ID + 1, BITS_PER_TYPE(uint64_t))

As before - plain 64 please, or it needs to become clear where the uint64_t is actually coming from.

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 68

Quoted 3 lines
xen/arch/riscv/imsic.c +3 -0
+struct imsic_mrif_eix {
+    unsigned long eip[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];
+    unsigned long eie[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];

Same here. Yet better may be to use DECLARE_BITMAP()?

xen/arch/riscv/imsic.c do { \ · line 113

Quoted 12 lines
xen/arch/riscv/imsic.c +8 -0
@@ -85,6 +103,15 @@ do {                            \
     csr_clear(CSR_SIREG, v);    \
 } while (0)
 
+#define imsic_vs_csr_swap(c, v)     \
+({                                  \
+    unsigned long r_;               \
+                                    \
+    csr_write(CSR_VSISELECT, (c));  \
+    r_ = csr_swap(CSR_VSIREG, (v)); \
+    r_;                             \
+})

Excess parentheses again. Plus - what use is r_ here?

Quoted 5 lines
xen/arch/riscv/imsic.c +1 -0
@@ -130,6 +157,21 @@ do {                                \
     imsic_switchcase_32(F, ireg + 0, ##__VA_ARGS__) \
     imsic_switchcase_32(F, ireg + 32, ##__VA_ARGS__)
 
+static unsigned long imsic_eix_swap(unsigned int ireg, unsigned long val)

xen/arch/riscv/imsic.c do { \ · line 170

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_ret, IMSIC_EIP0,
+                        imsic_vs_csr_swap, val)
+    imsic_switchcase_64(imsic_switchcase_ret, IMSIC_EIE0,
+                        imsic_vs_csr_swap, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }

There still wants to "break" in the default case.

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 1075

Quoted 6 lines
xen/arch/riscv/imsic.c +2 -0
@@ -973,5 +1071,11 @@ void imsic_migrate_vcpu(struct vcpu *v)
      * to the new IMSIC VS-file.
      */
 
+    /* Read and clear register state from old IMSIC VS-file */
+    imsic_vsfile_read_clear(old_vsfile_id, old_vsfile_cpu, nr_hw_eix, &tmrif);

Why is &tmrif being passed into the function, when it's not otherwise used here? The function could itself have a suitable local var.

Jan

#213 lore raw

Re: [PATCH v2 33/39] xen/riscv: dump old interrupt file to memory

Quoted 15 lines · Jan Beulich
Quoted 10 lines · Oleksii Kurochko

At the old interrupt file, dump to memory all the eip and eie arrays). After this step is done, the old interrupt file is no longer in use so old intrrupt file VGEIN could be released.

Restoring of old interrupt file state will be done in follow-up patch.

There are cases where it is needed to specify on which cpu it is necessary to VGEIN should be released so update vgein_release() to deal with that.

Beside this being difficult to parse, it looks like it is inapplicable? As said ...

Quoted 7 lines
Quoted 5 lines

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_release() is stub for now and will be introduced later.

... also here?

Agree that paragraph should be dropped, it ins't applicable anymore.

Quoted 7 lines
Quoted 7 lines
xen/arch/riscv/imsic.c +0 -0
@@ -56,6 +56,24 @@ static unsigned int __ro_after_init guest_num_msis;
   */
  #define GUEST_IMSIC_MAX_MSIS 255U
 
Quoted 9 lines

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 64

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+/*
+ * The interrupt identities an IMSIC interrupt file provides are 0 (which is
+ * never valid, but still occupies a bit) up to IMSIC_MAX_ID inclusive, so
+ * IMSIC_MAX_ID + 1 bits have to be covered.
+ */
+#define IMSIC_MAX_EIX DIV_ROUND_UP(IMSIC_MAX_ID + 1, BITS_PER_TYPE(uint64_t))

As before - plain 64 please, or it needs to become clear where the uint64_t is actually coming from.

I will use plain 64.

Quoted 6 lines

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 68

Quoted 4 lines
xen/arch/riscv/imsic.c +3 -0
+struct imsic_mrif_eix {
+    unsigned long eip[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];
+    unsigned long eie[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];

Same here. Yet better may be to use DECLARE_BITMAP()?

It will be better. I'll use:

    DECLARE_BITMAP(eip, 64);
    DECLARE_BITMAP(eie, 64);
Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/imsic.c +0 -0
@@ -85,6 +103,15 @@ do {                            \
      csr_clear(CSR_SIREG, v);    \
  } while (0)
 
Quoted 10 lines

xen/arch/riscv/imsic.c do { \ · line 113

Quoted 8 lines
xen/arch/riscv/imsic.c +8 -0
+#define imsic_vs_csr_swap(c, v)     \
+({                                  \
+    unsigned long r_;               \
+                                    \
+    csr_write(CSR_VSISELECT, (c));  \
+    r_ = csr_swap(CSR_VSIREG, (v)); \
+    r_;                             \
+})

Excess parentheses again. Plus - what use is r_ here?

r_ stands for return value but it should be dropped as it could be done so imsic_vs_csr_swap() just returns a value directly:

#define imsic_vs_csr_swap(c, v)     \
({                                  \
    csr_write(CSR_VSISELECT, c);    \
    csr_swap(CSR_VSIREG, v);        \

})

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/imsic.c +0 -0
@@ -130,6 +157,21 @@ do {                                \
      imsic_switchcase_32(F, ireg + 0, ##__VA_ARGS__) \
      imsic_switchcase_32(F, ireg + 32, ##__VA_ARGS__)
 
Quoted 14 lines

xen/arch/riscv/imsic.c do { \ · line 170

Quoted 11 lines
xen/arch/riscv/imsic.c +11 -0
+static unsigned long imsic_eix_swap(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_ret, IMSIC_EIP0,
+                        imsic_vs_csr_swap, val)
+    imsic_switchcase_64(imsic_switchcase_ret, IMSIC_EIE0,
+                        imsic_vs_csr_swap, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }

There still wants to "break" in the default case.

I'll add.

Quoted 10 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 1075

Quoted 6 lines
xen/arch/riscv/imsic.c +2 -0
@@ -973,5 +1071,11 @@ void imsic_migrate_vcpu(struct vcpu *v)
       * to the new IMSIC VS-file.
       */
 
+    /* Read and clear register state from old IMSIC VS-file */
+    imsic_vsfile_read_clear(old_vsfile_id, old_vsfile_cpu, nr_hw_eix, &tmrif);

Why is &tmrif being passed into the function, when it's not otherwise used here? The function could itself have a suitable local var.

tmrif isn't a scratch buffer local to the read: it carries the register state of the old interrupt file over to the new one. In this patch it's only filled in, but the next patch ("restore register state in the new IMSIC VS-file") passes the same buffer, via vsfile_data.mrif, to imsic_vsfile_local_update() on the new pCPU. By then the old file has been cleared and released, so the state has to live in the caller. I'll add a sentence to this patch's description saying the dumped state is consumed by the following patch:

The state is dumped into a buffer provided by the caller rather than one
local to imsic_vsfile_read_clear(), as it has to outlive the old interrupt file: once that file is released, the state is still needed to be restored into the new interrupt file.

Just to emphasize that in code I will use vsfile_data.mrif instead of &tmrif:

imsic_vsfile_read_clear(old_vsfile_id, old_vsfile_cpu,
vsfile_data.nr_eix, vsfile_data.mrif);

Thanks.

~ Oleksii

#214 lore raw

Re: [PATCH v2 33/39] xen/riscv: dump old interrupt file to memory

In reply to Oleksii Kurochko
Quoted 1 line

At the old interrupt file, dump to memory all the eip and eie arrays).

Typo )

Quoted 10 lines

After this step is done, the old interrupt file is no longer in use so old intrrupt file VGEIN could be released.

Restoring of old interrupt file state will be done in follow-up patch.

There are cases where it is needed to specify on which cpu it is necessary to VGEIN should be released so update vgein_release() to

The sentence miss a verb, here is a proposal:

```
There are cases where the cpu on which the VGEIN is released needs to
be specified, so update vgein_release() to deal with that.
```

Moreover, could you explain me the cases you are talking about? It's not clear by reading the commit message in the first place.

Quoted 55 lines

deal with that.

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard

against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_release() is stub for now and will be introduced later.

xen/arch/riscv/aia.c +5 -0
index 75c82bcfa1..be3901ec0c 100644
@@ -30,3 +30,8 @@ unsigned int vgein_assign(struct vcpu *v)
 
     return 0;
 }
+
+void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
+{
+    BUG_ON("unimplemented\n");
+}
xen/arch/riscv/imsic.c +10 -0
index 5e9f6995e4..3cba58e0c1 100644
@@ -56,6 +56,24 @@ static unsigned int __ro_after_init guest_num_msis;
  */
 #define GUEST_IMSIC_MAX_MSIS 255U
 
+/*
+ * The interrupt identities an IMSIC interrupt file provides are 0 (which is
+ * never valid, but still occupies a bit) up to IMSIC_MAX_ID inclusive, so
+ * IMSIC_MAX_ID + 1 bits have to be covered.
+ */
+#define IMSIC_MAX_EIX DIV_ROUND_UP(IMSIC_MAX_ID + 1, BITS_PER_TYPE(uint64_t))
 
 
+
+struct imsic_mrif_eix {
+    unsigned long eip[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];
+    unsigned long eie[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 76

Quoted 10 lines
xen/arch/riscv/imsic.c +8 -0
 
 
+};
+
+struct imsic_mrif {
+    struct imsic_mrif_eix eix[IMSIC_MAX_EIX];
+    unsigned long eithreshold;
+    unsigned long eidelivery;
+};
+

Maybe I didn't get something but I couldn't find anything in the commit message explaining why do we use mrif here.

Moreover, mrif, as described in aia spec (8.3 Memory-resident interrupt files), seems to be only usable with IOMMU that Xen doesn't support.

If you want to have something in memory that could store some interrupt file info, we should take another name to not be confusing.

Signature · 1 line
Baptiste Le Duc <[email protected]>
#215 lore raw

Re: [PATCH v2 33/39] xen/riscv: dump old interrupt file to memory

Quoted 2 lines · Baptiste Le Duc
Quoted 1 line

At the old interrupt file, dump to memory all the eip and eie arrays).

Typo )

Will drop ).

Quoted 8 lines
Quoted 6 lines

After this step is done, the old interrupt file is no longer in use so old intrrupt file VGEIN could be released.

Restoring of old interrupt file state will be done in follow-up patch.

Quoted 8 lines
Quoted 2 lines

There are cases where it is needed to specify on which cpu it is necessary to VGEIN should be released so update vgein_release() to

The sentence miss a verb, here is a proposal:

```
There are cases where the cpu on which the VGEIN is released needs to
be specified, so update vgein_release() to deal with that.
```

I think it could be dropped at all as vgein_release() stub is just introduced here and not updated.

Quoted 2 lines

Moreover, could you explain me the cases you are talking about? It's not clear by reading the commit message in the first place.

For example, during migration of vCPU, vCPU->processor points to new CPU where it will be run but we still have to free VGEIN on the prev. ->processor.

Quoted 59 lines
Quoted 57 lines

deal with that.

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard

against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_release() is stub for now and will be introduced later.

xen/arch/riscv/aia.c +5 -0
index 75c82bcfa1..be3901ec0c 100644
@@ -30,3 +30,8 @@ unsigned int vgein_assign(struct vcpu *v)
 
      return 0;
  }
+
+void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
+{
+    BUG_ON("unimplemented\n");
+}
xen/arch/riscv/imsic.c +10 -0
index 5e9f6995e4..3cba58e0c1 100644
@@ -56,6 +56,24 @@ static unsigned int __ro_after_init guest_num_msis;
   */
  #define GUEST_IMSIC_MAX_MSIS 255U
 
+/*
+ * The interrupt identities an IMSIC interrupt file provides are 0 (which is
+ * never valid, but still occupies a bit) up to IMSIC_MAX_ID inclusive, so
+ * IMSIC_MAX_ID + 1 bits have to be covered.
+ */
+#define IMSIC_MAX_EIX DIV_ROUND_UP(IMSIC_MAX_ID + 1, BITS_PER_TYPE(uint64_t))
 
 
+
+struct imsic_mrif_eix {
+    unsigned long eip[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];
+    unsigned long eie[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];
Quoted 10 lines

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 76

Quoted 8 lines
xen/arch/riscv/imsic.c +8 -0
+};
+
+struct imsic_mrif {
+    struct imsic_mrif_eix eix[IMSIC_MAX_EIX];
+    unsigned long eithreshold;
+    unsigned long eidelivery;
+};
+

Maybe I didn't get something but I couldn't find anything in the commit message explaining why do we use mrif here.

It is just convenient way to temporary store h/w interrupt file. Also it could be used not only for ...

Quoted 3 lines

Moreover, mrif, as described in aia spec (8.3 Memory-resident interrupt files), seems to be only usable with IOMMU that Xen doesn't support.

... IOMMU but also to support more guest interrupts file implemented by IMSIC (basically what I am calling as software interrupt file). Without memory-resident interrupt files, the number of virtual RISC-V harts that can directly receive MSIs from devices is limited by the total number of guest interrupt files implemented by all IMSICs in the system, because all MSIs to RISC-V harts must go through IMSICs. For a single RISC-V hart, the number of guest interrupt files is the GEILEN parameter defined by the Privileged Architecture, which can be at most 31 for RV32 and 63 for RV64.

Quoted 3 lines

If you want to have something in memory that could store some interrupt file info, we should take another name to not be confusing.

It seems like it is okay to use memory residential interrupt file (mrif) here based on KVM's code who are using mrif for the same purpose I described above.

In short, MRIF is a joint virtualization technology shared between the IOMMU and the hypervisor. The IOMMU uses the MRIF as a memory target to land incoming hardware MSIs, while the hypervisor manages these MRIFs in RAM as software data structures to support an effectively unlimited number of vCPUs that don't currently hold a physical IMSIC guest file slot.

~ Oleksii

#216 lore raw

Re: [PATCH v2 33/39] xen/riscv: dump old interrupt file to memory

Quoted 130 lines · Oleksii Kurochko
Quoted 2 lines · Baptiste Le Duc
Quoted 1 line

At the old interrupt file, dump to memory all the eip and eie arrays).

Typo )

Will drop ).

Quoted 8 lines
Quoted 6 lines

After this step is done, the old interrupt file is no longer in use so old intrrupt file VGEIN could be released.

Restoring of old interrupt file state will be done in follow-up patch.

Quoted 8 lines
Quoted 2 lines

There are cases where it is needed to specify on which cpu it is necessary to VGEIN should be released so update vgein_release() to

The sentence miss a verb, here is a proposal:

```
There are cases where the cpu on which the VGEIN is released needs to
be specified, so update vgein_release() to deal with that.
```

I think it could be dropped at all as vgein_release() stub is just introduced here and not updated.

Quoted 2 lines

Moreover, could you explain me the cases you are talking about? It's not clear by reading the commit message in the first place.

For example, during migration of vCPU, vCPU->processor points to new CPU where it will be run but we still have to free VGEIN on the prev. ->processor.

Quoted 59 lines
Quoted 57 lines

deal with that.

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard

against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_release() is stub for now and will be introduced later.

xen/arch/riscv/aia.c +5 -0
index 75c82bcfa1..be3901ec0c 100644
@@ -30,3 +30,8 @@ unsigned int vgein_assign(struct vcpu *v)
 
      return 0;
  }
+
+void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
+{
+    BUG_ON("unimplemented\n");
+}
xen/arch/riscv/imsic.c +10 -0
index 5e9f6995e4..3cba58e0c1 100644
@@ -56,6 +56,24 @@ static unsigned int __ro_after_init guest_num_msis;
   */
  #define GUEST_IMSIC_MAX_MSIS 255U
 
+/*
+ * The interrupt identities an IMSIC interrupt file provides are 0 (which is
+ * never valid, but still occupies a bit) up to IMSIC_MAX_ID inclusive, so
+ * IMSIC_MAX_ID + 1 bits have to be covered.
+ */
+#define IMSIC_MAX_EIX DIV_ROUND_UP(IMSIC_MAX_ID + 1, BITS_PER_TYPE(uint64_t))
 
 
+
+struct imsic_mrif_eix {
+    unsigned long eip[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];
+    unsigned long eie[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];
Quoted 10 lines

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 76

Quoted 8 lines
xen/arch/riscv/imsic.c +8 -0
+};
+
+struct imsic_mrif {
+    struct imsic_mrif_eix eix[IMSIC_MAX_EIX];
+    unsigned long eithreshold;
+    unsigned long eidelivery;
+};
+

Maybe I didn't get something but I couldn't find anything in the commit message explaining why do we use mrif here.

It is just convenient way to temporary store h/w interrupt file. Also it could be used not only for ...

Quoted 3 lines

Moreover, mrif, as described in aia spec (8.3 Memory-resident interrupt files), seems to be only usable with IOMMU that Xen doesn't support.

... IOMMU but also to support more guest interrupts file implemented by IMSIC (basically what I am calling as software interrupt file). Without memory-resident interrupt files, the number of virtual RISC-V harts that can directly receive MSIs from devices is limited by the total number of guest interrupt files implemented by all IMSICs in the system, because all MSIs to RISC-V harts must go through IMSICs. For a single RISC-V hart, the number of guest interrupt files is the GEILEN parameter defined by the Privileged Architecture, which can be at most 31 for RV32 and 63 for RV64.

Quoted 3 lines

If you want to have something in memory that could store some interrupt file info, we should take another name to not be confusing.

It seems like it is okay to use memory residential interrupt file (mrif) here based on KVM's code who are using mrif for the same purpose I described above.

Quoted 6 lines

In short, MRIF is a joint virtualization technology shared between the IOMMU and the hypervisor. The IOMMU uses the MRIF as a memory target to land incoming hardware MSIs, while the hypervisor manages these MRIFs in RAM as software data structures to support an effectively unlimited number of vCPUs that don't currently hold a physical IMSIC guest file slot.

Yes, I read the spec to understand but here, mrif doesn't catch the MSIs right? so it's not exactly the behaviour mentioned or you have in mind to add full support when IOMMU will be supported?

Quoted 4 lines

~ Oleksii

#217 lore raw

Re: [PATCH v2 33/39] xen/riscv: dump old interrupt file to memory

Quoted 131 lines · Baptiste Le Duc
Quoted 130 lines · Oleksii Kurochko
Quoted 2 lines · Baptiste Le Duc
Quoted 1 line

At the old interrupt file, dump to memory all the eip and eie arrays).

Typo )

Will drop ).

Quoted 8 lines
Quoted 6 lines

After this step is done, the old interrupt file is no longer in use so old intrrupt file VGEIN could be released.

Restoring of old interrupt file state will be done in follow-up patch.

Quoted 8 lines
Quoted 2 lines

There are cases where it is needed to specify on which cpu it is necessary to VGEIN should be released so update vgein_release() to

The sentence miss a verb, here is a proposal:

```
There are cases where the cpu on which the VGEIN is released needs to
be specified, so update vgein_release() to deal with that.
```

I think it could be dropped at all as vgein_release() stub is just introduced here and not updated.

Quoted 2 lines

Moreover, could you explain me the cases you are talking about? It's not clear by reading the commit message in the first place.

For example, during migration of vCPU, vCPU->processor points to new CPU where it will be run but we still have to free VGEIN on the prev. ->processor.

Quoted 59 lines
Quoted 57 lines

deal with that.

Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard

against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.

vgein_release() is stub for now and will be introduced later.

xen/arch/riscv/aia.c +5 -0
index 75c82bcfa1..be3901ec0c 100644
@@ -30,3 +30,8 @@ unsigned int vgein_assign(struct vcpu *v)
 
       return 0;
   }
+
+void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
+{
+    BUG_ON("unimplemented\n");
+}
xen/arch/riscv/imsic.c +10 -0
index 5e9f6995e4..3cba58e0c1 100644
@@ -56,6 +56,24 @@ static unsigned int __ro_after_init guest_num_msis;
    */
   #define GUEST_IMSIC_MAX_MSIS 255U
 
+/*
+ * The interrupt identities an IMSIC interrupt file provides are 0 (which is
+ * never valid, but still occupies a bit) up to IMSIC_MAX_ID inclusive, so
+ * IMSIC_MAX_ID + 1 bits have to be covered.
+ */
+#define IMSIC_MAX_EIX DIV_ROUND_UP(IMSIC_MAX_ID + 1, BITS_PER_TYPE(uint64_t))
 
 
+
+struct imsic_mrif_eix {
+    unsigned long eip[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];
+    unsigned long eie[BITS_PER_TYPE(uint64_t) / BITS_PER_LONG];
Quoted 10 lines

xen/arch/riscv/imsic.c static unsigned int __ro_after_init guest_num_msis; · line 76

Quoted 8 lines
xen/arch/riscv/imsic.c +8 -0
+};
+
+struct imsic_mrif {
+    struct imsic_mrif_eix eix[IMSIC_MAX_EIX];
+    unsigned long eithreshold;
+    unsigned long eidelivery;
+};
+

Maybe I didn't get something but I couldn't find anything in the commit message explaining why do we use mrif here.

It is just convenient way to temporary store h/w interrupt file. Also it could be used not only for ...

Quoted 3 lines

Moreover, mrif, as described in aia spec (8.3 Memory-resident interrupt files), seems to be only usable with IOMMU that Xen doesn't support.

... IOMMU but also to support more guest interrupts file implemented by IMSIC (basically what I am calling as software interrupt file). Without memory-resident interrupt files, the number of virtual RISC-V harts that can directly receive MSIs from devices is limited by the total number of guest interrupt files implemented by all IMSICs in the system, because all MSIs to RISC-V harts must go through IMSICs. For a single RISC-V hart, the number of guest interrupt files is the GEILEN parameter defined by the Privileged Architecture, which can be at most 31 for RV32 and 63 for RV64.

Quoted 3 lines

If you want to have something in memory that could store some interrupt file info, we should take another name to not be confusing.

It seems like it is okay to use memory residential interrupt file (mrif) here based on KVM's code who are using mrif for the same purpose I described above.

Quoted 8 lines
Quoted 6 lines

In short, MRIF is a joint virtualization technology shared between the IOMMU and the hypervisor. The IOMMU uses the MRIF as a memory target to land incoming hardware MSIs, while the hypervisor manages these MRIFs in RAM as software data structures to support an effectively unlimited number of vCPUs that don't currently hold a physical IMSIC guest file slot.

Yes, I read the spec to understand but here, mrif doesn't catch the MSIs right?

Yes, because right now only h/w if(s) are supported. For now it is just a storage where we are saving temporary h/w interrupt file (which has the same structure as MRIF).
When s/w if(s) will be supported we will need to store somewhere an interrupt file in RAM and considering that the structure of h/w if == s/w if and basically == mrif thereby mrif is a good candidate. Even more, ...

Quoted 2 lines

so it's not exactly the behaviour mentioned or you have in mind to add full support when IOMMU will be supported?

... IOMMU points to the the same structure so again h/w if == s/w if == mrif from organization point of you.

And answering your question we have in mind to support IOMMU for IMSIC purposes and then we still will need mrif structure.

~ Oleksii

#218 lore raw

PATCH v2 34/39 xen/riscv: restore register state in the new IMSIC VS-file

In reply to Oleksii Kurochko

At this point, all interrupt producers have been moved to the new IMSIC VS-file so we move register state from the old IMSIC VS/SW-file to the new IMSIC VS-file.

As new IMSIC VS-file is ready to be used update vCPU's hstatus with new VGEIN.

As the whole migration procedure is finished add some extra explanatory comments.

---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/imsic.c | 82 ++++++++++++++++++++++++++++++++++++++----
 1 file changed, 76 insertions(+), 6 deletions(-)
xen/arch/riscv/imsic.c +76 -6
index 3cba58e0c1b3..d7b137a1f559 100644
@@ -112,6 +112,12 @@ do {                            \
     r_;                             \
 })
 
+#define imsic_vs_csr_set(c, v)      \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_set(CSR_VSIREG, (v));       \
+} while ( 0 )
+
 #define imsic_vs_csr_write(c, v)    \
 do {                                \
     csr_write(CSR_VSISELECT, (c));  \
@@ -185,6 +191,19 @@ static void imsic_eix_write(unsigned int ireg, unsigned long val)
     }
 }
 
+static void imsic_eix_set(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_set, val)
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_set, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }
+}
+
 unsigned int vcpu_guest_file_id(const struct vcpu *v)
 {
     return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
@@ -630,13 +649,13 @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
     old_vsiselect = csr_read(CSR_VSISELECT);
     old_hstatus = csr_read(CSR_HSTATUS);
     new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
-    new_hstatus |= ((unsigned long)idata->hgei) << HSTATUS_VGEIN_SHIFT;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
     csr_write(CSR_HSTATUS, new_hstatus);
 
     /*
-     * There is no need to use atomic functions version to store
-     * values in MRIF because imsic_vsfile_read_clear() is always called
-     * with pointer to temporary MRIF on stack.
+     * No atomic accessors are needed to store the values into the MRIF here,
+     * as imsic_vsfile_read_clear() is always called with a pointer to a
+     * temporary MRIF on the stack.
      */
 
     mrif->eidelivery = imsic_vs_csr_swap(IMSIC_EIDELIVERY, 0);
@@ -972,6 +991,49 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
     return fdt_end_node(fdt);
 }
 
+static void cf_check imsic_vsfile_local_update(void *data)
+{
+    unsigned int i;
+    struct imsic_mrif_eix *eix;
+    const struct imsic_vsfile_data *idata = data;
+    struct imsic_mrif *mrif = idata->mrif;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only update if we have a HW IMSIC context */
+    if ( !idata->hgei )
+        return;
+
+    /*
+     * No atomic accessors are needed to read the values out of the MRIF here,
+     * as this is always called with a pointer to a temporary MRIF on the
+     * stack.
+     */
+
+    old_vsiselect = csr_read(CSR_VSISELECT);
+    old_hstatus = csr_read(CSR_HSTATUS);
+    new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
+    csr_write(CSR_HSTATUS, new_hstatus);
+
+    for ( i = 0; i < idata->nr_eix; i++ )
+    {
+        eix = &mrif->eix[i];
+
+        imsic_eix_set(IMSIC_EIP0 + i * 2, eix->eip[0]);
+        imsic_eix_set(IMSIC_EIE0 + i * 2, eix->eie[0]);
+#ifdef CONFIG_RISCV_32
+        imsic_eix_set(IMSIC_EIP0 + i * 2 + 1, eix->eip[1]);
+        imsic_eix_set(IMSIC_EIE0 + i * 2 + 1, eix->eie[1]);
+#endif
+    }
+
+    imsic_vs_csr_write(IMSIC_EITHRESHOLD, mrif->eithreshold);
+    imsic_vs_csr_write(IMSIC_EIDELIVERY, mrif->eidelivery);
+
+    csr_write(CSR_HSTATUS, old_hstatus);
+    csr_write(CSR_VSISELECT, old_vsiselect);
+}
+
 void imsic_migrate_vcpu(struct vcpu *v)
 {
     unsigned int new_vsfile_hgei;
@@ -1068,7 +1130,8 @@ void imsic_migrate_vcpu(struct vcpu *v)
 
     /*
      * At this point, all interrupt producers have been moved
-     * to the new IMSIC VS-file.
+     * to the new IMSIC VS-file so we move register state from
+     * the old IMSIC VS/SW-file to the new IMSIC VS-file.
      */
 
     /* Read and clear register state from old IMSIC VS-file */
@@ -1077,5 +1140,12 @@ void imsic_migrate_vcpu(struct vcpu *v)
     /* Free-up old IMSIC VS-file */
     vgein_release(v, old_vsfile_id, old_vsfile_cpu);
 
-    BUG_ON("unimplemented");
+    /* Restore register state in the new IMSIC VS-file */
+    vsfile_data.mrif = &tmrif;
+    imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_update, &vsfile_data);
+
+    /* Set VCPU HSTATUS.VGEIN to new IMSIC VS-file */
+    vcpu_guest_cpu_user_regs(v)->hstatus &= ~HSTATUS_VGEIN;
+    vcpu_guest_cpu_user_regs(v)->hstatus |=
+            MASK_INSR(new_vsfile_hgei, HSTATUS_VGEIN);
 }
Signature · 1 line
2.55.0
#219 lore raw

Re: [PATCH v2 34/39] xen/riscv: restore register state in the new IMSIC VS-file

xen/arch/riscv/imsic.c static void cf_check imsic_vsfile_local_read_clear(void *data) · line 652

Quoted 6 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +1 -1
@@ -630,13 +649,13 @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
     old_vsiselect = csr_read(CSR_VSISELECT);
     old_hstatus = csr_read(CSR_HSTATUS);
     new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
-    new_hstatus |= ((unsigned long)idata->hgei) << HSTATUS_VGEIN_SHIFT;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);

Please put into final shape upon introduction.

xen/arch/riscv/imsic.c static void cf_check imsic_vsfile_local_read_clear(void *data) · line 659

Quoted 10 lines
xen/arch/riscv/imsic.c +3 -3
     csr_write(CSR_HSTATUS, new_hstatus);
 
     /*
-     * There is no need to use atomic functions version to store
-     * values in MRIF because imsic_vsfile_read_clear() is always called
-     * with pointer to temporary MRIF on stack.
+     * No atomic accessors are needed to store the values into the MRIF here,
+     * as imsic_vsfile_read_clear() is always called with a pointer to a
+     * temporary MRIF on the stack.
      */

Same for this comment perhaps.

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 1144

Quoted 7 lines
xen/arch/riscv/imsic.c +2 -1
@@ -1077,5 +1140,12 @@ void imsic_migrate_vcpu(struct vcpu *v)
     /* Free-up old IMSIC VS-file */
     vgein_release(v, old_vsfile_id, old_vsfile_cpu);
 
-    BUG_ON("unimplemented");
+    /* Restore register state in the new IMSIC VS-file */
+    vsfile_data.mrif = &tmrif;

Ah, here &tmrif is used a 2nd time.

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 1150

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+    imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_update, &vsfile_data);
+
+    /* Set VCPU HSTATUS.VGEIN to new IMSIC VS-file */
+    vcpu_guest_cpu_user_regs(v)->hstatus &= ~HSTATUS_VGEIN;
+    vcpu_guest_cpu_user_regs(v)->hstatus |=
+            MASK_INSR(new_vsfile_hgei, HSTATUS_VGEIN);

Nit: Indentation.

Other comments on earlier patches apply here (and possibly elsewhere) as well. Just ftaod.

Jan

#220 lore raw

Re: [PATCH v2 34/39] xen/riscv: restore register state in the new IMSIC VS-file

Quoted 9 lines · Jan Beulich

xen/arch/riscv/imsic.c static void cf_check imsic_vsfile_local_read_clear(void *data) · line 652

Quoted 6 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +1 -1
@@ -630,13 +649,13 @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
      old_vsiselect = csr_read(CSR_VSISELECT);
      old_hstatus = csr_read(CSR_HSTATUS);
      new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
-    new_hstatus |= ((unsigned long)idata->hgei) << HSTATUS_VGEIN_SHIFT;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);

Please put into final shape upon introduction.

Oh, right, this ...

Quoted 12 lines

xen/arch/riscv/imsic.c static void cf_check imsic_vsfile_local_read_clear(void *data) · line 659

Quoted 11 lines
xen/arch/riscv/imsic.c +3 -3
      csr_write(CSR_HSTATUS, new_hstatus);
 
      /*
-     * There is no need to use atomic functions version to store
-     * values in MRIF because imsic_vsfile_read_clear() is always called
-     * with pointer to temporary MRIF on stack.
+     * No atomic accessors are needed to store the values into the MRIF here,
+     * as imsic_vsfile_read_clear() is always called with a pointer to a
+     * temporary MRIF on the stack.
       */
Quoted 1 line

Same for this comment perhaps.

... and this should be part of prev. patch.

Quoted 10 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 1144

Quoted 8 lines
xen/arch/riscv/imsic.c +2 -1
@@ -1077,5 +1140,12 @@ void imsic_migrate_vcpu(struct vcpu *v)
      /* Free-up old IMSIC VS-file */
      vgein_release(v, old_vsfile_id, old_vsfile_cpu);
 
-    BUG_ON("unimplemented");
+    /* Restore register state in the new IMSIC VS-file */
+    vsfile_data.mrif = &tmrif;

Ah, here &tmrif is used a 2nd time.

I think it could be dropped and just properly init vsfile_data.mrif during declaration:

    struct imsic_vsfile_data vsfile_data = {
        .nr_eix = imsic_nr_eix(),
        .mrif = &(struct imsic_mrif){ },
    };

and then use vsfile.mrif instead of &tmrif.

Quoted 8 lines

xen/arch/riscv/imsic.c void imsic_migrate_vcpu(struct vcpu *v) · line 1150

Quoted 7 lines
xen/arch/riscv/imsic.c +6 -0
+    imsic_call_on_cpu(new_vsfile_cpu, imsic_vsfile_local_update, &vsfile_data);
+
+    /* Set VCPU HSTATUS.VGEIN to new IMSIC VS-file */
+    vcpu_guest_cpu_user_regs(v)->hstatus &= ~HSTATUS_VGEIN;
+    vcpu_guest_cpu_user_regs(v)->hstatus |=
+            MASK_INSR(new_vsfile_hgei, HSTATUS_VGEIN);
Quoted 4 lines

Nit: Indentation.

Other comments on earlier patches apply here (and possibly elsewhere) as well. Just ftaod.

I will fix them.

Thanks.

~ Oleksii

#221 lore raw

Re: [PATCH v2 34/39] xen/riscv: restore register state in the new IMSIC VS-file

In reply to Oleksii Kurochko
Quoted 82 lines

At this point, all interrupt producers have been moved to the new IMSIC VS-file so we move register state from the old IMSIC VS/SW-file to the new IMSIC VS-file.

As new IMSIC VS-file is ready to be used update vCPU's hstatus with new VGEIN.

As the whole migration procedure is finished add some extra explanatory comments.

xen/arch/riscv/imsic.c +23 -4
index 3cba58e0c1..d7b137a1f5 100644
@@ -112,6 +112,12 @@ do {                            \
     r_;                             \
 })
 
+#define imsic_vs_csr_set(c, v)      \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_set(CSR_VSIREG, (v));       \
+} while ( 0 )
+
 #define imsic_vs_csr_write(c, v)    \
 do {                                \
     csr_write(CSR_VSISELECT, (c));  \
@@ -185,6 +191,19 @@ static void imsic_eix_write(unsigned int ireg, unsigned long val)
     }
 }
 
+static void imsic_eix_set(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_set, val)
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_set, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }
+}
+
 unsigned int vcpu_guest_file_id(const struct vcpu *v)
 {
     return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
@@ -630,13 +649,13 @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
     old_vsiselect = csr_read(CSR_VSISELECT);
     old_hstatus = csr_read(CSR_HSTATUS);
     new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
-    new_hstatus |= ((unsigned long)idata->hgei) << HSTATUS_VGEIN_SHIFT;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
 
 
     csr_write(CSR_HSTATUS, new_hstatus);
 
     /*
-     * There is no need to use atomic functions version to store
-     * values in MRIF because imsic_vsfile_read_clear() is always called
-     * with pointer to temporary MRIF on stack.
+     * No atomic accessors are needed to store the values into the MRIF here,
+     * as imsic_vsfile_read_clear() is always called with a pointer to a
+     * temporary MRIF on the stack.
      */

 
     mrif->eidelivery = imsic_vs_csr_swap(IMSIC_EIDELIVERY, 0);
xen/arch/riscv/imsic.c +7 -0
@@ -972,6 +991,49 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
     return fdt_end_node(fdt);
 }
 
+static void cf_check imsic_vsfile_local_update(void *data)
+{
+    unsigned int i;
+    struct imsic_mrif_eix *eix;
+    const struct imsic_vsfile_data *idata = data;
+    struct imsic_mrif *mrif = idata->mrif;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 1010

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+
+    /* We can only update if we have a HW IMSIC context */
+    if ( !idata->hgei )
+        return;
+
+    /*
+     * No atomic accessors are needed to read the values out of the MRIF here,
+     * as this is always called with a pointer to a temporary MRIF on the
+     * stack.
+     */

idata->mrif may point anywhere, so what the comment really states is a requirement on callers. It also only makes full sense next to KVM, where a shared SW-file MRIF is accessed atomically; Xen has neither of those (yet). Either explicitely explain that callers must declare mrif on their stack or move the comment directly in call sites.

Signature · 1 line
Baptiste Le Duc <[email protected]>
#222 lore raw

Re: [PATCH v2 34/39] xen/riscv: restore register state in the new IMSIC VS-file

Quoted 89 lines · Baptiste Le Duc
Quoted 89 lines

At this point, all interrupt producers have been moved to the new IMSIC VS-file so we move register state from the old IMSIC VS/SW-file to the new IMSIC VS-file.

As new IMSIC VS-file is ready to be used update vCPU's hstatus with new VGEIN.

As the whole migration procedure is finished add some extra explanatory comments.

xen/arch/riscv/imsic.c +23 -4
index 3cba58e0c1..d7b137a1f5 100644
@@ -112,6 +112,12 @@ do {                            \
      r_;                             \
  })
 
+#define imsic_vs_csr_set(c, v)      \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_set(CSR_VSIREG, (v));       \
+} while ( 0 )
+
  #define imsic_vs_csr_write(c, v)    \
  do {                                \
      csr_write(CSR_VSISELECT, (c));  \
@@ -185,6 +191,19 @@ static void imsic_eix_write(unsigned int ireg, unsigned long val)
      }
  }
 
+static void imsic_eix_set(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_set, val)
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_set, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }
+}
+
  unsigned int vcpu_guest_file_id(const struct vcpu *v)
  {
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
@@ -630,13 +649,13 @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
      old_vsiselect = csr_read(CSR_VSISELECT);
      old_hstatus = csr_read(CSR_HSTATUS);
      new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
-    new_hstatus |= ((unsigned long)idata->hgei) << HSTATUS_VGEIN_SHIFT;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
 
 
      csr_write(CSR_HSTATUS, new_hstatus);
 
      /*
-     * There is no need to use atomic functions version to store
-     * values in MRIF because imsic_vsfile_read_clear() is always called
-     * with pointer to temporary MRIF on stack.
+     * No atomic accessors are needed to store the values into the MRIF here,
+     * as imsic_vsfile_read_clear() is always called with a pointer to a
+     * temporary MRIF on the stack.
       */

  
      mrif->eidelivery = imsic_vs_csr_swap(IMSIC_EIDELIVERY, 0);
xen/arch/riscv/imsic.c +14 -0
@@ -972,6 +991,49 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
      return fdt_end_node(fdt);
  }
 
+static void cf_check imsic_vsfile_local_update(void *data)
+{
+    unsigned int i;
+    struct imsic_mrif_eix *eix;
+    const struct imsic_vsfile_data *idata = data;
+    struct imsic_mrif *mrif = idata->mrif;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only update if we have a HW IMSIC context */
+    if ( !idata->hgei )
+        return;
+
+    /*
+     * No atomic accessors are needed to read the values out of the MRIF here,
Quoted 8 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 1010

Quoted 3 lines
xen/arch/riscv/imsic.c +3 -0
+     * as this is always called with a pointer to a temporary MRIF on the
+     * stack.
+     */

idata->mrif may point anywhere, so what the comment really states is a requirement on callers. It also only makes full sense next to KVM, where a shared SW-file MRIF is accessed atomically; Xen has neither of those (yet). Either explicitely explain that callers must declare mrif on their stack or move the comment directly in call sites.

It is mentioned in the comment "is always called with a pointer to a temporary MRIF on the stack.".

With SW-file MRIF I expect that atomic operations should be used so this functions shouldn't just use for them and I assume KVM has something different function to work with SW-file MRIF. Anyway just mentioning KVM code isn't always useful as it forces me to go and investigate what is going on there what I am not fully convinced that it is okay...

~ Oleksii

#223 lore raw

Re: [PATCH v2 34/39] xen/riscv: restore register state in the new IMSIC VS-file

Quoted 101 lines · Oleksii Kurochko
Quoted 89 lines · Baptiste Le Duc
Quoted 89 lines

At this point, all interrupt producers have been moved to the new IMSIC VS-file so we move register state from the old IMSIC VS/SW-file to the new IMSIC VS-file.

As new IMSIC VS-file is ready to be used update vCPU's hstatus with new VGEIN.

As the whole migration procedure is finished add some extra explanatory comments.

xen/arch/riscv/imsic.c +23 -4
index 3cba58e0c1..d7b137a1f5 100644
@@ -112,6 +112,12 @@ do {                            \
      r_;                             \
  })
 
+#define imsic_vs_csr_set(c, v)      \
+do {                                \
+    csr_write(CSR_VSISELECT, (c));  \
+    csr_set(CSR_VSIREG, (v));       \
+} while ( 0 )
+
  #define imsic_vs_csr_write(c, v)    \
  do {                                \
      csr_write(CSR_VSISELECT, (c));  \
@@ -185,6 +191,19 @@ static void imsic_eix_write(unsigned int ireg, unsigned long val)
      }
  }
 
+static void imsic_eix_set(unsigned int ireg, unsigned long val)
+{
+    switch ( ireg )
+    {
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIP0,
+                        imsic_vs_csr_set, val)
+    imsic_switchcase_64(imsic_switchcase_break, IMSIC_EIE0,
+                        imsic_vs_csr_set, val)
+    default:
+        ASSERT_UNREACHABLE();
+    }
+}
+
  unsigned int vcpu_guest_file_id(const struct vcpu *v)
  {
      return ACCESS_ONCE(v->arch.vimsic_state->guest_file_id);
@@ -630,13 +649,13 @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
      old_vsiselect = csr_read(CSR_VSISELECT);
      old_hstatus = csr_read(CSR_HSTATUS);
      new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
-    new_hstatus |= ((unsigned long)idata->hgei) << HSTATUS_VGEIN_SHIFT;
+    new_hstatus |= MASK_INSR(idata->hgei, HSTATUS_VGEIN);
 
 
      csr_write(CSR_HSTATUS, new_hstatus);
 
      /*
-     * There is no need to use atomic functions version to store
-     * values in MRIF because imsic_vsfile_read_clear() is always called
-     * with pointer to temporary MRIF on stack.
+     * No atomic accessors are needed to store the values into the MRIF here,
+     * as imsic_vsfile_read_clear() is always called with a pointer to a
+     * temporary MRIF on the stack.
       */

  
      mrif->eidelivery = imsic_vs_csr_swap(IMSIC_EIDELIVERY, 0);
xen/arch/riscv/imsic.c +14 -0
@@ -972,6 +991,49 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
      return fdt_end_node(fdt);
  }
 
+static void cf_check imsic_vsfile_local_update(void *data)
+{
+    unsigned int i;
+    struct imsic_mrif_eix *eix;
+    const struct imsic_vsfile_data *idata = data;
+    struct imsic_mrif *mrif = idata->mrif;
+    unsigned long new_hstatus, old_hstatus, old_vsiselect;
+
+    /* We can only update if we have a HW IMSIC context */
+    if ( !idata->hgei )
+        return;
+
+    /*
+     * No atomic accessors are needed to read the values out of the MRIF here,
Quoted 8 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 1010

Quoted 3 lines
xen/arch/riscv/imsic.c +3 -0
+     * as this is always called with a pointer to a temporary MRIF on the
+     * stack.
+     */

idata->mrif may point anywhere, so what the comment really states is a requirement on callers. It also only makes full sense next to KVM, where a shared SW-file MRIF is accessed atomically; Xen has neither of those (yet). Either explicitely explain that callers must declare mrif on their stack or move the comment directly in call sites.

Quoted 2 lines

It is mentioned in the comment "is always called with a pointer to a temporary MRIF on the stack.".

Oh okay, I think I misunderstood the comment at the first place then. I thought you wanted to say the pointer itself is on the stack, not MRIF. Now it's more clear.

Quoted 6 lines

With SW-file MRIF I expect that atomic operations should be used so this functions shouldn't just use for them and I assume KVM has something different function to work with SW-file MRIF. Anyway just mentioning KVM code isn't always useful as it forces me to go and investigate what is going on there what I am not fully convinced that it is okay...

Yes sorry, no needs for more investigations here.

Quoted 6 lines

~ Oleksii

#224 lore raw

PATCH v2 35/39 xen/riscv: add basic VGEIN management for AIA guests

In reply to Oleksii Kurochko

It was decided to add support for IMSIC from the start instead of having APLIC operate in direct delivery mode, as it requires a trap-and-emulation approach, which is not optimal from a performance standpoint.

AIA provides a hardware-accelerated mechanism for delivering external interrupts to domains via "guest interrupt files" located in IMSIC. A single physical hart can implement multiple such files (up to GEILEN), allowing several virtual harts to receive interrupts directly from hardware.

Introduce per-CPU tracking of guest interrupt file identifiers (VGEIN) for systems implementing AIA specification. Each CPU maintains a bitmap describing which guest interrupt files are currently in use.

Implement helpers to initialize the bitmap based on the number of available guest interrupt files (GEILEN), assign a VGEIN to a vCPU, and release it when no longer needed.

---
Also in the next patch there is other context to understand the usage of spinlock introduced here.
---
Changes in v2:
- make vgein_init() pCPU agnostic as it is working with CSR which could be read only on local pCPU itself.
- Move introduction of vgein_ctrl->owners[] to separate patch.
- Add ASSERT() and re-init vgein->bmp with 0.
- Update the commit message (drop the last sentence as ->hstatus isn't filled anymore in in vgein_*() functions).
- Introduce vgein_deinit().
---

---
 xen/arch/riscv/aia.c | 141 +++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 137 insertions(+), 4 deletions(-)
xen/arch/riscv/aia.c +137 -4
index be3901ec0cfa..1aca07c2f70f 100644
@@ -1,13 +1,31 @@
 /* SPDX-License-Identifier: GPL-2.0-only */
 
-#include <xen/bug.h>
+#include <xen/bitops.h>
+#include <xen/cpu.h>
 #include <xen/errno.h>
 #include <xen/init.h>
 #include <xen/sections.h>
 #include <xen/sched.h>
+#include <xen/spinlock.h>
 #include <xen/types.h>
 
+#include <asm/aia.h>
 #include <asm/cpufeature.h>
+#include <asm/csr.h>
+#include <asm/current.h>
+
+struct vgein_ctrl {
+    /* The least-significant bits are implemented first, apart from bit 0 */
+    unsigned long bmp;
+    spinlock_t lock;
+    unsigned int geilen;
+};
+
+/*
+ * VGEIN control structure for each physical CPU to track which VS (guest)
+ * interrupt file IDs are in use.
+ */
+static DEFINE_PER_CPU(struct vgein_ctrl, vgein);
 
 static bool __ro_after_init _aia_usable;
 
@@ -16,22 +34,137 @@ bool aia_usable(void)
     return _aia_usable;
 }
 
+/* HGEIE is a per-hart CSR, so this has to run on the CPU being initialized. */
+static int vgein_init(void)
+{
+    struct vgein_ctrl *vgein = &this_cpu(vgein);
+
+    spin_lock_init(&vgein->lock);
+
+    csr_write(CSR_HGEIE, ~0UL);
+    vgein->geilen = flsl(csr_read(CSR_HGEIE) >> 1);
+    csr_write(CSR_HGEIE, 0);
+
+    vgein->bmp = 0;
+
+    if ( !vgein->geilen )
+        return -EOPNOTSUPP;
+
+    return 0;
+}
+
+static void vgein_deinit(void)
+{
+    csr_write(CSR_HGEIE, 0);
+}
+
+static int cf_check cpu_callback(struct notifier_block *nfb,
+                                 unsigned long action, void *hcpu)
+{
+    unsigned int cpu = (unsigned long)hcpu;
+    int rc = 0;
+
+    switch ( action )
+    {
+    case CPU_STARTING:
+        rc = vgein_init();
+        if ( rc )
+            printk(XENLOG_ERR "AIA: failed to init vgein for CPU%u: %d\n",
+                   cpu, rc);
+        break;
+
+    case CPU_DYING:
+        vgein_deinit();
+        break;
+    }
+
+    return notifier_from_errno(rc);
+}
+
+static struct notifier_block cpu_nfb = {
+    .notifier_call = cpu_callback,
+};
+
 void __init aia_init(void)
 {
+    int rc;
+
     if ( !riscv_isa_extension_available(NULL, RISCV_ISA_EXT_ssaia) )
+    {
+        dprintk(XENLOG_WARNING, "SSAIA isn't present in riscv,isa\n");
         return;
+    }
+
+    if ( (rc = vgein_init()) )
+    {
+        dprintk(XENLOG_ERR, "vgein_init() failed: %d\n", rc);
+        return;
+    }
 
     _aia_usable = true;
+
+    register_cpu_notifier(&cpu_nfb);
 }
 
 unsigned int vgein_assign(struct vcpu *v)
 {
-    BUG_ON("unimplemented\n");
+    unsigned int vgein_id;
+    struct vgein_ctrl *vgein = &per_cpu(vgein, v->processor);
+    unsigned long *bmp = &vgein->bmp;
+    unsigned long flags;
 
-    return 0;
+    if ( !vgein->geilen )
+        return 0;
+
+    spin_lock_irqsave(&vgein->lock, flags);
+    /*
+     * The vgein_id shouldn't be zero, as it will indicate that no guest
+     * external interrupt source is selected for VS-level external interrupts
+     * according to RISC-V privileged spec:
+     *   Hypervisor Status Register (hstatus) in RISC-V privileged spec:
+     *
+     *   The VGEIN (Virtual Guest External Interrupt Number) field selects
+     *   a guest external interrupt source for VS-level external interrupts.
+     *   VGEIN is a WLRL field that must be able to hold values between zero
+     *   and the maximum guest external interrupt number (known as GEILEN),
+     *   inclusive.
+     *   When VGEIN=0, no guest external interrupt source is selected for
+     *   VS-level external interrupts.
+     *
+     * So start to search from bit number 1.
+     */
+    vgein_id = find_next_zero_bit(bmp, vgein->geilen + 1, 1);
+
+    if ( vgein_id > vgein->geilen )
+        vgein_id = 0;
+    else
+        __set_bit(vgein_id, bmp);
+
+    spin_unlock_irqrestore(&vgein->lock, flags);
+
+#ifdef VGEIN_DEBUG
+    gprintk(XENLOG_DEBUG, "%s: %pv: vgein_id(%u), xen_cpu%u_bmp=%#lx\n",
+            __func__, v, vgein_id, v->processor, *bmp);
+#endif
+
+    return vgein_id;
 }
 
 void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
 {
-    BUG_ON("unimplemented\n");
+    unsigned long flags;
+    struct vgein_ctrl *vgein = &per_cpu(vgein, cpu);
+
+    if ( !vgein_id )
+        return;
+
+    spin_lock_irqsave(&vgein->lock, flags);
+    if ( !__test_and_clear_bit(vgein_id, &vgein->bmp) )
+        ASSERT_UNREACHABLE();
+    spin_unlock_irqrestore(&vgein->lock, flags);
+
+#ifdef VGEIN_DEBUG
+    gprintk(XENLOG_DEBUG, "%s: %pv: vgein_id(%u), xen_cpu%u_bmp=%#lx\n",
+            __func__, v, vgein_id, cpu, vgein->bmp);
+#endif
 }
Signature · 1 line
2.55.0
Acked-by on v2 35/39
#225 lore raw

Re: [PATCH v2 35/39] xen/riscv: add basic VGEIN management for AIA guests

Quoted 13 lines · Oleksii Kurochko

It was decided to add support for IMSIC from the start instead of having APLIC operate in direct delivery mode, as it requires a trap-and-emulation approach, which is not optimal from a performance standpoint.

AIA provides a hardware-accelerated mechanism for delivering external interrupts to domains via "guest interrupt files" located in IMSIC. A single physical hart can implement multiple such files (up to GEILEN), allowing several virtual harts to receive interrupts directly from hardware.

Introduce per-CPU tracking of guest interrupt file identifiers (VGEIN) for systems implementing AIA specification. Each CPU maintains a bitmap describing which guest interrupt files are currently in use.

Quoted 5 lines

Implement helpers to initialize the bitmap based on the number of available guest interrupt files (GEILEN), assign a VGEIN to a vCPU, and release it when no longer needed.

Reviewed-by on v2 35/39
#226 lore raw

Re: [PATCH v2 35/39] xen/riscv: add basic VGEIN management for AIA guests

In reply to Oleksii Kurochko
Quoted 10 lines · Oleksii Kurochko

It was decided to add support for IMSIC from the start instead of having APLIC operate in direct delivery mode, as it requires a trap-and-emulation approach, which is not optimal from a performance standpoint.

AIA provides a hardware-accelerated mechanism for delivering external interrupts to domains via "guest interrupt files" located in IMSIC. A single physical hart can implement multiple such files (up to GEILEN), allowing several virtual harts to receive interrupts directly from hardware.

[...]

Signature · 1 line
Baptiste Le Duc <[email protected]>
#227 lore raw

PATCH v2 36/39 xen/riscv: wake up a descheduled vCPU on a guest external interrupt

In reply to Oleksii Kurochko

While a vCPU is running, MSIs written to its h/w IMSIC guest interrupt file are delivered straight to VS-mode. Once the vCPU is descheduled nobody observes that file anymore, so a guest blocked on such an interrupt would stay blocked until some unrelated event happens to schedule it again.

Let Xen observe the file in that window: on deschedule set the vCPU's bit in HGEIE, which turns an interrupt pending in its VS-file into an HS-level SGEI, and clear the bit again on schedule-in. HGEIP only reports a file number, so to get from it back to a vCPU keep an owners[] map per pCPU, filled by vgein_{assign,release} alongside the VGEIN bitmap, and kick the vCPU it points at.

v->arch.hie is only initialized here and is written to the CSR later, on the context switch to the vCPU.

vgein_release() still has no caller: a vCPU going away has to both free its VGEIN slot and drop the owners[] entry, but there is no vCPU teardown path to hook it into yet. vgein_deinit() only covers a pCPU going offline.

---
Changes in v2:
- New patch.
---

---
 xen/arch/riscv/aia.c                | 52 +++++++++++++++++++++++++--
 xen/arch/riscv/domain.c             |  3 ++
 xen/arch/riscv/imsic.c              | 55 ++++++++++++++++++++++++++++-
 xen/arch/riscv/include/asm/aia.h    |  2 ++
 xen/arch/riscv/include/asm/domain.h |  1 +
 xen/arch/riscv/traps.c              |  7 +++-
 6 files changed, 115 insertions(+), 5 deletions(-)
xen/arch/riscv/aia.c +49 -3
index 1aca07c2f70f..9642a9796ead 100644
@@ -18,6 +18,13 @@ struct vgein_ctrl {
     /* The least-significant bits are implemented first, apart from bit 0 */
     unsigned long bmp;
     spinlock_t lock;
+    /*
+     * Guest interrupt file IDs run from 1 to geilen inclusive (0 means that
+     * no guest external interrupt source is selected), and geilen can never
+     * exceed BITS_PER_LONG - 1, so indexing this array by the ID directly
+     * always fits.
+     */
+    struct vcpu *owners[BITS_PER_LONG];
     unsigned int geilen;
 };
 
@@ -62,23 +69,25 @@ static int cf_check cpu_callback(struct notifier_block *nfb,
                                  unsigned long action, void *hcpu)
 {
     unsigned int cpu = (unsigned long)hcpu;
-    int rc = 0;
 
     switch ( action )
     {
     case CPU_STARTING:
-        rc = vgein_init();
+    {
+        int rc = vgein_init();
+
         if ( rc )
             printk(XENLOG_ERR "AIA: failed to init vgein for CPU%u: %d\n",
                    cpu, rc);
         break;
+    }
 
     case CPU_DYING:
         vgein_deinit();
         break;
     }
 
-    return notifier_from_errno(rc);
+    return NOTIFY_DONE;
 }
 
 static struct notifier_block cpu_nfb = {
@@ -138,7 +147,10 @@ unsigned int vgein_assign(struct vcpu *v)
     if ( vgein_id > vgein->geilen )
         vgein_id = 0;
     else
+    {
         __set_bit(vgein_id, bmp);
+        vgein->owners[vgein_id] = v;
+    }
 
     spin_unlock_irqrestore(&vgein->lock, flags);
 
@@ -161,6 +173,7 @@ void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
     spin_lock_irqsave(&vgein->lock, flags);
     if ( !__test_and_clear_bit(vgein_id, &vgein->bmp) )
         ASSERT_UNREACHABLE();
+    vgein->owners[vgein_id] = NULL;
     spin_unlock_irqrestore(&vgein->lock, flags);
 
 #ifdef VGEIN_DEBUG
@@ -168,3 +181,36 @@ void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
             __func__, v, vgein_id, cpu, vgein->bmp);
 #endif
 }
+
+void hgei_interrupt(void)
+{
+    unsigned long hgei_mask, flags;
+    struct vgein_ctrl *vgein = &this_cpu(vgein);
+
+    hgei_mask = csr_read(CSR_HGEIP) & csr_read(CSR_HGEIE);
+    csr_clear(CSR_HGEIE, hgei_mask);
+
+    spin_lock_irqsave(&vgein->lock, flags);
+
+    for_each_set_bit ( guest_file_id, hgei_mask )
+    {
+        /*
+         * guest_file_id shouldn't be zero, as it will indicate that no
+         * guest external interrupt source is selected for VS-level external
+         * interrupts.
+         */
+        ASSERT(guest_file_id);
+
+        if ( vgein->owners[guest_file_id] )
+        {
+#ifdef VGEIN_DEBUG
+            gprintk(XENLOG_DEBUG, "%s: kick ->%pv, hgei_mask(%#lx)\n",
+                    __func__, vgein->owners[guest_file_id], hgei_mask);
+#endif
+
+            vcpu_kick(vgein->owners[guest_file_id]);
+        }
+    }
+
+    spin_unlock_irqrestore(&vgein->lock, flags);
+}
xen/arch/riscv/domain.c +3 -0
index 2dfe4c2e72ce..29181968224c 100644
@@ -136,6 +136,8 @@ static void vcpu_csr_init(struct vcpu *v)
         v->arch.hstateen0 = (hstateen0 & csr_masks.hstateen0) |
                             csr_masks.ro_one.hstateen0;
     }
+
+    v->arch.hie = MIP_SGEIP;
 }
 
 static void continue_new_vcpu(struct vcpu *prev)
@@ -398,6 +400,7 @@ static void restore_csr_regs(struct vcpu *vcpu)
     csr_write(CSR_HEDELEG, vcpu->arch.hedeleg);
     csr_write(CSR_HIDELEG, vcpu->arch.hideleg);
     csr_write(CSR_HVIP, vcpu->arch.hvip);
+    csr_write(CSR_HIE, vcpu->arch.hie);
     csr_write64(CSR_HENVCFG, vcpu->arch.henvcfg);
     csr_write(CSR_HCOUNTEREN, vcpu->arch.hcounteren);
     csr_write64(CSR_HTIMEDELTA, vcpu->arch.htimedelta);
xen/arch/riscv/imsic.c +54 -1

84 lines not on this page · raw message

xen/arch/riscv/include/asm/aia.h +2 -0
index 8e4eb2f6b14e..6a05bdd8c236 100644
@@ -12,4 +12,6 @@ void aia_init(void);
 unsigned int vgein_assign(struct vcpu *v);
 void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu);
 
+void hgei_interrupt(void);
+
 #endif /* RISCV_AIA_H */
xen/arch/riscv/include/asm/domain.h +1 -0
index 23e301782068..6d5eafdf5522 100644
@@ -72,6 +72,7 @@ struct arch_vcpu {
     register_t hvip;
     uint64_t   hviprio1;
     uint64_t   hviprio2;
+    register_t hie;
 
     register_t vsatp;
     register_t vscause;
xen/arch/riscv/traps.c +6 -1
index f5f83fce10ba..b08cf2ff2e31 100644
@@ -12,9 +12,10 @@
 #include <xen/sched.h>
 #include <xen/softirq.h>
 
-#include <asm/extable.h>
+#include <asm/aia.h>
 #include <asm/cpufeature.h>
 #include <asm/emulate.h>
+#include <asm/extable.h>
 #include <asm/intc.h>
 #include <asm/processor.h>
 #include <asm/riscv_encoding.h>
@@ -273,6 +274,10 @@ void do_trap(struct cpu_user_regs *cpu_regs)
                 timer_interrupt();
                 break;
 
+            case IRQ_S_GEXT:
+                hgei_interrupt();
+                break;
+
             default:
                 intr_handled = false;
                 break;
Signature · 1 line
2.55.0
#228 lore raw

Re: [PATCH v2 36/39] xen/riscv: wake up a descheduled vCPU on a guest external interrupt

Quoted 17 lines · Oleksii Kurochko
xen/arch/riscv/aia.c +3 -2
@@ -62,23 +69,25 @@ static int cf_check cpu_callback(struct notifier_block *nfb,
                                  unsigned long action, void *hcpu)
 {
     unsigned int cpu = (unsigned long)hcpu;
-    int rc = 0;
 
     switch ( action )
     {
     case CPU_STARTING:
-        rc = vgein_init();
+    {
+        int rc = vgein_init();
+
         if ( rc )
             printk(XENLOG_ERR "AIA: failed to init vgein for CPU%u: %d\n",
                    cpu, rc);
         break;

xen/arch/riscv/aia.c static int cf_check cpu_callback(struct notifier_block *nfb, · line 91

Quoted 10 lines
xen/arch/riscv/aia.c +2 -1
+    }
 
     case CPU_DYING:
         vgein_deinit();
         break;
     }
 
-    return notifier_from_errno(rc);
+    return NOTIFY_DONE;
 }

What is this hunk doing in this patch? Was this meant to be merged into the prior one? But then - why?

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 190

Quoted 11 lines
xen/arch/riscv/aia.c +7 -0
@@ -168,3 +181,36 @@ void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
             __func__, v, vgein_id, cpu, vgein->bmp);
 #endif
 }
+
+void hgei_interrupt(void)
+{
+    unsigned long hgei_mask, flags;
+    struct vgein_ctrl *vgein = &this_cpu(vgein);
+
+    hgei_mask = csr_read(CSR_HGEIP) & csr_read(CSR_HGEIE);

Misra, aiui, isn't going to like this. You may want to split it up.

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 202

Quoted 12 lines
xen/arch/riscv/aia.c +12 -0
+    csr_clear(CSR_HGEIE, hgei_mask);
+
+    spin_lock_irqsave(&vgein->lock, flags);
+
+    for_each_set_bit ( guest_file_id, hgei_mask )
+    {
+        /*
+         * guest_file_id shouldn't be zero, as it will indicate that no
+         * guest external interrupt source is selected for VS-level external
+         * interrupts.
+         */
+        ASSERT(guest_file_id);

While it only affects debug builds, this check still needlessly is done on every loop iteration, when doing it once ahead of the loop would suffice.

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 209

Quoted 6 lines
xen/arch/riscv/aia.c +6 -0
+        if ( vgein->owners[guest_file_id] )
+        {
+#ifdef VGEIN_DEBUG
+            gprintk(XENLOG_DEBUG, "%s: kick ->%pv, hgei_mask(%#lx)\n",
+                    __func__, vgein->owners[guest_file_id], hgei_mask);
+#endif

This can ocur very frequently (when VGEIN_DEBUG is defined). A trace record may be a better alternative.

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 140

Quoted 8 lines
xen/arch/riscv/domain.c +2 -0
@@ -136,6 +136,8 @@ static void vcpu_csr_init(struct vcpu *v)
         v->arch.hstateen0 = (hstateen0 & csr_masks.hstateen0) |
                             csr_masks.ro_one.hstateen0;
     }
+
+    v->arch.hie = MIP_SGEIP;

Neither part of the rhs identifier has anything to do with the CSR having its default value set here. That's perhaps again a piece of RISC-V I'm missing, but I can't make sense of this.

Quoted 4 lines
xen/arch/riscv/imsic.c +0 -0
@@ -510,12 +510,31 @@ void cf_check imsic_ctxt_switch_from(struct vcpu *v)
 

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 520

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
     write_lock_irqsave(&imsic_state->vsfile_lock, flags);
     imsic_state->vsfile_cpu = v->processor;
+    /*
+     * Start to observe the VS-file from HS-mode: while the vCPU isn't
+     * running an interrupt pending in its VS-file is reported through HGEIP
+     * instead of being delivered to VS-mode, which lets Xen wake the vCPU up.
+     */
+    csr_set(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
     write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
 }

It is suspicious for the HGEIE write to be the last step. How's this free of a window where an interrupt is lost. (Sorry, likely another blind spot of mine wrt RISC-V.)

Quoted 8 lines
xen/arch/riscv/imsic.c +5 -1
 void cf_check imsic_ctxt_switch_to(struct vcpu *v)
 {
-    /* Nothing to do */
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+
+    /* A s/w VS-file is never observed through HGEIP. */
+    if ( !vcpu_guest_file_id(v) )

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 538

Quoted 10 lines
xen/arch/riscv/imsic.c +9 -0
+        return;
+
+    /*
+     * The vCPU is about to run, so hstatus.VGEIN delivers the VS-file's
+     * interrupts to it directly and there is nothing left for Xen to observe.
+     */
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    csr_clear(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
 }

How can this be a read-lock when you write a CSR? Or else - why is locking here necessary in the firt place?

Jan

#229 lore raw

Re: [PATCH v2 36/39] xen/riscv: wake up a descheduled vCPU on a guest external interrupt

Quoted 25 lines · Jan Beulich
Quoted 24 lines · Oleksii Kurochko
xen/arch/riscv/aia.c +4 -2
@@ -62,23 +69,25 @@ static int cf_check cpu_callback(struct notifier_block *nfb,
                                   unsigned long action, void *hcpu)
  {
      unsigned int cpu = (unsigned long)hcpu;
-    int rc = 0;
 
      switch ( action )
      {
      case CPU_STARTING:
-        rc = vgein_init();
+    {
+        int rc = vgein_init();
+
          if ( rc )
              printk(XENLOG_ERR "AIA: failed to init vgein for CPU%u: %d\n",
                     cpu, rc);
          break;
+    }
 
      case CPU_DYING:
          vgein_deinit();
          break;
      }
 
Quoted 6 lines

xen/arch/riscv/aia.c static int cf_check cpu_callback(struct notifier_block *nfb, · line 91

Quoted 3 lines
xen/arch/riscv/aia.c +1 -1
-    return notifier_from_errno(rc);
+    return NOTIFY_DONE;
  }

What is this hunk doing in this patch? Was this meant to be merged into the prior one?

Yes, it was meant to be a part of prev. patch.

Quoted 1 line

But then - why?

I had a case with what rc returns but looking at my downstream branches I don't face this case anymore so this hunk should be just dropped.

Quoted 14 lines

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 190

Quoted 12 lines
xen/arch/riscv/aia.c +7 -0
@@ -168,3 +181,36 @@ void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
              __func__, v, vgein_id, cpu, vgein->bmp);
  #endif
  }
+
+void hgei_interrupt(void)
+{
+    unsigned long hgei_mask, flags;
+    struct vgein_ctrl *vgein = &this_cpu(vgein);
+
+    hgei_mask = csr_read(CSR_HGEIP) & csr_read(CSR_HGEIE);

Misra, aiui, isn't going to like this. You may want to split it up.

I will write in the following way then:

    hgei_mask = csr_read(CSR_HGEIP);
    hgei_mask &= csr_read(CSR_HGEIE);
Quoted 17 lines

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 202

Quoted 13 lines
xen/arch/riscv/aia.c +12 -0
+    csr_clear(CSR_HGEIE, hgei_mask);
+
+    spin_lock_irqsave(&vgein->lock, flags);
+
+    for_each_set_bit ( guest_file_id, hgei_mask )
+    {
+        /*
+         * guest_file_id shouldn't be zero, as it will indicate that no
+         * guest external interrupt source is selected for VS-level external
+         * interrupts.
+         */
+        ASSERT(guest_file_id);

While it only affects debug builds, this check still needlessly is done on every loop iteration, when doing it once ahead of the loop would suffice.

Good point. I will do in the following way then before the loop:

    /*
     * Bit 0 of HGEIP/HGEIE is read-only zero: guest interrupt file ID 0
     * means that no guest external interrupt source is selected.
     */
    ASSERT(!(hgei_mask & 1));
Quoted 10 lines

xen/arch/riscv/aia.c void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) · line 209

Quoted 7 lines
xen/arch/riscv/aia.c +6 -0
+        if ( vgein->owners[guest_file_id] )
+        {
+#ifdef VGEIN_DEBUG
+            gprintk(XENLOG_DEBUG, "%s: kick ->%pv, hgei_mask(%#lx)\n",
+                    __func__, vgein->owners[guest_file_id], hgei_mask);
+#endif

This can ocur very frequently (when VGEIN_DEBUG is defined). A trace record may be a better alternative.

Agree, it would be nice but tracing isn't ready for RISC-V.

Considering that we haven't had any issue with hgei interrupt for a long time I will just drop gprintk() for now and use trace record when functionality will be ready.

Quoted 13 lines

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 140

Quoted 9 lines
xen/arch/riscv/domain.c +2 -0
@@ -136,6 +136,8 @@ static void vcpu_csr_init(struct vcpu *v)
          v->arch.hstateen0 = (hstateen0 & csr_masks.hstateen0) |
                              csr_masks.ro_one.hstateen0;
      }
+
+    v->arch.hie = MIP_SGEIP;

Neither part of the rhs identifier has anything to do with the CSR having its default value set here. That's perhaps again a piece of RISC-V I'm missing, but I can't make sense of this.

All interrupt pending/enable CSRs share one bit layout (bit N corresponds to interrupt cause N), which is why MIP_SGEIP happened to be numerically right. I'll use BIT(IRQ_S_GEXT, UL) instead and add a comment: hie.SGEIE is what allows the SGEI raised through hgeie to be taken by Xen at all, while hie's VS-level bits alias the guest's vsie and are left cleared. I will apply the following change:

- v->arch.hie = MIP_SGEIP;
+ /*

+     * Enable SGEIs, so that a guest interrupt file marked in HGEIE while
+     * the vCPU is descheduled can raise an interrupt to Xen.
+     *
+     * The VS-level bits of hie alias the guest's vsie, which is saved and
+     * restored separately, so they are left clear here.
+     */

+ v->arch.hie = BIT(IRQ_S_GEXT, UL);

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/imsic.c +0 -0
@@ -510,12 +510,31 @@ void cf_check imsic_ctxt_switch_from(struct vcpu *v)
 
Quoted 14 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 520

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
      write_lock_irqsave(&imsic_state->vsfile_lock, flags);
      imsic_state->vsfile_cpu = v->processor;
+    /*
+     * Start to observe the VS-file from HS-mode: while the vCPU isn't
+     * running an interrupt pending in its VS-file is reported through HGEIP
+     * instead of being delivered to VS-mode, which lets Xen wake the vCPU up.
+     */
+    csr_set(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
      write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
  }

It is suspicious for the HGEIE write to be the last step. How's this free of a window where an interrupt is lost. (Sorry, likely another blind spot of mine wrt RISC-V.)

There's no window: a guest interrupt file's hgeip bit is level-sensitive, i.e. it reflects whether the file currently has a pending-and-enabled interrupt (the MSI itself stays latched in the file's eip[] until the guest claims it), and hip.SGEIP is simply (hgeip & hgeie) != 0. So an MSI arriving after the vCPU stopped running but before hgeie is set raises an SGEI as soon as the bit is set, taken once interrupts are re-enabled. I'll extend the comment to say so:

/*
* Start to observe the VS-file from HS-mode: while the vCPU isn't
* running an interrupt pending in its VS-file is reported through
HGEIP
* instead of being delivered to VS-mode, which lets Xen wake the
vCPU up.
*
* HGEIP is level-sensitive, reflecting the VS-file's current state, so
* an interrupt that became pending before this point raises an SGEI as
* soon as the bit is set in HGEIE; nothing is lost in between. */

Does it make sense?

Quoted 13 lines
Quoted 13 lines
xen/arch/riscv/imsic.c +9 -1
  void cf_check imsic_ctxt_switch_to(struct vcpu *v)
  {
-    /* Nothing to do */
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+
+    /* A s/w VS-file is never observed through HGEIP. */
+    if ( !vcpu_guest_file_id(v) )
+        return;
+
+    /*
+     * The vCPU is about to run, so hstatus.VGEIN delivers the VS-file's
Quoted 8 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 538

Quoted 6 lines
xen/arch/riscv/imsic.c +5 -0
+     * interrupts to it directly and there is nothing left for Xen to observe.
+     */
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    csr_clear(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
  }

How can this be a read-lock when you write a CSR?

But here is a protection of ->guest_file_id not of write to a CSR and we want to not have a change of ->guest_file_id during an update of CSR_HGEIE.

Quoted 2 lines

Or else - why is locking
here necessary in the firt place?

Strictly speaking no locking is needed with the current implementation: HGEIE is local to this pCPU, and guest_file_id can't change concurrently. It's updated either by this very pCPU ahead of switching the vCPU in (imsic_migrate_vcpu() called from schedule(), imsic_vsfile_attach() right after), or while the vCPU can't be scheduled: sched_unit_migrate_finish() defers to unit_context_saved() while the unit is running, and sched_move_domain() pauses the domain.

(and the similar are true for imsic_ctxt_switch_from())

But IMO we should keep around ->vsfile_lock to not miss the case where some case will update ->guest_file_id in parallel with imsic_ctxt_switch_to().

Does it make to continue to have read_lock_irqsave(...->vsfile_lock, ...) here just for potential future cases?

Thanks.

~ Oleksii

#230 lore raw

Re: [PATCH v2 36/39] xen/riscv: wake up a descheduled vCPU on a guest external interrupt

Quoted 22 lines · Oleksii Kurochko
Quoted 13 lines · Jan Beulich

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 140

Quoted 8 lines · Oleksii Kurochko
xen/arch/riscv/domain.c +2 -0
@@ -136,6 +136,8 @@ static void vcpu_csr_init(struct vcpu *v)
          v->arch.hstateen0 = (hstateen0 & csr_masks.hstateen0) |
                              csr_masks.ro_one.hstateen0;
      }
+
+    v->arch.hie = MIP_SGEIP;

Neither part of the rhs identifier has anything to do with the CSR having its default value set here. That's perhaps again a piece of RISC-V I'm missing, but I can't make sense of this.

All interrupt pending/enable CSRs share one bit layout (bit N corresponds to interrupt cause N), which is why MIP_SGEIP happened to be numerically right. I'll use BIT(IRQ_S_GEXT, UL) instead and add a
comment: hie.SGEIE is what allows the SGEI raised through hgeie to be taken by Xen at all, while hie's VS-level bits alias the guest's vsie and are left cleared. I will apply the following change:

Review

Quoted 9 lines
(quoted diff) +8 -1
-    v->arch.hie = MIP_SGEIP;
+    /*
+     * Enable SGEIs, so that a guest interrupt file marked in HGEIE while
+     * the vCPU is descheduled can raise an interrupt to Xen.
+     *
+     * The VS-level bits of hie alias the guest's vsie, which is saved and
+     * restored separately, so they are left clear here.
+     */
+    v->arch.hie = BIT(IRQ_S_GEXT, UL);

It's somewhat better this way, yes. And as said - in not looking great to me (doc-wise) is likely an issue of mine, not of yours.

Quoted 39 lines
Quoted 4 lines
Quoted 4 lines
xen/arch/riscv/imsic.c +0 -0
@@ -510,12 +510,31 @@ void cf_check imsic_ctxt_switch_from(struct vcpu *v)
 
Quoted 14 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 520

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
      write_lock_irqsave(&imsic_state->vsfile_lock, flags);
      imsic_state->vsfile_cpu = v->processor;
+    /*
+     * Start to observe the VS-file from HS-mode: while the vCPU isn't
+     * running an interrupt pending in its VS-file is reported through HGEIP
+     * instead of being delivered to VS-mode, which lets Xen wake the vCPU up.
+     */
+    csr_set(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
      write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
  }

It is suspicious for the HGEIE write to be the last step. How's this free of a window where an interrupt is lost. (Sorry, likely another blind spot of mine wrt RISC-V.)

There's no window: a guest interrupt file's hgeip bit is level-sensitive, i.e. it reflects whether the file currently has a pending-and-enabled interrupt (the MSI itself stays latched in the file's eip[] until the guest claims it), and hip.SGEIP is simply (hgeip & hgeie) != 0. So an MSI arriving after the vCPU stopped running but before hgeie is set raises an SGEI as soon as the bit is set, taken once interrupts are re-enabled. I'll extend the comment to say so:

/*
* Start to observe the VS-file from HS-mode: while the vCPU isn't
* running an interrupt pending in its VS-file is reported through
HGEIP
* instead of being delivered to VS-mode, which lets Xen wake the
vCPU up.
*
* HGEIP is level-sensitive, reflecting the VS-file's current state, so
* an interrupt that became pending before this point raises an SGEI as
* soon as the bit is set in HGEIE; nothing is lost in between. */

Quoted 1 line

Does it make sense?

I think I get what you're trying to explain, but the term "level-sensitive" here doesn't really help. I'm unconvinced you actually mean that, as it requires pins / physical signals, which don't exist with MSI. It feels like you may mean "sticky" instead.

Quoted 35 lines
Quoted 12 lines
Quoted 12 lines
xen/arch/riscv/imsic.c +9 -1
  void cf_check imsic_ctxt_switch_to(struct vcpu *v)
  {
-    /* Nothing to do */
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+
+    /* A s/w VS-file is never observed through HGEIP. */
+    if ( !vcpu_guest_file_id(v) )
+        return;
+
+    /*
+     * The vCPU is about to run, so hstatus.VGEIN delivers the VS-file's
Quoted 8 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 538

Quoted 6 lines
xen/arch/riscv/imsic.c +5 -0
+     * interrupts to it directly and there is nothing left for Xen to observe.
+     */
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    csr_clear(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
  }

How can this be a read-lock when you write a CSR?

But here is a protection of ->guest_file_id not of write to a CSR and we want to not have a change of ->guest_file_id during an update of CSR_HGEIE.

Quoted 2 lines

Or else - why is locking
here necessary in the firt place?

Strictly speaking no locking is needed with the current implementation:
HGEIE is local to this pCPU, and guest_file_id can't change concurrently. It's updated either by this very pCPU ahead of switching the vCPU in (imsic_migrate_vcpu() called from schedule(), imsic_vsfile_attach() right after), or while the vCPU can't be
scheduled: sched_unit_migrate_finish() defers to unit_context_saved() while the unit is running, and sched_move_domain() pauses the domain.

Quoted 8 lines

(and the similar are true for imsic_ctxt_switch_from())

But IMO we should keep around ->vsfile_lock to not miss the case where some case will update ->guest_file_id in parallel with imsic_ctxt_switch_to().

Does it make to continue to have read_lock_irqsave(...->vsfile_lock, ...) here just for potential future cases?

You get to judge. If the lock typically is uncontended, keeping things as-is may indeed be fine. Introducing a bottleneck "just for potential future cases" otoh wouldn't look overly nice to me.

Jan

#231 lore raw

Re: [PATCH v2 36/39] xen/riscv: wake up a descheduled vCPU on a guest external interrupt

Quoted 42 lines · Jan Beulich
Quoted 41 lines · Oleksii Kurochko
Quoted 5 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/imsic.c +0 -0
@@ -510,12 +510,31 @@ void cf_check imsic_ctxt_switch_from(struct vcpu *v)
 
Quoted 14 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 520

Quoted 10 lines
xen/arch/riscv/imsic.c +6 -0
       write_lock_irqsave(&imsic_state->vsfile_lock, flags);
       imsic_state->vsfile_cpu = v->processor;
+    /*
+     * Start to observe the VS-file from HS-mode: while the vCPU isn't
+     * running an interrupt pending in its VS-file is reported through HGEIP
+     * instead of being delivered to VS-mode, which lets Xen wake the vCPU up.
+     */
+    csr_set(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
       write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
   }

It is suspicious for the HGEIE write to be the last step. How's this free of a window where an interrupt is lost. (Sorry, likely another blind spot of mine wrt RISC-V.)

There's no window: a guest interrupt file's hgeip bit is level-sensitive, i.e. it reflects whether the file currently has a pending-and-enabled interrupt (the MSI itself stays latched in the file's eip[] until the guest claims it), and hip.SGEIP is simply (hgeip & hgeie) != 0. So an MSI arriving after the vCPU stopped running but before hgeie is set raises an SGEI as soon as the bit is set, taken once interrupts are re-enabled. I'll extend the comment to say so:

/*
* Start to observe the VS-file from HS-mode: while the vCPU isn't
* running an interrupt pending in its VS-file is reported through
HGEIP
* instead of being delivered to VS-mode, which lets Xen wake the
vCPU up.
*
* HGEIP is level-sensitive, reflecting the VS-file's current state, so
* an interrupt that became pending before this point raises an SGEI as
* soon as the bit is set in HGEIE; nothing is lost in between. */

Quoted 6 lines
Quoted 1 line

Does it make sense?

I think I get what you're trying to explain, but the term "level-sensitive" here doesn't really help. I'm unconvinced you actually mean that, as it requires pins / physical signals, which don't exist with MSI. It feels like you may mean "sticky" instead.

Fair point regarding the terminology: 'level-sensitive' usually implies physical signal lines, whereas here MSIs are memory writes latched in the file's eip[] array. I meant that HGEIP dynamically reflects whether the VS-file currently has any pending-and-enabled interrupt latched.

I'll update the comment to clarify this without using 'level-sensitive':

/*
* Start to observe the VS-file from HS-mode: while the vCPU isn't
* running an interrupt pending in its VS-file is reported through HGEIP
* instead of being delivered to VS-mode, which lets Xen wake the vCPU up. *
* An MSI is recorded in the VS-file's eip[] array until the guest claims
* it, and HGEIP isn't latched but reflects whether the file currently
* has a pending-and-enabled interrupt. Hence an interrupt which arrived
* before this point raises an SGEI as soon as the bit is set in HGEIE;
* nothing is lost in between.
*/

Quoted 42 lines
Quoted 42 lines
Quoted 13 lines
Quoted 13 lines
xen/arch/riscv/imsic.c +9 -1
   void cf_check imsic_ctxt_switch_to(struct vcpu *v)
   {
-    /* Nothing to do */
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+
+    /* A s/w VS-file is never observed through HGEIP. */
+    if ( !vcpu_guest_file_id(v) )
+        return;
+
+    /*
+     * The vCPU is about to run, so hstatus.VGEIN delivers the VS-file's
Quoted 8 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_from(struct vcpu *v) · line 538

Quoted 6 lines
xen/arch/riscv/imsic.c +5 -0
+     * interrupts to it directly and there is nothing left for Xen to observe.
+     */
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    csr_clear(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
   }

How can this be a read-lock when you write a CSR?

But here is a protection of ->guest_file_id not of write to a CSR and we want to not have a change of ->guest_file_id during an update of CSR_HGEIE.

Quoted 2 lines

Or else - why is locking
here necessary in the firt place?

Strictly speaking no locking is needed with the current implementation:
HGEIE is local to this pCPU, and guest_file_id can't change concurrently. It's updated either by this very pCPU ahead of switching the vCPU in (imsic_migrate_vcpu() called from schedule(), imsic_vsfile_attach() right after), or while the vCPU can't be
scheduled: sched_unit_migrate_finish() defers to unit_context_saved() while the unit is running, and sched_move_domain() pauses the domain.

(and the similar are true for imsic_ctxt_switch_from())

But IMO we should keep around ->vsfile_lock to not miss the case where some case will update ->guest_file_id in parallel with imsic_ctxt_switch_to().

Quoted 7 lines
Quoted 2 lines

Does it make to continue to have read_lock_irqsave(...->vsfile_lock, ...) here just for potential future cases?

You get to judge. If the lock typically is uncontended, keeping things as-is may indeed be fine. Introducing a bottleneck "just for potential future cases" otoh wouldn't look overly nice to me.

For the moment, I prefer to have a lock here as it is expected to be cheap. If one day it won't be true anymore it will be easier to spot all the places and remove it where it will be necessary.

~ Oleksii

#232 lore raw

Re: [PATCH v2 36/39] xen/riscv: wake up a descheduled vCPU on a guest external interrupt

In reply to Oleksii Kurochko
Quoted 6 lines

While a vCPU is running, MSIs written to its h/w IMSIC guest interrupt file are delivered straight to VS-mode. Once the vCPU is descheduled nobody observes that file anymore, so a guest blocked on such an interrupt would stay blocked until some unrelated event happens to schedule it again.

Quoted 6 lines

Let Xen observe the file in that window: on deschedule set the vCPU's bit in HGEIE, which turns an interrupt pending in its VS-file into an HS-level SGEI, and clear the bit again on schedule-in. HGEIP only reports a file number, so to get from it back to a vCPU keep an owners[] map per pCPU, filled by vgein_{assign,release} alongside the VGEIN bitmap, and kick the vCPU it points at.

Nit: I would reword the last sentence to make it more clear:

HGEIP only reports an interrupt file number, so to find the vCPU to kick, keep a per-pCPU owners[] array indexed by file number and updated in vgein_assign()/vgein_release() together with the VGEIN bitmap.

Quoted 208 lines

v->arch.hie is only initialized here and is written to the CSR later, on the context switch to the vCPU.

vgein_release() still has no caller: a vCPU going away has to both free its VGEIN slot and drop the owners[] entry, but there is no vCPU teardown path to hook it into yet. vgein_deinit() only covers a pCPU going offline.

xen/arch/riscv/aia.c +12 -3
index 1aca07c2f7..9642a9796e 100644
@@ -18,6 +18,13 @@ struct vgein_ctrl {
     /* The least-significant bits are implemented first, apart from bit 0 */
     unsigned long bmp;
     spinlock_t lock;
+    /*
+     * Guest interrupt file IDs run from 1 to geilen inclusive (0 means that
+     * no guest external interrupt source is selected), and geilen can never
+     * exceed BITS_PER_LONG - 1, so indexing this array by the ID directly
+     * always fits.
+     */
+    struct vcpu *owners[BITS_PER_LONG];
     unsigned int geilen;
 };
 
@@ -62,23 +69,25 @@ static int cf_check cpu_callback(struct notifier_block *nfb,
                                  unsigned long action, void *hcpu)
 {
     unsigned int cpu = (unsigned long)hcpu;
-    int rc = 0;
 
     switch ( action )
     {
     case CPU_STARTING:
-        rc = vgein_init();
+    {
+        int rc = vgein_init();
+
         if ( rc )
             printk(XENLOG_ERR "AIA: failed to init vgein for CPU%u: %d\n",
                    cpu, rc);
         break;
+    }
 
     case CPU_DYING:
         vgein_deinit();
         break;
     }
 
-    return notifier_from_errno(rc);
+    return NOTIFY_DONE;
 }
 
 

static struct notifier_block cpu_nfb = {

xen/arch/riscv/aia.c +37 -0
@@ -138,7 +147,10 @@ unsigned int vgein_assign(struct vcpu *v)
     if ( vgein_id > vgein->geilen )
         vgein_id = 0;
     else
+    {
         __set_bit(vgein_id, bmp);
+        vgein->owners[vgein_id] = v;
+    }
 
     spin_unlock_irqrestore(&vgein->lock, flags);
 
@@ -161,6 +173,7 @@ void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
     spin_lock_irqsave(&vgein->lock, flags);
     if ( !__test_and_clear_bit(vgein_id, &vgein->bmp) )
         ASSERT_UNREACHABLE();
+    vgein->owners[vgein_id] = NULL;
     spin_unlock_irqrestore(&vgein->lock, flags);
 
 #ifdef VGEIN_DEBUG
@@ -168,3 +181,36 @@ void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)
             __func__, v, vgein_id, cpu, vgein->bmp);
 #endif
 }
+
+void hgei_interrupt(void)
+{
+    unsigned long hgei_mask, flags;
+    struct vgein_ctrl *vgein = &this_cpu(vgein);
+
+    hgei_mask = csr_read(CSR_HGEIP) & csr_read(CSR_HGEIE);
 
 
+    csr_clear(CSR_HGEIE, hgei_mask);
+
+    spin_lock_irqsave(&vgein->lock, flags);
+
+    for_each_set_bit ( guest_file_id, hgei_mask )
+    {
+        /*
+         * guest_file_id shouldn't be zero, as it will indicate that no
+         * guest external interrupt source is selected for VS-level external
+         * interrupts.
+         */
+        ASSERT(guest_file_id);
 
 
+
+        if ( vgein->owners[guest_file_id] )
+        {
+#ifdef VGEIN_DEBUG
+            gprintk(XENLOG_DEBUG, "%s: kick ->%pv, hgei_mask(%#lx)\n",
+                    __func__, vgein->owners[guest_file_id], hgei_mask);
+#endif
 
 
+
+            vcpu_kick(vgein->owners[guest_file_id]);
+        }
+    }
+
+    spin_unlock_irqrestore(&vgein->lock, flags);
+}
xen/arch/riscv/domain.c +2 -0
index 2dfe4c2e72..2918196822 100644
@@ -136,6 +136,8 @@ static void vcpu_csr_init(struct vcpu *v)
         v->arch.hstateen0 = (hstateen0 & csr_masks.hstateen0) |
                             csr_masks.ro_one.hstateen0;
     }
+
+    v->arch.hie = MIP_SGEIP;
 
 
 }

static void continue_new_vcpu(struct vcpu *prev)

xen/arch/riscv/domain.c +1 -0
@@ -398,6 +400,7 @@ static void restore_csr_regs(struct vcpu *vcpu)
     csr_write(CSR_HEDELEG, vcpu->arch.hedeleg);
     csr_write(CSR_HIDELEG, vcpu->arch.hideleg);
     csr_write(CSR_HVIP, vcpu->arch.hvip);
+    csr_write(CSR_HIE, vcpu->arch.hie);
     csr_write64(CSR_HENVCFG, vcpu->arch.henvcfg);
     csr_write(CSR_HCOUNTEREN, vcpu->arch.hcounteren);
     csr_write64(CSR_HTIMEDELTA, vcpu->arch.htimedelta);
xen/arch/riscv/imsic.c +20 -1
index d7b137a1f5..0715206611 100644
@@ -510,12 +510,31 @@ void cf_check imsic_ctxt_switch_from(struct vcpu *v)
 
     write_lock_irqsave(&imsic_state->vsfile_lock, flags);
     imsic_state->vsfile_cpu = v->processor;
+    /*
+     * Start to observe the VS-file from HS-mode: while the vCPU isn't
+     * running an interrupt pending in its VS-file is reported through HGEIP
+     * instead of being delivered to VS-mode, which lets Xen wake the vCPU up.
+     */
+    csr_set(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
     write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
 }
 
 
 
 void cf_check imsic_ctxt_switch_to(struct vcpu *v)
 {
-    /* Nothing to do */
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+
+    /* A s/w VS-file is never observed through HGEIP. */
+    if ( !vcpu_guest_file_id(v) )
+        return;
+
+    /*
+     * The vCPU is about to run, so hstatus.VGEIN delivers the VS-file's
+     * interrupts to it directly and there is nothing left for Xen to observe.
+     */
+    read_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    csr_clear(CSR_HGEIE, BIT(imsic_state->guest_file_id, UL));
+    read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
 }

int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)

xen/arch/riscv/imsic.c +11 -0
@@ -646,6 +665,12 @@ static void cf_check imsic_vsfile_local_read_clear(void *data)
     struct imsic_mrif *mrif = idata->mrif;
     unsigned long new_hstatus, old_hstatus, old_vsiselect;
 
+    /*
+     * The HGEIE bit imsic_ctxt_switch_from() armed belongs to the old owner
+     * only.
+     */
+    csr_clear(CSR_HGEIE, BIT(idata->hgei, UL));
+
     old_vsiselect = csr_read(CSR_VSISELECT);
     old_hstatus = csr_read(CSR_HSTATUS);
     new_hstatus = old_hstatus & ~HSTATUS_VGEIN;
@@ -991,6 +1016,21 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,
     return fdt_end_node(fdt);
 }
 
+/*
+ * Start to observe the interrupt file from HS-mode, the same way
+ * imsic_ctxt_switch_from() does it for a vCPU which is switched out.
+ *
+ * The counterpart, clearing the bit of the interrupt file which is left

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 1033

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+ * behind, is done by imsic_vsfile_local_read_clear(), which already runs on
+ * the pCPU owning that file.
+ */
+static void cf_check imsic_local_hgeie_set(void *data)
+{
+    const struct imsic_vsfile_data *idata = data;
+
+    csr_set(CSR_HGEIE, BIT(idata->hgei, UL));
+}
+

Sorry I'm a bit lost here, are you doing that for vCPUs migration? Because in your commit message you only mentioned scheduled-out case which needs to have Xen observing the descheduled vCPU to re-scheduled it, but no other case that would need to have interrupt file observed is explained

Signature · 1 line
Baptiste Le Duc <[email protected]>
#233 lore raw

Re: [PATCH v2 36/39] xen/riscv: wake up a descheduled vCPU on a guest external interrupt

Quoted 12 lines · Baptiste Le Duc
Quoted 6 lines

While a vCPU is running, MSIs written to its h/w IMSIC guest interrupt file are delivered straight to VS-mode. Once the vCPU is descheduled nobody observes that file anymore, so a guest blocked on such an interrupt would stay blocked until some unrelated event happens to schedule it again.

Quoted 6 lines

Let Xen observe the file in that window: on deschedule set the vCPU's bit in HGEIE, which turns an interrupt pending in its VS-file into an HS-level SGEI, and clear the bit again on schedule-in. HGEIP only reports a file number, so to get from it back to a vCPU keep an owners[] map per pCPU, filled by vgein_{assign,release} alongside the VGEIN bitmap, and kick the vCPU it points at.

Quoted 7 lines

Nit: I would reword the last sentence to make it more clear:

HGEIP only reports an interrupt file number, so to find the vCPU to kick, keep a per-pCPU owners[] array indexed by file number and updated in vgein_assign()/vgein_release() together with the VGEIN bitmap.

LGTM: I will apply your suggestion.

Quoted 13 lines
Quoted 13 lines
xen/arch/riscv/imsic.c +12 -0
+/*
+ * Start to observe the interrupt file from HS-mode, the same way
+ * imsic_ctxt_switch_from() does it for a vCPU which is switched out.
+ *
+ * The counterpart, clearing the bit of the interrupt file which is left
+ * behind, is done by imsic_vsfile_local_read_clear(), which already runs on
+ * the pCPU owning that file.
+ */
+static void cf_check imsic_local_hgeie_set(void *data)
+{
+    const struct imsic_vsfile_data *idata = data;
+
Quoted 9 lines

xen/arch/riscv/imsic.c int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo, · line 1033

Quoted 3 lines
xen/arch/riscv/imsic.c +3 -0
+    csr_set(CSR_HGEIE, BIT(idata->hgei, UL));
+}
+

Sorry I'm a bit lost here, are you doing that for vCPUs migration? Because in your commit message you only mentioned scheduled-out case which needs to have Xen observing the descheduled vCPU to re-scheduled it, but no other case that would need to have interrupt file observed is explained

Yes, this is for migration. A vCPU can be migrated while it isn't
running: e.g. a blocked vCPU whose affinity is changed (it is moved by sched_unit_migrate_finish() and stays blocked on the new pCPU), or the vCPUs of a domain moved to another cpupool.

Before the migration, imsic_ctxt_switch_from() armed the HGEIE bit of
the vCPU's interrupt file on the old pCPU. That file is released as part
of the migration (and imsic_vsfile_local_read_clear() clears its HGEIE
bit), so afterwards nothing observes the vCPU's interrupts anymore: the
vCPU isn't switched in on the new pCPU, so imsic_ctxt_switch_from() never arms HGEIE for the new file. A blocked vCPU waiting for an MSI could then stay blocked until some unrelated event wakes it up, possibly never.

Hence imsic_local_hgeie_set() arms HGEIE for the new interrupt file on the new pCPU. As HGEIP reflects the current state of the file, this also covers an interrupt which was already pending in the old file and got carried over: it raises an SGEI as soon as the bit is set.

For a vCPU which is about to run, this isn't needed, as imsic_ctxt_switch_to() clears the bit anyway.

I'll describe this case in the commit message:

```
The same applies to a vCPU which is migrated to another pCPU while it
isn't running. Its old interrupt file is released during the migration,
and the vCPU isn't switched in on the new pCPU until something wakes it
up, so nothing would observe the new interrupt file. Hence arm HGEIE for
the new interrupt file on the new pCPU in imsic_migrate_vcpu(), and
clear the bit of the old one in imsic_vsfile_local_read_clear(), which
already runs on the pCPU owning it.
```

Thanks!

~ Oleksii

#234 lore raw

PATCH v2 37/39 xen/riscv: map IMSIC interrupt file for vCPUs

In reply to Oleksii Kurochko

A guest running in VS-mode expects its own IMSIC S-file at offset 0 of its guest-physical IMSIC block. Physically, the guest-file (G-file) assigned to this vCPU lives at a hart-relative offset given by guest_file_id (assigned via the vGEIN allocator). Therefore, imsic_map_guest_file() uses stage-2 translation to redirect the guest's fixed per-vCPU GPA page (offset 0) to the specific physical guest-file page.

---
Changes in v2:
- Use GUEST_IMSIC_S_BASE instead of imsic_cfg.base_addr as the base of the guest address to map to, and change the type of gaddr to paddr_t as it holds a guest physical address.
- Rename guest_stride to guest_offset: it is an offset of the VS-file inside the pCPU's IMSIC block, not a stride.
- Use PRIpaddr for physical addresses and %u for unsigned values in the debug/error messages.
- Switch the mapping failure message from printk() to dprintk(XENLOG_ERR, ...).
- Update the comment above imsic_map_guest_file(): vCPUs aren't pinned, they run on the pCPU chosen by the scheduler, and mention that on migration a VS-file is acquired on the new pCPU and mapped at the same GFN, so the stale mapping is replaced rather than explicitly torn down.
---

---
 xen/arch/riscv/imsic.c | 66 +++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 65 insertions(+), 1 deletion(-)
xen/arch/riscv/imsic.c +65 -1
index 07152066116a..374a21ace15f 100644
@@ -29,6 +29,7 @@
 #include <asm/aia.h>
 #include <asm/aplic.h>
 #include <asm/imsic.h>
+#include <asm/p2m.h>
 
 #define IMSIC_HART_SIZE(guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
 
@@ -537,9 +538,72 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
     read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
 }
 
+/*
+ * Map the physical IMSIC guest interrupt file (G-file) assigned to vCPU
+ * into the domain's stage-2 guest-physical address space.
+ *
+ * In the machine's physical address space (SPA), each hart's IMSIC
+ * supervisor-level file (S-file) is located at offset 0 of its address block,
+ * followed contiguously by GEILEN guest files at offsets of 1, 2, ..., N pages.
+ *
+ * Because a guest OS running in VS-mode expects its own supervisor-level
+ * interrupt file to be at offset 0 of its guest-physical IMSIC block, the
+ * hypervisor must use stage-2 address translation to map the vCPU's
+ * guest-physical "supervisor" page (GPA offset 0) to the specific
+ * physical guest file page (SPA offset guest_file_id) on the physical hart.
+ *
+ * A vCPU runs on the pCPU the scheduler picked for it (v->processor), and
+ * the guest file it is given (guest_file_id, from the vGEIN allocator)
+ * belongs to that very pCPU's IMSIC. A guest_file_id of 0 indicates that no
+ * hardware guest file is selected (matching the architectural behavior where
+ * vGEIN = 0 in the hstatus CSR selects no guest external interrupt source),
+ * requiring the VS-file to be emulated in software.
+ *
+ * Consequently the mapping installed here is only valid as long as the vCPU
+ * stays on that pCPU. When it migrates, a VS-file is acquired on the new
+ * pCPU and mapped at the very same GFN, so the stale mapping needs no
+ * explicit tear-down: it is simply replaced.
+ *
+ * The base guest-physical address advertised to the guest in the device
+ * tree matches offset 0 of the vCPU's virtual IMSIC block. Stage-2
+ * translation ensures that guest supervisor accesses to this page are
+ * transparently routed to the real hardware VS-file granted to it on
+ * the pCPU it currently runs on.
+ */
 int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
 {
-    return -EOPNOTSUPP;
+    struct domain *d = v->domain;
+    unsigned int cpu = v->processor;
+    paddr_t gaddr = GUEST_IMSIC_S_BASE + (IMSIC_MMIO_PAGE_SZ * v->vcpu_id);
+    paddr_t paddr, guest_offset;
+    int res;
+
+    /* Nothing to map in the case of sw interrupt file. */
+    if ( !vsfile_id )
+        return 0;
+
+    guest_offset = vsfile_id * IMSIC_MMIO_PAGE_SZ;
+
+    paddr = imsic_cfg.msi[cpu].base_addr + imsic_cfg.msi[cpu].offset +
+            guest_offset;
+
+#ifdef IMSIC_DEBUG
+    printk(XENLOG_DEBUG
+           "%s: %pv: ga(%#"PRIpaddr") -> pa(%#"PRIpaddr"), cpu(%u), "
+           "guest_file_id(%u) base_addr(%#"PRIpaddr") offset(%#lx)\n",
+           __func__, v, gaddr, paddr, cpu, vsfile_id,
+           imsic_cfg.msi[cpu].base_addr, imsic_cfg.msi[cpu].offset);
+#endif
+
+    res = map_regions_p2mt(d, gaddr_to_gfn(gaddr),
+                           PFN_DOWN(IMSIC_MMIO_PAGE_SZ), maddr_to_mfn(paddr),
+                           arch_dt_passthrough_p2m_type());
+    if ( res )
+        dprintk(XENLOG_ERR,
+                "%s: Failed to map %#"PRIpaddr" to the guest at %#"PRIpaddr"\n",
+                __func__, paddr, gaddr);
+
+    return res;
 }
 
 int cf_check vcpu_imsic_init(struct vcpu *v)
Signature · 1 line
2.55.0
Acked-by on v2 37/39
#235 lore raw

Re: [PATCH v2 37/39] xen/riscv: map IMSIC interrupt file for vCPUs

Quoted 8 lines · Oleksii Kurochko

A guest running in VS-mode expects its own IMSIC S-file at offset 0 of its guest-physical IMSIC block. Physically, the guest-file (G-file) assigned to this vCPU lives at a hart-relative offset given by guest_file_id (assigned via the vGEIN allocator). Therefore, imsic_map_guest_file() uses stage-2 translation to redirect the guest's fixed per-vCPU GPA page (offset 0) to the specific physical guest-file page.

perhaps with ...

Quoted 50 lines
xen/arch/riscv/imsic.c +43 -1
@@ -537,9 +538,72 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
     read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
 }
 
+/*
+ * Map the physical IMSIC guest interrupt file (G-file) assigned to vCPU
+ * into the domain's stage-2 guest-physical address space.
+ *
+ * In the machine's physical address space (SPA), each hart's IMSIC
+ * supervisor-level file (S-file) is located at offset 0 of its address block,
+ * followed contiguously by GEILEN guest files at offsets of 1, 2, ..., N pages.
+ *
+ * Because a guest OS running in VS-mode expects its own supervisor-level
+ * interrupt file to be at offset 0 of its guest-physical IMSIC block, the
+ * hypervisor must use stage-2 address translation to map the vCPU's
+ * guest-physical "supervisor" page (GPA offset 0) to the specific
+ * physical guest file page (SPA offset guest_file_id) on the physical hart.
+ *
+ * A vCPU runs on the pCPU the scheduler picked for it (v->processor), and
+ * the guest file it is given (guest_file_id, from the vGEIN allocator)
+ * belongs to that very pCPU's IMSIC. A guest_file_id of 0 indicates that no
+ * hardware guest file is selected (matching the architectural behavior where
+ * vGEIN = 0 in the hstatus CSR selects no guest external interrupt source),
+ * requiring the VS-file to be emulated in software.
+ *
+ * Consequently the mapping installed here is only valid as long as the vCPU
+ * stays on that pCPU. When it migrates, a VS-file is acquired on the new
+ * pCPU and mapped at the very same GFN, so the stale mapping needs no
+ * explicit tear-down: it is simply replaced.
+ *
+ * The base guest-physical address advertised to the guest in the device
+ * tree matches offset 0 of the vCPU's virtual IMSIC block. Stage-2
+ * translation ensures that guest supervisor accesses to this page are
+ * transparently routed to the real hardware VS-file granted to it on
+ * the pCPU it currently runs on.
+ */
 int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
 {
-    return -EOPNOTSUPP;
+    struct domain *d = v->domain;
+    unsigned int cpu = v->processor;
+    paddr_t gaddr = GUEST_IMSIC_S_BASE + (IMSIC_MMIO_PAGE_SZ * v->vcpu_id);
+    paddr_t paddr, guest_offset;
+    int res;
+
+    /* Nothing to map in the case of sw interrupt file. */
+    if ( !vsfile_id )
+        return 0;
+
+    guest_offset = vsfile_id * IMSIC_MMIO_PAGE_SZ;

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_to(struct vcpu *v) · line 595

Quoted 10 lines
xen/arch/riscv/imsic.c +10 -0
+
+    paddr = imsic_cfg.msi[cpu].base_addr + imsic_cfg.msi[cpu].offset +
+            guest_offset;
+
+#ifdef IMSIC_DEBUG
+    printk(XENLOG_DEBUG
+           "%s: %pv: ga(%#"PRIpaddr") -> pa(%#"PRIpaddr"), cpu(%u), "
+           "guest_file_id(%u) base_addr(%#"PRIpaddr") offset(%#lx)\n",
+           __func__, v, gaddr, paddr, cpu, vsfile_id,
+           imsic_cfg.msi[cpu].base_addr, imsic_cfg.msi[cpu].offset);

... this also converted to dprintk(), or at least using XENLOG_G_DEBUG.

Jan

#236 lore raw

Re: [PATCH v2 37/39] xen/riscv: map IMSIC interrupt file for vCPUs

Quoted 11 lines · Jan Beulich
Quoted 8 lines · Oleksii Kurochko

A guest running in VS-mode expects its own IMSIC S-file at offset 0 of its guest-physical IMSIC block. Physically, the guest-file (G-file) assigned to this vCPU lives at a hart-relative offset given by guest_file_id (assigned via the vGEIN allocator). Therefore, imsic_map_guest_file() uses stage-2 translation to redirect the guest's fixed per-vCPU GPA page (offset 0) to the specific physical guest-file page.

Thanks.

Quoted 56 lines

perhaps with ...

Quoted 54 lines
xen/arch/riscv/imsic.c +47 -1
@@ -537,9 +538,72 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)
      read_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
  }
 
+/*
+ * Map the physical IMSIC guest interrupt file (G-file) assigned to vCPU
+ * into the domain's stage-2 guest-physical address space.
+ *
+ * In the machine's physical address space (SPA), each hart's IMSIC
+ * supervisor-level file (S-file) is located at offset 0 of its address block,
+ * followed contiguously by GEILEN guest files at offsets of 1, 2, ..., N pages.
+ *
+ * Because a guest OS running in VS-mode expects its own supervisor-level
+ * interrupt file to be at offset 0 of its guest-physical IMSIC block, the
+ * hypervisor must use stage-2 address translation to map the vCPU's
+ * guest-physical "supervisor" page (GPA offset 0) to the specific
+ * physical guest file page (SPA offset guest_file_id) on the physical hart.
+ *
+ * A vCPU runs on the pCPU the scheduler picked for it (v->processor), and
+ * the guest file it is given (guest_file_id, from the vGEIN allocator)
+ * belongs to that very pCPU's IMSIC. A guest_file_id of 0 indicates that no
+ * hardware guest file is selected (matching the architectural behavior where
+ * vGEIN = 0 in the hstatus CSR selects no guest external interrupt source),
+ * requiring the VS-file to be emulated in software.
+ *
+ * Consequently the mapping installed here is only valid as long as the vCPU
+ * stays on that pCPU. When it migrates, a VS-file is acquired on the new
+ * pCPU and mapped at the very same GFN, so the stale mapping needs no
+ * explicit tear-down: it is simply replaced.
+ *
+ * The base guest-physical address advertised to the guest in the device
+ * tree matches offset 0 of the vCPU's virtual IMSIC block. Stage-2
+ * translation ensures that guest supervisor accesses to this page are
+ * transparently routed to the real hardware VS-file granted to it on
+ * the pCPU it currently runs on.
+ */
  int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id)
  {
-    return -EOPNOTSUPP;
+    struct domain *d = v->domain;
+    unsigned int cpu = v->processor;
+    paddr_t gaddr = GUEST_IMSIC_S_BASE + (IMSIC_MMIO_PAGE_SZ * v->vcpu_id);
+    paddr_t paddr, guest_offset;
+    int res;
+
+    /* Nothing to map in the case of sw interrupt file. */
+    if ( !vsfile_id )
+        return 0;
+
+    guest_offset = vsfile_id * IMSIC_MMIO_PAGE_SZ;
+
+    paddr = imsic_cfg.msi[cpu].base_addr + imsic_cfg.msi[cpu].offset +
+            guest_offset;
+
Quoted 8 lines

xen/arch/riscv/imsic.c void cf_check imsic_ctxt_switch_to(struct vcpu *v) · line 595

Quoted 6 lines
xen/arch/riscv/imsic.c +6 -0
+#ifdef IMSIC_DEBUG
+    printk(XENLOG_DEBUG
+           "%s: %pv: ga(%#"PRIpaddr") -> pa(%#"PRIpaddr"), cpu(%u), "
+           "guest_file_id(%u) base_addr(%#"PRIpaddr") offset(%#lx)\n",
+           __func__, v, gaddr, paddr, cpu, vsfile_id,
+           imsic_cfg.msi[cpu].base_addr, imsic_cfg.msi[cpu].offset);

... this also converted to dprintk(), or at least using XENLOG_G_DEBUG.

I will convert to dprintk().

~ Oleksii