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 1 of 3

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore
#0 lore raw

v2 cover virtual interrupt controller (vAPLIC/vIMSIC) support

Hi all,

This series adds the initial virtual interrupt controller (vINTC) support for RISC-V guests in Xen, based on the Advanced Interrupt Architecture (AIA): a virtual APLIC (vAPLIC) in MSI mode backed by a virtual IMSIC (vIMSIC) using hardware guest interrupt files.

Rather than emulating APLIC in direct-delivery mode (which requires trap-and-emulate for every interrupt and is costly), the series targets IMSIC from the start. AIA lets a hart implement several "guest interrupt files" (up to GEILEN), so external interrupts can be delivered to a vCPU directly by hardware via the VGEIN field of hstatus, without a hypervisor round-trip. Xen only has to emulate the APLIC MMIO programming interface and route the guest's intent onto the physical MSI topology; interrupt delivery itself stays in hardware.

The work breaks down into a few logical blocks:

Preparatory fixes and cleanups (patches 1-6)
- Drop the unused pregs field of struct cpu_user_regs and bug.h's duplicate instruction length helpers.
- Program hstatus.VSXL explicitly, as decoding a trapped instruction depends on the effective XLEN of the guest.
- csr_read64() as the counterpart of csr_write64(), used for CSR_TIME so that get_cycles() no longer truncates the time counter on RV32, and UINT64_MAX rather than ULONG_MAX to disable the VS-timer.
- Request a G-stage flush on vmenter where VMIDs are unavailable, so a domain cannot run on the translations left behind by the one which ran on that hart before it.

APLIC groundwork and vAPLIC MMIO emulation (patches 7-11)
- Add the missing APLIC register offsets/masks needed by both the physical and virtual APLIC code, rearranging asm/aplic.h in the style of x86's asm/msr-index.h (no functional change).
- A per-domain MMIO handler table modelled on Arm's framework, so emulated devices self-register their GPA ranges and the fault path stays agnostic via a single try_handle_mmio() entry point.
- vAPLIC MMIO read/write emulation. Writes are gated by the domain's authorised-IRQ bitmap so a guest cannot touch interrupts it does not own, and TARGET writes are translated from virtual to physical hart/guest-file indices. Delegation (SOURCECFG.D) is not yet supported.
- Build the physical APLIC's target hart index with aplic_hart_field() as well, dropping the last in-tree duplicate of the AIA hart index formula, and add a helper to test for APLIC MSI mode.

vCPU context switching (patches 12-15)
- context_switch() and the helpers it needs: save/restore of H/VS CSRs, the virtual timer and P2M context, and __context_switch() in assembly. The VMID is claimed in p2m_ctxt_switch_to() rather than at the next guest entry, which leaves p2m_handle_vmenter() with nothing to do.
- Save and restore the AIA CSRs a guest can change (vsiselect and hviprio{1,2}), gated by hstateen0 where Smstateen is implemented.
- vintc_ctxt_switch_{from,to}() wrappers over new ctxt_switch_{from,to} hooks in struct vintc_ops, called from the context switch path, plus the IMSIC implementation of those hooks: it records which pCPU owns a vCPU's guest interrupt file, as the pCPU id is part of the MSI address.

Trap and instruction emulation infrastructure (patches 16-26)
- Extend the exception-table format with type/data fields and add EX_TYPE_TRAP_INFO so fixups can capture sepc/scause/stval, and look the table up for any trap taken in Xen context rather than for illegal instructions only, so that the hlv/hlvx sequences reach their fixup.
- A guest page-fault handler, and trap_redirect() to forward a synchronous trap back into the guest's VS-mode handler for the faults which can never become an emulated access.
- Resolve the faulting guest physical address from htval and stval, which first needs Shtvala to be detected, and define all four INSN_PSEUDO_VS_* values independently of the hypervisor's XLEN, so that a fault taken on an implicit VS-stage access is recognized as one rather than mistaken for an MMIO trap.
- riscv_read_guest() (HLV/HLVX) to read guest memory and instructions safely, the decoding helpers shared by both access types, and the load and store emulation which dispatches the access through try_handle_mmio().

vCPU migration between pCPUs (patches 27-34) (introduced here for better context of VGEIN fumctions usage)
- arch_move_irqs(), dispatching through a new move_irqs hook in struct vintc_ops down to imsic_migrate_vcpu(), and the case where a vCPU has no guest interrupt file to move yet.
- The move of a vCPU's IMSIC guest interrupt file itself, following the sequence the AIA spec prescribes: quiesce and save eidelivery/ eithreshold of the old file, zero the new one, G-stage remap it, retarget the domain's APLIC interrupts at it (aplic_reconfigure_target()) and fence off straggler MSIs with a genmsi barrier, dump the old file's eip/eie arrays to memory, then restore that state into the new file and update the vCPU's hstatus.VGEIN.

VGEIN allocation and vCPU bring-up (patches 35-39)
- Per-pCPU VGEIN (guest interrupt file) allocator: a bitmap of the files a hart implements (up to GEILEN) with helpers to assign and release one, and an owners[] map so a file reported pending in HGEIP can be traced back to the vCPU it belongs to.
- Watch a descheduled vCPU's guest interrupt file through HGEIE, so that a guest blocked on an external interrupt is woken up instead of waiting for an unrelated event to schedule it again.
- Stage-2 map a vCPU's physical guest interrupt file to the fixed per-vCPU GPA page the guest expects at offset 0.
- continue_new_vcpu(): switch to the idle vCPU's own stack for the idle vCPU, and enter the guest through the new return_to_new_vcpu() path in entry.S for a guest one.
- imsic_vsfile_attach(), called once the pCPU a vCPU will run on is
known: it assigns a VGEIN, maps the guest interrupt file and records the IMSIC state as a consistent unit.

CI tests: https://gitlab.com/xen-project/people/olkur/xen/-/pipelines/2796779115

The series depends on [1].

[1] https://lore.kernel.org/xen-devel/[email protected]/T/#t

---
Changes in v2:
- The series has grown from 17 to 39 patches. vCPU context switching, vCPU migration between pCPUs and the vCPU bring-up path (continue_new_vcpu(), attaching an IMSIC h/w interrupt file) are now part of it to have better context of how things are using, together with the trap-side pieces the MMIO emulation depends on (faulting GPA resolution, Shtvala detection, instruction decoding).
- vintc_state_{save,restore}() became vintc_ctxt_switch_{from,to}() and vcpu_aia_init() became imsic_vsfile_attach(); "xen/riscv: manage IRQ_DISABLED flag in APLIC irq enable/disable callbacks" is no longer part of this series. The remaining changes are described in the per-patch changelogs.
---

Oleksii Kurochko (39):
xen/riscv: drop pregs from struct cpu_user_regs
xen/riscv: drop bug.h's duplicate instruction length helpers xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL xen/riscv: introduce csr_read64()
xen/riscv: request a G-stage flush on vmenter when VMIDs are disabled xen/riscv: use UINT64_MAX to disable the VS-timer xen/riscv: add missing APLIC register offsets, masks to asm/aplic.h xen/riscv: introduce device-agnostic MMIO emulation dispatch xen/riscv: implement virtual APLIC MMIO emulation xen/riscv: build the target hart index via aplic_hart_field() xen/riscv: add helper to check APLIC MSI mode
xen/riscv: implement vCPU context switching
xen/riscv: save and restore AIA state on vCPU context switch xen/riscv: introduce vintc_ctxt_switch_{from,to}() xen/riscv: add IMSIC vCPU context switch handlers xen/riscv: extend exception tables with type and data fields xen/riscv: decouple INSN_PSEUDO_VS_* from the hypervisor's XLEN xen/riscv: add guest page fault handling stub
xen/riscv: implement trap redirection to a guest xen/riscv: detect Shtvala
xen/riscv: resolve the faulting guest physical address xen/riscv: add guest memory read helper
xen/riscv: look up the exception table for any trap taken in Xen
context
xen/riscv: add helpers for decoding a trapped load or store xen/riscv: add guest load emulation for trapped MMIO accesses xen/riscv: add guest store emulation for trapped MMIO accesses xen/riscv: introduce arch_move_irqs()
xen/riscv: handle the case when no vCPU migration is needed xen/riscv: introduce aplic_reconfigure_target()
xen/riscv: prepare new IMSIC VS-file
xen/riscv: implement APLIC-hart sync barrier for vCPU migration xen/riscv: remap interrupts to new IMSIC VS-file xen/riscv: dump old interrupt file to memory
xen/riscv: restore register state in the new IMSIC VS-file xen/riscv: add basic VGEIN management for AIA guests xen/riscv: wake up a descheduled vCPU on a guest external interrupt xen/riscv: map IMSIC interrupt file for vCPUs
xen/riscv: implement continue_new_vcpu()
xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu

 xen/arch/riscv/Makefile                     |   2 +
 xen/arch/riscv/aia.c                        | 193 ++++++
 xen/arch/riscv/aplic-priv.h                 |   3 +
 xen/arch/riscv/aplic.c                      | 235 ++++++-
 xen/arch/riscv/cpufeature.c                 |   1 +
 xen/arch/riscv/domain.c                     | 271 +++++++-
 xen/arch/riscv/emulate.c                    | 578 ++++++++++++++++
 xen/arch/riscv/entry.S                      |  67 ++
 xen/arch/riscv/extable.c                    |  70 +-
 xen/arch/riscv/guestcopy.c                  |  87 +++
 xen/arch/riscv/imsic.c                      | 691 ++++++++++++++++++++
 xen/arch/riscv/include/asm/aia.h            |   7 +
 xen/arch/riscv/include/asm/aplic.h          | 130 +++-
 xen/arch/riscv/include/asm/bug.h            |  19 -
 xen/arch/riscv/include/asm/cpufeature.h     |   1 +
 xen/arch/riscv/include/asm/csr.h            |  24 +
 xen/arch/riscv/include/asm/current.h        |   4 +
 xen/arch/riscv/include/asm/domain.h         |  23 +-
 xen/arch/riscv/include/asm/emulate.h        |  10 +
 xen/arch/riscv/include/asm/extable.h        |  64 +-
 xen/arch/riscv/include/asm/gpr-num.h        |  37 ++
 xen/arch/riscv/include/asm/guest_access.h   |   4 +
 xen/arch/riscv/include/asm/imsic.h          |  31 +
 xen/arch/riscv/include/asm/intc.h           |  12 +
 xen/arch/riscv/include/asm/irq.h            |   5 +-
 xen/arch/riscv/include/asm/mmio.h           |  63 ++
 xen/arch/riscv/include/asm/p2m.h            |   1 -
 xen/arch/riscv/include/asm/processor.h      |  16 +-
 xen/arch/riscv/include/asm/riscv_encoding.h |  34 +-
 xen/arch/riscv/include/asm/system.h         |   4 +
 xen/arch/riscv/include/asm/time.h           |   4 +-
 xen/arch/riscv/include/asm/traps.h          |   9 +
 xen/arch/riscv/include/asm/vaplic.h         |   5 +
 xen/arch/riscv/intc.c                       |  22 +
 xen/arch/riscv/mmio.c                       | 176 +++++
 xen/arch/riscv/p2m.c                        |  55 +-
 xen/arch/riscv/riscv64/asm-offsets.c        |  20 +-
 xen/arch/riscv/stubs.c                      |   5 -
 xen/arch/riscv/time.c                       |   4 +-
 xen/arch/riscv/traps.c                      | 110 +++-
 xen/arch/riscv/vaplic.c                     | 358 +++++++++-
 xen/arch/riscv/vmid.c                       |   4 +-
 xen/include/xen/config.h                    |   1 +
 43 files changed, 3281 insertions(+), 179 deletions(-)
 create mode 100644 xen/arch/riscv/emulate.c
 create mode 100644 xen/arch/riscv/include/asm/emulate.h
 create mode 100644 xen/arch/riscv/include/asm/gpr-num.h
 create mode 100644 xen/arch/riscv/include/asm/mmio.h
 create mode 100644 xen/arch/riscv/mmio.c
Signature · 1 line
2.55.0
#1 lore raw

PATCH v2 1/39 xen/riscv: drop pregs from struct cpu_user_regs

As nothing is using pregs in upstream or downstream ports of RISC-V drop it from struct cpu_user_regs. Once it will really be needed re-introduce it.

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

---
 xen/arch/riscv/include/asm/processor.h | 2 --
 xen/arch/riscv/riscv64/asm-offsets.c   | 1 -
 2 files changed, 3 deletions(-)
xen/arch/riscv/include/asm/processor.h +0 -2
index 6b89df4a2d4f..b1745c107100 100644
@@ -50,8 +50,6 @@ struct cpu_user_regs
     unsigned long sepc;
     unsigned long sstatus;
     unsigned long hstatus;
-    /* pointer to previous stack_cpu_regs */
-    unsigned long pregs;
 };
 
 /* TODO: need to implement */
xen/arch/riscv/riscv64/asm-offsets.c +0 -1
index 472cced4f8af..1290b9dbbe82 100644
@@ -50,7 +50,6 @@ void asm_offsets(void)
     OFFSET(CPU_USER_REGS_SEPC, struct cpu_user_regs, sepc);
     OFFSET(CPU_USER_REGS_SSTATUS, struct cpu_user_regs, sstatus);
     OFFSET(CPU_USER_REGS_HSTATUS, struct cpu_user_regs, hstatus);
-    OFFSET(CPU_USER_REGS_PREGS, struct cpu_user_regs, pregs);
     BLANK();
     DEFINE(PCPU_INFO_SIZE, sizeof(struct pcpu_info));
     BLANK();
Signature · 1 line
2.55.0
Reviewed-by on v2 1/39
#2 lore raw

Re: [PATCH v2 01/39] xen/riscv: drop pregs from struct cpu_user_regs

Quoted 3 lines · Oleksii Kurochko

As nothing is using pregs in upstream or downstream ports of RISC-V drop it from struct cpu_user_regs. Once it will really be needed re-introduce it.

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

PATCH v2 2/39 xen/riscv: drop bug.h's duplicate instruction length helpers

In reply to Oleksii Kurochko

asm/riscv_encoding.h already provides INSN_16BIT_MASK and INSN_LEN(), and emulate.c uses them, so the tree carried two spellings of the same thing which could drift apart. COMPRESSED_INSN_MASK never had a user.

No functional change.

---
Changes in v2:
- new patch.
---

---
 xen/arch/riscv/include/asm/bug.h | 19 -------------------
 xen/arch/riscv/traps.c           |  2 +-
 2 files changed, 1 insertion(+), 20 deletions(-)
xen/arch/riscv/include/asm/bug.h +0 -19
index e6f286881662..c2cdc2dc2a46 100644
@@ -13,25 +13,6 @@
 
 #define BUG_INSTR "unimp"
 
-/*
- * The base instruction set has a fixed length of 32-bit naturally aligned
- * instructions.
- *
- * There are extensions of variable length ( where each instruction can be
- * any number of 16-bit parcels in length ).
- *
- * Compressed ISA is used now where the instruction length is 16 bit and
- * 'unimp' instruction, in this case, can be either 16 or 32 bit (
- * depending on if compressed ISA is used or not )
- */
-#define INSN_LENGTH_MASK        _UL(0x3)
-#define INSN_LENGTH_32          _UL(0x3)
-
-#define COMPRESSED_INSN_MASK    _UL(0xffff)
-
-#define GET_INSN_LENGTH(insn)                               \
-    (((insn) & INSN_LENGTH_MASK) == INSN_LENGTH_32 ? 4 : 2) \
-
 #endif /* !__ASSEMBLER__ */
 
 #endif /* ASM__RISCV__BUG_H */
xen/arch/riscv/traps.c +1 -1
index d35c013e1399..8530e6fbda0a 100644
@@ -214,7 +214,7 @@ void do_trap(struct cpu_user_regs *cpu_regs)
                 die();
             }
 
-            cpu_regs->sepc += GET_INSN_LENGTH(*(uint16_t *)pc);
+            cpu_regs->sepc += INSN_LEN(*(uint16_t *)pc);
 
             break;
         }
Signature · 1 line
2.55.0
Reviewed-by on v2 2/39
#5 lore raw

Re: [PATCH v2 02/39] xen/riscv: drop bug.h's duplicate instruction length helpers

Quoted 8 lines · Oleksii Kurochko

asm/riscv_encoding.h already provides INSN_16BIT_MASK and INSN_LEN(), and emulate.c uses them, so the tree carried two spellings of the same thing which could drift apart. COMPRESSED_INSN_MASK never had a user.

No functional change.

[...]

Signature · 1 line
Baptiste Le Duc <[email protected]>
Acked-by on v2 2/39
#6 lore raw

Re: [PATCH v2 02/39] xen/riscv: drop bug.h's duplicate instruction length helpers

In reply to Oleksii Kurochko
Quoted 7 lines · Oleksii Kurochko

asm/riscv_encoding.h already provides INSN_16BIT_MASK and INSN_LEN(), and emulate.c uses them, so the tree carried two spellings of the same thing which could drift apart. COMPRESSED_INSN_MASK never had a user.

No functional change.

As I'm happy to see the duplication go away:

However, ...

xen/arch/riscv/traps.c void do_trap(struct cpu_user_regs *cpu_regs) · line 217

Quoted 8 lines
xen/arch/riscv/traps.c +1 -1
@@ -214,7 +214,7 @@ void do_trap(struct cpu_user_regs *cpu_regs)
                 die();
             }
 
-            cpu_regs->sepc += GET_INSN_LENGTH(*(uint16_t *)pc);
+            cpu_regs->sepc += INSN_LEN(*(uint16_t *)pc);

... for one I'd prefer if we took the opportunity and add "const" to the pointer target here.

And then

#define INSN_16BIT_MASK 0x3
#define INSN_32BIT_MASK 0x1c

are really named backwards, seeing e.g. their use in

#define INSN_IS_16BIT(insn)		\
	(((insn) & INSN_16BIT_MASK) != INSN_16BIT_MASK)
#define INSN_IS_32BIT(insn)		\
	(((insn) & INSN_16BIT_MASK) == INSN_16BIT_MASK && \
	 ((insn) & INSN_32BIT_MASK) != INSN_32BIT_MASK)

Furthermore,

#define INSN_LEN(insn) (INSN_IS_16BIT(insn) ? 2 : 4)

fails to use INSN_32BIT_MASK / INSN_IS_32BIT() altogether.

Jan

#7 lore raw

Re: [PATCH v2 02/39] xen/riscv: drop bug.h's duplicate instruction length helpers

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

asm/riscv_encoding.h already provides INSN_16BIT_MASK and INSN_LEN(), and emulate.c uses them, so the tree carried two spellings of the same thing which could drift apart. COMPRESSED_INSN_MASK never had a user.

No functional change.

As I'm happy to see the duplication go away:

Thanks.

Quoted 8 lines

However, ...

Quoted 6 lines
xen/arch/riscv/traps.c +0 -0
@@ -214,7 +214,7 @@ void do_trap(struct cpu_user_regs *cpu_regs)
                  die();
              }
 
Quoted 5 lines

xen/arch/riscv/traps.c void do_trap(struct cpu_user_regs *cpu_regs) · line 217

Quoted 2 lines
xen/arch/riscv/traps.c +1 -1
-            cpu_regs->sepc += GET_INSN_LENGTH(*(uint16_t *)pc);
+            cpu_regs->sepc += INSN_LEN(*(uint16_t *)pc);

... for one I'd prefer if we took the opportunity and add "const" to the pointer target here.

Thanks for adding 'const' during commit.

Quoted 7 lines

And then

#define INSN_16BIT_MASK 0x3
#define INSN_32BIT_MASK 0x1c

are really named backwards, seeing e.g. their use in

It was derived from OpenSBI project and I haven't paid enough attention for these defines.

Now looking at them again I fully agree that names here not really correct. It should be according to the spec:
#define INSN_32BIT_MASK 0x3
#define INSN_48BIT_MASK 0x1c

Then ...

Quoted 6 lines
#define INSN_IS_16BIT(insn)		\
	(((insn) & INSN_16BIT_MASK) != INSN_16BIT_MASK)
#define INSN_IS_32BIT(insn)		\
	(((insn) & INSN_16BIT_MASK) == INSN_16BIT_MASK && \
	 ((insn) & INSN_32BIT_MASK) != INSN_32BIT_MASK)

...

#define INSN_IS_16BIT(insn)      \
    (((insn) & INSN_32BIT_MASK) != INSN_32BIT_MASK)
#define INSN_IS_32BIT(insn)      \
    ((((insn) & INSN_32BIT_MASK) == INSN_32BIT_MASK) && \
     (((insn) & INSN_48BIT_MASK) != INSN_48BIT_MASK))
Quoted 6 lines

Furthermore,

#define INSN_LEN(insn) (INSN_IS_16BIT(insn) ? 2 : 4)

fails to use INSN_32BIT_MASK / INSN_IS_32BIT() altogether.

Then INSN_LEN will be redefined as:

/*
* Length in bytes of the instruction whose first parcel is @insn. Callers
* must have established that the encoding is 16- or 32-bit wide; the ISA
* defines no instruction wider than that, and the wider encodings are
* reserved.
*/

#define INSN_LEN(insn) \
    (INSN_IS_16BIT(insn) ? 2 : (INSN_IS_32BIT(insn) ? 4 : 0))

I am thinking if it makes sense to have here the generic way to calculate INSN_LEN. Something like:

/*
* Length in bytes of the instruction whose first 16-bit parcel is
@insn, or
* zero for the encoding reserved for instructions of 192 bits or more,
whose
* length the ISA leaves unspecified. See "Expanded Instruction-Length
* Encoding" in the unprivileged spec; the first parcel holds all of the
* information needed.
*/
static inline unsigned int INSN_LEN(uint16_t insn)

{
    unsigned int nnn;

    if ( INSN_IS_16BIT(insn) )
        return 2;

    if ( INSN_IS_32BIT(insn) )
        return 4;

    if ( INSN_IS_48BIT(insn) )
        return 6;

    if ( INSN_IS_64BIT(insn) )
        return 8;

    /* xnnnxxxxx1111111 with nnn != 111 is (80 + 16 * nnn) bits wide. */
    nnn = MASK_EXTR(insn, INSN_NNN_MASK);

    return (nnn == 7) ? 0 : 10 + 2 * nnn;
}

I think that for now it is enough to go without common implmenntation of INSN_LEN and just return 0 as suggested above.

If you are okay with suggested changes I will send a separate patch for them.

~ Oleksii

#8 lore raw

Re: [PATCH v2 02/39] xen/riscv: drop bug.h's duplicate instruction length helpers

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

And then

#define INSN_16BIT_MASK 0x3
#define INSN_32BIT_MASK 0x1c

are really named backwards, seeing e.g. their use in

Quoted 7 lines

It was derived from OpenSBI project and I haven't paid enough attention for these defines.

Now looking at them again I fully agree that names here not really correct. It should be according to the spec:

    #define INSN_32BIT_MASK          0x3
    #define INSN_48BIT_MASK          0x1c

Especially the latter would then still be misnamed, as the mask merely identifies insns >= 48 bits. Even for the former I'd still question the name to some degree ("mask" doesn't mean all of the bits need to be set).

In how many places are you going to need these constants? If, by suitably using helpers, it's just one - maybe better to get away without any named constants in this case (i.e. when suitable names are apparently difficult to come up with)?

Quoted 2 lines

I think that for now it is enough to go without common implmenntation of INSN_LEN and just return 0 as suggested above.

Suitably commented upon that would certainly be okay with me.

Jan

#9 lore raw

Re: [PATCH v2 02/39] xen/riscv: drop bug.h's duplicate instruction length helpers

Quoted 17 lines · Jan Beulich
Quoted 8 lines · Oleksii Kurochko
Quoted 6 lines · Jan Beulich

And then

#define INSN_16BIT_MASK 0x3
#define INSN_32BIT_MASK 0x1c

are really named backwards, seeing e.g. their use in

Quoted 7 lines

It was derived from OpenSBI project and I haven't paid enough attention for these defines.

Now looking at them again I fully agree that names here not really correct. It should be according to the spec:

     #define INSN_32BIT_MASK          0x3
     #define INSN_48BIT_MASK          0x1c
Quoted 8 lines

Especially the latter would then still be misnamed, as the mask merely identifies insns >= 48 bits. Even for the former I'd still question the name to some degree ("mask" doesn't mean all of the bits need to be set).

In how many places are you going to need these constants? If, by suitably using helpers, it's just one - maybe better to get away without any named constants in this case (i.e. when suitable names are apparently difficult to come up with)?

INSN_16BIT_MASK - will be used only once (except INSN_IS_32BIT() and INSN_IS_16BIT()) in insn_fetch_faulted() introduced later in this patch series:

        di->insn = htinst | INSN_16BIT_MASK;

INSN_32BIT_MASK - is used only inside INSN_IS_32BIT().

And INSN_IS_32BIT() and INSN_IS_16BIT() are using in several places.

I am okay to drop these masks and then just have a comment:

/*
* Instruction length encoding helpers (see RISC-V Unprivileged ISA,
* Section "Base Instruction-Length Encoding").
*
* - Instructions with bits [1:0] != 11 are 16-bit (compressed).
* - Instructions with bits [1:0] == 11 and bits [4:2] != 111 are 32-bit. */
#define INSN_IS_16BIT(insn) (((insn) & 0x3) != 0x3)
#define INSN_IS_32BIT(insn) (((insn) & 0x3) == 0x3 && ((insn) & 0x1c) != 0x1c)

As an option we could come up with the following names:

/* Bitmasks for instruction length encoding fields */

#define INSN_LEN_1_0_MASK        0x3   /* Bits [1:0] for 16-bit vs >=32-bit */
#define INSN_LEN_4_2_MASK        0x1c  /* Bits [4:2] for 32-bit vs >=48-bit */

#define INSN_IS_16BIT(insn) (((insn) & INSN_LEN_1_0_MASK) != INSN_LEN_1_0_MASK)

#define INSN_IS_32BIT(insn)      \
    (((insn) & INSN_LEN_1_0_MASK) == INSN_LEN_1_0_MASK && \
     ((insn) & INSN_LEN_4_2_MASK) != INSN_LEN_4_2_MASK)

But it seems the first option still looks better.

Would you also prefer Option 1?

Quoted 5 lines
Quoted 3 lines

I think that for now it is enough to go without common implmenntation of INSN_LEN and just return 0 as suggested above.

Suitably commented upon that would certainly be okay with me.

The the following comment looks good enough for me:

/*
* Length in bytes of the instruction whose first parcel is @insn: 2 or
4, or
* 0 when the encoding is 48 bits or wider. No ratified extension
defines an
* instruction of such a length, so rather than open-coding a decoder for
* encodings which cannot legitimately occur, leave it to the caller to
treat
* the 0 as an illegal instruction.
*/

#define INSN_LEN(insn) \
    (INSN_IS_16BIT(insn) ? 2 : (INSN_IS_32BIT(insn) ? 4 : 0))

~ Oleksii

#10 lore raw

Re: [PATCH v2 02/39] xen/riscv: drop bug.h's duplicate instruction length helpers

Quoted 38 lines · Oleksii Kurochko
Quoted 17 lines · Jan Beulich
Quoted 8 lines · Oleksii Kurochko
Quoted 6 lines · Jan Beulich

And then

#define INSN_16BIT_MASK 0x3
#define INSN_32BIT_MASK 0x1c

are really named backwards, seeing e.g. their use in

Quoted 7 lines

It was derived from OpenSBI project and I haven't paid enough attention for these defines.

Now looking at them again I fully agree that names here not really correct. It should be according to the spec:

     #define INSN_32BIT_MASK          0x3
     #define INSN_48BIT_MASK          0x1c
Quoted 8 lines

Especially the latter would then still be misnamed, as the mask merely identifies insns >= 48 bits. Even for the former I'd still question the name to some degree ("mask" doesn't mean all of the bits need to be set).

In how many places are you going to need these constants? If, by suitably using helpers, it's just one - maybe better to get away without any named constants in this case (i.e. when suitable names are apparently difficult to come up with)?

INSN_16BIT_MASK - will be used only once (except INSN_IS_32BIT() and INSN_IS_16BIT()) in insn_fetch_faulted() introduced later in this patch series:

         di->insn = htinst | INSN_16BIT_MASK;

INSN_32BIT_MASK - is used only inside INSN_IS_32BIT().

And INSN_IS_32BIT() and INSN_IS_16BIT() are using in several places.

I am okay to drop these masks and then just have a comment:

Quoted 10 lines

/*
* Instruction length encoding helpers (see RISC-V Unprivileged ISA,
* Section "Base Instruction-Length Encoding").
*
* - Instructions with bits [1:0] != 11 are 16-bit (compressed).
* - Instructions with bits [1:0] == 11 and bits [4:2] != 111 are 32-bit. */
#define INSN_IS_16BIT(insn) (((insn) & 0x3) != 0x3)
#define INSN_IS_32BIT(insn) (((insn) & 0x3) == 0x3 && ((insn) &
0x1c) != 0x1c)

Largely okay; I'd still prefer

#define INSN_IS_16BIT(insn) (((insn) & 3) != 3)
#define INSN_IS_32BIT(insn) (!INSN_IS_16BIT(insn) && ((insn) & 0x1c) != 0x1c)

Quoted 10 lines

As an option we could come up with the following names:

/* Bitmasks for instruction length encoding fields */
#define INSN_LEN_1_0_MASK 0x3 /* Bits [1:0] for 16-bit vs

Quoted 1 line

=32-bit */

#define INSN_LEN_4_2_MASK 0x1c /* Bits [4:2] for 32-bit vs

Quoted 1 line

=48-bit */

#define INSN_IS_16BIT(insn) (((insn) & INSN_LEN_1_0_MASK) !=
INSN_LEN_1_0_MASK)

Quoted 7 lines
#define INSN_IS_32BIT(insn)      \
     (((insn) & INSN_LEN_1_0_MASK) == INSN_LEN_1_0_MASK && \
      ((insn) & INSN_LEN_4_2_MASK) != INSN_LEN_4_2_MASK)

But it seems the first option still looks better.

Would you also prefer Option 1?

I do, yes.

Quoted 17 lines
Quoted 4 lines
Quoted 2 lines

I think that for now it is enough to go without common implmenntation of INSN_LEN and just return 0 as suggested above.

Suitably commented upon that would certainly be okay with me.

The the following comment looks good enough for me:

/*
* Length in bytes of the instruction whose first parcel is @insn: 2 or
4, or
* 0 when the encoding is 48 bits or wider. No ratified extension
defines an
* instruction of such a length, so rather than open-coding a decoder for
* encodings which cannot legitimately occur, leave it to the caller to
treat
* the 0 as an illegal instruction.
*/

Quoted 2 lines
#define INSN_LEN(insn) \
     (INSN_IS_16BIT(insn) ? 2 : (INSN_IS_32BIT(insn) ? 4 : 0))

Reads okay, thanks.

Jan

#11 lore raw

PATCH v2 3/39 xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

In reply to Oleksii Kurochko

hstatus.VSXL is WARL, so its reset value is implementation-defined. Xen supports 64-bit guests only, so program it explicitly instead of relying on whatever the hardware happens to leave there.

This matters beyond the guest's own view of itself: decoding a trapped instruction depends on the effective XLEN of the guest, as the encodings which exist for XLEN=64 only must not be recognized for a 32-bit one.

---
Changes in v2:
- new patch
---

---
 xen/arch/riscv/domain.c                     | 8 +++++++-
 xen/arch/riscv/include/asm/riscv_encoding.h | 2 ++
 2 files changed, 9 insertions(+), 1 deletion(-)
xen/arch/riscv/domain.c +7 -1
index d94652809e36..57c37cb2dfc2 100644
@@ -88,7 +88,13 @@ static void vcpu_csr_init(struct vcpu *v)
 {
     v->arch.hedeleg = HEDELEG_DEFAULT & csr_masks.hedeleg;
 
-    vcpu_guest_cpu_user_regs(v)->hstatus = HSTATUS_SPV | HSTATUS_SPVP;
+    /*
+     * Xen supports 64-bit guests only, so set the guest's XLEN explicitly
+     * rather than leaving it to the WARL behaviour of hstatus.VSXL, which the
+     * decoding of a trapped instruction depends on.
+     */
+    vcpu_guest_cpu_user_regs(v)->hstatus =
+        HSTATUS_SPV | HSTATUS_SPVP | MASK_INSR(HSTATUS_VSXL_64, HSTATUS_VSXL);
 
     v->arch.hideleg = HIDELEG_DEFAULT & csr_masks.hideleg;
 
xen/arch/riscv/include/asm/riscv_encoding.h +2 -0
index 03e186bcdb8c..c63e5e304691 100644
@@ -68,6 +68,8 @@
 #if __riscv_xlen == 64
 #define HSTATUS_VSXL			_UL(0x300000000)
 #define HSTATUS_VSXL_SHIFT		32
+#define HSTATUS_VSXL_64			_UL(2)
+#define HSTATUS_VSXL_32			_UL(1)
 #endif
 #define HSTATUS_VTSR			_UL(0x00400000)
 #define HSTATUS_VTW			_UL(0x00200000)
Signature · 1 line
2.55.0
#12 lore raw

Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

Quoted 8 lines

hstatus.VSXL is WARL, so its reset value is implementation-defined. Xen supports 64-bit guests only, so program it explicitly instead of relying on whatever the hardware happens to leave there.

This matters beyond the guest's own view of itself: decoding a trapped instruction depends on the effective XLEN of the guest, as the encodings which exist for XLEN=64 only must not be recognized for a 32-bit one.

It's not clear which instruction "decoding a trapped instruction" refers to without more context. I assume you mean decode_ldst_insn() in emulate.c, but the patch introducing that function comes later in the series, so this isn't obvious on a first read.

Please reorder the series so this patch follows the one introducing decode_ldst_insn(), or reference it explicitly in the commit message (e.g. "load/store trap emulation, introduced later in this series in emulate.c, needs...").

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

Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

Quoted 13 lines · Baptiste Le Duc
Quoted 8 lines

hstatus.VSXL is WARL, so its reset value is implementation-defined. Xen supports 64-bit guests only, so program it explicitly instead of relying on whatever the hardware happens to leave there.

This matters beyond the guest's own view of itself: decoding a trapped instruction depends on the effective XLEN of the guest, as the encodings which exist for XLEN=64 only must not be recognized for a 32-bit one.

It's not clear which instruction "decoding a trapped instruction" refers to without more context. I assume you mean decode_ldst_insn() in emulate.c, but the patch introducing that function comes later in the series, so this isn't obvious on a first read.

Quoted 4 lines

Please reorder the series so this patch follows the one introducing decode_ldst_insn(), or reference it explicitly in the commit message (e.g. "load/store trap emulation, introduced later in this series in emulate.c, needs...").

Just to remind you: No "later in this series" or alike in patch descriptions please. Such wording loses meaning when viewed in git history.

Jan

#14 lore raw

Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

In reply to Baptiste Le Duc
Quoted 13 lines · Baptiste Le Duc
Quoted 8 lines

hstatus.VSXL is WARL, so its reset value is implementation-defined. Xen supports 64-bit guests only, so program it explicitly instead of relying on whatever the hardware happens to leave there.

This matters beyond the guest's own view of itself: decoding a trapped instruction depends on the effective XLEN of the guest, as the encodings which exist for XLEN=64 only must not be recognized for a 32-bit one.

It's not clear which instruction "decoding a trapped instruction" refers to without more context. I assume you mean decode_ldst_insn() in emulate.c, but the patch introducing that function comes later in the series, so this isn't obvious on a first read.

Quoted 5 lines

Please reorder the series so this patch follows the one introducing decode_ldst_insn(), or reference it explicitly in the commit message (e.g. "load/store trap emulation, introduced later in this series in emulate.c, needs...").

I think I can just drop this paragraph from commit message. Even without it considering that we are supporting only rv64 guest we should set hstatus.VSXL correspondingly and not rely on what hardware will put there.

~ Oleksii

#15 lore raw

Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

In reply to Baptiste Le Duc
Quoted 10 lines · Baptiste Le Duc
Quoted 8 lines

hstatus.VSXL is WARL, so its reset value is implementation-defined. Xen supports 64-bit guests only, so program it explicitly instead of relying on whatever the hardware happens to leave there.

This matters beyond the guest's own view of itself: decoding a trapped instruction depends on the effective XLEN of the guest, as the encodings which exist for XLEN=64 only must not be recognized for a 32-bit one.

It's not clear which instruction "decoding a trapped instruction" refers to without more context.

Use "decoding of trapped instructions" instead? (I think I'd prefer the paragraph to remain here.)

Jan

Quoted 9 lines

I assume you mean decode_ldst_insn() in
emulate.c, but the patch introducing that function comes later in the series, so this isn't obvious on a first read.

Please reorder the series so this patch follows the one introducing decode_ldst_insn(), or reference it explicitly in the commit message (e.g. "load/store trap emulation, introduced later in this series in emulate.c, needs...").

#16 lore raw

Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

In reply to Oleksii Kurochko
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/domain.c +0 -0
@@ -88,7 +88,13 @@ static void vcpu_csr_init(struct vcpu *v)
 {

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 97

Quoted 10 lines
xen/arch/riscv/domain.c +7 -1
     v->arch.hedeleg = HEDELEG_DEFAULT & csr_masks.hedeleg;
 
-    vcpu_guest_cpu_user_regs(v)->hstatus = HSTATUS_SPV | HSTATUS_SPVP;
+    /*
+     * Xen supports 64-bit guests only, so set the guest's XLEN explicitly
+     * rather than leaving it to the WARL behaviour of hstatus.VSXL, which the
+     * decoding of a trapped instruction depends on.
+     */
+    vcpu_guest_cpu_user_regs(v)->hstatus =
+        HSTATUS_SPV | HSTATUS_SPVP | MASK_INSR(HSTATUS_VSXL_64, HSTATUS_VSXL);

The comment is correct right now, but the situation better would change at some point. Can't you arrange for things to be correct here also for a future where 32- and 128-bit guests would also be supported?

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

Quoted 9 lines
xen/arch/riscv/include/asm/riscv_encoding.h +2 -0
@@ -68,6 +68,8 @@
 #if __riscv_xlen == 64
 #define HSTATUS_VSXL			_UL(0x300000000)
 #define HSTATUS_VSXL_SHIFT		32
+#define HSTATUS_VSXL_64			_UL(2)
+#define HSTATUS_VSXL_32			_UL(1)
 #endif

While adding the two #define-s, would you mind considering to remove the unused (and supposed to remain so) HSTATUS_VSXL_SHIFT?

Jan

#17 lore raw

Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

Quoted 7 lines · Jan Beulich
Quoted 6 lines · Oleksii Kurochko
xen/arch/riscv/domain.c +0 -0
@@ -88,7 +88,13 @@ static void vcpu_csr_init(struct vcpu *v)
  {
      v->arch.hedeleg = HEDELEG_DEFAULT & csr_masks.hedeleg;
 
Quoted 12 lines

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 97

Quoted 8 lines
xen/arch/riscv/domain.c +7 -1
-    vcpu_guest_cpu_user_regs(v)->hstatus = HSTATUS_SPV | HSTATUS_SPVP;
+    /*
+     * Xen supports 64-bit guests only, so set the guest's XLEN explicitly
+     * rather than leaving it to the WARL behaviour of hstatus.VSXL, which the
+     * decoding of a trapped instruction depends on.
+     */
+    vcpu_guest_cpu_user_regs(v)->hstatus =
+        HSTATUS_SPV | HSTATUS_SPVP | MASK_INSR(HSTATUS_VSXL_64, HSTATUS_VSXL);

The comment is correct right now, but the situation better would change at some point. Can't you arrange for things to be correct here also for a future where 32- and 128-bit guests would also be supported?

I am not sure about 128-bit guests as H extension is dependent on RV32 or RV64 but probably it will be changed:

```
The hypervisor extension depends on an "I" base integer ISA with 32 x registers (RV32I or RV64I), not RV32E or RV64E, which have only 16 x registers.
```

I will introduce the following (also it will be needed also to check if we could VSXL set at all as implmentation can make that field read-only and do VSXLLEN=HSXLEN):

/*
* Return the hstatus.VSXL value encoding the guest's XLEN. The switch()
* deliberately has no default case, so that adding a new domain_type (a
* 128-bit one, in particular) fails to build until this mapping is
updated.
*/
static unsigned int domain_vsxl(const struct domain *d)

{
    switch ( d->type )
    {
    case DOMAIN_32BIT:
        return HSTATUS_VSXL_32;

    case DOMAIN_64BIT:
        return HSTATUS_VSXL_64;
    }

    ASSERT_UNREACHABLE();

    return HSTATUS_VSXL_64;
}

It will also affect then common code as vcpu_csr_init() could be then called before domain type is set:

+++ b/xen/common/device-tree/dom0less-build.c
@@ -812,17 +812,18 @@ static int __init construct_domU(struct kernel_info *kinfo,

     else if ( rc == 0 && !strcmp(dom0less_enhanced, "no-xenstore") )
         kinfo->dom0less_feature = DOM0LESS_ENHANCED_NO_XS;

- if ( vcpu_create(d, 0) == NULL )
- return -ENOMEM;
-

     d->max_pages = ((paddr_t)mem * SZ_1K) >> PAGE_SHIFT;

     rc = kernel_probe(kinfo, node);
     if ( rc < 0 )
         return rc;

+ /* The domain type needs to be known before the first vCPU is created. */

     set_domain_type(d, kinfo);

+ if ( vcpu_create(d, 0) == NULL )
+ return -ENOMEM;

Quoted 13 lines

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

Quoted 10 lines
xen/arch/riscv/include/asm/riscv_encoding.h +2 -0
@@ -68,6 +68,8 @@
  #if __riscv_xlen == 64
  #define HSTATUS_VSXL			_UL(0x300000000)
  #define HSTATUS_VSXL_SHIFT		32
+#define HSTATUS_VSXL_64			_UL(2)
+#define HSTATUS_VSXL_32			_UL(1)
  #endif

While adding the two #define-s, would you mind considering to remove the unused (and supposed to remain so) HSTATUS_VSXL_SHIFT?

Sure, I will drop that.

Thanks.

~ Oleksii

#18 lore raw

Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

Quoted 21 lines · Oleksii Kurochko
Quoted 7 lines · Jan Beulich
Quoted 6 lines · Oleksii Kurochko
xen/arch/riscv/domain.c +0 -0
@@ -88,7 +88,13 @@ static void vcpu_csr_init(struct vcpu *v)
  {
      v->arch.hedeleg = HEDELEG_DEFAULT & csr_masks.hedeleg;
 
Quoted 12 lines

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 97

Quoted 8 lines
xen/arch/riscv/domain.c +7 -1
-    vcpu_guest_cpu_user_regs(v)->hstatus = HSTATUS_SPV | HSTATUS_SPVP;
+    /*
+     * Xen supports 64-bit guests only, so set the guest's XLEN explicitly
+     * rather than leaving it to the WARL behaviour of hstatus.VSXL, which the
+     * decoding of a trapped instruction depends on.
+     */
+    vcpu_guest_cpu_user_regs(v)->hstatus =
+        HSTATUS_SPV | HSTATUS_SPVP | MASK_INSR(HSTATUS_VSXL_64, HSTATUS_VSXL);

The comment is correct right now, but the situation better would change at some point. Can't you arrange for things to be correct here also for a future where 32- and 128-bit guests would also be supported?

Quoted 7 lines

I am not sure about 128-bit guests as H extension is dependent on RV32 or RV64 but probably it will be changed:

```
The hypervisor extension depends on an "I" base integer ISA with 32 x 
registers (RV32I or RV64I), not RV32E or RV64E, which have only 16 x 
registers.
```

Lots of updates like this likely will be needed for RV128 to actually become a thing.

Quoted 11 lines

I will introduce the following (also it will be needed also to check if we could VSXL set at all as implmentation can make that field read-only and do VSXLLEN=HSXLEN):

/*
* Return the hstatus.VSXL value encoding the guest's XLEN. The switch()
* deliberately has no default case, so that adding a new domain_type (a
* 128-bit one, in particular) fails to build until this mapping is
updated.
*/
static unsigned int domain_vsxl(const struct domain *d)

Quoted 13 lines
{
     switch ( d->type )
     {
     case DOMAIN_32BIT:
         return HSTATUS_VSXL_32;

     case DOMAIN_64BIT:
         return HSTATUS_VSXL_64;
     }

     ASSERT_UNREACHABLE();

     return HSTATUS_VSXL_64;

Why not simply return 0 here? You genuinely don't know the size.

Quoted 24 lines

}

It will also affect then common code as vcpu_csr_init() could be then called before domain type is set:

+++ b/xen/common/device-tree/dom0less-build.c

(quoted diff) +1 -3
@@ -812,17 +812,18 @@ static int __init construct_domU(struct 
 kernel_info *kinfo,
      else if ( rc == 0 && !strcmp(dom0less_enhanced, "no-xenstore") )
          kinfo->dom0less_feature = DOM0LESS_ENHANCED_NO_XS;
 
-    if ( vcpu_create(d, 0) == NULL )
-        return -ENOMEM;
-
      d->max_pages = ((paddr_t)mem * SZ_1K) >> PAGE_SHIFT;
 
      rc = kernel_probe(kinfo, node);
      if ( rc < 0 )
          return rc;
 
+    /* The domain type needs to be known before the first vCPU is 

created. */

      set_domain_type(d, kinfo);

Review

Quoted 2 lines
(quoted diff) +2 -0
+    if ( vcpu_create(d, 0) == NULL )
+        return -ENOMEM;

I don't understand the need for this, likely because I don't see why domain_vsxl() would need calling from underneath vcpu_create().

Jan

#19 lore raw

Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

Quoted 54 lines · Jan Beulich
Quoted 21 lines · Oleksii Kurochko
Quoted 7 lines · Jan Beulich
Quoted 6 lines · Oleksii Kurochko
xen/arch/riscv/domain.c +0 -0
@@ -88,7 +88,13 @@ static void vcpu_csr_init(struct vcpu *v)
   {
       v->arch.hedeleg = HEDELEG_DEFAULT & csr_masks.hedeleg;
 
Quoted 12 lines

xen/arch/riscv/domain.c static void vcpu_csr_init(struct vcpu *v) · line 97

Quoted 8 lines
xen/arch/riscv/domain.c +7 -1
-    vcpu_guest_cpu_user_regs(v)->hstatus = HSTATUS_SPV | HSTATUS_SPVP;
+    /*
+     * Xen supports 64-bit guests only, so set the guest's XLEN explicitly
+     * rather than leaving it to the WARL behaviour of hstatus.VSXL, which the
+     * decoding of a trapped instruction depends on.
+     */
+    vcpu_guest_cpu_user_regs(v)->hstatus =
+        HSTATUS_SPV | HSTATUS_SPVP | MASK_INSR(HSTATUS_VSXL_64, HSTATUS_VSXL);

The comment is correct right now, but the situation better would change at some point. Can't you arrange for things to be correct here also for a future where 32- and 128-bit guests would also be supported?

Quoted 7 lines

I am not sure about 128-bit guests as H extension is dependent on RV32 or RV64 but probably it will be changed:

```
The hypervisor extension depends on an "I" base integer ISA with 32 x
registers (RV32I or RV64I), not RV32E or RV64E, which have only 16 x
registers.
```

Lots of updates like this likely will be needed for RV128 to actually become a thing.

Quoted 21 lines

I will introduce the following (also it will be needed also to check if we could VSXL set at all as implmentation can make that field read-only and do VSXLLEN=HSXLEN):

/*
* Return the hstatus.VSXL value encoding the guest's XLEN. The switch()
* deliberately has no default case, so that adding a new domain_type (a
* 128-bit one, in particular) fails to build until this mapping is
updated.
*/
static unsigned int domain_vsxl(const struct domain *d)

{
      switch ( d->type )
      {
      case DOMAIN_32BIT:
          return HSTATUS_VSXL_32;

      case DOMAIN_64BIT:
          return HSTATUS_VSXL_64;
      }
Quoted 5 lines
Quoted 3 lines
      ASSERT_UNREACHABLE();

      return HSTATUS_VSXL_64;

Why not simply return 0 here? You genuinely don't know the size.

Agree, just 0 will be better.

Quoted 25 lines
Quoted 25 lines

}

It will also affect then common code as vcpu_csr_init() could be then called before domain type is set:

+++ b/xen/common/device-tree/dom0less-build.c

(quoted diff) +1 -3
@@ -812,17 +812,18 @@ static int __init construct_domU(struct
 kernel_info *kinfo,
       else if ( rc == 0 && !strcmp(dom0less_enhanced, "no-xenstore") )
           kinfo->dom0less_feature = DOM0LESS_ENHANCED_NO_XS;
 
-    if ( vcpu_create(d, 0) == NULL )
-        return -ENOMEM;
-
       d->max_pages = ((paddr_t)mem * SZ_1K) >> PAGE_SHIFT;
 
       rc = kernel_probe(kinfo, node);
       if ( rc < 0 )
           return rc;
 
+    /* The domain type needs to be known before the first vCPU is

created. */

       set_domain_type(d, kinfo);
Quoted 5 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+    if ( vcpu_create(d, 0) == NULL )
+        return -ENOMEM;

I don't understand the need for this, likely because I don't see why domain_vsxl() would need calling from underneath vcpu_create().

The call trace will be the following:
vcpu_create() -> arch_vcpu_create() -> vcpu_csr_init() ->
domain_vsxldomain_vsxl()

    unsigned int vsxl = domain_vsxl(v->domain);

    ...

    vcpu_guest_cpu_user_regs(v)->hstatus =
        HSTATUS_SPV | HSTATUS_SPVP | MASK_INSR(vsxl, HSTATUS_VSXL);

Without moving vcpu_create(d, 0) after set_domain_type(), domain_vsxl() will return something wrong.

I also thought about updating of VSXL for each vCPU in construct_domain() where d->type is already known and then no changes in common code are needed. But I think it is a little bit better just have a change in common code.

~ Oleksii

#20 lore raw

Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

Quoted 41 lines · Oleksii Kurochko
Quoted 23 lines · Jan Beulich
Quoted 22 lines · Oleksii Kurochko

It will also affect then common code as vcpu_csr_init() could be then called before domain type is set:

+++ b/xen/common/device-tree/dom0less-build.c

(quoted diff) +1 -3
@@ -812,17 +812,18 @@ static int __init construct_domU(struct
 kernel_info *kinfo,
       else if ( rc == 0 && !strcmp(dom0less_enhanced, "no-xenstore") )
           kinfo->dom0less_feature = DOM0LESS_ENHANCED_NO_XS;
 
-    if ( vcpu_create(d, 0) == NULL )
-        return -ENOMEM;
-
       d->max_pages = ((paddr_t)mem * SZ_1K) >> PAGE_SHIFT;
 
       rc = kernel_probe(kinfo, node);
       if ( rc < 0 )
           return rc;
 
+    /* The domain type needs to be known before the first vCPU is

created. */

       set_domain_type(d, kinfo);
Quoted 5 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+    if ( vcpu_create(d, 0) == NULL )
+        return -ENOMEM;

I don't understand the need for this, likely because I don't see why domain_vsxl() would need calling from underneath vcpu_create().

The call trace will be the following:

   vcpu_create() -> arch_vcpu_create() -> vcpu_csr_init() -> 

domain_vsxldomain_vsxl()

     unsigned int vsxl = domain_vsxl(v->domain);

     ...

     vcpu_guest_cpu_user_regs(v)->hstatus =
         HSTATUS_SPV | HSTATUS_SPVP | MASK_INSR(vsxl, HSTATUS_VSXL);
Quoted 2 lines

Without moving vcpu_create(d, 0) after set_domain_type(), domain_vsxl() will return something wrong.

Question is - do you need to set ->hstatus this early?

Quoted 4 lines

I also thought about updating of VSXL for each vCPU in construct_domain() where d->type is already known and then no changes in common code are needed. But I think it is a little bit better just have a change in common code.

If the maintainers accept that change, it certainly may end up being easier.

Jan

#21 lore raw

Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

Quoted 39 lines · Jan Beulich
Quoted 38 lines · Oleksii Kurochko
Quoted 23 lines · Jan Beulich
Quoted 22 lines · Oleksii Kurochko

It will also affect then common code as vcpu_csr_init() could be then called before domain type is set:

+++ b/xen/common/device-tree/dom0less-build.c

(quoted diff) +1 -3
@@ -812,17 +812,18 @@ static int __init construct_domU(struct
 kernel_info *kinfo,
        else if ( rc == 0 && !strcmp(dom0less_enhanced, "no-xenstore") )
            kinfo->dom0less_feature = DOM0LESS_ENHANCED_NO_XS;
 
-    if ( vcpu_create(d, 0) == NULL )
-        return -ENOMEM;
-
        d->max_pages = ((paddr_t)mem * SZ_1K) >> PAGE_SHIFT;
 
        rc = kernel_probe(kinfo, node);
        if ( rc < 0 )
            return rc;
 
+    /* The domain type needs to be known before the first vCPU is

created. */

        set_domain_type(d, kinfo);
Quoted 5 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+    if ( vcpu_create(d, 0) == NULL )
+        return -ENOMEM;

I don't understand the need for this, likely because I don't see why domain_vsxl() would need calling from underneath vcpu_create().

The call trace will be the following:

    vcpu_create() -> arch_vcpu_create() -> vcpu_csr_init() ->

domain_vsxldomain_vsxl()

      unsigned int vsxl = domain_vsxl(v->domain);

      ...
Quoted 7 lines
Quoted 5 lines
      vcpu_guest_cpu_user_regs(v)->hstatus =
          HSTATUS_SPV | HSTATUS_SPVP | MASK_INSR(vsxl, HSTATUS_VSXL);

Without moving vcpu_create(d, 0) after set_domain_type(), domain_vsxl() will return something wrong.

Question is - do you need to set ->hstatus this early?

Good point. I think that there is no really such need. It could be set (at least, VSXL) just before jumping to new vCPU where we know domain type for sure.

~ Oleksii

#22 lore raw

Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

Quoted 45 lines · Oleksii Kurochko
Quoted 42 lines · Jan Beulich
Quoted 41 lines · Oleksii Kurochko
Quoted 23 lines · Jan Beulich
Quoted 22 lines · Oleksii Kurochko

It will also affect then common code as vcpu_csr_init() could be then called before domain type is set:

+++ b/xen/common/device-tree/dom0less-build.c

(quoted diff) +1 -3
@@ -812,17 +812,18 @@ static int __init construct_domU(struct
 kernel_info *kinfo,
         else if ( rc == 0 && !strcmp(dom0less_enhanced, "no- xenstore") )
             kinfo->dom0less_feature = DOM0LESS_ENHANCED_NO_XS;
 
-    if ( vcpu_create(d, 0) == NULL )
-        return -ENOMEM;
-
         d->max_pages = ((paddr_t)mem * SZ_1K) >> PAGE_SHIFT;
 
         rc = kernel_probe(kinfo, node);
         if ( rc < 0 )
             return rc;
 
+    /* The domain type needs to be known before the first vCPU is

created. */
        set_domain_type(d, kinfo);

Quoted 5 lines
Quoted 2 lines

+    if ( vcpu_create(d, 0) == NULL )
+        return -ENOMEM;

I don't understand the need for this, likely because I don't see why domain_vsxl() would need calling from underneath vcpu_create().

The call trace will be the following:
    vcpu_create() -> arch_vcpu_create() -> vcpu_csr_init() -> domain_vsxldomain_vsxl()

      unsigned int vsxl = domain_vsxl(v->domain);

      ...

      vcpu_guest_cpu_user_regs(v)->hstatus =
          HSTATUS_SPV | HSTATUS_SPVP | MASK_INSR(vsxl, HSTATUS_VSXL);

Quoted 6 lines
Quoted 4 lines
Quoted 2 lines

Without moving vcpu_create(d, 0) after set_domain_type(), domain_vsxl() will return something wrong.

Question is - do you need to set ->hstatus this early?

Good point. I think that there is no really such need. It could be set (at least, VSXL) just before jumping to new vCPU where we know domain type for sure.

I planned to set VSXL bits here: https://lore.kernel.org/xen-devel/[email protected]/T/#m4144ea90815b48f2d281a2267cd28f50bd4cd54c

But it seems that I can't do that there as considering that platform can do VSXLEN == HSXLEN == 64 but someone will try do run vCPU in 32bit mode we can't just crash domain in continue_new_vcpu().

Then still to set it in arch_vcpu_create() will be better (or in the construct_domain() if we want to avoid to change dom0less common code). At this stage it is easier to reject to create such vCPU which violates platform implementation.

~ Oleksii

#23 lore raw

Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL

Quoted 51 lines · Oleksii Kurochko
Quoted 48 lines · Oleksii Kurochko
Quoted 45 lines · Jan Beulich
Quoted 43 lines · Oleksii Kurochko
Quoted 23 lines · Jan Beulich
Quoted 22 lines · Oleksii Kurochko

It will also affect then common code as vcpu_csr_init() could be then called before domain type is set:

+++ b/xen/common/device-tree/dom0less-build.c

(quoted diff) +1 -3
@@ -812,17 +812,18 @@ static int __init construct_domU(struct
 kernel_info *kinfo,
         else if ( rc == 0 && !strcmp(dom0less_enhanced, "no- xenstore") )
             kinfo->dom0less_feature = DOM0LESS_ENHANCED_NO_XS;
 
-    if ( vcpu_create(d, 0) == NULL )
-        return -ENOMEM;
-
         d->max_pages = ((paddr_t)mem * SZ_1K) >> PAGE_SHIFT;
 
         rc = kernel_probe(kinfo, node);
         if ( rc < 0 )
             return rc;
 
+    /* The domain type needs to be known before the first vCPU is

created. */
        set_domain_type(d, kinfo);

Quoted 5 lines
Quoted 2 lines

+    if ( vcpu_create(d, 0) == NULL )
+        return -ENOMEM;

I don't understand the need for this, likely because I don't see why domain_vsxl() would need calling from underneath vcpu_create().

The call trace will be the following:
    vcpu_create() -> arch_vcpu_create() -> vcpu_csr_init() -> domain_vsxldomain_vsxl()

      unsigned int vsxl = domain_vsxl(v->domain);

      ...

      vcpu_guest_cpu_user_regs(v)->hstatus =
          HSTATUS_SPV | HSTATUS_SPVP | MASK_INSR(vsxl, HSTATUS_VSXL);

Without moving vcpu_create(d, 0) after set_domain_type(), domain_vsxl() will return something wrong.

Quoted 8 lines
Quoted 3 lines
Quoted 1 line

Question is - do you need to set ->hstatus this early?

Good point. I think that there is no really such need. It could be set (at least, VSXL) just before jumping to new vCPU where we know domain type for sure.

I planned to set VSXL bits here: https://lore.kernel.org/xen-devel/ [email protected]/T/ #m4144ea90815b48f2d281a2267cd28f50bd4cd54c

But it seems that I can't do that there as considering that platform can do VSXLEN == HSXLEN == 64 but someone will try do run vCPU in 32bit mode we can't just crash domain in continue_new_vcpu().

I think that I can have a check that platform supports VSXLEN guest requested based on d->type in construct_domain() where d->type will be for sure properly set and reject construction of a domain VSXLEN of which isn't supported by a platform. And it looks a proper place for such check in general. Then in continue_new_vcpu() just set hstatus.VSXLEN without any issue as at that moment we will for sure now that requested VSXLEN is correct.

Doing in such way will continue to follow your suggestion (not ->hstatus so early in vcpu_csr_init()) and also ...

Quoted 2 lines

Then still to set it in arch_vcpu_create() will be better (or in the construct_domain() if we want to avoid to change dom0less common code). At this stage it is easier to reject to create such vCPU which violates platform implementation.

... help to void changing of common code.

~ Oleksii

#24 lore raw

PATCH v2 4/39 xen/riscv: introduce csr_read64()

In reply to Oleksii Kurochko

csr_write64() already hides the RV32 split of a 64-bit CSR into a low and a high half; add the read counterpart.

Reading the two halves isn't simply the mirror of writing them. A CSR which hardware increments can carry from the low half into the high one between the two reads, so a plain pair of reads can produce a value the CSR never held. Therefore the high half is re-read and the sequence retried if it changed in the meantime.

Use it for CSR_TIME, which is exactly such a counter, and widen cycles_t to uint64_t. Otherwise get_cycles() would still truncate the time counter to 32 bits on RV32.

Fixes a541ddadec0a ("xen/riscv: introduce time.h")

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

---
 xen/arch/riscv/include/asm/csr.h  | 24 ++++++++++++++++++++++++
 xen/arch/riscv/include/asm/time.h |  4 ++--
 2 files changed, 26 insertions(+), 2 deletions(-)
xen/arch/riscv/include/asm/csr.h +24 -0
index 888d6a2a86d6..a5cdd6f99c8e 100644
@@ -39,12 +39,36 @@
     csr_write(csr, v_);             \
     csr_write(csr ## H, v_ >> 32);  \
 })
+
+/*
+ * The two halves are read by separate instructions, so a CSR which hardware
+ * increments can carry from the low half into the high one in between,
+ * yielding a value the CSR never held. Re-read the high half and retry the
+ * sequence if it changed.
+ */
+#define csr_read64(csr)                         \
+({                                              \
+    uint32_t hi_, lo_;                          \
+                                                \
+    do {                                        \
+        hi_ = csr_read(csr ## H);               \
+        lo_ = csr_read(csr);                    \
+    } while ( hi_ != csr_read(csr ## H) );      \
+                                                \
+    ((uint64_t)hi_ << 32) | lo_;                \
+})
 #else
 #define csr_write64(csr, val)       \
 ({                                  \
     csr_write(csr, val);            \
     (void)csr ## H;                 \
 })
+
+#define csr_read64(csr)             \
+({                                  \
+    (void)csr ## H;                 \
+    csr_read(csr);                  \
+})
 #endif
 
 #define csr_swap(csr, val)                                      \
xen/arch/riscv/include/asm/time.h +2 -2
index 4d68900151a7..ec771c3fe80f 100644
@@ -18,11 +18,11 @@ static inline void force_update_vcpu_system_time(struct vcpu *v)
     BUG_ON("unimplemented");
 }
 
-typedef unsigned long cycles_t;
+typedef uint64_t cycles_t;
 
 static inline cycles_t get_cycles(void)
 {
-    return csr_read(CSR_TIME);
+    return csr_read64(CSR_TIME);
 }
 
 void preinit_xen_time(void);
Signature · 1 line
2.55.0
#25 lore raw

Re: [PATCH v2 04/39] xen/riscv: introduce csr_read64()

Quoted 16 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/csr.h +8 -0
index 888d6a2a86d6..a5cdd6f99c8e 100644
@@ -39,12 +39,36 @@
     csr_write(csr, v_);             \
     csr_write(csr ## H, v_ >> 32);  \
 })
+
+/*
+ * The two halves are read by separate instructions, so a CSR which hardware
+ * increments can carry from the low half into the high one in between,
+ * yielding a value the CSR never held. Re-read the high half and retry the
+ * sequence if it changed.
+ */
+#define csr_read64(csr)                         \

xen/arch/riscv/include/asm/csr.h line 59

Quoted 10 lines
xen/arch/riscv/include/asm/csr.h +10 -0
+({                                              \
+    uint32_t hi_, lo_;                          \
+                                                \
+    do {                                        \
+        hi_ = csr_read(csr ## H);               \
+        lo_ = csr_read(csr);                    \
+    } while ( hi_ != csr_read(csr ## H) );      \
+                                                \
+    ((uint64_t)hi_ << 32) | lo_;                \
+})

This double reads H in the looping case.  You want something more like:

hi = csr_read();
do {
    old = hi;
    lo = csr_read();
} while ( (hi = csr_read()) != old );

Still, this only matters for volatile CSRs, and is unnecessary in the general case.  I'd suggest naming it csr_volatile_read64().  Most CSRs can use a simple split access.

~Andrew

#26 lore raw

Re: [PATCH v2 04/39] xen/riscv: introduce csr_read64()

Quoted 30 lines · Andrew Cooper
Quoted 16 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/csr.h +8 -0
index 888d6a2a86d6..a5cdd6f99c8e 100644
@@ -39,12 +39,36 @@
      csr_write(csr, v_);             \
      csr_write(csr ## H, v_ >> 32);  \
  })
+
+/*
+ * The two halves are read by separate instructions, so a CSR which hardware
+ * increments can carry from the low half into the high one in between,
+ * yielding a value the CSR never held. Re-read the high half and retry the
+ * sequence if it changed.
+ */
+#define csr_read64(csr)                         \

xen/arch/riscv/include/asm/csr.h line 59

Quoted 10 lines
xen/arch/riscv/include/asm/csr.h +10 -0
+({                                              \
+    uint32_t hi_, lo_;                          \
+                                                \
+    do {                                        \
+        hi_ = csr_read(csr ## H);               \
+        lo_ = csr_read(csr);                    \
+    } while ( hi_ != csr_read(csr ## H) );      \
+                                                \
+    ((uint64_t)hi_ << 32) | lo_;                \
+})

This double reads H in the looping case.  You want something more like:

Quoted 5 lines

hi = csr_read();
do {
    old = hi;
    lo = csr_read();
} while ( (hi = csr_read()) != old );

Good point. I'll apply that.

Quoted 4 lines

Still, this only matters for volatile CSRs, and is unnecessary in the general case.  I'd suggest naming it csr_volatile_read64().

Yes, that makes sense. I will rename it to csr_volatile_read64().

Quoted 2 lines

Most CSRs
can use a simple split access.

I may have misunderstood you here, but wouldn't it still make sense to have a macro covering the case where a register is 64-bit on RV32 yet accessed through two CSRs? VSIE and VSIEH, for example.

My plan was to use a single csr_read64() (but while loop then really isn't needed in this case) call to abstract the access to VSIE, so that the code looks the same on RV32 and RV64.

Does that make sense, or would it be better to have separate vsie and vsieh fields instead?

~ Oleksii

#27 lore raw

Re: [PATCH v2 04/39] xen/riscv: introduce csr_read64()

Quoted 55 lines · Oleksii Kurochko
Quoted 30 lines · Andrew Cooper
Quoted 16 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/csr.h +8 -0
index 888d6a2a86d6..a5cdd6f99c8e 100644
@@ -39,12 +39,36 @@
      csr_write(csr, v_);             \
      csr_write(csr ## H, v_ >> 32);  \
  })
+
+/*
+ * The two halves are read by separate instructions, so a CSR which hardware
+ * increments can carry from the low half into the high one in between,
+ * yielding a value the CSR never held. Re-read the high half and retry the
+ * sequence if it changed.
+ */
+#define csr_read64(csr)                         \

xen/arch/riscv/include/asm/csr.h line 59

Quoted 10 lines
xen/arch/riscv/include/asm/csr.h +10 -0
+({                                              \
+    uint32_t hi_, lo_;                          \
+                                                \
+    do {                                        \
+        hi_ = csr_read(csr ## H);               \
+        lo_ = csr_read(csr);                    \
+    } while ( hi_ != csr_read(csr ## H) );      \
+                                                \
+    ((uint64_t)hi_ << 32) | lo_;                \
+})

This double reads H in the looping case.  You want something more like:

Quoted 5 lines

hi = csr_read();
do {
    old = hi;
    lo = csr_read();
} while ( (hi = csr_read()) != old );

Good point. I'll apply that.

Quoted 4 lines

Still, this only matters for volatile CSRs, and is unnecessary in the general case.  I'd suggest naming it csr_volatile_read64().

Yes, that makes sense. I will rename it to csr_volatile_read64().

Quoted 2 lines

Most CSRs
can use a simple split access.

I may have misunderstood you here, but wouldn't it still make sense to have a macro covering the case where a register is 64-bit on RV32 yet accessed through two CSRs? VSIE and VSIEH, for example.

Quoted 6 lines

My plan was to use a single csr_read64() (but while loop then really isn't needed in this case) call to abstract the access to VSIE, so that the code looks the same on RV32 and RV64.

Does that make sense, or would it be better to have separate vsie and vsieh fields instead?

For registers which can't change under your feet (or where both halves are independent of one another) the simpler accessor form may still be useful. And I really mean "change under your feet", i.e. "which hardware increments" (as you have it in the comment) is really only a subset of the cases where csr_volatile_read64() will need using.

Jan

#28 lore raw

PATCH v2 5/39 xen/riscv: request a G-stage flush on vmenter when VMIDs are disabled

In reply to Oleksii Kurochko

vmid_handle_vmenter() reports that no flush is needed when VMIDs are unavailable (vmid=off, or hardware with no more than one VMID bit). Every domain then runs under VMID 0 with nothing flushed in between, so as soon as a hart runs more than one domain, a domain entered there can use the G-stage translations left behind by the domain which ran before it.

Adjust the comment in p2m_handle_vmenter() accordingly: skipping the VS-stage flush no longer relies on an old VMID not being reused, which doesn't hold when there are no VMIDs to begin with.

While at it, spell the other early return as a bool literal.

Fixes bff3b9ea4696 ("xen/riscv: introduce VMID allocation and manegement")

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

---
 xen/arch/riscv/p2m.c  | 4 +++-
 xen/arch/riscv/vmid.c | 4 ++--
 2 files changed, 5 insertions(+), 3 deletions(-)
xen/arch/riscv/p2m.c +3 -1
index 1cea86512c8c..de25607247a6 100644
@@ -1584,7 +1584,9 @@ void p2m_handle_vmenter(void)
     /*
      * There is also no need to flush the VS-stage TLB: even if speculation
      * occurs (VSATP + old HGATP were used), it will use the old VMID, which
-     * won't be reused until need_flush is set to true.
+     * won't be reused until need_flush is set to true. When VMIDs aren't
+     * available there is no old VMID to rely on, but then need_flush is set
+     * on every entry, so the flush above covers that case.
      */
 }
 
xen/arch/riscv/vmid.c +2 -2
index 11c7e9d6d6c8..93714b359534 100644
@@ -141,7 +141,7 @@ bool vmid_handle_vmenter(struct vcpu_vmid *vmid)
 
     /* Test if VCPU has valid VMID. */
     if ( read_atomic(&vmid->generation) == data->generation )
-        return 0;
+        return false;
 
     /* If there are no free VMIDs, need to go to a new generation. */
     if ( unlikely(data->next_vmid > data->max_vmid) )
@@ -164,7 +164,7 @@ bool vmid_handle_vmenter(struct vcpu_vmid *vmid)
 
  disabled:
     vmid->vmid = 0;
-    return 0;
+    return true;
 }
 
 /*
Signature · 1 line
2.55.0
#29 lore raw

Re: [PATCH v2 05/39] xen/riscv: request a G-stage flush on vmenter when VMIDs are disabled

Quoted 6 lines

vmid_handle_vmenter() reports that no flush is needed when VMIDs are unavailable (vmid=off, or hardware with no more than one VMID bit). Every domain then runs under VMID 0 with nothing flushed in between, so as soon as a hart runs more than one domain, a domain entered there can use the G-stage translations left behind by the domain which ran before it.

Quoted 9 lines

Adjust the comment in p2m_handle_vmenter() accordingly: skipping the VS-stage flush no longer relies on an old VMID not being reused, which doesn't hold when there are no VMIDs to begin with.

While at it, spell the other early return as a bool literal.

Fixes bff3b9ea4696 ("xen/riscv: introduce VMID allocation and manegement")

FWIW this comment and p2m_handle_vmenter() itself get dropped a few patches later in "implement vCPU context switching", which folds the VMID claim into p2m_ctxt_switch_to(). The fix survives there via the need_flush check. Is this patch really needed?

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

Re: [PATCH v2 05/39] xen/riscv: request a G-stage flush on vmenter when VMIDs are disabled

Quoted 12 lines · Baptiste Le Duc
Quoted 12 lines

vmid_handle_vmenter() reports that no flush is needed when VMIDs are unavailable (vmid=off, or hardware with no more than one VMID bit). Every domain then runs under VMID 0 with nothing flushed in between, so as soon as a hart runs more than one domain, a domain entered there can use the G-stage translations left behind by the domain which ran before it.

Adjust the comment in p2m_handle_vmenter() accordingly: skipping the VS-stage flush no longer relies on an old VMID not being reused, which doesn't hold when there are no VMIDs to begin with.

While at it, spell the other early return as a bool literal.

Quoted 9 lines
Quoted 3 lines
Fixes bff3b9ea4696 ("xen/riscv: introduce VMID allocation and manegement")

FWIW this comment and p2m_handle_vmenter() itself get dropped a few patches later in "implement vCPU context switching", which folds the VMID claim into p2m_ctxt_switch_to(). The fix survives there via the need_flush check. Is this patch really needed?

I think yes as it is fixing current implementation of what we have in staging.

We could back to this topic after the discussion of "implement vCPU context switching" in the case someone will suggest better way to handle p2m context switch (probably without dropping of p2m_handle_vmenter().

~ Oleksii

#31 lore raw

PATCH v2 6/39 xen/riscv: use UINT64_MAX to disable the VS-timer

In reply to Oleksii Kurochko

vstimecmp is a 64-bit CSR independently of XLEN, which is why it is written with csr_write64(). On RV32 that macro splits the value into the vstimecmp/vstimecmph pair, so passing ULONG_MAX (0xffffffff there) writes all ones to the low half and zero to the high half, leaving the CSR at 0x00000000ffffffff rather than at its maximum. A VS-timer irq would then become pending as soon as (time + htimedelta) reaches 2^32, which is exactly what the code is trying to avoid.

Use UINT64_MAX, which matches the width of the CSR. On RV64 it is equal to ULONG_MAX, so no functional change there.

Fixes 25e032730690 ("xen/riscv: allow Xen to use SSTC while hiding it from guests")

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

---
 xen/arch/riscv/time.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
xen/arch/riscv/time.c +2 -2
index 602c029641b8..8c25198b4063 100644
@@ -101,8 +101,8 @@ void __init preinit_xen_time(void)
          * A VS-timer interrupt becomes pending whenever the value of
          * (time + htimedelta) is greater than or equal to vstimecmp CSR.
          * Thereby to avoid spurious VS-timer irqs set vstimecmp CSR to
-         * ULONG_MAX.
+         * UINT64_MAX.
          */
-        csr_write64(CSR_VSTIMECMP, ULONG_MAX);
+        csr_write64(CSR_VSTIMECMP, UINT64_MAX);
     }
 }
Signature · 1 line
2.55.0
Reviewed-by on v2 6/39
#32 lore raw

Re: [PATCH v2 06/39] xen/riscv: use UINT64_MAX to disable the VS-timer

Quoted 9 lines · Oleksii Kurochko

vstimecmp is a 64-bit CSR independently of XLEN, which is why it is written with csr_write64(). On RV32 that macro splits the value into the vstimecmp/vstimecmph pair, so passing ULONG_MAX (0xffffffff there) writes all ones to the low half and zero to the high half, leaving the CSR at 0x00000000ffffffff rather than at its maximum. A VS-timer irq would then become pending as soon as (time + htimedelta) reaches 2^32, which is exactly what the code is trying to avoid.

[...]

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

Re: [PATCH v2 06/39] xen/riscv: use UINT64_MAX to disable the VS-timer

In reply to Oleksii Kurochko
Quoted 10 lines · Oleksii Kurochko

vstimecmp is a 64-bit CSR independently of XLEN, which is why it is written with csr_write64(). On RV32 that macro splits the value into the vstimecmp/vstimecmph pair, so passing ULONG_MAX (0xffffffff there) writes all ones to the low half and zero to the high half, leaving the CSR at 0x00000000ffffffff rather than at its maximum. A VS-timer irq would then become pending as soon as (time + htimedelta) reaches 2^32, which is exactly what the code is trying to avoid.

Use UINT64_MAX, which matches the width of the CSR. On RV64 it is equal to ULONG_MAX, so no functional change there.

Hmm. This again is an example where code (likely) will be silently wrong for RV128. Presumably the CSR would be XLEN bits wide there as well, and hence you'd need to write it with 128 bits of ones. Imo ~0 is what wants using here.

Jan

#34 lore raw

Re: [PATCH v2 06/39] xen/riscv: use UINT64_MAX to disable the VS-timer

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

vstimecmp is a 64-bit CSR independently of XLEN, which is why it is written with csr_write64(). On RV32 that macro splits the value into the vstimecmp/vstimecmph pair, so passing ULONG_MAX (0xffffffff there) writes all ones to the low half and zero to the high half, leaving the CSR at 0x00000000ffffffff rather than at its maximum. A VS-timer irq would then become pending as soon as (time + htimedelta) reaches 2^32, which is exactly what the code is trying to avoid.

Quoted 8 lines
Quoted 2 lines

Use UINT64_MAX, which matches the width of the CSR. On RV64 it is equal to ULONG_MAX, so no functional change there.

Hmm. This again is an example where code (likely) will be silently wrong for RV128. Presumably the CSR would be XLEN bits wide there as well, and hence you'd need to write it with 128 bits of ones. Imo ~0 is what wants using here.

Agree, it makes would be better to have ~0 here. I will apply that.

Thanks.

~ Oleksii

#35 lore raw

PATCH v2 7/39 xen/riscv: add missing APLIC register offsets, masks to asm/aplic.h

In reply to Oleksii Kurochko

These definitions are required for correct decoding of APLIC MMIO accesses and target configuration, and will be used by both the physical and virtual APLIC implementations.

While adding them, rearrange the header in the style of x86's asm/msr-index.h: a register's offset is immediately followed by the definitions of that register's fields, with the blocks sorted by offset. This makes the relation between a register and its fields obvious from the layout alone, so no comment is needed to express it.

No functional change is intended by this patch; it only centralises hardware definitions that were previously missing.

---
Changes in v2:
- Rearrange the whole header the way x86's asm/msr-index.h is laid out:
put each register offset first and the definitions of its fields immediately after it (indented by an extra space), sorted by offset.
- Describe the convention in a comment at the top of the definitions, mirroring the one in asm/msr-index.h.
- Reflow APLIC_SIZE() to fit the new alignment column.
- Fix the comment for declaration of member target in aplic_regs[]. It should be 0x3004.
- s/APLIC_REG_OFFSET_MASK/APLIC_CTRL_REGION_OFFSET_MASK
---

---
 xen/arch/riscv/include/asm/aplic.h | 90 ++++++++++++++++++++++++------
 1 file changed, 73 insertions(+), 17 deletions(-)
xen/arch/riscv/include/asm/aplic.h +73 -17
index 07318aaac25d..a2af55d54fc0 100644
@@ -15,32 +15,88 @@
 
 #include <asm/imsic.h>
 
+/*
+ * APLIC register offsets and, immediately following each of them, the
+ * definitions of the fields of the respective register:
+ *
+ * #define APLIC_$NAME                      0x$OFFSET
+ * #define  APLIC_$NAME_$FIELD1             ...
+ * #define   APLIC_$NAME_$FIELD1_$VAL       ...
+ * #define  APLIC_$NAME_$FIELD2             ...
+ *
+ * Blocks of related constants are sorted by register offset.
+ */
+
+#define APLIC_CTRL_REGION_OFFSET_MASK       0x3fff
+
+#define APLIC_DOMAINCFG                     0x0000
 /*
  * domaincfg read-only fields (AIA spec):
  *  - bits [31:24] -> read-only 0x80
  *  - bit 7        -> read-only 0
  */
-#define APLIC_DOMAINCFG_RO      (0x80U << 24)
-#define APLIC_DOMAINCFG_IE      BIT(8, U)
-#define APLIC_DOMAINCFG_DM      BIT(2, U)
-#define APLIC_DOMAINCFG_BE      BIT(0, U)
+#define  APLIC_DOMAINCFG_RO             (0x80U << 24)
+#define  APLIC_DOMAINCFG_IE             BIT(8, U)
+#define  APLIC_DOMAINCFG_DM             BIT(2, U)
+#define  APLIC_DOMAINCFG_BE             BIT(0, U)
+
+#define APLIC_SOURCECFG_BASE            0x0004
+#define APLIC_SOURCECFG_LAST            0x0ffc
+/*
+ * sourcecfg[] register fields:
+ *  - bit 10 (D) selects the layout of the remaining bits;
+ *  - D = 1: bits [9:0] hold the Child Index, i.e. the source is delegated
+ *           to a child domain (unsupported by Xen);
+ *  - D = 0: bits [2:0] hold the source mode SM (WARL).
+ */
+#define  APLIC_SOURCECFG_D              BIT(10, U)
+#define  APLIC_SOURCECFG_SM             GENMASK(2, 0)
+#define   APLIC_SOURCECFG_SM_INACTIVE   0x0
+#define   APLIC_SOURCECFG_SM_DETACH     0x1
+/* Bits 0x2 and 0x3 are reserved */
+#define   APLIC_SOURCECFG_SM_EDGE_RISE  0x4
+#define   APLIC_SOURCECFG_SM_EDGE_FALL  0x5
+#define   APLIC_SOURCECFG_SM_LEVEL_HIGH 0x6
+#define   APLIC_SOURCECFG_SM_LEVEL_LOW  0x7
+
+#define APLIC_SMSICFGADDR               0x1bc8
+#define APLIC_SMSICFGADDRH              0x1bcc
+
+#define APLIC_SETIP_BASE                0x1c00
+#define APLIC_SETIP_LAST                0x1c7c
+#define APLIC_SETIPNUM                  0x1cdc
+
+#define APLIC_CLRIP_BASE                0x1d00
+#define APLIC_CLRIP_LAST                0x1d7c
+#define APLIC_CLRIPNUM                  0x1ddc
+
+#define APLIC_SETIE_BASE                0x1e00
+#define APLIC_SETIE_LAST                0x1e7c
+#define APLIC_SETIENUM                  0x1edc
+
+#define APLIC_CLRIE_BASE                0x1f00
+#define APLIC_CLRIE_LAST                0x1f7c
+#define APLIC_CLRIENUM                  0x1fdc
+
+#define APLIC_SETIPNUM_LE               0x2000
 
-#define APLIC_SOURCECFG_SM_INACTIVE     0x0
-#define APLIC_SOURCECFG_SM_DETACH       0x1
-#define APLIC_SOURCECFG_SM_EDGE_RISE    0x4
-#define APLIC_SOURCECFG_SM_EDGE_FALL    0x5
-#define APLIC_SOURCECFG_SM_LEVEL_HIGH   0x6
-#define APLIC_SOURCECFG_SM_LEVEL_LOW    0x7
+#define APLIC_GENMSI                    0x3000
 
-#define APLIC_TARGET_HART_IDX_SHIFT 18
+#define APLIC_TARGET_BASE               0x3004
+#define APLIC_TARGET_LAST               0x3ffc
+#define  APLIC_TARGET_HART_IDX          GENMASK(31, 18)
+#define  APLIC_TARGET_HART_IDX_SHIFT    18
+#define  APLIC_TARGET_GUEST_IDX         GENMASK(17, 12)
+/* Bit 11 is reserved and reads as zero */
+#define  APLIC_TARGET_EIID              GENMASK(10, 0)
 
-#define APLIC_IDC_SIZE          32
+#define APLIC_IDC_SIZE                  32
 
-#define APLIC_MIN_SIZE          0x4000
-#define APLIC_SIZE_ALIGN(x)     ROUNDUP(x, APLIC_MIN_SIZE)
+#define APLIC_MIN_SIZE                  0x4000
+#define APLIC_SIZE_ALIGN(x)             ROUNDUP(x, APLIC_MIN_SIZE)
 
-#define APLIC_SIZE(nr_cpus)     (APLIC_MIN_SIZE + \
-                                 APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_cpus)))
+#define APLIC_SIZE(nr_cpus) \
+    (APLIC_MIN_SIZE + APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_cpus)))
 
 struct aplic_regs {
     uint32_t domaincfg;         /* 0x0000 */
@@ -82,7 +138,7 @@ struct aplic_regs {
     uint8_t _reserved11[4088];  /* 0x2008 */
 
     uint32_t genmsi;            /* 0x3000 */
-    uint32_t target[1023];      /* 0x3008 */
+    uint32_t target[1023];      /* 0x3004 */
 };
 
 #endif /* ASM_RISCV_APLIC_H */
Signature · 1 line
2.55.0
Reviewed-by on v2 7/39
#36 lore raw

Re: [PATCH v2 07/39] xen/riscv: add missing APLIC register offsets, masks to asm/aplic.h

Quoted 11 lines · Oleksii Kurochko

These definitions are required for correct decoding of APLIC MMIO accesses and target configuration, and will be used by both the physical and virtual APLIC implementations.

While adding them, rearrange the header in the style of x86's asm/msr-index.h: a register's offset is immediately followed by the definitions of that register's fields, with the blocks sorted by offset. This makes the relation between a register and its fields obvious from the layout alone, so no comment is needed to express it.

[...]

Signature · 1 line
Baptiste Le Duc <[email protected]>
Acked-by
#37 lore raw

Re: [PATCH v2 07/39] xen/riscv: add missing APLIC register offsets, masks to asm/aplic.h

Quoted 11 lines · Baptiste Le Duc
Quoted 10 lines · Oleksii Kurochko

These definitions are required for correct decoding of APLIC MMIO accesses and target configuration, and will be used by both the physical and virtual APLIC implementations.

While adding them, rearrange the header in the style of x86's asm/msr-index.h: a register's offset is immediately followed by the definitions of that register's fields, with the blocks sorted by offset. This makes the relation between a register and its fields obvious from the layout alone, so no comment is needed to express it.

Quoted 3 lines
Quoted 1 line

[...]

If there's no dependency on earlier patches (nor the prereq series), this could go in right away. Yet nothing is being said anywhere, unless I overlooked anything.

Jan

#38 lore raw

Re: [PATCH v2 07/39] xen/riscv: add missing APLIC register offsets, masks to asm/aplic.h

Quoted 14 lines · Jan Beulich
Quoted 13 lines · Baptiste Le Duc
Quoted 11 lines · Oleksii Kurochko

These definitions are required for correct decoding of APLIC MMIO accesses and target configuration, and will be used by both the physical and virtual APLIC implementations.

While adding them, rearrange the header in the style of x86's asm/msr-index.h: a register's offset is immediately followed by the definitions of that register's fields, with the blocks sorted by offset. This makes the relation between a register and its fields obvious from the layout alone, so no comment is needed to express it.

[...]

Quoted 7 lines
Quoted 1 line

If there's no dependency on earlier patches (nor the prereq series), this could go in right away. Yet nothing is being said anywhere, unless I overlooked anything.

Doesn't apply cleanly to current staging, so left out for the time being.

Jan

#39 lore raw

Re: [PATCH v2 07/39] xen/riscv: add missing APLIC register offsets, masks to asm/aplic.h

Quoted 13 lines · Jan Beulich
Quoted 12 lines · Jan Beulich
Quoted 11 lines · Baptiste Le Duc
Quoted 10 lines · Oleksii Kurochko

These definitions are required for correct decoding of APLIC MMIO accesses and target configuration, and will be used by both the physical and virtual APLIC implementations.

While adding them, rearrange the header in the style of x86's asm/msr-index.h: a register's offset is immediately followed by the definitions of that register's fields, with the blocks sorted by offset. This makes the relation between a register and its fields obvious from the layout alone, so no comment is needed to express it.

Quoted 5 lines
Quoted 5 lines
Quoted 3 lines
Quoted 1 line

[...]

Thanks.

Quoted 6 lines
Quoted 4 lines

If there's no dependency on earlier patches (nor the prereq series), this could go in right away. Yet nothing is being said anywhere, unless I overlooked anything.

Doesn't apply cleanly to current staging, so left out for the time being.

Yes, it isn't applied because of:

[PATCH v8 12/20] xen/riscv: introduce minimal virtual APLIC (vAPLIC) infrastructure

~ Oleksii

#40 lore raw

PATCH v2 8/39 xen/riscv: introduce device-agnostic MMIO emulation dispatch

In reply to Oleksii Kurochko

RISC-V guests can expose several virtual interrupt controllers at distinct GPA ranges: vPLIC (hasn't been introduced yet) for legacy machines, vAPLIC and vIMSIC for AIA-compliant ones (are being introduced in the follow up patches). Routing MMIO faults via a per-device is_access() check in the trap handler would couple it to every device it must serve, requiring a new conditional branch in the fault path each time a new emulated device is added.

Introduce a per-domain MMIO handler registration table, modeled after the equivalent ARM framework, so that virtual devices self-register their GPA ranges and read/write callbacks at domain creation time. The MMIO fault path delegates to a single try_handle_mmio() entry point and remains agnostic of which device owns a particular address.

A subsequent patch wires this into the MMIO fault path in traps.c.

---
Changes in v2:
- Drop copyright from mmio.c as it will go stale anyway as code moves around.
- Drop the max_count parameter of domain_io_init() (MAX_IO_HANDLER is a global boundary) and embed the handler array directly in struct vmmio as struct mmio_handler handlers[MAX_IO_HANDLER]. This removes the xvzalloc_array() allocation, the max_num_entries field and domain_io_free() altogether; domain_io_init() consequently cannot fail any longer and now returns void. Note this goes slightly beyond the suggested variant in that max_num_entries is dropped as well, since ARRAY_SIZE(vmmio->handlers) serves the same purpose.
- Drop the separate register_t argument of mmio_read_t/mmio_write_t; handlers now produce and consume the value through info->data. handle_read()/handle_write() are gone as a result, with try_handle_mmio() invoking ops->read()/ops->write() directly.
- Turn mmio_read_t/mmio_write_t into function types rather than pointer-to-function types, so that pointer-ness is visible at the use sites in struct mmio_handler_ops. Constify the mmio_info_t * of the write callback, which has no reason to modify it any more.
- register_mmio_handler() returns int instead of BUG_ON()ing on a full
table: -ENOSPC now lets the caller fail domain creation. It also validates its inputs, rejecting a NULL ops (or one with a missing read/write callback) as well as zero-sized and address-wrapping regions with -EINVAL.
- Guarantee the non-overlap property that cmp_mmio_handler() relies on:
register_mmio_handler() checks the new region against both neighbours of its insertion slot and returns -EEXIST on overlap.
- Replace the sort() call per registration with an insertion into the already sorted array: locate the slot and memmove() the tail up by one. sort(), swap_mmio_handler() and <xen/sort.h> are gone.
- Extend cmp_mmio_handler()'s comment to state that it is a bsearch() comparator and to explain the key/elem asymmetry; document why the neighbours' addr + size cannot overflow.
- Fix over-long lines and a mis-indented label.
---

---
 xen/arch/riscv/Makefile             |   1 +
 xen/arch/riscv/domain.c             |   3 +
 xen/arch/riscv/include/asm/domain.h |   3 +
 xen/arch/riscv/include/asm/mmio.h   |  63 ++++++++++
 xen/arch/riscv/mmio.c               | 176 ++++++++++++++++++++++++++++
 5 files changed, 246 insertions(+)
 create mode 100644 xen/arch/riscv/include/asm/mmio.h
 create mode 100644 xen/arch/riscv/mmio.c
xen/arch/riscv/Makefile +1 -0
index 3b948c11dd61..ce6410a299a4 100644
@@ -14,6 +14,7 @@ obj-y += intc.o
 obj-y += irq.o
 obj-y += kernel.init.o
 obj-y += mm.o
+obj-y += mmio.o
 obj-y += p2m.o
 obj-y += paging.o
 obj-y += pt.o
xen/arch/riscv/domain.c +3 -0
index 57c37cb2dfc2..ec327a5e8a23 100644
@@ -12,6 +12,7 @@
 #include <asm/cpufeature.h>
 #include <asm/csr.h>
 #include <asm/intc.h>
+#include <asm/mmio.h>
 #include <asm/riscv_encoding.h>
 #include <asm/vtimer.h>
 
@@ -316,6 +317,8 @@ int arch_domain_create(struct domain *d,
     if ( (rc = p2m_init(d, config)) != 0)
         goto fail;
 
+    domain_io_init(d);
+
     if ( (rc = domain_vintc_init(d)) )
         goto fail;
 
xen/arch/riscv/include/asm/domain.h +3 -0
index e035b33ddfdc..15e8fa19685e 100644
@@ -9,6 +9,7 @@
 
 #include <asm/cpufeature.h>
 #include <asm/guest-layout.h>
+#include <asm/mmio.h>
 #include <asm/p2m.h>
 #include <asm/vtimer.h>
 
@@ -101,6 +102,8 @@ struct arch_domain {
     const unsigned long *isa;
 
     struct vintc *vintc;
+
+    struct vmmio vmmio;
 };
 
 #include <xen/sched.h>
xen/arch/riscv/include/asm/mmio.h new file +63 -0

63 lines not on this page · raw message

xen/arch/riscv/mmio.c new file +176 -0

176 lines not on this page · raw message

Signature · 1 line
2.55.0
#41 lore raw

Re: [PATCH v2 08/39] xen/riscv: introduce device-agnostic MMIO emulation dispatch

Quoted 4 lines

RISC-V guests can expose several virtual interrupt controllers at distinct GPA ranges: vPLIC (hasn't been introduced yet) for legacy machines, vAPLIC and vIMSIC for AIA-compliant ones (are being introduced in the follow up patches).

As Jan said here [1], we shouldn't use "as later in this series" in commit message...

[1]: https://lore.kernel.org/xen-devel/[email protected]/T/#m56fbac1ceb0642d5d868e9dcb2b5ed93ecbe5058

Quoted 5 lines

Routing MMIO faults via a per-device is_access() check in the trap handler would couple it to every device it must serve, requiring a new conditional branch in the fault path each time a new emulated device is added.

Quoted 8 lines

Introduce a per-domain MMIO handler registration table, modeled after the equivalent ARM framework, so that virtual devices self-register their GPA ranges and read/write callbacks at domain creation time. The MMIO fault path delegates to a single try_handle_mmio() entry point and remains agnostic of which device owns a particular address.

A subsequent patch wires this into the MMIO fault path in traps.c.

...same here

Quoted 234 lines
xen/arch/riscv/Makefile +1 -0
index 3b948c11dd..ce6410a299 100644
@@ -14,6 +14,7 @@ obj-y += intc.o
 obj-y += irq.o
 obj-y += kernel.init.o
 obj-y += mm.o
+obj-y += mmio.o
 obj-y += p2m.o
 obj-y += paging.o
 obj-y += pt.o
xen/arch/riscv/domain.c +3 -0
index 57c37cb2df..ec327a5e8a 100644
@@ -12,6 +12,7 @@
 #include <asm/cpufeature.h>
 #include <asm/csr.h>
 #include <asm/intc.h>
+#include <asm/mmio.h>
 #include <asm/riscv_encoding.h>
 #include <asm/vtimer.h>
 
@@ -316,6 +317,8 @@ int arch_domain_create(struct domain *d,
     if ( (rc = p2m_init(d, config)) != 0)
         goto fail;
 
+    domain_io_init(d);
+
     if ( (rc = domain_vintc_init(d)) )
         goto fail;
 
xen/arch/riscv/include/asm/domain.h +3 -0
index e035b33ddf..15e8fa1968 100644
@@ -9,6 +9,7 @@
 
 #include <asm/cpufeature.h>
 #include <asm/guest-layout.h>
+#include <asm/mmio.h>
 #include <asm/p2m.h>
 #include <asm/vtimer.h>
 
@@ -101,6 +102,8 @@ struct arch_domain {
     const unsigned long *isa;
 
     struct vintc *vintc;
+
+    struct vmmio vmmio;
 };
 
 #include <xen/sched.h>
xen/arch/riscv/include/asm/mmio.h new file +63 -0
new file mode 100644
index 0000000000..582969e535
@@ -0,0 +1,63 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+#ifndef RISCV_MMIO_H
+#define RISCV_MMIO_H
+
+#include <xen/lib.h>
+#include <xen/rwlock.h>
+
+struct domain;
+struct vcpu;
+
+#define MAX_IO_HANDLER  16
+
+typedef struct {
+    paddr_t gpa;
+    unsigned int len;  /* access width in bytes (1, 2, 4, 8) */
+    bool is_write;
+    /* store: value to write; load: value read (set by handler) */
+    register_t data;
+} mmio_info_t;
+
+enum io_state
+{
+    IO_ABORT,       /* The IO was handled and led to an abort. */
+    IO_HANDLED,     /* The IO was successfully handled. */
+    IO_UNHANDLED,   /* No handler found for the IO. */
+};
+
+typedef enum io_state (mmio_read_t)(struct vcpu *v, mmio_info_t *info);
+typedef enum io_state (mmio_write_t)(struct vcpu *v, const mmio_info_t *info);
+
+struct mmio_handler_ops {
+    mmio_read_t *read;
+    mmio_write_t *write;
+};
+
+struct mmio_handler {
+    paddr_t addr;
+    paddr_t size;
+    const struct mmio_handler_ops *ops;
+};
+
+struct vmmio {
+    unsigned int num_entries;
+    rwlock_t lock;
+    struct mmio_handler handlers[MAX_IO_HANDLER];
+};
+
+int do_mmio(mmio_info_t *info, paddr_t fault_addr, unsigned int len);
+int register_mmio_handler(struct domain *d,
+                          const struct mmio_handler_ops *ops,
+                          paddr_t addr, paddr_t size);
+void domain_io_init(struct domain *d);
+
+#endif /* RISCV_MMIO_H */
+
+/*
+ * Local variables:
+ * mode: C
+ * c-file-style: "BSD"
+ * c-basic-offset: 4
+ * indent-tabs-mode: nil
+ * End:
+ */
xen/arch/riscv/mmio.c new file +102 -0
new file mode 100644
index 0000000000..d241ab5ea1
@@ -0,0 +1,176 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+#include <xen/bsearch.h>
+#include <xen/lib.h>
+#include <xen/rwlock.h>
+#include <xen/sched.h>
+#include <xen/string.h>
+
+#include <asm/current.h>
+#include <asm/mmio.h>
+
+/*
+ * bsearch() comparator: @key holds the address to look up in its addr field,
+ * @elem is an entry of vmmio->handlers. Relies on the regions not
+ * overlapping, which register_mmio_handler() enforces.
+ */
+static int cmp_mmio_handler(const void *key, const void *elem)
+{
+    const struct mmio_handler *handler0 = key;
+    const struct mmio_handler *handler1 = elem;
+
+    if ( handler0->addr < handler1->addr )
+        return -1;
+
+    if ( handler0->addr >= (handler1->addr + handler1->size) )
+        return 1;
+
+    return 0;
+}
+
+/*
+ * Return a copy of the matching handler rather than a pointer into
+ * vmmio->handlers: a concurrent register_mmio_handler() shifts entries
+ * up to keep the array sorted, so an escaped pointer could refer to a
+ * different (or torn) entry once the lock is dropped. The copy stays
+ * valid as the ops structures are never freed.
+ */
+static bool find_mmio_handler(struct domain *d, paddr_t gpa,
+                              struct mmio_handler *out)
+{
+    struct vmmio *vmmio = &d->arch.vmmio;
+    struct mmio_handler key = { .addr = gpa };
+    const struct mmio_handler *handler;
+
+    read_lock(&vmmio->lock);
+    handler = bsearch(&key, vmmio->handlers, vmmio->num_entries,
+                      sizeof(*handler), cmp_mmio_handler);
+    if ( handler )
+        *out = *handler;
+    read_unlock(&vmmio->lock);
+
+    return handler != NULL;
+}
+
+static enum io_state try_handle_mmio(mmio_info_t *info)
+{
+    struct vcpu *v = current;
+    struct mmio_handler handler = {};
+
+    if ( !find_mmio_handler(v->domain, info->gpa, &handler) )
+        return IO_UNHANDLED;
+
+    if ( info->is_write )
+        return handler.ops->write(v, info);
+    else
+        return handler.ops->read(v, info);
+}
+
+/*
+ * Check alignment and dispatch a decoded MMIO access to a registered
+ * handler. On success (0), info->data holds the read value for loads.
+ *
+ * There is no "retry" outcome to handle: find_mmio_handler() returns a
+ * copy of the matching handler taken under vmmio->lock and the ops
+ * structures are never freed, so the lookup result cannot go stale
+ * between finding the handler and invoking it.
+ */
+int do_mmio(mmio_info_t *info, paddr_t fault_addr, unsigned int len)
+{
+    /* Fault address should be aligned to length of MMIO */
+    if ( fault_addr & (len - 1) )
+        return -EIO;
+
+    info->gpa = fault_addr;
+    info->len = len;
+
+    switch ( try_handle_mmio(info) )
+    {
+    case IO_HANDLED:
+        return 0;
+
+    case IO_ABORT:
+        return -EIO;
+
+    default:
+        return -EOPNOTSUPP;
+    }
+}
+
+int register_mmio_handler(struct domain *d,
+                          const struct mmio_handler_ops *ops,
+                          paddr_t addr, paddr_t size)

xen/arch/riscv/mmio.c line 112

Quoted 10 lines
xen/arch/riscv/mmio.c new file +10 -0
+{
+    struct vmmio *vmmio = &d->arch.vmmio;
+    struct mmio_handler *handlers = vmmio->handlers;
+    paddr_t end = addr + size;
+    unsigned int i;
+    int rc = 0;
+    bool overlap;
+
+    if ( !ops || !ops->read || !ops->write || !size || end < addr )
+        return -EINVAL;

Just a question: is the aim of end < addr check to handle possible overflow of end?

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

Re: [PATCH v2 08/39] xen/riscv: introduce device-agnostic MMIO emulation dispatch

Quoted 6 lines · Baptiste Le Duc
Quoted 4 lines

RISC-V guests can expose several virtual interrupt controllers at distinct GPA ranges: vPLIC (hasn't been introduced yet) for legacy machines, vAPLIC and vIMSIC for AIA-compliant ones (are being introduced in the follow up patches).

As Jan said here [1], we shouldn't use "as later in this series" in commit message...

I will reword this paragraph to:

```
A RISC-V guest can be given several emulated devices at distinct GPA
ranges; the virtual interrupt controllers alone account for vPLIC on
legacy machines and vAPLIC together with vIMSIC on AIA-compliant ones.
Routing MMIO faults via a per-device is_access() check in the trap
handler would couple that handler to every device it must serve,
requiring a new conditional branch in the fault path for each emulated
device added.
```
Quoted 14 lines

[1]: https://lore.kernel.org/xen-devel/[email protected]/T/#m56fbac1ceb0642d5d868e9dcb2b5ed93ecbe5058

Quoted 12 lines

Routing MMIO faults via a per-device is_access() check in the trap handler would couple it to every device it must serve, requiring a new conditional branch in the fault path each time a new emulated device is added.

Introduce a per-domain MMIO handler registration table, modeled after the equivalent ARM framework, so that virtual devices self-register their GPA ranges and read/write callbacks at domain creation time. The MMIO fault path delegates to a single try_handle_mmio() entry point and remains agnostic of which device owns a particular address.

Quoted 2 lines
Quoted 1 line

A subsequent patch wires this into the MMIO fault path in traps.c.

...same here

I'll reword this to:

```
Nothing registers a handler and try_handle_mmio() has no callers yet,
so this patch is a no-op; the trap handler is left untouched.
```

+

I will add after Signed-off-by:

```
---
Wiring this into the MMIO fault path in traps.c is done in this patch
series later.
```

[...]

Quoted 7 lines
Quoted 7 lines
xen/arch/riscv/mmio.c new file +7 -0
+
+int register_mmio_handler(struct domain *d,
+                          const struct mmio_handler_ops *ops,
+                          paddr_t addr, paddr_t size)
+{
+    struct vmmio *vmmio = &d->arch.vmmio;
+    struct mmio_handler *handlers = vmmio->handlers;
Quoted 9 lines

xen/arch/riscv/mmio.c line 112

Quoted 7 lines
xen/arch/riscv/mmio.c new file +7 -0
+    paddr_t end = addr + size;
+    unsigned int i;
+    int rc = 0;
+    bool overlap;
+
+    if ( !ops || !ops->read || !ops->write || !size || end < addr )
+        return -EINVAL;

Just a question: is the aim of end < addr check to handle possible overflow of end?

Yes, your understanding is correct.

Thanks.

~ Oleksii

#43 lore raw

Re: [PATCH v2 08/39] xen/riscv: introduce device-agnostic MMIO emulation dispatch

In reply to Oleksii Kurochko
Quoted 10 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/mmio.h new file +7 -0
@@ -0,0 +1,63 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+#ifndef RISCV_MMIO_H
+#define RISCV_MMIO_H
+
+#include <xen/lib.h>
+#include <xen/rwlock.h>
+

xen/arch/riscv/include/asm/mmio.h line 17

Quoted 10 lines
xen/arch/riscv/include/asm/mmio.h new file +10 -0
+struct domain;
+struct vcpu;
+
+#define MAX_IO_HANDLER  16
+
+typedef struct {
+    paddr_t gpa;
+    unsigned int len;  /* access width in bytes (1, 2, 4, 8) */
+    bool is_write;
+    /* store: value to write; load: value read (set by handler) */

Nit: Comment style (twice). I'd also like to mention that enumerating access widths is prone to go stale once the V or Q extensions are supported.

xen/arch/riscv/include/asm/mmio.h line 29

Quoted 12 lines
xen/arch/riscv/include/asm/mmio.h new file +12 -0
+    register_t data;
+} mmio_info_t;
+
+enum io_state
+{
+    IO_ABORT,       /* The IO was handled and led to an abort. */
+    IO_HANDLED,     /* The IO was successfully handled. */
+    IO_UNHANDLED,   /* No handler found for the IO. */
+};
+
+typedef enum io_state (mmio_read_t)(struct vcpu *v, mmio_info_t *info);
+typedef enum io_state (mmio_write_t)(struct vcpu *v, const mmio_info_t *info);

I don't quite understand the (need for) parentheses around the typedef names.

Quoted 4 lines
xen/arch/riscv/include/asm/mmio.h new file +4 -0
+/*
+ * Check alignment and dispatch a decoded MMIO access to a registered
+ * handler. On success (0), info->data holds the read value for loads.
+ *

xen/arch/riscv/include/asm/mmio.h line 43

Quoted 10 lines
xen/arch/riscv/include/asm/mmio.h new file +10 -0
+ * There is no "retry" outcome to handle: find_mmio_handler() returns a
+ * copy of the matching handler taken under vmmio->lock and the ops
+ * structures are never freed, so the lookup result cannot go stale
+ * between finding the handler and invoking it.
+ */
+int do_mmio(mmio_info_t *info, paddr_t fault_addr, unsigned int len)
+{
+    /* Fault address should be aligned to length of MMIO */
+    if ( fault_addr & (len - 1) )
+        return -EIO;

Better first check (or at least assert) that len is a power of 2?

xen/arch/riscv/include/asm/mmio.h line 56

Quoted 13 lines
xen/arch/riscv/include/asm/mmio.h new file +13 -0
+int register_mmio_handler(struct domain *d,
+                          const struct mmio_handler_ops *ops,
+                          paddr_t addr, paddr_t size)
+{
+    struct vmmio *vmmio = &d->arch.vmmio;
+    struct mmio_handler *handlers = vmmio->handlers;
+    paddr_t end = addr + size;
+    unsigned int i;
+    int rc = 0;
+    bool overlap;
+
+    if ( !ops || !ops->read || !ops->write || !size || end < addr )
+        return -EINVAL;

"!size || end < addr" can be had shorter as "end <= addr".

Whether it's worth checking ops to be non-NULL I question, bit I wouldn't insist on dropping the check.

Quoted 7 lines
xen/arch/riscv/include/asm/mmio.h new file +7 -0
+    write_lock(&vmmio->lock);
+
+    if ( vmmio->num_entries >= ARRAY_SIZE(vmmio->handlers) )
+    {
+        rc = -ENOSPC;
+        goto out;
+    }

xen/arch/riscv/include/asm/mmio.h

Quoted 10 lines
xen/arch/riscv/include/asm/mmio.h new file +10 -0
+
+    /*
+     * The array is kept sorted by base address, so rather than appending and
+     * re-sorting, find the slot the new region belongs to and shift the tail
+     * up by one.
+     */
+    for ( i = vmmio->num_entries;
+          i > 0 && handlers[i - 1].addr > addr;
+          i-- )
+        /* Nothing */;
    for ( i = vmmio->num_entries; i-- > 0 && handlers[i].addr > addr; )
        /* Nothing */;

?

xen/arch/riscv/include/asm/mmio.h

Quoted 11 lines
xen/arch/riscv/include/asm/mmio.h new file +11 -0
+    /*
+     * Regions are required not to overlap; check both neighbours. Their
+     * addr + size cannot overflow, as such regions are rejected above when
+     * they get registered.
+     */
+    overlap = (i > 0 && handlers[i - 1].addr + handlers[i - 1].size > addr) ||
+              (i < vmmio->num_entries && end > handlers[i].addr);
+
+    if ( overlap )
+    {
+        rc = -EEXIST;

I fear -EEXIST can be misleading; it generally means _this_ range is already covered, not some sub-range thereof.

xen/arch/riscv/include/asm/mmio.h

Quoted 4 lines
xen/arch/riscv/include/asm/mmio.h new file +4 -0
+void domain_io_init(struct domain *d)
+{
+    rwlock_init(&d->arch.vmmio.lock);
+    d->arch.vmmio.num_entries = 0;

The latter shouldn't be necessary, as struct domain-s start out zero filled.

Jan

#44 lore raw

Re: [PATCH v2 08/39] xen/riscv: introduce device-agnostic MMIO emulation dispatch

Quoted 19 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/mmio.c new file +4 -0
+/*
+ * Check alignment and dispatch a decoded MMIO access to a registered
+ * handler. On success (0), info->data holds the read value for loads.
+ *

xen/arch/riscv/mmio.c line 82

Quoted 10 lines
xen/arch/riscv/mmio.c new file +10 -0
+ * There is no "retry" outcome to handle: find_mmio_handler() returns a
+ * copy of the matching handler taken under vmmio->lock and the ops
+ * structures are never freed, so the lookup result cannot go stale
+ * between finding the handler and invoking it.
+ */
+int do_mmio(mmio_info_t *info, paddr_t fault_addr, unsigned int len)
+{
+    /* Fault address should be aligned to length of MMIO */
+    if ( fault_addr & (len - 1) )
+        return -EIO;

Better first check (or at least assert) that len is a power of 2?

It make sense. I will do then:

    if ( len & (len - 1) || fault_addr & (len - 1) )
Quoted 16 lines
Quoted 4 lines
xen/arch/riscv/mmio.c new file +3 -0
+int register_mmio_handler(struct domain *d,
+                          const struct mmio_handler_ops *ops,
+                          paddr_t addr, paddr_t size)

xen/arch/riscv/mmio.c line 112

Quoted 10 lines
xen/arch/riscv/mmio.c new file +10 -0
+{
+    struct vmmio *vmmio = &d->arch.vmmio;
+    struct mmio_handler *handlers = vmmio->handlers;
+    paddr_t end = addr + size;
+    unsigned int i;
+    int rc = 0;
+    bool overlap;
+
+    if ( !ops || !ops->read || !ops->write || !size || end < addr )
+        return -EINVAL;

"!size || end < addr" can be had shorter as "end <= addr".

I will apply this.

Quoted 4 lines

Whether it's worth checking ops to be non-NULL I question, bit I wouldn't insist on dropping the check.

Probably it isn't really needed but just extra check that someone miss to provide implementation of ->read, ->write still could be useful. Also it is executed only at boot time so not big perfomance impact.

Quoted 21 lines
Quoted 7 lines
xen/arch/riscv/mmio.c new file +7 -0
+    write_lock(&vmmio->lock);
+
+    if ( vmmio->num_entries >= ARRAY_SIZE(vmmio->handlers) )
+    {
+        rc = -ENOSPC;
+        goto out;
+    }

xen/arch/riscv/mmio.c line 130

Quoted 10 lines
xen/arch/riscv/mmio.c new file +10 -0
+
+    /*
+     * The array is kept sorted by base address, so rather than appending and
+     * re-sorting, find the slot the new region belongs to and shift the tail
+     * up by one.
+     */
+    for ( i = vmmio->num_entries;
+          i > 0 && handlers[i - 1].addr > addr;
+          i-- )
+        /* Nothing */;
     for ( i = vmmio->num_entries; i-- > 0 && handlers[i].addr > addr; )
         /* Nothing */;
Quoted 1 line

?

It seems like it will break the code after it.

This breaks cases:
1. On a normal exit (handlers[i].addr <= addr), i is the index of the entry that was found, whereas the insertion slot ought to be i + 1. The code below, however, uses i as the insertion slot and handlers[i - 1] as the left neighbour - an off-by-one.

2.If every entry has a bigger addr than the new one, the loop exits when i == 0: 0 > 0 is false, yet i-- has already taken effect, so i == UINT_MAX. Then i > 0 is true, leading to a read of handlers[UINT_MAX - 1] and to memmove() with a size of (num_entries - UINT_MAX).

Case 1 pretty easy to fix, just use proper indexing but case 2 will require extra check at least. Thereby I think we could keep here original for loop.

Quoted 13 lines

xen/arch/riscv/mmio.c line 142

Quoted 12 lines
xen/arch/riscv/mmio.c new file +11 -0
+    /*
+     * Regions are required not to overlap; check both neighbours. Their
+     * addr + size cannot overflow, as such regions are rejected above when
+     * they get registered.
+     */
+    overlap = (i > 0 && handlers[i - 1].addr + handlers[i - 1].size > addr) ||
+              (i < vmmio->num_entries && end > handlers[i].addr);
+
+    if ( overlap )
+    {
+        rc = -EEXIST;
Quoted 2 lines

I fear -EEXIST can be misleading; it generally means _this_ range is already covered, not some sub-range thereof.

Then probably EADDRINUSE() would be better.

Thanks.

~ Oleksii

#45 lore raw

Re: [PATCH v2 08/39] xen/riscv: introduce device-agnostic MMIO emulation dispatch

Quoted 19 lines · Oleksii Kurochko
Quoted 17 lines · Jan Beulich
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/mmio.c new file +4 -0
+/*
+ * Check alignment and dispatch a decoded MMIO access to a registered
+ * handler. On success (0), info->data holds the read value for loads.
+ *

xen/arch/riscv/mmio.c line 82

Quoted 10 lines
xen/arch/riscv/mmio.c new file +10 -0
+ * There is no "retry" outcome to handle: find_mmio_handler() returns a
+ * copy of the matching handler taken under vmmio->lock and the ops
+ * structures are never freed, so the lookup result cannot go stale
+ * between finding the handler and invoking it.
+ */
+int do_mmio(mmio_info_t *info, paddr_t fault_addr, unsigned int len)
+{
+    /* Fault address should be aligned to length of MMIO */
+    if ( fault_addr & (len - 1) )
+        return -EIO;

Better first check (or at least assert) that len is a power of 2?

Quoted 3 lines

It make sense. I will do then:

     if ( len & (len - 1) || fault_addr & (len - 1) )

With more parentheses added, I suppose.

Quoted 19 lines
Quoted 7 lines
Quoted 7 lines
xen/arch/riscv/mmio.c new file +7 -0
+int register_mmio_handler(struct domain *d,
+                          const struct mmio_handler_ops *ops,
+                          paddr_t addr, paddr_t size)
+{
+    struct vmmio *vmmio = &d->arch.vmmio;
+    struct mmio_handler *handlers = vmmio->handlers;
+    paddr_t end = addr + size;
Quoted 8 lines

xen/arch/riscv/mmio.c line 112

Quoted 6 lines
xen/arch/riscv/mmio.c new file +6 -0
+    unsigned int i;
+    int rc = 0;
+    bool overlap;
+
+    if ( !ops || !ops->read || !ops->write || !size || end < addr )
+        return -EINVAL;

"!size || end < addr" can be had shorter as "end <= addr".

I will apply this.

Quoted 1 line
Quoted 6 lines
Quoted 2 lines

Whether it's worth checking ops to be non-NULL I question, bit I wouldn't insist on dropping the check.

Probably it isn't really needed but just extra check that someone miss to provide implementation of ->read, ->write still could be useful. Also it is executed only at boot time so not big perfomance impact.

I questioned merely the checking of ops itself, not that of the ->read and ->write hooks.

Quoted 31 lines
Quoted 21 lines
Quoted 7 lines
xen/arch/riscv/mmio.c new file +7 -0
+    write_lock(&vmmio->lock);
+
+    if ( vmmio->num_entries >= ARRAY_SIZE(vmmio->handlers) )
+    {
+        rc = -ENOSPC;
+        goto out;
+    }

xen/arch/riscv/mmio.c line 130

Quoted 10 lines
xen/arch/riscv/mmio.c new file +10 -0
+
+    /*
+     * The array is kept sorted by base address, so rather than appending and
+     * re-sorting, find the slot the new region belongs to and shift the tail
+     * up by one.
+     */
+    for ( i = vmmio->num_entries;
+          i > 0 && handlers[i - 1].addr > addr;
+          i-- )
+        /* Nothing */;
     for ( i = vmmio->num_entries; i-- > 0 && handlers[i].addr > addr; )
         /* Nothing */;
Quoted 1 line

?

It seems like it will break the code after it.

This breaks cases:
1. On a normal exit (handlers[i].addr <= addr), i is the index of the entry that was found, whereas the insertion slot ought to be i + 1. The code below, however, uses i as the insertion slot and handlers[i - 1] as the left neighbour - an off-by-one.

Quoted 8 lines

2.If every entry has a bigger addr than the new one, the loop exits when i == 0: 0 > 0 is false, yet i-- has already taken effect, so i == UINT_MAX. Then i > 0 is true, leading to a read of handlers[UINT_MAX - 1] and to memmove() with a size of (num_entries - UINT_MAX).

Case 1 pretty easy to fix, just use proper indexing but case 2 will require extra check at least. Thereby I think we could keep here original for loop.

Oh, I'm sorry for the bad suggestion then.

Jan

#46 lore raw

PATCH v2 9/39 xen/riscv: implement virtual APLIC MMIO emulation

In reply to Oleksii Kurochko

Guests running under Xen program interrupt routing by writing to APLIC MMIO registers. Xen must intercept these accesses to enforce interrupt isolation between domains and to translate guest routing intent into the underlying physical MSI topology.

Writes are gated by the domain's authorised interrupt bitmap so that a guest cannot affect interrupts it does not own. TARGET register writes additionally require translation of the hart and IMSIC guest-file indices from virtual to physical, as the APLIC uses these fields directly to compute the MSI delivery address.

Delegation (APLIC_SOURCECFG_D) is not yet supported.

---
Changes in v2:
- Shadow the guest-written target registers in a per-domain array and serve reads of APLIC_TARGET_* from it: the hardware register holds the value produced by aplic_msi_target_gen() (physical hart field, VS-file id), so reading it back would expose the host layout and return something the guest never wrote. A non-zero guest index is dropped with a one-time warning instead of being echoed back.
- aplic_hart_field(): take a CPU id instead of a hartid and derive both the group and the hart index from msi->base_addr + msi->offset - the hart index bits are a part of that offset, so the hartid can't be used as the hart index. Add APLIC_xMSICFGADDR_PPN_LHX_{MASK,SHIFT} for that.
- Document the IMSIC MSI target address layout and the APLIC hart index packing above aplic_hart_field(), and correct the corresponding diagram in asm/imsic.h.
- Drop the mask parameter of aplic_hw_read_reg() and apply the authorization mask in vaplic_emulate_load() instead.
- vaplic_emulate_{load,store}(): return bool instead of int, rename v/d to curr/currd and add ASSERT(curr == current).
- Use domain_vcpu() instead of open-coded d->vcpu[] indexing when resolving the target hart index.
- s/APLIC_REG_OFFSET_MASK/APLIC_CTRL_REGION_OFFSET_MASK/.
- Update store emulation handling for target register to be able to deal with target format in both cases (MSI and Direct).
- Update store emulation handling of domaincfg. There is no need to force DM/IE mode here (it will be forced/checked on Xen irq handler side).
- Rename APLIC_DEFAULT_PRIORITY and move to aplic.h as default prioity value is used in vaplic code too now.
---

---
 xen/arch/riscv/aplic-priv.h         |   3 +
 xen/arch/riscv/aplic.c              | 128 +++++++++-
 xen/arch/riscv/include/asm/aplic.h  |  34 +++
 xen/arch/riscv/include/asm/imsic.h  |  13 ++
 xen/arch/riscv/include/asm/vaplic.h |   5 +
 xen/arch/riscv/vaplic.c             | 350 +++++++++++++++++++++++++++-
 6 files changed, 528 insertions(+), 5 deletions(-)
xen/arch/riscv/aplic-priv.h +3 -0
index 35100d3a64fe..b3a1f79c5b76 100644
@@ -47,4 +47,7 @@ struct aplic_priv {
  */
 extern unsigned int guest_aplic_num_sources;
 
+uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
+                              uint32_t base_val);
+
 #endif /* ASM_RISCV_APLIC_PRIV_H */
xen/arch/riscv/aplic.c +124 -4

153 lines not on this page · raw message

xen/arch/riscv/include/asm/aplic.h +34 -0
index a2af55d54fc0..babba386071f 100644
@@ -39,6 +39,13 @@
 #define  APLIC_DOMAINCFG_IE             BIT(8, U)
 #define  APLIC_DOMAINCFG_DM             BIT(2, U)
 #define  APLIC_DOMAINCFG_BE             BIT(0, U)
+/*
+ * The bits a write may change. Everything else, including the read-only zero
+ * bit 7 and the reserved bits, has to read back as zero, and BE is WARL and
+ * hardwired to 0 as Xen is little-endian only.
+ */
+#define  APLIC_DOMAINCFG_WMASK          (APLIC_DOMAINCFG_IE | \
+                                         APLIC_DOMAINCFG_DM)
 
 #define APLIC_SOURCECFG_BASE            0x0004
 #define APLIC_SOURCECFG_LAST            0x0ffc
@@ -89,6 +96,9 @@
 #define  APLIC_TARGET_GUEST_IDX         GENMASK(17, 12)
 /* Bit 11 is reserved and reads as zero */
 #define  APLIC_TARGET_EIID              GENMASK(10, 0)
+/* If target is in DM mode */
+#define  APLIC_TARGET_IPRIO             GENMASK(7, 0)
+#define   APLIC_TARGET_IPRIO_DEFAULT    1U
 
 #define APLIC_IDC_SIZE                  32
 
@@ -98,6 +108,27 @@
 #define APLIC_SIZE(nr_cpus) \
     (APLIC_MIN_SIZE + APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_cpus)))
 
+/*
+ * Using setip is fine here, as all SET* and CLR* register groups consist of 32
+ * registers and therefore have identical sizes.
+ *
+ * Lowest 2 bits are always zero for SET* and CLR* registers.
+ */
+#define APLIC_SETCLR_OFFSET_MASK \
+    (sizeof_field(struct aplic_regs, setip) - sizeof(uint32_t))
+
+#define APLIC_xMSICFGADDR_PPN_SHIFT IMSIC_MMIO_PAGE_SHIFT
+
+#define APLIC_xMSICFGADDR_PPN_HHX_MASK(hhxw) \
+    (BIT(hhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_HHX_SHIFT(hhxs) \
+    ((hhxs) + APLIC_xMSICFGADDR_PPN_SHIFT)
+
+#define APLIC_xMSICFGADDR_PPN_LHX_MASK(lhxw) \
+    (BIT(lhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_LHX_SHIFT(lhxs) \
+    (lhxs)
+
 struct aplic_regs {
     uint32_t domaincfg;         /* 0x0000 */
     uint32_t sourcecfg[1023];   /* 0x0004 */
@@ -141,4 +172,7 @@ struct aplic_regs {
     uint32_t target[1023];      /* 0x3004 */
 };
 
+uint32_t aplic_hw_read_reg(unsigned int offset);
+void aplic_hw_write_reg(unsigned int offset, uint32_t value);
+
 #endif /* ASM_RISCV_APLIC_H */
xen/arch/riscv/include/asm/imsic.h +13 -0
index 2425430ed116..93f9e44c7d2c 100644
@@ -40,6 +40,19 @@ struct imsic_config {
     /* Base address */
     paddr_t base_addr;
 
+    /*
+     * MSI Target Address Scheme
+     *
+     * XLEN-1       HHXS+24          LHXS+12          12          0
+     * |            |                |                |           |
+     * ------------------------------------------------------------
+     * |xxxx|   g   |xxxxxxxx|   h   |xxxx|Guest Index|     0     |
+     * ------------------------------------------------------------
+     * - g: group number.
+     * - h: hart number relative to the group.
+     * - xxxx: remaining Base PPN bits; each gap may be zero-width.
+     */
+
     /* Bits representing Guest index, HART index, and Group index */
     unsigned int guest_index_bits;
     unsigned int hart_index_bits;
xen/arch/riscv/include/asm/vaplic.h +5 -0
index 96080bfbc23b..046c604915c4 100644
@@ -21,11 +21,16 @@ struct domain;
 
 struct vaplic_regs {
     uint32_t domaincfg;
+
+    uint32_t *target;
 };
 
 struct vaplic {
     struct vintc vintc;
     struct vaplic_regs regs;
+
+    paddr_t regs_start;
+    unsigned int regs_size;
 };
 
 int domain_vaplic_init(struct domain *d);
xen/arch/riscv/vaplic.c +349 -1

385 lines not on this page · raw message

Signature · 1 line
2.55.0
#47 lore raw

Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation

Quoted 53 lines

Guests running under Xen program interrupt routing by writing to APLIC MMIO registers. Xen must intercept these accesses to enforce interrupt isolation between domains and to translate guest routing intent into the underlying physical MSI topology.

Writes are gated by the domain's authorised interrupt bitmap so that a guest cannot affect interrupts it does not own. TARGET register writes additionally require translation of the hart and IMSIC guest-file indices from virtual to physical, as the APLIC uses these fields directly to compute the MSI delivery address.

Delegation (APLIC_SOURCECFG_D) is not yet supported.

xen/arch/riscv/aplic-priv.h +3 -0
index 35100d3a64..b3a1f79c5b 100644
@@ -47,4 +47,7 @@ struct aplic_priv {
  */
 extern unsigned int guest_aplic_num_sources;
 
+uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
+                              uint32_t base_val);
+
 #endif /* ASM_RISCV_APLIC_PRIV_H */
xen/arch/riscv/aplic.c +1 -2
index 3681f0669e..66ba4986a9 100644
@@ -16,6 +16,7 @@
 #include <xen/irq.h>
 #include <xen/mm.h>
 #include <xen/sections.h>
+#include <xen/sched.h>
 #include <xen/spinlock.h>
 #include <xen/types.h>
 #include <xen/vmap.h>
@@ -28,8 +29,6 @@
 #include <asm/io.h>
 #include <asm/riscv_encoding.h>
 
-#define APLIC_DEFAULT_PRIORITY  1
-
 static struct aplic_priv aplic = {
     .lock = SPIN_LOCK_UNLOCKED,
 };
@@ -38,6 +37,127 @@ static struct intc_info __ro_after_init aplic_info = {
     .hw_variant = INTC_APLIC,
 };
 

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 49

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+/*
+ * The arrangement of IMSIC interrupt files in MMIO space follows a topology
+ * defined by the RISC-V AIA specification. An IMSIC group is a set of
+ * interrupt files (e.g., in a cluster or socket) co-located in memory.
+ *
+ * The physical address of an outgoing MSI is calculated by bitwise ORing a
+ * Base Physical Page Number (Base PPN) with the Group Index (g), the Hart
+ * Index (h) and, for a supervisor-level interrupt domain, the Guest Index:
+ *
+ *   ( Base PPN | (g << (HHXS + 12)) | (h << LHXS) | guest ) << 12

Nit: it should be Guest Index (according to the spec) instead of guest wording:

    ( Base PPN | (g << (HHXS + 12)) | (h << LHXS) | Guest Index ) << 12
Quoted 24 lines
xen/arch/riscv/aplic.c +24 -0
+ *
+ * where Base PPN, HHXS, LHXS, HHXW and LHXW come from the {m,s}msiaddrcfg[h]
+ * registers of the interrupt domain that sends the MSI:
+ *
+ * XLEN-1       HHXS+24          LHXS+12          12          0
+ * |            |                |                |           |
+ * ------------------------------------------------------------
+ * |xxxx|   g   |xxxxxxxx|   h   |xxxx|Guest Index|     0     |
+ * ------------------------------------------------------------
+ *
+ * - g: group number.
+ * - h: hart number relative to the group.
+ * - xxxx: remaining Base PPN bits; each gap may be zero-width.
+ * - Guest Index: selects one of the 4 KiB pages right above the hart's own
+ *   supervisor-level file, i.e. it starts at bit 12; LHXS must therefore be
+ *   at least as large as the number of guest index bits.
+ * - Bits 11:0: always zero because IMSIC files are 4 KiB page-aligned.
+ *
+ * For wired interrupts in MSI delivery mode (domaincfg.DM = 1) the APLIC
+ * builds that address itself from the "Hart Index" field (bits 31:18) of the
+ * corresponding target[i] register. That field holds a hart index *number*,
+ * in which both indices are packed adjacently:
+ *
+ * 13          lhxw+hhxw   lhxw       0

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = {

Quoted 10 lines
xen/arch/riscv/aplic.c +9 -0
+ * |           |           |          |
+ * ------------------------------------
+ * |     0     |Group Index|Hart Index|
+ * ------------------------------------
+ *
+ * - lhxw (Low Hart Index Width): the number of bits used for the hart number
+ *   within a group.
+ * - hhxw (High Hart Index Width): the number of bits used for the group
+ *   number; the remaining bits of the field must be zero.
 

I think it's not very clear that the schema represents the "Hart Index" field i.e. target[i] bits 31:18. Moreover, the schema like that is wrong as it is not Group Index or Hart Index but g and h.

I'd suggest something like this:

* For wired interrupts in MSI delivery mode (domaincfg.DM = 1), the APLIC
* computes the MSI target address itself from the "Hart Index" field
* (bits 31:18) of the corresponding target[i] register. This 14-bit field
* holds both g and h:
*
* 13 lhxw+hhxw lhxw 0
* | | | |
* ------------------------------------
* | 0 | g | h |
* ------------------------------------
*
* - lhxw (Low Hart Index Width): the number of bits used for the hart number
* within a group.
* - hhxw (High Hart Index Width): the number of bits used for the group
* number; the remaining bits of the field must be zero.

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 92

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+ *
+ * The Guest Index isn't a part of it: for a supervisor-level interrupt domain
+ * it has its own field (bits 17:12) in target[i].
+ *
+ * Because there are "xxxx" gaps (Base PPN bits) between the indices in the
+ * physical address (depending on HHXS and LHXS), software must extract the
+ * group and hart components separately and pack them into the APLIC-defined
+ * Hart Index format to ensure correct MSI targeting.
+ */
+static unsigned long aplic_hart_field(unsigned int cpu)

I should have renamed this to aplic_hart_index() as it's formerly what the function returns.

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 95

Quoted 3 lines
xen/arch/riscv/aplic.c +3 -0
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    const struct imsic_msi *msi = &imsic->msi[cpu];

Nit: this could be const ...

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 97

Quoted 2 lines
xen/arch/riscv/aplic.c +2 -0
+    /* Low Hart Index Shift */
+    unsigned int lhxs = imsic->guest_index_bits;

It seems incoherent with the diagram above as there is some xxxx between Guest Index bits and lhxs + 12. Therefore, it is not that obvious that lhxs is equal to guest_index_bits.

Quoted 7 lines
xen/arch/riscv/aplic.c +7 -0
+    /* Low Hart Index Width */
+    unsigned int lhxw = imsic->hart_index_bits;
+    /* High Hart Index Width */
+    unsigned int hhxw = imsic->group_index_bits;
+    /* High Hart Index Shift */
+    unsigned int hhxs =
+        imsic->group_index_shift - APLIC_xMSICFGADDR_PPN_SHIFT * 2;

...

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 106

Quoted 2 lines
xen/arch/riscv/aplic.c +2 -0
+    /*
+     * msi->base_addr is the base of the MMIO regset this CPU's interrupt

So if I understood correctly, msi->base_addr corresponds to the group terminology? Is it always the case?

Quoted 11 lines
xen/arch/riscv/aplic.c +11 -0
+     * files live in, and one regset can cover several harts; msi->offset
+     * selects this CPU's block inside it. The hart index bits are part of
+     * that offset, so both indexes have to be derived from the full address.
+     */
+    paddr_t target_addr = msi->base_addr + msi->offset;
+    unsigned long tppn = target_addr >> APLIC_xMSICFGADDR_PPN_SHIFT;
+    unsigned long g =
+        (tppn >> APLIC_xMSICFGADDR_PPN_HHX_SHIFT(hhxs)) &
+        APLIC_xMSICFGADDR_PPN_HHX_MASK(hhxw);
+    unsigned long h =
+        (tppn >> APLIC_xMSICFGADDR_PPN_LHX_SHIFT(lhxs)) &

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 127

Quoted 10 lines
xen/arch/riscv/aplic.c +10 -0
+        APLIC_xMSICFGADDR_PPN_LHX_MASK(lhxw);
+
+    return (g << lhxw) | h;
+}
+
+uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
+                              uint32_t base_val)
+{
+    unsigned int guest_id = vcpu_guest_file_id(target_vcpu);
+    unsigned long hart_field = aplic_hart_field(target_vcpu->processor);

Nit: could be const
Should be hart_index too, according to previous comment.

Quoted 67 lines
xen/arch/riscv/aplic.c +35 -2
+
+    base_val &= APLIC_TARGET_EIID;
+    base_val |= MASK_INSR(guest_id, APLIC_TARGET_GUEST_IDX);
+    base_val |= MASK_INSR(hart_field, APLIC_TARGET_HART_IDX);
+
+    return base_val;
+}
+
+uint32_t aplic_hw_read_reg(unsigned int offset)
+{
+    unsigned long flags;
+    uint32_t val;
+
+    ASSERT((offset < aplic.size) && IS_ALIGNED(offset, sizeof(uint32_t)));
+
+    spin_lock_irqsave(&aplic.lock, flags);
+    val = readl((volatile void __iomem *)aplic.regs + offset);
+    spin_unlock_irqrestore(&aplic.lock, flags);
+
+    return val;
+}
+
+void aplic_hw_write_reg(unsigned int offset, uint32_t value)
+{
+    unsigned long flags;
+
+    ASSERT((offset < aplic.size) && IS_ALIGNED(offset, sizeof(uint32_t)));
+
+    spin_lock_irqsave(&aplic.lock, flags);
+    writel(value, (volatile void __iomem *)aplic.regs + offset);
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+
 static void __init aplic_init_hw_interrupts(void)
 {
     unsigned int i;
@@ -53,9 +173,9 @@ static void __init aplic_init_hw_interrupts(void)
         /*
          * Low bits of target register contains Interrupt Priority bits which
          * can't be zero according to AIA spec.
-         * Thereby they are initialized to APLIC_DEFAULT_PRIORITY.
+         * Thereby they are initialized to APLIC_TARGET_IPRIO_DEFAULT.
          */
-        writel(APLIC_DEFAULT_PRIORITY, &aplic.regs->target[i]);
+        writel(APLIC_TARGET_IPRIO_DEFAULT, &aplic.regs->target[i]);
     }
 
     writel(APLIC_DOMAINCFG_IE | APLIC_DOMAINCFG_DM, &aplic.regs->domaincfg);
xen/arch/riscv/include/asm/aplic.h +7 -0
index a2af55d54f..babba38607 100644
@@ -39,6 +39,13 @@
 #define  APLIC_DOMAINCFG_IE             BIT(8, U)
 #define  APLIC_DOMAINCFG_DM             BIT(2, U)
 #define  APLIC_DOMAINCFG_BE             BIT(0, U)
+/*
+ * The bits a write may change. Everything else, including the read-only zero
+ * bit 7 and the reserved bits, has to read back as zero, and BE is WARL and
+ * hardwired to 0 as Xen is little-endian only.
+ */
+#define  APLIC_DOMAINCFG_WMASK          (APLIC_DOMAINCFG_IE | \
+                                         APLIC_DOMAINCFG_DM)
 
 #define APLIC_SOURCECFG_BASE            0x0004
 #define APLIC_SOURCECFG_LAST            0x0ffc

xen/arch/riscv/include/asm/aplic.h line 99

Quoted 4 lines
xen/arch/riscv/include/asm/aplic.h +1 -0
@@ -89,6 +96,9 @@
 #define  APLIC_TARGET_GUEST_IDX         GENMASK(17, 12)
 /* Bit 11 is reserved and reads as zero */
 #define  APLIC_TARGET_EIID              GENMASK(10, 0)
+/* If target is in DM mode */

I think this comment is not clear; I expect, by reading it, to have domaincfg.DM = 1 which is MSI mode, but I think you were talking about direct delivery mode, right? If so, I would change this comment to

/* If target is in direct delivery mode (domaincfg.DM = 0) */

Quoted 52 lines
xen/arch/riscv/include/asm/aplic.h +26 -0
+#define  APLIC_TARGET_IPRIO             GENMASK(7, 0)
+#define   APLIC_TARGET_IPRIO_DEFAULT    1U
 
 #define APLIC_IDC_SIZE                  32
 
@@ -98,6 +108,27 @@
 #define APLIC_SIZE(nr_cpus) \
     (APLIC_MIN_SIZE + APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_cpus)))
 
+/*
+ * Using setip is fine here, as all SET* and CLR* register groups consist of 32
+ * registers and therefore have identical sizes.
+ *
+ * Lowest 2 bits are always zero for SET* and CLR* registers.
+ */
+#define APLIC_SETCLR_OFFSET_MASK \
+    (sizeof_field(struct aplic_regs, setip) - sizeof(uint32_t))
+
+#define APLIC_xMSICFGADDR_PPN_SHIFT IMSIC_MMIO_PAGE_SHIFT
+
+#define APLIC_xMSICFGADDR_PPN_HHX_MASK(hhxw) \
+    (BIT(hhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_HHX_SHIFT(hhxs) \
+    ((hhxs) + APLIC_xMSICFGADDR_PPN_SHIFT)
+
+#define APLIC_xMSICFGADDR_PPN_LHX_MASK(lhxw) \
+    (BIT(lhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_LHX_SHIFT(lhxs) \
+    (lhxs)
+
 struct aplic_regs {
     uint32_t domaincfg;         /* 0x0000 */
     uint32_t sourcecfg[1023];   /* 0x0004 */
@@ -141,4 +172,7 @@ struct aplic_regs {
     uint32_t target[1023];      /* 0x3004 */
 };
 
+uint32_t aplic_hw_read_reg(unsigned int offset);
+void aplic_hw_write_reg(unsigned int offset, uint32_t value);
+
 #endif /* ASM_RISCV_APLIC_H */
xen/arch/riscv/include/asm/imsic.h +3 -0
index 2425430ed1..93f9e44c7d 100644
@@ -40,6 +40,19 @@ struct imsic_config {
     /* Base address */
     paddr_t base_addr;
 
+    /*
+     * MSI Target Address Scheme
+     *

xen/arch/riscv/include/asm/imsic.h struct imsic_config { · line 55

Quoted 10 lines
xen/arch/riscv/include/asm/imsic.h +10 -0
+     * XLEN-1       HHXS+24          LHXS+12          12          0
+     * |            |                |                |           |
+     * ------------------------------------------------------------
+     * |xxxx|   g   |xxxxxxxx|   h   |xxxx|Guest Index|     0     |
+     * ------------------------------------------------------------
+     * - g: group number.
+     * - h: hart number relative to the group.
+     * - xxxx: remaining Base PPN bits; each gap may be zero-width.
+     */
+

Is this really needed as you already explain this above in aplic.c? Please choose one place between the two if not.

Quoted 243 lines
xen/arch/riscv/include/asm/imsic.h +0 -0
     /* Bits representing Guest index, HART index, and Group index */
     unsigned int guest_index_bits;
     unsigned int hart_index_bits;
xen/arch/riscv/include/asm/vaplic.h +5 -0
index 96080bfbc2..046c604915 100644
@@ -21,11 +21,16 @@ struct domain;
 
 struct vaplic_regs {
     uint32_t domaincfg;
+
+    uint32_t *target;
 };
 
 struct vaplic {
     struct vintc vintc;
     struct vaplic_regs regs;
+
+    paddr_t regs_start;
+    unsigned int regs_size;
 };
 
 int domain_vaplic_init(struct domain *d);
xen/arch/riscv/vaplic.c +204 -0
index 14f6e3164a..8726f7203d 100644
@@ -17,6 +17,7 @@
 #include <asm/aia.h>
 #include <asm/imsic.h>
 #include <asm/intc.h>
+#include <asm/mmio.h>
 #include <asm/vaplic.h>
 
 #include "aplic-priv.h"
@@ -27,6 +28,279 @@ unsigned int __ro_after_init guest_aplic_num_sources;
 
 #define FDT_VAPLIC_INT_CELLS 2
 
+#define AUTH_IRQ_BIT(d, irqn) \
+    (((irqn) < (d)->arch.vintc->nr_virqs) && \
+     test_bit(irqn, (d)->arch.vintc->used_irqs))
+
+/*
+ * Convert a byte offset (within a SETIP/CLRIP/SETIE/CLRIE register group) to
+ * a 32-bit word index into the used_irqs bitmap. Each word covers 32
+ * interrupt sources. For SOURCECFG and TARGET groups the same division also
+ * yields the interrupt number directly, because those arrays store one 32-bit
+ * register per source.
+ */
+#define regoffset_to_word_idx(reg_val) ((reg_val) / sizeof(uint32_t))
+
+static uint32_t vaplic_target_read(const struct domain *d, unsigned int irqn)
+{
+    const struct vaplic *vaplic = to_vaplic(d);
+
+    /* target[0] doesn't exist so irqn == 0 should be impossible */
+    if ( !irqn || irqn >= vaplic->vintc.nr_virqs )
+        return 0;
+
+    return read_atomic(&vaplic->regs.target[irqn]);
+}
+
+static inline uint32_t generate_auth_mask(const struct domain *currd,
+                                          unsigned int word_idx)
+{
+    unsigned int first_bit = word_idx * sizeof(uint32_t) * BITS_PER_BYTE;
+
+    if ( word_idx >= DIV_ROUND_UP(currd->arch.vintc->nr_virqs,
+                                  sizeof(uint32_t) * BITS_PER_BYTE) )
+    {
+        gdprintk(XENLOG_DEBUG, "incorrect word_idx(%u) is passed\n", word_idx);
+
+        return 0;
+    }
+
+    return currd->arch.vintc->used_irqs[first_bit / BITS_PER_LONG] >>
+           (first_bit % BITS_PER_LONG);
+}
+
+static bool vaplic_emulate_load(const struct vcpu *curr, paddr_t addr,
+                                uint32_t *out)
+{
+    const struct domain *currd = curr->domain;
+    const struct vaplic *vaplic = to_vaplic(currd);
+    const unsigned int offset = addr & APLIC_CTRL_REGION_OFFSET_MASK;
+    uint32_t auth_mask;
+    unsigned int i;
+
+    ASSERT(curr == current);
+
+    switch ( offset )
+    {
+    case APLIC_DOMAINCFG:
+        *out = vaplic->regs.domaincfg;
+
+        return true;
+
+    case APLIC_SETIPNUM:
+    case APLIC_SETIPNUM_LE:
+    case APLIC_CLRIPNUM:
+    case APLIC_SETIENUM:
+    case APLIC_CLRIENUM:
+    case APLIC_CLRIE_BASE ... APLIC_CLRIE_LAST:
+        /*
+         * Based on the RISC-V AIA spec a read of these registers
+         * always returns zero
+         */
+        *out = 0;
+
+        return true;
+
+    case APLIC_SETIP_BASE ... APLIC_SETIP_LAST:
+    case APLIC_CLRIP_BASE ... APLIC_CLRIP_LAST:
+    case APLIC_SETIE_BASE ... APLIC_SETIE_LAST:
+        i = regoffset_to_word_idx(offset & APLIC_SETCLR_OFFSET_MASK);
+        auth_mask = generate_auth_mask(currd, i);
+
+        break;
+
+    case APLIC_TARGET_BASE ... APLIC_TARGET_LAST:
+        /*
+         * As target registers start from 1:
+         *  0x3000 genmsi
+         *  0x3004 target[1]
+         *  0x3008 target[2]
+         *   ...
+         *  0x3FFC target[1023]
+         * It is necessary to calculate an interrupt number by subtracting
+         * APLIC_GENMSI instead of APLIC_TARGET_BASE.
+         */
+        i = regoffset_to_word_idx(offset - APLIC_GENMSI);
+
+        *out = AUTH_IRQ_BIT(currd, i) ? vaplic_target_read(currd, i) : 0;
+
+        return true;
+
+    default:
+        gdprintk(XENLOG_WARNING, "Unhandled APLIC read at offset %#x\n",
+                 offset);
+
+        return false;
+    }
+
+    *out = aplic_hw_read_reg(offset) & auth_mask;
+
+    return true;
+}
+
+static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
+                                 uint32_t value)
+{
+    const struct domain *currd = curr->domain;
+    unsigned int offset = addr & APLIC_CTRL_REGION_OFFSET_MASK;
+
+    ASSERT(curr == current);
+
+    switch ( offset )
+    {
+    case APLIC_SETIP_BASE ... APLIC_SETIP_LAST:
+    case APLIC_CLRIP_BASE ... APLIC_CLRIP_LAST:
+    case APLIC_SETIE_BASE ... APLIC_SETIE_LAST:
+    case APLIC_CLRIE_BASE ... APLIC_CLRIE_LAST:
+    {
+        unsigned int word_idx =
+            regoffset_to_word_idx(offset & APLIC_SETCLR_OFFSET_MASK);
+
+        value &= generate_auth_mask(currd, word_idx);
+
+        break;
+    }
+
+    case APLIC_SOURCECFG_BASE ... APLIC_SOURCECFG_LAST:
+        if ( value & APLIC_SOURCECFG_D )
+        {
+            dprintk(XENLOG_ERR, "APLIC_SOURCECFG_D isn't supported\n");
+
+            goto fail;
+        }
+
+        /*
+         * As sourcecfg register starts from 1:
+         *   0x0000 domaincfg
+         *   0x0004 sourcecfg[1]
+         *   0x0008 sourcecfg[2]
+         *    ...
+         *   0x0FFC sourcecfg[1023]
+         * It is necessary to calculate an interrupt number by subtracting
+         * APLIC_DOMAINCFG instead of APLIC_SOURCECFG_BASE.
+         */
+        if ( !AUTH_IRQ_BIT(currd,
+                           regoffset_to_word_idx(offset - APLIC_DOMAINCFG)) )
+            /* Interrupt not enabled, ignore it */
+            return true;
+
+        if ( value > APLIC_SOURCECFG_SM_LEVEL_LOW )
+        {
+            gdprintk(XENLOG_ERR,
+                     "value(%#x) is incorrect for sourcecfg register\n",
+                     value);
+
+            return true;
+        }
+
+        break;
+
+    case APLIC_TARGET_BASE ... APLIC_TARGET_LAST:
+    {
+        struct vaplic *vaplic = to_vaplic(currd);
+        struct vcpu *target_vcpu;
+        unsigned int guest_hart_idx = MASK_EXTR(value, APLIC_TARGET_HART_IDX);
+        /*
+         * Look at vaplic_emulate_load() for explanation why APLIC_GENMSI is
+         * subtracted.
+         */
+        unsigned int srcn = regoffset_to_word_idx(offset - APLIC_GENMSI);
+
+        if ( !AUTH_IRQ_BIT(currd, srcn) )
+            /* Interrupt not enabled, ignore it */
+            return true;
+
+        target_vcpu = domain_vcpu(currd, guest_hart_idx);
+
+        if ( !target_vcpu )
+        {
+            dprintk(XENLOG_ERR, "Invalid vCPU id in target register\n");
+
+            /* Ignore such writings */
+            return true;
+        }
+
+        if ( vaplic->regs.domaincfg & APLIC_DOMAINCFG_DM )
+        {
+            /*
+             * A non-zero guest index asks for delivery to an interrupt file of
+             * nested guest. The vIMSIC node has no riscv,guest-index-bits
+             * property, so a guest is told its harts have no guest interrupt
+             * files and the field is read-only zero for them. The write isn't
+             * rejected (that would throw away a valid hart index and EIID);
+             * instead the field is dropped, which is also what
+             * aplic_msi_target_gen() does with it when programming the h/w.
+             */

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 243

Quoted 10 lines
xen/arch/riscv/vaplic.c +9 -0
+            if ( MASK_EXTR(value, APLIC_TARGET_GUEST_IDX) )
+            {
+                printk_once(XENLOG_WARNING
+                            "%pd: vAPLIC target guest index != 0 is unsupported\n",
+                            currd);
+
+                /* Ignore such writes ... */
+                return true;
+            }
 

Comment above this says "The write isn't rejected ... instead the field is dropped, which is also what aplic_msi_target_gen() does with it." But the code doesn't follow it as it returns true immediately here before the write occurred and without zeroing the guest index field.

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

Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation

Quoted 11 lines · Baptiste Le Duc
Quoted 11 lines

+/*
+ * The arrangement of IMSIC interrupt files in MMIO space follows a topology
+ * defined by the RISC-V AIA specification. An IMSIC group is a set of
+ * interrupt files (e.g., in a cluster or socket) co-located in memory.
+ *
+ * The physical address of an outgoing MSI is calculated by bitwise ORing a
+ * Base Physical Page Number (Base PPN) with the Group Index (g), the Hart
+ * Index (h) and, for a supervisor-level interrupt domain, the Guest Index:
+ *
+ * ( Base PPN | (g << (HHXS + 12)) | (h << LHXS) | guest ) << 12

Quoted 3 lines

Nit: it should be Guest Index (according to the spec) instead of guest wording:

     ( Base PPN | (g << (HHXS + 12)) | (h << LHXS) | Guest Index ) << 12

Applied.

Quoted 40 lines
Quoted 25 lines

+ *
+ * where Base PPN, HHXS, LHXS, HHXW and LHXW come from the {m,s}msiaddrcfg[h]
+ * registers of the interrupt domain that sends the MSI:
+ *

+ * XLEN-1       HHXS+24          LHXS+12          12          0
+ * |            |                |                |           |

+ * ------------------------------------------------------------
+ * |xxxx| g |xxxxxxxx| h |xxxx|Guest Index| 0 |
+ * ------------------------------------------------------------
+ *
+ * - g: group number.
+ * - h: hart number relative to the group.
+ * - xxxx: remaining Base PPN bits; each gap may be zero-width.
+ * - Guest Index: selects one of the 4 KiB pages right above the hart's own
+ * supervisor-level file, i.e. it starts at bit 12; LHXS must therefore be
+ * at least as large as the number of guest index bits.
+ * - Bits 11:0: always zero because IMSIC files are 4 KiB page-aligned.
+ *
+ * For wired interrupts in MSI delivery mode (domaincfg.DM = 1) the APLIC
+ * builds that address itself from the "Hart Index" field (bits 31:18) of the
+ * corresponding target[i] register. That field holds a hart index *number*,
+ * in which both indices are packed adjacently:
+ *

+ * 13          lhxw+hhxw   lhxw       0
+ * |           |           |          |
Quoted 9 lines

+ * ------------------------------------
+ * | 0 |Group Index|Hart Index|
+ * ------------------------------------
+ *
+ * - lhxw (Low Hart Index Width): the number of bits used for the hart number
+ * within a group.
+ * - hhxw (High Hart Index Width): the number of bits used for the group
+ * number; the remaining bits of the field must be zero.

I think it's not very clear that the schema represents the "Hart Index" field i.e. target[i] bits 31:18. Moreover, the schema like that is wrong as it is not Group Index or Hart Index but g and h.

I'd suggest something like this:

Quoted 15 lines

* For wired interrupts in MSI delivery mode (domaincfg.DM = 1), the APLIC
* computes the MSI target address itself from the "Hart Index" field
* (bits 31:18) of the corresponding target[i] register. This 14-bit field
* holds both g and h:
*
* 13 lhxw+hhxw lhxw 0
* | | | |
* ------------------------------------
* | 0 | g | h |
* ------------------------------------
*
* - lhxw (Low Hart Index Width): the number of bits used for the hart number
* within a group.
* - hhxw (High Hart Index Width): the number of bits used for the group
* number; the remaining bits of the field must be zero.

Applied.

Quoted 11 lines
Quoted 11 lines

+ *
+ * The Guest Index isn't a part of it: for a supervisor-level interrupt domain
+ * it has its own field (bits 17:12) in target[i].
+ *
+ * Because there are "xxxx" gaps (Base PPN bits) between the indices in the
+ * physical address (depending on HHXS and LHXS), software must extract the
+ * group and hart components separately and pack them into the APLIC-defined
+ * Hart Index format to ensure correct MSI targeting.
+ */
+static unsigned long aplic_hart_field(unsigned int cpu)

Quoted 2 lines

I should have renamed this to aplic_hart_index() as it's formerly what the function returns.

Applied.

Quoted 4 lines

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 95

Quoted 3 lines
xen/arch/riscv/aplic.c +3 -0
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    const struct imsic_msi *msi = &imsic->msi[cpu];

Nit: this could be const ...

Sorry, I am not understand what do you expect from me to do with 'const' here. At the moment we don't chnage anything in this function connected to msi variable, just a reading.

Quoted 12 lines

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 97

Quoted 2 lines
xen/arch/riscv/aplic.c +2 -0
+    /* Low Hart Index Shift */
+    unsigned int lhxs = imsic->guest_index_bits;

It seems incoherent with the diagram above as there is some xxxx between Guest Index bits and lhxs + 12. Therefore, it is not that obvious that lhxs is equal to guest_index_bits.

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 104

Quoted 7 lines
xen/arch/riscv/aplic.c +7 -0
+    /* Low Hart Index Width */
+    unsigned int lhxw = imsic->hart_index_bits;
+    /* High Hart Index Width */
+    unsigned int hhxw = imsic->group_index_bits;
+    /* High Hart Index Shift */
+    unsigned int hhxs =
+        imsic->group_index_shift - APLIC_xMSICFGADDR_PPN_SHIFT * 2;
Quoted 5 lines

...

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 106

Quoted 2 lines
xen/arch/riscv/aplic.c +2 -0
+    /*
+     * msi->base_addr is the base of the MMIO regset this CPU's interrupt

So if I understood correctly, msi->base_addr corresponds to the group terminology? Is it always the case?

I think - yes. This value is taken from DTS which and is used to describe IMSIC group.

Quoted 14 lines
Quoted 14 lines
xen/arch/riscv/aplic.c +14 -0
+     * files live in, and one regset can cover several harts; msi->offset
+     * selects this CPU's block inside it. The hart index bits are part of
+     * that offset, so both indexes have to be derived from the full address.
+     */
+    paddr_t target_addr = msi->base_addr + msi->offset;
+    unsigned long tppn = target_addr >> APLIC_xMSICFGADDR_PPN_SHIFT;
+    unsigned long g =
+        (tppn >> APLIC_xMSICFGADDR_PPN_HHX_SHIFT(hhxs)) &
+        APLIC_xMSICFGADDR_PPN_HHX_MASK(hhxw);
+    unsigned long h =
+        (tppn >> APLIC_xMSICFGADDR_PPN_LHX_SHIFT(lhxs)) &
+        APLIC_xMSICFGADDR_PPN_LHX_MASK(lhxw);
+
+    return (g << lhxw) | h;
Quoted 8 lines

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 127

Quoted 7 lines
xen/arch/riscv/aplic.c +7 -0
+}
+
+uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
+                              uint32_t base_val)
+{
+    unsigned int guest_id = vcpu_guest_file_id(target_vcpu);
+    unsigned long hart_field = aplic_hart_field(target_vcpu->processor);

Nit: could be const

Techically I agree. Then for guest_id it should const too, right?

But it seems like Xen in such cases don't use const. Have you found a rule that we have to use const in such cases?

I don't mind to put const here but then it would be nice if someone will tell me some kind of rule...

Quoted 1 line

Should be hart_index too, according to previous comment.

Applied.

Quoted 75 lines
Quoted 67 lines
xen/arch/riscv/aplic.c +35 -2
+
+    base_val &= APLIC_TARGET_EIID;
+    base_val |= MASK_INSR(guest_id, APLIC_TARGET_GUEST_IDX);
+    base_val |= MASK_INSR(hart_field, APLIC_TARGET_HART_IDX);
+
+    return base_val;
+}
+
+uint32_t aplic_hw_read_reg(unsigned int offset)
+{
+    unsigned long flags;
+    uint32_t val;
+
+    ASSERT((offset < aplic.size) && IS_ALIGNED(offset, sizeof(uint32_t)));
+
+    spin_lock_irqsave(&aplic.lock, flags);
+    val = readl((volatile void __iomem *)aplic.regs + offset);
+    spin_unlock_irqrestore(&aplic.lock, flags);
+
+    return val;
+}
+
+void aplic_hw_write_reg(unsigned int offset, uint32_t value)
+{
+    unsigned long flags;
+
+    ASSERT((offset < aplic.size) && IS_ALIGNED(offset, sizeof(uint32_t)));
+
+    spin_lock_irqsave(&aplic.lock, flags);
+    writel(value, (volatile void __iomem *)aplic.regs + offset);
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+
  static void __init aplic_init_hw_interrupts(void)
  {
      unsigned int i;
@@ -53,9 +173,9 @@ static void __init aplic_init_hw_interrupts(void)
          /*
           * Low bits of target register contains Interrupt Priority bits which
           * can't be zero according to AIA spec.
-         * Thereby they are initialized to APLIC_DEFAULT_PRIORITY.
+         * Thereby they are initialized to APLIC_TARGET_IPRIO_DEFAULT.
           */
-        writel(APLIC_DEFAULT_PRIORITY, &aplic.regs->target[i]);
+        writel(APLIC_TARGET_IPRIO_DEFAULT, &aplic.regs->target[i]);
      }
 
      writel(APLIC_DOMAINCFG_IE | APLIC_DOMAINCFG_DM, &aplic.regs->domaincfg);
xen/arch/riscv/include/asm/aplic.h +7 -0
index a2af55d54f..babba38607 100644
@@ -39,6 +39,13 @@
  #define  APLIC_DOMAINCFG_IE             BIT(8, U)
  #define  APLIC_DOMAINCFG_DM             BIT(2, U)
  #define  APLIC_DOMAINCFG_BE             BIT(0, U)
+/*
+ * The bits a write may change. Everything else, including the read-only zero
+ * bit 7 and the reserved bits, has to read back as zero, and BE is WARL and
+ * hardwired to 0 as Xen is little-endian only.
+ */
+#define  APLIC_DOMAINCFG_WMASK          (APLIC_DOMAINCFG_IE | \
+                                         APLIC_DOMAINCFG_DM)
 
  #define APLIC_SOURCECFG_BASE            0x0004
  #define APLIC_SOURCECFG_LAST            0x0ffc

xen/arch/riscv/include/asm/aplic.h line 99

Quoted 4 lines
xen/arch/riscv/include/asm/aplic.h +1 -0
@@ -89,6 +96,9 @@
  #define  APLIC_TARGET_GUEST_IDX         GENMASK(17, 12)
  /* Bit 11 is reserved and reads as zero */
  #define  APLIC_TARGET_EIID              GENMASK(10, 0)
+/* If target is in DM mode */

I think this comment is not clear; I expect, by reading it, to have domaincfg.DM = 1 which is MSI mode, but I think you were talking about direct delivery mode, right? If so, I would change this comment to

Quoted 1 line

/* If target is in direct delivery mode (domaincfg.DM = 0) */

Yes, my comment is incorrect, it should be yours. Applied.

Quoted 49 lines
Quoted 49 lines
xen/arch/riscv/include/asm/aplic.h +26 -0
+#define  APLIC_TARGET_IPRIO             GENMASK(7, 0)
+#define   APLIC_TARGET_IPRIO_DEFAULT    1U
 
  #define APLIC_IDC_SIZE                  32
 
@@ -98,6 +108,27 @@
  #define APLIC_SIZE(nr_cpus) \
      (APLIC_MIN_SIZE + APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_cpus)))
 
+/*
+ * Using setip is fine here, as all SET* and CLR* register groups consist of 32
+ * registers and therefore have identical sizes.
+ *
+ * Lowest 2 bits are always zero for SET* and CLR* registers.
+ */
+#define APLIC_SETCLR_OFFSET_MASK \
+    (sizeof_field(struct aplic_regs, setip) - sizeof(uint32_t))
+
+#define APLIC_xMSICFGADDR_PPN_SHIFT IMSIC_MMIO_PAGE_SHIFT
+
+#define APLIC_xMSICFGADDR_PPN_HHX_MASK(hhxw) \
+    (BIT(hhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_HHX_SHIFT(hhxs) \
+    ((hhxs) + APLIC_xMSICFGADDR_PPN_SHIFT)
+
+#define APLIC_xMSICFGADDR_PPN_LHX_MASK(lhxw) \
+    (BIT(lhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_LHX_SHIFT(lhxs) \
+    (lhxs)
+
  struct aplic_regs {
      uint32_t domaincfg;         /* 0x0000 */
      uint32_t sourcecfg[1023];   /* 0x0004 */
@@ -141,4 +172,7 @@ struct aplic_regs {
      uint32_t target[1023];      /* 0x3004 */
  };
 
+uint32_t aplic_hw_read_reg(unsigned int offset);
+void aplic_hw_write_reg(unsigned int offset, uint32_t value);
+
  #endif /* ASM_RISCV_APLIC_H */
xen/arch/riscv/include/asm/imsic.h +0 -0
index 2425430ed1..93f9e44c7d 100644
@@ -40,6 +40,19 @@ struct imsic_config {
      /* Base address */
      paddr_t base_addr;
 
Quoted 15 lines

xen/arch/riscv/include/asm/imsic.h struct imsic_config { · line 55

Quoted 13 lines
xen/arch/riscv/include/asm/imsic.h +13 -0
+    /*
+     * MSI Target Address Scheme
+     *
+     * XLEN-1       HHXS+24          LHXS+12          12          0
+     * |            |                |                |           |
+     * ------------------------------------------------------------
+     * |xxxx|   g   |xxxxxxxx|   h   |xxxx|Guest Index|     0     |
+     * ------------------------------------------------------------
+     * - g: group number.
+     * - h: hart number relative to the group.
+     * - xxxx: remaining Base PPN bits; each gap may be zero-width.
+     */
+

Is this really needed as you already explain this above in aplic.c? Please choose one place between the two if not.

No, I don't think so. For me, it is also enough to have in one place. I will drop it here and keep only in aplic.c.

[...]

Quoted 100 lines
Quoted 100 lines
xen/arch/riscv/include/asm/imsic.h +100 -0
+
+static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
+                                 uint32_t value)
+{
+    const struct domain *currd = curr->domain;
+    unsigned int offset = addr & APLIC_CTRL_REGION_OFFSET_MASK;
+
+    ASSERT(curr == current);
+
+    switch ( offset )
+    {
+    case APLIC_SETIP_BASE ... APLIC_SETIP_LAST:
+    case APLIC_CLRIP_BASE ... APLIC_CLRIP_LAST:
+    case APLIC_SETIE_BASE ... APLIC_SETIE_LAST:
+    case APLIC_CLRIE_BASE ... APLIC_CLRIE_LAST:
+    {
+        unsigned int word_idx =
+            regoffset_to_word_idx(offset & APLIC_SETCLR_OFFSET_MASK);
+
+        value &= generate_auth_mask(currd, word_idx);
+
+        break;
+    }
+
+    case APLIC_SOURCECFG_BASE ... APLIC_SOURCECFG_LAST:
+        if ( value & APLIC_SOURCECFG_D )
+        {
+            dprintk(XENLOG_ERR, "APLIC_SOURCECFG_D isn't supported\n");
+
+            goto fail;
+        }
+
+        /*
+         * As sourcecfg register starts from 1:
+         *   0x0000 domaincfg
+         *   0x0004 sourcecfg[1]
+         *   0x0008 sourcecfg[2]
+         *    ...
+         *   0x0FFC sourcecfg[1023]
+         * It is necessary to calculate an interrupt number by subtracting
+         * APLIC_DOMAINCFG instead of APLIC_SOURCECFG_BASE.
+         */
+        if ( !AUTH_IRQ_BIT(currd,
+                           regoffset_to_word_idx(offset - APLIC_DOMAINCFG)) )
+            /* Interrupt not enabled, ignore it */
+            return true;
+
+        if ( value > APLIC_SOURCECFG_SM_LEVEL_LOW )
+        {
+            gdprintk(XENLOG_ERR,
+                     "value(%#x) is incorrect for sourcecfg register\n",
+                     value);
+
+            return true;
+        }
+
+        break;
+
+    case APLIC_TARGET_BASE ... APLIC_TARGET_LAST:
+    {
+        struct vaplic *vaplic = to_vaplic(currd);
+        struct vcpu *target_vcpu;
+        unsigned int guest_hart_idx = MASK_EXTR(value, APLIC_TARGET_HART_IDX);
+        /*
+         * Look at vaplic_emulate_load() for explanation why APLIC_GENMSI is
+         * subtracted.
+         */
+        unsigned int srcn = regoffset_to_word_idx(offset - APLIC_GENMSI);
+
+        if ( !AUTH_IRQ_BIT(currd, srcn) )
+            /* Interrupt not enabled, ignore it */
+            return true;
+
+        target_vcpu = domain_vcpu(currd, guest_hart_idx);
+
+        if ( !target_vcpu )
+        {
+            dprintk(XENLOG_ERR, "Invalid vCPU id in target register\n");
+
+            /* Ignore such writings */
+            return true;
+        }
+
+        if ( vaplic->regs.domaincfg & APLIC_DOMAINCFG_DM )
+        {
+            /*
+             * A non-zero guest index asks for delivery to an interrupt file of
+             * nested guest. The vIMSIC node has no riscv,guest-index-bits
+             * property, so a guest is told its harts have no guest interrupt
+             * files and the field is read-only zero for them. The write isn't
+             * rejected (that would throw away a valid hart index and EIID);
+             * instead the field is dropped, which is also what
+             * aplic_msi_target_gen() does with it when programming the h/w.
+             */
+            if ( MASK_EXTR(value, APLIC_TARGET_GUEST_IDX) )
+            {
+                printk_once(XENLOG_WARNING
+                            "%pd: vAPLIC target guest index != 0 is unsupported\n",
+                            currd);
+
Quoted 9 lines

xen/arch/riscv/include/asm/imsic.h

Quoted 4 lines
xen/arch/riscv/include/asm/imsic.h +3 -0
+                /* Ignore such writes ... */
+                return true;
+            }

Comment above this says "The write isn't rejected ... instead the field is dropped, which is also what aplic_msi_target_gen() does with it." But the code doesn't follow it as it returns true immediately here before the write occurred and without zeroing the guest index field.

You're right that the comment doesn't match the code, but the fix is in the comment rather than in the code. vaplic->regs.target[] comes from xvzalloc_array(), so the guest index field starts as zero, and every write carrying a non-zero guest index is rejected here, the field can therefore never become non-zero and there is nothing to mask out. Rejecting the whole write is deliberate: a non-zero guest index is illegal for a guest whose vIMSIC advertises no guest interrupt files.

The second half of the comment was wrong too: aplic_msi_target_gen() doesn't drop the field, it overwrites it with vcpu_guest_file_id() of the target vCPU, which is non-zero when that vCPU owns a h/w VS-file. I'll reword the comment in v3 accordingly:

/*
* A non-zero guest index asks for delivery to an interrupt file
* of a nested guest. The vIMSIC node has no riscv,guest-index-bits
* property, so a guest is told its harts have no guest interrupt
* files and the field reads as zero for them. Such a write is
* illegal and is therefore ignored as a whole: the stored copy
* keeps the zero it was allocated with, so the field never needs
* to be masked out here.
* What ends up in the h/w register is Xen's own value anyway:
* aplic_msi_target_gen() overwrites the field with
* vcpu_guest_file_id() of the target vCPU.
*/

Are you okay with that?

Thanks!

~ Oleksii

#49 lore raw

Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation

Quoted 8 lines · Oleksii Kurochko
Quoted 6 lines · Baptiste Le Duc

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 127

Quoted 5 lines
xen/arch/riscv/aplic.c +5 -0
+uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
+                              uint32_t base_val)
+{
+    unsigned int guest_id = vcpu_guest_file_id(target_vcpu);
+    unsigned long hart_field = aplic_hart_field(target_vcpu->processor);

Nit: could be const

Quoted 7 lines

Techically I agree. Then for guest_id it should const too, right?

But it seems like Xen in such cases don't use const. Have you found a rule that we have to use const in such cases?

I don't mind to put const here but then it would be nice if someone will tell me some kind of rule...

We want const on pointer targets whenever possible. We don't normally want const on plain variables, unless it needs emphasizing that a variable is to change value (which should be very rare).

Jan

#50 lore raw

Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation

In reply to Oleksii Kurochko
Quoted 461 lines

Guests running under Xen program interrupt routing by writing to APLIC MMIO registers. Xen must intercept these accesses to enforce interrupt isolation between domains and to translate guest routing intent into the underlying physical MSI topology.

Writes are gated by the domain's authorised interrupt bitmap so that a guest cannot affect interrupts it does not own. TARGET register writes additionally require translation of the hart and IMSIC guest-file indices from virtual to physical, as the APLIC uses these fields directly to compute the MSI delivery address.

Delegation (APLIC_SOURCECFG_D) is not yet supported.

xen/arch/riscv/aplic-priv.h +3 -0
index 35100d3a64..b3a1f79c5b 100644
@@ -47,4 +47,7 @@ struct aplic_priv {
  */
 extern unsigned int guest_aplic_num_sources;
 
+uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
+                              uint32_t base_val);
+
 #endif /* ASM_RISCV_APLIC_PRIV_H */
xen/arch/riscv/aplic.c +124 -4
index 3681f0669e..66ba4986a9 100644
@@ -16,6 +16,7 @@
 #include <xen/irq.h>
 #include <xen/mm.h>
 #include <xen/sections.h>
+#include <xen/sched.h>
 #include <xen/spinlock.h>
 #include <xen/types.h>
 #include <xen/vmap.h>
@@ -28,8 +29,6 @@
 #include <asm/io.h>
 #include <asm/riscv_encoding.h>
 
-#define APLIC_DEFAULT_PRIORITY  1
-
 static struct aplic_priv aplic = {
     .lock = SPIN_LOCK_UNLOCKED,
 };
@@ -38,6 +37,127 @@ static struct intc_info __ro_after_init aplic_info = {
     .hw_variant = INTC_APLIC,
 };
 
+/*
+ * The arrangement of IMSIC interrupt files in MMIO space follows a topology
+ * defined by the RISC-V AIA specification. An IMSIC group is a set of
+ * interrupt files (e.g., in a cluster or socket) co-located in memory.
+ *
+ * The physical address of an outgoing MSI is calculated by bitwise ORing a
+ * Base Physical Page Number (Base PPN) with the Group Index (g), the Hart
+ * Index (h) and, for a supervisor-level interrupt domain, the Guest Index:
+ *
+ *   ( Base PPN | (g << (HHXS + 12)) | (h << LHXS) | guest ) << 12
+ *
+ * where Base PPN, HHXS, LHXS, HHXW and LHXW come from the {m,s}msiaddrcfg[h]
+ * registers of the interrupt domain that sends the MSI:
+ *
+ * XLEN-1       HHXS+24          LHXS+12          12          0
+ * |            |                |                |           |
+ * ------------------------------------------------------------
+ * |xxxx|   g   |xxxxxxxx|   h   |xxxx|Guest Index|     0     |
+ * ------------------------------------------------------------
+ *
+ * - g: group number.
+ * - h: hart number relative to the group.
+ * - xxxx: remaining Base PPN bits; each gap may be zero-width.
+ * - Guest Index: selects one of the 4 KiB pages right above the hart's own
+ *   supervisor-level file, i.e. it starts at bit 12; LHXS must therefore be
+ *   at least as large as the number of guest index bits.
+ * - Bits 11:0: always zero because IMSIC files are 4 KiB page-aligned.
+ *
+ * For wired interrupts in MSI delivery mode (domaincfg.DM = 1) the APLIC
+ * builds that address itself from the "Hart Index" field (bits 31:18) of the
+ * corresponding target[i] register. That field holds a hart index *number*,
+ * in which both indices are packed adjacently:
+ *
+ * 13          lhxw+hhxw   lhxw       0
+ * |           |           |          |
+ * ------------------------------------
+ * |     0     |Group Index|Hart Index|
+ * ------------------------------------
+ *
+ * - lhxw (Low Hart Index Width): the number of bits used for the hart number
+ *   within a group.
+ * - hhxw (High Hart Index Width): the number of bits used for the group
+ *   number; the remaining bits of the field must be zero.
+ *
+ * The Guest Index isn't a part of it: for a supervisor-level interrupt domain
+ * it has its own field (bits 17:12) in target[i].
+ *
+ * Because there are "xxxx" gaps (Base PPN bits) between the indices in the
+ * physical address (depending on HHXS and LHXS), software must extract the
+ * group and hart components separately and pack them into the APLIC-defined
+ * Hart Index format to ensure correct MSI targeting.
+ */
+static unsigned long aplic_hart_field(unsigned int cpu)
+{
+    const struct imsic_config *imsic = imsic_get_config();
+    const struct imsic_msi *msi = &imsic->msi[cpu];
+    /* Low Hart Index Shift */
+    unsigned int lhxs = imsic->guest_index_bits;
+    /* Low Hart Index Width */
+    unsigned int lhxw = imsic->hart_index_bits;
+    /* High Hart Index Width */
+    unsigned int hhxw = imsic->group_index_bits;
+    /* High Hart Index Shift */
+    unsigned int hhxs =
+        imsic->group_index_shift - APLIC_xMSICFGADDR_PPN_SHIFT * 2;
+    /*
+     * msi->base_addr is the base of the MMIO regset this CPU's interrupt
+     * files live in, and one regset can cover several harts; msi->offset
+     * selects this CPU's block inside it. The hart index bits are part of
+     * that offset, so both indexes have to be derived from the full address.
+     */
+    paddr_t target_addr = msi->base_addr + msi->offset;
+    unsigned long tppn = target_addr >> APLIC_xMSICFGADDR_PPN_SHIFT;
+    unsigned long g =
+        (tppn >> APLIC_xMSICFGADDR_PPN_HHX_SHIFT(hhxs)) &
+        APLIC_xMSICFGADDR_PPN_HHX_MASK(hhxw);
+    unsigned long h =
+        (tppn >> APLIC_xMSICFGADDR_PPN_LHX_SHIFT(lhxs)) &
+        APLIC_xMSICFGADDR_PPN_LHX_MASK(lhxw);
+
+    return (g << lhxw) | h;
+}
+
+uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
+                              uint32_t base_val)
+{
+    unsigned int guest_id = vcpu_guest_file_id(target_vcpu);
+    unsigned long hart_field = aplic_hart_field(target_vcpu->processor);
+
+    base_val &= APLIC_TARGET_EIID;
+    base_val |= MASK_INSR(guest_id, APLIC_TARGET_GUEST_IDX);
+    base_val |= MASK_INSR(hart_field, APLIC_TARGET_HART_IDX);
+
+    return base_val;
+}
+
+uint32_t aplic_hw_read_reg(unsigned int offset)
+{
+    unsigned long flags;
+    uint32_t val;
+
+    ASSERT((offset < aplic.size) && IS_ALIGNED(offset, sizeof(uint32_t)));
+
+    spin_lock_irqsave(&aplic.lock, flags);
+    val = readl((volatile void __iomem *)aplic.regs + offset);
+    spin_unlock_irqrestore(&aplic.lock, flags);
+
+    return val;
+}
+
+void aplic_hw_write_reg(unsigned int offset, uint32_t value)
+{
+    unsigned long flags;
+
+    ASSERT((offset < aplic.size) && IS_ALIGNED(offset, sizeof(uint32_t)));
+
+    spin_lock_irqsave(&aplic.lock, flags);
+    writel(value, (volatile void __iomem *)aplic.regs + offset);
+    spin_unlock_irqrestore(&aplic.lock, flags);
+}
+
 static void __init aplic_init_hw_interrupts(void)
 {
     unsigned int i;
@@ -53,9 +173,9 @@ static void __init aplic_init_hw_interrupts(void)
         /*
          * Low bits of target register contains Interrupt Priority bits which
          * can't be zero according to AIA spec.
-         * Thereby they are initialized to APLIC_DEFAULT_PRIORITY.
+         * Thereby they are initialized to APLIC_TARGET_IPRIO_DEFAULT.
          */
-        writel(APLIC_DEFAULT_PRIORITY, &aplic.regs->target[i]);
+        writel(APLIC_TARGET_IPRIO_DEFAULT, &aplic.regs->target[i]);
     }
 
     writel(APLIC_DOMAINCFG_IE | APLIC_DOMAINCFG_DM, &aplic.regs->domaincfg);
xen/arch/riscv/include/asm/aplic.h +34 -0
index a2af55d54f..babba38607 100644
@@ -39,6 +39,13 @@
 #define  APLIC_DOMAINCFG_IE             BIT(8, U)
 #define  APLIC_DOMAINCFG_DM             BIT(2, U)
 #define  APLIC_DOMAINCFG_BE             BIT(0, U)
+/*
+ * The bits a write may change. Everything else, including the read-only zero
+ * bit 7 and the reserved bits, has to read back as zero, and BE is WARL and
+ * hardwired to 0 as Xen is little-endian only.
+ */
+#define  APLIC_DOMAINCFG_WMASK          (APLIC_DOMAINCFG_IE | \
+                                         APLIC_DOMAINCFG_DM)
 
 #define APLIC_SOURCECFG_BASE            0x0004
 #define APLIC_SOURCECFG_LAST            0x0ffc
@@ -89,6 +96,9 @@
 #define  APLIC_TARGET_GUEST_IDX         GENMASK(17, 12)
 /* Bit 11 is reserved and reads as zero */
 #define  APLIC_TARGET_EIID              GENMASK(10, 0)
+/* If target is in DM mode */
+#define  APLIC_TARGET_IPRIO             GENMASK(7, 0)
+#define   APLIC_TARGET_IPRIO_DEFAULT    1U
 
 #define APLIC_IDC_SIZE                  32
 
@@ -98,6 +108,27 @@
 #define APLIC_SIZE(nr_cpus) \
     (APLIC_MIN_SIZE + APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_cpus)))
 
+/*
+ * Using setip is fine here, as all SET* and CLR* register groups consist of 32
+ * registers and therefore have identical sizes.
+ *
+ * Lowest 2 bits are always zero for SET* and CLR* registers.
+ */
+#define APLIC_SETCLR_OFFSET_MASK \
+    (sizeof_field(struct aplic_regs, setip) - sizeof(uint32_t))
+
+#define APLIC_xMSICFGADDR_PPN_SHIFT IMSIC_MMIO_PAGE_SHIFT
+
+#define APLIC_xMSICFGADDR_PPN_HHX_MASK(hhxw) \
+    (BIT(hhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_HHX_SHIFT(hhxs) \
+    ((hhxs) + APLIC_xMSICFGADDR_PPN_SHIFT)
+
+#define APLIC_xMSICFGADDR_PPN_LHX_MASK(lhxw) \
+    (BIT(lhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_LHX_SHIFT(lhxs) \
+    (lhxs)
+
 struct aplic_regs {
     uint32_t domaincfg;         /* 0x0000 */
     uint32_t sourcecfg[1023];   /* 0x0004 */
@@ -141,4 +172,7 @@ struct aplic_regs {
     uint32_t target[1023];      /* 0x3004 */
 };
 
+uint32_t aplic_hw_read_reg(unsigned int offset);
+void aplic_hw_write_reg(unsigned int offset, uint32_t value);
+
 #endif /* ASM_RISCV_APLIC_H */
xen/arch/riscv/include/asm/imsic.h +13 -0
index 2425430ed1..93f9e44c7d 100644
@@ -40,6 +40,19 @@ struct imsic_config {
     /* Base address */
     paddr_t base_addr;
 
+    /*
+     * MSI Target Address Scheme
+     *
+     * XLEN-1       HHXS+24          LHXS+12          12          0
+     * |            |                |                |           |
+     * ------------------------------------------------------------
+     * |xxxx|   g   |xxxxxxxx|   h   |xxxx|Guest Index|     0     |
+     * ------------------------------------------------------------
+     * - g: group number.
+     * - h: hart number relative to the group.
+     * - xxxx: remaining Base PPN bits; each gap may be zero-width.
+     */
+
     /* Bits representing Guest index, HART index, and Group index */
     unsigned int guest_index_bits;
     unsigned int hart_index_bits;
xen/arch/riscv/include/asm/vaplic.h +5 -0
index 96080bfbc2..046c604915 100644
@@ -21,11 +21,16 @@ struct domain;
 
 struct vaplic_regs {
     uint32_t domaincfg;
+
+    uint32_t *target;
 };
 
 struct vaplic {
     struct vintc vintc;
     struct vaplic_regs regs;
+
+    paddr_t regs_start;
+    unsigned int regs_size;
 };
 
 int domain_vaplic_init(struct domain *d);
xen/arch/riscv/vaplic.c +148 -0
index 14f6e3164a..8726f7203d 100644
@@ -17,6 +17,7 @@
 #include <asm/aia.h>
 #include <asm/imsic.h>
 #include <asm/intc.h>
+#include <asm/mmio.h>
 #include <asm/vaplic.h>
 
 #include "aplic-priv.h"
@@ -27,6 +28,279 @@ unsigned int __ro_after_init guest_aplic_num_sources;
 
 #define FDT_VAPLIC_INT_CELLS 2
 
+#define AUTH_IRQ_BIT(d, irqn) \
+    (((irqn) < (d)->arch.vintc->nr_virqs) && \
+     test_bit(irqn, (d)->arch.vintc->used_irqs))
+
+/*
+ * Convert a byte offset (within a SETIP/CLRIP/SETIE/CLRIE register group) to
+ * a 32-bit word index into the used_irqs bitmap. Each word covers 32
+ * interrupt sources. For SOURCECFG and TARGET groups the same division also
+ * yields the interrupt number directly, because those arrays store one 32-bit
+ * register per source.
+ */
+#define regoffset_to_word_idx(reg_val) ((reg_val) / sizeof(uint32_t))
+
+static uint32_t vaplic_target_read(const struct domain *d, unsigned int irqn)
+{
+    const struct vaplic *vaplic = to_vaplic(d);
+
+    /* target[0] doesn't exist so irqn == 0 should be impossible */
+    if ( !irqn || irqn >= vaplic->vintc.nr_virqs )
+        return 0;
+
+    return read_atomic(&vaplic->regs.target[irqn]);
+}
+
+static inline uint32_t generate_auth_mask(const struct domain *currd,
+                                          unsigned int word_idx)
+{
+    unsigned int first_bit = word_idx * sizeof(uint32_t) * BITS_PER_BYTE;
+
+    if ( word_idx >= DIV_ROUND_UP(currd->arch.vintc->nr_virqs,
+                                  sizeof(uint32_t) * BITS_PER_BYTE) )
+    {
+        gdprintk(XENLOG_DEBUG, "incorrect word_idx(%u) is passed\n", word_idx);
+
+        return 0;
+    }
+
+    return currd->arch.vintc->used_irqs[first_bit / BITS_PER_LONG] >>
+           (first_bit % BITS_PER_LONG);
+}
+
+static bool vaplic_emulate_load(const struct vcpu *curr, paddr_t addr,
+                                uint32_t *out)
+{
+    const struct domain *currd = curr->domain;
+    const struct vaplic *vaplic = to_vaplic(currd);
+    const unsigned int offset = addr & APLIC_CTRL_REGION_OFFSET_MASK;
+    uint32_t auth_mask;
+    unsigned int i;
+
+    ASSERT(curr == current);
+
+    switch ( offset )
+    {
+    case APLIC_DOMAINCFG:
+        *out = vaplic->regs.domaincfg;
+
+        return true;
+
+    case APLIC_SETIPNUM:
+    case APLIC_SETIPNUM_LE:
+    case APLIC_CLRIPNUM:
+    case APLIC_SETIENUM:
+    case APLIC_CLRIENUM:
+    case APLIC_CLRIE_BASE ... APLIC_CLRIE_LAST:
+        /*
+         * Based on the RISC-V AIA spec a read of these registers
+         * always returns zero
+         */
+        *out = 0;
+
+        return true;
+
+    case APLIC_SETIP_BASE ... APLIC_SETIP_LAST:
+    case APLIC_CLRIP_BASE ... APLIC_CLRIP_LAST:
+    case APLIC_SETIE_BASE ... APLIC_SETIE_LAST:
+        i = regoffset_to_word_idx(offset & APLIC_SETCLR_OFFSET_MASK);
+        auth_mask = generate_auth_mask(currd, i);
+
+        break;
+
+    case APLIC_TARGET_BASE ... APLIC_TARGET_LAST:
+        /*
+         * As target registers start from 1:
+         *  0x3000 genmsi
+         *  0x3004 target[1]
+         *  0x3008 target[2]
+         *   ...
+         *  0x3FFC target[1023]
+         * It is necessary to calculate an interrupt number by subtracting
+         * APLIC_GENMSI instead of APLIC_TARGET_BASE.
+         */
+        i = regoffset_to_word_idx(offset - APLIC_GENMSI);
+
+        *out = AUTH_IRQ_BIT(currd, i) ? vaplic_target_read(currd, i) : 0;
+
+        return true;
+
+    default:
+        gdprintk(XENLOG_WARNING, "Unhandled APLIC read at offset %#x\n",
+                 offset);
+
+        return false;
+    }
+
+    *out = aplic_hw_read_reg(offset) & auth_mask;
+
+    return true;
+}
+
+static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
+                                 uint32_t value)
+{
+    const struct domain *currd = curr->domain;
+    unsigned int offset = addr & APLIC_CTRL_REGION_OFFSET_MASK;
+
+    ASSERT(curr == current);
+
+    switch ( offset )
+    {
+    case APLIC_SETIP_BASE ... APLIC_SETIP_LAST:
+    case APLIC_CLRIP_BASE ... APLIC_CLRIP_LAST:
+    case APLIC_SETIE_BASE ... APLIC_SETIE_LAST:
+    case APLIC_CLRIE_BASE ... APLIC_CLRIE_LAST:
+    {
+        unsigned int word_idx =
+            regoffset_to_word_idx(offset & APLIC_SETCLR_OFFSET_MASK);
+
+        value &= generate_auth_mask(currd, word_idx);
+
+        break;
+    }
+
+    case APLIC_SOURCECFG_BASE ... APLIC_SOURCECFG_LAST:
+        if ( value & APLIC_SOURCECFG_D )
+        {
+            dprintk(XENLOG_ERR, "APLIC_SOURCECFG_D isn't supported\n");
+
+            goto fail;
+        }
+
+        /*
+         * As sourcecfg register starts from 1:
+         *   0x0000 domaincfg
+         *   0x0004 sourcecfg[1]
+         *   0x0008 sourcecfg[2]
+         *    ...

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 187

Quoted 10 lines
xen/arch/riscv/vaplic.c +10 -0
+         *   0x0FFC sourcecfg[1023]
+         * It is necessary to calculate an interrupt number by subtracting
+         * APLIC_DOMAINCFG instead of APLIC_SOURCECFG_BASE.
+         */
+        if ( !AUTH_IRQ_BIT(currd,
+                           regoffset_to_word_idx(offset - APLIC_DOMAINCFG)) )
+            /* Interrupt not enabled, ignore it */
+            return true;
+
+        if ( value > APLIC_SOURCECFG_SM_LEVEL_LOW )

This compares the whole value against 7, not the extracted SM field (bits [2:0]). A perfectly legal SM=0 write with any bit set in the reserved [9:3] range (e.g. value=8) gets rejected here even though the actual field is fine Should be MASK_EXTR(value, APLIC_SOURCECFG_SM) > APLIC_SOURCECFG_SM_LEVEL_LOW.

SM is WARL. If SM invalid but other fields valid, shouldn't reject whole write. Instead override value.SM with current valid SM in this branch, so other valid fields still get written.

Quoted 45 lines
xen/arch/riscv/vaplic.c +45 -0
+        {
+            gdprintk(XENLOG_ERR,
+                     "value(%#x) is incorrect for sourcecfg register\n",
+                     value);
+
+            return true;
+        }
+
+        break;
+
+    case APLIC_TARGET_BASE ... APLIC_TARGET_LAST:
+    {
+        struct vaplic *vaplic = to_vaplic(currd);
+        struct vcpu *target_vcpu;
+        unsigned int guest_hart_idx = MASK_EXTR(value, APLIC_TARGET_HART_IDX);
+        /*
+         * Look at vaplic_emulate_load() for explanation why APLIC_GENMSI is
+         * subtracted.
+         */
+        unsigned int srcn = regoffset_to_word_idx(offset - APLIC_GENMSI);
+
+        if ( !AUTH_IRQ_BIT(currd, srcn) )
+            /* Interrupt not enabled, ignore it */
+            return true;
+
+        target_vcpu = domain_vcpu(currd, guest_hart_idx);
+
+        if ( !target_vcpu )
+        {
+            dprintk(XENLOG_ERR, "Invalid vCPU id in target register\n");
+
+            /* Ignore such writings */
+            return true;
+        }
+
+        if ( vaplic->regs.domaincfg & APLIC_DOMAINCFG_DM )
+        {
+            /*
+             * A non-zero guest index asks for delivery to an interrupt file of
+             * nested guest. The vIMSIC node has no riscv,guest-index-bits
+             * property, so a guest is told its harts have no guest interrupt
+             * files and the field is read-only zero for them. The write isn't
+             * rejected (that would throw away a valid hart index and EIID);
+             * instead the field is dropped, which is also what
+             * aplic_msi_target_gen() does with it when programming the h/w.

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 242

Quoted 10 lines
xen/arch/riscv/vaplic.c +10 -0
+             */
+            if ( MASK_EXTR(value, APLIC_TARGET_GUEST_IDX) )
+            {
+                printk_once(XENLOG_WARNING
+                            "%pd: vAPLIC target guest index != 0 is unsupported\n",
+                            currd);
+
+                /* Ignore such writes ... */
+                return true;
+            }

Comment above this says "The write isn't rejected ... instead the field is dropped, which is also what aplic_msi_target_gen() does with it." But the code doesn't follow it as it returns true immediately here before the write occurred and without zeroing the guest index field.

Quoted 34 lines
xen/arch/riscv/vaplic.c +34 -0
+
+            write_atomic(&vaplic->regs.target[srcn], value);
+
+            value = aplic_msi_target_gen(target_vcpu, value);
+        }
+        else
+        {
+            /*
+             * IPRIO is WARL and zero isn't a legal value for it, so normalize
+             * it once: the guest then reads back exactly what it gets.
+             */
+            unsigned int iprio = MASK_EXTR(value, APLIC_TARGET_IPRIO) ?:
+                                 APLIC_TARGET_IPRIO_DEFAULT;
+            unsigned long h = cpuid_to_hartid(guest_hart_idx);
+
+            value = MASK_INSR(guest_hart_idx, APLIC_TARGET_HART_IDX) |
+                    MASK_INSR(iprio, APLIC_TARGET_IPRIO);
+
+            write_atomic(&vaplic->regs.target[srcn], value);
+
+            value = MASK_INSR(h, APLIC_TARGET_HART_IDX) |
+                    MASK_INSR(iprio, APLIC_TARGET_IPRIO);
+        }
+
+        break;
+    }
+
+    case APLIC_SETIPNUM:
+    case APLIC_SETIPNUM_LE:
+    case APLIC_CLRIPNUM:
+    case APLIC_SETIENUM:
+    case APLIC_CLRIENUM:
+        if ( !value || !AUTH_IRQ_BIT(currd, value) )
+            return true;

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 286

Quoted 10 lines
xen/arch/riscv/vaplic.c +10 -0
+
+        break;
+
+    case APLIC_DOMAINCFG:
+    {
+        struct vaplic *vaplic = to_vaplic(currd);
+
+        vaplic->regs.domaincfg = APLIC_DOMAINCFG_RO |
+                                 (value & APLIC_DOMAINCFG_WMASK);
+

APLIC_DOMAINCFG_WMASK includes APLIC_DOMAINCFG_DM, so
the guest can clear DM through this write. But aplic.c:
aplic_init_hw_interrupts() sets the real hardware APLIC's domaincfg to IE|DM exactly once and never touches it again. Is this expected?

Moreover, I saw that d8fbe0bbc7's commit message claims: "a guest's domaincfg.DM reads back as a fixed one, so is there situation where we would allow direct delivery mode? If not, the else branch should be dropped.

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

Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation

Quoted 45 lines · Baptiste Le Duc
Quoted 45 lines
xen/arch/riscv/vaplic.c +45 -0
+
+static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
+                                 uint32_t value)
+{
+    const struct domain *currd = curr->domain;
+    unsigned int offset = addr & APLIC_CTRL_REGION_OFFSET_MASK;
+
+    ASSERT(curr == current);
+
+    switch ( offset )
+    {
+    case APLIC_SETIP_BASE ... APLIC_SETIP_LAST:
+    case APLIC_CLRIP_BASE ... APLIC_CLRIP_LAST:
+    case APLIC_SETIE_BASE ... APLIC_SETIE_LAST:
+    case APLIC_CLRIE_BASE ... APLIC_CLRIE_LAST:
+    {
+        unsigned int word_idx =
+            regoffset_to_word_idx(offset & APLIC_SETCLR_OFFSET_MASK);
+
+        value &= generate_auth_mask(currd, word_idx);
+
+        break;
+    }
+
+    case APLIC_SOURCECFG_BASE ... APLIC_SOURCECFG_LAST:
+        if ( value & APLIC_SOURCECFG_D )
+        {
+            dprintk(XENLOG_ERR, "APLIC_SOURCECFG_D isn't supported\n");
+
+            goto fail;
+        }
+
+        /*
+         * As sourcecfg register starts from 1:
+         *   0x0000 domaincfg
+         *   0x0004 sourcecfg[1]
+         *   0x0008 sourcecfg[2]
+         *    ...
+         *   0x0FFC sourcecfg[1023]
+         * It is necessary to calculate an interrupt number by subtracting
+         * APLIC_DOMAINCFG instead of APLIC_SOURCECFG_BASE.
+         */
+        if ( !AUTH_IRQ_BIT(currd,
+                           regoffset_to_word_idx(offset - APLIC_DOMAINCFG)) )
+            /* Interrupt not enabled, ignore it */
Quoted 8 lines

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 187

Quoted 3 lines
xen/arch/riscv/vaplic.c +3 -0
+            return true;
+
+        if ( value > APLIC_SOURCECFG_SM_LEVEL_LOW )

This compares the whole value against 7, not the extracted SM field (bits [2:0]). A perfectly legal SM=0 write with any bit set in the reserved [9:3] range (e.g. value=8) gets rejected here even though the actual field is fine Should be MASK_EXTR(value, APLIC_SOURCECFG_SM) > APLIC_SOURCECFG_SM_LEVEL_LOW.

Agree, if() written in this way is incorrect in the way what is going before this if().

I think that we don't need it at all and what we want instead is ignoring write to others bits then D (bit10) and SM(bits 2:0) as they are reserved and read as zeros.

/*
* Only D (bit 10) and SM (bits 2:0) are implemented, the rest
of the
* bits are reserved and read as zero, so ignore what a guest
writes

         * to them.
         */
        value &= (APLIC_SOURCECFG_D | APLIC_SOURCECFG_SM);

Probably it make sense to introduce and use it above:

/*
* All other bits of sourcecfg[] are reserved and read as zero, so drop
them on a write.
*/
#define APLIC_SOURCECFG_WMASK (APLIC_SOURCECFG_D | APLIC_SOURCECFG_SM)

And ...

Quoted 4 lines

SM is WARL. If SM invalid but other fields valid, shouldn't reject whole write. Instead override value.SM with current valid SM in this branch, so other valid fields still get written.

... considering that SM is WARL it means that technically any value could be written to this field but read of this register should be return always something valid. So considering that in the case of SOURCECFG we don't have a shadow copy for vAPLIC and use just real h/w we could ignore fully the value it is trying to write to SM field as even it is something illegal h/w will choose something legal instead.

If one day we will need a copy of SOURCECFG for vAPLIC we will need to do something like this to emulate behavior of real SOURCECFG:

/*
* SM is a WARL field. If the guest wrote reserved values (2 or 3),
* optionally coerce them to a supported default (e.g.,
Inactive/0).

         */
        if ( value == 2 || value == 3 )
            value = APLIC_SOURCECFG_SM_INACTIVE;

For now we can do nothing. I can put TODO:

/*
* SM is WARL, so the reserved values 0x2 and 0x3 need no handling
* here: vAPLIC keeps no shadow copy of sourcecfg[], the value is
* written straight to the h/w register and is read back from
it, so
* it is the h/w which substitutes a legal value for an illegal
one.
*
* TODO: when vAPLIC starts to shadow sourcecfg[], the WARL
behaviour
* will have to be emulated here instead, e.g.:
* if ( value == 0x2 || value == 0x3 )
* value = APLIC_SOURCECFG_SM_INACTIVE;
*/

Note that here it is okay not to use MASK_EXTR as we have always D=0 so sourcecfg[i] value is basically SM field (as other bits are reserved and are read only)

So my final suggestion is:

case APLIC_SOURCECFG_BASE ... APLIC_SOURCECFG_LAST:
+ /*

+         * Only D (bit 10) and SM (bits 2:0) are implemented, the rest of the
+         * bits are reserved and read as zero, so ignore what a guest writes
+         * to them.
+         */
+        value &= APLIC_SOURCECFG_WMASK;
+
         if ( value & APLIC_SOURCECFG_D )
         {
             dprintk(XENLOG_ERR, "APLIC_SOURCECFG_D isn't supported\n");
@@ -169,6 +176,18 @@ static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
             goto fail;
         }

+ /*

+         * SM is WARL, so the reserved values 0x2 and 0x3 need no handling
+         * here: vAPLIC keeps no shadow copy of sourcecfg[], the value is
+         * written straight to the h/w register and is read back from it, so
+         * it is the h/w which substitutes a legal value for an illegal one.
+         *
+         * TODO: when vAPLIC starts to shadow sourcecfg[], the WARL behaviour
+         * will have to be emulated here instead, e.g.:
+         *   if ( value == 0x2 || value == 0x3 )
+         *       value = APLIC_SOURCECFG_SM_INACTIVE;
+         */

+
/*
* As sourcecfg register starts from 1:
* 0x0000 domaincfg
@@ -184,15 +203,6 @@ static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,

             /* Interrupt not enabled, ignore it */
             return true;

- if ( value > APLIC_SOURCECFG_SM_LEVEL_LOW )
- {
- gdprintk(XENLOG_ERR,
- "value(%#x) is incorrect for sourcecfg register\n",
- value);
-
- return true;
- }
-

         break;

Does it make sense? Or I still missing something.

Quoted 51 lines
Quoted 51 lines
xen/arch/riscv/vaplic.c +51 -0
+        {
+            gdprintk(XENLOG_ERR,
+                     "value(%#x) is incorrect for sourcecfg register\n",
+                     value);
+
+            return true;
+        }
+
+        break;
+
+    case APLIC_TARGET_BASE ... APLIC_TARGET_LAST:
+    {
+        struct vaplic *vaplic = to_vaplic(currd);
+        struct vcpu *target_vcpu;
+        unsigned int guest_hart_idx = MASK_EXTR(value, APLIC_TARGET_HART_IDX);
+        /*
+         * Look at vaplic_emulate_load() for explanation why APLIC_GENMSI is
+         * subtracted.
+         */
+        unsigned int srcn = regoffset_to_word_idx(offset - APLIC_GENMSI);
+
+        if ( !AUTH_IRQ_BIT(currd, srcn) )
+            /* Interrupt not enabled, ignore it */
+            return true;
+
+        target_vcpu = domain_vcpu(currd, guest_hart_idx);
+
+        if ( !target_vcpu )
+        {
+            dprintk(XENLOG_ERR, "Invalid vCPU id in target register\n");
+
+            /* Ignore such writings */
+            return true;
+        }
+
+        if ( vaplic->regs.domaincfg & APLIC_DOMAINCFG_DM )
+        {
+            /*
+             * A non-zero guest index asks for delivery to an interrupt file of
+             * nested guest. The vIMSIC node has no riscv,guest-index-bits
+             * property, so a guest is told its harts have no guest interrupt
+             * files and the field is read-only zero for them. The write isn't
+             * rejected (that would throw away a valid hart index and EIID);
+             * instead the field is dropped, which is also what
+             * aplic_msi_target_gen() does with it when programming the h/w.
+             */
+            if ( MASK_EXTR(value, APLIC_TARGET_GUEST_IDX) )
+            {
+                printk_once(XENLOG_WARNING
+                            "%pd: vAPLIC target guest index != 0 is unsupported\n",
+                            currd);
Quoted 8 lines

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 242

Quoted 4 lines
xen/arch/riscv/vaplic.c +4 -0
+
+                /* Ignore such writes ... */
+                return true;
+            }

Comment above this says "The write isn't rejected ... instead the field is dropped, which is also what aplic_msi_target_gen() does with it." But the code doesn't follow it as it returns true immediately here before the write occurred and without zeroing the guest index field.

It looks like the same question in the other thread [1] at the end.

If you don't mind lets continue discussion there. I responded there.

[1] https://lore.kernel.org/xen-devel/[email protected]/T/#m0de75013bd31481a2f6abd6f36ccccb8ede87a20

Quoted 40 lines
Quoted 40 lines
xen/arch/riscv/vaplic.c +40 -0
+
+            write_atomic(&vaplic->regs.target[srcn], value);
+
+            value = aplic_msi_target_gen(target_vcpu, value);
+        }
+        else
+        {
+            /*
+             * IPRIO is WARL and zero isn't a legal value for it, so normalize
+             * it once: the guest then reads back exactly what it gets.
+             */
+            unsigned int iprio = MASK_EXTR(value, APLIC_TARGET_IPRIO) ?:
+                                 APLIC_TARGET_IPRIO_DEFAULT;
+            unsigned long h = cpuid_to_hartid(guest_hart_idx);
+
+            value = MASK_INSR(guest_hart_idx, APLIC_TARGET_HART_IDX) |
+                    MASK_INSR(iprio, APLIC_TARGET_IPRIO);
+
+            write_atomic(&vaplic->regs.target[srcn], value);
+
+            value = MASK_INSR(h, APLIC_TARGET_HART_IDX) |
+                    MASK_INSR(iprio, APLIC_TARGET_IPRIO);
+        }
+
+        break;
+    }
+
+    case APLIC_SETIPNUM:
+    case APLIC_SETIPNUM_LE:
+    case APLIC_CLRIPNUM:
+    case APLIC_SETIENUM:
+    case APLIC_CLRIENUM:
+        if ( !value || !AUTH_IRQ_BIT(currd, value) )
+            return true;
+
+        break;
+
+    case APLIC_DOMAINCFG:
+    {
+        struct vaplic *vaplic = to_vaplic(currd);
Quoted 8 lines

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 286

Quoted 4 lines
xen/arch/riscv/vaplic.c +4 -0
+
+        vaplic->regs.domaincfg = APLIC_DOMAINCFG_RO |
+                                 (value & APLIC_DOMAINCFG_WMASK);
+

APLIC_DOMAINCFG_WMASK includes APLIC_DOMAINCFG_DM, so
the guest can clear DM through this write. But aplic.c:
aplic_init_hw_interrupts() sets the real hardware APLIC's domaincfg to IE|DM exactly once and never touches it again. Is this expected?

Yes, it is expected as we are supporting now only APLIC+IMSIC in Xen and it is the reason why we here started to provided a shadow copy of domaincfg register for vAPLIC instead of using real APLIC domaincfg register.

Quoted 5 lines

Moreover, I saw that d8fbe0bbc7's commit message claims: "a guest's domaincfg.DM reads back as a fixed one, so is there situation where we would allow direct delivery mode? If not, the else branch should be dropped.

At the moment, we started with a support only when we are working in MSI mode but commonly it is possible that IMSIC will be absent and we don't have any other choice as started to support delivery mode.

Thanks for review!

~ Oleksii

#52 lore raw

Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation

In reply to Oleksii Kurochko

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 127

Quoted 5 lines · Oleksii Kurochko
xen/arch/riscv/aplic.c +5 -0
+uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
+                              uint32_t base_val)
+{
+    unsigned int guest_id = vcpu_guest_file_id(target_vcpu);
+    unsigned long hart_field = aplic_hart_field(target_vcpu->processor);

What guarantees target_vcpu's ->processor field to be meaningful at this point? (Also again naming of the parameter: Generally it wants to be "v" or "curr"; only very special cases may use other names.)

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 144

Quoted 9 lines
xen/arch/riscv/aplic.c +9 -0
+uint32_t aplic_hw_read_reg(unsigned int offset)
+{
+    unsigned long flags;
+    uint32_t val;
+
+    ASSERT((offset < aplic.size) && IS_ALIGNED(offset, sizeof(uint32_t)));
+
+    spin_lock_irqsave(&aplic.lock, flags);
+    val = readl((volatile void __iomem *)aplic.regs + offset);

Please can this have const alongside volatile?

Quoted 14 lines
xen/arch/riscv/include/asm/aplic.h +10 -0
@@ -98,6 +108,27 @@
 #define APLIC_SIZE(nr_cpus) \
     (APLIC_MIN_SIZE + APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_cpus)))
 
+/*
+ * Using setip is fine here, as all SET* and CLR* register groups consist of 32
+ * registers and therefore have identical sizes.
+ *
+ * Lowest 2 bits are always zero for SET* and CLR* registers.
+ */
+#define APLIC_SETCLR_OFFSET_MASK \
+    (sizeof_field(struct aplic_regs, setip) - sizeof(uint32_t))
+
+#define APLIC_xMSICFGADDR_PPN_SHIFT IMSIC_MMIO_PAGE_SHIFT

xen/arch/riscv/include/asm/aplic.h line 130

Quoted 10 lines
xen/arch/riscv/include/asm/aplic.h +10 -0
+
+#define APLIC_xMSICFGADDR_PPN_HHX_MASK(hhxw) \
+    (BIT(hhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_HHX_SHIFT(hhxs) \
+    ((hhxs) + APLIC_xMSICFGADDR_PPN_SHIFT)
+
+#define APLIC_xMSICFGADDR_PPN_LHX_MASK(lhxw) \
+    (BIT(lhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_LHX_SHIFT(lhxs) \
+    (lhxs)

May I ask to avoid unnecessary line splitting here as well?

xen/arch/riscv/include/asm/vaplic.h struct domain; · line 26

Quoted 9 lines
xen/arch/riscv/include/asm/vaplic.h +2 -0
@@ -21,11 +21,16 @@ struct domain;
 
 struct vaplic_regs {
     uint32_t domaincfg;
+
+    uint32_t *target;
 };

A pointer in this structure is odd, as this (supposedly) is a set of guest register values. The field name also doesn't clarify its purpose. All in all: Likely a comment is needed here.

Quoted 37 lines
xen/arch/riscv/vaplic.c +24 -0
@@ -17,6 +17,7 @@
 #include <asm/aia.h>
 #include <asm/imsic.h>
 #include <asm/intc.h>
+#include <asm/mmio.h>
 #include <asm/vaplic.h>
 
 #include "aplic-priv.h"
@@ -27,6 +28,279 @@ unsigned int __ro_after_init guest_aplic_num_sources;
 
 #define FDT_VAPLIC_INT_CELLS 2
 
+#define AUTH_IRQ_BIT(d, irqn) \
+    (((irqn) < (d)->arch.vintc->nr_virqs) && \
+     test_bit(irqn, (d)->arch.vintc->used_irqs))
+
+/*
+ * Convert a byte offset (within a SETIP/CLRIP/SETIE/CLRIE register group) to
+ * a 32-bit word index into the used_irqs bitmap. Each word covers 32
+ * interrupt sources. For SOURCECFG and TARGET groups the same division also
+ * yields the interrupt number directly, because those arrays store one 32-bit
+ * register per source.
+ */
+#define regoffset_to_word_idx(reg_val) ((reg_val) / sizeof(uint32_t))
+
+static uint32_t vaplic_target_read(const struct domain *d, unsigned int irqn)
+{
+    const struct vaplic *vaplic = to_vaplic(d);
+
+    /* target[0] doesn't exist so irqn == 0 should be impossible */
+    if ( !irqn || irqn >= vaplic->vintc.nr_virqs )
+        return 0;
+
+    return read_atomic(&vaplic->regs.target[irqn]);
+}

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 63

Quoted 10 lines
xen/arch/riscv/vaplic.c +10 -0
+
+static inline uint32_t generate_auth_mask(const struct domain *currd,
+                                          unsigned int word_idx)
+{
+    unsigned int first_bit = word_idx * sizeof(uint32_t) * BITS_PER_BYTE;
+
+    if ( word_idx >= DIV_ROUND_UP(currd->arch.vintc->nr_virqs,
+                                  sizeof(uint32_t) * BITS_PER_BYTE) )
+    {
+        gdprintk(XENLOG_DEBUG, "incorrect word_idx(%u) is passed\n", word_idx);

Along the lines of earlier remarks: What value does "is passed" add?

Quoted 17 lines
xen/arch/riscv/vaplic.c +17 -0
+static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
+                                 uint32_t value)
+{
+    const struct domain *currd = curr->domain;
+    unsigned int offset = addr & APLIC_CTRL_REGION_OFFSET_MASK;
+
+    ASSERT(curr == current);
+
+    switch ( offset )
+    {
+    case APLIC_SETIP_BASE ... APLIC_SETIP_LAST:
+    case APLIC_CLRIP_BASE ... APLIC_CLRIP_LAST:
+    case APLIC_SETIE_BASE ... APLIC_SETIE_LAST:
+    case APLIC_CLRIE_BASE ... APLIC_CLRIE_LAST:
+    {
+        unsigned int word_idx =
+            regoffset_to_word_idx(offset & APLIC_SETCLR_OFFSET_MASK);

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 167

Quoted 10 lines
xen/arch/riscv/vaplic.c +10 -0
+
+        value &= generate_auth_mask(currd, word_idx);
+
+        break;
+    }
+
+    case APLIC_SOURCECFG_BASE ... APLIC_SOURCECFG_LAST:
+        if ( value & APLIC_SOURCECFG_D )
+        {
+            dprintk(XENLOG_ERR, "APLIC_SOURCECFG_D isn't supported\n");

gdprintk()?

Quoted 23 lines
xen/arch/riscv/vaplic.c +23 -0
+            goto fail;
+        }
+
+        /*
+         * As sourcecfg register starts from 1:
+         *   0x0000 domaincfg
+         *   0x0004 sourcecfg[1]
+         *   0x0008 sourcecfg[2]
+         *    ...
+         *   0x0FFC sourcecfg[1023]
+         * It is necessary to calculate an interrupt number by subtracting
+         * APLIC_DOMAINCFG instead of APLIC_SOURCECFG_BASE.
+         */
+        if ( !AUTH_IRQ_BIT(currd,
+                           regoffset_to_word_idx(offset - APLIC_DOMAINCFG)) )
+            /* Interrupt not enabled, ignore it */
+            return true;
+
+        if ( value > APLIC_SOURCECFG_SM_LEVEL_LOW )
+        {
+            gdprintk(XENLOG_ERR,
+                     "value(%#x) is incorrect for sourcecfg register\n",
+                     value);

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 201

Quoted 10 lines
xen/arch/riscv/vaplic.c +10 -0
+
+            return true;
+        }
+
+        break;
+
+    case APLIC_TARGET_BASE ... APLIC_TARGET_LAST:
+    {
+        struct vaplic *vaplic = to_vaplic(currd);
+        struct vcpu *target_vcpu;

This, btw, is a case where I think not using "v" is warranted.

Quoted 42 lines
xen/arch/riscv/vaplic.c +42 -0
+        unsigned int guest_hart_idx = MASK_EXTR(value, APLIC_TARGET_HART_IDX);
+        /*
+         * Look at vaplic_emulate_load() for explanation why APLIC_GENMSI is
+         * subtracted.
+         */
+        unsigned int srcn = regoffset_to_word_idx(offset - APLIC_GENMSI);
+
+        if ( !AUTH_IRQ_BIT(currd, srcn) )
+            /* Interrupt not enabled, ignore it */
+            return true;
+
+        target_vcpu = domain_vcpu(currd, guest_hart_idx);
+
+        if ( !target_vcpu )
+        {
+            dprintk(XENLOG_ERR, "Invalid vCPU id in target register\n");
+
+            /* Ignore such writings */
+            return true;
+        }
+
+        if ( vaplic->regs.domaincfg & APLIC_DOMAINCFG_DM )
+        {
+            /*
+             * A non-zero guest index asks for delivery to an interrupt file of
+             * nested guest. The vIMSIC node has no riscv,guest-index-bits
+             * property, so a guest is told its harts have no guest interrupt
+             * files and the field is read-only zero for them. The write isn't
+             * rejected (that would throw away a valid hart index and EIID);
+             * instead the field is dropped, which is also what
+             * aplic_msi_target_gen() does with it when programming the h/w.
+             */
+            if ( MASK_EXTR(value, APLIC_TARGET_GUEST_IDX) )
+            {
+                printk_once(XENLOG_WARNING
+                            "%pd: vAPLIC target guest index != 0 is unsupported\n",
+                            currd);
+
+                /* Ignore such writes ... */
+                return true;
+            }
+

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 253

Quoted 10 lines
xen/arch/riscv/vaplic.c +10 -0
+            write_atomic(&vaplic->regs.target[srcn], value);
+
+            value = aplic_msi_target_gen(target_vcpu, value);
+        }
+        else
+        {
+            /*
+             * IPRIO is WARL and zero isn't a legal value for it, so normalize
+             * it once: the guest then reads back exactly what it gets.
+             */

What is "reads back exactly what it gets" supposed to express? The use of "once" there also isn't quite clear to me.

Quoted 25 lines
xen/arch/riscv/vaplic.c +25 -0
+            unsigned int iprio = MASK_EXTR(value, APLIC_TARGET_IPRIO) ?:
+                                 APLIC_TARGET_IPRIO_DEFAULT;
+            unsigned long h = cpuid_to_hartid(guest_hart_idx);
+
+            value = MASK_INSR(guest_hart_idx, APLIC_TARGET_HART_IDX) |
+                    MASK_INSR(iprio, APLIC_TARGET_IPRIO);
+
+            write_atomic(&vaplic->regs.target[srcn], value);
+
+            value = MASK_INSR(h, APLIC_TARGET_HART_IDX) |
+                    MASK_INSR(iprio, APLIC_TARGET_IPRIO);
+        }
+
+        break;
+    }
+
+    case APLIC_SETIPNUM:
+    case APLIC_SETIPNUM_LE:
+    case APLIC_CLRIPNUM:
+    case APLIC_SETIENUM:
+    case APLIC_CLRIENUM:
+        if ( !value || !AUTH_IRQ_BIT(currd, value) )
+            return true;
+
+        break;

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 288

Quoted 10 lines
xen/arch/riscv/vaplic.c +10 -0
+
+    case APLIC_DOMAINCFG:
+    {
+        struct vaplic *vaplic = to_vaplic(currd);
+
+        vaplic->regs.domaincfg = APLIC_DOMAINCFG_RO |
+                                 (value & APLIC_DOMAINCFG_WMASK);
+
+        return true;
+    }

May I suggest that you arrange case blocks (primarily) by offset? This would then mean for DOMAINCFG handling to move to the top, helping at least a little with SOURCECFG_{BASE,LAST} handling (slightly oddly) using APLIC_DOMAINCFG.

Quoted 16 lines
xen/arch/riscv/vaplic.c +11 -1
@@ -122,7 +447,29 @@ int domain_vaplic_init(struct domain *d)
      */
     d->arch.vintc->nr_virqs = guest_aplic_num_sources + 1;
 
-    return 0;
+    /* Slot 0 is unused: APLIC source numbering starts at 1 (see used_irqs). */
+    vaplic->regs.target = xvzalloc_array(uint32_t, d->arch.vintc->nr_virqs);
+    if ( !vaplic->regs.target )
+    {
+        d->arch.vintc = NULL;
+        xvfree(vaplic);
+
+        return -ENOMEM;
+    }
+
+    vaplic->regs_start = GUEST_APLIC_S_BASE;

xen/arch/riscv/vaplic.c int domain_vaplic_init(struct domain *d) · line 470

Quoted 10 lines
xen/arch/riscv/vaplic.c +10 -0
+    vaplic->regs_size = APLIC_SIZE(d->max_vcpus);
+
+    rc = register_mmio_handler(d, &vaplic_mmio_ops,
+                               vaplic->regs_start, vaplic->regs_size);
+    if ( rc )
+    {
+        d->arch.vintc = NULL;
+        xvfree(vaplic->regs.target);
+        xvfree(vaplic);
+    }

Could you perhaps arrange for it to be possible to simply call domain_vaplic_deinit() here (and maybe also on at least some of the earlier error paths)? The code above loks very similar to ...

xen/arch/riscv/vaplic.c void domain_vaplic_deinit(struct domain *d) · line 486

Quoted 7 lines
xen/arch/riscv/vaplic.c +1 -0
@@ -134,5 +481,6 @@ void domain_vaplic_deinit(struct domain *d)
 
     vaplic = to_vaplic(d);
     d->arch.vintc = NULL;
+    xvfree(vaplic->regs.target);
     xvfree(vaplic);
 }

... what's here.

Jan

#53 lore raw

Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation

Quoted 9 lines · Jan Beulich

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 127

Quoted 5 lines · Oleksii Kurochko
xen/arch/riscv/aplic.c +5 -0
+uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
+                              uint32_t base_val)
+{
+    unsigned int guest_id = vcpu_guest_file_id(target_vcpu);
+    unsigned long hart_field = aplic_hart_field(target_vcpu->processor);

What guarantees target_vcpu's ->processor field to be meaningful at this point?

Good question. Considering the places where it is called, I would expect target_vcpu->processor to have something meaningful, since it is called from a place that can only be reached when the guest is running.

Even without that, I don't think there is a big issue here, as ->processor is initialized to 0 at allocation time. This means that the target register will be configured in such a way that CPU 0 will handle such IRQs.

Quoted 2 lines

(Also again naming of the parameter: Generally it wants to be "v" or "curr"; only very special cases may use other names.)

I will use just v then here.

Quoted 12 lines

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 144

Quoted 10 lines
xen/arch/riscv/aplic.c +9 -0
+uint32_t aplic_hw_read_reg(unsigned int offset)
+{
+    unsigned long flags;
+    uint32_t val;
+
+    ASSERT((offset < aplic.size) && IS_ALIGNED(offset, sizeof(uint32_t)));
+
+    spin_lock_irqsave(&aplic.lock, flags);
+    val = readl((volatile void __iomem *)aplic.regs + offset);

Please can this have const alongside volatile?

Sure, I will add.

Quoted 19 lines
Quoted 19 lines
xen/arch/riscv/include/asm/aplic.h +14 -0
@@ -98,6 +108,27 @@
  #define APLIC_SIZE(nr_cpus) \
      (APLIC_MIN_SIZE + APLIC_SIZE_ALIGN(APLIC_IDC_SIZE * (nr_cpus)))
 
+/*
+ * Using setip is fine here, as all SET* and CLR* register groups consist of 32
+ * registers and therefore have identical sizes.
+ *
+ * Lowest 2 bits are always zero for SET* and CLR* registers.
+ */
+#define APLIC_SETCLR_OFFSET_MASK \
+    (sizeof_field(struct aplic_regs, setip) - sizeof(uint32_t))
+
+#define APLIC_xMSICFGADDR_PPN_SHIFT IMSIC_MMIO_PAGE_SHIFT
+
+#define APLIC_xMSICFGADDR_PPN_HHX_MASK(hhxw) \
+    (BIT(hhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_HHX_SHIFT(hhxs) \
Quoted 8 lines

xen/arch/riscv/include/asm/aplic.h line 130

Quoted 6 lines
xen/arch/riscv/include/asm/aplic.h +6 -0
+    ((hhxs) + APLIC_xMSICFGADDR_PPN_SHIFT)
+
+#define APLIC_xMSICFGADDR_PPN_LHX_MASK(lhxw) \
+    (BIT(lhxw, UL) - 1)
+#define APLIC_xMSICFGADDR_PPN_LHX_SHIFT(lhxs) \
+    (lhxs)

May I ask to avoid unnecessary line splitting here as well?

I will fix that for APLIC_xMSICFGADDR_PPN_HHX_MASK, APLIC_xMSICFGADDR_PPN_LHX_MASK and APLIC_xMSICFGADDR_PPN_LHX_SHIFT.

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/include/asm/vaplic.h +0 -0
@@ -21,11 +21,16 @@ struct domain;
 
Quoted 9 lines

xen/arch/riscv/include/asm/vaplic.h struct domain; · line 26

Quoted 5 lines
xen/arch/riscv/include/asm/vaplic.h +2 -0
  struct vaplic_regs {
      uint32_t domaincfg;
+
+    uint32_t *target;
  };

A pointer in this structure is odd, as this (supposedly) is a set of guest register values. The field name also doesn't clarify its purpose. All in all: Likely a comment is needed here.

It is a pointer because I tried to save some memory and allocate register target based on how many irqs a guest really needed.

As an option I can allocate that statically and use the value from AIA
spec: target[1]-target[1023]. Would it better?

If a dynamic allocation is still fine then I will add the following comment:

/*
* Guest's view of the APLIC target registers, indexed by IRQ number. *
* The array holds d->arch.vintc->nr_virqs elements; target[0] is
unused

     * as APLIC interrupt sources start from 1.
     */
    uint32_t *target;
Quoted 42 lines
Quoted 42 lines
xen/arch/riscv/vaplic.c +28 -0
@@ -17,6 +17,7 @@
  #include <asm/aia.h>
  #include <asm/imsic.h>
  #include <asm/intc.h>
+#include <asm/mmio.h>
  #include <asm/vaplic.h>
 
  #include "aplic-priv.h"
@@ -27,6 +28,279 @@ unsigned int __ro_after_init guest_aplic_num_sources;
 
  #define FDT_VAPLIC_INT_CELLS 2
 
+#define AUTH_IRQ_BIT(d, irqn) \
+    (((irqn) < (d)->arch.vintc->nr_virqs) && \
+     test_bit(irqn, (d)->arch.vintc->used_irqs))
+
+/*
+ * Convert a byte offset (within a SETIP/CLRIP/SETIE/CLRIE register group) to
+ * a 32-bit word index into the used_irqs bitmap. Each word covers 32
+ * interrupt sources. For SOURCECFG and TARGET groups the same division also
+ * yields the interrupt number directly, because those arrays store one 32-bit
+ * register per source.
+ */
+#define regoffset_to_word_idx(reg_val) ((reg_val) / sizeof(uint32_t))
+
+static uint32_t vaplic_target_read(const struct domain *d, unsigned int irqn)
+{
+    const struct vaplic *vaplic = to_vaplic(d);
+
+    /* target[0] doesn't exist so irqn == 0 should be impossible */
+    if ( !irqn || irqn >= vaplic->vintc.nr_virqs )
+        return 0;
+
+    return read_atomic(&vaplic->regs.target[irqn]);
+}
+
+static inline uint32_t generate_auth_mask(const struct domain *currd,
+                                          unsigned int word_idx)
+{
Quoted 8 lines

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 63

Quoted 6 lines
xen/arch/riscv/vaplic.c +6 -0
+    unsigned int first_bit = word_idx * sizeof(uint32_t) * BITS_PER_BYTE;
+
+    if ( word_idx >= DIV_ROUND_UP(currd->arch.vintc->nr_virqs,
+                                  sizeof(uint32_t) * BITS_PER_BYTE) )
+    {
+        gdprintk(XENLOG_DEBUG, "incorrect word_idx(%u) is passed\n", word_idx);

Along the lines of earlier remarks: What value does "is passed" add?

Probably not too much sense. I will drop it.

Quoted 22 lines
Quoted 22 lines
xen/arch/riscv/vaplic.c +21 -0
+static bool vaplic_emulate_store(const struct vcpu *curr, paddr_t addr,
+                                 uint32_t value)
+{
+    const struct domain *currd = curr->domain;
+    unsigned int offset = addr & APLIC_CTRL_REGION_OFFSET_MASK;
+
+    ASSERT(curr == current);
+
+    switch ( offset )
+    {
+    case APLIC_SETIP_BASE ... APLIC_SETIP_LAST:
+    case APLIC_CLRIP_BASE ... APLIC_CLRIP_LAST:
+    case APLIC_SETIE_BASE ... APLIC_SETIE_LAST:
+    case APLIC_CLRIE_BASE ... APLIC_CLRIE_LAST:
+    {
+        unsigned int word_idx =
+            regoffset_to_word_idx(offset & APLIC_SETCLR_OFFSET_MASK);
+
+        value &= generate_auth_mask(currd, word_idx);
+
+        break;
Quoted 8 lines

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 167

Quoted 6 lines
xen/arch/riscv/vaplic.c +6 -0
+    }
+
+    case APLIC_SOURCECFG_BASE ... APLIC_SOURCECFG_LAST:
+        if ( value & APLIC_SOURCECFG_D )
+        {
+            dprintk(XENLOG_ERR, "APLIC_SOURCECFG_D isn't supported\n");

gdprintk()?

Agree, it would be better to be gdprintk() here.

Quoted 84 lines
Quoted 24 lines
xen/arch/riscv/vaplic.c +23 -0
+            goto fail;
+        }
+
+        /*
+         * As sourcecfg register starts from 1:
+         *   0x0000 domaincfg
+         *   0x0004 sourcecfg[1]
+         *   0x0008 sourcecfg[2]
+         *    ...
+         *   0x0FFC sourcecfg[1023]
+         * It is necessary to calculate an interrupt number by subtracting
+         * APLIC_DOMAINCFG instead of APLIC_SOURCECFG_BASE.
+         */
+        if ( !AUTH_IRQ_BIT(currd,
+                           regoffset_to_word_idx(offset - APLIC_DOMAINCFG)) )
+            /* Interrupt not enabled, ignore it */
+            return true;
+
+        if ( value > APLIC_SOURCECFG_SM_LEVEL_LOW )
+        {
+            gdprintk(XENLOG_ERR,
+                     "value(%#x) is incorrect for sourcecfg register\n",
+                     value);

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 201

Quoted 10 lines
xen/arch/riscv/vaplic.c +10 -0
+
+            return true;
+        }
+
+        break;
+
+    case APLIC_TARGET_BASE ... APLIC_TARGET_LAST:
+    {
+        struct vaplic *vaplic = to_vaplic(currd);
+        struct vcpu *target_vcpu;

This, btw, is a case where I think not using "v" is warranted.

Quoted 47 lines
xen/arch/riscv/vaplic.c +47 -0
+        unsigned int guest_hart_idx = MASK_EXTR(value, APLIC_TARGET_HART_IDX);
+        /*
+         * Look at vaplic_emulate_load() for explanation why APLIC_GENMSI is
+         * subtracted.
+         */
+        unsigned int srcn = regoffset_to_word_idx(offset - APLIC_GENMSI);
+
+        if ( !AUTH_IRQ_BIT(currd, srcn) )
+            /* Interrupt not enabled, ignore it */
+            return true;
+
+        target_vcpu = domain_vcpu(currd, guest_hart_idx);
+
+        if ( !target_vcpu )
+        {
+            dprintk(XENLOG_ERR, "Invalid vCPU id in target register\n");
+
+            /* Ignore such writings */
+            return true;
+        }
+
+        if ( vaplic->regs.domaincfg & APLIC_DOMAINCFG_DM )
+        {
+            /*
+             * A non-zero guest index asks for delivery to an interrupt file of
+             * nested guest. The vIMSIC node has no riscv,guest-index-bits
+             * property, so a guest is told its harts have no guest interrupt
+             * files and the field is read-only zero for them. The write isn't
+             * rejected (that would throw away a valid hart index and EIID);
+             * instead the field is dropped, which is also what
+             * aplic_msi_target_gen() does with it when programming the h/w.
+             */
+            if ( MASK_EXTR(value, APLIC_TARGET_GUEST_IDX) )
+            {
+                printk_once(XENLOG_WARNING
+                            "%pd: vAPLIC target guest index != 0 is unsupported\n",
+                            currd);
+
+                /* Ignore such writes ... */
+                return true;
+            }
+
+            write_atomic(&vaplic->regs.target[srcn], value);
+
+            value = aplic_msi_target_gen(target_vcpu, value);
+        }
+        else
Quoted 8 lines

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 253

Quoted 5 lines
xen/arch/riscv/vaplic.c +5 -0
+        {
+            /*
+             * IPRIO is WARL and zero isn't a legal value for it, so normalize
+             * it once: the guest then reads back exactly what it gets.
+             */

What is "reads back exactly what it gets" supposed to express? The use of "once" there also isn't quite clear to me.

"once" meant the substitution is done in a single place (before the value is stored) so nothing has to be adjusted again on the read path; "reads back exactly what it gets" meant the shadow copy holds the same legal priority that is programmed into the hardware, not the zero the guest wrote.

I will re-word the comment to:

/*
* IPRIO is WARL and zero isn't a legal value for it, so a write
* of zero is replaced by APLIC_TARGET_IPRIO_DEFAULT. This is done
* before the value is stored, so the guest-visible copy and what
* is programmed into the h/w hold the same legal priority and no
* fix-up is needed when the guest reads the register back. */

Quoted 32 lines
Quoted 32 lines
xen/arch/riscv/vaplic.c +31 -0
+            unsigned int iprio = MASK_EXTR(value, APLIC_TARGET_IPRIO) ?:
+                                 APLIC_TARGET_IPRIO_DEFAULT;
+            unsigned long h = cpuid_to_hartid(guest_hart_idx);
+
+            value = MASK_INSR(guest_hart_idx, APLIC_TARGET_HART_IDX) |
+                    MASK_INSR(iprio, APLIC_TARGET_IPRIO);
+
+            write_atomic(&vaplic->regs.target[srcn], value);
+
+            value = MASK_INSR(h, APLIC_TARGET_HART_IDX) |
+                    MASK_INSR(iprio, APLIC_TARGET_IPRIO);
+        }
+
+        break;
+    }
+
+    case APLIC_SETIPNUM:
+    case APLIC_SETIPNUM_LE:
+    case APLIC_CLRIPNUM:
+    case APLIC_SETIENUM:
+    case APLIC_CLRIENUM:
+        if ( !value || !AUTH_IRQ_BIT(currd, value) )
+            return true;
+
+        break;
+
+    case APLIC_DOMAINCFG:
+    {
+        struct vaplic *vaplic = to_vaplic(currd);
+
+        vaplic->regs.domaincfg = APLIC_DOMAINCFG_RO |
Quoted 8 lines

xen/arch/riscv/vaplic.c unsigned int __ro_after_init guest_aplic_num_sources; · line 288

Quoted 4 lines
xen/arch/riscv/vaplic.c +4 -0
+                                 (value & APLIC_DOMAINCFG_WMASK);
+
+        return true;
+    }

May I suggest that you arrange case blocks (primarily) by offset? This would then mean for DOMAINCFG handling to move to the top, helping at least a little with SOURCECFG_{BASE,LAST} handling (slightly oddly) using APLIC_DOMAINCFG.

I will do that.

Quoted 34 lines
Quoted 17 lines
xen/arch/riscv/vaplic.c +11 -1
@@ -122,7 +447,29 @@ int domain_vaplic_init(struct domain *d)
       */
      d->arch.vintc->nr_virqs = guest_aplic_num_sources + 1;
 
-    return 0;
+    /* Slot 0 is unused: APLIC source numbering starts at 1 (see used_irqs). */
+    vaplic->regs.target = xvzalloc_array(uint32_t, d->arch.vintc->nr_virqs);
+    if ( !vaplic->regs.target )
+    {
+        d->arch.vintc = NULL;
+        xvfree(vaplic);
+
+        return -ENOMEM;
+    }
+
+    vaplic->regs_start = GUEST_APLIC_S_BASE;

xen/arch/riscv/vaplic.c int domain_vaplic_init(struct domain *d) · line 470

Quoted 10 lines
xen/arch/riscv/vaplic.c +10 -0
+    vaplic->regs_size = APLIC_SIZE(d->max_vcpus);
+
+    rc = register_mmio_handler(d, &vaplic_mmio_ops,
+                               vaplic->regs_start, vaplic->regs_size);
+    if ( rc )
+    {
+        d->arch.vintc = NULL;
+        xvfree(vaplic->regs.target);
+        xvfree(vaplic);
+    }

Could you perhaps arrange for it to be possible to simply call domain_vaplic_deinit() here (and maybe also on at least some of the earlier error paths)? The code above loks very similar to ...

Quoted 2 lines
xen/arch/riscv/vaplic.c +0 -0
@@ -134,5 +481,6 @@ void domain_vaplic_deinit(struct domain *d)
 
Quoted 7 lines

xen/arch/riscv/vaplic.c void domain_vaplic_deinit(struct domain *d) · line 486

Quoted 5 lines
xen/arch/riscv/vaplic.c +1 -0
      vaplic = to_vaplic(d);
      d->arch.vintc = NULL;
+    xvfree(vaplic->regs.target);
      xvfree(vaplic);
  }

... what's here.

Agree, domain_vaplic_deinit() could be used instead of open-coding when recieved rc is handled from register_mmio_handler() and error path above.

Thanks!

~ Oleksii

#54 lore raw

Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation

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

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 127

Quoted 5 lines · Oleksii Kurochko
xen/arch/riscv/aplic.c +5 -0
+uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
+                              uint32_t base_val)
+{
+    unsigned int guest_id = vcpu_guest_file_id(target_vcpu);
+    unsigned long hart_field = aplic_hart_field(target_vcpu->processor);

What guarantees target_vcpu's ->processor field to be meaningful at this point?

Quoted 8 lines

Good question. Considering the places where it is called, I would expect target_vcpu->processor to have something meaningful, since it is called from a place that can only be reached when the guest is running.

Even without that, I don't think there is a big issue here, as ->processor is initialized to 0 at allocation time. This means that the target register will be configured in such a way that CPU 0 will handle such IRQs.

I may not have been explicit enough then: Whether the guest (as a whole) is running is of no interest. If the specific vCPU is running, all is fine. If the specific vCPU is in the process of being moved to a different CPU, and if you read ->processor just before the new value is put there, is all going to be fine as well? I doubt that.

Quoted 14 lines
Quoted 4 lines
Quoted 4 lines
xen/arch/riscv/include/asm/vaplic.h +0 -0
@@ -21,11 +21,16 @@ struct domain;
 
Quoted 9 lines

xen/arch/riscv/include/asm/vaplic.h struct domain; · line 26

Quoted 5 lines
xen/arch/riscv/include/asm/vaplic.h +2 -0
  struct vaplic_regs {
      uint32_t domaincfg;
+
+    uint32_t *target;
  };

A pointer in this structure is odd, as this (supposedly) is a set of guest register values. The field name also doesn't clarify its purpose. All in all: Likely a comment is needed here.

Quoted 5 lines

It is a pointer because I tried to save some memory and allocate register target based on how many irqs a guest really needed.

As an option I can allocate that statically and use the value from AIA
spec: target[1]-target[1023]. Would it better?

No, I think dynamic allocation is justified here. (Question is whether it should be struct vaplic_regs as a whole, but that depends on whether another runtime-sized array may need adding to it later on.)

Jan

#55 lore raw

Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation

Quoted 21 lines · Jan Beulich
Quoted 11 lines · Oleksii Kurochko
Quoted 9 lines · Jan Beulich

xen/arch/riscv/aplic.c static struct intc_info __ro_after_init aplic_info = { · line 127

Quoted 5 lines · Oleksii Kurochko
xen/arch/riscv/aplic.c +5 -0
+uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,
+                              uint32_t base_val)
+{
+    unsigned int guest_id = vcpu_guest_file_id(target_vcpu);
+    unsigned long hart_field = aplic_hart_field(target_vcpu->processor);

What guarantees target_vcpu's ->processor field to be meaningful at this point?

Quoted 8 lines

Good question. Considering the places where it is called, I would expect target_vcpu->processor to have something meaningful, since it is called from a place that can only be reached when the guest is running.

Even without that, I don't think there is a big issue here, as ->processor is initialized to 0 at allocation time. This means that the target register will be configured in such a way that CPU 0 will handle such IRQs.

Quoted 6 lines

I may not have been explicit enough then: Whether the guest (as a whole) is running is of no interest. If the specific vCPU is running, all is fine. If the specific vCPU is in the process of being moved to a different CPU, and if you read ->processor just before the new value is put there, is all going to be fine as well? I doubt that.

You're right, and it's worse than a stale CPU number: v->processor is updated by the scheduler (sched_unit_migrate_finish()) before sched_move_irqs() -> imsic_migrate_vcpu() moves the interrupt file, so a concurrent vAPLIC TARGET write can combine the new CPU with the old guest file index (an MSI into someone else's file, which aplic_reconfigure_target(), which is introduced later in this patch series, won't catch), or compute a correct old target but write it after aplic_reconfigure_target() (the function which is called during migration to re-target irqs to new pCPU) has already scanned.

In v3 I'll (a) stop using ->processor and take the (guest_file_id, vsfile_cpu) pair, which imsic_update_state() updates atomically under vsfile_lock, and (b) do the snapshot plus the h/w TARGET write under aplic.lock, which aplic_reconfigure_target() also holds. As imsic_update_state() completes before aplic_reconfigure_target() (also that could be checked in this patch series and is introduced a little bit later. Probably I have to re-order some patches again) takes the lock, the emulated write either happens before the scan (and gets fixed up, or skipped as already correct) or after it (and sees the new location).

Any better option I have now?

~ Oleksii

#56 lore raw

Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation

On Thu, Sep 10, 2026 at 04:24:06PM +0200, Oleksii Kurochko wrote:
[...]

Quoted 11 lines

In v3 I'll (a) stop using ->processor and take the (guest_file_id, vsfile_cpu) pair, which imsic_update_state() updates atomically under vsfile_lock, and (b) do the snapshot plus the h/w TARGET write under aplic.lock, which aplic_reconfigure_target() also holds. As imsic_update_state() completes before aplic_reconfigure_target() (also that could be checked in this patch series and is introduced a little bit later. Probably I have to re-order some patches again) takes the lock, the emulated write either happens before the scan (and gets fixed up, or skipped as already correct) or after it (and sees the new location).

Any better option I have now?

Unless I am missing something, the snapshot also needs to handle the case where the target vCPU has not been attached yet:
vcpu_guest_file_id() returns zero until the vCPU has gone through imsic_vsfile_attach(), i.e. until it is scheduled for the first time, and vsfile_cpu is NR_CPUS until then.

With the current code, a write targeting such a vCPU makes aplic_msi_target_gen() program Guest Index 0 into the physical APLIC target register. According to AIA section 4.5.16, Guest Index 0 selects the hart's supervisor-level interrupt file rather than a VS-level guest interrupt file. Could this cause the MSI to be delivered to Xen's own interrupt file with the EIID supplied by the guest?

I also could not find where such a target would be updated once the VS-file is attached. imsic_migrate_vcpu() reprograms the relevant targets during migration, but the initial imsic_vsfile_attach() path does not appear to replay targets which were written before the attachment.

Whether a write targeting an unattached vCPU should be supported seems like a separate question. Independently of that choice, would it make sense to avoid programming the physical TARGET register while guest_file_id is zero? The virtual target could either be rejected, or retained in the shadow target[] and programmed once the VS-file is attached.

Thanks,
SeungJu

#57 lore raw

Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation

Quoted 33 lines · SeungJu Cheon

On Thu, Sep 10, 2026 at 04:24:06PM +0200, Oleksii Kurochko wrote:
[...]

Quoted 11 lines

In v3 I'll (a) stop using ->processor and take the (guest_file_id, vsfile_cpu) pair, which imsic_update_state() updates atomically under vsfile_lock, and (b) do the snapshot plus the h/w TARGET write under aplic.lock, which aplic_reconfigure_target() also holds. As imsic_update_state() completes before aplic_reconfigure_target() (also that could be checked in this patch series and is introduced a little bit later. Probably I have to re-order some patches again) takes the lock, the emulated write either happens before the scan (and gets fixed up, or skipped as already correct) or after it (and sees the new location).

Any better option I have now?

Unless I am missing something, the snapshot also needs to handle the case where the target vCPU has not been attached yet:
vcpu_guest_file_id() returns zero until the vCPU has gone through imsic_vsfile_attach(), i.e. until it is scheduled for the first time, and vsfile_cpu is NR_CPUS until then.

With the current code, a write targeting such a vCPU makes aplic_msi_target_gen() program Guest Index 0 into the physical APLIC target register. According to AIA section 4.5.16, Guest Index 0 selects the hart's supervisor-level interrupt file rather than a VS-level guest interrupt file. Could this cause the MSI to be delivered to Xen's own interrupt file with the EIID supplied by the guest?

I also could not find where such a target would be updated once the VS-file is attached. imsic_migrate_vcpu() reprograms the relevant targets during migration, but the initial imsic_vsfile_attach() path does not appear to replay targets which were written before the attachment.

Quoted 6 lines

Whether a write targeting an unattached vCPU should be supported seems like a separate question. Independently of that choice, would it make sense to avoid programming the physical TARGET register while guest_file_id is zero? The virtual target could either be rejected, or retained in the shadow target[] and programmed once the VS-file is attached.

If the target vCPU hasn't attached yet it means that continue_to_new_vcpu() for it wasn't called so it will be rejected by target register emulated code:

...
target_vcpu = domain_vcpu(currd, guest_hart_idx);

if ( !target_vcpu )
{
gdprintk(XENLOG_ERR, "Invalid vCPU id in target
register\n");

                /* Ignore such writings */
                return true;
            }

...

(probably we should back to this question in v3 of this patch as several things were updated and some of your concerns mentioned here looks to me not really possible)

Thanks.

~ Oleksii

#58 lore raw

PATCH v2 10/39 xen/riscv: build the target hart index via aplic_hart_field()

In reply to Oleksii Kurochko

aplic_set_irq_affinity() open-coded the packing of the group and hart indices into the target register, and got two things wrong along the way:

- imsic_config.msi[] is indexed by logical CPU id, but the index was run through cpuid_to_hartid() first. On any platform where the two spaces differ this picks another CPU's interrupt file, or reads past the array;

- the same hart id was then used verbatim as the low hart index, and the group index was derived from msi[].base_addr alone. The hart index bits live in msi[].offset, the base address only covers the MMIO regset, which may hold the files of several harts. Both indices have to come out of base_addr + offset.

aplic_hart_field() already extracts them that way, and is what the vAPLIC target path uses, so call it here as well and insert the result with MASK_INSR(APLIC_TARGET_HART_IDX) instead of a bare shift, which keeps the value from spilling out of the 14-bit field. This also drops the last in-tree duplicate of the AIA hart index formula. So drop defintion of APLIC_TARGET_HART_IDX_SHIFT.

No functional change on a single-group platform whose hart ids match their CPU ids and whose IMSIC regset holds one file per hart.

Fixes d4676a1398bc ("xen/riscv: implementation of aplic and imsic operations")

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

---
 xen/arch/riscv/aplic.c             | 30 ++++++------------------------
 xen/arch/riscv/include/asm/aplic.h |  1 -
 2 files changed, 6 insertions(+), 25 deletions(-)
xen/arch/riscv/aplic.c +6 -24
index 66ba4986a9ff..319a954f6f3c 100644
@@ -325,9 +325,7 @@ static unsigned int aplic_get_cpu_from_mask(const cpumask_t *cpumask)
 static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask_t *mask)
 {
     unsigned int cpu;
-    uint64_t group_index, base_ppn;
-    uint32_t hhxw, lhxw, hhxs, value;
-    const struct imsic_config *imsic = aplic.imsic_cfg;
+    uint32_t value;
 
     /*
      * TODO: Currently, APLIC is supported only with MSI interrupts.
@@ -340,27 +338,11 @@ static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask
 
     ASSERT(spin_is_locked(&desc->lock));
 
-    cpu = cpuid_to_hartid(aplic_get_cpu_from_mask(mask));
-    hhxw = imsic->group_index_bits;
-    lhxw = imsic->hart_index_bits;
-    /*
-     * Although this variable is used only once in the calculation of
-     * group_index, and it might seem that hhxs could be defined as:
-     *   hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT;
-     * and then the addition of IMSIC_MMIO_PAGE_SHIFT could be omitted
-     * when calculating the group index.
-     * It was done intentionally this way to follow the formula from
-     * the AIA specification for calculating the MSI address.
-     */
-    hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT * 2;
-    base_ppn = imsic->msi[cpu].base_addr >> IMSIC_MMIO_PAGE_SHIFT;
-
-    /* Update hart and EEID in the target register */
-    group_index = (base_ppn >> (hhxs + IMSIC_MMIO_PAGE_SHIFT)) &
-                  (BIT(hhxw, UL) - 1);
-    value = desc->irq;
-    value |= cpu << APLIC_TARGET_HART_IDX_SHIFT;
-    value |= group_index << (lhxw + APLIC_TARGET_HART_IDX_SHIFT);
+    cpu = aplic_get_cpu_from_mask(mask);
+
+    /* Update hart index and EIID in the target register */
+    value = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+            (desc->irq & APLIC_TARGET_EIID);
 
     spin_lock(&aplic.lock);
 
xen/arch/riscv/include/asm/aplic.h +0 -1
index babba386071f..d629e1c83887 100644
@@ -92,7 +92,6 @@
 #define APLIC_TARGET_BASE               0x3004
 #define APLIC_TARGET_LAST               0x3ffc
 #define  APLIC_TARGET_HART_IDX          GENMASK(31, 18)
-#define  APLIC_TARGET_HART_IDX_SHIFT    18
 #define  APLIC_TARGET_GUEST_IDX         GENMASK(17, 12)
 /* Bit 11 is reserved and reads as zero */
 #define  APLIC_TARGET_EIID              GENMASK(10, 0)
Signature · 1 line
2.55.0
Reviewed-by on v2 10/39
#59 lore raw

Re: [PATCH v2 10/39] xen/riscv: build the target hart index via aplic_hart_field()

Quoted 10 lines · Oleksii Kurochko

aplic_set_irq_affinity() open-coded the packing of the group and hart indices into the target register, and got two things wrong along the way:

- imsic_config.msi[] is indexed by logical CPU id, but the index was run through cpuid_to_hartid() first. On any platform where the two spaces differ this picks another CPU's interrupt file, or reads past the array;

[...]

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

Re: [PATCH v2 10/39] xen/riscv: build the target hart index via aplic_hart_field()

Quoted 5 lines · Baptiste Le Duc
Quoted 4 lines · Oleksii Kurochko

aplic_set_irq_affinity() open-coded the packing of the group and hart indices into the target register, and got two things wrong along the way:

Quoted 9 lines
Quoted 6 lines

- imsic_config.msi[] is indexed by logical CPU id, but the index was run through cpuid_to_hartid() first. On any platform where the two spaces differ this picks another CPU's interrupt file, or reads past the array;

[...]

Thanks.

Considering your suggestion regarding renaming of the function aplic_hart_field() in the prev. patches. I will also do here:

@ -344 +344 @@ static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask

-    value = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+    value = MASK_INSR(aplic_hart_index(cpu), APLIC_TARGET_HART_IDX) |

+

Update the functions name in the commit message.

~ Oleksii

Acked-by
#61 lore raw

Re: [PATCH v2 10/39] xen/riscv: build the target hart index via aplic_hart_field()

In reply to Baptiste Le Duc
Quoted 5 lines · Baptiste Le Duc
Quoted 4 lines · Oleksii Kurochko

aplic_set_irq_affinity() open-coded the packing of the group and hart indices into the target register, and got two things wrong along the way:

Quoted 8 lines
Quoted 6 lines

- imsic_config.msi[] is indexed by logical CPU id, but the index was run through cpuid_to_hartid() first. On any platform where the two spaces differ this picks another CPU's interrupt file, or reads past the array;

[...]

I'm puzzled by this being unconditional, considering the naming comment you gave on patch 09. With the (aiui now agreed upon) renaming:

Jan

#62 lore raw

Re: [PATCH v2 10/39] xen/riscv: build the target hart index via aplic_hart_field()

In reply to Oleksii Kurochko
Quoted 13 lines · Oleksii Kurochko
xen/arch/riscv/aplic.c +0 -9
@@ -340,27 +338,11 @@ static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask
 
     ASSERT(spin_is_locked(&desc->lock));
 
-    cpu = cpuid_to_hartid(aplic_get_cpu_from_mask(mask));
-    hhxw = imsic->group_index_bits;
-    lhxw = imsic->hart_index_bits;
-    /*
-     * Although this variable is used only once in the calculation of
-     * group_index, and it might seem that hhxs could be defined as:
-     *   hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT;
-     * and then the addition of IMSIC_MMIO_PAGE_SHIFT could be omitted
-     * when calculating the group index.

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 361

Quoted 10 lines
xen/arch/riscv/aplic.c +0 -10
-     * It was done intentionally this way to follow the formula from
-     * the AIA specification for calculating the MSI address.
-     */
-    hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT * 2;
-    base_ppn = imsic->msi[cpu].base_addr >> IMSIC_MMIO_PAGE_SHIFT;
-
-    /* Update hart and EEID in the target register */
-    group_index = (base_ppn >> (hhxs + IMSIC_MMIO_PAGE_SHIFT)) &
-                  (BIT(hhxw, UL) - 1);
-    value = desc->irq;

Hmm, only after sending the ack I noticed that there's no masking here, ...

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 345

Quoted 7 lines
xen/arch/riscv/aplic.c +5 -2
-    value |= cpu << APLIC_TARGET_HART_IDX_SHIFT;
-    value |= group_index << (lhxw + APLIC_TARGET_HART_IDX_SHIFT);
+    cpu = aplic_get_cpu_from_mask(mask);
+
+    /* Update hart index and EIID in the target register */
+    value = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+            (desc->irq & APLIC_TARGET_EIID);

... but there is masking here. Chopping off bits doesn't look as if it can lead to anything good. What's the deal here?

Jan

#63 lore raw

Re: [PATCH v2 10/39] xen/riscv: build the target hart index via aplic_hart_field()

Quoted 35 lines · Jan Beulich
Quoted 13 lines · Oleksii Kurochko
xen/arch/riscv/aplic.c +0 -9
@@ -340,27 +338,11 @@ static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask
 
      ASSERT(spin_is_locked(&desc->lock));
 
-    cpu = cpuid_to_hartid(aplic_get_cpu_from_mask(mask));
-    hhxw = imsic->group_index_bits;
-    lhxw = imsic->hart_index_bits;
-    /*
-     * Although this variable is used only once in the calculation of
-     * group_index, and it might seem that hhxs could be defined as:
-     *   hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT;
-     * and then the addition of IMSIC_MMIO_PAGE_SHIFT could be omitted
-     * when calculating the group index.

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 361

Quoted 10 lines
xen/arch/riscv/aplic.c +0 -10
-     * It was done intentionally this way to follow the formula from
-     * the AIA specification for calculating the MSI address.
-     */
-    hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT * 2;
-    base_ppn = imsic->msi[cpu].base_addr >> IMSIC_MMIO_PAGE_SHIFT;
-
-    /* Update hart and EEID in the target register */
-    group_index = (base_ppn >> (hhxs + IMSIC_MMIO_PAGE_SHIFT)) &
-                  (BIT(hhxw, UL) - 1);
-    value = desc->irq;

Hmm, only after sending the ack I noticed that there's no masking here, ...

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 345

Quoted 7 lines
xen/arch/riscv/aplic.c +5 -2
-    value |= cpu << APLIC_TARGET_HART_IDX_SHIFT;
-    value |= group_index << (lhxw + APLIC_TARGET_HART_IDX_SHIFT);
+    cpu = aplic_get_cpu_from_mask(mask);
+
+    /* Update hart index and EIID in the target register */
+    value = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+            (desc->irq & APLIC_TARGET_EIID);
Quoted 2 lines

... but there is masking here. Chopping off bits doesn't look as if it can lead to anything good. What's the deal here?

The mask is a no-op: desc->irq < NR_IRQS (1024) always fits the 11-bit EIID field, so I'll drop it and add a BUILD_BUG_ON() instead.

Would it be better to:

+ /* desc->irq < NR_IRQS, so it always fits the EIID field */
+ BUILD_BUG_ON(NR_IRQS - 1 > APLIC_TARGET_EIID);
+
+ value = MASK_INSR(aplic_hart_index(cpu), APLIC_TARGET_HART_IDX) | desc->irq;

?

Thanks.

~ Oleksii

#64 lore raw

Re: [PATCH v2 10/39] xen/riscv: build the target hart index via aplic_hart_field()

Quoted 44 lines · Oleksii Kurochko
Quoted 35 lines · Jan Beulich
Quoted 13 lines · Oleksii Kurochko
xen/arch/riscv/aplic.c +0 -9
@@ -340,27 +338,11 @@ static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask
 
      ASSERT(spin_is_locked(&desc->lock));
 
-    cpu = cpuid_to_hartid(aplic_get_cpu_from_mask(mask));
-    hhxw = imsic->group_index_bits;
-    lhxw = imsic->hart_index_bits;
-    /*
-     * Although this variable is used only once in the calculation of
-     * group_index, and it might seem that hhxs could be defined as:
-     *   hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT;
-     * and then the addition of IMSIC_MMIO_PAGE_SHIFT could be omitted
-     * when calculating the group index.

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 361

Quoted 10 lines
xen/arch/riscv/aplic.c +0 -10
-     * It was done intentionally this way to follow the formula from
-     * the AIA specification for calculating the MSI address.
-     */
-    hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT * 2;
-    base_ppn = imsic->msi[cpu].base_addr >> IMSIC_MMIO_PAGE_SHIFT;
-
-    /* Update hart and EEID in the target register */
-    group_index = (base_ppn >> (hhxs + IMSIC_MMIO_PAGE_SHIFT)) &
-                  (BIT(hhxw, UL) - 1);
-    value = desc->irq;

Hmm, only after sending the ack I noticed that there's no masking here, ...

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 345

Quoted 7 lines
xen/arch/riscv/aplic.c +5 -2
-    value |= cpu << APLIC_TARGET_HART_IDX_SHIFT;
-    value |= group_index << (lhxw + APLIC_TARGET_HART_IDX_SHIFT);
+    cpu = aplic_get_cpu_from_mask(mask);
+
+    /* Update hart index and EIID in the target register */
+    value = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+            (desc->irq & APLIC_TARGET_EIID);
Quoted 2 lines

... but there is masking here. Chopping off bits doesn't look as if it can lead to anything good. What's the deal here?

The mask is a no-op: desc->irq < NR_IRQS (1024) always fits the 11-bit EIID field, so I'll drop it and add a BUILD_BUG_ON() instead.

Would it be better to:

Review

Quoted 2 lines
(quoted diff) +2 -0
+    /* desc->irq < NR_IRQS, so it always fits the EIID field */
+    BUILD_BUG_ON(NR_IRQS - 1 > APLIC_TARGET_EIID);

If the question is whether to prefer BUILD_BUG_ON() over BUG_ON(), then:
Yes please. However, APLIC_TARGET_EIID is a mask (despite its name not indicating that), which only happens to start at bit 0. This kind of assumption would better be avoided.

This raises another question though: No matter how big a RISC-V system is, it can only ever have 1k IRQs? How does that work with a single MSI-X device having up to 2k MSIs?

Jan

Jan

#65 lore raw

Re: [PATCH v2 10/39] xen/riscv: build the target hart index via aplic_hart_field()

In reply to Oleksii Kurochko
Quoted 44 lines · Oleksii Kurochko
Quoted 35 lines · Jan Beulich
Quoted 13 lines · Oleksii Kurochko
xen/arch/riscv/aplic.c +0 -9
@@ -340,27 +338,11 @@ static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask
 
      ASSERT(spin_is_locked(&desc->lock));
 
-    cpu = cpuid_to_hartid(aplic_get_cpu_from_mask(mask));
-    hhxw = imsic->group_index_bits;
-    lhxw = imsic->hart_index_bits;
-    /*
-     * Although this variable is used only once in the calculation of
-     * group_index, and it might seem that hhxs could be defined as:
-     *   hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT;
-     * and then the addition of IMSIC_MMIO_PAGE_SHIFT could be omitted
-     * when calculating the group index.

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 361

Quoted 10 lines
xen/arch/riscv/aplic.c +0 -10
-     * It was done intentionally this way to follow the formula from
-     * the AIA specification for calculating the MSI address.
-     */
-    hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT * 2;
-    base_ppn = imsic->msi[cpu].base_addr >> IMSIC_MMIO_PAGE_SHIFT;
-
-    /* Update hart and EEID in the target register */
-    group_index = (base_ppn >> (hhxs + IMSIC_MMIO_PAGE_SHIFT)) &
-                  (BIT(hhxw, UL) - 1);
-    value = desc->irq;

Hmm, only after sending the ack I noticed that there's no masking here, ...

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 345

Quoted 7 lines
xen/arch/riscv/aplic.c +5 -2
-    value |= cpu << APLIC_TARGET_HART_IDX_SHIFT;
-    value |= group_index << (lhxw + APLIC_TARGET_HART_IDX_SHIFT);
+    cpu = aplic_get_cpu_from_mask(mask);
+
+    /* Update hart index and EIID in the target register */
+    value = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+            (desc->irq & APLIC_TARGET_EIID);
Quoted 2 lines

... but there is masking here. Chopping off bits doesn't look as if it can lead to anything good. What's the deal here?

The mask is a no-op: desc->irq < NR_IRQS (1024) always fits the 11-bit EIID field, so I'll drop it and add a BUILD_BUG_ON() instead.

Would it be better to:

Review

Quoted 2 lines
(quoted diff) +2 -0
+    /* desc->irq < NR_IRQS, so it always fits the EIID field */
+    BUILD_BUG_ON(NR_IRQS - 1 > APLIC_TARGET_EIID);

If the question is whether to prefer BUILD_BUG_ON() over BUG_ON(), then:
Yes please. However, APLIC_TARGET_EIID is a mask (despite its name not indicating that), which only happens to start at bit 0. This kind of assumption would better be avoided.

This raises another question though: No matter how big a RISC-V system is, it can only ever have 1k IRQs? How does that work with a single MSI-X device having up to 2k MSIs?

Jan

Jan

#66 lore raw

Re: [PATCH v2 10/39] xen/riscv: build the target hart index via aplic_hart_field()

Quoted 45 lines · Jan Beulich
Quoted 44 lines · Oleksii Kurochko
Quoted 35 lines · Jan Beulich
Quoted 13 lines · Oleksii Kurochko
xen/arch/riscv/aplic.c +0 -9
@@ -340,27 +338,11 @@ static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask
 
       ASSERT(spin_is_locked(&desc->lock));
 
-    cpu = cpuid_to_hartid(aplic_get_cpu_from_mask(mask));
-    hhxw = imsic->group_index_bits;
-    lhxw = imsic->hart_index_bits;
-    /*
-     * Although this variable is used only once in the calculation of
-     * group_index, and it might seem that hhxs could be defined as:
-     *   hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT;
-     * and then the addition of IMSIC_MMIO_PAGE_SHIFT could be omitted
-     * when calculating the group index.

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 361

Quoted 10 lines
xen/arch/riscv/aplic.c +0 -10
-     * It was done intentionally this way to follow the formula from
-     * the AIA specification for calculating the MSI address.
-     */
-    hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT * 2;
-    base_ppn = imsic->msi[cpu].base_addr >> IMSIC_MMIO_PAGE_SHIFT;
-
-    /* Update hart and EEID in the target register */
-    group_index = (base_ppn >> (hhxs + IMSIC_MMIO_PAGE_SHIFT)) &
-                  (BIT(hhxw, UL) - 1);
-    value = desc->irq;

Hmm, only after sending the ack I noticed that there's no masking here, ...

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 345

Quoted 7 lines
xen/arch/riscv/aplic.c +5 -2
-    value |= cpu << APLIC_TARGET_HART_IDX_SHIFT;
-    value |= group_index << (lhxw + APLIC_TARGET_HART_IDX_SHIFT);
+    cpu = aplic_get_cpu_from_mask(mask);
+
+    /* Update hart index and EIID in the target register */
+    value = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+            (desc->irq & APLIC_TARGET_EIID);
Quoted 2 lines

... but there is masking here. Chopping off bits doesn't look as if it can lead to anything good. What's the deal here?

The mask is a no-op: desc->irq < NR_IRQS (1024) always fits the 11-bit EIID field, so I'll drop it and add a BUILD_BUG_ON() instead.

Would it be better to:

Quoted 7 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+    /* desc->irq < NR_IRQS, so it always fits the EIID field */
+    BUILD_BUG_ON(NR_IRQS - 1 > APLIC_TARGET_EIID);

If the question is whether to prefer BUILD_BUG_ON() over BUG_ON(), then:
Yes please. However, APLIC_TARGET_EIID is a mask (despite its name not indicating that), which only happens to start at bit 0. This kind of assumption would better be avoided.

Then BUILD_BUG_on should be updated to:

/* desc->irq < NR_IRQS, so it always fits the EIID field */

    BUILD_BUG_ON(NR_IRQS - 1 > MASK_EXTR(~0U, APLIC_TARGET_EIID));
Quoted 4 lines

This raises another question though: No matter how big a RISC-V system is, it can only ever have 1k IRQs? How does that work with a single MSI-X device having up to 2k MSIs?

Device MSIs never pass through the APLIC. They are written straight into an IMSIC interrupt file. The ID space belongs to each file, so each hart has up to 2047 IDs (IMSIC_MAX_ID).

1k it is limitation for wired interrupts (which could be delivered in MSI mode where APLIC + IMSIC is needed) which are going through APLIC.

~ Oleksii

#67 lore raw

Re: [PATCH v2 10/39] xen/riscv: build the target hart index via aplic_hart_field()

Quoted 67 lines · Oleksii Kurochko
Quoted 45 lines · Jan Beulich
Quoted 44 lines · Oleksii Kurochko
Quoted 35 lines · Jan Beulich
Quoted 13 lines · Oleksii Kurochko
xen/arch/riscv/aplic.c +0 -9
@@ -340,27 +338,11 @@ static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask
 
       ASSERT(spin_is_locked(&desc->lock));
 
-    cpu = cpuid_to_hartid(aplic_get_cpu_from_mask(mask));
-    hhxw = imsic->group_index_bits;
-    lhxw = imsic->hart_index_bits;
-    /*
-     * Although this variable is used only once in the calculation of
-     * group_index, and it might seem that hhxs could be defined as:
-     *   hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT;
-     * and then the addition of IMSIC_MMIO_PAGE_SHIFT could be omitted
-     * when calculating the group index.

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 361

Quoted 10 lines
xen/arch/riscv/aplic.c +0 -10
-     * It was done intentionally this way to follow the formula from
-     * the AIA specification for calculating the MSI address.
-     */
-    hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT * 2;
-    base_ppn = imsic->msi[cpu].base_addr >> IMSIC_MMIO_PAGE_SHIFT;
-
-    /* Update hart and EEID in the target register */
-    group_index = (base_ppn >> (hhxs + IMSIC_MMIO_PAGE_SHIFT)) &
-                  (BIT(hhxw, UL) - 1);
-    value = desc->irq;

Hmm, only after sending the ack I noticed that there's no masking here, ...

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 345

Quoted 7 lines
xen/arch/riscv/aplic.c +5 -2
-    value |= cpu << APLIC_TARGET_HART_IDX_SHIFT;
-    value |= group_index << (lhxw + APLIC_TARGET_HART_IDX_SHIFT);
+    cpu = aplic_get_cpu_from_mask(mask);
+
+    /* Update hart index and EIID in the target register */
+    value = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+            (desc->irq & APLIC_TARGET_EIID);
Quoted 2 lines

... but there is masking here. Chopping off bits doesn't look as if it can lead to anything good. What's the deal here?

The mask is a no-op: desc->irq < NR_IRQS (1024) always fits the 11-bit EIID field, so I'll drop it and add a BUILD_BUG_ON() instead.

Would it be better to:

Quoted 7 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+    /* desc->irq < NR_IRQS, so it always fits the EIID field */
+    BUILD_BUG_ON(NR_IRQS - 1 > APLIC_TARGET_EIID);

If the question is whether to prefer BUILD_BUG_ON() over BUG_ON(), then:
Yes please. However, APLIC_TARGET_EIID is a mask (despite its name not indicating that), which only happens to start at bit 0. This kind of assumption would better be avoided.

Then BUILD_BUG_on should be updated to:

  /* desc->irq < NR_IRQS, so it always fits the EIID field */
     BUILD_BUG_ON(NR_IRQS - 1 > MASK_EXTR(~0U, APLIC_TARGET_EIID));
Quoted 4 lines

This raises another question though: No matter how big a RISC-V system is, it can only ever have 1k IRQs? How does that work with a single MSI-X device having up to 2k MSIs?

Quoted 6 lines

Device MSIs never pass through the APLIC. They are written straight into an IMSIC interrupt file. The ID space belongs to each file, so each hart has up to 2047 IDs (IMSIC_MAX_ID).

1k it is limitation for wired interrupts (which could be delivered in MSI mode where APLIC + IMSIC is needed) which are going through APLIC.

But desc->irq and NR_IRQS have to represent both. Which then puts the BUILD_BUG_ON() above under question.

Jan

#68 lore raw

Re: [PATCH v2 10/39] xen/riscv: build the target hart index via aplic_hart_field()

Quoted 60 lines · Jan Beulich
Quoted 59 lines · Oleksii Kurochko
Quoted 40 lines · Jan Beulich
Quoted 39 lines · Oleksii Kurochko
Quoted 33 lines · Jan Beulich
Quoted 13 lines · Oleksii Kurochko
xen/arch/riscv/aplic.c +0 -9
@@ -340,27 +338,11 @@ static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask
 
        ASSERT(spin_is_locked(&desc->lock));
 
-    cpu = cpuid_to_hartid(aplic_get_cpu_from_mask(mask));
-    hhxw = imsic->group_index_bits;
-    lhxw = imsic->hart_index_bits;
-    /*
-     * Although this variable is used only once in the calculation of
-     * group_index, and it might seem that hhxs could be defined as:
-     *   hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT;
-     * and then the addition of IMSIC_MMIO_PAGE_SHIFT could be omitted
-     * when calculating the group index.

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 361

Quoted 10 lines
xen/arch/riscv/aplic.c +0 -10
-     * It was done intentionally this way to follow the formula from
-     * the AIA specification for calculating the MSI address.
-     */
-    hhxs = imsic->group_index_shift - IMSIC_MMIO_PAGE_SHIFT * 2;
-    base_ppn = imsic->msi[cpu].base_addr >> IMSIC_MMIO_PAGE_SHIFT;
-
-    /* Update hart and EEID in the target register */
-    group_index = (base_ppn >> (hhxs + IMSIC_MMIO_PAGE_SHIFT)) &
-                  (BIT(hhxw, UL) - 1);
-    value = desc->irq;

Hmm, only after sending the ack I noticed that there's no masking here, ...

xen/arch/riscv/aplic.c static void cf_check aplic_set_irq_affinity(struct irq_desc *desc, const cpumask · line 345

Quoted 7 lines
xen/arch/riscv/aplic.c +5 -2
-    value |= cpu << APLIC_TARGET_HART_IDX_SHIFT;
-    value |= group_index << (lhxw + APLIC_TARGET_HART_IDX_SHIFT);
+    cpu = aplic_get_cpu_from_mask(mask);
+
+    /* Update hart index and EIID in the target register */
+    value = MASK_INSR(aplic_hart_field(cpu), APLIC_TARGET_HART_IDX) |
+            (desc->irq & APLIC_TARGET_EIID);
Quoted 2 lines

... but there is masking here. Chopping off bits doesn't look as if it can lead to anything good. What's the deal here?

The mask is a no-op: desc->irq < NR_IRQS (1024) always fits the 11-bit EIID field, so I'll drop it and add a BUILD_BUG_ON() instead.

Quoted 8 lines

Review

Quoted 4 lines

Would it be better to:

(quoted diff) +2 -0
+    /* desc->irq < NR_IRQS, so it always fits the EIID field */
+    BUILD_BUG_ON(NR_IRQS - 1 > APLIC_TARGET_EIID);

If the question is whether to prefer BUILD_BUG_ON() over BUG_ON(), then:
Yes please. However, APLIC_TARGET_EIID is a mask (despite its name not indicating that), which only happens to start at bit 0. This kind of assumption would better be avoided.

Then BUILD_BUG_on should be updated to:

   /* desc->irq < NR_IRQS, so it always fits the EIID field */
      BUILD_BUG_ON(NR_IRQS - 1 > MASK_EXTR(~0U, APLIC_TARGET_EIID));
Quoted 3 lines

This raises another question though: No matter how big a RISC-V system is, it can only ever have 1k IRQs? How does that work with a single MSI-X device having up to 2k MSIs?

Quoted 8 lines
Quoted 6 lines

Device MSIs never pass through the APLIC. They are written straight into an IMSIC interrupt file. The ID space belongs to each file, so each hart has up to 2047 IDs (IMSIC_MAX_ID).

1k it is limitation for wired interrupts (which could be delivered in MSI mode where APLIC + IMSIC is needed) which are going through APLIC.

But desc->irq and NR_IRQS have to represent both. Which then puts the BUILD_BUG_ON() above under question.

Agreed. Right now desc->irq, the APLIC source number and the IMSIC EIID are all the same number: aplic_set_irq_affinity() writes desc->irq into EIID, and aplic_handle_interrupt() hands the IMSIC identity from stopei straight to do_IRQ(). That only works because there's no MSI support on RISC-V yet, so NR_IRQS covers wired interrupts only.

Once device MSIs are supported, that identity mapping can't stay anyway. IMSIC IDs are per interrupt file and shared between wired and MSI interrupts, so we'll need to allocate EIIDs and map desc->irq to (hart, EIID). target[] will then get the allocated EIID rather than desc->irq, and NR_IRQS will grow beyond 1024.

So for this patch I'll tie the check to the APLIC source range instead of NR_IRQS:

BUILD_BUG_ON(ARRAY_SIZE(aplic.regs->target) >

             MASK_EXTR(~0U, APLIC_TARGET_EIID));

ASSERT(desc->irq && desc->irq <= aplic_info.num_irqs);

The ASSERT also covers the target[desc->irq - 1] indexing.

~ Oleksii

#69 lore raw

PATCH v2 11/39 xen/riscv: add helper to check APLIC MSI mode

In reply to Oleksii Kurochko

Use convient helper instead of open-coding the things.

---
Changes in v2:
- Rename helper.
- Update the commit message.
---

---
 xen/arch/riscv/aplic.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
xen/arch/riscv/aplic.c +7 -2
index 319a954f6f3c..b4c419755ac3 100644
@@ -37,6 +37,11 @@ static struct intc_info __ro_after_init aplic_info = {
     .hw_variant = INTC_APLIC,
 };
 
+static bool aplic_msi_mode(void)
+{
+    return readl(&aplic.regs->domaincfg) & APLIC_DOMAINCFG_DM;
+}
+
 /*
  * The arrangement of IMSIC interrupt files in MMIO space follows a topology
  * defined by the RISC-V AIA specification. An IMSIC group is a set of
@@ -250,7 +255,7 @@ static void cf_check aplic_irq_enable(struct irq_desc *desc)
      *       If APLIC without MSI interrupts is required in the future,
      *       this function will need to be updated accordingly.
      */
-    ASSERT(readl(&aplic.regs->domaincfg) & APLIC_DOMAINCFG_DM);
+    ASSERT(aplic_msi_mode());
 
     ASSERT(spin_is_locked(&desc->lock));
 
@@ -281,7 +286,7 @@ static void cf_check aplic_irq_disable(struct irq_desc *desc)
      *       If APLIC without MSI interrupts is required in the future,
      *       this function will need to be updated accordingly.
      */
-    ASSERT(readl(&aplic.regs->domaincfg) & APLIC_DOMAINCFG_DM);
+    ASSERT(aplic_msi_mode());
 
     ASSERT(spin_is_locked(&desc->lock));
 
Signature · 1 line
2.55.0
#72 lore raw

PATCH v2 12/39 xen/riscv: implement vCPU context switching

In reply to Oleksii Kurochko

Implement context_switch() and the helpers it needs: save/restore of H/VS CSRs, virtual timer and P2M context, and __context_switch() in assembly, which switches Xen's own callee-saved state (and thereby the stack) from prev to next. Virtual interrupt controller context switch will be introduced later.

Add offsets of struct arch_vcpu's xen_saved_context to asm-offsets.c for use by __context_switch().

henvcfg and htimedelta are 64-bit on both RV32 and RV64, so store them as uint64_t and use csr_{read,write}64() instead of open-coding accesses to the high halves.

A hart which drops out of a domain's dirty_cpumask stops being a target of p2m_tlb_flush() while its TLB may still hold G-stage translations of that domain, and neither the vCPU which just ran nor any other vCPU of that domain which ran there earlier has had its VMID invalidated. Move the hart to a new VMID generation at that point: a VMID number is never re-used until a full local flush has happened, hence none of those translations can be reached again.

Claim the VMID in p2m_ctxt_switch_to() rather than at the next guest entry. VMIDs are a per-hart resource, so the (generation, vmid) pair a migrating vCPU brings from another hart is meaningless here and may even match this hart's current generation, leaving the vCPU under a VMID owned by another domain. ctxt_switch_to() invalidates that pair, but claiming a replacement only on guest entry is too late: p2m_ctxt_switch_to() has by then already made HGATP live, and speculation can populate G-stage entries of the incoming domain under the stale VMID. The local flush for a wrapped generation moves along with the claim.

That leaves p2m_handle_vmenter() with nothing to do, so drop it together with its call from check_for_pcpu_work(). A VMID can only be invalidated while its vCPU isn't running: vmid_flush_vcpu() is called for the vCPU being switched in, and vmid_flush_hart() runs either from schedule_tail(), ahead of ctxt_switch_to(), or from the wrap path of vmid_handle_vmenter() itself. A P2M change on another hart doesn't invalidate it either, as p2m_tlb_flush() drops the stale entries directly with sbi_remote_hfence_gvma() instead of retiring the VMIDs which tag them. A guest therefore always runs under the VMID claimed on its way in, and there is nothing left for a guest entry hook to notice.

p2m_handle_vmenter() also skipped the HGATP write when the VMID it claimed was unchanged. That isn't carried over: HGATP holds the G-stage root as well, and skipping the write is only correct where that root is already the incoming domain's. On the guest entry path it is, on the context switch path it is not.

While at it, fix the inclusion order of headers in asm-offsets.c: Xen's headers go first, then arch specific ones.

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

---
 xen/arch/riscv/domain.c              | 167 +++++++++++++++++++++++++++
 xen/arch/riscv/entry.S               |  44 +++++++
 xen/arch/riscv/include/asm/domain.h  |  16 ++-
 xen/arch/riscv/include/asm/p2m.h     |   1 -
 xen/arch/riscv/include/asm/system.h  |   4 +
 xen/arch/riscv/p2m.c                 |  57 ++-------
 xen/arch/riscv/riscv64/asm-offsets.c |  19 ++-
 xen/arch/riscv/stubs.c               |   5 -
 xen/arch/riscv/traps.c               |   2 -
 9 files changed, 258 insertions(+), 57 deletions(-)
xen/arch/riscv/domain.c +167 -0
index ec327a5e8a23..91a46d630f44 100644
@@ -11,9 +11,11 @@
 #include <asm/bitops.h>
 #include <asm/cpufeature.h>
 #include <asm/csr.h>
+#include <asm/current.h>
 #include <asm/intc.h>
 #include <asm/mmio.h>
 #include <asm/riscv_encoding.h>
+#include <asm/vmid.h>
 #include <asm/vtimer.h>
 
 struct csr_masks {
@@ -158,6 +160,8 @@ int arch_vcpu_create(struct vcpu *v)
     if ( is_idle_vcpu(v) )
         return 0;
 
+    v->arch.last_cpu = NR_CPUS;
+
     vcpu_csr_init(v);
 
     if ( (rc = vcpu_vtimer_init(v)) )
@@ -329,6 +333,169 @@ int arch_domain_create(struct domain *d,
     return rc;
 }
 
+static void save_csr_regs(struct vcpu *vcpu)
+{
+    /*
+     * There is no need to save these CSRs as only hypervisor writes them in
+     * restore_csr_regs() and guest can't access them so they shouldn't be
+     * stored here. Keep them commented here just for symmetry with the
+     * restore CSRs register part.
+     *
+     * vcpu->arch.hedeleg = csr_read(CSR_HEDELEG);
+     * vcpu->arch.hideleg = csr_read(CSR_HIDELEG);
+     * vcpu->arch.henvcfg = csr_read64(CSR_HENVCFG);
+     * vcpu->arch.hcounteren = csr_read(CSR_HCOUNTEREN);
+     * vcpu->arch.htimedelta = csr_read64(CSR_HTIMEDELTA);
+     *
+     * if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+     *     vcpu->arch.hstateen0 = csr_read(CSR_HSTATEEN0);
+     */
+
+    vcpu->arch.hvip = csr_read(CSR_HVIP);
+
+    vcpu->arch.vsstatus = csr_read(CSR_VSSTATUS);
+    vcpu->arch.vsie = csr_read(CSR_VSIE);
+    vcpu->arch.vstvec = csr_read(CSR_VSTVEC);
+    vcpu->arch.vsscratch = csr_read(CSR_VSSCRATCH);
+    vcpu->arch.vscause = csr_read(CSR_VSCAUSE);
+    vcpu->arch.vstval = csr_read(CSR_VSTVAL);
+    vcpu->arch.vsepc = csr_read(CSR_VSEPC);
+}
+
+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_write64(CSR_HENVCFG, vcpu->arch.henvcfg);
+    csr_write(CSR_HCOUNTEREN, vcpu->arch.hcounteren);
+    csr_write64(CSR_HTIMEDELTA, vcpu->arch.htimedelta);
+
+    if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        csr_write(CSR_HSTATEEN0, vcpu->arch.hstateen0);
+
+    csr_write(CSR_VSSTATUS, vcpu->arch.vsstatus);
+    csr_write(CSR_VSIE, vcpu->arch.vsie);
+    csr_write(CSR_VSTVEC, vcpu->arch.vstvec);
+    csr_write(CSR_VSSCRATCH, vcpu->arch.vsscratch);
+    csr_write(CSR_VSCAUSE, vcpu->arch.vscause);
+    csr_write(CSR_VSTVAL, vcpu->arch.vstval);
+    csr_write(CSR_VSEPC, vcpu->arch.vsepc);
+}
+
+static void ctxt_switch_from(struct vcpu *p)
+{
+    /*
+     * When the idle VCPU is running, Xen will always stay in hypervisor
+     * mode.
+     * Therefore we don't need to save the context of an idle VCPU.
+     */
+    if ( is_idle_vcpu(p) )
+        return;
+
+    p2m_ctxt_switch_from(p);
+
+    vtimer_ctxt_switch_from(p);
+
+    save_csr_regs(p);
+}
+
+static void ctxt_switch_to(struct vcpu *n)
+{
+    /*
+     * When the idle VCPU is running, Xen will always stay in hypervisor
+     * mode.
+     * Therefore we don't need to restore the context of an idle VCPU.
+     */
+    if ( is_idle_vcpu(n) )
+        return;
+
+    /*
+     * If this vCPU last ran on a different pCPU, invalidate its VMID so
+     * vmid_handle_vmenter() assigns a fresh one from the current pCPU's pool.
+     * Without this, two pCPUs could independently assign the same
+     * (generation, vmid) pair, generation counters start at the same value
+     * on all pCPUs and increment independently, causing TLB contamination.
+     */
+    if ( n->arch.last_cpu != smp_processor_id() )
+        vmid_flush_vcpu(n);
+
+    vtimer_ctxt_switch_to(n);
+
+    restore_csr_regs(n);
+
+    p2m_ctxt_switch_to(n);
+}
+
+static void schedule_tail(struct vcpu *prev)
+{
+    unsigned int cpu = smp_processor_id();
+
+    ASSERT(prev != current);
+
+    ctxt_switch_from(prev);
+
+    /*
+     * Mark this CPU in next domain's dirty cpumasks before calling
+     * ctxt_switch_to(). This avoids a race on things like p2m flushing,
+     * which is synchronised on that function.
+     */
+    if ( prev->domain != current->domain )
+    {
+        cpumask_set_cpu(cpu, current->domain->dirty_cpumask);
+
+        /*
+         * Once this hart drops out of prev's dirty_cpumask it stops being a
+         * target of p2m_tlb_flush(), while its TLB may still hold G-stage
+         * translations of prev's domain: neither the vCPU which just ran nor
+         * any other vCPU of that domain which ran here earlier has had its
+         * VMID invalidated. Move the hart to a new VMID generation so that
+         * none of them can be reached again.
+         *
+         * Switching away from the idle vCPU needs no bump: the idle domain
+         * has no p2m of its own, and whatever G-stage entries this hart may
+         * still hold (or speculatively create while HGATP keeps pointing at
+         * the last guest's p2m) are tagged with a VMID which was already made
+         * stale when that guest was switched out. Skipping the bump here also
+         * avoids burning a generation on every pass through idle.
+         */
+        if ( !is_idle_vcpu(prev) )
+            vmid_flush_hart();
+
+        cpumask_clear_cpu(cpu, prev->domain->dirty_cpumask);
+    }
+    write_atomic(&current->dirty_cpu, cpu);
+
+    ctxt_switch_to(current);
+
+    write_atomic(&prev->dirty_cpu, VCPU_CPU_CLEAN);
+
+    current->arch.last_cpu = cpu;
+
+    /*
+     * sched_context_switched() internally uses a spinlock,
+     * which requires interrupts to be enabled.
+     */
+    local_irq_enable();
+
+    sched_context_switched(prev, current);
+}
+
+void context_switch(struct vcpu *prev, struct vcpu *next)
+{
+    ASSERT(local_irq_is_enabled());
+    ASSERT(prev != next);
+    ASSERT(!vcpu_cpu_dirty(next));
+
+    local_irq_disable();
+
+    set_current(next);
+
+    prev = __context_switch(prev, next);
+
+    schedule_tail(prev);
+}
+
 static void __init __maybe_unused build_assertions(void)
 {
     /*
xen/arch/riscv/entry.S +44 -0

47 lines not on this page · raw message

xen/arch/riscv/include/asm/domain.h +15 -1
index 15e8fa19685e..90ed584bb844 100644
@@ -29,6 +29,12 @@ struct arch_vcpu_io {
 struct arch_vcpu {
     struct vcpu_vmid vmid;
 
+    /*
+     * The last CPU this vCPU ran on. Initialised to NR_CPUS
+     * (never ran).
+     */
+    unsigned int last_cpu;
+
     /*
      * Callee saved registers for Xen's state used to switch from
      * prev's stack to the next's stack during context switch.
@@ -60,11 +66,19 @@ struct arch_vcpu {
     register_t hcounteren;
     register_t hedeleg;
     register_t hideleg;
-    register_t henvcfg;
+    uint64_t   henvcfg;
     register_t hstateen0;
+    uint64_t   htimedelta;
     register_t hvip;
 
     register_t vsatp;
+    register_t vscause;
+    register_t vsepc;
+    register_t vsie;
+    register_t vsscratch;
+    register_t vsstatus;
+    register_t vstval;
+    register_t vstvec;
 
     /*
      * VCPU interrupts
xen/arch/riscv/include/asm/p2m.h +0 -1
index 0d1dace1a0d8..9edf78377ee5 100644
@@ -262,7 +262,6 @@ struct page_info *p2m_get_page_from_gfn(struct p2m_domain *p2m, gfn_t gfn,
 
 void p2m_ctxt_switch_from(struct vcpu *p);
 void p2m_ctxt_switch_to(struct vcpu *n);
-void p2m_handle_vmenter(void);
 
 #endif /* ASM__RISCV__P2M_H */
 
xen/arch/riscv/include/asm/system.h +4 -0
index f33af64fd2ec..f5f30a9c8059 100644
@@ -76,6 +76,10 @@ static inline bool local_irq_is_enabled(void)
 
 #define arch_fetch_and_add(x, v) __sync_fetch_and_add(x, v)
 
+struct vcpu;
+
+struct vcpu *__context_switch(struct vcpu *prev, struct vcpu *next);
+
 #endif /* __ASSEMBLER__ */
 
 #endif /* ASM__RISCV__SYSTEM_H */
xen/arch/riscv/p2m.c +10 -47

86 lines not on this page · raw message

xen/arch/riscv/riscv64/asm-offsets.c +18 -1
index 1290b9dbbe82..c1be1614ce94 100644
@@ -1,8 +1,10 @@
 #define COMPILE_OFFSETS
 
+#include <xen/sched.h>
+#include <xen/types.h>
+
 #include <asm/current.h>
 #include <asm/processor.h>
-#include <xen/types.h>
 
 #define DEFINE(_sym, _val)                                                 \
     asm volatile ( "\n.ascii\"==>#define " #_sym " %0 /* " #_val " */<==\""\
@@ -53,4 +55,19 @@ void asm_offsets(void)
     BLANK();
     DEFINE(PCPU_INFO_SIZE, sizeof(struct pcpu_info));
     BLANK();
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S0, struct vcpu, arch.xen_saved_context.s0);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S1, struct vcpu, arch.xen_saved_context.s1);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S2, struct vcpu, arch.xen_saved_context.s2);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S3, struct vcpu, arch.xen_saved_context.s3);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S4, struct vcpu, arch.xen_saved_context.s4);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S5, struct vcpu, arch.xen_saved_context.s5);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S6, struct vcpu, arch.xen_saved_context.s6);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S7, struct vcpu, arch.xen_saved_context.s7);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S8, struct vcpu, arch.xen_saved_context.s8);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S9, struct vcpu, arch.xen_saved_context.s9);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S10, struct vcpu, arch.xen_saved_context.s10);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_S11, struct vcpu, arch.xen_saved_context.s11);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_SP, struct vcpu, arch.xen_saved_context.sp);
+    OFFSET(VCPU_XEN_SAVED_CONTEXT_RA, struct vcpu, arch.xen_saved_context.ra);
+    BLANK();
 }
xen/arch/riscv/stubs.c +0 -5
index 3a7953593d93..e0febae432b2 100644
@@ -81,11 +81,6 @@ void smp_send_state_dump(unsigned int cpu)
 
 DEFINE_PER_CPU(struct vcpu *, curr_vcpu);
 
-void context_switch(struct vcpu *prev, struct vcpu *next)
-{
-    BUG_ON("unimplemented");
-}
-
 void continue_running(struct vcpu *same)
 {
     BUG_ON("unimplemented");
xen/arch/riscv/traps.c +0 -2
index 8530e6fbda0a..093d81e2d803 100644
@@ -178,8 +178,6 @@ static void check_for_pcpu_work(void)
     vcpu_sync_interrupts(curr);
 
     vcpu_flush_interrupts(curr);
-
-    p2m_handle_vmenter();
 }
 
 static void timer_interrupt(void)
Signature · 1 line
2.55.0
#73 lore raw

Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching

Quoted 14 lines · Oleksii Kurochko
  }
xen/arch/riscv/domain.c +12 -0
+static void save_csr_regs(struct vcpu *vcpu)
+{
+    /*
+     * There is no need to save these CSRs as only hypervisor writes them in
+     * restore_csr_regs() and guest can't access them so they shouldn't be
+     * stored here. Keep them commented here just for symmetry with the
+     * restore CSRs register part.
+     *
+     * vcpu->arch.hedeleg = csr_read(CSR_HEDELEG);
+     * vcpu->arch.hideleg = csr_read(CSR_HIDELEG);
+     * vcpu->arch.henvcfg = csr_read64(CSR_HENVCFG);
+     * vcpu->arch.hcounteren = csr_read(CSR_HCOUNTEREN);

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 357

Quoted 10 lines
xen/arch/riscv/domain.c +10 -0
+     * vcpu->arch.htimedelta = csr_read64(CSR_HTIMEDELTA);
+     *
+     * if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+     *     vcpu->arch.hstateen0 = csr_read(CSR_HSTATEEN0);
+     */
+
+    vcpu->arch.hvip = csr_read(CSR_HVIP);
+
+    vcpu->arch.vsstatus = csr_read(CSR_VSSTATUS);
+    vcpu->arch.vsie = csr_read(CSR_VSIE);

It should be heere csr_read64() (accidentally this changed moved to the next patch).

Quoted 11 lines
xen/arch/riscv/domain.c +11 -0
+    vcpu->arch.vstvec = csr_read(CSR_VSTVEC);
+    vcpu->arch.vsscratch = csr_read(CSR_VSSCRATCH);
+    vcpu->arch.vscause = csr_read(CSR_VSCAUSE);
+    vcpu->arch.vstval = csr_read(CSR_VSTVAL);
+    vcpu->arch.vsepc = csr_read(CSR_VSEPC);
+}
+
+static void restore_csr_regs(struct vcpu *vcpu)
+{
+    csr_write(CSR_HEDELEG, vcpu->arch.hedeleg);
+    csr_write(CSR_HIDELEG, vcpu->arch.hideleg);

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 378

Quoted 10 lines
xen/arch/riscv/domain.c +10 -0
+    csr_write(CSR_HVIP, vcpu->arch.hvip);
+    csr_write64(CSR_HENVCFG, vcpu->arch.henvcfg);
+    csr_write(CSR_HCOUNTEREN, vcpu->arch.hcounteren);
+    csr_write64(CSR_HTIMEDELTA, vcpu->arch.htimedelta);
+
+    if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        csr_write(CSR_HSTATEEN0, vcpu->arch.hstateen0);
+
+    csr_write(CSR_VSSTATUS, vcpu->arch.vsstatus);
+    csr_write(CSR_VSIE, vcpu->arch.vsie);

It should be heere csr_write64() (accidentally this changed moved to the next patch).

Quoted 7 lines
xen/arch/riscv/domain.c +7 -0
+    csr_write(CSR_VSTVEC, vcpu->arch.vstvec);
+    csr_write(CSR_VSSCRATCH, vcpu->arch.vsscratch);
+    csr_write(CSR_VSCAUSE, vcpu->arch.vscause);
+    csr_write(CSR_VSTVAL, vcpu->arch.vstval);
+    csr_write(CSR_VSEPC, vcpu->arch.vsepc);
+}
+

[...]

Quoted 21 lines
xen/arch/riscv/include/asm/domain.h +6 -0
index 15e8fa19685e..90ed584bb844 100644
@@ -29,6 +29,12 @@ struct arch_vcpu_io {
  struct arch_vcpu {
      struct vcpu_vmid vmid;
 
+    /*
+     * The last CPU this vCPU ran on. Initialised to NR_CPUS
+     * (never ran).
+     */
+    unsigned int last_cpu;
+
      /*
       * Callee saved registers for Xen's state used to switch from
       * prev's stack to the next's stack during context switch.
@@ -60,11 +66,19 @@ struct arch_vcpu {
      register_t hcounteren;
      register_t hedeleg;
      register_t hideleg;

xen/arch/riscv/include/asm/domain.h struct arch_vcpu { · line 77

Quoted 10 lines
xen/arch/riscv/include/asm/domain.h +5 -1
-    register_t henvcfg;
+    uint64_t   henvcfg;
      register_t hstateen0;
+    uint64_t   htimedelta;
      register_t hvip;
 
      register_t vsatp;
+    register_t vscause;
+    register_t vsepc;
+    register_t vsie;

It should be uint64_t.

xen/arch/riscv/include/asm/domain.h struct arch_vcpu { · line 82

Quoted 5 lines
xen/arch/riscv/include/asm/domain.h +4 -0
+    register_t vsscratch;
+    register_t vsstatus;
+    register_t vstval;
+    register_t vstvec;
 

Sorry for inconvenience.

~ Oleksii

#74 lore raw

Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching

In reply to Oleksii Kurochko

As I understand it, a generation wrap doesn't retire a single VMID, it resets next_vmid to 1, which makes every VMID in 1..max_vmid reusable again in the new generation. We do a full (local) flush at that point to avoid two different vCPUs ending up with the same VMID valid at once, across generations.

If this is correct, doing a full flush there also throws away entries for the current vCPU that a local HFENCE.GVMA(vmid) per retired VMID could have preserved. A local-flush-per-VMID approach could also reduce how often we need a full flush at all.

Is there a reason we don't do local flushing instead? I see x86 and KVM use the same flush-all design on wrap, so I assume there's a reason I'm missing, I'd like to understand it.

Thanks in advance.

Quoted 41 lines

H/VS CSRs, virtual timer and P2M context, and __context_switch() in assembly, which switches Xen's own callee-saved state (and thereby the stack) from prev to next. Virtual interrupt controller context switch will be introduced later.

Add offsets of struct arch_vcpu's xen_saved_context to asm-offsets.c for use by __context_switch().

henvcfg and htimedelta are 64-bit on both RV32 and RV64, so store them as uint64_t and use csr_{read,write}64() instead of open-coding accesses to the high halves.

A hart which drops out of a domain's dirty_cpumask stops being a target of p2m_tlb_flush() while its TLB may still hold G-stage translations of that domain, and neither the vCPU which just ran nor any other vCPU of that domain which ran there earlier has had its VMID invalidated. Move the hart to a new VMID generation at that point: a VMID number is never re-used until a full local flush has happened, hence none of those translations can be reached again.

Claim the VMID in p2m_ctxt_switch_to() rather than at the next guest entry. VMIDs are a per-hart resource, so the (generation, vmid) pair a migrating vCPU brings from another hart is meaningless here and may even match this hart's current generation, leaving the vCPU under a VMID owned by another domain. ctxt_switch_to() invalidates that pair, but claiming a replacement only on guest entry is too late: p2m_ctxt_switch_to() has by then already made HGATP live, and speculation can populate G-stage entries of the incoming domain under the stale VMID. The local flush for a wrapped generation moves along with the claim.

That leaves p2m_handle_vmenter() with nothing to do, so drop it together with its call from check_for_pcpu_work(). A VMID can only be invalidated while its vCPU isn't running: vmid_flush_vcpu() is called for the vCPU being switched in, and vmid_flush_hart() runs either from schedule_tail(), ahead of ctxt_switch_to(), or from the wrap path of vmid_handle_vmenter() itself. A P2M change on another hart doesn't invalidate it either, as p2m_tlb_flush() drops the stale entries directly with sbi_remote_hfence_gvma() instead of retiring the VMIDs which tag them. A guest therefore always runs under the VMID claimed on its way in, and there is nothing left for a guest entry hook to notice.

Quoted 8 lines

p2m_handle_vmenter() also skipped the HGATP write when the VMID it claimed was unchanged. That isn't carried over: HGATP holds the G-stage root as well, and skipping the write is only correct where that root is already the incoming domain's. On the guest entry path it is, on the context switch path it is not.

While at it, fix the inclusion order of headers in asm-offsets.c: Xen's headers go first, then arch specific ones.

This could have a dedicated patch no?

Quoted 76 lines
xen/arch/riscv/domain.c +47 -0
index ec327a5e8a..91a46d630f 100644
@@ -11,9 +11,11 @@
 #include <asm/bitops.h>
 #include <asm/cpufeature.h>
 #include <asm/csr.h>
+#include <asm/current.h>
 #include <asm/intc.h>
 #include <asm/mmio.h>
 #include <asm/riscv_encoding.h>
+#include <asm/vmid.h>
 #include <asm/vtimer.h>
 
 struct csr_masks {
@@ -158,6 +160,8 @@ int arch_vcpu_create(struct vcpu *v)
     if ( is_idle_vcpu(v) )
         return 0;
 
+    v->arch.last_cpu = NR_CPUS;
+
     vcpu_csr_init(v);
 
     if ( (rc = vcpu_vtimer_init(v)) )
@@ -329,6 +333,169 @@ int arch_domain_create(struct domain *d,
     return rc;
 }
 
+static void save_csr_regs(struct vcpu *vcpu)
+{
+    /*
+     * There is no need to save these CSRs as only hypervisor writes them in
+     * restore_csr_regs() and guest can't access them so they shouldn't be
+     * stored here. Keep them commented here just for symmetry with the
+     * restore CSRs register part.
+     *
+     * vcpu->arch.hedeleg = csr_read(CSR_HEDELEG);
+     * vcpu->arch.hideleg = csr_read(CSR_HIDELEG);
+     * vcpu->arch.henvcfg = csr_read64(CSR_HENVCFG);
+     * vcpu->arch.hcounteren = csr_read(CSR_HCOUNTEREN);
+     * vcpu->arch.htimedelta = csr_read64(CSR_HTIMEDELTA);
+     *
+     * if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+     *     vcpu->arch.hstateen0 = csr_read(CSR_HSTATEEN0);
+     */
+
+    vcpu->arch.hvip = csr_read(CSR_HVIP);
+
+    vcpu->arch.vsstatus = csr_read(CSR_VSSTATUS);
+    vcpu->arch.vsie = csr_read(CSR_VSIE);
 
 
+    vcpu->arch.vstvec = csr_read(CSR_VSTVEC);
+    vcpu->arch.vsscratch = csr_read(CSR_VSSCRATCH);
+    vcpu->arch.vscause = csr_read(CSR_VSCAUSE);
+    vcpu->arch.vstval = csr_read(CSR_VSTVAL);
+    vcpu->arch.vsepc = csr_read(CSR_VSEPC);
+}
+
+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_write64(CSR_HENVCFG, vcpu->arch.henvcfg);
+    csr_write(CSR_HCOUNTEREN, vcpu->arch.hcounteren);
+    csr_write64(CSR_HTIMEDELTA, vcpu->arch.htimedelta);
+
+    if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        csr_write(CSR_HSTATEEN0, vcpu->arch.hstateen0);
+
+    csr_write(CSR_VSSTATUS, vcpu->arch.vsstatus);
+    csr_write(CSR_VSIE, vcpu->arch.vsie);

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 386

Quoted 10 lines
xen/arch/riscv/domain.c +8 -0
 
 
+    csr_write(CSR_VSTVEC, vcpu->arch.vstvec);
+    csr_write(CSR_VSSCRATCH, vcpu->arch.vsscratch);
+    csr_write(CSR_VSCAUSE, vcpu->arch.vscause);
+    csr_write(CSR_VSTVAL, vcpu->arch.vstval);
+    csr_write(CSR_VSEPC, vcpu->arch.vsepc);
+}
+
+static void ctxt_switch_from(struct vcpu *p)

Is it expected to have diverse names for the vcpu arg? Above it's vcpu, here it's p (I assume it's for previous but I think the _from alone is enough to understand) and below it's n. Shouldn't be better to keep the same name?

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

Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching

Quoted 51 lines · Baptiste Le Duc
Quoted 49 lines
xen/arch/riscv/domain.c +43 -0
@@ -329,6 +333,169 @@ int arch_domain_create(struct domain *d,
     return rc;
 }
 
+static void save_csr_regs(struct vcpu *vcpu)
+{
+    /*
+     * There is no need to save these CSRs as only hypervisor writes them in
+     * restore_csr_regs() and guest can't access them so they shouldn't be
+     * stored here. Keep them commented here just for symmetry with the
+     * restore CSRs register part.
+     *
+     * vcpu->arch.hedeleg = csr_read(CSR_HEDELEG);
+     * vcpu->arch.hideleg = csr_read(CSR_HIDELEG);
+     * vcpu->arch.henvcfg = csr_read64(CSR_HENVCFG);
+     * vcpu->arch.hcounteren = csr_read(CSR_HCOUNTEREN);
+     * vcpu->arch.htimedelta = csr_read64(CSR_HTIMEDELTA);
+     *
+     * if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+     *     vcpu->arch.hstateen0 = csr_read(CSR_HSTATEEN0);
+     */
+
+    vcpu->arch.hvip = csr_read(CSR_HVIP);
+
+    vcpu->arch.vsstatus = csr_read(CSR_VSSTATUS);
+    vcpu->arch.vsie = csr_read(CSR_VSIE);
 
 
+    vcpu->arch.vstvec = csr_read(CSR_VSTVEC);
+    vcpu->arch.vsscratch = csr_read(CSR_VSSCRATCH);
+    vcpu->arch.vscause = csr_read(CSR_VSCAUSE);
+    vcpu->arch.vstval = csr_read(CSR_VSTVAL);
+    vcpu->arch.vsepc = csr_read(CSR_VSEPC);
+}
+
+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_write64(CSR_HENVCFG, vcpu->arch.henvcfg);
+    csr_write(CSR_HCOUNTEREN, vcpu->arch.hcounteren);
+    csr_write64(CSR_HTIMEDELTA, vcpu->arch.htimedelta);
+
+    if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        csr_write(CSR_HSTATEEN0, vcpu->arch.hstateen0);
+
+    csr_write(CSR_VSSTATUS, vcpu->arch.vsstatus);
+    csr_write(CSR_VSIE, vcpu->arch.vsie);
Quoted 11 lines

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 386

Quoted 8 lines
xen/arch/riscv/domain.c +8 -0
+    csr_write(CSR_VSTVEC, vcpu->arch.vstvec);
+    csr_write(CSR_VSSCRATCH, vcpu->arch.vsscratch);
+    csr_write(CSR_VSCAUSE, vcpu->arch.vscause);
+    csr_write(CSR_VSTVAL, vcpu->arch.vstval);
+    csr_write(CSR_VSEPC, vcpu->arch.vsepc);
+}
+
+static void ctxt_switch_from(struct vcpu *p)

Is it expected to have diverse names for the vcpu arg? Above it's vcpu, here it's p (I assume it's for previous but I think the _from alone is enough to understand) and below it's n. Shouldn't be better to keep the same name?

Context switch code is special, and using p and n can be warranted there. Everywhere else it should be v, nothing else (and I said so to Oleksii more than once before). Unless, of course, multiple vCPU-s come into play at the same time.

Jan

#76 lore raw

Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching

Quoted 64 lines · Jan Beulich
Quoted 51 lines · Baptiste Le Duc
Quoted 49 lines
xen/arch/riscv/domain.c +43 -0
@@ -329,6 +333,169 @@ int arch_domain_create(struct domain *d,
     return rc;
 }
 
+static void save_csr_regs(struct vcpu *vcpu)
+{
+    /*
+     * There is no need to save these CSRs as only hypervisor writes them in
+     * restore_csr_regs() and guest can't access them so they shouldn't be
+     * stored here. Keep them commented here just for symmetry with the
+     * restore CSRs register part.
+     *
+     * vcpu->arch.hedeleg = csr_read(CSR_HEDELEG);
+     * vcpu->arch.hideleg = csr_read(CSR_HIDELEG);
+     * vcpu->arch.henvcfg = csr_read64(CSR_HENVCFG);
+     * vcpu->arch.hcounteren = csr_read(CSR_HCOUNTEREN);
+     * vcpu->arch.htimedelta = csr_read64(CSR_HTIMEDELTA);
+     *
+     * if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+     *     vcpu->arch.hstateen0 = csr_read(CSR_HSTATEEN0);
+     */
+
+    vcpu->arch.hvip = csr_read(CSR_HVIP);
+
+    vcpu->arch.vsstatus = csr_read(CSR_VSSTATUS);
+    vcpu->arch.vsie = csr_read(CSR_VSIE);
 
 
+    vcpu->arch.vstvec = csr_read(CSR_VSTVEC);
+    vcpu->arch.vsscratch = csr_read(CSR_VSSCRATCH);
+    vcpu->arch.vscause = csr_read(CSR_VSCAUSE);
+    vcpu->arch.vstval = csr_read(CSR_VSTVAL);
+    vcpu->arch.vsepc = csr_read(CSR_VSEPC);
+}
+
+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_write64(CSR_HENVCFG, vcpu->arch.henvcfg);
+    csr_write(CSR_HCOUNTEREN, vcpu->arch.hcounteren);
+    csr_write64(CSR_HTIMEDELTA, vcpu->arch.htimedelta);
+
+    if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        csr_write(CSR_HSTATEEN0, vcpu->arch.hstateen0);
+
+    csr_write(CSR_VSSTATUS, vcpu->arch.vsstatus);
+    csr_write(CSR_VSIE, vcpu->arch.vsie);
Quoted 11 lines

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 386

Quoted 8 lines
xen/arch/riscv/domain.c +8 -0
+    csr_write(CSR_VSTVEC, vcpu->arch.vstvec);
+    csr_write(CSR_VSSCRATCH, vcpu->arch.vsscratch);
+    csr_write(CSR_VSCAUSE, vcpu->arch.vscause);
+    csr_write(CSR_VSTVAL, vcpu->arch.vstval);
+    csr_write(CSR_VSEPC, vcpu->arch.vsepc);
+}
+
+static void ctxt_switch_from(struct vcpu *p)

Is it expected to have diverse names for the vcpu arg? Above it's vcpu, here it's p (I assume it's for previous but I think the _from alone is enough to understand) and below it's n. Shouldn't be better to keep the same name?

Quoted 5 lines

Context switch code is special, and using p and n can be warranted there. Everywhere else it should be v, nothing else (and I said so to Oleksii more than once before). Unless, of course, multiple vCPU-s come into play at the same time.

Ok noted, thanks for clarifying that.

Quoted 4 lines

Jan

#77 lore raw

Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching

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

As I understand it, a generation wrap doesn't retire a single VMID, it resets next_vmid to 1, which makes every VMID in 1..max_vmid reusable again in the new generation. We do a full (local) flush at that point to avoid two different vCPUs ending up with the same VMID valid at once, across generations.

If this is correct, doing a full flush there also throws away entries for the current vCPU that a local HFENCE.GVMA(vmid) per retired VMID

We are doing flushed for the pCPU on which a vCPU is ran.

Quoted 6 lines

could have preserved. A local-flush-per-VMID approach could also reduce how often we need a full flush at all.

Is there a reason we don't do local flushing instead? I see x86 and KVM use the same flush-all design on wrap, so I assume there's a reason I'm missing, I'd like to understand it.

What do you mean here by "local flushing instead"? We are doing local flush:

if ( unlikely(need_flush) )
local_hfence_gvma_all();

Do you mean why we don't do hfence_gvma only for specific VMID?

A vCPU's VMID is valid only while vmid->generation == data->generation (vmid.c:141). Bumping the generation invalidates every vCPU's VMID on this hart simultaneously, so every G-stage entry in the TLB (whatever number it is tagged with) belongs to a (vcpu, vmid) binding that can never be consulted again. Each of those vCPUs will be handed a fresh number on its next vmenter before it can run.

That includes the current vCPU, which is the case you're worried about. At the wrap it is being assigned VMID 1, not its previous number, so its old entries are unreachable regardless of whether we flush them. hfence.gvma per retired VMID would preserve them physically but not usefully [A concrete example. vCPU A is running on the hart with VMID=100 in generation G; the TLB holds G-stage entries tagged VMID=100. A wrap occurs: the generation becomes G+1, next_vmid is reset to 1, and A is assigned VMID=1 (vmid.c:154). From that moment on, the hardware looks up translations for A under the tag VMID=1. The entries tagged 100 will no longer match anything: A isn't 100 any more, and no one else will be handed 100 until the next wrap. So A loses its warm entries not because we did an hfence.gvma, but because it was renumbered. The flush has nothing to do with it. It merely discards what has already become unreachable.]; they'd just occupy TLB capacity until natural eviction. Preserving them would require a different allocator that keeps a vCPU's number stable across a rollover (Linux/KVM-arm64 style, with an active/reserved set pinning live ASIDs), not a different flush granularity.

So x86's hvm_asid_handle_vmenter() and KVM's equivalent aren't doing this out of inertia — with a round-robin generation allocator, the full flush is free of useful collateral damage and strictly cheaper than the alternative. Preserving entries across a rollover is a real optimisation, but it's an allocator change, and IMO worth doing only if profiling shows the wrap flush matters.

Quoted 48 lines
Quoted 48 lines

H/VS CSRs, virtual timer and P2M context, and __context_switch() in assembly, which switches Xen's own callee-saved state (and thereby the stack) from prev to next. Virtual interrupt controller context switch will be introduced later.

Add offsets of struct arch_vcpu's xen_saved_context to asm-offsets.c for use by __context_switch().

henvcfg and htimedelta are 64-bit on both RV32 and RV64, so store them as uint64_t and use csr_{read,write}64() instead of open-coding accesses to the high halves.

A hart which drops out of a domain's dirty_cpumask stops being a target of p2m_tlb_flush() while its TLB may still hold G-stage translations of that domain, and neither the vCPU which just ran nor any other vCPU of that domain which ran there earlier has had its VMID invalidated. Move the hart to a new VMID generation at that point: a VMID number is never re-used until a full local flush has happened, hence none of those translations can be reached again.

Claim the VMID in p2m_ctxt_switch_to() rather than at the next guest entry. VMIDs are a per-hart resource, so the (generation, vmid) pair a migrating vCPU brings from another hart is meaningless here and may even match this hart's current generation, leaving the vCPU under a VMID owned by another domain. ctxt_switch_to() invalidates that pair, but claiming a replacement only on guest entry is too late: p2m_ctxt_switch_to() has by then already made HGATP live, and speculation can populate G-stage entries of the incoming domain under the stale VMID. The local flush for a wrapped generation moves along with the claim.

That leaves p2m_handle_vmenter() with nothing to do, so drop it together with its call from check_for_pcpu_work(). A VMID can only be invalidated while its vCPU isn't running: vmid_flush_vcpu() is called for the vCPU being switched in, and vmid_flush_hart() runs either from schedule_tail(), ahead of ctxt_switch_to(), or from the wrap path of vmid_handle_vmenter() itself. A P2M change on another hart doesn't invalidate it either, as p2m_tlb_flush() drops the stale entries directly with sbi_remote_hfence_gvma() instead of retiring the VMIDs which tag them. A guest therefore always runs under the VMID claimed on its way in, and there is nothing left for a guest entry hook to notice.

p2m_handle_vmenter() also skipped the HGATP write when the VMID it claimed was unchanged. That isn't carried over: HGATP holds the G-stage root as well, and skipping the write is only correct where that root is already the incoming domain's. On the guest entry path it is, on the context switch path it is not.

Quoted 3 lines
Quoted 2 lines

While at it, fix the inclusion order of headers in asm-offsets.c: Xen's headers go first, then arch specific ones.

This could have a dedicated patch no?

It could but considering that it is pretty small fix I think it could be part of this patch. If you are insisting on moving that to separate patch I will happy to do that.

Quoted 78 lines
Quoted 76 lines
xen/arch/riscv/domain.c +47 -0
index ec327a5e8a..91a46d630f 100644
@@ -11,9 +11,11 @@
  #include <asm/bitops.h>
  #include <asm/cpufeature.h>
  #include <asm/csr.h>
+#include <asm/current.h>
  #include <asm/intc.h>
  #include <asm/mmio.h>
  #include <asm/riscv_encoding.h>
+#include <asm/vmid.h>
  #include <asm/vtimer.h>
 
  struct csr_masks {
@@ -158,6 +160,8 @@ int arch_vcpu_create(struct vcpu *v)
      if ( is_idle_vcpu(v) )
          return 0;
 
+    v->arch.last_cpu = NR_CPUS;
+
      vcpu_csr_init(v);
 
      if ( (rc = vcpu_vtimer_init(v)) )
@@ -329,6 +333,169 @@ int arch_domain_create(struct domain *d,
      return rc;
  }
 
+static void save_csr_regs(struct vcpu *vcpu)
+{
+    /*
+     * There is no need to save these CSRs as only hypervisor writes them in
+     * restore_csr_regs() and guest can't access them so they shouldn't be
+     * stored here. Keep them commented here just for symmetry with the
+     * restore CSRs register part.
+     *
+     * vcpu->arch.hedeleg = csr_read(CSR_HEDELEG);
+     * vcpu->arch.hideleg = csr_read(CSR_HIDELEG);
+     * vcpu->arch.henvcfg = csr_read64(CSR_HENVCFG);
+     * vcpu->arch.hcounteren = csr_read(CSR_HCOUNTEREN);
+     * vcpu->arch.htimedelta = csr_read64(CSR_HTIMEDELTA);
+     *
+     * if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+     *     vcpu->arch.hstateen0 = csr_read(CSR_HSTATEEN0);
+     */
+
+    vcpu->arch.hvip = csr_read(CSR_HVIP);
+
+    vcpu->arch.vsstatus = csr_read(CSR_VSSTATUS);
+    vcpu->arch.vsie = csr_read(CSR_VSIE);
 
 
+    vcpu->arch.vstvec = csr_read(CSR_VSTVEC);
+    vcpu->arch.vsscratch = csr_read(CSR_VSSCRATCH);
+    vcpu->arch.vscause = csr_read(CSR_VSCAUSE);
+    vcpu->arch.vstval = csr_read(CSR_VSTVAL);
+    vcpu->arch.vsepc = csr_read(CSR_VSEPC);
+}
+
+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_write64(CSR_HENVCFG, vcpu->arch.henvcfg);
+    csr_write(CSR_HCOUNTEREN, vcpu->arch.hcounteren);
+    csr_write64(CSR_HTIMEDELTA, vcpu->arch.htimedelta);
+
+    if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        csr_write(CSR_HSTATEEN0, vcpu->arch.hstateen0);
+
+    csr_write(CSR_VSSTATUS, vcpu->arch.vsstatus);
+    csr_write(CSR_VSIE, vcpu->arch.vsie);
Quoted 11 lines

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 386

Quoted 8 lines
xen/arch/riscv/domain.c +8 -0
+    csr_write(CSR_VSTVEC, vcpu->arch.vstvec);
+    csr_write(CSR_VSSCRATCH, vcpu->arch.vsscratch);
+    csr_write(CSR_VSCAUSE, vcpu->arch.vscause);
+    csr_write(CSR_VSTVAL, vcpu->arch.vstval);
+    csr_write(CSR_VSEPC, vcpu->arch.vsepc);
+}
+
+static void ctxt_switch_from(struct vcpu *p)

Is it expected to have diverse names for the vcpu arg? Above it's vcpu, here it's p (I assume it's for previous but I think the _from alone is enough to understand) and below it's n. Shouldn't be better to keep the same name?

Above should be used n. It is what usually is used in Xen in such cases. vcpu isn't the best one name in general as it should be v. But for these functions I will use n and p correspondignly.

Thanks for noticing that.

~ Oleksii

#78 lore raw

Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching

Quoted 207 lines · Oleksii Kurochko
Quoted 8 lines · Baptiste Le Duc

As I understand it, a generation wrap doesn't retire a single VMID, it resets next_vmid to 1, which makes every VMID in 1..max_vmid reusable again in the new generation. We do a full (local) flush at that point to avoid two different vCPUs ending up with the same VMID valid at once, across generations.

If this is correct, doing a full flush there also throws away entries for the current vCPU that a local HFENCE.GVMA(vmid) per retired VMID

We are doing flushed for the pCPU on which a vCPU is ran.

Quoted 6 lines

could have preserved. A local-flush-per-VMID approach could also reduce how often we need a full flush at all.

Is there a reason we don't do local flushing instead? I see x86 and KVM use the same flush-all design on wrap, so I assume there's a reason I'm missing, I'd like to understand it.

What do you mean here by "local flushing instead"? We are doing local flush:

if ( unlikely(need_flush) )
local_hfence_gvma_all();

Do you mean why we don't do hfence_gvma only for specific VMID?

A vCPU's VMID is valid only while vmid->generation == data->generation (vmid.c:141). Bumping the generation invalidates every vCPU's VMID on this hart simultaneously, so every G-stage entry in the TLB (whatever number it is tagged with) belongs to a (vcpu, vmid) binding that can never be consulted again. Each of those vCPUs will be handed a fresh number on its next vmenter before it can run.

That includes the current vCPU, which is the case you're worried about. At the wrap it is being assigned VMID 1, not its previous number, so its old entries are unreachable regardless of whether we flush them. hfence.gvma per retired VMID would preserve them physically but not usefully [A concrete example. vCPU A is running on the hart with VMID=100 in generation G; the TLB holds G-stage entries tagged VMID=100. A wrap occurs: the generation becomes G+1, next_vmid is reset to 1, and A is assigned VMID=1 (vmid.c:154). From that moment on, the hardware looks up translations for A under the tag VMID=1. The entries tagged 100 will no longer match anything: A isn't 100 any more, and no one else will be handed 100 until the next wrap.
So A loses its warm entries not because we did an hfence.gvma, but because it was renumbered. The flush has nothing to do with it. It merely discards what has already become unreachable.]; they'd just occupy TLB capacity until natural eviction. Preserving them would require a different allocator that keeps a vCPU's number stable across a rollover (Linux/KVM-arm64 style, with an active/reserved set pinning live ASIDs), not a different flush granularity.

So x86's hvm_asid_handle_vmenter() and KVM's equivalent aren't doing this out of inertia — with a round-robin generation allocator, the full flush is free of useful collateral damage and strictly cheaper than the alternative. Preserving entries across a rollover is a real optimisation, but it's an allocator change, and IMO worth doing only if profiling shows the wrap flush matters.

Quoted 48 lines
Quoted 48 lines

H/VS CSRs, virtual timer and P2M context, and __context_switch() in assembly, which switches Xen's own callee-saved state (and thereby the stack) from prev to next. Virtual interrupt controller context switch will be introduced later.

Add offsets of struct arch_vcpu's xen_saved_context to asm-offsets.c for use by __context_switch().

henvcfg and htimedelta are 64-bit on both RV32 and RV64, so store them as uint64_t and use csr_{read,write}64() instead of open-coding accesses to the high halves.

A hart which drops out of a domain's dirty_cpumask stops being a target of p2m_tlb_flush() while its TLB may still hold G-stage translations of that domain, and neither the vCPU which just ran nor any other vCPU of that domain which ran there earlier has had its VMID invalidated. Move the hart to a new VMID generation at that point: a VMID number is never re-used until a full local flush has happened, hence none of those translations can be reached again.

Claim the VMID in p2m_ctxt_switch_to() rather than at the next guest entry. VMIDs are a per-hart resource, so the (generation, vmid) pair a migrating vCPU brings from another hart is meaningless here and may even match this hart's current generation, leaving the vCPU under a VMID owned by another domain. ctxt_switch_to() invalidates that pair, but claiming a replacement only on guest entry is too late: p2m_ctxt_switch_to() has by then already made HGATP live, and speculation can populate G-stage entries of the incoming domain under the stale VMID. The local flush for a wrapped generation moves along with the claim.

That leaves p2m_handle_vmenter() with nothing to do, so drop it together with its call from check_for_pcpu_work(). A VMID can only be invalidated while its vCPU isn't running: vmid_flush_vcpu() is called for the vCPU being switched in, and vmid_flush_hart() runs either from schedule_tail(), ahead of ctxt_switch_to(), or from the wrap path of vmid_handle_vmenter() itself. A P2M change on another hart doesn't invalidate it either, as p2m_tlb_flush() drops the stale entries directly with sbi_remote_hfence_gvma() instead of retiring the VMIDs which tag them. A guest therefore always runs under the VMID claimed on its way in, and there is nothing left for a guest entry hook to notice.

p2m_handle_vmenter() also skipped the HGATP write when the VMID it claimed was unchanged. That isn't carried over: HGATP holds the G-stage root as well, and skipping the write is only correct where that root is already the incoming domain's. On the guest entry path it is, on the context switch path it is not.

Quoted 3 lines
Quoted 2 lines

While at it, fix the inclusion order of headers in asm-offsets.c: Xen's headers go first, then arch specific ones.

This could have a dedicated patch no?

It could but considering that it is pretty small fix I think it could be part of this patch. If you are insisting on moving that to separate patch I will happy to do that.

Quoted 78 lines
Quoted 76 lines
xen/arch/riscv/domain.c +47 -0
index ec327a5e8a..91a46d630f 100644
@@ -11,9 +11,11 @@
  #include <asm/bitops.h>
  #include <asm/cpufeature.h>
  #include <asm/csr.h>
+#include <asm/current.h>
  #include <asm/intc.h>
  #include <asm/mmio.h>
  #include <asm/riscv_encoding.h>
+#include <asm/vmid.h>
  #include <asm/vtimer.h>
 
  struct csr_masks {
@@ -158,6 +160,8 @@ int arch_vcpu_create(struct vcpu *v)
      if ( is_idle_vcpu(v) )
          return 0;
 
+    v->arch.last_cpu = NR_CPUS;
+
      vcpu_csr_init(v);
 
      if ( (rc = vcpu_vtimer_init(v)) )
@@ -329,6 +333,169 @@ int arch_domain_create(struct domain *d,
      return rc;
  }
 
+static void save_csr_regs(struct vcpu *vcpu)
+{
+    /*
+     * There is no need to save these CSRs as only hypervisor writes them in
+     * restore_csr_regs() and guest can't access them so they shouldn't be
+     * stored here. Keep them commented here just for symmetry with the
+     * restore CSRs register part.
+     *
+     * vcpu->arch.hedeleg = csr_read(CSR_HEDELEG);
+     * vcpu->arch.hideleg = csr_read(CSR_HIDELEG);
+     * vcpu->arch.henvcfg = csr_read64(CSR_HENVCFG);
+     * vcpu->arch.hcounteren = csr_read(CSR_HCOUNTEREN);
+     * vcpu->arch.htimedelta = csr_read64(CSR_HTIMEDELTA);
+     *
+     * if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+     *     vcpu->arch.hstateen0 = csr_read(CSR_HSTATEEN0);
+     */
+
+    vcpu->arch.hvip = csr_read(CSR_HVIP);
+
+    vcpu->arch.vsstatus = csr_read(CSR_VSSTATUS);
+    vcpu->arch.vsie = csr_read(CSR_VSIE);
 
 
+    vcpu->arch.vstvec = csr_read(CSR_VSTVEC);
+    vcpu->arch.vsscratch = csr_read(CSR_VSSCRATCH);
+    vcpu->arch.vscause = csr_read(CSR_VSCAUSE);
+    vcpu->arch.vstval = csr_read(CSR_VSTVAL);
+    vcpu->arch.vsepc = csr_read(CSR_VSEPC);
+}
+
+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_write64(CSR_HENVCFG, vcpu->arch.henvcfg);
+    csr_write(CSR_HCOUNTEREN, vcpu->arch.hcounteren);
+    csr_write64(CSR_HTIMEDELTA, vcpu->arch.htimedelta);
+
+    if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        csr_write(CSR_HSTATEEN0, vcpu->arch.hstateen0);
+
+    csr_write(CSR_VSSTATUS, vcpu->arch.vsstatus);
+    csr_write(CSR_VSIE, vcpu->arch.vsie);
Quoted 11 lines

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 386

Quoted 8 lines
xen/arch/riscv/domain.c +8 -0
+    csr_write(CSR_VSTVEC, vcpu->arch.vstvec);
+    csr_write(CSR_VSSCRATCH, vcpu->arch.vsscratch);
+    csr_write(CSR_VSCAUSE, vcpu->arch.vscause);
+    csr_write(CSR_VSTVAL, vcpu->arch.vstval);
+    csr_write(CSR_VSEPC, vcpu->arch.vsepc);
+}
+
+static void ctxt_switch_from(struct vcpu *p)

Is it expected to have diverse names for the vcpu arg? Above it's vcpu, here it's p (I assume it's for previous but I think the _from alone is enough to understand) and below it's n. Shouldn't be better to keep the same name?

Quoted 1 line

Above should be used n.

Why would that be? n in such contexts stands for "next", while here it can only be "previous".

Jan

#79 lore raw

Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching

Quoted 208 lines · Jan Beulich
Quoted 207 lines · Oleksii Kurochko
Quoted 8 lines · Baptiste Le Duc

As I understand it, a generation wrap doesn't retire a single VMID, it resets next_vmid to 1, which makes every VMID in 1..max_vmid reusable again in the new generation. We do a full (local) flush at that point to avoid two different vCPUs ending up with the same VMID valid at once, across generations.

If this is correct, doing a full flush there also throws away entries for the current vCPU that a local HFENCE.GVMA(vmid) per retired VMID

We are doing flushed for the pCPU on which a vCPU is ran.

Quoted 6 lines

could have preserved. A local-flush-per-VMID approach could also reduce how often we need a full flush at all.

Is there a reason we don't do local flushing instead? I see x86 and KVM use the same flush-all design on wrap, so I assume there's a reason I'm missing, I'd like to understand it.

What do you mean here by "local flushing instead"? We are doing local flush:

if ( unlikely(need_flush) )
local_hfence_gvma_all();

Do you mean why we don't do hfence_gvma only for specific VMID?

A vCPU's VMID is valid only while vmid->generation == data->generation (vmid.c:141). Bumping the generation invalidates every vCPU's VMID on this hart simultaneously, so every G-stage entry in the TLB (whatever number it is tagged with) belongs to a (vcpu, vmid) binding that can never be consulted again. Each of those vCPUs will be handed a fresh number on its next vmenter before it can run.

That includes the current vCPU, which is the case you're worried about. At the wrap it is being assigned VMID 1, not its previous number, so its old entries are unreachable regardless of whether we flush them. hfence.gvma per retired VMID would preserve them physically but not usefully [A concrete example. vCPU A is running on the hart with VMID=100 in generation G; the TLB holds G-stage entries tagged VMID=100. A wrap occurs: the generation becomes G+1, next_vmid is reset to 1, and A is assigned VMID=1 (vmid.c:154). From that moment on, the hardware looks up translations for A under the tag VMID=1. The entries tagged 100 will no longer match anything: A isn't 100 any more, and no one else will be handed 100 until the next wrap.
So A loses its warm entries not because we did an hfence.gvma, but because it was renumbered. The flush has nothing to do with it. It merely discards what has already become unreachable.]; they'd just occupy TLB capacity until natural eviction. Preserving them would require a different allocator that keeps a vCPU's number stable across a rollover (Linux/KVM-arm64 style, with an active/reserved set pinning live ASIDs), not a different flush granularity.

So x86's hvm_asid_handle_vmenter() and KVM's equivalent aren't doing this out of inertia — with a round-robin generation allocator, the full flush is free of useful collateral damage and strictly cheaper than the alternative. Preserving entries across a rollover is a real optimisation, but it's an allocator change, and IMO worth doing only if profiling shows the wrap flush matters.

Quoted 48 lines
Quoted 48 lines

H/VS CSRs, virtual timer and P2M context, and __context_switch() in assembly, which switches Xen's own callee-saved state (and thereby the stack) from prev to next. Virtual interrupt controller context switch will be introduced later.

Add offsets of struct arch_vcpu's xen_saved_context to asm-offsets.c for use by __context_switch().

henvcfg and htimedelta are 64-bit on both RV32 and RV64, so store them as uint64_t and use csr_{read,write}64() instead of open-coding accesses to the high halves.

A hart which drops out of a domain's dirty_cpumask stops being a target of p2m_tlb_flush() while its TLB may still hold G-stage translations of that domain, and neither the vCPU which just ran nor any other vCPU of that domain which ran there earlier has had its VMID invalidated. Move the hart to a new VMID generation at that point: a VMID number is never re-used until a full local flush has happened, hence none of those translations can be reached again.

Claim the VMID in p2m_ctxt_switch_to() rather than at the next guest entry. VMIDs are a per-hart resource, so the (generation, vmid) pair a migrating vCPU brings from another hart is meaningless here and may even match this hart's current generation, leaving the vCPU under a VMID owned by another domain. ctxt_switch_to() invalidates that pair, but claiming a replacement only on guest entry is too late: p2m_ctxt_switch_to() has by then already made HGATP live, and speculation can populate G-stage entries of the incoming domain under the stale VMID. The local flush for a wrapped generation moves along with the claim.

That leaves p2m_handle_vmenter() with nothing to do, so drop it together with its call from check_for_pcpu_work(). A VMID can only be invalidated while its vCPU isn't running: vmid_flush_vcpu() is called for the vCPU being switched in, and vmid_flush_hart() runs either from schedule_tail(), ahead of ctxt_switch_to(), or from the wrap path of vmid_handle_vmenter() itself. A P2M change on another hart doesn't invalidate it either, as p2m_tlb_flush() drops the stale entries directly with sbi_remote_hfence_gvma() instead of retiring the VMIDs which tag them. A guest therefore always runs under the VMID claimed on its way in, and there is nothing left for a guest entry hook to notice.

p2m_handle_vmenter() also skipped the HGATP write when the VMID it claimed was unchanged. That isn't carried over: HGATP holds the G-stage root as well, and skipping the write is only correct where that root is already the incoming domain's. On the guest entry path it is, on the context switch path it is not.

Quoted 3 lines
Quoted 2 lines

While at it, fix the inclusion order of headers in asm-offsets.c: Xen's headers go first, then arch specific ones.

This could have a dedicated patch no?

It could but considering that it is pretty small fix I think it could be part of this patch. If you are insisting on moving that to separate patch I will happy to do that.

Quoted 89 lines
Quoted 76 lines
xen/arch/riscv/domain.c +47 -0
index ec327a5e8a..91a46d630f 100644
@@ -11,9 +11,11 @@
   #include <asm/bitops.h>
   #include <asm/cpufeature.h>
   #include <asm/csr.h>
+#include <asm/current.h>
   #include <asm/intc.h>
   #include <asm/mmio.h>
   #include <asm/riscv_encoding.h>
+#include <asm/vmid.h>
   #include <asm/vtimer.h>
 
   struct csr_masks {
@@ -158,6 +160,8 @@ int arch_vcpu_create(struct vcpu *v)
       if ( is_idle_vcpu(v) )
           return 0;
 
+    v->arch.last_cpu = NR_CPUS;
+
       vcpu_csr_init(v);
 
       if ( (rc = vcpu_vtimer_init(v)) )
@@ -329,6 +333,169 @@ int arch_domain_create(struct domain *d,
       return rc;
   }
 
+static void save_csr_regs(struct vcpu *vcpu)
+{
+    /*
+     * There is no need to save these CSRs as only hypervisor writes them in
+     * restore_csr_regs() and guest can't access them so they shouldn't be
+     * stored here. Keep them commented here just for symmetry with the
+     * restore CSRs register part.
+     *
+     * vcpu->arch.hedeleg = csr_read(CSR_HEDELEG);
+     * vcpu->arch.hideleg = csr_read(CSR_HIDELEG);
+     * vcpu->arch.henvcfg = csr_read64(CSR_HENVCFG);
+     * vcpu->arch.hcounteren = csr_read(CSR_HCOUNTEREN);
+     * vcpu->arch.htimedelta = csr_read64(CSR_HTIMEDELTA);
+     *
+     * if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+     *     vcpu->arch.hstateen0 = csr_read(CSR_HSTATEEN0);
+     */
+
+    vcpu->arch.hvip = csr_read(CSR_HVIP);
+
+    vcpu->arch.vsstatus = csr_read(CSR_VSSTATUS);
+    vcpu->arch.vsie = csr_read(CSR_VSIE);
 
 
+    vcpu->arch.vstvec = csr_read(CSR_VSTVEC);
+    vcpu->arch.vsscratch = csr_read(CSR_VSSCRATCH);
+    vcpu->arch.vscause = csr_read(CSR_VSCAUSE);
+    vcpu->arch.vstval = csr_read(CSR_VSTVAL);
+    vcpu->arch.vsepc = csr_read(CSR_VSEPC);
+}
+
+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_write64(CSR_HENVCFG, vcpu->arch.henvcfg);
+    csr_write(CSR_HCOUNTEREN, vcpu->arch.hcounteren);
+    csr_write64(CSR_HTIMEDELTA, vcpu->arch.htimedelta);
+
+    if ( riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        csr_write(CSR_HSTATEEN0, vcpu->arch.hstateen0);
+
+    csr_write(CSR_VSSTATUS, vcpu->arch.vsstatus);
+    csr_write(CSR_VSIE, vcpu->arch.vsie);

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 386

Quoted 10 lines
xen/arch/riscv/domain.c +8 -0
 
 
+    csr_write(CSR_VSTVEC, vcpu->arch.vstvec);
+    csr_write(CSR_VSSCRATCH, vcpu->arch.vsscratch);
+    csr_write(CSR_VSCAUSE, vcpu->arch.vscause);
+    csr_write(CSR_VSTVAL, vcpu->arch.vstval);
+    csr_write(CSR_VSEPC, vcpu->arch.vsepc);
+}
+
+static void ctxt_switch_from(struct vcpu *p)

Is it expected to have diverse names for the vcpu arg? Above it's vcpu, here it's p (I assume it's for previous but I think the _from alone is enough to understand) and below it's n. Shouldn't be better to keep the same name?

Quoted 4 lines
Quoted 1 line

Above should be used n.

Why would that be? n in such contexts stands for "next", while here it can only be "previous".

Sorry for confusion.

I meant for restore_csr_regs() and correpondingly p for save_csr_regs().

I will also renaim the function to cxt_switch_to/from style.

~ Oleksii

#80 lore raw

Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching

In reply to Oleksii Kurochko

I've updated the part of handling of VMID for p2m during context switch as some things were still missed. This one implementation looks more correct to me.

xen/arch/riscv/domain.c +80 -33
index 0ad851ee0f5f..c05d6f8abaaa 100644
@@ -404,16 +404,6 @@ static void ctxt_switch_to(struct vcpu *n)
     if ( is_idle_vcpu(n) )
         return;
 
-    /*
-     * If this vCPU last ran on a different pCPU, invalidate its VMID so
-     * vmid_handle_vmenter() assigns a fresh one from the current pCPU's pool.
-     * Without this, two pCPUs could independently assign the same
-     * (generation, vmid) pair, generation counters start at the same value
-     * on all pCPUs and increment independently, causing TLB contamination.
-     */
-    if ( n->arch.last_cpu != smp_processor_id() )
-        vmid_flush_vcpu(n);
-
     vtimer_ctxt_switch_to(n);
 
     restore_csr_regs(n);
@@ -421,6 +411,15 @@ static void ctxt_switch_to(struct vcpu *n)
     p2m_ctxt_switch_to(n);
 }
 
+/*
+ * Domain whose p2m this hart's HGATP points at. ctxt_switch_to() bails out
+ * early for the idle vCPU, so HGATP survives a pass through idle and keeps
+ * pointing at the domain which ran here last. That domain, rather than the
+ * one the scheduler switched away from, is what owns this hart's G-stage
+ * translations.
+ */
+static DEFINE_PER_CPU(struct domain *, hgatp_owner);
+
 static void schedule_tail(struct vcpu *prev)
 {
     unsigned int cpu = smp_processor_id();
@@ -429,40 +428,88 @@ static void schedule_tail(struct vcpu *prev)
 
     ctxt_switch_from(prev);
 
+    write_atomic(&prev->dirty_cpu, VCPU_CPU_CLEAN);
+
     /*
-     * Mark this CPU in next domain's dirty cpumasks before calling
-     * ctxt_switch_to(). This avoids a race on things like p2m flushing,
-     * which is synchronised on that function.
+     * Switching to the idle vCPU leaves HGATP alone, so this hart keeps both
+     * the G-stage translations of its owner and its place in that domain's
+     * dirty_cpumask: p2m_tlb_flush() goes on reaching it, and a domain which
+     * idles between two runs on the same hart keeps its VMIDs.
      */
-    if ( prev->domain != current->domain )
+    if ( !is_idle_vcpu(current) )
+    {
+        struct domain *owner = this_cpu(hgatp_owner);
+
+        if ( owner != current->domain )
+        {
+            /*
+             * Once this hart drops out of the owner's dirty_cpumask it stops
+             * being a target of p2m_tlb_flush(), while its TLB may still hold
+             * G-stage translations of that domain: none of the vCPUs of that
+             * domain which ran here has had its VMID invalidated. Move the
+             * hart to a new VMID generation so that none of them can be
+             * reached again.
+             */
+            if ( owner )
+            {
+                vmid_flush_hart();
+
+                cpumask_clear_cpu(cpu, owner->dirty_cpumask);
+            }
+
+            /*
+             * Mark this hart in the incoming domain's dirty_cpumask before
+             * ctxt_switch_to() points HGATP at its p2m. This avoids a race on
+             * things like p2m flushing, which is synchronised on that
+             * function.
+             */
+            cpumask_set_cpu(cpu, current->domain->dirty_cpumask);
+
+            /*
+             * Pairs with the barrier in p2m_tlb_flush(). cpumask_set_cpu() is
+             * an unordered AMO on RISC-V, so without this a concurrent flusher
+             * could read the mask without this hart in it while this hart is
+             * already walking the p2m it is about to be pointed at.
+             */
+            smp_mb();
+
+            this_cpu(hgatp_owner) = current->domain;
+        }
+    }
+
+    if ( !is_idle_vcpu(current) )
     {
-        cpumask_set_cpu(cpu, current->domain->dirty_cpumask);
+        bool need_flush;
+
+        /*
+         * A VMID is meaningful only on the hart whose pool issued it:
+         * generations are per-hart counters which all start at 1 and advance
+         * independently, so the pair a vCPU brings from another hart may match
+         * this hart's generation by coincidence, leaving the vCPU under a VMID
+         * which is live here for someone else.
+         */
+        if ( current->arch.last_cpu != cpu )
+            vmid_flush_vcpu(current);
 
         /*
-         * Once this hart drops out of prev's dirty_cpumask it stops being a
-         * target of p2m_tlb_flush(), while its TLB may still hold G-stage
-         * translations of prev's domain: neither the vCPU which just ran nor
-         * any other vCPU of that domain which ran here earlier has had its
-         * VMID invalidated. Move the hart to a new VMID generation so that
-         * none of them can be reached again.
-         *
-         * Switching away from the idle vCPU needs no bump: the idle domain
-         * has no p2m of its own, and whatever G-stage entries this hart may
-         * still hold (or speculatively create while HGATP keeps pointing at
-         * the last guest's p2m) are tagged with a VMID which was already made
-         * stale when that guest was switched out. Skipping the bump here also
-         * avoids burning a generation on every pass through idle.
+         * Claim the VMID here rather than leaving it to the next guest entry:
+         * ctxt_switch_to() makes HGATP live below, and a stale VMID there
+         * pairs this domain's G-stage root with a tag which may already have
+         * been re-issued to a vCPU of another domain.
          */
-        if ( !is_idle_vcpu(prev) )
-            vmid_flush_hart();
+        need_flush = vmid_handle_vmenter(&current->arch.vmid);
 
-        cpumask_clear_cpu(cpu, prev->domain->dirty_cpumask);
+        /*
+         * A VMID isn't re-used until the generation it was issued in wraps, so
+         * a G-stage flush is needed only when vmid_handle_vmenter() says so.
+         */
+        if ( unlikely(need_flush) )
+            local_hfence_gvma_all();
     }
-    write_atomic(&current->dirty_cpu, cpu);
 
     ctxt_switch_to(current);
 
-    write_atomic(&prev->dirty_cpu, VCPU_CPU_CLEAN);
+    write_atomic(&current->dirty_cpu, cpu);
 
     current->arch.last_cpu = cpu;
 
xen/arch/riscv/p2m.c +9 -10
index 1f7a6907525d..98c2d6de6933 100644
@@ -243,6 +243,15 @@ static void p2m_tlb_flush(struct p2m_domain *p2m)
 
     p2m->need_flush = false;
 
+    /*
+     * Order the p2m updates above against the read of dirty_cpumask below,
+     * pairing with the barrier in schedule_tail(). Either that hart is seen
+     * here and gets an HFENCE.GVMA, or it adds itself to the mask afterwards,
+     * in which case it starts walking this p2m only once the updates are
+     * visible to it.
+     */
+    smp_mb();
+
     sbi_remote_hfence_gvma(d->dirty_cpumask, 0, 0);
 }
 
@@ -1523,22 +1532,12 @@ void p2m_ctxt_switch_from(struct vcpu *p)
 void p2m_ctxt_switch_to(struct vcpu *n)
 {
     struct p2m_domain *p2m = p2m_get_hostp2m(n->domain);
-    bool need_flush;
 
     if ( is_idle_vcpu(n) )
         return;
 
-    need_flush = vmid_handle_vmenter(&n->arch.vmid);
-
     csr_write(CSR_HGATP, construct_hgatp(p2m, n->arch.vmid.vmid));
 
-    /*
-     * A VMID isn't re-used until the generation it was issued in wraps, so
-     * a G-stage flush is needed only when vmid_handle_vmenter() says so.
-     */
-    if ( unlikely(need_flush) )
-        local_hfence_gvma_all();
-
     csr_write(CSR_VSATP, n->arch.vsatp);
 
     /*

Any concerns about this implementation?

Thanks in advance.

~ Oleksii

#81 lore raw

Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching

In reply to Oleksii Kurochko
Quoted 26 lines · Oleksii Kurochko
xen/arch/riscv/domain.c +26 -0
+static void ctxt_switch_from(struct vcpu *p)
+{
+    /*
+     * When the idle VCPU is running, Xen will always stay in hypervisor
+     * mode.
+     * Therefore we don't need to save the context of an idle VCPU.
+     */
+    if ( is_idle_vcpu(p) )
+        return;
+
+    p2m_ctxt_switch_from(p);
+
+    vtimer_ctxt_switch_from(p);
+
+    save_csr_regs(p);
+}
+
+static void ctxt_switch_to(struct vcpu *n)
+{
+    /*
+     * When the idle VCPU is running, Xen will always stay in hypervisor
+     * mode.
+     * Therefore we don't need to restore the context of an idle VCPU.
+     */
+    if ( is_idle_vcpu(n) )
+        return;

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 421

Quoted 10 lines
xen/arch/riscv/domain.c +10 -0
+
+    /*
+     * If this vCPU last ran on a different pCPU, invalidate its VMID so
+     * vmid_handle_vmenter() assigns a fresh one from the current pCPU's pool.
+     * Without this, two pCPUs could independently assign the same
+     * (generation, vmid) pair, generation counters start at the same value
+     * on all pCPUs and increment independently, causing TLB contamination.
+     */
+    if ( n->arch.last_cpu != smp_processor_id() )
+        vmid_flush_vcpu(n);

I wonder why you need this, when we don't have anything similar in x86/HVM (and at the first glance Arm doesn't have anything similar either).

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 428

Quoted 6 lines
xen/arch/riscv/domain.c +6 -0
+    vtimer_ctxt_switch_to(n);
+
+    restore_csr_regs(n);
+
+    p2m_ctxt_switch_to(n);
+}

In the absenmce of a comment towards the need for this specific order I'd expect these three calls to be ordered the opposite of their counterparts in ctxt_switch_from().

Quoted 58 lines
xen/arch/riscv/domain.c +58 -0
+static void schedule_tail(struct vcpu *prev)
+{
+    unsigned int cpu = smp_processor_id();
+
+    ASSERT(prev != current);
+
+    ctxt_switch_from(prev);
+
+    /*
+     * Mark this CPU in next domain's dirty cpumasks before calling
+     * ctxt_switch_to(). This avoids a race on things like p2m flushing,
+     * which is synchronised on that function.
+     */
+    if ( prev->domain != current->domain )
+    {
+        cpumask_set_cpu(cpu, current->domain->dirty_cpumask);
+
+        /*
+         * Once this hart drops out of prev's dirty_cpumask it stops being a
+         * target of p2m_tlb_flush(), while its TLB may still hold G-stage
+         * translations of prev's domain: neither the vCPU which just ran nor
+         * any other vCPU of that domain which ran here earlier has had its
+         * VMID invalidated. Move the hart to a new VMID generation so that
+         * none of them can be reached again.
+         *
+         * Switching away from the idle vCPU needs no bump: the idle domain
+         * has no p2m of its own, and whatever G-stage entries this hart may
+         * still hold (or speculatively create while HGATP keeps pointing at
+         * the last guest's p2m) are tagged with a VMID which was already made
+         * stale when that guest was switched out. Skipping the bump here also
+         * avoids burning a generation on every pass through idle.
+         */
+        if ( !is_idle_vcpu(prev) )
+            vmid_flush_hart();
+
+        cpumask_clear_cpu(cpu, prev->domain->dirty_cpumask);
+    }
+    write_atomic(&current->dirty_cpu, cpu);
+
+    ctxt_switch_to(current);
+
+    write_atomic(&prev->dirty_cpu, VCPU_CPU_CLEAN);
+
+    current->arch.last_cpu = cpu;
+
+    /*
+     * sched_context_switched() internally uses a spinlock,
+     * which requires interrupts to be enabled.
+     */
+    local_irq_enable();
+
+    sched_context_switched(prev, current);
+}
+
+void context_switch(struct vcpu *prev, struct vcpu *next)
+{
+    ASSERT(local_irq_is_enabled());
+    ASSERT(prev != next);

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 497

Quoted 10 lines
xen/arch/riscv/domain.c +10 -0
+    ASSERT(!vcpu_cpu_dirty(next));
+
+    local_irq_disable();
+
+    set_current(next);
+
+    prev = __context_switch(prev, next);
+
+    schedule_tail(prev);
+}

__context_switch() switches stacks, which can easily collide with code the compiler has emitted. For example, the call to schedule_tail() may not be a tail call, and context_switch()'s return address may have been spilled to the stack (or into one of the s<N> registers). There's a reason Arm and x86 have reset_stack_and_jump().

xen/arch/riscv/entry.S restore_registers: · line 106

Quoted 11 lines
xen/arch/riscv/entry.S +5 -0
@@ -99,3 +99,47 @@ restore_registers:
 
         sret
 END(handle_trap)
+
+/*
+ * struct vcpu *__context_switch(struct vcpu *prev, struct vcpu *next)
+ *
+ * This is called on prev's stack, and returns on next's.

With ra being switched it may also return to other than the caller. If that's really intended, I think it also needs calling out here.

Quoted 28 lines
xen/arch/riscv/entry.S +28 -0
+ * a0 - prev
+ * a1 - next
+ *
+ * Returns prev in a0
+ */
+FUNC(__context_switch)
+        REG_S   s0, VCPU_XEN_SAVED_CONTEXT_S0(a0)
+        REG_S   s1, VCPU_XEN_SAVED_CONTEXT_S1(a0)
+        REG_S   s2, VCPU_XEN_SAVED_CONTEXT_S2(a0)
+        REG_S   s3, VCPU_XEN_SAVED_CONTEXT_S3(a0)
+        REG_S   s4, VCPU_XEN_SAVED_CONTEXT_S4(a0)
+        REG_S   s5, VCPU_XEN_SAVED_CONTEXT_S5(a0)
+        REG_S   s6, VCPU_XEN_SAVED_CONTEXT_S6(a0)
+        REG_S   s7, VCPU_XEN_SAVED_CONTEXT_S7(a0)
+        REG_S   s8, VCPU_XEN_SAVED_CONTEXT_S8(a0)
+        REG_S   s9, VCPU_XEN_SAVED_CONTEXT_S9(a0)
+        REG_S   s10, VCPU_XEN_SAVED_CONTEXT_S10(a0)
+        REG_S   s11, VCPU_XEN_SAVED_CONTEXT_S11(a0)
+        REG_S   sp, VCPU_XEN_SAVED_CONTEXT_SP(a0)
+        REG_S   ra, VCPU_XEN_SAVED_CONTEXT_RA(a0)
+
+        REG_L   s0, VCPU_XEN_SAVED_CONTEXT_S0(a1)
+        REG_L   s1, VCPU_XEN_SAVED_CONTEXT_S1(a1)
+        REG_L   s2, VCPU_XEN_SAVED_CONTEXT_S2(a1)
+        REG_L   s3, VCPU_XEN_SAVED_CONTEXT_S3(a1)
+        REG_L   s4, VCPU_XEN_SAVED_CONTEXT_S4(a1)
+        REG_L   s5, VCPU_XEN_SAVED_CONTEXT_S5(a1)
+        REG_L   s6, VCPU_XEN_SAVED_CONTEXT_S6(a1)

xen/arch/riscv/entry.S restore_registers: · line 145

Quoted 10 lines
xen/arch/riscv/entry.S +10 -0
+        REG_L   s7, VCPU_XEN_SAVED_CONTEXT_S7(a1)
+        REG_L   s8, VCPU_XEN_SAVED_CONTEXT_S8(a1)
+        REG_L   s9, VCPU_XEN_SAVED_CONTEXT_S9(a1)
+        REG_L   s10, VCPU_XEN_SAVED_CONTEXT_S10(a1)
+        REG_L   s11, VCPU_XEN_SAVED_CONTEXT_S11(a1)
+        REG_L   sp, VCPU_XEN_SAVED_CONTEXT_SP(a1)
+        REG_L   ra, VCPU_XEN_SAVED_CONTEXT_RA(a1)
+
+        ret
+END(__context_switch)

What about gp and tp?

xen/arch/riscv/include/asm/system.h static inline bool local_irq_is_enabled(void) · line 79

Quoted 7 lines
xen/arch/riscv/include/asm/system.h +1 -0
@@ -76,6 +76,10 @@ static inline bool local_irq_is_enabled(void)
 
 #define arch_fetch_and_add(x, v) __sync_fetch_and_add(x, v)
 
+struct vcpu;

I don't think this is needed, as ...

xen/arch/riscv/include/asm/system.h static inline bool local_irq_is_enabled(void) · line 81

Quoted 1 line
xen/arch/riscv/include/asm/system.h +1 -0
+struct vcpu *__context_switch(struct vcpu *prev, struct vcpu *next);

... parsing of the return type will make the struct known (before parameters are parsed).

Also - can't next be pointer-to-const?

Jan

#82 lore raw

Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching

Quoted 32 lines · Jan Beulich
Quoted 31 lines · Oleksii Kurochko
xen/arch/riscv/domain.c +31 -0
+static void ctxt_switch_from(struct vcpu *p)
+{
+    /*
+     * When the idle VCPU is running, Xen will always stay in hypervisor
+     * mode.
+     * Therefore we don't need to save the context of an idle VCPU.
+     */
+    if ( is_idle_vcpu(p) )
+        return;
+
+    p2m_ctxt_switch_from(p);
+
+    vtimer_ctxt_switch_from(p);
+
+    save_csr_regs(p);
+}
+
+static void ctxt_switch_to(struct vcpu *n)
+{
+    /*
+     * When the idle VCPU is running, Xen will always stay in hypervisor
+     * mode.
+     * Therefore we don't need to restore the context of an idle VCPU.
+     */
+    if ( is_idle_vcpu(n) )
+        return;
+
+    /*
+     * If this vCPU last ran on a different pCPU, invalidate its VMID so
+     * vmid_handle_vmenter() assigns a fresh one from the current pCPU's pool.
+     * Without this, two pCPUs could independently assign the same
Quoted 8 lines

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 421

Quoted 5 lines
xen/arch/riscv/domain.c +5 -0
+     * (generation, vmid) pair, generation counters start at the same value
+     * on all pCPUs and increment independently, causing TLB contamination.
+     */
+    if ( n->arch.last_cpu != smp_processor_id() )
+        vmid_flush_vcpu(n);

I wonder why you need this, when we don't have anything similar in x86/HVM (and at the first glance Arm doesn't have anything similar either).

x86 does have the equivalent: vmx_do_resume() calls hvm_asid_flush_vcpu() in the active_cpu != smp_processor_id() branch, and svm_do_resume() does the same when launch_core != smp_processor_id() ("Migrating to another ASID domain. Request a new ASID."). The RISC-V VMID allocator follows the x86 ASID scheme: VMIDs are a per-pCPU resource with a per-pCPU generation, so a (generation, vmid) pair obtained on one pCPU means nothing on another. Arm doesn't need this because it allocates a single VMID per domain from a global bitmap.

Also, note that I've update a little bit how VMIDs are flushed here [1] but this check still present IIURC.

[1] https://lore.kernel.org/xen-devel/[email protected]/T/#m2c06e58c03a09022af112388be3585bf3ae6e4dc

Quoted 11 lines

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 428

Quoted 7 lines
xen/arch/riscv/domain.c +6 -0
+    vtimer_ctxt_switch_to(n);
+
+    restore_csr_regs(n);
+
+    p2m_ctxt_switch_to(n);
+}

In the absenmce of a comment towards the need for this specific order I'd expect these three calls to be ordered the opposite of their counterparts in ctxt_switch_from().

I will put restore_csr_regs(n) (and rename it to csr_regs_ctxt_switch_to(n)) before vtimer_ctxt_switch_to(). There is no any specific requirement to be ordered in the way it is now.

Quoted 67 lines
Quoted 67 lines
xen/arch/riscv/domain.c +66 -0
+static void schedule_tail(struct vcpu *prev)
+{
+    unsigned int cpu = smp_processor_id();
+
+    ASSERT(prev != current);
+
+    ctxt_switch_from(prev);
+
+    /*
+     * Mark this CPU in next domain's dirty cpumasks before calling
+     * ctxt_switch_to(). This avoids a race on things like p2m flushing,
+     * which is synchronised on that function.
+     */
+    if ( prev->domain != current->domain )
+    {
+        cpumask_set_cpu(cpu, current->domain->dirty_cpumask);
+
+        /*
+         * Once this hart drops out of prev's dirty_cpumask it stops being a
+         * target of p2m_tlb_flush(), while its TLB may still hold G-stage
+         * translations of prev's domain: neither the vCPU which just ran nor
+         * any other vCPU of that domain which ran here earlier has had its
+         * VMID invalidated. Move the hart to a new VMID generation so that
+         * none of them can be reached again.
+         *
+         * Switching away from the idle vCPU needs no bump: the idle domain
+         * has no p2m of its own, and whatever G-stage entries this hart may
+         * still hold (or speculatively create while HGATP keeps pointing at
+         * the last guest's p2m) are tagged with a VMID which was already made
+         * stale when that guest was switched out. Skipping the bump here also
+         * avoids burning a generation on every pass through idle.
+         */
+        if ( !is_idle_vcpu(prev) )
+            vmid_flush_hart();
+
+        cpumask_clear_cpu(cpu, prev->domain->dirty_cpumask);
+    }
+    write_atomic(&current->dirty_cpu, cpu);
+
+    ctxt_switch_to(current);
+
+    write_atomic(&prev->dirty_cpu, VCPU_CPU_CLEAN);
+
+    current->arch.last_cpu = cpu;
+
+    /*
+     * sched_context_switched() internally uses a spinlock,
+     * which requires interrupts to be enabled.
+     */
+    local_irq_enable();
+
+    sched_context_switched(prev, current);
+}
+
+void context_switch(struct vcpu *prev, struct vcpu *next)
+{
+    ASSERT(local_irq_is_enabled());
+    ASSERT(prev != next);
+    ASSERT(!vcpu_cpu_dirty(next));
+
+    local_irq_disable();
+
+    set_current(next);
+
+    prev = __context_switch(prev, next);
+
Quoted 8 lines

xen/arch/riscv/domain.c int arch_domain_create(struct domain *d, · line 497

Quoted 2 lines
xen/arch/riscv/domain.c +2 -0
+    schedule_tail(prev);
+}

__context_switch() switches stacks, which can easily collide with code the compiler has emitted. For example, the call to schedule_tail() may not be a tail call, and context_switch()'s return address may have been spilled to the stack (or into one of the s<N> registers). There's a reason Arm and x86 have reset_stack_and_jump().

RISC-V will have reset_stack_and_jump() that too but just introduced later and will be used for different use case (in continue_new_vcpu() introduced later in this patch series). But as the Arm RISC-V doesn't use reset_stack_and_jump() in context_switch().

This follows the Arm model: every vCPU has its own Xen stack, and from the incoming vCPU's point of view __context_switch() is ABI-conforming. It restores exactly the sp/ra/s0-s11 that vCPU had when it itself called __context_switch() from context_switch(). So after the return we are in next's own context_switch() frame, and anything the compiler spilled there (ra included) belongs to next. The only exception is a vCPU which has never run: its ra points at continue_new_vcpu() on an empty stack, and that's where reset_stack_and_jump() is needed, as on Arm. I'll make continue_new_vcpu() noreturn accordingly. x86 differs because its stacks are per-pCPU (IIUC), hence its context_switch() can't return.

Here is some diagram for better understanding:
vCPU A (stack A) vCPU B (stack B, switched out earlier)
schedule() schedule()
- context_switch(A, B) - context_switch(B, X)
[A's frame: ra, s-regs] [B's frame: ra, s-regs]
`- __context_switch() --------> "returns" here
(save A, load B) schedule_tail(prev = A)
ld ra <- B's frame (B's own ra) ret -> B's sched_context_switch()
-> ... -> back into B

Quoted 5 lines
Quoted 5 lines
xen/arch/riscv/entry.S +0 -0
@@ -99,3 +99,47 @@ restore_registers:
 
Quoted 10 lines

xen/arch/riscv/entry.S restore_registers: · line 106

Quoted 7 lines
xen/arch/riscv/entry.S +5 -0
          sret
  END(handle_trap)
+
+/*
+ * struct vcpu *__context_switch(struct vcpu *prev, struct vcpu *next)
+ *
+ * This is called on prev's stack, and returns on next's.

With ra being switched it may also return to other than the caller. If that's really intended, I think it also needs calling out here.

Yes, it's intended. Normally it returns into next's own context_switch() (where next itself last called __context_switch()), and for a vCPU which has never run it returns to continue_new_vcpu(). I'll update the comment to:

* This is called on prev's stack, and returns on next's. As ra is
* switched too, it doesn't return to its caller: it returns to where
* next last called it from, i.e. into next's own context_switch(), or,
* for a vCPU which has never run, to continue_new_vcpu() with an empty
* stack.

Quoted 33 lines
Quoted 33 lines
xen/arch/riscv/entry.S +32 -0
+ * a0 - prev
+ * a1 - next
+ *
+ * Returns prev in a0
+ */
+FUNC(__context_switch)
+        REG_S   s0, VCPU_XEN_SAVED_CONTEXT_S0(a0)
+        REG_S   s1, VCPU_XEN_SAVED_CONTEXT_S1(a0)
+        REG_S   s2, VCPU_XEN_SAVED_CONTEXT_S2(a0)
+        REG_S   s3, VCPU_XEN_SAVED_CONTEXT_S3(a0)
+        REG_S   s4, VCPU_XEN_SAVED_CONTEXT_S4(a0)
+        REG_S   s5, VCPU_XEN_SAVED_CONTEXT_S5(a0)
+        REG_S   s6, VCPU_XEN_SAVED_CONTEXT_S6(a0)
+        REG_S   s7, VCPU_XEN_SAVED_CONTEXT_S7(a0)
+        REG_S   s8, VCPU_XEN_SAVED_CONTEXT_S8(a0)
+        REG_S   s9, VCPU_XEN_SAVED_CONTEXT_S9(a0)
+        REG_S   s10, VCPU_XEN_SAVED_CONTEXT_S10(a0)
+        REG_S   s11, VCPU_XEN_SAVED_CONTEXT_S11(a0)
+        REG_S   sp, VCPU_XEN_SAVED_CONTEXT_SP(a0)
+        REG_S   ra, VCPU_XEN_SAVED_CONTEXT_RA(a0)
+
+        REG_L   s0, VCPU_XEN_SAVED_CONTEXT_S0(a1)
+        REG_L   s1, VCPU_XEN_SAVED_CONTEXT_S1(a1)
+        REG_L   s2, VCPU_XEN_SAVED_CONTEXT_S2(a1)
+        REG_L   s3, VCPU_XEN_SAVED_CONTEXT_S3(a1)
+        REG_L   s4, VCPU_XEN_SAVED_CONTEXT_S4(a1)
+        REG_L   s5, VCPU_XEN_SAVED_CONTEXT_S5(a1)
+        REG_L   s6, VCPU_XEN_SAVED_CONTEXT_S6(a1)
+        REG_L   s7, VCPU_XEN_SAVED_CONTEXT_S7(a1)
+        REG_L   s8, VCPU_XEN_SAVED_CONTEXT_S8(a1)
+        REG_L   s9, VCPU_XEN_SAVED_CONTEXT_S9(a1)
+        REG_L   s10, VCPU_XEN_SAVED_CONTEXT_S10(a1)
Quoted 8 lines

xen/arch/riscv/entry.S restore_registers: · line 145

Quoted 6 lines
xen/arch/riscv/entry.S +6 -0
+        REG_L   s11, VCPU_XEN_SAVED_CONTEXT_S11(a1)
+        REG_L   sp, VCPU_XEN_SAVED_CONTEXT_SP(a1)
+        REG_L   ra, VCPU_XEN_SAVED_CONTEXT_RA(a1)
+
+        ret
+END(__context_switch)

What about gp and tp?

tp points to this hart's pcpu_info (set up once per hart by setup_tp()), i.e. it's per-pCPU rather than per-vCPU state. __context_switch() starts and ends on the same hart, so tp has to be left alone.

gp isn't used by Xen at all: there's no __global_pointer$ in the linker script, so no gp-relative relaxation happens, and the compiler never allocates gp.

Neither of them is callee-saved per the psABI, so there's nothing to preserve across the call. The guest's gp/tp are part of the guest state and are going to be saved/restored via cpu_user_regs by the trap entry/exit path.

Quoted 7 lines
Quoted 7 lines
xen/arch/riscv/include/asm/system.h +0 -0
@@ -76,6 +76,10 @@ static inline bool local_irq_is_enabled(void)
 
  #define arch_fetch_and_add(x, v) __sync_fetch_and_add(x, v)
 
Quoted 8 lines

xen/arch/riscv/include/asm/system.h static inline bool local_irq_is_enabled(void) · line 79

Quoted 1 line
xen/arch/riscv/include/asm/system.h +1 -0
+struct vcpu;

I don't think this is needed, as ...

xen/arch/riscv/include/asm/system.h static inline bool local_irq_is_enabled(void) · line 81

Quoted 1 line
xen/arch/riscv/include/asm/system.h +1 -0
+struct vcpu *__context_switch(struct vcpu *prev, struct vcpu *next);

... parsing of the return type will make the struct known (before parameters are parsed).

Make sense to me. I will drop forward declaration.

Quoted 2 lines

Also - can't next be pointer-to-const?

It could be. I will add const.

Thanks!

~ Oleksii

#83 lore raw

PATCH v2 13/39 xen/riscv: save and restore AIA state on vCPU context switch

In reply to Oleksii Kurochko

vsiselect and hviprio{1,2} are per-hart CSRs which a guest can change, so they have to be part of the vCPU context:
- vsiselect is written directly by VS-mode through siselect;
- hviprio1 and hviprio2 hold the priorities of the local interrupts which VS-mode reaches through the iprio array of vsiselect/vsireg, so writes the guest performs there land in these CSRs.

Without saving them, one vCPU's selector leaks into another vCPU's vsireg accesses and one guest's interrupt priorities apply to the next guest which runs on the same hart.

Whether the CSRs may be touched at all is gated by hstateen0 when Smstateen is implemented: SVSLCT for vsiselect/vsireg and AIA for the rest of the AIA state. A bit staying clear in v->arch.hstateen0 means M-mode denied the access (see vcpu_csr_init()), and in that case the CSR can't be accessed from HS-mode either, hence the gating helper.

vsie, hviprio1 and hviprio2 are 64-bit registers on both RV32 and RV64, so store them as uint64_t and use csr_{read,write}64() rather than truncating them to XLEN.

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

---
 xen/arch/riscv/domain.c             | 44 +++++++++++++++++++++++++++--
 xen/arch/riscv/include/asm/domain.h |  5 +++-
 2 files changed, 46 insertions(+), 3 deletions(-)
xen/arch/riscv/domain.c +42 -2
index 91a46d630f44..4afdfb4d09ab 100644
@@ -333,6 +333,28 @@ int arch_domain_create(struct domain *d,
     return rc;
 }
 
+/*
+ * vsiselect and hviprio{1,2} are per-hart, but the guest can change them:
+ * vsiselect directly through siselect, and hviprio{1,2} through the iprio
+ * array which vsiselect/vsireg give VS-mode access to. Hence they are part
+ * of the vCPU context.
+ *
+ * When Smstateen is implemented, hstateen0 gates that access: SVSLCT for
+ * vsiselect/vsireg and AIA for the rest of the AIA state. A bit staying clear
+ * in v->arch.hstateen0 means M-mode denied it (see vcpu_csr_init()), and then
+ * the corresponding CSR can't be accessed from HS-mode either.
+ */
+static bool vcpu_has_aia_state(const struct vcpu *v, register_t hstateen0_bit)
+{
+    if ( !riscv_isa_extension_available(NULL, RISCV_ISA_EXT_ssaia) )
+        return false;
+
+    if ( !riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        return true;
+
+    return v->arch.hstateen0 & hstateen0_bit;
+}
+
 static void save_csr_regs(struct vcpu *vcpu)
 {
     /*
@@ -354,12 +376,21 @@ static void save_csr_regs(struct vcpu *vcpu)
     vcpu->arch.hvip = csr_read(CSR_HVIP);
 
     vcpu->arch.vsstatus = csr_read(CSR_VSSTATUS);
-    vcpu->arch.vsie = csr_read(CSR_VSIE);
+    vcpu->arch.vsie = csr_read64(CSR_VSIE);
     vcpu->arch.vstvec = csr_read(CSR_VSTVEC);
     vcpu->arch.vsscratch = csr_read(CSR_VSSCRATCH);
     vcpu->arch.vscause = csr_read(CSR_VSCAUSE);
     vcpu->arch.vstval = csr_read(CSR_VSTVAL);
     vcpu->arch.vsepc = csr_read(CSR_VSEPC);
+
+    if ( vcpu_has_aia_state(vcpu, SMSTATEEN0_SVSLCT) )
+        vcpu->arch.vsiselect = csr_read(CSR_VSISELECT);
+
+    if ( vcpu_has_aia_state(vcpu, SMSTATEEN0_AIA) )
+    {
+        vcpu->arch.hviprio1 = csr_read64(CSR_HVIPRIO1);
+        vcpu->arch.hviprio2 = csr_read64(CSR_HVIPRIO2);
+    }
 }
 
 static void restore_csr_regs(struct vcpu *vcpu)
@@ -375,12 +406,21 @@ static void restore_csr_regs(struct vcpu *vcpu)
         csr_write(CSR_HSTATEEN0, vcpu->arch.hstateen0);
 
     csr_write(CSR_VSSTATUS, vcpu->arch.vsstatus);
-    csr_write(CSR_VSIE, vcpu->arch.vsie);
+    csr_write64(CSR_VSIE, vcpu->arch.vsie);
     csr_write(CSR_VSTVEC, vcpu->arch.vstvec);
     csr_write(CSR_VSSCRATCH, vcpu->arch.vsscratch);
     csr_write(CSR_VSCAUSE, vcpu->arch.vscause);
     csr_write(CSR_VSTVAL, vcpu->arch.vstval);
     csr_write(CSR_VSEPC, vcpu->arch.vsepc);
+
+    if ( vcpu_has_aia_state(vcpu, SMSTATEEN0_SVSLCT) )
+        csr_write(CSR_VSISELECT, vcpu->arch.vsiselect);
+
+    if ( vcpu_has_aia_state(vcpu, SMSTATEEN0_AIA) )
+    {
+        csr_write64(CSR_HVIPRIO1, vcpu->arch.hviprio1);
+        csr_write64(CSR_HVIPRIO2, vcpu->arch.hviprio2);
+    }
 }
 
 static void ctxt_switch_from(struct vcpu *p)
xen/arch/riscv/include/asm/domain.h +4 -1
index 90ed584bb844..23e301782068 100644
@@ -70,11 +70,14 @@ struct arch_vcpu {
     register_t hstateen0;
     uint64_t   htimedelta;
     register_t hvip;
+    uint64_t   hviprio1;
+    uint64_t   hviprio2;
 
     register_t vsatp;
     register_t vscause;
     register_t vsepc;
-    register_t vsie;
+    uint64_t   vsie;
+    register_t vsiselect;
     register_t vsscratch;
     register_t vsstatus;
     register_t vstval;
Signature · 1 line
2.55.0
#84 lore raw

Re: [PATCH v2 13/39] xen/riscv: save and restore AIA state on vCPU context switch

Quoted 2 lines

vsiselect and hviprio{1,2} are per-hart CSRs which a guest can change, so they have to be part of the vCPU context:

Where in the spec did you see that? Because in AIA spec section 6.3.1, it is written that "When vsiselect has a value in the range 0x30-0x3F, an attempt from VS-mode to access sireg (really vsireg) causes a virtual instruction exception" and this even when hstateen0.CSRIND is set as hstateen0 just control whether a guest/S-mode is allowed to access a CSR (exactly as you described below).

Therefore, the hypervisor has two options to modify the priority of a major irq:
- emulate the iprio array in software.
- Use hviprio1/hviprio2 (only 10 irqs configurable).

But the guest shouldn't be able to modify h CSRs at all, in any case, or I may have misunderstood a part of the spec.

For the moment I don't see any catch of possible instruction exception in do_trap().

Quoted 4 lines

- vsiselect is written directly by VS-mode through siselect;
- hviprio1 and hviprio2 hold the priorities of the local interrupts which VS-mode reaches through the iprio array of vsiselect/vsireg, so writes the guest performs there land in these CSRs.

hviprio1 and hviprio2 hold priorities for interrupts 1 (SSI), 5 (STI), 13 (counter overflow), and 14-23 (local) so calling all of them "local" is wrong.

Quoted 6 lines

Without saving them, one vCPU's selector leaks into another vCPU's vsireg accesses and one guest's interrupt priorities apply to the next guest which runs on the same hart.

Whether the CSRs may be touched at all is gated by hstateen0 when Smstateen is implemented: SVSLCT for vsiselect/vsireg and AIA for the rest of the AIA

I couldn't find any reference to SVSLCT in the spec. I assume you wanted to refer to CSRIND and SVSLCT is an OpenSBI's own nickname.

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

Re: [PATCH v2 13/39] xen/riscv: save and restore AIA state on vCPU context switch

Quoted 8 lines · Baptiste Le Duc
Quoted 2 lines

vsiselect and hviprio{1,2} are per-hart CSRs which a guest can change, so they have to be part of the vCPU context:

Where in the spec did you see that? Because in AIA spec section 6.3.1, it is written that "When vsiselect has a value in the range 0x30-0x3F, an attempt from VS-mode to access sireg (really vsireg) causes a virtual instruction exception" and this even when hstateen0.CSRIND is set as hstateen0 just control whether a guest/S-mode is allowed to access a CSR (exactly as you described below).

Your understanding is correct, it was me who confused the things. Sorry for that.

Quoted 11 lines

Therefore, the hypervisor has two options to modify the priority of a major irq:
- emulate the iprio array in software.
- Use hviprio1/hviprio2 (only 10 irqs configurable).

But the guest shouldn't be able to modify h CSRs at all, in any case, or I may have misunderstood a part of the spec.

For the moment I don't see any catch of possible instruction exception in do_trap().

There is no such because we don't emulate range 0x30-0x3F. We don't have such use cases now.

I think that I have to recheck what should be saved/restored now.

There is no need to save/restore CSR_HVIPRIO* during context switch as we don't have support of handling of 0x30-0x3f. I will introduce that later when we really will need that.

VSISELECT should be save/restored then only in this patch as we have hstateen0.SMSTATEEN0_SVSLCT set so guest could change VSISELECT directly so we need to store/restore.

Am I missing something?

With having only VSISELECT saved/restored in this patch I think the commit message should be:

xen/riscv: save and restore vsiselect on vCPU context switch

vsiselect is a per-hart CSR which a guest changes on its own: when V=1, VS-mode accesses to siselect are really accesses to vsiselect. Architecturally a vCPU has to find there the value it last wrote, but as long as the CSR isn't part of the vCPU context it finds whatever selector the vCPU which ran on the hart before it left behind. A guest which writes siselect, is descheduled and then reads sireg without rewriting siselect therefore reaches a register it never selected, and it can also observe another guest's selector value.

When Smstateen is implemented, access to vsiselect and vsireg is gated by hstateen0.CSRIND (bit 60, SMSTATEEN0_SVSLCT in Xen's headers), and v->arch.hstateen0 holds the bits vcpu_csr_init() ended up with. A clear bit there covers the two cases in which the CSR has to be skipped:

- Xen didn't hand the guest access to it, so the guest can't have changed

     the CSR and there is no state to preserve;

- M-mode denied the state altogether. Smstateen makes a bit which is zero in mstateen0 read-only zero in hstateen0, and a zero bit in mstateen0 traps accesses from every privilege mode less privileged than M-mode, HS-mode included, so Xen couldn't even read the CSR to save it.

Without Smstateen no bit controls access to the CSR, so it is saved and restored whenever Ssaia is available.

---
Changes in v3:
- Update the commit message.
- Save and restore only VSISELECT.
---
Changes in v2:
- New patch.
---

xen/arch/riscv/domain.c +28 -0
index 0ad851ee0f5f..1085ef152b8b 100644
@@ -327,6 +327,28 @@ int arch_domain_create(struct domain *d,
     return rc;
 }
 
+/*
+ * vsiselect is a per-hart CSR, but a guest changes it on its own: when V=1,
+ * VS-mode accesses to siselect are really accesses to vsiselect. Hence it is
+ * part of the vCPU context.
+ *
+ * When Smstateen is implemented, hstateen0.CSRIND (SMSTATEEN0_SVSLCT) gates
+ * that access, and a bit staying clear in v->arch.hstateen0 (see
+ * vcpu_csr_init()) means either that the guest was never given access to the
+ * CSR, and so can't have changed it, or that M-mode denied the state
+ * altogether, in which case the CSR can't be accessed from HS-mode either.
+ */
+static bool vcpu_can_access_vsiselect(const struct vcpu *v)
+{
+    if ( !riscv_isa_extension_available(NULL, RISCV_ISA_EXT_ssaia) )
+        return false;
+
+    if ( !riscv_isa_extension_available(NULL, RISCV_ISA_EXT_smstateen) )
+        return true;
+
+    return v->arch.hstateen0 & SMSTATEEN0_SVSLCT;
+}
+
 static void save_csr_regs(struct vcpu *p)
 {
     /*
@@ -354,6 +376,9 @@ static void save_csr_regs(struct vcpu *p)
     p->arch.vscause = csr_read(CSR_VSCAUSE);
     p->arch.vstval = csr_read(CSR_VSTVAL);
     p->arch.vsepc = csr_read(CSR_VSEPC);
+
+    if ( vcpu_can_access_vsiselect(p) )
+        p->arch.vsiselect = csr_read(CSR_VSISELECT);
 }
 
 static void restore_csr_regs(struct vcpu *n)
@@ -375,6 +400,9 @@ static void restore_csr_regs(struct vcpu *n)
     csr_write(CSR_VSCAUSE, n->arch.vscause);
     csr_write(CSR_VSTVAL, n->arch.vstval);
     csr_write(CSR_VSEPC, n->arch.vsepc);
+
+    if ( vcpu_can_access_vsiselect(n) )
+        csr_write(CSR_VSISELECT, n->arch.vsiselect);
 }
 
 static void ctxt_switch_from(struct vcpu *p)
xen/arch/riscv/include/asm/domain.h +1 -0
index 58d1e8076876..b0824d7f9add 100644
@@ -75,6 +75,7 @@ struct arch_vcpu {
     register_t vscause;
     register_t vsepc;
     uint64_t   vsie;
+    register_t vsiselect;
     register_t vsscratch;
     register_t vsstatus;
     register_t vstval;

Does it make sense to you?

Quoted 8 lines
Quoted 5 lines

- vsiselect is written directly by VS-mode through siselect;
- hviprio1 and hviprio2 hold the priorities of the local interrupts which VS-mode reaches through the iprio array of vsiselect/vsireg, so writes the guest performs there land in these CSRs.

hviprio1 and hviprio2 hold priorities for interrupts 1 (SSI), 5 (STI), 13 (counter overflow), and 14-23 (local) so calling all of them "local" is wrong.

Agree, it is incorrect to call them "local"

Quoted 9 lines
Quoted 6 lines

Without saving them, one vCPU's selector leaks into another vCPU's vsireg accesses and one guest's interrupt priorities apply to the next guest which runs on the same hart.

Whether the CSRs may be touched at all is gated by hstateen0 when Smstateen is implemented: SVSLCT for vsiselect/vsireg and AIA for the rest of the AIA

I couldn't find any reference to SVSLCT in the spec. I assume you wanted to refer to CSRIND and SVSLCT is an OpenSBI's own nickname.

Indeed, SVSLCT is the OpenSBI nickname/macro definition for this feature and CSRIND would be better to use in commit message.

Thanks.

~ Oleksii

#86 lore raw

PATCH v2 14/39 xen/riscv: introduce vintc_ctxt_switch_{from,to}()

In reply to Oleksii Kurochko

Virtual interrupt controller state must be preserved across vCPU context switches.

Introduce vintc_ctxt_switch_{from,to}() wrappers around new ctxt_switch_{from,to}() hooks in struct vintc_ops, and call them from the context switch path, so that this state can be saved/restored without knowing which vINTC variant a domain uses.

No vINTC variant implements the hooks yet: the vAPLIC implementation is added separately.

---
Changes in v2:
- Update the commit message.
- s/vintc_state_{save,restore}/vintc_ctxt_switch_{to,from}.
- s/{re}store_state/ctxt_switch_{to,from} for vintc_ops.
- s/vcpu/v for vintc_ctxt_switch_{to,from}() arguments.
---

---
 xen/arch/riscv/domain.c           |  4 ++++
 xen/arch/riscv/include/asm/intc.h |  9 +++++++++
 xen/arch/riscv/intc.c             | 14 ++++++++++++++
 3 files changed, 27 insertions(+)
xen/arch/riscv/domain.c +4 -0
index 4afdfb4d09ab..2dfe4c2e72ce 100644
@@ -437,6 +437,8 @@ static void ctxt_switch_from(struct vcpu *p)
 
     vtimer_ctxt_switch_from(p);
 
+    vintc_ctxt_switch_from(p);
+
     save_csr_regs(p);
 }
 
@@ -462,6 +464,8 @@ static void ctxt_switch_to(struct vcpu *n)
 
     vtimer_ctxt_switch_to(n);
 
+    vintc_ctxt_switch_to(n);
+
     restore_csr_regs(n);
 
     p2m_ctxt_switch_to(n);
xen/arch/riscv/include/asm/intc.h +9 -0
index 1bfba7c6155b..62e1410156c7 100644
@@ -64,6 +64,12 @@ struct vintc_ops {
 
     /* Deinitialize some vINTC-related stuff for a vCPU */
     void (*vcpu_deinit)(struct vcpu *v);
+
+    /* Save vINTC state of the vCPU being switched out */
+    void (*ctxt_switch_from)(struct vcpu *v);
+
+    /* Restore vINTC state of the vCPU being switched in */
+    void (*ctxt_switch_to)(struct vcpu *v);
 };
 
 struct vintc {
@@ -91,4 +97,7 @@ void domain_vintc_deinit(struct domain *d);
 
 int vintc_reserve_virq(const struct domain *d, unsigned int virq);
 
+void vintc_ctxt_switch_from(struct vcpu *v);
+void vintc_ctxt_switch_to(struct vcpu *v);
+
 #endif /* ASM__RISCV__INTERRUPT_CONTOLLER_H */
xen/arch/riscv/intc.c +14 -0
index bca83b4f4fa3..9fff501b9c25 100644
@@ -178,3 +178,17 @@ int __overlay_init vintc_reserve_virq(const struct domain *d,
 
     return test_and_set_bit(virq, d->arch.vintc->used_irqs) ? -EEXIST : 0;
 }
+
+void vintc_ctxt_switch_from(struct vcpu *v)
+{
+    const struct vintc_ops *ops = v->domain->arch.vintc->ops;
+
+    ops->ctxt_switch_from(v);
+}
+
+void vintc_ctxt_switch_to(struct vcpu *v)
+{
+    const struct vintc_ops *ops = v->domain->arch.vintc->ops;
+
+    ops->ctxt_switch_to(v);
+}
Signature · 1 line
2.55.0
#87 lore raw

Re: [PATCH v2 14/39] xen/riscv: introduce vintc_ctxt_switch_{from,to}()

Quoted 10 lines

Virtual interrupt controller state must be preserved across vCPU context switches.

Introduce vintc_ctxt_switch_{from,to}() wrappers around new ctxt_switch_{from,to}() hooks in struct vintc_ops, and call them from the context switch path, so that this state can be saved/restored without knowing which vINTC variant a domain uses.

No vINTC variant implements the hooks yet: the vAPLIC implementation is added separately.

So this patch couldn't be applied alone as, at the time of this commit, you only set in vaplic.c:
static const struct vintc_ops vintc_ops = {
.vcpu_init = vcpu_imsic_init,
.vcpu_deinit = vcpu_imsic_deinit,
};

So ops->ctxt_switch_from(v) or ops->ctxt_switch_to(v) will try to deference NULL pointer causing segfault. I don't know if it's matter but worth to mention somewhere.

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

Re: [PATCH v2 14/39] xen/riscv: introduce vintc_ctxt_switch_{from,to}()

Quoted 16 lines · Baptiste Le Duc
Quoted 10 lines

Virtual interrupt controller state must be preserved across vCPU context switches.

Introduce vintc_ctxt_switch_{from,to}() wrappers around new ctxt_switch_{from,to}() hooks in struct vintc_ops, and call them from the context switch path, so that this state can be saved/restored without knowing which vINTC variant a domain uses.

No vINTC variant implements the hooks yet: the vAPLIC implementation is added separately.

So this patch couldn't be applied alone as, at the time of this commit, you only set in vaplic.c:
static const struct vintc_ops vintc_ops = {
.vcpu_init = vcpu_imsic_init,
.vcpu_deinit = vcpu_imsic_deinit,
};

Quoted 4 lines

So ops->ctxt_switch_from(v) or ops->ctxt_switch_to(v) will try to deference NULL pointer causing segfault. I don't know if it's matter but worth to mention somewhere.

Just abstraction is introduced here and context switch isn't happen for now so we are safe.

~ Oleksii

Acked-by on v2 14/39
#89 lore raw

Re: [PATCH v2 14/39] xen/riscv: introduce vintc_ctxt_switch_{from,to}()

In reply to Oleksii Kurochko
Quoted 8 lines · Oleksii Kurochko

Virtual interrupt controller state must be preserved across vCPU context switches.

Introduce vintc_ctxt_switch_{from,to}() wrappers around new ctxt_switch_{from,to}() hooks in struct vintc_ops, and call them from the context switch path, so that this state can be saved/restored without knowing which vINTC variant a domain uses.

Quoted 4 lines

No vINTC variant implements the hooks yet: the vAPLIC implementation is added separately.

Also in case you decide to ...

Quoted 6 lines

---
Changes in v2:
- Update the commit message.
- s/vintc_state_{save,restore}/vintc_ctxt_switch_{to,from}.
- s/{re}store_state/ctxt_switch_{to,from} for vintc_ops.
- s/vcpu/v for vintc_ctxt_switch_{to,from}() arguments.

... rename them again to n / p.

Jan

#90 lore raw

PATCH v2 15/39 xen/riscv: add IMSIC vCPU context switch handlers

In reply to Oleksii Kurochko

IMSIC state currently needs to track only which physical CPU owns a vCPU's IMSIC guest interrupt file, as the CPU id is part of the physical address the file is mapped at.

Add imsic_ctxt_switch_from() to record that CPU when a vCPU is switched out. A vCPU running on the s/w VS-file has no h/w file bound to a CPU, so there is nothing to record for it. The recorded value stays unused until vCPU migration support, which needs it to find the file to move away from, is added later.

imsic_ctxt_switch_to() has nothing to do: by the time a vCPU is switched in, VGEIN is already assigned to it and its guest interrupt file is already mapped. Work is only required once a vCPU can move to a different CPU, which means recalculating VGEIN and remapping the file; that is handled separately by the vCPU migration patches.

Install both as the ctxt_switch_{from,to} hooks of struct vintc_ops. MSI delivery is the only mode Xen supports ( aplic_init() panics on an APLIC without an "msi-parent" property, and a guest's domaincfg.DM reads back as a fixed one) so the vAPLIC state to save and restore is always the IMSIC one and no vAPLIC-level forwarder is needed. Being indirect call targets, both handlers get cf_check.

---
Changes in v2:
- s/imsic_state_{save,restore}/imsic_ctxt_switch_{from,to}: the old names suggested saving and restoring register state, which isn't what these functions do.
- Fix the comment in imsic_ctxt_switch_from(): it explained the ->vsfile_cpu sentinel while the code checks ->guest_file_id.
- Adapt to ->vsfile_cpu holding v->processor instead of a hartid.
- Add cf_check as both are indirect call targets now.
- Fold in the vintc_ops hook-up, which was a separate patch in v1. It no longer adds vaplic_state_{save,restore}() forwarders: the BUG_ON("unimplemented") path in them was unreachable and has_msi_support() was an MMIO read done on every context switch.
- Drop the claim that the not-yet-supported case is guarded by a BUG_ON(); there is no such BUG_ON().
- Update the subject accordingly.
---

---
 xen/arch/riscv/imsic.c             | 23 +++++++++++++++++++++++
 xen/arch/riscv/include/asm/imsic.h |  3 +++
 xen/arch/riscv/vaplic.c            |  7 +++++++
 3 files changed, 33 insertions(+)
xen/arch/riscv/imsic.c +23 -0
index ad0a220edac2..3787f270d8e3 100644
@@ -20,6 +20,7 @@
 #include <xen/init.h>
 #include <xen/libfdt/libfdt.h>
 #include <xen/macros.h>
+#include <xen/rwlock.h>
 #include <xen/sched.h>
 #include <xen/smp.h>
 #include <xen/spinlock.h>
@@ -342,6 +343,28 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
     return 0;
 }
 
+void cf_check imsic_ctxt_switch_from(struct vcpu *v)
+{
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+
+    /*
+     * A vCPU using the s/w IMSIC VS-file (guest_file_id == 0) has no h/w
+     * VS-file bound to a physical CPU, so there is no location to record.
+     */
+    if ( !vcpu_guest_file_id(v) )
+        return;
+
+    write_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    imsic_state->vsfile_cpu = v->processor;
+    write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+}
+
+void cf_check imsic_ctxt_switch_to(struct vcpu *v)
+{
+    /* Nothing to do */
+}
+
 int cf_check vcpu_imsic_init(struct vcpu *v)
 {
     struct vimsic_state *imsic_state;
xen/arch/riscv/include/asm/imsic.h +3 -0
index 93f9e44c7d2c..73129c3c9ea7 100644
@@ -109,4 +109,7 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v);
 
 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);
+
 #endif /* ASM_RISCV_IMSIC_H */
xen/arch/riscv/vaplic.c +7 -0
index 8726f7203d6e..6c60fe2baf0c 100644
@@ -422,6 +422,13 @@ static const struct mmio_handler_ops vaplic_mmio_ops = {
 static const struct vintc_ops vintc_ops = {
     .vcpu_init = vcpu_imsic_init,
     .vcpu_deinit = vcpu_imsic_deinit,
+    /*
+     * MSI delivery is the only supported mode: aplic_init() panics on an
+     * APLIC without an "msi-parent", so the vAPLIC state to save and restore
+     * is always the IMSIC one.
+     */
+    .ctxt_switch_from = imsic_ctxt_switch_from,
+    .ctxt_switch_to = imsic_ctxt_switch_to,
 };
 
 int domain_vaplic_init(struct domain *d)
Signature · 1 line
2.55.0
#91 lore raw

Re: [PATCH v2 15/39] xen/riscv: add IMSIC vCPU context switch handlers

Quoted 84 lines

IMSIC state currently needs to track only which physical CPU owns a vCPU's IMSIC guest interrupt file, as the CPU id is part of the physical address the file is mapped at.

Add imsic_ctxt_switch_from() to record that CPU when a vCPU is switched out. A vCPU running on the s/w VS-file has no h/w file bound to a CPU, so there is nothing to record for it. The recorded value stays unused until vCPU migration support, which needs it to find the file to move away from, is added later.

imsic_ctxt_switch_to() has nothing to do: by the time a vCPU is switched in, VGEIN is already assigned to it and its guest interrupt file is already mapped. Work is only required once a vCPU can move to a different CPU, which means recalculating VGEIN and remapping the file; that is handled separately by the vCPU migration patches.

Install both as the ctxt_switch_{from,to} hooks of struct vintc_ops. MSI delivery is the only mode Xen supports ( aplic_init() panics on an APLIC without an "msi-parent" property, and a guest's domaincfg.DM reads back as a fixed one) so the vAPLIC state to save and restore is always the IMSIC one and no vAPLIC-level forwarder is needed. Being indirect call targets, both handlers get cf_check.

xen/arch/riscv/imsic.c +23 -0
index ad0a220eda..3787f270d8 100644
@@ -20,6 +20,7 @@
 #include <xen/init.h>
 #include <xen/libfdt/libfdt.h>
 #include <xen/macros.h>
+#include <xen/rwlock.h>
 #include <xen/sched.h>
 #include <xen/smp.h>
 #include <xen/spinlock.h>
@@ -342,6 +343,28 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
     return 0;
 }
 
+void cf_check imsic_ctxt_switch_from(struct vcpu *v)
+{
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+
+    /*
+     * A vCPU using the s/w IMSIC VS-file (guest_file_id == 0) has no h/w
+     * VS-file bound to a physical CPU, so there is no location to record.
+     */
+    if ( !vcpu_guest_file_id(v) )
+        return;
+
+    write_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    imsic_state->vsfile_cpu = v->processor;
+    write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+}
+
+void cf_check imsic_ctxt_switch_to(struct vcpu *v)
+{
+    /* Nothing to do */
+}
+
 int cf_check vcpu_imsic_init(struct vcpu *v)
 {
     struct vimsic_state *imsic_state;
xen/arch/riscv/include/asm/imsic.h +3 -0
index 93f9e44c7d..73129c3c9e 100644
@@ -109,4 +109,7 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v);
 
 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);
+
 #endif /* ASM_RISCV_IMSIC_H */
xen/arch/riscv/vaplic.c +0 -0
index 8726f7203d..6c60fe2baf 100644

xen/arch/riscv/vaplic.c static const struct mmio_handler_ops vaplic_mmio_ops = { · line 431

Quoted 10 lines
xen/arch/riscv/vaplic.c +7 -0
@@ -422,6 +422,13 @@ static const struct mmio_handler_ops vaplic_mmio_ops = {
 static const struct vintc_ops vintc_ops = {
     .vcpu_init = vcpu_imsic_init,
     .vcpu_deinit = vcpu_imsic_deinit,
+    /*
+     * MSI delivery is the only supported mode: aplic_init() panics on an
+     * APLIC without an "msi-parent", so the vAPLIC state to save and restore
+     * is always the IMSIC one.
+     */
+    .ctxt_switch_from = imsic_ctxt_switch_from,
+    .ctxt_switch_to = imsic_ctxt_switch_to,

Maybe this patch could be merged with previous one: patch 50fe9554e1c0 ("xen/riscv: introduce vintc_ctxt_switch_{from,to}()")

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

Re: [PATCH v2 15/39] xen/riscv: add IMSIC vCPU context switch handlers

Quoted 88 lines · Baptiste Le Duc
Quoted 88 lines

IMSIC state currently needs to track only which physical CPU owns a vCPU's IMSIC guest interrupt file, as the CPU id is part of the physical address the file is mapped at.

Add imsic_ctxt_switch_from() to record that CPU when a vCPU is switched out. A vCPU running on the s/w VS-file has no h/w file bound to a CPU, so there is nothing to record for it. The recorded value stays unused until vCPU migration support, which needs it to find the file to move away from, is added later.

imsic_ctxt_switch_to() has nothing to do: by the time a vCPU is switched in, VGEIN is already assigned to it and its guest interrupt file is already mapped. Work is only required once a vCPU can move to a different CPU, which means recalculating VGEIN and remapping the file; that is handled separately by the vCPU migration patches.

Install both as the ctxt_switch_{from,to} hooks of struct vintc_ops. MSI delivery is the only mode Xen supports ( aplic_init() panics on an APLIC without an "msi-parent" property, and a guest's domaincfg.DM reads back as a fixed one) so the vAPLIC state to save and restore is always the IMSIC one and no vAPLIC-level forwarder is needed. Being indirect call targets, both handlers get cf_check.

xen/arch/riscv/imsic.c +23 -0
index ad0a220eda..3787f270d8 100644
@@ -20,6 +20,7 @@
  #include <xen/init.h>
  #include <xen/libfdt/libfdt.h>
  #include <xen/macros.h>
+#include <xen/rwlock.h>
  #include <xen/sched.h>
  #include <xen/smp.h>
  #include <xen/spinlock.h>
@@ -342,6 +343,28 @@ static int __init imsic_parse_node(const struct dt_device_node *node,
      return 0;
  }
 
+void cf_check imsic_ctxt_switch_from(struct vcpu *v)
+{
+    struct vimsic_state *imsic_state = v->arch.vimsic_state;
+    unsigned long flags;
+
+    /*
+     * A vCPU using the s/w IMSIC VS-file (guest_file_id == 0) has no h/w
+     * VS-file bound to a physical CPU, so there is no location to record.
+     */
+    if ( !vcpu_guest_file_id(v) )
+        return;
+
+    write_lock_irqsave(&imsic_state->vsfile_lock, flags);
+    imsic_state->vsfile_cpu = v->processor;
+    write_unlock_irqrestore(&imsic_state->vsfile_lock, flags);
+}
+
+void cf_check imsic_ctxt_switch_to(struct vcpu *v)
+{
+    /* Nothing to do */
+}
+
  int cf_check vcpu_imsic_init(struct vcpu *v)
  {
      struct vimsic_state *imsic_state;
xen/arch/riscv/include/asm/imsic.h +3 -0
index 93f9e44c7d..73129c3c9e 100644
@@ -109,4 +109,7 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v);
 
  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);
+
  #endif /* ASM_RISCV_IMSIC_H */
xen/arch/riscv/vaplic.c +1 -0
index 8726f7203d..6c60fe2baf 100644
@@ -422,6 +422,13 @@ static const struct mmio_handler_ops vaplic_mmio_ops = {
  static const struct vintc_ops vintc_ops = {
      .vcpu_init = vcpu_imsic_init,
      .vcpu_deinit = vcpu_imsic_deinit,
+    /*
Quoted 8 lines

xen/arch/riscv/vaplic.c static const struct mmio_handler_ops vaplic_mmio_ops = { · line 431

Quoted 6 lines
xen/arch/riscv/vaplic.c +6 -0
+     * MSI delivery is the only supported mode: aplic_init() panics on an
+     * APLIC without an "msi-parent", so the vAPLIC state to save and restore
+     * is always the IMSIC one.
+     */
+    .ctxt_switch_from = imsic_ctxt_switch_from,
+    .ctxt_switch_to = imsic_ctxt_switch_to,

Maybe this patch could be merged with previous one: patch 50fe9554e1c0 ("xen/riscv: introduce vintc_ctxt_switch_{from,to}()")

At some point I agree but I think I prefer a little bit to separate them. It is safe to have them separately as context switch isn't happening between these patches so any problem will occur. What I intented to do is that to separately introduce abstraction and separately introduce users of this abstraction.

~ Oleksii

#93 lore raw

Re: [PATCH v2 15/39] xen/riscv: add IMSIC vCPU context switch handlers

In reply to Oleksii Kurochko
Quoted 4 lines · Oleksii Kurochko
xen/arch/riscv/vaplic.c +0 -0
@@ -422,6 +422,13 @@ static const struct mmio_handler_ops vaplic_mmio_ops = {
 static const struct vintc_ops vintc_ops = {

xen/arch/riscv/vaplic.c static const struct mmio_handler_ops vaplic_mmio_ops = { · line 432

Quoted 10 lines
xen/arch/riscv/vaplic.c +7 -0
     .vcpu_init = vcpu_imsic_init,
     .vcpu_deinit = vcpu_imsic_deinit,
+    /*
+     * MSI delivery is the only supported mode: aplic_init() panics on an
+     * APLIC without an "msi-parent", so the vAPLIC state to save and restore
+     * is always the IMSIC one.
+     */
+    .ctxt_switch_from = imsic_ctxt_switch_from,
+    .ctxt_switch_to = imsic_ctxt_switch_to,
 };

As previously expressed, I'm not happy with comments like this. aplic_init() isn't related to vAPLIC behavior. We're doing virtualization, so at least conceptually host and guest behavior want properly separating. Then it may still be that for the time being only a certain subset of possibilities is supported.

Jan

#94 lore raw

Re: [PATCH v2 15/39] xen/riscv: add IMSIC vCPU context switch handlers

Quoted 13 lines · Jan Beulich
Quoted 12 lines · Oleksii Kurochko
xen/arch/riscv/vaplic.c +6 -0
@@ -422,6 +422,13 @@ static const struct mmio_handler_ops vaplic_mmio_ops = {
  static const struct vintc_ops vintc_ops = {
      .vcpu_init = vcpu_imsic_init,
      .vcpu_deinit = vcpu_imsic_deinit,
+    /*
+     * MSI delivery is the only supported mode: aplic_init() panics on an
+     * APLIC without an "msi-parent", so the vAPLIC state to save and restore
+     * is always the IMSIC one.
+     */
+    .ctxt_switch_from = imsic_ctxt_switch_from,
Quoted 8 lines

xen/arch/riscv/vaplic.c static const struct mmio_handler_ops vaplic_mmio_ops = { · line 432

Quoted 2 lines
xen/arch/riscv/vaplic.c +1 -0
+    .ctxt_switch_to = imsic_ctxt_switch_to,
  };

As previously expressed, I'm not happy with comments like this. aplic_init() isn't related to vAPLIC behavior. We're doing virtualization, so at least conceptually host and guest behavior want properly separating. Then it may still be that for the time being only a certain subset of possibilities is supported.

I will drop the part "aplic_init() panics on an APLIC without an "msi-parent". It is really not very relevant here.

Thanks.

~ Oleksii

#95 lore raw

PATCH v2 16/39 xen/riscv: extend exception tables with type and data fields

In reply to Oleksii Kurochko

Extend the RISC-V exception table format to include a type and auxiliary data field.

The existing format only supports simple fixups. Some use cases require additional context from the fault (e.g. capturing trap information), which cannot be expressed with the current EX_TYPE_FIXUP entries.

Introduce a generic ASM_EXTABLE_RAW() helper to describe entries with a handler type and associated data. Reimplement ASM_EXTABLE() in terms of it using EX_TYPE_FIXUP for compatibility.

Add EX_TYPE_TRAP_INFO to allow handlers to retrieve trap state (sepc/scause/stval) and pass it to the fixup path. The data field is used to encode which GPR contains a pointer to a struct trap_info.

Provide ASM_EXTABLE_TRAP_INFO() as a convenience wrapper for this case.

Also add gpr-num.h, providing symbolic GPR numbers for use in assembly and inline asm. This is derived from Linux 6.16 with minor adjustments such as using .irp instead of open-coding the same using a set of .equ.

Update the exception handling code to dispatch based on the entry type.

---
Changes in v2:
- regs_get_gpr(): take a GPR number instead of a byte offset, dropping the multiplication at the call site. A non-multiple-of-8 offset is now unrepresentable.
- regs_get_gpr(): ASSERT(num < 32) instead of a range check returning 0, which isn't usable as an error indicator. No num == 0 check: reading x0 is harmless out of context, and a NULL trap_info is caught by the existing BUG_ON() where the dereference happens.
- regs_get_gpr(): index the register frame as an array, constify regs and drop the pointless inline.
- Anchor the first BUILD_BUG_ON() at offsetof(..., zero) == 0 rather than at ra, pinning both ends of the x0..x31 range.
- Drop MAX_REG_OFFSET; asm/processor.h is no longer touched by this patch.
- ex_handler_trap_info(): use regs->sepc and the cause passed down from do_trap() instead of re-reading CSR_SEPC/CSR_SCAUSE; fixup_exception() gains a cause parameter. stval stays a CSR read as do_trap() doesn't read it.
- asm/extable.h: revert the .word -> .long change, the extra parens and the stray semicolon after .popsection; use .half for the new type and data fields to match .word.
- Make GPR_LIST() the single source of the ABI-name -> register-number mapping, and check struct cpu_user_regs against it at build time, so the two can no longer diverge.
- Add the explanatory comment above sturc cpu_user_regs to explain an ordering of x0-x31 registers.
---

---
 xen/arch/riscv/extable.c               | 70 +++++++++++++++++++++++++-
 xen/arch/riscv/include/asm/extable.h   | 64 +++++++++++++++--------
 xen/arch/riscv/include/asm/gpr-num.h   | 37 ++++++++++++++
 xen/arch/riscv/include/asm/processor.h | 14 +++++-
 xen/arch/riscv/include/asm/traps.h     |  6 +++
 xen/arch/riscv/traps.c                 |  2 +-
 6 files changed, 169 insertions(+), 24 deletions(-)
 create mode 100644 xen/arch/riscv/include/asm/gpr-num.h
xen/arch/riscv/extable.c +68 -2
index 5b89c4278c65..6470198d0117 100644
@@ -6,8 +6,10 @@
 #include <xen/sort.h>
 #include <xen/virtual_region.h>
 
+#include <asm/csr.h>
 #include <asm/extable.h>
 #include <asm/processor.h>
+#include <asm/traps.h>
 
 #define EX_FIELD(ptr, field) ((unsigned long)&(ptr)->field + (ptr)->field)
 
@@ -32,6 +34,12 @@ static void __init cf_check swap_ex(void *a, void *b)
 
     x->fixup = y->fixup + delta;
     y->fixup = tmp.fixup - delta;
+
+    x->type = y->type;
+    y->type = tmp.type;
+
+    x->data = y->data;
+    y->data = tmp.data;
 }
 
 static int cf_check cmp_ex(const void *a, const void *b)
@@ -59,7 +67,49 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
     regs->sepc = ex_fixup(ex);
 }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+#define CHECK_GPR_INDEX(num, name)                      \
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, name)   \
+                 != (num) * sizeof(unsigned long));
+
+static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
+                                  unsigned int num)
+{
+    /*
+     * The GPR number -> struct index mapping below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural order,
+     * matching the register numbers GPR_LIST() hands to the assembler.
+     */
+    GPR_LIST(CHECK_GPR_INDEX)
+
+    ASSERT(num < 32);
+
+    return ((const unsigned long *)regs)[num];
+}
+
+#undef CHECK_GPR_INDEX
+
+static void ex_handler_trap_info(const struct exception_table_entry *ex,
+                                 struct cpu_user_regs *regs,
+                                 unsigned long cause)
+{
+    struct trap_info *trap_info =
+        (struct trap_info *)regs_get_gpr(regs, ex->data);
+
+    BUG_ON(!trap_info);
+
+    /*
+     * Only stval still needs a CSR read: sepc and scause were already
+     * captured by the trap entry path and do_trap() respectively. Latch
+     * trap_info->sepc before regs->sepc is pointed at the fixup code.
+     */
+    trap_info->sepc = regs->sepc;
+    trap_info->scause = cause;
+    trap_info->stval = csr_read(CSR_STVAL);
+
+    regs->sepc = ex_fixup(ex);
+}
+
+bool fixup_exception(struct cpu_user_regs *regs, unsigned long cause)
 {
     unsigned long pc = regs->sepc;
     const struct virtual_region *region = find_text_region(pc);
@@ -77,7 +127,23 @@ bool fixup_exception(struct cpu_user_regs *regs)
     if ( !ex )
         return false;
 
-    ex_handler_fixup(ex, regs);
+    switch ( ex->type )
+    {
+    case EX_TYPE_FIXUP:
+        ex_handler_fixup(ex, regs);
+        break;
+
+    case EX_TYPE_TRAP_INFO:
+        ex_handler_trap_info(ex, regs, cause);
+        break;
+
+    default:
+        printk(XENLOG_ERR
+               "Unsupported exception table entry type %u for pc %#lx\n",
+               ex->type, pc);
+
+        return false;
+    }
 
     return true;
 }
xen/arch/riscv/include/asm/extable.h +44 -20

95 lines not on this page · raw message

xen/arch/riscv/include/asm/gpr-num.h new file +37 -0
new file mode 100644
index 000000000000..3b97a72e6c30
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef RISCV_GPR_NUM_H
+#define RISCV_GPR_NUM_H
+
+/*
+ * GPRs by ABI name, together with their register number (x0 .. x31).
+ *
+ * This is the single source of truth for the mapping: it generates the
+ * .L_gpr_num_<name> assembler symbols used to turn a register name emitted
+ * by the compiler into a register number, and struct cpu_user_regs is
+ * checked against it at build time (see regs_get_gpr()). Neither list can
+ * therefore be changed without the other.
+ */
+#define GPR_LIST(x)                                 \
+    x(0,  zero) x(1,  ra)  x(2,  sp)  x(3,  gp)     \
+    x(4,  tp)   x(5,  t0)  x(6,  t1)  x(7,  t2)     \
+    x(8,  s0)   x(9,  s1)  x(10, a0)  x(11, a1)     \
+    x(12, a2)   x(13, a3)  x(14, a4)  x(15, a5)     \
+    x(16, a6)   x(17, a7)  x(18, s2)  x(19, s3)     \
+    x(20, s4)   x(21, s5)  x(22, s6)  x(23, s7)     \
+    x(24, s8)   x(25, s9)  x(26, s10) x(27, s11)    \
+    x(28, t3)   x(29, t4)  x(30, t5)  x(31, t6)
+
+#ifdef __ASSEMBLER__
+
+#define GPR_NUM_EQU(num, name)  .equ .L_gpr_num_##name, num;
+GPR_LIST(GPR_NUM_EQU)
+#undef GPR_NUM_EQU
+
+#else /* __ASSEMBLER__ */
+
+#define GPR_NUM_EQU(num, name)  ".equ .L_gpr_num_" #name ", " #num "\n"
+#define DEFINE_ASM_GPR_NUMS     GPR_LIST(GPR_NUM_EQU)
+
+#endif /* __ASSEMBLER__ */
+
+#endif /* RISCV_GPR_NUM_H */
xen/arch/riscv/include/asm/processor.h +13 -1
index b1745c107100..e7b0f2321a0e 100644
@@ -12,7 +12,19 @@
 
 #ifndef __ASSEMBLER__
 
-/* On stack VCPU state */
+/*
+ * On stack VCPU state.
+ *
+ * x0..x31 must remain at the start of this structure, in architectural
+ * register-number order: code which resolves a register number to its saved
+ * value indexes this structure directly (instruction emulation via
+ * REG_PTR() from asm/riscv_encoding.h, exception table fixups via
+ * regs_get_gpr()). ->zero therefore has to stay at offset 0 and must always
+ * read as 0, since it supplies the value of x0 when x0 is used as a source
+ * operand. The layout is checked against GPR_LIST() at build time; see
+ * regs_get_gpr() in extable.c. Do not reorder these fields or insert
+ * anything between them.
+ */
 struct cpu_user_regs
 {
     unsigned long zero;
xen/arch/riscv/include/asm/traps.h +6 -0
index 21fa3c3259b3..8d4ab664bca9 100644
@@ -7,6 +7,12 @@
 
 #ifndef __ASSEMBLER__
 
+struct trap_info {
+    register_t sepc;
+    register_t scause;
+    register_t stval;
+};
+
 void do_trap(struct cpu_user_regs *cpu_regs);
 void handle_trap(void);
 void trap_init(void);
xen/arch/riscv/traps.c +1 -1
index 093d81e2d803..11a6fa1bc942 100644
@@ -217,7 +217,7 @@ void do_trap(struct cpu_user_regs *cpu_regs)
             break;
         }
 
-        if ( fixup_exception(cpu_regs) )
+        if ( fixup_exception(cpu_regs, cause) )
             break;
 
         fallthrough;
Signature · 1 line
2.55.0
#96 lore raw

Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields

Quoted 237 lines

Extend the RISC-V exception table format to include a type and auxiliary data field.

The existing format only supports simple fixups. Some use cases require additional context from the fault (e.g. capturing trap information), which cannot be expressed with the current EX_TYPE_FIXUP entries.

Introduce a generic ASM_EXTABLE_RAW() helper to describe entries with a handler type and associated data. Reimplement ASM_EXTABLE() in terms of it using EX_TYPE_FIXUP for compatibility.

Add EX_TYPE_TRAP_INFO to allow handlers to retrieve trap state (sepc/scause/stval) and pass it to the fixup path. The data field is used to encode which GPR contains a pointer to a struct trap_info.

Provide ASM_EXTABLE_TRAP_INFO() as a convenience wrapper for this case.

Also add gpr-num.h, providing symbolic GPR numbers for use in assembly and inline asm. This is derived from Linux 6.16 with minor adjustments such as using .irp instead of open-coding the same using a set of .equ.

Update the exception handling code to dispatch based on the entry type.

xen/arch/riscv/extable.c +68 -2
index 5b89c4278c..6470198d01 100644
@@ -6,8 +6,10 @@
 #include <xen/sort.h>
 #include <xen/virtual_region.h>
 
+#include <asm/csr.h>
 #include <asm/extable.h>
 #include <asm/processor.h>
+#include <asm/traps.h>
 
 #define EX_FIELD(ptr, field) ((unsigned long)&(ptr)->field + (ptr)->field)
 
@@ -32,6 +34,12 @@ static void __init cf_check swap_ex(void *a, void *b)
 
     x->fixup = y->fixup + delta;
     y->fixup = tmp.fixup - delta;
+
+    x->type = y->type;
+    y->type = tmp.type;
+
+    x->data = y->data;
+    y->data = tmp.data;
 }
 
 static int cf_check cmp_ex(const void *a, const void *b)
@@ -59,7 +67,49 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
     regs->sepc = ex_fixup(ex);
 }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+#define CHECK_GPR_INDEX(num, name)                      \
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, name)   \
+                 != (num) * sizeof(unsigned long));
+
+static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
+                                  unsigned int num)
+{
+    /*
+     * The GPR number -> struct index mapping below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural order,
+     * matching the register numbers GPR_LIST() hands to the assembler.
+     */
+    GPR_LIST(CHECK_GPR_INDEX)
+
+    ASSERT(num < 32);
+
+    return ((const unsigned long *)regs)[num];
+}
+
+#undef CHECK_GPR_INDEX
+
+static void ex_handler_trap_info(const struct exception_table_entry *ex,
+                                 struct cpu_user_regs *regs,
+                                 unsigned long cause)
+{
+    struct trap_info *trap_info =
+        (struct trap_info *)regs_get_gpr(regs, ex->data);
+
+    BUG_ON(!trap_info);
+
+    /*
+     * Only stval still needs a CSR read: sepc and scause were already
+     * captured by the trap entry path and do_trap() respectively. Latch
+     * trap_info->sepc before regs->sepc is pointed at the fixup code.
+     */
+    trap_info->sepc = regs->sepc;
+    trap_info->scause = cause;
+    trap_info->stval = csr_read(CSR_STVAL);
+
+    regs->sepc = ex_fixup(ex);
+}
+
+bool fixup_exception(struct cpu_user_regs *regs, unsigned long cause)
 {
     unsigned long pc = regs->sepc;
     const struct virtual_region *region = find_text_region(pc);
@@ -77,7 +127,23 @@ bool fixup_exception(struct cpu_user_regs *regs)
     if ( !ex )
         return false;
 
-    ex_handler_fixup(ex, regs);
+    switch ( ex->type )
+    {
+    case EX_TYPE_FIXUP:
+        ex_handler_fixup(ex, regs);
+        break;
+
+    case EX_TYPE_TRAP_INFO:
+        ex_handler_trap_info(ex, regs, cause);
+        break;
+
+    default:
+        printk(XENLOG_ERR
+               "Unsupported exception table entry type %u for pc %#lx\n",
+               ex->type, pc);
+
+        return false;
+    }
 
     return true;
 }
xen/arch/riscv/include/asm/extable.h +44 -20
index c0128a9181..7378f86e7e 100644
@@ -3,17 +3,24 @@
 #ifndef ASM__RISCV__ASM_EXTABLE_H
 #define ASM__RISCV__ASM_EXTABLE_H
 
+#include <asm/gpr-num.h>
+
+#define EX_TYPE_FIXUP       0
+#define EX_TYPE_TRAP_INFO   1
+
 #ifdef __ASSEMBLER__
 
-#define ASM_EXTABLE(insn, fixup) \
-    .pushsection .ex_table, "a"; \
-    .balign     4;               \
-    .word       (insn) - .;      \
-    .word       (fixup) - .;     \
+#define ASM_EXTABLE_RAW(insn, fixup, type, data)    \
+    .pushsection .ex_table, "a";                    \
+    .balign     4;                                  \
+    .word       (insn) - .;                         \
+    .word       (fixup) - .;                        \
+    .half       (type);                             \
+    .half       (data);                             \
     .popsection
 
-.macro asm_extable, insn, fixup
-    ASM_EXTABLE(\insn, \fixup)
+.macro _asm_extable, insn, fixup
+    ASM_EXTABLE_RAW(\insn, \fixup, EX_TYPE_FIXUP, 0)
 .endm
 
 #else /* __ASSEMBLER__ */
@@ -23,20 +30,36 @@
 
 struct cpu_user_regs;
 
-#define ASM_EXTABLE(insn, fixup)      \
-    ".pushsection .ex_table, \"a\"\n" \
-    ".balign    4\n"                  \
-    ".word      (" #insn " - .)\n"    \
-    ".word      (" #fixup " - .)\n"   \
+#define ASM_EXTABLE_RAW(insn, fixup, type, data)    \
+    ".pushsection .ex_table, \"a\"\n"               \
+    ".balign    4\n"                                \
+    ".word      (" insn ") - .\n"                   \
+    ".word      (" fixup ") - .\n"                  \
+    ".half      (" type ")\n"                       \
+    ".half      (" data ")\n"                       \
     ".popsection\n"
 
+#define ASM_EXTABLE(insn, fixup)    \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_FIXUP), "0")
+
+#define EX_TRAP_INFO_REG(gpr)   \
+    "(.L_gpr_num_" #gpr ")"
+
+#define ASM_EXTABLE_TRAP_INFO(insn, fixup, data)                    \
+    DEFINE_ASM_GPR_NUMS                                             \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_TRAP_INFO),  \
+                    EX_TRAP_INFO_REG(data))
+
 /*
- * The exception table consists of pairs of relative offsets: the first
- * is the relative offset to an instruction that is allowed to fault,
- * and the second is the relative offset at which the program should
- * continue. No general-purpose registers are modified by the exception
- * handling mechanism itself, so it is up to the fixup code to handle
- * any necessary state cleanup.
+ * Each exception table entry consists of two relative offsets and a
+ * handler description: `insn` is the relative offset to an instruction
+ * that is allowed to fault, `fixup` is the relative offset at which the
+ * program should continue, `type` selects how the exception is handled
+ * (EX_TYPE_*), and `data` holds auxiliary information for the handler
+ * (e.g. for EX_TYPE_TRAP_INFO, the number of the GPR that contains a
+ * pointer to a struct trap_info). No general-purpose registers are
+ * modified by the exception handling mechanism itself, so it is up to
+ * the fixup code to handle any necessary state cleanup.
  *
  * The exception table and fixup code live out of line with the main
  * instruction path. This means when everything is well, we don't even
@@ -45,14 +68,15 @@ struct cpu_user_regs;
  */
 struct exception_table_entry {
     int32_t insn, fixup;
+    uint16_t type, data;
 };
 
 extern struct exception_table_entry __start___ex_table[];
 extern struct exception_table_entry __stop___ex_table[];
 
 void sort_exception_tables(void);
-bool fixup_exception(struct cpu_user_regs *regs);
+bool fixup_exception(struct cpu_user_regs *regs, unsigned long cause);
 
-#endif /* __ASSEMBLY__ */
+#endif /* __ASSEMBLER__ */
 
 #endif /* ASM__RISCV__ASM_EXTABLE_H */
xen/arch/riscv/include/asm/gpr-num.h new file +0 -0
new file mode 100644
index 0000000000..3b97a72e6c

xen/arch/riscv/include/asm/gpr-num.h line 3

Quoted 3 lines
xen/arch/riscv/include/asm/gpr-num.h new file +3 -0
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef RISCV_GPR_NUM_H
+#define RISCV_GPR_NUM_H

Nit: commit message says this is derived from Linux 6.16. Other imported RISC-V headers here carry an in-file note (bitops.h: "Based on linux/arch/.../bitops.h") but this file doesn't.

Quoted 47 lines
xen/arch/riscv/include/asm/gpr-num.h new file +33 -0
+/*
+ * GPRs by ABI name, together with their register number (x0 .. x31).
+ *
+ * This is the single source of truth for the mapping: it generates the
+ * .L_gpr_num_<name> assembler symbols used to turn a register name emitted
+ * by the compiler into a register number, and struct cpu_user_regs is
+ * checked against it at build time (see regs_get_gpr()). Neither list can
+ * therefore be changed without the other.
+ */
+#define GPR_LIST(x)                                 \
+    x(0,  zero) x(1,  ra)  x(2,  sp)  x(3,  gp)     \
+    x(4,  tp)   x(5,  t0)  x(6,  t1)  x(7,  t2)     \
+    x(8,  s0)   x(9,  s1)  x(10, a0)  x(11, a1)     \
+    x(12, a2)   x(13, a3)  x(14, a4)  x(15, a5)     \
+    x(16, a6)   x(17, a7)  x(18, s2)  x(19, s3)     \
+    x(20, s4)   x(21, s5)  x(22, s6)  x(23, s7)     \
+    x(24, s8)   x(25, s9)  x(26, s10) x(27, s11)    \
+    x(28, t3)   x(29, t4)  x(30, t5)  x(31, t6)
+
+#ifdef __ASSEMBLER__
+
+#define GPR_NUM_EQU(num, name)  .equ .L_gpr_num_##name, num;
+GPR_LIST(GPR_NUM_EQU)
+#undef GPR_NUM_EQU
+
+#else /* __ASSEMBLER__ */
+
+#define GPR_NUM_EQU(num, name)  ".equ .L_gpr_num_" #name ", " #num "\n"
+#define DEFINE_ASM_GPR_NUMS     GPR_LIST(GPR_NUM_EQU)
+
+#endif /* __ASSEMBLER__ */
+
+#endif /* RISCV_GPR_NUM_H */
xen/arch/riscv/include/asm/processor.h +5 -1
index b1745c1071..e7b0f2321a 100644
@@ -12,7 +12,19 @@
 
 #ifndef __ASSEMBLER__
 
-/* On stack VCPU state */
+/*
+ * On stack VCPU state.
+ *
+ * x0..x31 must remain at the start of this structure, in architectural
+ * register-number order: code which resolves a register number to its saved

xen/arch/riscv/include/asm/processor.h line 29

Quoted 10 lines
xen/arch/riscv/include/asm/processor.h +8 -0
+ * value indexes this structure directly (instruction emulation via
+ * REG_PTR() from asm/riscv_encoding.h, exception table fixups via
+ * regs_get_gpr()). ->zero therefore has to stay at offset 0 and must always
+ * read as 0, since it supplies the value of x0 when x0 is used as a source
+ * operand. The layout is checked against GPR_LIST() at build time; see
+ * regs_get_gpr() in extable.c. Do not reorder these fields or insert
+ * anything between them.
+ */
 {
     unsigned long zero;

Comment claims ->zero "must always read as 0" as it's hard-wired to zero by the HW, but nothing enforces that, it's still a plain writable unsigned long. Maybe a write-side counterpart that special-cases num==0 as a no-op, or with a minimum ASSERT(num != 0) / BUG_ON(num == 0) to anticipate any future forbidden writes.

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

Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields

Quoted 19 lines · Baptiste Le Duc
Quoted 19 lines
xen/arch/riscv/include/asm/processor.h +12 -1
@@ -12,7 +12,19 @@
 
 #ifndef __ASSEMBLER__
 
-/* On stack VCPU state */
+/*
+ * On stack VCPU state.
+ *
+ * x0..x31 must remain at the start of this structure, in architectural
+ * register-number order: code which resolves a register number to its saved
+ * value indexes this structure directly (instruction emulation via
+ * REG_PTR() from asm/riscv_encoding.h, exception table fixups via
+ * regs_get_gpr()). ->zero therefore has to stay at offset 0 and must always
+ * read as 0, since it supplies the value of x0 when x0 is used as a source
+ * operand. The layout is checked against GPR_LIST() at build time; see
+ * regs_get_gpr() in extable.c. Do not reorder these fields or insert
+ * anything between them.
Quoted 8 lines

xen/arch/riscv/include/asm/processor.h line 30

Quoted 3 lines
xen/arch/riscv/include/asm/processor.h +1 -0
+ */
 {
     unsigned long zero;

Comment claims ->zero "must always read as 0" as it's hard-wired to zero by the HW, but nothing enforces that, it's still a plain writable unsigned long. Maybe a write-side counterpart that special-cases num==0 as a no-op, or with a minimum ASSERT(num != 0) / BUG_ON(num == 0) to anticipate any future forbidden writes.

With polarity inverted, though.

Jan

#98 lore raw

Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields

Quoted 10 lines · Jan Beulich
Quoted 6 lines · Baptiste Le Duc
Quoted 1 line

--- a/xen/arch/riscv/include/asm/processor.h

Comment claims ->zero "must always read as 0" as it's hard-wired to zero by the HW, but nothing enforces that, it's still a plain writable unsigned long. Maybe a write-side counterpart that special-cases num==0 as a no-op, or with a minimum ASSERT(num != 0) / BUG_ON(num == 0) to anticipate any future forbidden writes.

With polarity inverted, though.

Yes sorry, it should be ASSERT(num == 0) / BUG_ON(num != 0)

Quoted 2 lines

Jan

#99 lore raw

Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields

In reply to Baptiste Le Duc
Quoted 297 lines · Baptiste Le Duc
Quoted 237 lines

Extend the RISC-V exception table format to include a type and auxiliary data field.

The existing format only supports simple fixups. Some use cases require additional context from the fault (e.g. capturing trap information), which cannot be expressed with the current EX_TYPE_FIXUP entries.

Introduce a generic ASM_EXTABLE_RAW() helper to describe entries with a handler type and associated data. Reimplement ASM_EXTABLE() in terms of it using EX_TYPE_FIXUP for compatibility.

Add EX_TYPE_TRAP_INFO to allow handlers to retrieve trap state (sepc/scause/stval) and pass it to the fixup path. The data field is used to encode which GPR contains a pointer to a struct trap_info.

Provide ASM_EXTABLE_TRAP_INFO() as a convenience wrapper for this case.

Also add gpr-num.h, providing symbolic GPR numbers for use in assembly and inline asm. This is derived from Linux 6.16 with minor adjustments such as using .irp instead of open-coding the same using a set of .equ.

Update the exception handling code to dispatch based on the entry type.

xen/arch/riscv/extable.c +68 -2
index 5b89c4278c..6470198d01 100644
@@ -6,8 +6,10 @@
  #include <xen/sort.h>
  #include <xen/virtual_region.h>
 
+#include <asm/csr.h>
  #include <asm/extable.h>
  #include <asm/processor.h>
+#include <asm/traps.h>
 
  #define EX_FIELD(ptr, field) ((unsigned long)&(ptr)->field + (ptr)->field)
 
@@ -32,6 +34,12 @@ static void __init cf_check swap_ex(void *a, void *b)
 
      x->fixup = y->fixup + delta;
      y->fixup = tmp.fixup - delta;
+
+    x->type = y->type;
+    y->type = tmp.type;
+
+    x->data = y->data;
+    y->data = tmp.data;
  }
 
  static int cf_check cmp_ex(const void *a, const void *b)
@@ -59,7 +67,49 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
      regs->sepc = ex_fixup(ex);
  }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+#define CHECK_GPR_INDEX(num, name)                      \
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, name)   \
+                 != (num) * sizeof(unsigned long));
+
+static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
+                                  unsigned int num)
+{
+    /*
+     * The GPR number -> struct index mapping below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural order,
+     * matching the register numbers GPR_LIST() hands to the assembler.
+     */
+    GPR_LIST(CHECK_GPR_INDEX)
+
+    ASSERT(num < 32);
+
+    return ((const unsigned long *)regs)[num];
+}
+
+#undef CHECK_GPR_INDEX
+
+static void ex_handler_trap_info(const struct exception_table_entry *ex,
+                                 struct cpu_user_regs *regs,
+                                 unsigned long cause)
+{
+    struct trap_info *trap_info =
+        (struct trap_info *)regs_get_gpr(regs, ex->data);
+
+    BUG_ON(!trap_info);
+
+    /*
+     * Only stval still needs a CSR read: sepc and scause were already
+     * captured by the trap entry path and do_trap() respectively. Latch
+     * trap_info->sepc before regs->sepc is pointed at the fixup code.
+     */
+    trap_info->sepc = regs->sepc;
+    trap_info->scause = cause;
+    trap_info->stval = csr_read(CSR_STVAL);
+
+    regs->sepc = ex_fixup(ex);
+}
+
+bool fixup_exception(struct cpu_user_regs *regs, unsigned long cause)
  {
      unsigned long pc = regs->sepc;
      const struct virtual_region *region = find_text_region(pc);
@@ -77,7 +127,23 @@ bool fixup_exception(struct cpu_user_regs *regs)
      if ( !ex )
          return false;
 
-    ex_handler_fixup(ex, regs);
+    switch ( ex->type )
+    {
+    case EX_TYPE_FIXUP:
+        ex_handler_fixup(ex, regs);
+        break;
+
+    case EX_TYPE_TRAP_INFO:
+        ex_handler_trap_info(ex, regs, cause);
+        break;
+
+    default:
+        printk(XENLOG_ERR
+               "Unsupported exception table entry type %u for pc %#lx\n",
+               ex->type, pc);
+
+        return false;
+    }
 
      return true;
  }
xen/arch/riscv/include/asm/extable.h +44 -20
index c0128a9181..7378f86e7e 100644
@@ -3,17 +3,24 @@
  #ifndef ASM__RISCV__ASM_EXTABLE_H
  #define ASM__RISCV__ASM_EXTABLE_H
 
+#include <asm/gpr-num.h>
+
+#define EX_TYPE_FIXUP       0
+#define EX_TYPE_TRAP_INFO   1
+
  #ifdef __ASSEMBLER__
 
-#define ASM_EXTABLE(insn, fixup) \
-    .pushsection .ex_table, "a"; \
-    .balign     4;               \
-    .word       (insn) - .;      \
-    .word       (fixup) - .;     \
+#define ASM_EXTABLE_RAW(insn, fixup, type, data)    \
+    .pushsection .ex_table, "a";                    \
+    .balign     4;                                  \
+    .word       (insn) - .;                         \
+    .word       (fixup) - .;                        \
+    .half       (type);                             \
+    .half       (data);                             \
      .popsection
 
-.macro asm_extable, insn, fixup
-    ASM_EXTABLE(\insn, \fixup)
+.macro _asm_extable, insn, fixup
+    ASM_EXTABLE_RAW(\insn, \fixup, EX_TYPE_FIXUP, 0)
  .endm
 
  #else /* __ASSEMBLER__ */
@@ -23,20 +30,36 @@
 
  struct cpu_user_regs;
 
-#define ASM_EXTABLE(insn, fixup)      \
-    ".pushsection .ex_table, \"a\"\n" \
-    ".balign    4\n"                  \
-    ".word      (" #insn " - .)\n"    \
-    ".word      (" #fixup " - .)\n"   \
+#define ASM_EXTABLE_RAW(insn, fixup, type, data)    \
+    ".pushsection .ex_table, \"a\"\n"               \
+    ".balign    4\n"                                \
+    ".word      (" insn ") - .\n"                   \
+    ".word      (" fixup ") - .\n"                  \
+    ".half      (" type ")\n"                       \
+    ".half      (" data ")\n"                       \
      ".popsection\n"
 
+#define ASM_EXTABLE(insn, fixup)    \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_FIXUP), "0")
+
+#define EX_TRAP_INFO_REG(gpr)   \
+    "(.L_gpr_num_" #gpr ")"
+
+#define ASM_EXTABLE_TRAP_INFO(insn, fixup, data)                    \
+    DEFINE_ASM_GPR_NUMS                                             \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_TRAP_INFO),  \
+                    EX_TRAP_INFO_REG(data))
+
  /*
- * The exception table consists of pairs of relative offsets: the first
- * is the relative offset to an instruction that is allowed to fault,
- * and the second is the relative offset at which the program should
- * continue. No general-purpose registers are modified by the exception
- * handling mechanism itself, so it is up to the fixup code to handle
- * any necessary state cleanup.
+ * Each exception table entry consists of two relative offsets and a
+ * handler description: `insn` is the relative offset to an instruction
+ * that is allowed to fault, `fixup` is the relative offset at which the
+ * program should continue, `type` selects how the exception is handled
+ * (EX_TYPE_*), and `data` holds auxiliary information for the handler
+ * (e.g. for EX_TYPE_TRAP_INFO, the number of the GPR that contains a
+ * pointer to a struct trap_info). No general-purpose registers are
+ * modified by the exception handling mechanism itself, so it is up to
+ * the fixup code to handle any necessary state cleanup.
   *
   * The exception table and fixup code live out of line with the main
   * instruction path. This means when everything is well, we don't even
@@ -45,14 +68,15 @@ struct cpu_user_regs;
   */
  struct exception_table_entry {
      int32_t insn, fixup;
+    uint16_t type, data;
  };
 
  extern struct exception_table_entry __start___ex_table[];
  extern struct exception_table_entry __stop___ex_table[];
 
  void sort_exception_tables(void);
-bool fixup_exception(struct cpu_user_regs *regs);
+bool fixup_exception(struct cpu_user_regs *regs, unsigned long cause);
 
-#endif /* __ASSEMBLY__ */
+#endif /* __ASSEMBLER__ */
 
  #endif /* ASM__RISCV__ASM_EXTABLE_H */
xen/arch/riscv/include/asm/gpr-num.h new file +0 -0
new file mode 100644
index 0000000000..3b97a72e6c

xen/arch/riscv/include/asm/gpr-num.h line 3

Quoted 3 lines
xen/arch/riscv/include/asm/gpr-num.h new file +3 -0
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef RISCV_GPR_NUM_H
+#define RISCV_GPR_NUM_H

Nit: commit message says this is derived from Linux 6.16. Other imported RISC-V headers here carry an in-file note (bitops.h: "Based on linux/arch/.../bitops.h") but this file doesn't.

Quoted 54 lines
xen/arch/riscv/include/asm/gpr-num.h new file +33 -0
+/*
+ * GPRs by ABI name, together with their register number (x0 .. x31).
+ *
+ * This is the single source of truth for the mapping: it generates the
+ * .L_gpr_num_<name> assembler symbols used to turn a register name emitted
+ * by the compiler into a register number, and struct cpu_user_regs is
+ * checked against it at build time (see regs_get_gpr()). Neither list can
+ * therefore be changed without the other.
+ */
+#define GPR_LIST(x)                                 \
+    x(0,  zero) x(1,  ra)  x(2,  sp)  x(3,  gp)     \
+    x(4,  tp)   x(5,  t0)  x(6,  t1)  x(7,  t2)     \
+    x(8,  s0)   x(9,  s1)  x(10, a0)  x(11, a1)     \
+    x(12, a2)   x(13, a3)  x(14, a4)  x(15, a5)     \
+    x(16, a6)   x(17, a7)  x(18, s2)  x(19, s3)     \
+    x(20, s4)   x(21, s5)  x(22, s6)  x(23, s7)     \
+    x(24, s8)   x(25, s9)  x(26, s10) x(27, s11)    \
+    x(28, t3)   x(29, t4)  x(30, t5)  x(31, t6)
+
+#ifdef __ASSEMBLER__
+
+#define GPR_NUM_EQU(num, name)  .equ .L_gpr_num_##name, num;
+GPR_LIST(GPR_NUM_EQU)
+#undef GPR_NUM_EQU
+
+#else /* __ASSEMBLER__ */
+
+#define GPR_NUM_EQU(num, name)  ".equ .L_gpr_num_" #name ", " #num "\n"
+#define DEFINE_ASM_GPR_NUMS     GPR_LIST(GPR_NUM_EQU)
+
+#endif /* __ASSEMBLER__ */
+
+#endif /* RISCV_GPR_NUM_H */
xen/arch/riscv/include/asm/processor.h +12 -1
index b1745c1071..e7b0f2321a 100644
@@ -12,7 +12,19 @@
 
  #ifndef __ASSEMBLER__
 
-/* On stack VCPU state */
+/*
+ * On stack VCPU state.
+ *
+ * x0..x31 must remain at the start of this structure, in architectural
+ * register-number order: code which resolves a register number to its saved
+ * value indexes this structure directly (instruction emulation via
+ * REG_PTR() from asm/riscv_encoding.h, exception table fixups via
+ * regs_get_gpr()). ->zero therefore has to stay at offset 0 and must always
+ * read as 0, since it supplies the value of x0 when x0 is used as a source
+ * operand. The layout is checked against GPR_LIST() at build time; see
+ * regs_get_gpr() in extable.c. Do not reorder these fields or insert
+ * anything between them.
Quoted 9 lines

xen/arch/riscv/include/asm/processor.h line 30

Quoted 3 lines
xen/arch/riscv/include/asm/processor.h +1 -0
+ */
  {
      unsigned long zero;

Comment claims ->zero "must always read as 0" as it's hard-wired to zero by the HW, but nothing enforces that, it's still a plain writable unsigned long. Maybe a write-side counterpart that special-cases num==0 as a no-op, or with a minimum ASSERT(num != 0) / BUG_ON(num == 0) to anticipate any future forbidden writes.

Could you please clarify where do you want me to put this check in this patch? In regs_get_gpr()? There is no write-side in this patch. Am i missing something?

Thanks in advance.

~ Oleksii

#100 lore raw

Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields

Quoted 310 lines · Oleksii Kurochko
Quoted 297 lines · Baptiste Le Duc
Quoted 237 lines

Extend the RISC-V exception table format to include a type and auxiliary data field.

The existing format only supports simple fixups. Some use cases require additional context from the fault (e.g. capturing trap information), which cannot be expressed with the current EX_TYPE_FIXUP entries.

Introduce a generic ASM_EXTABLE_RAW() helper to describe entries with a handler type and associated data. Reimplement ASM_EXTABLE() in terms of it using EX_TYPE_FIXUP for compatibility.

Add EX_TYPE_TRAP_INFO to allow handlers to retrieve trap state (sepc/scause/stval) and pass it to the fixup path. The data field is used to encode which GPR contains a pointer to a struct trap_info.

Provide ASM_EXTABLE_TRAP_INFO() as a convenience wrapper for this case.

Also add gpr-num.h, providing symbolic GPR numbers for use in assembly and inline asm. This is derived from Linux 6.16 with minor adjustments such as using .irp instead of open-coding the same using a set of .equ.

Update the exception handling code to dispatch based on the entry type.

xen/arch/riscv/extable.c +68 -2
index 5b89c4278c..6470198d01 100644
@@ -6,8 +6,10 @@
  #include <xen/sort.h>
  #include <xen/virtual_region.h>
 
+#include <asm/csr.h>
  #include <asm/extable.h>
  #include <asm/processor.h>
+#include <asm/traps.h>
 
  #define EX_FIELD(ptr, field) ((unsigned long)&(ptr)->field + (ptr)->field)
 
@@ -32,6 +34,12 @@ static void __init cf_check swap_ex(void *a, void *b)
 
      x->fixup = y->fixup + delta;
      y->fixup = tmp.fixup - delta;
+
+    x->type = y->type;
+    y->type = tmp.type;
+
+    x->data = y->data;
+    y->data = tmp.data;
  }
 
  static int cf_check cmp_ex(const void *a, const void *b)
@@ -59,7 +67,49 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
      regs->sepc = ex_fixup(ex);
  }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+#define CHECK_GPR_INDEX(num, name)                      \
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, name)   \
+                 != (num) * sizeof(unsigned long));
+
+static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
+                                  unsigned int num)
+{
+    /*
+     * The GPR number -> struct index mapping below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural order,
+     * matching the register numbers GPR_LIST() hands to the assembler.
+     */
+    GPR_LIST(CHECK_GPR_INDEX)
+
+    ASSERT(num < 32);
+
+    return ((const unsigned long *)regs)[num];
+}
+
+#undef CHECK_GPR_INDEX
+
+static void ex_handler_trap_info(const struct exception_table_entry *ex,
+                                 struct cpu_user_regs *regs,
+                                 unsigned long cause)
+{
+    struct trap_info *trap_info =
+        (struct trap_info *)regs_get_gpr(regs, ex->data);
+
+    BUG_ON(!trap_info);
+
+    /*
+     * Only stval still needs a CSR read: sepc and scause were already
+     * captured by the trap entry path and do_trap() respectively. Latch
+     * trap_info->sepc before regs->sepc is pointed at the fixup code.
+     */
+    trap_info->sepc = regs->sepc;
+    trap_info->scause = cause;
+    trap_info->stval = csr_read(CSR_STVAL);
+
+    regs->sepc = ex_fixup(ex);
+}
+
+bool fixup_exception(struct cpu_user_regs *regs, unsigned long cause)
  {
      unsigned long pc = regs->sepc;
      const struct virtual_region *region = find_text_region(pc);
@@ -77,7 +127,23 @@ bool fixup_exception(struct cpu_user_regs *regs)
      if ( !ex )
          return false;
 
-    ex_handler_fixup(ex, regs);
+    switch ( ex->type )
+    {
+    case EX_TYPE_FIXUP:
+        ex_handler_fixup(ex, regs);
+        break;
+
+    case EX_TYPE_TRAP_INFO:
+        ex_handler_trap_info(ex, regs, cause);
+        break;
+
+    default:
+        printk(XENLOG_ERR
+               "Unsupported exception table entry type %u for pc %#lx\n",
+               ex->type, pc);
+
+        return false;
+    }
 
      return true;
  }
xen/arch/riscv/include/asm/extable.h +44 -20
index c0128a9181..7378f86e7e 100644
@@ -3,17 +3,24 @@
  #ifndef ASM__RISCV__ASM_EXTABLE_H
  #define ASM__RISCV__ASM_EXTABLE_H
 
+#include <asm/gpr-num.h>
+
+#define EX_TYPE_FIXUP       0
+#define EX_TYPE_TRAP_INFO   1
+
  #ifdef __ASSEMBLER__
 
-#define ASM_EXTABLE(insn, fixup) \
-    .pushsection .ex_table, "a"; \
-    .balign     4;               \
-    .word       (insn) - .;      \
-    .word       (fixup) - .;     \
+#define ASM_EXTABLE_RAW(insn, fixup, type, data)    \
+    .pushsection .ex_table, "a";                    \
+    .balign     4;                                  \
+    .word       (insn) - .;                         \
+    .word       (fixup) - .;                        \
+    .half       (type);                             \
+    .half       (data);                             \
      .popsection
 
-.macro asm_extable, insn, fixup
-    ASM_EXTABLE(\insn, \fixup)
+.macro _asm_extable, insn, fixup
+    ASM_EXTABLE_RAW(\insn, \fixup, EX_TYPE_FIXUP, 0)
  .endm
 
  #else /* __ASSEMBLER__ */
@@ -23,20 +30,36 @@
 
  struct cpu_user_regs;
 
-#define ASM_EXTABLE(insn, fixup)      \
-    ".pushsection .ex_table, \"a\"\n" \
-    ".balign    4\n"                  \
-    ".word      (" #insn " - .)\n"    \
-    ".word      (" #fixup " - .)\n"   \
+#define ASM_EXTABLE_RAW(insn, fixup, type, data)    \
+    ".pushsection .ex_table, \"a\"\n"               \
+    ".balign    4\n"                                \
+    ".word      (" insn ") - .\n"                   \
+    ".word      (" fixup ") - .\n"                  \
+    ".half      (" type ")\n"                       \
+    ".half      (" data ")\n"                       \
      ".popsection\n"
 
+#define ASM_EXTABLE(insn, fixup)    \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_FIXUP), "0")
+
+#define EX_TRAP_INFO_REG(gpr)   \
+    "(.L_gpr_num_" #gpr ")"
+
+#define ASM_EXTABLE_TRAP_INFO(insn, fixup, data)                    \
+    DEFINE_ASM_GPR_NUMS                                             \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_TRAP_INFO),  \
+                    EX_TRAP_INFO_REG(data))
+
  /*
- * The exception table consists of pairs of relative offsets: the first
- * is the relative offset to an instruction that is allowed to fault,
- * and the second is the relative offset at which the program should
- * continue. No general-purpose registers are modified by the exception
- * handling mechanism itself, so it is up to the fixup code to handle
- * any necessary state cleanup.
+ * Each exception table entry consists of two relative offsets and a
+ * handler description: `insn` is the relative offset to an instruction
+ * that is allowed to fault, `fixup` is the relative offset at which the
+ * program should continue, `type` selects how the exception is handled
+ * (EX_TYPE_*), and `data` holds auxiliary information for the handler
+ * (e.g. for EX_TYPE_TRAP_INFO, the number of the GPR that contains a
+ * pointer to a struct trap_info). No general-purpose registers are
+ * modified by the exception handling mechanism itself, so it is up to
+ * the fixup code to handle any necessary state cleanup.
   *
   * The exception table and fixup code live out of line with the main
   * instruction path. This means when everything is well, we don't even
@@ -45,14 +68,15 @@ struct cpu_user_regs;
   */
  struct exception_table_entry {
      int32_t insn, fixup;
+    uint16_t type, data;
  };
 
  extern struct exception_table_entry __start___ex_table[];
  extern struct exception_table_entry __stop___ex_table[];
 
  void sort_exception_tables(void);
-bool fixup_exception(struct cpu_user_regs *regs);
+bool fixup_exception(struct cpu_user_regs *regs, unsigned long cause);
 
-#endif /* __ASSEMBLY__ */
+#endif /* __ASSEMBLER__ */
 
  #endif /* ASM__RISCV__ASM_EXTABLE_H */
xen/arch/riscv/include/asm/gpr-num.h new file +0 -0
new file mode 100644
index 0000000000..3b97a72e6c

xen/arch/riscv/include/asm/gpr-num.h line 3

Quoted 3 lines
xen/arch/riscv/include/asm/gpr-num.h new file +3 -0
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef RISCV_GPR_NUM_H
+#define RISCV_GPR_NUM_H

Nit: commit message says this is derived from Linux 6.16. Other imported RISC-V headers here carry an in-file note (bitops.h: "Based on linux/arch/.../bitops.h") but this file doesn't.

Quoted 54 lines
xen/arch/riscv/include/asm/gpr-num.h new file +33 -0
+/*
+ * GPRs by ABI name, together with their register number (x0 .. x31).
+ *
+ * This is the single source of truth for the mapping: it generates the
+ * .L_gpr_num_<name> assembler symbols used to turn a register name emitted
+ * by the compiler into a register number, and struct cpu_user_regs is
+ * checked against it at build time (see regs_get_gpr()). Neither list can
+ * therefore be changed without the other.
+ */
+#define GPR_LIST(x)                                 \
+    x(0,  zero) x(1,  ra)  x(2,  sp)  x(3,  gp)     \
+    x(4,  tp)   x(5,  t0)  x(6,  t1)  x(7,  t2)     \
+    x(8,  s0)   x(9,  s1)  x(10, a0)  x(11, a1)     \
+    x(12, a2)   x(13, a3)  x(14, a4)  x(15, a5)     \
+    x(16, a6)   x(17, a7)  x(18, s2)  x(19, s3)     \
+    x(20, s4)   x(21, s5)  x(22, s6)  x(23, s7)     \
+    x(24, s8)   x(25, s9)  x(26, s10) x(27, s11)    \
+    x(28, t3)   x(29, t4)  x(30, t5)  x(31, t6)
+
+#ifdef __ASSEMBLER__
+
+#define GPR_NUM_EQU(num, name)  .equ .L_gpr_num_##name, num;
+GPR_LIST(GPR_NUM_EQU)
+#undef GPR_NUM_EQU
+
+#else /* __ASSEMBLER__ */
+
+#define GPR_NUM_EQU(num, name)  ".equ .L_gpr_num_" #name ", " #num "\n"
+#define DEFINE_ASM_GPR_NUMS     GPR_LIST(GPR_NUM_EQU)
+
+#endif /* __ASSEMBLER__ */
+
+#endif /* RISCV_GPR_NUM_H */
xen/arch/riscv/include/asm/processor.h +12 -1
index b1745c1071..e7b0f2321a 100644
@@ -12,7 +12,19 @@
 
  #ifndef __ASSEMBLER__
 
-/* On stack VCPU state */
+/*
+ * On stack VCPU state.
+ *
+ * x0..x31 must remain at the start of this structure, in architectural
+ * register-number order: code which resolves a register number to its saved
+ * value indexes this structure directly (instruction emulation via
+ * REG_PTR() from asm/riscv_encoding.h, exception table fixups via
+ * regs_get_gpr()). ->zero therefore has to stay at offset 0 and must always
+ * read as 0, since it supplies the value of x0 when x0 is used as a source
+ * operand. The layout is checked against GPR_LIST() at build time; see
+ * regs_get_gpr() in extable.c. Do not reorder these fields or insert
+ * anything between them.
Quoted 9 lines

xen/arch/riscv/include/asm/processor.h line 30

Quoted 3 lines
xen/arch/riscv/include/asm/processor.h +1 -0
+ */
  {
      unsigned long zero;

Comment claims ->zero "must always read as 0" as it's hard-wired to zero by the HW, but nothing enforces that, it's still a plain writable unsigned long. Maybe a write-side counterpart that special-cases num==0 as a no-op, or with a minimum ASSERT(num != 0) / BUG_ON(num == 0) to anticipate any future forbidden writes.

Quoted 3 lines

Could you please clarify where do you want me to put this check in this patch? In regs_get_gpr()? There is no write-side in this patch. Am i missing something?

Honestly, I don't know where it would be most appropriate. But I'd like to highlight that nothing strictly forbids Xen code from writing a value != 0 into regs->zero.

I saw that in emulate_load(), which is introduced later, you used a branch to avoid an incorrect load into regs->zero:
/*
* 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.
*/

One solution could be to make cpu_user_regs private and add get/set methods, with a check in the setter that forbids this type of write, but that would imply some big changes, so it may not be the appropriate fix.

Quoted 8 lines

Thanks in advance.

~ Oleksii

#101 lore raw

Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields

In reply to Oleksii Kurochko

xen/arch/riscv/extable.c static void ex_handler_fixup(const struct exception_table_entry *ex, · line 72

Quoted 8 lines · Oleksii Kurochko
xen/arch/riscv/extable.c +3 -1
@@ -59,7 +67,49 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
     regs->sepc = ex_fixup(ex);
 }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+#define CHECK_GPR_INDEX(num, name)                      \
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, name)   \
+                 != (num) * sizeof(unsigned long));

Nit: Placement of the !=. Also there should be no semicolon here; it wants to ...

xen/arch/riscv/extable.c static void ex_handler_fixup(const struct exception_table_entry *ex, · line 82

Quoted 9 lines
xen/arch/riscv/extable.c +9 -0
+static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
+                                  unsigned int num)
+{
+    /*
+     * The GPR number -> struct index mapping below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural order,
+     * matching the register numbers GPR_LIST() hands to the assembler.
+     */
+    GPR_LIST(CHECK_GPR_INDEX)

... appear here instead, for this to actually look like a statement.

xen/arch/riscv/extable.c static void ex_handler_fixup(const struct exception_table_entry *ex, · line 86

Quoted 3 lines
xen/arch/riscv/extable.c +3 -0
+    ASSERT(num < 32);
+
+    return ((const unsigned long *)regs)[num];

What about release builds? You'd happily overrun the array there. Maybe (ab)use array_index_nospec() here?

xen/arch/riscv/extable.c static void ex_handler_fixup(const struct exception_table_entry *ex, · line 89

Quoted 3 lines
xen/arch/riscv/extable.c +3 -0
+}
+
+#undef CHECK_GPR_INDEX

If the sole use of the macro is in a single function, it wants #define-ing (and #undef-ing) there, not outside of it.

xen/arch/riscv/extable.c static void ex_handler_fixup(const struct exception_table_entry *ex, · line 98

Quoted 8 lines
xen/arch/riscv/extable.c +8 -0
+static void ex_handler_trap_info(const struct exception_table_entry *ex,
+                                 struct cpu_user_regs *regs,
+                                 unsigned long cause)
+{
+    struct trap_info *trap_info =
+        (struct trap_info *)regs_get_gpr(regs, ex->data);
+
+    BUG_ON(!trap_info);

This feels extremely weak. As you're fetching from a GPR, the majority of possible values stored in GPRs is going to be invalid, not just NULL. And while the accesses below would trap on NULL anyway, whether other bogus values would trap is pretty hard to predict. If trap_info is expected to always live on the stack, why not check for that (perhaps also check that the low few bits are clear)?

Quoted 13 lines
xen/arch/riscv/include/asm/extable.h +4 -5
@@ -23,20 +30,36 @@
 
 struct cpu_user_regs;
 
-#define ASM_EXTABLE(insn, fixup)      \
-    ".pushsection .ex_table, \"a\"\n" \
-    ".balign    4\n"                  \
-    ".word      (" #insn " - .)\n"    \
-    ".word      (" #fixup " - .)\n"   \
+#define ASM_EXTABLE_RAW(insn, fixup, type, data)    \
+    ".pushsection .ex_table, \"a\"\n"               \
+    ".balign    4\n"                                \
+    ".word      (" insn ") - .\n"                   \

xen/arch/riscv/include/asm/extable.h line 46

Quoted 10 lines
xen/arch/riscv/include/asm/extable.h +8 -0
+    ".word      (" fixup ") - .\n"                  \
+    ".half      (" type ")\n"                       \
+    ".half      (" data ")\n"                       \
     ".popsection\n"
 
+#define ASM_EXTABLE(insn, fixup)    \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_FIXUP), "0")
+
+#define EX_TRAP_INFO_REG(gpr)   \
+    "(.L_gpr_num_" #gpr ")"

This doesn't need to be wrapped across lines, does it?

xen/arch/riscv/include/asm/extable.h line 51

Quoted 4 lines
xen/arch/riscv/include/asm/extable.h +4 -0
+#define ASM_EXTABLE_TRAP_INFO(insn, fixup, data)                    \
+    DEFINE_ASM_GPR_NUMS                                             \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_TRAP_INFO),  \
+                    EX_TRAP_INFO_REG(data))

There's no visible statement separator between DEFINE_ASM_GPR_NUMS and ASM_EXTABLE_RAW(), which only works because DEFINE_ASM_GPR_NUMS appends a separator also at the very end of its expansion. I think that better would be changed, such that at use sites such as this one a separator becomes mandatory.

xen/arch/riscv/include/asm/extable.h

Quoted 11 lines
xen/arch/riscv/include/asm/extable.h +4 -6
 /*
- * The exception table consists of pairs of relative offsets: the first
- * is the relative offset to an instruction that is allowed to fault,
- * and the second is the relative offset at which the program should
- * continue. No general-purpose registers are modified by the exception
- * handling mechanism itself, so it is up to the fixup code to handle
- * any necessary state cleanup.
+ * Each exception table entry consists of two relative offsets and a
+ * handler description: `insn` is the relative offset to an instruction
+ * that is allowed to fault, `fixup` is the relative offset at which the
+ * program should continue,

"... in case of a fault, ..."

xen/arch/riscv/include/asm/gpr-num.h line 8

Quoted 11 lines
xen/arch/riscv/include/asm/gpr-num.h new file +8 -0
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef RISCV_GPR_NUM_H
+#define RISCV_GPR_NUM_H
+
+/*
+ * GPRs by ABI name, together with their register number (x0 .. x31).
+ *
+ * This is the single source of truth for the mapping:

True until here, but ...

Quoted 2 lines

it generates the
+ * .L_gpr_num_<name> assembler symbols

... no, it doesn't. It's ...

Quoted 10 lines

used to turn a register name emitted
+ * by the compiler into a register number, and struct cpu_user_regs is
+ * checked against it at build time (see regs_get_gpr()). Neither list can
+ * therefore be changed without the other.
+ */

xen/arch/riscv/include/asm/gpr-num.h new file +5 -0
+#define GPR_LIST(x)                                 \
+    x(0,  zero) x(1,  ra)  x(2,  sp)  x(3,  gp)     \
+    x(4,  tp)   x(5,  t0)  x(6,  t1)  x(7,  t2)     \
+    x(8,  s0)   x(9,  s1)  x(10, a0)  x(11, a1)     \
+    x(12, a2)   x(13, a3)  x(14, a4)  x(15, a5)     \

xen/arch/riscv/include/asm/gpr-num.h line 28

Quoted 10 lines
xen/arch/riscv/include/asm/gpr-num.h new file +10 -0
+    x(16, a6)   x(17, a7)  x(18, s2)  x(19, s3)     \
+    x(20, s4)   x(21, s5)  x(22, s6)  x(23, s7)     \
+    x(24, s8)   x(25, s9)  x(26, s10) x(27, s11)    \
+    x(28, t3)   x(29, t4)  x(30, t5)  x(31, t6)
+
+#ifdef __ASSEMBLER__
+
+#define GPR_NUM_EQU(num, name)  .equ .L_gpr_num_##name, num;
+GPR_LIST(GPR_NUM_EQU)
+#undef GPR_NUM_EQU

... this construct which does. This is relevant to separate, since GPR_LIST() is also used elsewhere.

xen/arch/riscv/include/asm/processor.h line 19

Quoted 12 lines
xen/arch/riscv/include/asm/processor.h +5 -1
@@ -12,7 +12,19 @@
 
 #ifndef __ASSEMBLER__
 
-/* On stack VCPU state */
+/*
+ * On stack VCPU state.
+ *
+ * x0..x31 must remain at the start of this structure, in architectural
+ * register-number order:

I understand that the order need retaining. But why would it being at the start of the struct be (overly) relevant? You could use the "zero" field as the anchor for calculations.

Jan

author Applied
#102 lore raw

Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields

Quoted 13 lines · Jan Beulich

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 72

Quoted 8 lines · Oleksii Kurochko
(quoted diff) +3 -1
@@ -59,7 +67,49 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
      regs->sepc = ex_fixup(ex);
  }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+#define CHECK_GPR_INDEX(num, name)                      \
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, name)   \
+                 != (num) * sizeof(unsigned long));

Nit: Placement of the !=. Also there should be no semicolon here; it wants to ...

Quoted 11 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 81

Quoted 9 lines
(quoted diff) +9 -0
+static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
+                                  unsigned int num)
+{
+    /*
+     * The GPR number -> struct index mapping below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural order,
+     * matching the register numbers GPR_LIST() hands to the assembler.
+     */
+    GPR_LIST(CHECK_GPR_INDEX)

... appear here instead, for this to actually look like a statement.

I will apply that.

Quoted 7 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 84

Quoted 4 lines
(quoted diff) +3 -0
+    ASSERT(num < 32);
+
+    return ((const unsigned long *)regs)[num];

What about release builds? You'd happily overrun the array there. Maybe (ab)use array_index_nospec() here?

num is coming not from guest, not from calculation in runtume, it is generated by assembler at the build time. So it should be always correct.

So just having the following looks okay to me:

static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
unsigned int num)
{
#define CHECK_GPR_INDEX(num, name) \
BUILD_BUG_ON(offsetof(struct cpu_user_regs, name) != \
(num) * sizeof(unsigned long))

#define GPR_CASE(nr, name) case nr: return regs->name;

/*
* The GPR number -> struct index mapping below relies on x0..x31 being
* laid out at the start of struct cpu_user_regs in architectural
order,

     * matching the register numbers GPR_LIST() hands to the assembler.
     */
    GPR_LIST(CHECK_GPR_INDEX);

#undef CHECK_GPR_INDEX

    switch ( num )
    {
    GPR_LIST(GPR_CASE)
    }

#undef GPR_CASE

    ASSERT_UNREACHABLE();

    return 0;
}

Any thoughts on that regard?

Quoted 7 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 87

Quoted 3 lines
(quoted diff) +3 -0
+}
+
+#undef CHECK_GPR_INDEX

If the sole use of the macro is in a single function, it wants #define-ing (and #undef-ing) there, not outside of it.

I will move inside.

Quoted 7 lines
Quoted 7 lines
(quoted diff) +7 -0
+static void ex_handler_trap_info(const struct exception_table_entry *ex,
+                                 struct cpu_user_regs *regs,
+                                 unsigned long cause)
+{
+    struct trap_info *trap_info =
+        (struct trap_info *)regs_get_gpr(regs, ex->data);
+
Quoted 9 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 95

Quoted 1 line
(quoted diff) +1 -0
+    BUG_ON(!trap_info);

This feels extremely weak. As you're fetching from a GPR, the majority of possible values stored in GPRs is going to be invalid, not just NULL. And while the accesses below would trap on NULL anyway, whether other bogus values would trap is pretty hard to predict. If trap_info is expected to always live on the stack, why not check for that (perhaps also check that the low few bits are clear)?

Considering the nature if how trap_info is filled I think we could just drop BUG_ON(), it is guaranteed by compilation that trap_info will be correct.

I think it could be also hard to force trap_info be always allocated on the stack.

Quoted 18 lines
Quoted 18 lines
(quoted diff) +7 -5
@@ -23,20 +30,36 @@
 
  struct cpu_user_regs;
 
-#define ASM_EXTABLE(insn, fixup)      \
-    ".pushsection .ex_table, \"a\"\n" \
-    ".balign    4\n"                  \
-    ".word      (" #insn " - .)\n"    \
-    ".word      (" #fixup " - .)\n"   \
+#define ASM_EXTABLE_RAW(insn, fixup, type, data)    \
+    ".pushsection .ex_table, \"a\"\n"               \
+    ".balign    4\n"                                \
+    ".word      (" insn ") - .\n"                   \
+    ".word      (" fixup ") - .\n"                  \
+    ".half      (" type ")\n"                       \
+    ".half      (" data ")\n"                       \
      ".popsection\n"
 
Quoted 7 lines

Review line 46

Quoted 5 lines
(quoted diff) +5 -0
+#define ASM_EXTABLE(insn, fixup)    \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_FIXUP), "0")
+
+#define EX_TRAP_INFO_REG(gpr)   \
+    "(.L_gpr_num_" #gpr ")"

This doesn't need to be wrapped across lines, does it?

Oh, really, it could be one line.

Quoted 11 lines

Review line 50

Quoted 5 lines
(quoted diff) +4 -0
+#define ASM_EXTABLE_TRAP_INFO(insn, fixup, data)                    \
+    DEFINE_ASM_GPR_NUMS                                             \
+    ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_TRAP_INFO),  \
+                    EX_TRAP_INFO_REG(data))

There's no visible statement separator between DEFINE_ASM_GPR_NUMS and ASM_EXTABLE_RAW(), which only works because DEFINE_ASM_GPR_NUMS appends a separator also at the very end of its expansion. I think that better would be changed, such that at use sites such as this one a separator becomes mandatory.

I will do the following then:

 #define ASM_EXTABLE_TRAP_INFO(insn, fixup, data)                    \
-    DEFINE_ASM_GPR_NUMS                                             \
+    DEFINE_ASM_GPR_NUMS "\n"                                        \
     ASM_EXTABLE_RAW(#insn, #fixup, __stringify(EX_TYPE_TRAP_INFO),  \
                     EX_TRAP_INFO_REG(data))
xen/arch/riscv/include/asm/gpr-num.h +8 -2
index 3b97a72e6c30..d497bd501e87 100644
@@ -23,13 +23,19 @@
 
 #ifdef __ASSEMBLER__
 
-#define GPR_NUM_EQU(num, name)  .equ .L_gpr_num_##name, num;
+/*
+ * The separator is emitted ahead of each entry rather than after it, so that
+ * the expansion doesn't end with one: whatever follows a use of the list has
+ * to supply its own separator, instead of silently relying on a trailing one.
+ */
+#define GPR_NUM_EQU(num, name)  ; .equ .L_gpr_num_##name, num
 GPR_LIST(GPR_NUM_EQU)
 #undef GPR_NUM_EQU
 
 #else /* __ASSEMBLER__ */
 
-#define GPR_NUM_EQU(num, name)  ".equ .L_gpr_num_" #name ", " #num "\n"
+/* See the comment ahead of the __ASSEMBLER__ flavour above. */
+#define GPR_NUM_EQU(num, name)  "\n.equ .L_gpr_num_" #name ", " #num
 #define DEFINE_ASM_GPR_NUMS     GPR_LIST(GPR_NUM_EQU)
 
Quoted 13 lines

Review line 55

Quoted 12 lines
(quoted diff) +4 -6
  /*
- * The exception table consists of pairs of relative offsets: the first
- * is the relative offset to an instruction that is allowed to fault,
- * and the second is the relative offset at which the program should
- * continue. No general-purpose registers are modified by the exception
- * handling mechanism itself, so it is up to the fixup code to handle
- * any necessary state cleanup.
+ * Each exception table entry consists of two relative offsets and a
+ * handler description: `insn` is the relative offset to an instruction
+ * that is allowed to fault, `fixup` is the relative offset at which the
+ * program should continue,
Quoted 1 line

"... in case of a fault, ..."

Applied.

Quoted 15 lines

xen/arch/riscv/include/asm/gpr-num.h line 8

Quoted 12 lines
xen/arch/riscv/include/asm/gpr-num.h new file +8 -0
@@ -0,0 +1,37 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+#ifndef RISCV_GPR_NUM_H
+#define RISCV_GPR_NUM_H
+
+/*
+ * GPRs by ABI name, together with their register number (x0 .. x31).
+ *
+ * This is the single source of truth for the mapping:

True until here, but ...

Quoted 4 lines
Quoted 2 lines

it generates the
+ * .L_gpr_num_<name> assembler symbols

... no, it doesn't. It's ...

I will update the comment to:
/*
* GPRs by ABI name, together with their register number (x0 .. x31). *
* This is the single source of truth for the mapping; users expand it with
* their own per-register macro. Among them, struct cpu_user_regs is
checked
* against this list at build time (see regs_get_gpr()), so neither
list can
* be changed without the other.
*/

#define GPR_LIST(x)                                 \
    ...

and then ...

Quoted 16 lines
Quoted 16 lines

used to turn a register name emitted
+ * by the compiler into a register number, and struct cpu_user_regs is
+ * checked against it at build time (see regs_get_gpr()). Neither list can
+ * therefore be changed without the other.
+ */

xen/arch/riscv/include/asm/gpr-num.h new file +10 -0
+#define GPR_LIST(x)                                 \
+    x(0,  zero) x(1,  ra)  x(2,  sp)  x(3,  gp)     \
+    x(4,  tp)   x(5,  t0)  x(6,  t1)  x(7,  t2)     \
+    x(8,  s0)   x(9,  s1)  x(10, a0)  x(11, a1)     \
+    x(12, a2)   x(13, a3)  x(14, a4)  x(15, a5)     \
+    x(16, a6)   x(17, a7)  x(18, s2)  x(19, s3)     \
+    x(20, s4)   x(21, s5)  x(22, s6)  x(23, s7)     \
+    x(24, s8)   x(25, s9)  x(26, s10) x(27, s11)    \
+    x(28, t3)   x(29, t4)  x(30, t5)  x(31, t6)
+
Quoted 9 lines

xen/arch/riscv/include/asm/gpr-num.h

Quoted 5 lines
xen/arch/riscv/include/asm/gpr-num.h new file +5 -0
+#ifdef __ASSEMBLER__
+
+#define GPR_NUM_EQU(num, name)  .equ .L_gpr_num_##name, num;
+GPR_LIST(GPR_NUM_EQU)
+#undef GPR_NUM_EQU

... this construct which does. This is relevant to separate, since GPR_LIST() is also used elsewhere.

... here:

/*
* Generate the .L_gpr_num_<name> assembler symbols, used to turn a
register
* name emitted by the compiler into a register number.
*
* The separator is emitted ahead of each entry rather than after it,
so that

Quoted 6 lines
Quoted 6 lines
xen/arch/riscv/include/asm/processor.h +0 -0
@@ -12,7 +12,19 @@
 
  #ifndef __ASSEMBLER__
 
Quoted 10 lines

xen/arch/riscv/include/asm/processor.h line 19

Quoted 6 lines
xen/arch/riscv/include/asm/processor.h +5 -1
-/* On stack VCPU state */
+/*
+ * On stack VCPU state.
+ *
+ * x0..x31 must remain at the start of this structure, in architectural
+ * register-number order:

I understand that the order need retaining. But why would it being at the start of the struct be (overly) relevant? You could use the "zero" field as the anchor for calculations.

You're right.

The placement requirement comes only from REG_PTR() computing a byte offset from the struct base. Anchoring it on ->zero instead removes the need for the block to sit at the start:

#define REG_PTR(insn, pos, regs) \
    (&(regs)->zero + (REG_OFFSET(insn, pos) / REGBYTES))

I'll do that and reword the comment to state the actual invariants: the x0..x31 fields have to stay contiguous and in ascending register-number order, and ->zero has to read as 0.

Thanks.

~ Oleksii

#103 lore raw

Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields

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

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 72

Quoted 8 lines · Oleksii Kurochko
(quoted diff) +3 -1
@@ -59,7 +67,49 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
      regs->sepc = ex_fixup(ex);
  }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+#define CHECK_GPR_INDEX(num, name)                      \
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, name)   \
+                 != (num) * sizeof(unsigned long));

Nit: Placement of the !=. Also there should be no semicolon here; it wants to ...

Quoted 11 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 81

Quoted 9 lines
(quoted diff) +9 -0
+static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
+                                  unsigned int num)
+{
+    /*
+     * The GPR number -> struct index mapping below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural order,
+     * matching the register numbers GPR_LIST() hands to the assembler.
+     */
+    GPR_LIST(CHECK_GPR_INDEX)

... appear here instead, for this to actually look like a statement.

I will apply that.

Quoted 7 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 84

Quoted 4 lines
(quoted diff) +3 -0
+    ASSERT(num < 32);
+
+    return ((const unsigned long *)regs)[num];

What about release builds? You'd happily overrun the array there. Maybe (ab)use array_index_nospec() here?

num is coming not from guest, not from calculation in runtume, it is generated by assembler at the build time. So it should be always correct.

So just having the following looks okay to me:

static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
unsigned int num)
{
#define CHECK_GPR_INDEX(num, name) \
BUILD_BUG_ON(offsetof(struct cpu_user_regs, name) != \
(num) * sizeof(unsigned long))

#define GPR_CASE(nr, name) case nr: return regs->name;

/*
* The GPR number -> struct index mapping below relies on x0..x31 being
* laid out at the start of struct cpu_user_regs in architectural
order,

      * matching the register numbers GPR_LIST() hands to the assembler.
      */
     GPR_LIST(CHECK_GPR_INDEX);

#undef CHECK_GPR_INDEX

     switch ( num )
     {
     GPR_LIST(GPR_CASE)
     }
Quoted 8 lines

#undef GPR_CASE

     ASSERT_UNREACHABLE();

     return 0;
}

Any thoughts on that regard?

Depends very much on how efficiently the compiler translates this (as opposed to the other variant).

Jan

#104 lore raw

Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields

Quoted 70 lines · Jan Beulich
Quoted 69 lines · Oleksii Kurochko
Quoted 13 lines · Jan Beulich

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 72

Quoted 8 lines · Oleksii Kurochko
(quoted diff) +3 -1
@@ -59,7 +67,49 @@ static void ex_handler_fixup(const struct exception_table_entry *ex,
       regs->sepc = ex_fixup(ex);
   }
 
-bool fixup_exception(struct cpu_user_regs *regs)
+#define CHECK_GPR_INDEX(num, name)                      \
+    BUILD_BUG_ON(offsetof(struct cpu_user_regs, name)   \
+                 != (num) * sizeof(unsigned long));

Nit: Placement of the !=. Also there should be no semicolon here; it wants to ...

Quoted 11 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 81

Quoted 9 lines
(quoted diff) +9 -0
+static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
+                                  unsigned int num)
+{
+    /*
+     * The GPR number -> struct index mapping below relies on x0..x31 being
+     * laid out at the start of struct cpu_user_regs in architectural order,
+     * matching the register numbers GPR_LIST() hands to the assembler.
+     */
+    GPR_LIST(CHECK_GPR_INDEX)

... appear here instead, for this to actually look like a statement.

I will apply that.

Quoted 7 lines

Review static void ex_handler_fixup(const struct exception_table_entry *ex, · line 84

Quoted 4 lines
(quoted diff) +3 -0
+    ASSERT(num < 32);
+
+    return ((const unsigned long *)regs)[num];

What about release builds? You'd happily overrun the array there. Maybe (ab)use array_index_nospec() here?

num is coming not from guest, not from calculation in runtume, it is generated by assembler at the build time. So it should be always correct.

So just having the following looks okay to me:

static unsigned long regs_get_gpr(const struct cpu_user_regs *regs,
unsigned int num)
{
#define CHECK_GPR_INDEX(num, name) \
BUILD_BUG_ON(offsetof(struct cpu_user_regs, name) != \
(num) * sizeof(unsigned long))

#define GPR_CASE(nr, name) case nr: return regs->name;

/*
* The GPR number -> struct index mapping below relies on x0..x31 being
* laid out at the start of struct cpu_user_regs in architectural
order,

       * matching the register numbers GPR_LIST() hands to the assembler.
       */
      GPR_LIST(CHECK_GPR_INDEX);

#undef CHECK_GPR_INDEX

      switch ( num )
      {
      GPR_LIST(GPR_CASE)
      }

#undef GPR_CASE

      ASSERT_UNREACHABLE();
Quoted 7 lines
Quoted 4 lines
      return 0;
}

Any thoughts on that regard?

Depends very much on how efficiently the compiler translates this (as opposed to the other variant).

It is worthier. I will follow then your original suggestion and use array_index_nospec().

~ Oleksii

#105 lore raw

PATCH v2 17/39 xen/riscv: decouple INSN_PSEUDO_VS_* from the hypervisor's XLEN

In reply to Oleksii Kurochko

htinst reports a pseudoinstruction when a guest page fault is taken on an implicit memory access done for VS-stage address translation. Four such values are defined, differing in the access type (read or write) and in the access width: 4 bytes (0x2000/0x2020) or 8 bytes (0x3000/0x3020).

That width is the width of a VS-stage PTE, i.e. it follows the guest's paging mode (4 bytes for Sv32, 8 bytes for Sv39 and wider) and has nothing to do with the XLEN Xen itself is built for. Selecting just one pair with where a guest running with VSXL=32 and Sv32 in vsatp produces the 4-byte forms. Such an htinst would not be recognized as a pseudoinstruction and the fault would be mistaken for an ordinary MMIO trap: Xen would fetch and decode whatever instruction sepc happens to point at (unrelated to the access which faulted) and emulate it against a guest physical address derived from htval, which for an implicit access holds the address of a VS-stage PTE rather than of any access the guest performed.

Define all four values unconditionally instead, named after the access width they encode rather than after the build's XLEN. On RV32 the 8-byte forms simply never occur, so recognizing them costs nothing.

Dropping the ladder loses no build-time coverage: a build for an XLEN other than 32 or 64 already fails on the equivalent ladders in asm/asm.h and asm/config.h, so no replacement #error is needed here. Adding one keyed on CONFIG_RISCV_* would in any case re-introduce exactly the conflation this patch removes.

This diverges from the imported version of riscv_encoding.h.

No functional change: the values have no user yet.

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

---
 xen/arch/riscv/include/asm/riscv_encoding.h | 16 ++++------------
 1 file changed, 4 insertions(+), 12 deletions(-)
xen/arch/riscv/include/asm/riscv_encoding.h +4 -12
index c63e5e304691..2d2e7e11b3ef 100644
@@ -839,25 +839,17 @@
 #define INSN_MASK_FENCE_TSO		0xffffffff
 #define INSN_MATCH_FENCE_TSO		0x8330000f
 
-#if __riscv_xlen == 64
-
 /* 64-bit read for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_LOAD		0x00003000
+#define INSN_PSEUDO_VS_LOAD64		0x00003000
 
 /* 64-bit write for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_STORE	0x00003020
-
-#elif __riscv_xlen == 32
+#define INSN_PSEUDO_VS_STORE64		0x00003020
 
 /* 32-bit read for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_LOAD		0x00002000
+#define INSN_PSEUDO_VS_LOAD32		0x00002000
 
 /* 32-bit write for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_STORE	0x00002020
-
-#else
-#error "Unexpected __riscv_xlen"
-#endif
+#define INSN_PSEUDO_VS_STORE32		0x00002020
 
 #define INSN_16BIT_MASK			0x3
 #define INSN_32BIT_MASK			0x1c
Signature · 1 line
2.55.0
#106 lore raw

Re: [PATCH v2 17/39] xen/riscv: decouple INSN_PSEUDO_VS_* from the hypervisor's XLEN

Quoted 9 lines

htinst reports a pseudoinstruction when a guest page fault is taken on an implicit memory access done for VS-stage address translation. Four such values are defined, differing in the access type (read or write) and in the access width: 4 bytes (0x2000/0x2020) or 8 bytes (0x3000/0x3020).

That width is the width of a VS-stage PTE, i.e. it follows the guest's paging mode (4 bytes for Sv32, 8 bytes for Sv39 and wider) and has nothing to do with the XLEN Xen itself is built for. Selecting just one pair with where a guest running with VSXL=32 and Sv32 in vsatp produces the 4-byte

Sentence is broken. Guess you mean "Selecting just one pair based on Xen's XLEN misses the case where …".

Quoted 40 lines

forms. Such an htinst would not be recognized as a pseudoinstruction and the fault would be mistaken for an ordinary MMIO trap: Xen would fetch and decode whatever instruction sepc happens to point at (unrelated to the access which faulted) and emulate it against a guest physical address derived from htval, which for an implicit access holds the address of a VS-stage PTE rather than of any access the guest performed.

Define all four values unconditionally instead, named after the access width they encode rather than after the build's XLEN. On RV32 the 8-byte forms simply never occur, so recognizing them costs nothing.

Dropping the ladder loses no build-time coverage: a build for an XLEN other than 32 or 64 already fails on the equivalent ladders in asm/asm.h and asm/config.h, so no replacement #error is needed here. Adding one keyed on CONFIG_RISCV_* would in any case re-introduce exactly the conflation this patch removes.

This diverges from the imported version of riscv_encoding.h.

No functional change: the values have no user yet.

xen/arch/riscv/include/asm/riscv_encoding.h +1 -5
index c63e5e3046..2d2e7e11b3 100644
@@ -839,25 +839,17 @@
 #define INSN_MASK_FENCE_TSO		0xffffffff
 #define INSN_MATCH_FENCE_TSO		0x8330000f
 
-#if __riscv_xlen == 64
-
 /* 64-bit read for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_LOAD		0x00003000
+#define INSN_PSEUDO_VS_LOAD64		0x00003000
 
 /* 64-bit write for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_STORE	0x00003020
-

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

Quoted 10 lines
xen/arch/riscv/include/asm/riscv_encoding.h +2 -4
-#elif __riscv_xlen == 32
+#define INSN_PSEUDO_VS_STORE64		0x00003020
 
 /* 32-bit read for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_LOAD		0x00002000
+#define INSN_PSEUDO_VS_LOAD32		0x00002000
 
 /* 32-bit write for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_STORE	0x00002020
-

Whole point of patch is these no longer depend on build XLEN, yet comments still say "(RV64)"/"(RV32)" which could be confusing. Maybe it should be better to indicate, as the spec does, that RV32 values are used when VSXLEN=32 (only sv32 paging mode) and RV64 values when VSXLEN=64 (sv39+ paging modes).

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

Re: [PATCH v2 17/39] xen/riscv: decouple INSN_PSEUDO_VS_* from the hypervisor's XLEN

Quoted 11 lines · Baptiste Le Duc
Quoted 9 lines

htinst reports a pseudoinstruction when a guest page fault is taken on an implicit memory access done for VS-stage address translation. Four such values are defined, differing in the access type (read or write) and in the access width: 4 bytes (0x2000/0x2020) or 8 bytes (0x3000/0x3020).

That width is the width of a VS-stage PTE, i.e. it follows the guest's paging mode (4 bytes for Sv32, 8 bytes for Sv39 and wider) and has nothing to do with the XLEN Xen itself is built for. Selecting just one pair with where a guest running with VSXL=32 and Sv32 in vsatp produces the 4-byte

Sentence is broken. Guess you mean "Selecting just one pair based on Xen's XLEN misses the case where …".

Likely it is becuase of my low level English but it seems that original version wast okay and what you added is just a part from prev. sentence but I will add your suggestion for better clearness. Thanks for noticing that!

Quoted 48 lines
Quoted 48 lines

forms. Such an htinst would not be recognized as a pseudoinstruction and the fault would be mistaken for an ordinary MMIO trap: Xen would fetch and decode whatever instruction sepc happens to point at (unrelated to the access which faulted) and emulate it against a guest physical address derived from htval, which for an implicit access holds the address of a VS-stage PTE rather than of any access the guest performed.

Define all four values unconditionally instead, named after the access width they encode rather than after the build's XLEN. On RV32 the 8-byte forms simply never occur, so recognizing them costs nothing.

Dropping the ladder loses no build-time coverage: a build for an XLEN other than 32 or 64 already fails on the equivalent ladders in asm/asm.h and asm/config.h, so no replacement #error is needed here. Adding one keyed on CONFIG_RISCV_* would in any case re-introduce exactly the conflation this patch removes.

This diverges from the imported version of riscv_encoding.h.

No functional change: the values have no user yet.

xen/arch/riscv/include/asm/riscv_encoding.h +3 -7
index c63e5e3046..2d2e7e11b3 100644
@@ -839,25 +839,17 @@
  #define INSN_MASK_FENCE_TSO		0xffffffff
  #define INSN_MATCH_FENCE_TSO		0x8330000f
 
-#if __riscv_xlen == 64
-
  /* 64-bit read for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_LOAD		0x00003000
+#define INSN_PSEUDO_VS_LOAD64		0x00003000
 
  /* 64-bit write for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_STORE	0x00003020
-
-#elif __riscv_xlen == 32
+#define INSN_PSEUDO_VS_STORE64		0x00003020
 
  /* 32-bit read for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_LOAD		0x00002000
+#define INSN_PSEUDO_VS_LOAD32		0x00002000
 
Quoted 9 lines

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

Quoted 3 lines
xen/arch/riscv/include/asm/riscv_encoding.h +0 -2
  /* 32-bit write for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_STORE	0x00002020
-

Whole point of patch is these no longer depend on build XLEN, yet comments still say "(RV64)"/"(RV32)" which could be confusing. Maybe it should be better to indicate, as the spec does, that RV32 values are used when VSXLEN=32 (only sv32 paging mode) and RV64 values when VSXLEN=64 (sv39+ paging modes).

Could you please clarify to me what in the spec it is?

This comments are just copy from the spec:

Table 39. Special pseudoinstruction values for guest-page faults. The RV32 values are used when VSXLEN=32, and the RV64 values when VSXLEN=64.

Value           Meaning
0x00002000      32-bit read for VS-stage address translation (RV32)
0x00002020      32-bit write for VS-stage address translation (RV32)
Value           Meaning
0x00003000      64-bit read for VS-stage address translation (RV64)
0x00003020      64-bit write for VS-stage address translation (RV64)

So the comments are just copy of "Meaning" column from the spec.

And I think that Meaning column is fine here as we could have a case of when hypervisor has XLEN=64 but guests could be on it RV32 and RV64 and if a guest is RV32 (what means VSXLEN=32) then the comment above defintion mean that we hav 32-bit read/write VS-stage address translation for (RV32) guest and the similar is for RV64.

Do I miss something? Is a comments make more sense now or I have to still update them in some way?

Thanks!

~ Oleksii

#108 lore raw

Re: [PATCH v2 17/39] xen/riscv: decouple INSN_PSEUDO_VS_* from the hypervisor's XLEN

Quoted 78 lines · Oleksii Kurochko
Quoted 11 lines · Baptiste Le Duc
Quoted 9 lines

htinst reports a pseudoinstruction when a guest page fault is taken on an implicit memory access done for VS-stage address translation. Four such values are defined, differing in the access type (read or write) and in the access width: 4 bytes (0x2000/0x2020) or 8 bytes (0x3000/0x3020).

That width is the width of a VS-stage PTE, i.e. it follows the guest's paging mode (4 bytes for Sv32, 8 bytes for Sv39 and wider) and has nothing to do with the XLEN Xen itself is built for. Selecting just one pair with where a guest running with VSXL=32 and Sv32 in vsatp produces the 4-byte

Sentence is broken. Guess you mean "Selecting just one pair based on Xen's XLEN misses the case where …".

Likely it is becuase of my low level English but it seems that original version wast okay and what you added is just a part from prev. sentence but I will add your suggestion for better clearness. Thanks for noticing that!

Quoted 48 lines
Quoted 48 lines

forms. Such an htinst would not be recognized as a pseudoinstruction and the fault would be mistaken for an ordinary MMIO trap: Xen would fetch and decode whatever instruction sepc happens to point at (unrelated to the access which faulted) and emulate it against a guest physical address derived from htval, which for an implicit access holds the address of a VS-stage PTE rather than of any access the guest performed.

Define all four values unconditionally instead, named after the access width they encode rather than after the build's XLEN. On RV32 the 8-byte forms simply never occur, so recognizing them costs nothing.

Dropping the ladder loses no build-time coverage: a build for an XLEN other than 32 or 64 already fails on the equivalent ladders in asm/asm.h and asm/config.h, so no replacement #error is needed here. Adding one keyed on CONFIG_RISCV_* would in any case re-introduce exactly the conflation this patch removes.

This diverges from the imported version of riscv_encoding.h.

No functional change: the values have no user yet.

xen/arch/riscv/include/asm/riscv_encoding.h +3 -7
index c63e5e3046..2d2e7e11b3 100644
@@ -839,25 +839,17 @@
  #define INSN_MASK_FENCE_TSO		0xffffffff
  #define INSN_MATCH_FENCE_TSO		0x8330000f
 
-#if __riscv_xlen == 64
-
  /* 64-bit read for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_LOAD		0x00003000
+#define INSN_PSEUDO_VS_LOAD64		0x00003000
 
  /* 64-bit write for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_STORE	0x00003020
-
-#elif __riscv_xlen == 32
+#define INSN_PSEUDO_VS_STORE64		0x00003020
 
  /* 32-bit read for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_LOAD		0x00002000
+#define INSN_PSEUDO_VS_LOAD32		0x00002000
 
Quoted 9 lines

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

Quoted 3 lines
xen/arch/riscv/include/asm/riscv_encoding.h +0 -2
  /* 32-bit write for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_STORE	0x00002020
-

Whole point of patch is these no longer depend on build XLEN, yet comments still say "(RV64)"/"(RV32)" which could be confusing. Maybe it should be better to indicate, as the spec does, that RV32 values are used when VSXLEN=32 (only sv32 paging mode) and RV64 values when VSXLEN=64 (sv39+ paging modes).

Quoted 1 line

Could you please clarify to me what in the spec it is?

It is the same table as you indicated below (but mine is Table 56, so it seems we don't have the same spec version, I'm using the version 20260120).

When I found unclear is that "RV32" or "RV64" alone is ambiguous, since host and guest can differ (e.g. RV64 host running an RV32 guest). Saying it depends on VSXLEN instead makes clear which one is meant.

Quoted 15 lines

This comments are just copy from the spec:

Table 39. Special pseudoinstruction values for guest-page faults. The RV32 values are used when VSXLEN=32, and the RV64 values when VSXLEN=64.

Value           Meaning
0x00002000      32-bit read for VS-stage address translation (RV32)
0x00002020      32-bit write for VS-stage address translation (RV32)
Value           Meaning
0x00003000      64-bit read for VS-stage address translation (RV64)
0x00003020      64-bit write for VS-stage address translation (RV64)

So the comments are just copy of "Meaning" column from the spec.

Quoted 9 lines

And I think that Meaning column is fine here as we could have a case of when hypervisor has XLEN=64 but guests could be on it RV32 and RV64 and if a guest is RV32 (what means VSXLEN=32) then the comment above defintion mean that we hav 32-bit read/write VS-stage address translation for (RV32) guest and the similar is for RV64.

Do I miss something? Is a comments make more sense now or I have to still update them in some way?

I think it would be more clear to modify the comment by that:
/* 32-bit read for VS-stage address translation (VSXLEN=32) */

But now with your explanation, your comment is more clear as it specify VS-stage address, so the guest. Feel free to adopt my version or not.

Quoted 8 lines

Thanks!

~ Oleksii

#109 lore raw

Re: [PATCH v2 17/39] xen/riscv: decouple INSN_PSEUDO_VS_* from the hypervisor's XLEN

Quoted 109 lines · Baptiste Le Duc
Quoted 78 lines · Oleksii Kurochko
Quoted 11 lines · Baptiste Le Duc
Quoted 9 lines

htinst reports a pseudoinstruction when a guest page fault is taken on an implicit memory access done for VS-stage address translation. Four such values are defined, differing in the access type (read or write) and in the access width: 4 bytes (0x2000/0x2020) or 8 bytes (0x3000/0x3020).

That width is the width of a VS-stage PTE, i.e. it follows the guest's paging mode (4 bytes for Sv32, 8 bytes for Sv39 and wider) and has nothing to do with the XLEN Xen itself is built for. Selecting just one pair with where a guest running with VSXL=32 and Sv32 in vsatp produces the 4-byte

Sentence is broken. Guess you mean "Selecting just one pair based on Xen's XLEN misses the case where …".

Likely it is becuase of my low level English but it seems that original version wast okay and what you added is just a part from prev. sentence but I will add your suggestion for better clearness. Thanks for noticing that!

Quoted 48 lines
Quoted 48 lines

forms. Such an htinst would not be recognized as a pseudoinstruction and the fault would be mistaken for an ordinary MMIO trap: Xen would fetch and decode whatever instruction sepc happens to point at (unrelated to the access which faulted) and emulate it against a guest physical address derived from htval, which for an implicit access holds the address of a VS-stage PTE rather than of any access the guest performed.

Define all four values unconditionally instead, named after the access width they encode rather than after the build's XLEN. On RV32 the 8-byte forms simply never occur, so recognizing them costs nothing.

Dropping the ladder loses no build-time coverage: a build for an XLEN other than 32 or 64 already fails on the equivalent ladders in asm/asm.h and asm/config.h, so no replacement #error is needed here. Adding one keyed on CONFIG_RISCV_* would in any case re-introduce exactly the conflation this patch removes.

This diverges from the imported version of riscv_encoding.h.

No functional change: the values have no user yet.

xen/arch/riscv/include/asm/riscv_encoding.h +3 -7
index c63e5e3046..2d2e7e11b3 100644
@@ -839,25 +839,17 @@
   #define INSN_MASK_FENCE_TSO		0xffffffff
   #define INSN_MATCH_FENCE_TSO		0x8330000f
 
-#if __riscv_xlen == 64
-
   /* 64-bit read for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_LOAD		0x00003000
+#define INSN_PSEUDO_VS_LOAD64		0x00003000
 
   /* 64-bit write for VS-stage address translation (RV64) */
-#define INSN_PSEUDO_VS_STORE	0x00003020
-
-#elif __riscv_xlen == 32
+#define INSN_PSEUDO_VS_STORE64		0x00003020
 
   /* 32-bit read for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_LOAD		0x00002000
+#define INSN_PSEUDO_VS_LOAD32		0x00002000
 
Quoted 9 lines

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

Quoted 3 lines
xen/arch/riscv/include/asm/riscv_encoding.h +0 -2
   /* 32-bit write for VS-stage address translation (RV32) */
-#define INSN_PSEUDO_VS_STORE	0x00002020
-

Whole point of patch is these no longer depend on build XLEN, yet comments still say "(RV64)"/"(RV32)" which could be confusing. Maybe it should be better to indicate, as the spec does, that RV32 values are used when VSXLEN=32 (only sv32 paging mode) and RV64 values when VSXLEN=64 (sv39+ paging modes).

Quoted 1 line

Could you please clarify to me what in the spec it is?

It is the same table as you indicated below (but mine is Table 56, so it seems we don't have the same spec version, I'm using the version 20260120).

When I found unclear is that "RV32" or "RV64" alone is ambiguous, since host and guest can differ (e.g. RV64 host running an RV32 guest). Saying it depends on VSXLEN instead makes clear which one is meant.

Quoted 21 lines

This comments are just copy from the spec:

Table 39. Special pseudoinstruction values for guest-page faults. The RV32 values are used when VSXLEN=32, and the RV64 values when VSXLEN=64.

Value           Meaning
0x00002000      32-bit read for VS-stage address translation (RV32)
0x00002020      32-bit write for VS-stage address translation (RV32)
Value           Meaning
0x00003000      64-bit read for VS-stage address translation (RV64)
0x00003020      64-bit write for VS-stage address translation (RV64)

So the comments are just copy of "Meaning" column from the spec.

And I think that Meaning column is fine here as we could have a case of when hypervisor has XLEN=64 but guests could be on it RV32 and RV64 and if a guest is RV32 (what means VSXLEN=32) then the comment above defintion mean that we hav 32-bit read/write VS-stage address translation for (RV32) guest and the similar is for RV64.

Quoted 8 lines
Quoted 3 lines

Do I miss something? Is a comments make more sense now or I have to still update them in some way?

I think it would be more clear to modify the comment by that:
/* 32-bit read for VS-stage address translation (VSXLEN=32) */

But now with your explanation, your comment is more clear as it specify VS-stage address, so the guest. Feel free to adopt my version or not.

Agree your suggestion here will be more clear. I will apply it.

Thanks.

~ Oleksii

#110 lore raw

PATCH v2 18/39 xen/riscv: add guest page fault handling stub

In reply to Oleksii Kurochko

Add a handler for guest page faults and hook it into the trap path, providing the trap-side entry point which will later feed the MMIO dispatch.

This will be used, for example, to trap accesses to APLIC registers so that a guest can initialize and drive an emulated interrupt controller.

Two of the situations handled here are already decided, as neither can ever be turned into an emulated access:

- A fault reported with a pseudoinstruction in htinst was taken on an implicit access made for VS-stage address translation, so htval holds the address of a VS-stage PTE rather than of anything the guest asked for, and the guest physical address behind the original access is not known. This is orthogonal to the cause and can accompany any of the three, which is why it is checked first. scause keeps reporting the type of the original access, and on bare hardware a PTE which cannot be read raises an access fault of exactly that type, so reflect one back to the guest.

- A fetch fault means the guest tried to execute from a guest physical address which is unmapped or which G-stage does not allow to be executed. On bare hardware a fetch from physical memory which does not exist, or which may not be executed, raises an instruction access fault, so reflect one back too.

Explicit loads and stores are where MMIO emulation will hook in.

Neither of the two paths above consults the p2m first, and neither will the MMIO one: RISC-V has no populate-on-demand, no paging and no mem_access, so every guest mapping is established eagerly and a G-stage fault never denotes a mapping Xen could install to let the faulting access complete.

Both of the helpers this leans on, resolve_faulting_gpa() and trap_redirect(), are BUG_ON() placeholders for now, so each of the three causes currently takes the host down rather than the domain. That is no worse than before this patch, where the same causes fell through to do_unexpected_trap() and die(). Implementing the helpers is left to later patches.

---
Changes in v2:
- Introduce struct guest_fault.
- Change the prototypes of emulate_{load,store}() to take a non-const struct guest_fault, as emulation has to write the destination register and advance sepc.
- Add handling of pseudoinstructions before the call of emulate_{load,store}.
- Rename get_fault_gpa to resolve_faulting_gpa and change its prototype to take struct guest_fault.
- Add handling of CAUSE_FETCH_GUEST_PAGE_FAULT now.
- Document why the p2m is not consulted before a fault is injected, and add a BUILD_BUG_ON() on CONFIG_VM_EVENT to catch that assumption breaking.
- Print the fault cause in the domain_crash() message rather than deriving an access type string which cannot cover every case.
- Move code to introduced emulate.c instead of having it in traps.c
---

---
 xen/arch/riscv/Makefile              |   1 +
 xen/arch/riscv/emulate.c             | 179 +++++++++++++++++++++++++++
 xen/arch/riscv/include/asm/emulate.h |  10 ++
 xen/arch/riscv/include/asm/traps.h   |   3 +
 xen/arch/riscv/traps.c               |  23 +++-
 5 files changed, 215 insertions(+), 1 deletion(-)
 create mode 100644 xen/arch/riscv/emulate.c
 create mode 100644 xen/arch/riscv/include/asm/emulate.h
xen/arch/riscv/Makefile +1 -0
index ce6410a299a4..4a021ee9eb70 100644
@@ -6,6 +6,7 @@ obj-y += domain.o
 obj-y += domain-build.init.o
 obj-$(CONFIG_DOM0LESS_BOOT) += dom0less-build.init.o
 obj-$(CONFIG_EARLY_PRINTK) += early_printk.o
+obj-y += emulate.o
 obj-y += entry.o
 obj-y += extable.o
 obj-y += guestcopy.o
xen/arch/riscv/emulate.c new file +179 -0

179 lines not on this page · raw message

xen/arch/riscv/include/asm/emulate.h new file +10 -0
new file mode 100644
index 000000000000..59e69ca6794c
@@ -0,0 +1,10 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+#ifndef RISCV_EMULATE_H
+#define RISCV_EMULATE_H
+
+struct cpu_user_regs;
+
+void handle_guest_page_fault(struct cpu_user_regs *regs, unsigned long cause);
+
+#endif /* RISCV_EMULATE_H */
xen/arch/riscv/include/asm/traps.h +3 -0
index 8d4ab664bca9..38c6423742e0 100644
@@ -17,6 +17,9 @@ void do_trap(struct cpu_user_regs *cpu_regs);
 void handle_trap(void);
 void trap_init(void);
 
+/* Reflect @trap back to the guest, i.e. enter its VS-mode trap handler. */
+void trap_redirect(const struct trap_info *trap);
+
 #endif /* __ASSEMBLER__ */
 
 #endif /* ASM__RISCV__TRAPS_H */
xen/arch/riscv/traps.c +22 -1
index 11a6fa1bc942..9cd37d943be1 100644
@@ -14,6 +14,7 @@
 
 #include <asm/extable.h>
 #include <asm/cpufeature.h>
+#include <asm/emulate.h>
 #include <asm/intc.h>
 #include <asm/processor.h>
 #include <asm/riscv_encoding.h>
@@ -193,6 +194,7 @@ void do_trap(struct cpu_user_regs *cpu_regs)
 {
     register_t pc = cpu_regs->sepc;
     unsigned long cause = csr_read(CSR_SCAUSE);
+    bool from_guest = cpu_regs->hstatus & HSTATUS_SPV;
 
     switch ( cause )
     {
@@ -203,6 +205,19 @@ void do_trap(struct cpu_user_regs *cpu_regs)
         vsbi_handle_ecall(cpu_regs);
         break;
 
+    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);
+
+        handle_guest_page_fault(cpu_regs, cause);
+        break;
+
     case CAUSE_ILLEGAL_INSTRUCTION:
         if ( do_bug_frame(cpu_regs, pc) >= 0 )
         {
@@ -251,7 +266,7 @@ void do_trap(struct cpu_user_regs *cpu_regs)
         break;
     }
 
-    if ( cpu_regs->hstatus & HSTATUS_SPV )
+    if ( from_guest )
         check_for_pcpu_work();
 }
 
@@ -275,3 +290,9 @@ enum mc_disposition arch_do_multicall_call(struct mc_state *state)
     BUG_ON("unimplemented");
     return mc_continue;
 }
+
+/* Redirect trap to Guest. */
+void trap_redirect(const struct trap_info *trap)
+{
+    BUG_ON("unimplemented");
+}
Signature · 1 line
2.55.0
#111 lore raw

Re: [PATCH v2 18/39] xen/riscv: add guest page fault handling stub

Quoted 34 lines

Add a handler for guest page faults and hook it into the trap path, providing the trap-side entry point which will later feed the MMIO dispatch.

This will be used, for example, to trap accesses to APLIC registers so that a guest can initialize and drive an emulated interrupt controller.

Two of the situations handled here are already decided, as neither can ever be turned into an emulated access:

- A fault reported with a pseudoinstruction in htinst was taken on an implicit access made for VS-stage address translation, so htval holds the address of a VS-stage PTE rather than of anything the guest asked for, and the guest physical address behind the original access is not known. This is orthogonal to the cause and can accompany any of the three, which is why it is checked first. scause keeps reporting the type of the original access, and on bare hardware a PTE which cannot be read raises an access fault of exactly that type, so reflect one back to the guest.

- A fetch fault means the guest tried to execute from a guest physical address which is unmapped or which G-stage does not allow to be executed. On bare hardware a fetch from physical memory which does not exist, or which may not be executed, raises an instruction access fault, so reflect one back too.

Explicit loads and stores are where MMIO emulation will hook in.

Neither of the two paths above consults the p2m first, and neither will the MMIO one: RISC-V has no populate-on-demand, no paging and no mem_access, so every guest mapping is established eagerly and a G-stage fault never denotes a mapping Xen could install to let the faulting access complete.

Quoted 9 lines

Both of the helpers this leans on, resolve_faulting_gpa() and trap_redirect(), are BUG_ON() placeholders for now, so each of the three causes currently takes the host down rather than the domain. That is no worse than before this patch, where the same causes fell through to do_unexpected_trap() and die(). Implementing the helpers is left to later patches.

I think the commit message it not very clear as it conflates two different countable things (the 3 fault causes reported via scause vs. the pseudoinstruction condition, which is orthogonal and can accompany any of them), which makes "two situations decided" or "any of the three" hard to follow on first read.

Here is a proposition with a split to distinguish fetch-fault and pseudoinstruction cases into explicit bullets with their outcome stated ("Decided here"), and added spec-mentioned conditions about the pseudoinstruction's existence conditions:

```
    Add a handler for guest page faults and hook it into the trap path,
    providing the trap-side entry point which will later feed the MMIO
    dispatch.

    This will be used, for example, to trap accesses to APLIC registers so
    that a guest can initialize and drive an emulated interrupt controller.

    A G-stage (stage-2) fault has one of three causes, reported via scause:

        - Fetch fault: guest tried to execute from a guest-physical address
        that is unmapped or that G-stage marks non-executable. Never
        emulatable (nothing to emulate a fetch into). On real hardware
        this raises an instruction access fault, so Xen reflects the same
        fault back to the guest. Decided here.

        - Load fault / Store fault: left undecided by this patch, this is
        where MMIO emulation will hook in later.

    Any of these three faults can instead be reported via a pseudoinstruction
    in htinst, when both:

        (a) the fault occurred on an implicit access Xen made to walk a
            VS-stage page table, and
        (b) htval holds a nonzero value: the guest-physical address of that
            VS-stage PTE, not of the guest's original access.

    However, none of these paths consult the p2m first, and the future MMIO path
    won't either: RISC-V has no populate-on-demand, no paging, and no
    mem_access, so every guest mapping is established eagerly. A G-stage
    fault therefore never indicates a mapping Xen could lazily resolve to
    let the access complete.

    Both helpers this handler relies on, resolve_faulting_gpa() and
    trap_redirect(), are BUG_ON() placeholders for now, so all three causes
    currently take the host down instead of just the guest. This is no worse
    than before this patch, where these traps fell through to
    do_unexpected_trap() and die().
```
Signature · 1 line
Baptiste Le Duc <[email protected]>
#112 lore raw

Re: [PATCH v2 18/39] xen/riscv: add guest page fault handling stub

Quoted 85 lines · Baptiste Le Duc
Quoted 34 lines

Add a handler for guest page faults and hook it into the trap path, providing the trap-side entry point which will later feed the MMIO dispatch.

This will be used, for example, to trap accesses to APLIC registers so that a guest can initialize and drive an emulated interrupt controller.

Two of the situations handled here are already decided, as neither can ever be turned into an emulated access:

- A fault reported with a pseudoinstruction in htinst was taken on an implicit access made for VS-stage address translation, so htval holds the address of a VS-stage PTE rather than of anything the guest asked for, and the guest physical address behind the original access is not known. This is orthogonal to the cause and can accompany any of the three, which is why it is checked first. scause keeps reporting the type of the original access, and on bare hardware a PTE which cannot be read raises an access fault of exactly that type, so reflect one back to the guest.

- A fetch fault means the guest tried to execute from a guest physical address which is unmapped or which G-stage does not allow to be executed. On bare hardware a fetch from physical memory which does not exist, or which may not be executed, raises an instruction access fault, so reflect one back too.

Explicit loads and stores are where MMIO emulation will hook in.

Neither of the two paths above consults the p2m first, and neither will the MMIO one: RISC-V has no populate-on-demand, no paging and no mem_access, so every guest mapping is established eagerly and a G-stage fault never denotes a mapping Xen could install to let the faulting access complete.

Quoted 9 lines

Both of the helpers this leans on, resolve_faulting_gpa() and trap_redirect(), are BUG_ON() placeholders for now, so each of the three causes currently takes the host down rather than the domain. That is no worse than before this patch, where the same causes fell through to do_unexpected_trap() and die(). Implementing the helpers is left to later patches.

I think the commit message it not very clear as it conflates two different countable things (the 3 fault causes reported via scause vs. the pseudoinstruction condition, which is orthogonal and can accompany any of them), which makes "two situations decided" or "any of the three" hard to follow on first read.

Here is a proposition with a split to distinguish fetch-fault and pseudoinstruction cases into explicit bullets with their outcome stated ("Decided here"), and added spec-mentioned conditions about the pseudoinstruction's existence conditions:

```
     Add a handler for guest page faults and hook it into the trap path,
     providing the trap-side entry point which will later feed the MMIO
     dispatch.

     This will be used, for example, to trap accesses to APLIC registers so
     that a guest can initialize and drive an emulated interrupt controller.

     A G-stage (stage-2) fault has one of three causes, reported via scause:

         - Fetch fault: guest tried to execute from a guest-physical address
         that is unmapped or that G-stage marks non-executable. Never
         emulatable (nothing to emulate a fetch into). On real hardware
         this raises an instruction access fault, so Xen reflects the same
         fault back to the guest. Decided here.

         - Load fault / Store fault: left undecided by this patch, this is
         where MMIO emulation will hook in later.

     Any of these three faults can instead be reported via a pseudoinstruction
     in htinst, when both:

         (a) the fault occurred on an implicit access Xen made to walk a
             VS-stage page table, and
         (b) htval holds a nonzero value: the guest-physical address of that
             VS-stage PTE, not of the guest's original access.

     However, none of these paths consult the p2m first, and the future MMIO path
     won't either: RISC-V has no populate-on-demand, no paging, and no
     mem_access, so every guest mapping is established eagerly. A G-stage
     fault therefore never indicates a mapping Xen could lazily resolve to
Quoted 8 lines
     let the access complete.

     Both helpers this handler relies on, resolve_faulting_gpa() and
     trap_redirect(), are BUG_ON() placeholders for now, so all three causes
     currently take the host down instead of just the guest. This is no worse
     than before this patch, where these traps fell through to
     do_unexpected_trap() and die().
```

I will apply your suggestion.

Thanks.

~ Oleksii

#113 lore raw

Re: [PATCH v2 18/39] xen/riscv: add guest page fault handling stub

In reply to Oleksii Kurochko
Quoted 18 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c new file +15 -0
@@ -0,0 +1,179 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+/*
+ * RISC-V instruction emulation for trapped guest accesses
+ */
+
+#include <xen/bug.h>
+#include <xen/errno.h>
+#include <xen/sched.h>
+#include <xen/types.h>
+
+#include <asm/csr.h>
+#include <asm/current.h>
+#include <asm/emulate.h>
+#include <asm/riscv_encoding.h>

xen/arch/riscv/emulate.c line 25

Quoted 10 lines
xen/arch/riscv/emulate.c new file +10 -0
+#include <asm/traps.h>
+
+/*
+ * 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
+ * access.
+ */
+struct guest_fault {
+    /* The guest register state as saved on entry to do_trap(). */
+    struct cpu_user_regs *regs;

If the comment was true, this could be pointer-to-const.

Quoted 28 lines
xen/arch/riscv/emulate.c new file +28 -0
+    /* scause: a fetch, a load or a store/AMO guest page fault. */
+    unsigned long cause;
+    /*
+     * htinst: the trapped instruction in its transformed form, or one of the
+     * special values (zero, or a pseudoinstruction).
+     */
+    unsigned long htinst;
+    /* htval: as written by hardware; see resolve_faulting_gpa(). */
+    unsigned long htval;
+    /* stval: the guest virtual address of the faulting access. */
+    unsigned long stval;
+    /* The faulting guest physical address, filled by resolve_faulting_gpa(). */
+    paddr_t gpa;
+};
+
+/*
+ * Is @htinst one of the pseudoinstructions reported for a guest page fault
+ * taken on an implicit memory access done for VS-stage address translation?
+ *
+ * All four values are recognized regardless of the hypervisor's XLEN: the
+ * width they encode is that of a VS-stage PTE, i.e. it follows the guest's
+ * paging mode (4 bytes for Sv32, 8 otherwise). On RV32 the 64-bit forms
+ * simply never occur.
+ */
+static bool htinst_is_pseudo(unsigned long htinst)
+{
+    switch ( htinst )
+    {

xen/arch/riscv/emulate.c line 63

Quoted 10 lines
xen/arch/riscv/emulate.c new file +10 -0
+    case INSN_PSEUDO_VS_LOAD32:
+    case INSN_PSEUDO_VS_STORE32:
+    case INSN_PSEUDO_VS_LOAD64:
+    case INSN_PSEUDO_VS_STORE64:
+        return true;
+
+    default:
+        return false;
+    }
+}

This feels fragile. New pseudo-insns can appear at any time. If the value as a whole is non-zero, aiui the low two bits being zero indicate a pseudo-insn. In which case enumerating pseudo-insns we are currently aware of isn't necessary.

Quoted 16 lines
xen/arch/riscv/emulate.c new file +16 -0
+static void inject_access_fault(const struct guest_fault *gf)
+{
+    struct trap_info utrap = {};
+
+    switch ( gf->cause )
+    {
+    case CAUSE_FETCH_GUEST_PAGE_FAULT:
+        utrap.scause = CAUSE_FETCH_ACCESS;
+        break;
+
+    case CAUSE_LOAD_GUEST_PAGE_FAULT:
+        utrap.scause = CAUSE_LOAD_ACCESS;
+        break;
+
+    case CAUSE_STORE_GUEST_PAGE_FAULT:
+        utrap.scause = CAUSE_STORE_ACCESS;

xen/arch/riscv/emulate.c line 106

Quoted 10 lines
xen/arch/riscv/emulate.c new file +10 -0
+        break;
+
+    default:
+        domain_crash(current->domain, "Impossible cause (%#lx) in %s?\n",
+                     gf->cause, __func__);
+        return;
+    }
+
+    utrap.sepc = gf->regs->sepc;
+    utrap.stval = gf->stval;

Would there be anything wrong with putting these in utrap's initializer?

xen/arch/riscv/emulate.c line 120

Quoted 13 lines
xen/arch/riscv/emulate.c new file +13 -0
+    trap_redirect(&utrap);
+}
+
+void handle_guest_page_fault(struct cpu_user_regs *regs, unsigned long cause)
+{
+    struct guest_fault gf = {
+        .regs = regs,
+        .cause = cause,
+        .htinst = csr_read(CSR_HTINST),
+        .htval = csr_read(CSR_HTVAL),
+        .stval = csr_read(CSR_STVAL),
+        .gpa = INVALID_PADDR,
+    };

At some point RISC-V code will (very likely) also be scanned for Misra violations. The csr_read()s here violate rule 13.1 ("Initializer lists shall not contain persistent side effects"), and I think it would be better if such was avoided from the start.

Quoted 15 lines
xen/arch/riscv/emulate.c new file +15 -0
+    int rc;
+
+    /*
+     * A guest-page fault may arise due to an implicit memory access during
+     * first-stage (VS-stage) address translation, in which case a guest
+     * physical address written to htval is that of the implicit memory
+     * access that faulted - for example, the address of a VS-level page
+     * table entry that could not be read. (The guest physical address
+     * corresponding to the original virtual address is unknown when
+     * VS-stage translation fails to complete)
+     *
+     * In such cases htinst reports one of the pseudoinstructions recognized
+     * by htinst_is_pseudo(), and the fault requires separate handling (since
+     * G-stage translation failed on an unpopulated/unmapped guest physical
+     * address during a hardware page-table walk). To match bare hardware

xen/arch/riscv/emulate.c line 145

Quoted 10 lines
xen/arch/riscv/emulate.c new file +10 -0
+     * behavior, we must inject an access fault of the ORIGINAL access type
+     * (Instruction, Load, or Store/AMO) that initiated the address
+     * translation.
+     */
+    if ( htinst_is_pseudo(gf.htinst) )
+    {
+        inject_access_fault(&gf);
+
+        return;
+    }

I.e. you imply that guests won't put their page tables in MMIO? That's fragile imo; I have seen OSes to use video frame buffers for all kinds of (transient) purposes, for example.

xen/arch/riscv/emulate.c line 147

Quoted 1 line
xen/arch/riscv/emulate.c new file +1 -0
+    resolve_faulting_gpa(&gf);

Since the function is only a stub right now - how is one to tell whether this indeed can never fail?

Quoted 5 lines
xen/arch/riscv/emulate.c new file +5 -0
+    switch ( cause )
+    {
+    case CAUSE_LOAD_GUEST_PAGE_FAULT:
+        rc = emulate_load(&gf);
+        break;

xen/arch/riscv/emulate.c line 163

Quoted 10 lines
xen/arch/riscv/emulate.c new file +10 -0
+
+    case CAUSE_STORE_GUEST_PAGE_FAULT:
+        rc = emulate_store(&gf);
+        break;
+
+    case CAUSE_FETCH_GUEST_PAGE_FAULT:
+        /*
+         * Guest is trying to reach unmapped/unpopulated or G-stage PTE doesn't
+         * allow execution (X=0). Generate fetch fault in this case.
+         */

Is there perhaps a comma missing before "or", to help parsing the sentence?

xen/arch/riscv/emulate.c line 166

Quoted 3 lines
xen/arch/riscv/emulate.c new file +3 -0
+        inject_access_fault(&gf);
+        rc = 0;
+        break;

Simply "return" instead of the latter two statements?

xen/arch/riscv/emulate.c line 170

Quoted 3 lines
xen/arch/riscv/emulate.c new file +3 -0
+    default:
+        rc = -EOPNOTSUPP;
+        ASSERT_UNREACHABLE();

To fit a common pattern, these two lines want to be the other way around.

xen/arch/riscv/emulate.c line 177

Quoted 7 lines
xen/arch/riscv/emulate.c new file +7 -0
+        break;
+    }
+
+    if ( rc )
+        domain_crash(current->domain,
+                     "%s: unable to handle guest page fault (cause=%#lx) at "
+                     "gpa %#"PRIpaddr"\n",

Please avoid wrapping of format strings across lines.

Jan

#114 lore raw

Re: [PATCH v2 18/39] xen/riscv: add guest page fault handling stub

Quoted 23 lines · Jan Beulich
Quoted 22 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c new file +19 -0
@@ -0,0 +1,179 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+/*
+ * RISC-V instruction emulation for trapped guest accesses
+ */
+
+#include <xen/bug.h>
+#include <xen/errno.h>
+#include <xen/sched.h>
+#include <xen/types.h>
+
+#include <asm/csr.h>
+#include <asm/current.h>
+#include <asm/emulate.h>
+#include <asm/riscv_encoding.h>
+#include <asm/traps.h>
+
+/*
+ * The hardware-reported details of a guest page fault, gathered once by
Quoted 8 lines

xen/arch/riscv/emulate.c line 25

Quoted 6 lines
xen/arch/riscv/emulate.c new file +6 -0
+ * handle_guest_page_fault() and passed down to the emulation of the faulted
+ * access.
+ */
+struct guest_fault {
+    /* The guest register state as saved on entry to do_trap(). */
+    struct cpu_user_regs *regs;

If the comment was true, this could be pointer-to-const.

I think it can't be pointer-to-const as emulate_load/store functions wants to change PC register after MMIO access emulation is finished to not trap again.

Regarding the comment itself I agree that it isn't fully true right now because there is no trap from guest and so no guest registers save/restore but it will for sure be and we can't not to save/restore guest registers when do_trap() happens.

I will re-word it to:

/* The guest register state */

Quoted 36 lines
Quoted 36 lines
xen/arch/riscv/emulate.c new file +35 -0
+    /* scause: a fetch, a load or a store/AMO guest page fault. */
+    unsigned long cause;
+    /*
+     * htinst: the trapped instruction in its transformed form, or one of the
+     * special values (zero, or a pseudoinstruction).
+     */
+    unsigned long htinst;
+    /* htval: as written by hardware; see resolve_faulting_gpa(). */
+    unsigned long htval;
+    /* stval: the guest virtual address of the faulting access. */
+    unsigned long stval;
+    /* The faulting guest physical address, filled by resolve_faulting_gpa(). */
+    paddr_t gpa;
+};
+
+/*
+ * Is @htinst one of the pseudoinstructions reported for a guest page fault
+ * taken on an implicit memory access done for VS-stage address translation?
+ *
+ * All four values are recognized regardless of the hypervisor's XLEN: the
+ * width they encode is that of a VS-stage PTE, i.e. it follows the guest's
+ * paging mode (4 bytes for Sv32, 8 otherwise). On RV32 the 64-bit forms
+ * simply never occur.
+ */
+static bool htinst_is_pseudo(unsigned long htinst)
+{
+    switch ( htinst )
+    {
+    case INSN_PSEUDO_VS_LOAD32:
+    case INSN_PSEUDO_VS_STORE32:
+    case INSN_PSEUDO_VS_LOAD64:
+    case INSN_PSEUDO_VS_STORE64:
+        return true;
+
+    default:
Quoted 8 lines

xen/arch/riscv/emulate.c line 63

Quoted 3 lines
xen/arch/riscv/emulate.c new file +3 -0
+        return false;
+    }
+}

This feels fragile. New pseudo-insns can appear at any time. If the value as a whole is non-zero, aiui the low two bits being zero indicate a pseudo-insn. In which case enumerating pseudo-insns we are currently aware of isn't necessary.

I will write it simpler then:

/*
* Is @htinst one of the special pseudoinstruction values, reported for
a guest
* page fault taken on an implicit memory access done for VS-stage address
* translation?
*
* It is enough to check only bits[1:0] as according to the spec:
*
* The value is one of the special pseudoinstructions defined later, all of
* which have bits 1:0 equal to 00.
*/
static bool htinst_is_pseudo(unsigned long htinst)

{
    return htinst && ((htinst & 3) == 0);
}
Quoted 21 lines
Quoted 21 lines
xen/arch/riscv/emulate.c new file +20 -0
+static void inject_access_fault(const struct guest_fault *gf)
+{
+    struct trap_info utrap = {};
+
+    switch ( gf->cause )
+    {
+    case CAUSE_FETCH_GUEST_PAGE_FAULT:
+        utrap.scause = CAUSE_FETCH_ACCESS;
+        break;
+
+    case CAUSE_LOAD_GUEST_PAGE_FAULT:
+        utrap.scause = CAUSE_LOAD_ACCESS;
+        break;
+
+    case CAUSE_STORE_GUEST_PAGE_FAULT:
+        utrap.scause = CAUSE_STORE_ACCESS;
+        break;
+
+    default:
+        domain_crash(current->domain, "Impossible cause (%#lx) in %s?\n",
Quoted 8 lines

xen/arch/riscv/emulate.c line 106

Quoted 6 lines
xen/arch/riscv/emulate.c new file +6 -0
+                     gf->cause, __func__);
+        return;
+    }
+
+    utrap.sepc = gf->regs->sepc;
+    utrap.stval = gf->stval;

Would there be anything wrong with putting these in utrap's initializer?

It could be initializers. I will use utrap's initializer.

Quoted 11 lines
Quoted 11 lines
xen/arch/riscv/emulate.c new file +10 -0
+    trap_redirect(&utrap);
+}
+
+void handle_guest_page_fault(struct cpu_user_regs *regs, unsigned long cause)
+{
+    struct guest_fault gf = {
+        .regs = regs,
+        .cause = cause,
+        .htinst = csr_read(CSR_HTINST),
+        .htval = csr_read(CSR_HTVAL),
Quoted 8 lines

xen/arch/riscv/emulate.c line 120

Quoted 3 lines
xen/arch/riscv/emulate.c new file +3 -0
+        .stval = csr_read(CSR_STVAL),
+        .gpa = INVALID_PADDR,
+    };

At some point RISC-V code will (very likely) also be scanned for Misra violations. The csr_read()s here violate rule 13.1 ("Initializer lists shall not contain persistent side effects"), and I think it would be better if such was avoided from the start.

I will do the following then:

struct guest_fault gf = {
.regs = regs,
.cause = cause,
.gpa = INVALID_PADDR,
};
int rc;

gf.htinst = csr_read(CSR_HTINST);
gf.htval = csr_read(CSR_HTVAL);
gf.stval = csr_read(CSR_STVAL);

Quoted 22 lines
Quoted 22 lines
xen/arch/riscv/emulate.c new file +21 -0
+    int rc;
+
+    /*
+     * A guest-page fault may arise due to an implicit memory access during
+     * first-stage (VS-stage) address translation, in which case a guest
+     * physical address written to htval is that of the implicit memory
+     * access that faulted - for example, the address of a VS-level page
+     * table entry that could not be read. (The guest physical address
+     * corresponding to the original virtual address is unknown when
+     * VS-stage translation fails to complete)
+     *
+     * In such cases htinst reports one of the pseudoinstructions recognized
+     * by htinst_is_pseudo(), and the fault requires separate handling (since
+     * G-stage translation failed on an unpopulated/unmapped guest physical
+     * address during a hardware page-table walk). To match bare hardware
+     * behavior, we must inject an access fault of the ORIGINAL access type
+     * (Instruction, Load, or Store/AMO) that initiated the address
+     * translation.
+     */
+    if ( htinst_is_pseudo(gf.htinst) )
+    {
Quoted 8 lines

xen/arch/riscv/emulate.c line 145

Quoted 4 lines
xen/arch/riscv/emulate.c new file +4 -0
+        inject_access_fault(&gf);
+
+        return;
+    }

I.e. you imply that guests won't put their page tables in MMIO? That's fragile imo; I have seen OSes to use video frame buffers for all kinds of (transient) purposes, for example.

I think it is okay for now and if it will a real use case then an update of this code will be needed.

Quoted 5 lines

xen/arch/riscv/emulate.c line 147

Quoted 2 lines
xen/arch/riscv/emulate.c new file +1 -0
+    resolve_faulting_gpa(&gf);

Since the function is only a stub right now - how is one to tell whether this indeed can never fail?

It can't be tell. But what is wrong if it could fail? (Actually with current implementation introduced in later patches you can find it can fail if a necessary extension or software page walk isn't introduced).

If we can't resolve faulting GPA address then we can't continue to work and so at least domain should be crashed.

Quoted 10 lines
Quoted 10 lines
xen/arch/riscv/emulate.c new file +9 -0
+    switch ( cause )
+    {
+    case CAUSE_LOAD_GUEST_PAGE_FAULT:
+        rc = emulate_load(&gf);
+        break;
+
+    case CAUSE_STORE_GUEST_PAGE_FAULT:
+        rc = emulate_store(&gf);
+        break;
Quoted 8 lines

xen/arch/riscv/emulate.c line 163

Quoted 6 lines
xen/arch/riscv/emulate.c new file +6 -0
+
+    case CAUSE_FETCH_GUEST_PAGE_FAULT:
+        /*
+         * Guest is trying to reach unmapped/unpopulated or G-stage PTE doesn't
+         * allow execution (X=0). Generate fetch fault in this case.
+         */

Is there perhaps a comma missing before "or", to help parsing the sentence?

I will add one.

Quoted 6 lines

xen/arch/riscv/emulate.c line 166

Quoted 4 lines
xen/arch/riscv/emulate.c new file +3 -0
+        inject_access_fault(&gf);
+        rc = 0;
+        break;

Simply "return" instead of the latter two statements?

It makes sense. I will do just return.

Thanks.

~ Oleksii

#115 lore raw

Re: [PATCH v2 18/39] xen/riscv: add guest page fault handling stub

Quoted 33 lines · Oleksii Kurochko
Quoted 23 lines · Jan Beulich
Quoted 22 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c new file +19 -0
@@ -0,0 +1,179 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+/*
+ * RISC-V instruction emulation for trapped guest accesses
+ */
+
+#include <xen/bug.h>
+#include <xen/errno.h>
+#include <xen/sched.h>
+#include <xen/types.h>
+
+#include <asm/csr.h>
+#include <asm/current.h>
+#include <asm/emulate.h>
+#include <asm/riscv_encoding.h>
+#include <asm/traps.h>
+
+/*
+ * The hardware-reported details of a guest page fault, gathered once by
Quoted 8 lines

xen/arch/riscv/emulate.c line 25

Quoted 6 lines
xen/arch/riscv/emulate.c new file +6 -0
+ * handle_guest_page_fault() and passed down to the emulation of the faulted
+ * access.
+ */
+struct guest_fault {
+    /* The guest register state as saved on entry to do_trap(). */
+    struct cpu_user_regs *regs;

If the comment was true, this could be pointer-to-const.

Quoted 3 lines

I think it can't be pointer-to-const as emulate_load/store functions wants to change PC register after MMIO access emulation is finished to not trap again.

Of course, hence how I started the sentence.

Quoted 58 lines
Quoted 35 lines
Quoted 35 lines
xen/arch/riscv/emulate.c new file +35 -0
+    /* scause: a fetch, a load or a store/AMO guest page fault. */
+    unsigned long cause;
+    /*
+     * htinst: the trapped instruction in its transformed form, or one of the
+     * special values (zero, or a pseudoinstruction).
+     */
+    unsigned long htinst;
+    /* htval: as written by hardware; see resolve_faulting_gpa(). */
+    unsigned long htval;
+    /* stval: the guest virtual address of the faulting access. */
+    unsigned long stval;
+    /* The faulting guest physical address, filled by resolve_faulting_gpa(). */
+    paddr_t gpa;
+};
+
+/*
+ * Is @htinst one of the pseudoinstructions reported for a guest page fault
+ * taken on an implicit memory access done for VS-stage address translation?
+ *
+ * All four values are recognized regardless of the hypervisor's XLEN: the
+ * width they encode is that of a VS-stage PTE, i.e. it follows the guest's
+ * paging mode (4 bytes for Sv32, 8 otherwise). On RV32 the 64-bit forms
+ * simply never occur.
+ */
+static bool htinst_is_pseudo(unsigned long htinst)
+{
+    switch ( htinst )
+    {
+    case INSN_PSEUDO_VS_LOAD32:
+    case INSN_PSEUDO_VS_STORE32:
+    case INSN_PSEUDO_VS_LOAD64:
+    case INSN_PSEUDO_VS_STORE64:
+        return true;
+
+    default:
Quoted 8 lines

xen/arch/riscv/emulate.c line 63

Quoted 3 lines
xen/arch/riscv/emulate.c new file +3 -0
+        return false;
+    }
+}

This feels fragile. New pseudo-insns can appear at any time. If the value as a whole is non-zero, aiui the low two bits being zero indicate a pseudo-insn. In which case enumerating pseudo-insns we are currently aware of isn't necessary.

I will write it simpler then:

/*
* Is @htinst one of the special pseudoinstruction values, reported for
a guest
* page fault taken on an implicit memory access done for VS-stage address
* translation?
*
* It is enough to check only bits[1:0] as according to the spec:
*
* The value is one of the special pseudoinstructions defined later, all of
* which have bits 1:0 equal to 00.
*/
static bool htinst_is_pseudo(unsigned long htinst)

Quoted 3 lines
{
     return htinst && ((htinst & 3) == 0);
}

And preferably

     return htinst && !(htinst & 3);

to be self-consistent.

Quoted 24 lines
Quoted 24 lines
Quoted 23 lines
xen/arch/riscv/emulate.c new file +23 -0
+    /*
+     * A guest-page fault may arise due to an implicit memory access during
+     * first-stage (VS-stage) address translation, in which case a guest
+     * physical address written to htval is that of the implicit memory
+     * access that faulted - for example, the address of a VS-level page
+     * table entry that could not be read. (The guest physical address
+     * corresponding to the original virtual address is unknown when
+     * VS-stage translation fails to complete)
+     *
+     * In such cases htinst reports one of the pseudoinstructions recognized
+     * by htinst_is_pseudo(), and the fault requires separate handling (since
+     * G-stage translation failed on an unpopulated/unmapped guest physical
+     * address during a hardware page-table walk). To match bare hardware
+     * behavior, we must inject an access fault of the ORIGINAL access type
+     * (Instruction, Load, or Store/AMO) that initiated the address
+     * translation.
+     */
+    if ( htinst_is_pseudo(gf.htinst) )
+    {
+        inject_access_fault(&gf);
+
+        return;
+    }
Quoted 6 lines
Quoted 3 lines

I.e. you imply that guests won't put their page tables in MMIO? That's fragile imo; I have seen OSes to use video frame buffers for all kinds of (transient) purposes, for example.

I think it is okay for now and if it will a real use case then an update of this code will be needed.

May I then ask that you leave a remark (maybe even fixme) to this effect?

Quoted 8 lines
Quoted 4 lines

xen/arch/riscv/emulate.c line 147

Quoted 1 line
xen/arch/riscv/emulate.c new file +1 -0
+    resolve_faulting_gpa(&gf);

Since the function is only a stub right now - how is one to tell whether this indeed can never fail?

It can't be tell. But what is wrong if it could fail? (Actually with current implementation introduced in later patches you can find it can fail if a necessary extension or software page walk isn't introduced).

Well, quite obviously if it can fail, its return value would need checking here.

Jan

#116 lore raw

Re: [PATCH v2 18/39] xen/riscv: add guest page fault handling stub

Quoted 102 lines · Jan Beulich
Quoted 33 lines · Oleksii Kurochko
Quoted 23 lines · Jan Beulich
Quoted 22 lines · Oleksii Kurochko
xen/arch/riscv/emulate.c new file +19 -0
@@ -0,0 +1,179 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+/*
+ * RISC-V instruction emulation for trapped guest accesses
+ */
+
+#include <xen/bug.h>
+#include <xen/errno.h>
+#include <xen/sched.h>
+#include <xen/types.h>
+
+#include <asm/csr.h>
+#include <asm/current.h>
+#include <asm/emulate.h>
+#include <asm/riscv_encoding.h>
+#include <asm/traps.h>
+
+/*
+ * The hardware-reported details of a guest page fault, gathered once by
Quoted 8 lines

xen/arch/riscv/emulate.c line 25

Quoted 6 lines
xen/arch/riscv/emulate.c new file +6 -0
+ * handle_guest_page_fault() and passed down to the emulation of the faulted
+ * access.
+ */
+struct guest_fault {
+    /* The guest register state as saved on entry to do_trap(). */
+    struct cpu_user_regs *regs;

If the comment was true, this could be pointer-to-const.

Quoted 3 lines

I think it can't be pointer-to-const as emulate_load/store functions wants to change PC register after MMIO access emulation is finished to not trap again.

Of course, hence how I started the sentence.

Quoted 58 lines
Quoted 35 lines
Quoted 35 lines
xen/arch/riscv/emulate.c new file +35 -0
+    /* scause: a fetch, a load or a store/AMO guest page fault. */
+    unsigned long cause;
+    /*
+     * htinst: the trapped instruction in its transformed form, or one of the
+     * special values (zero, or a pseudoinstruction).
+     */
+    unsigned long htinst;
+    /* htval: as written by hardware; see resolve_faulting_gpa(). */
+    unsigned long htval;
+    /* stval: the guest virtual address of the faulting access. */
+    unsigned long stval;
+    /* The faulting guest physical address, filled by resolve_faulting_gpa(). */
+    paddr_t gpa;
+};
+
+/*
+ * Is @htinst one of the pseudoinstructions reported for a guest page fault
+ * taken on an implicit memory access done for VS-stage address translation?
+ *
+ * All four values are recognized regardless of the hypervisor's XLEN: the
+ * width they encode is that of a VS-stage PTE, i.e. it follows the guest's
+ * paging mode (4 bytes for Sv32, 8 otherwise). On RV32 the 64-bit forms
+ * simply never occur.
+ */
+static bool htinst_is_pseudo(unsigned long htinst)
+{
+    switch ( htinst )
+    {
+    case INSN_PSEUDO_VS_LOAD32:
+    case INSN_PSEUDO_VS_STORE32:
+    case INSN_PSEUDO_VS_LOAD64:
+    case INSN_PSEUDO_VS_STORE64:
+        return true;
+
+    default:
Quoted 8 lines

xen/arch/riscv/emulate.c line 63

Quoted 3 lines
xen/arch/riscv/emulate.c new file +3 -0
+        return false;
+    }
+}

This feels fragile. New pseudo-insns can appear at any time. If the value as a whole is non-zero, aiui the low two bits being zero indicate a pseudo-insn. In which case enumerating pseudo-insns we are currently aware of isn't necessary.

I will write it simpler then:

/*
* Is @htinst one of the special pseudoinstruction values, reported for
a guest
* page fault taken on an implicit memory access done for VS-stage address
* translation?
*
* It is enough to check only bits[1:0] as according to the spec:
*
* The value is one of the special pseudoinstructions defined later, all of
* which have bits 1:0 equal to 00.
*/
static bool htinst_is_pseudo(unsigned long htinst)

Quoted 3 lines
{
      return htinst && ((htinst & 3) == 0);
}
Quoted 6 lines

And preferably

      return htinst && !(htinst & 3);

to be self-consistent.

Good point. I will apply your suggestion.

Quoted 24 lines
Quoted 24 lines
Quoted 24 lines
Quoted 23 lines
xen/arch/riscv/emulate.c new file +23 -0
+    /*
+     * A guest-page fault may arise due to an implicit memory access during
+     * first-stage (VS-stage) address translation, in which case a guest
+     * physical address written to htval is that of the implicit memory
+     * access that faulted - for example, the address of a VS-level page
+     * table entry that could not be read. (The guest physical address
+     * corresponding to the original virtual address is unknown when
+     * VS-stage translation fails to complete)
+     *
+     * In such cases htinst reports one of the pseudoinstructions recognized
+     * by htinst_is_pseudo(), and the fault requires separate handling (since
+     * G-stage translation failed on an unpopulated/unmapped guest physical
+     * address during a hardware page-table walk). To match bare hardware
+     * behavior, we must inject an access fault of the ORIGINAL access type
+     * (Instruction, Load, or Store/AMO) that initiated the address
+     * translation.
+     */
+    if ( htinst_is_pseudo(gf.htinst) )
+    {
+        inject_access_fault(&gf);
+
+        return;
+    }
Quoted 8 lines
Quoted 6 lines
Quoted 3 lines

I.e. you imply that guests won't put their page tables in MMIO? That's fragile imo; I have seen OSes to use video frame buffers for all kinds of (transient) purposes, for example.

I think it is okay for now and if it will a real use case then an update of this code will be needed.

May I then ask that you leave a remark (maybe even fixme) to this effect?

Sure, I will then add the following to the comment above if ():

* FIXME: This assumes that guest page tables never reside in an
emulated
* MMIO region, i.e. that an implicit access faulting at G-stage always
* targets an unpopulated GPA. Guests may (even transiently) place page
* tables in MMIO-backed memory, e.g. a video frame buffer. Supporting
* that would require walking the VS-stage page tables in software,
* accessing the PTEs (including A/D updates) through the MMIO
handlers,
* and then emulating the original access, instead of injecting a
fault.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

xen/arch/riscv/emulate.c line 147

Quoted 2 lines
xen/arch/riscv/emulate.c new file +1 -0
+    resolve_faulting_gpa(&gf);

Since the function is only a stub right now - how is one to tell whether this indeed can never fail?

Quoted 7 lines
Quoted 3 lines

It can't be tell. But what is wrong if it could fail? (Actually with current implementation introduced in later patches you can find it can fail if a necessary extension or software page walk isn't introduced).

Well, quite obviously if it can fail, its return value would need checking here.

That what I thought about after I sent my e-mail as a possible option.

I will update the prototype to:

+static int resolve_faulting_gpa(struct guest_fault *gf)
{
- BUG_ON("unimplemented");
+ return -EOPNOTSUPP;
}

And handle an error code in the following way:

@@ -136,7 +144,8 @@ void handle_guest_page_fault(struct cpu_user_regs *regs, unsigned long cause )

         return;
     }

- resolve_faulting_gpa(&gf);
+ if ( rc = resolve_faulting_gpa(&gf) )
+ goto out;

switch ( cause )
{
@@ -163,6 +172,7 @@ void handle_guest_page_fault(struct cpu_user_regs *regs, unsigned long cause )

         break;
     }

+ out:
if ( rc )
domain_crash(current->domain,

and then in the next patch "[PATCH v2 21/39] xen/riscv: resolve the faulting guest physical address" I will do "return -EOPNOTSUPP" instead of panic():

- panic("Shtvala isn't supported by h/w; s/w VS-stage walk
required\n");
++ {
++ printk_once(XENLOG_WARNING
++ "Shtvala isn't supported by h/w; s/w VS-stage walk required\n");
++ return -EOPNOTSUPP;
++ }

~ Oleksii

#117 lore raw

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

In reply to Oleksii Kurochko

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.

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.

---
Changes in v2:
- Add new defines STVEC_*. The STVEC_MODE_DIRECT/_VECTORED values are currently unused and were included because riscv encoding header is a spec mirror full of unused encodings.
- Use STVEC_BASE_MASK instead of open-coding it.
- Rename riscv_vcpu_trap_redirect() to trap_redirect(): unlike its KVM counterpart the function takes no vCPU argument, it implicitly operates on current, so "vcpu" in the name describes nothing.

---
 xen/arch/riscv/include/asm/riscv_encoding.h |  6 +++
 xen/arch/riscv/traps.c                      | 50 ++++++++++++++++++++-
 2 files changed, 55 insertions(+), 1 deletion(-)
xen/arch/riscv/include/asm/riscv_encoding.h +6 -0
index 2d2e7e11b3ef..b2071f47587c 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)
+
 #define PRV_U				_UL(0)
 #define PRV_S				_UL(1)
 #define PRV_M				_UL(3)
xen/arch/riscv/traps.c +49 -1

54 lines not on this page · raw message

Signature · 1 line
2.55.0