virtual interrupt controller (vAPLIC/vIMSIC) support
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
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
@@ -50,8 +50,6 @@ struct cpu_user_regsunsigned 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
@@ -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
PATCH v2 4/39 xen/riscv: introduce csr_read64()
In reply to Oleksii Kurochkocsr_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.
---
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
@@ -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
@@ -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
PATCH v2 6/39 xen/riscv: use UINT64_MAX to disable the VS-timer
In reply to Oleksii Kurochkovstimecmp 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.
---
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
@@ -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
PATCH v2 2/39 xen/riscv: drop bug.h's duplicate instruction length helpers
In reply to Oleksii Kurochkoasm/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
@@ -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
@@ -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
PATCH v2 5/39 xen/riscv: request a G-stage flush on vmenter when VMIDs are disabled
In reply to Oleksii Kurochkovmid_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.
---
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
@@ -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
@@ -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
PATCH v2 8/39 xen/riscv: introduce device-agnostic MMIO emulation dispatch
In reply to Oleksii KurochkoRISC-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
@@ -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
@@ -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
@@ -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
PATCH v2 3/39 xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL
In reply to Oleksii Kurochkohstatus.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
@@ -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
@@ -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
PATCH v2 7/39 xen/riscv: add missing APLIC register offsets, masks to asm/aplic.h
In reply to Oleksii KurochkoThese 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
@@ -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
PATCH v2 10/39 xen/riscv: build the target hart index via aplic_hart_field()
In reply to Oleksii Kurochkoaplic_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.
---
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
@@ -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 cpumaskASSERT (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
@@ -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
PATCH v2 9/39 xen/riscv: implement virtual APLIC MMIO emulation
In reply to Oleksii KurochkoGuests 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
@@ -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
@@ -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
@@ -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
@@ -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
PATCH v2 11/39 xen/riscv: add helper to check APLIC MSI mode
In reply to Oleksii KurochkoUse 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
@@ -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
PATCH v2 12/39 xen/riscv: implement vCPU context switching
In reply to Oleksii KurochkoImplement 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
@@ -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 (¤t->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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
PATCH v2 14/39 xen/riscv: introduce vintc_ctxt_switch_{from,to}()
In reply to Oleksii KurochkoVirtual 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
@@ -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
@@ -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
@@ -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
PATCH v2 13/39 xen/riscv: save and restore AIA state on vCPU context switch
In reply to Oleksii Kurochkovsiselect 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
@@ -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
@@ -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
PATCH v2 16/39 xen/riscv: extend exception tables with type and data fields
In reply to Oleksii KurochkoExtend 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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
PATCH v2 15/39 xen/riscv: add IMSIC vCPU context switch handlers
In reply to Oleksii KurochkoIMSIC 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
@@ -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
@@ -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
@@ -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
PATCH v2 18/39 xen/riscv: add guest page fault handling stub
In reply to Oleksii KurochkoAdd 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
@@ -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
@@ -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
@@ -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
@@ -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
PATCH v2 17/39 xen/riscv: decouple INSN_PSEUDO_VS_* from the hypervisor's XLEN
In reply to Oleksii Kurochkohtinst 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
@@ -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
PATCH v2 19/39 xen/riscv: implement trap redirection to a guest
In reply to Oleksii KurochkoSome 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
@@ -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
PATCH v2 20/39 xen/riscv: detect Shtvala
In reply to Oleksii KurochkoShtvala says that htval is written with the faulting guest physical address on a guest-page fault. The H extension itself allows an implementation to write htval with either that address or with zero, so where the extension is absent a zero htval cannot be told apart from a genuine fault on guest physical address 0-3.
It is not offered to guests. Shtvala describes the HS-mode trap interface, which a VS-mode guest never sees, and the H extension it belongs to is already withheld from guests. Its guest-facing counterpart is a separate extension, Shvstvala.
---
Change in v2:
- New patch.
---
--- xen/arch/riscv/cpufeature.c | 1 + xen/arch/riscv/include/asm/cpufeature.h | 1 + 2 files changed, 2 insertions(+)
xen/arch/riscv/cpufeature.c +1 -0
@@ -195,6 +195,7 @@ static const struct riscv_isa_ext_entry __initconstrel riscv_isa_ext[] = {RISCV_ISA_EXT_ENTRY (zba,RISCV_ISA_EXT_GUEST_ANY ),RISCV_ISA_EXT_ENTRY (zbb,RISCV_ISA_EXT_GUEST_ANY ),RISCV_ISA_EXT_ENTRY (zbs,RISCV_ISA_EXT_GUEST_ANY ), +RISCV_ISA_EXT_ENTRY (shtvala,RISCV_ISA_EXT_GUEST_NONE ),RISCV_ISA_EXT_ENTRY (smaia,RISCV_ISA_EXT_GUEST_ANY ),RISCV_ISA_EXT_ENTRY (smstateen,RISCV_ISA_EXT_GUEST_ANY ), RISCV_ISA_EXT_ENTRY(ssaia, RISCV_ISA_EXT_GUEST_ANY),
xen/arch/riscv/include/asm/cpufeature.h +1 -0
@@ -36,6 +36,7 @@ enum riscv_isa_ext_id { RISCV_ISA_EXT_zba, RISCV_ISA_EXT_zbb, RISCV_ISA_EXT_zbs, + RISCV_ISA_EXT_shtvala, RISCV_ISA_EXT_smaia, RISCV_ISA_EXT_smstateen, RISCV_ISA_EXT_ssaia,
Signature · 1 line
2.55.0
PATCH v2 22/39 xen/riscv: add guest memory read helper
In reply to Oleksii KurochkoIntroduce riscv_read_guest() to allow Xen to safely read guest memory using HLV/HLVX instructions while reliably capturing trap context.
This is required for instruction fetch emulation and MMIO decoding, where Xen must inspect guest memory that may not be directly accessible and may fault.
The implementation is based on kvm_riscv_vcpu_unpriv_read() from Linux, with one deviation: the hlv/hlvx instructions translate the guest address through the live vsatp/hgatp CSRs, i.e. through the address space of the currently running vCPU, so the function can only be called safely for current. Instead of taking a struct vcpu argument, it always operates on current directly.
---
Changes in v2:
- Rename riscv_vcpu_unpriv_read() to riscv_read_guest() and make the guest address the first parameter. "unprivileged" described how hlv/hlvx perform the access rather than what the helper is for, and "unprivileged guest" reads as a synonym for DomU although the helper works for any domain.
- Drop the hstatus save/restore and the local_irq_save() protecting it:
hstatus already belongs to the vCPU which trapped, as Xen never installs a value of its own and does not reschedule before returning to the guest. ASSERT() hstatus.SPV in the saved copy instead, which also documents that the helper is only usable while handling a trap from a guest.
- Poison val with ~0UL and make [val] "+&r": the fixup for the first access resumes past the loads without writing it, so a caller which checks trap->scause is no longer handed an uninitialized value.
- Describe the trap_info write with a "+m" (*trap) operand instead of a "memory" clobber; the exception handler writes that structure and nothing else.
- Combine the two halfwords with slli/or instead of sll/add, and use bnez for the instruction length check.
- Turn the hlv.d/hlv.w selection into #if/#elif with an #error default, rather than silently using hlv.w for anything that is not RV64.
- Document that at most two halfwords are fetched, i.e. that encodings wider than 32 bits are unsupported and cannot be completed by calling the helper again at guest_addr + 4, since the length check would then be applied to a continuation halfword.
---
--- xen/arch/riscv/guestcopy.c | 87 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+)
xen/arch/riscv/guestcopy.c +87 -0
@@ -6,6 +6,7 @@#include <xen/string.h> #include <asm/guest_access.h> +#include <asm/traps.h> #define COPY_from_guest 0U#define COPY_to_guest BIT(0, U)
@@ -114,3 +115,89 @@ unsigned long copy_to_guest_phys(struct domain *d, paddr_t gpa, void *buf,return copy_guest (buf, gpa, len,GPA_INFO (d), COPY_to_guest | COPY_gpa); } + +/* +* Read machine word from guest memory +* +* @guest_addr: Guest address to read +* @read_insn: Flag representing whether we are reading instruction +* @trap: Output pointer to trap details if something went wrong during read +* +* The hlv/hlvx instructions translate guest_addr through the live +* vsatp/hgatp CSRs, so the read is only meaningful for the address +* space of the currently running vCPU. +* +* At most two halfwords are fetched when @read_insn is true, i.e. encodings +* wider than 32 bits are not supported. Such an encoding cannot be completed +* by calling this function again at @guest_addr + 4: the length check is +* applied to the first halfword read, which would then be a continuation of +* the instruction rather than its opcode. It is up to the caller to reject +* anything that is neither a 16- nor a 32-bit encoding. +*/ +unsigned long riscv_read_guest (unsigned long guest_addr,bool read_insn, +struct trap_info *trap) +{ +/* +* Poison the result: if the very first access faults, the fixup skips +* over the loads without writing it. Callers must check trap->scause. +*/ +unsigned long val = ~0UL , tmp; + +/* +* hlv/hlvx use hstatus.SPVP for the privilege of the access, and the +* live vsatp/hgatp for the translation. Xen never installs a value of +* its own in hstatus (it is only saved on trap entry and restored +* before sret) and it doesn't reschedule before returning to the +* guest, so all three still belong to the vCPU which trapped. +* +* Check the saved copy rather than the live CSR: a nested trap taken +* from HS-mode clears hstatus.SPV in the CSR (but leaves SPVP alone). +*/ +ASSERT (vcpu_guest_cpu_user_regs (current)->hstatus &HSTATUS_SPV ); + +if ( read_insn ) + { + asmvolatile ("\n" +"1: hlvx.hu %[val], (%[addr])\n" + ASM_EXTABLE_TRAP_INFO(1b, 3f, %[ti]) +" andi %[tmp], %[val], 3\n" +" addi %[tmp], %[tmp], -3\n" +" bnez %[tmp], 3f\n" +" addi %[addr], %[addr], 2\n" +"\n" +"2: hlvx.hu %[tmp], (%[addr])\n" + ASM_EXTABLE_TRAP_INFO(2b, 3f, %[ti]) +" slli %[tmp], %[tmp], 16\n" +" or %[val], %[val], %[tmp]\n" +"3:\n" + : [val] "+&r" (val), [tmp] "=&r" (tmp), [addr] "+&r" (guest_addr), + "+m" (*trap) + : [ti] "r" (trap) ); + +/* +* Although HLVX instructions' explicit memory accesses require execute +* permissions, they still raise the same exceptions as other load +* instructions, rather than raising fetch exceptions instead. +*/ +if ( trap->scause ==CAUSE_LOAD_PAGE_FAULT ) + trap->scause =CAUSE_FETCH_PAGE_FAULT ; + } +else + { + asm volatile ( "\n" + "1: " +#if defined(CONFIG_RISCV_64 ) + "hlv.d %[val], (%[addr])\n" +#elif defined(CONFIG_RISCV_32 ) + "hlv.w %[val], (%[addr])\n" +#else +# error "unsupported RISC-V variant: no hlv for a machine word" +#endif +"2:\n" + ASM_EXTABLE_TRAP_INFO(1b, 2b, %[ti]) + : [val] "+&r" (val), "+m" (*trap) + : [addr] "r" (guest_addr), [ti] "r" (trap) ); + } + + return val; +}
Signature · 1 line
2.55.0
PATCH v2 21/39 xen/riscv: resolve the faulting guest physical address
In reply to Oleksii KurochkoTake the guest physical address from htval and stval: on a guest-page fault htval holds it shifted right by 2, so that an address wider than XLEN fits, and stval holds the faulting guest virtual address, whose two least significant bits are those of the guest physical address. The shift is done on paddr_t rather than on the raw register: a guest physical address is 34 bits wide on RV32 with Sv32x4, so shifting an XLEN-wide value would drop its top two bits.
Those two low bits come from stval only for a fault on an explicit access. Where one is taken on an implicit access made for VS-stage translation htval holds the address of the VS-stage PTE which could not be read, while stval still holds the guest virtual address which started the walk, and the low bits of the address written to htval are zero instead. htinst tells the two apart, which is what the spec points at it for.
stval needs no check against an ISA extension: a guest-page fault writes it with the faulting guest virtual address regardless. Sstvala would not be the right thing to test for either (it covers stval across every trap type which writes it, a wider guarantee than what is needed here).
htval does need one. The H extension lets an implementation write it with either the faulting address or zero, so without Shtvala a zero htval cannot be told apart from a genuine fault on guest physical address 0-3, and the address has to be recovered by decoding the access and walking the VS-stage page tables in software instead. That is left as a TODO, and until it is written such hardware panics rather than acting on an address which may not be the one which faulted.
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/emulate.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-)
xen/arch/riscv/emulate.c +21 -2
@@ -9,6 +9,7 @@#include <xen/sched.h> #include <xen/types.h> +#include <asm/cpufeature.h> #include <asm/csr.h> #include <asm/current.h> #include <asm/emulate.h>
@@ -62,10 +63,28 @@ static bool htinst_is_pseudo(unsigned long htinst) } } -/* Reconstruct the guest physical address of the access which faulted. */ +/* Resolves the guest physical address the access faulted on into @gf->gpa. */ static void resolve_faulting_gpa (struct guest_fault *gf) { -BUG_ON ("unimplemented" ); +/* +* A zero htval is either a genuine fault on guest physical address 0-3, or +* an implementation which does not report the address at all; only Shtvala +* tells the two apart. +* +* TODO: where it is absent, recover the address in software rather than +* giving up. +*/ +if ( !gf->htval && + !riscv_isa_extension_available (NULL , RISCV_ISA_EXT_shtvala) ) +panic ("Shtvala isn't supported by h/w; s/w VS-stage walk required\n" ); + +/* +* htval does not carry the two low bits of the address: for an explicit +* access they are those of the faulting guest virtual address in stval, +* and for an implicit access made for VS-stage translation they are zero. +*/ + gf->gpa = ((paddr_t )gf->htval <<2 ) | + (htinst_is_pseudo (gf->htinst) ?0 : (gf->stval &3 )); }static int emulate_load (const struct guest_fault *gf)
Signature · 1 line
2.55.0
PATCH v2 23/39 xen/riscv: look up the exception table for any trap taken in Xen context
In reply to Oleksii Kurochkodo_trap() consulted the exception table only for CAUSE_ILLEGAL_INSTRUCTION, which covers csr_read_safe() but not the hlv/hlvx sequences reading guest
memory: those fault with load/store (guest) page fault causes and would reach do_unexpected_trap() instead of their fixup.
Move the lookup ahead of the cause switch, and gate it on the trap having been taken in Xen context and not being an interrupt:
- sepc of a trap taken from the guest is a guest VA/PA, which the guest can point at an address listed in the exception table; Xen would then act on that entry and, for EX_TYPE_TRAP_INFO, write through a pointer fully under guest control. Entries are matched by exact address, so this needs no more than a numerical collision.
- an interrupt taken at an address listed in the table would otherwise be "fixed up" as if the access itself had faulted, silently skipping it and handing the caller the interrupt's scause as a fault cause.
Returning early skips check_for_pcpu_work(), which is correct: that only runs for traps taken from the guest.
With that in place a G-stage fault reaching the switch can no longer have been caused by an hlv/hlvx covered by an entry, so anything left must have come from the guest; assert as much.
Cache the "trap came from the guest" test in a local, it is now used four times.
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/traps.c | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-)
xen/arch/riscv/traps.c +24 -4
@@ -196,11 +196,34 @@ void do_trap(struct cpu_user_regs *cpu_regs)unsigned long cause =csr_read (CSR_SCAUSE );bool from_guest = cpu_regs->hstatus &HSTATUS_SPV ; +/* +* A synchronous trap taken in Xen context may come from an access done on +* a vCPU's behalf, e.g. the hlv/hlvx sequences in riscv_read_guest(), +* or from a probing access like csr_read_safe(). Both are covered by +* exception table entries which record the fault details for the caller +* and resume execution past the faulting instruction. +* +* Traps taken from the guest must never be fixed up: sepc is then a guest +* address, which the guest could point at an address listed in the +* exception table, making Xen act on an entry (and, for EX_TYPE_TRAP_INFO, +* write through a pointer) fully under guest control. +* +* Interrupts must be excluded too: one taken at an address which happens +* to be listed in the exception table would otherwise be "fixed up" as if +* the access itself had faulted, silently skipping it. +* +* Returning early skips check_for_pcpu_work() below, which is correct: +* that only runs for traps taken from the guest. +*/ +if ( !from_guest && !(cause &CAUSE_IRQ_FLAG ) && +fixup_exception (cpu_regs, cause) ) +return ; +switch ( cause ) {case CAUSE_VIRTUAL_SUPERVISOR_ECALL :/* CAUSE_VIRTUAL_SUPERVISOR_ECALL should come from VS-mode */ -BUG_ON (!(cpu_regs->hstatus &HSTATUS_SPV )); +BUG_ON (!from_guest);vsbi_handle_ecall (cpu_regs);break ;
@@ -232,9 +255,6 @@ void do_trap(struct cpu_user_regs *cpu_regs)break ; } -if (fixup_exception (cpu_regs, cause) ) -break ; - fallthrough;default :if ( cause &CAUSE_IRQ_FLAG )
Signature · 1 line
2.55.0
PATCH v2 24/39 xen/riscv: add helpers for decoding a trapped load or store
In reply to Oleksii Kurochkoemulate_load() and emulate_store() will both need to obtain the instruction which caused a guest MMIO trap, decode it, and locate the register operand it names. Add what the two share, ahead of either of them being implemented: struct decoded_insn, insn_fetch_faulted(), decode_ldst_insn(), guest_xlen(), guest_gpr() and advance_pc().
The mask/match chain is adapted from Linux's KVM RISC-V implementation.
Nothing calls any of this yet, so tag the functions __maybe_unused to keep the build going; the tags go away once emulate_load() and emulate_store() gain their bodies later.
---
How this function could be used can be seen in the next patch.
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/emulate.c | 330 ++++++++++++++++++++ xen/arch/riscv/include/asm/guest_access.h | 4 + xen/arch/riscv/include/asm/riscv_encoding.h | 10 + 3 files changed, 344 insertions(+)
xen/arch/riscv/emulate.c +330 -0
@@ -5,6 +5,7 @@*/ #include <xen/bug.h> +#include <xen/compiler.h> #include <xen/errno.h> #include <xen/sched.h> #include <xen/types.h>
@@ -13,9 +14,29 @@#include <asm/csr.h> #include <asm/current.h> #include <asm/emulate.h> +#include <asm/guest_access.h> +#include <asm/processor.h> #include <asm/riscv_encoding.h> #include <asm/traps.h> +/* +* Determine the trapped load or store instruction which caused a guest MMIO +* trap. +*/ +struct decoded_insn { +/* The instruction itself, and its length in bytes. */ +unsigned long insn; +unsigned int insn_len; +/* Width of the memory access, in bytes. */ +unsigned int len; +/* Number of the register operand: rd for a load, rs2 for a store. */ +unsigned int reg; +/* The access is a store rather than a load. */ +bool is_write; +/* The load zero-extends its result rather than sign-extending it. */ +bool is_unsigned; +}; +/* * The hardware-reported details of a guest page fault, gathered once by * handle_guest_page_fault() and passed down to the emulation of the faulted
@@ -39,6 +60,71 @@ struct guest_fault {paddr_t gpa; }; +static bool is_load_guest_page_fault (unsigned long scause) +{ +return scause ==CAUSE_LOAD_GUEST_PAGE_FAULT ; +} + +static __maybe_unused void advance_pc (struct cpu_user_regs *regs, +unsigned int step) +{ + regs->sepc += step; +} + +/* +* The effective XLEN of the guest at the point of the trap: hstatus.VSXL for a +* trap taken from VS-mode, vsstatus.UXL for one taken from VU-mode. +* +* VSXL is consulted whichever mode the trap came from, as it also gives the +* width of vsstatus itself: where VSXL says 32, that register has no UXL field +* to consult and VU-mode is 32-bit as well, there being nothing to configure. +* +* It is needed to decode a trapped instruction: the encodings which exist only +* for XLEN=64 must not be recognized for a 32-bit guest. Besides those simply +* being reserved there, the compressed ones are ambiguous: C.LD and C.FLW +* share the encoding 0x6000 (mask 0xe003), and likewise C.SD/C.FSW, +* C.LDSP/C.FLWSP and C.SDSP/C.FSWSP. +* +* IS_ENABLED() can't be used here as HSTATUS_VSXL is defined for +* __riscv_xlen == 64 only, the field not existing on RV32 in the first place. +*/ +static __maybe_unused unsigned int guest_xlen (const struct cpu_user_regs *regs) +{ +#ifdef CONFIG_RISCV_32 +return 32 ; +#else +unsigned long xl =MASK_EXTR (regs->hstatus,HSTATUS_VSXL ); + +if ( (xl ==XLEN_FIELD_64 ) && !(regs->sstatus &SSTATUS_SPP ) ) + xl =MASK_EXTR (csr_read (CSR_VSSTATUS ),SSTATUS64_UXL ); + +switch ( xl ) + { +case XLEN_FIELD_32 : +return 32 ; + +case XLEN_FIELD_64 : +return 64 ; + +default : +/* +* The field holds nothing else in practice: XLEN_FIELD_128 would mean +* RV128, which no implementation provides, and the only value left is +* reserved. ASSERT_UNREACHABLE() being debug-only, a width still has +* to be answered in release builds. +* +* Answer 32, that being the safe way to be wrong: the decoder then +* fails to recognize the RV64-only encodings and emulation gives up. +* Answering 64 for what may well be a 32-bit guest would instead have +* it take C.FLW for C.LD and C.FSW for C.SD (see above), i.e. quietly +* emulate an access of the wrong width against the wrong register. +*/ +ASSERT_UNREACHABLE (); +return 32 ; + } +#endif +} +/* * Is @htinst one of the pseudoinstructions reported for a guest page fault * taken on an implicit memory access done for VS-stage address translation?
@@ -87,6 +173,250 @@ static void resolve_faulting_gpa(struct guest_fault *gf) (htinst_is_pseudo (gf->htinst) ?0 : (gf->stval &3 )); } +/* +* Where the value of a decoded instruction's register operand is held. +* +* Relies on x0..x31 being laid out at the start of struct cpu_user_regs in +* architectural register-number order; see the comment there. +*/ +static __maybe_unused unsigned long *guest_gpr (struct cpu_user_regs *regs, +unsigned int reg) +{ +ASSERT (reg <32 ); + +return REG_PTR (reg,0 , regs); +} + +/* +* Obtain the instruction which caused a guest MMIO trap, filling in +* @di->insn and @di->insn_len. It either comes transformed in htinst, or has +* to be fetched from guest memory. +* +* Returns true if the fetch faulted in turn; the resulting trap has then +* already been redirected to the guest and there is nothing further for the +* caller to do. Where it returns false, @di has been filled in and emulation +* is to continue. +*/ +static bool __maybe_unused insn_fetch_faulted (const struct guest_fault *gf, +struct decoded_insn *di) +{ +unsigned long htinst = gf->htinst; + +/* +* A pseudoinstruction says nothing about the instruction the guest was +* executing, and comes with a guest physical address which isn't the one +* that instruction accessed. handle_guest_page_fault() deals with such a +* fault on its own, so no emulation can ever start for one. +*/ +ASSERT (!htinst_is_pseudo (htinst)); + +if ( htinst &BIT (0 ,UL ) ) + { +/* +* Bit[0] == 1 implies trapped instruction value is +* transformed instruction or custom instruction. +* +* The transformation always yields the 32-bit format, with bits[1:0] +* holding a marker instead of the original opcode bits: bit[0] set to +* flag the transformation, bit[1] clear if the trapped instruction +* was a compressed one. Restoring the opcode bits makes the value the +* valid 32-bit encoding decode_ldst_insn() matches against. Its +* INSN_MASK_C_* cases exist for the branch below, where a compressed +* instruction is read from guest memory as is: a trapped one arrives +* here already expanded to its 32-bit equivalent, and the opcode bits +* just restored keep it from matching those cases anyway. +* +* The length then cannot come from the value anymore, only from +* bit[1]. And only a 16- or a 32-bit instruction is ever reported +* this way: the standard load and store instructions the hardware +* transforms are all of one of these two lengths, anything else comes +* as the zero special value handled below. +*/ + di->insn = htinst |INSN_16BIT_MASK ; + di->insn_len = (htinst &BIT (1 ,UL )) ?4 :2 ; + } +else + { +const struct cpu_user_regs *regs = gf->regs; +struct trap_info utrap = {}; + +/* +* Bit[0] == 0 implies trapped instruction value is +* zero or special value. With the pseudoinstructions ruled out +* above, only zero is left: the instruction has to be read from +* guest memory. +*/ + + di->insn =riscv_read_guest (regs->sepc, true, &utrap); +if ( utrap.scause ) + { +/* +* If during getting of trapped instruction a fault happen in +* G-stage translation then CAUSE_LOAD_GUEST_PAGE_FAULT is +* generated. Such faults during this operation is considered as +* bus error. +*/ +if (is_load_guest_page_fault (utrap.scause) ) + utrap.scause =CAUSE_FETCH_ACCESS ; + + utrap.sepc = regs->sepc; + +trap_redirect (&utrap); + +return true; + } + +/* +* riscv_read_guest() fetches at most two halfwords, so a wider +* encoding has been read in part only and cannot be decoded here. +* +* Report an illegal instruction, which is what the guest would have +* got for such an encoding anyway: the ISA defines no instruction +* wider than 32 bits. +*/ +if ( !INSN_IS_16BIT (di->insn) && !INSN_IS_32BIT (di->insn) ) + { + utrap.sepc = regs->sepc; + utrap.scause =CAUSE_ILLEGAL_INSTRUCTION ; +/* +* stval is left zero: the spec allows that for an illegal +* instruction, and only part of the instruction is in hand. +*/ + +trap_redirect (&utrap); + +return true; + } + + di->insn_len =INSN_LEN (di->insn); + } + +return false; +} + +/* +* Decode the load or store instruction fetched into @di, filling in the +* remaining fields of it (@di->insn and @di->insn_len are filled by +* insn_fetch_faulted()). +* +* @xlen is the effective XLEN of the guest, needed as +* the encodings which exist for XLEN=64 only must not be recognized for a +* 32-bit guest. +* +* Returns false if the instruction is not a load or store which can be +* emulated here. +*/ +static __maybe_unused bool decode_ldst_insn (struct decoded_insn *di, +unsigned int xlen) +{ +unsigned long insn = di->insn; +/* Register fields of the uncompressed forms ... */ +unsigned int rd =RV_RD (insn); +unsigned int rs2 =RV_RS2 (insn); +/* +* ... and of the compressed ones, where the 3-bit field selects one of +* x8..x15, while the stack-pointer-relative forms have a full-width one. +*/ +unsigned int rs2s =RVC_RS2S (insn); +unsigned int rs2c =RVC_RS2 (insn); + + di->is_write = false; + di->is_unsigned = false; + di->reg = rd; + +if ( (insn &INSN_MASK_LB ) ==INSN_MATCH_LB ) + di->len =1 ; +else if ( (insn &INSN_MASK_LBU ) ==INSN_MATCH_LBU ) + { + di->len =1 ; + di->is_unsigned = true; + } +else if ( (insn &INSN_MASK_LH ) ==INSN_MATCH_LH ) + di->len =2 ; +else if ( (insn &INSN_MASK_LHU ) ==INSN_MATCH_LHU ) + { + di->len =2 ; + di->is_unsigned = true; + } +else if ( (insn &INSN_MASK_LW ) ==INSN_MATCH_LW ) + di->len =4 ; +else if ( xlen ==64 && (insn &INSN_MASK_LWU ) ==INSN_MATCH_LWU ) + { + di->len =4 ; + di->is_unsigned = true; + } +else if ( (insn &INSN_MASK_C_LW ) ==INSN_MATCH_C_LW ) + { + di->len =4 ; + di->reg = rs2s; + } +/* c.lwsp and c.ldsp are reserved with rd being x0. */ +else if ( (insn &INSN_MASK_C_LWSP ) ==INSN_MATCH_C_LWSP && rd ) + di->len =4 ; +else if ( xlen ==64 && (insn &INSN_MASK_LD ) ==INSN_MATCH_LD ) + di->len =8 ; +else if ( xlen ==64 && (insn &INSN_MASK_C_LD ) ==INSN_MATCH_C_LD ) + { + di->len =8 ; + di->reg = rs2s; + } +else if ( xlen ==64 && (insn &INSN_MASK_C_LDSP ) ==INSN_MATCH_C_LDSP && + rd ) + di->len =8 ; +else if ( (insn &INSN_MASK_SB ) ==INSN_MATCH_SB ) + { + di->len =1 ; + di->is_write = true; + di->reg = rs2; + } +else if ( (insn &INSN_MASK_SH ) ==INSN_MATCH_SH ) + { + di->len =2 ; + di->is_write = true; + di->reg = rs2; + } +else if ( (insn &INSN_MASK_SW ) ==INSN_MATCH_SW ) + { + di->len =4 ; + di->is_write = true; + di->reg = rs2; + } +else if ( (insn &INSN_MASK_C_SW ) ==INSN_MATCH_C_SW ) + { + di->len =4 ; + di->is_write = true; + di->reg = rs2s; + } +else if ( (insn &INSN_MASK_C_SWSP ) ==INSN_MATCH_C_SWSP ) + { + di->len =4 ; + di->is_write = true; + di->reg = rs2c; + } +else if ( xlen ==64 && (insn &INSN_MASK_SD ) ==INSN_MATCH_SD ) + { + di->len =8 ; + di->is_write = true; + di->reg = rs2; + } +else if ( xlen ==64 && (insn &INSN_MASK_C_SD ) ==INSN_MATCH_C_SD ) + { + di->len =8 ; + di->is_write = true; + di->reg = rs2s; + } +else if ( xlen ==64 && (insn &INSN_MASK_C_SDSP ) ==INSN_MATCH_C_SDSP ) + { + di->len =8 ; + di->is_write = true; + di->reg = rs2c; + } +else +return false; + +return true; +} +static int emulate_load (const struct guest_fault *gf) {return -EOPNOTSUPP ;
xen/arch/riscv/include/asm/guest_access.h +4 -0
@@ -5,6 +5,7 @@#include <xen/types.h> struct domain ; +struct trap_info ;unsigned long raw_copy_to_guest (void *to,const void *from,unsigned len);unsigned long raw_copy_from_guest (void *to,const void *from,unsigned len);
@@ -25,6 +26,9 @@ unsigned long raw_clear_guest(void *to, unsigned int len);unsigned long copy_to_guest_phys (struct domain *d,paddr_t gpa,void *buf,unsigned long len); +unsigned long riscv_read_guest (unsigned long guest_addr,bool read_insn, +struct trap_info *trap); +#endif /* ASM__RISCV__GUEST_ACCESS_H */ /* * Local variables:
xen/arch/riscv/include/asm/riscv_encoding.h +10 -0
@@ -65,6 +65,14 @@#define SSTATUS64_UXL MSTATUS_UXL#define SSTATUS64_SD MSTATUS64_SD +/* +* Width encoded by the MXL, SXL, UXL and VSXL fields, all of which share one +* encoding. 0 is reserved. +*/ +#define XLEN_FIELD_32 _UL(1) +#define XLEN_FIELD_64 _UL(2) +#define XLEN_FIELD_128 _UL(3) +#if __riscv_xlen ==64 #define HSTATUS_VSXL _UL(0x300000000)#define HSTATUS_VSXL_SHIFT 32
@@ -896,6 +904,8 @@ (RV_X(x, 7, 2) << 6))#define RVC_SDSP_IMM (x) ((RV_X(x, 10, 3) << 3) | \ (RV_X(x, 7, 3) << 6)) +#define RV_RD (insn) RV_X(insn, SH_RD, 5) +#define RV_RS2 (insn) RV_X(insn, SH_RS2, 5)#define RVC_RS1S (insn) (8 + RV_X(insn, SH_RD, 3))#define RVC_RS2S (insn) (8 + RV_X(insn, SH_RS2C, 3))#define RVC_RS2 (insn) RV_X(insn, SH_RS2C, 5)
Signature · 1 line
2.55.0
PATCH v2 26/39 xen/riscv: add guest store emulation for trapped MMIO accesses
In reply to Oleksii KurochkoExtend the guest page fault handler with store emulation to support MMIO write accesses.
The instruction decode mirrors emulate_load() and, like it, is adapted from Linux's KVM RISC-V implementation. As with the load path, the completion is synchronous through try_handle_mmio() rather than KVM's userspace exit/return split, since Xen's MMIO handlers run in the hypervisor. Faults taken while re-reading the trapped instruction are handled by decode_ldst_insn(), shared with the load path.
When a guest store instruction faults, the trapped instruction is decoded using HTINST or, if unavailable, fetched via unprivileged access. At the moment only virtual interrupt controller (vINTC) traps are expected to occur, since it is currently the only backend registered with the MMIO handler dispatch, so in practice the store is emulated via the vINTC backend.
Together with load emulation, this completes the basic MMIO handling path needed for virtual interrupt controller support on RISC-V.
---
Changes in v2:
- Move the emulation code to the new arch/riscv/emulate.c, leaving traps.c with trap dispatch only.
- Split the patch up: the instruction fetch and the mask/match chain now live in "xen/riscv: add helpers for decoding a trapped load or store" (struct decoded_insn, insn_fetch_faulted(), decode_ldst_insn(), guest_gpr(), advance_pc()), so only emulate_store() itself is left here.
- Since the decoder is now shared with the load path, reject an encoding which is not a store (!di.is_write) explicitly; in v2 the mask/match chain was store-only and could not match a load.
- Recognize the XLEN=64-only encodings by the guest's effective XLEN (guest_xlen()) rather than by Xen's own (CONFIG_RISCV_32). Besides those encodings simply being reserved on RV32, the compressed ones are ambiguous
there: C.SD and C.FSW share an encoding, and likewise C.SDSP and C.FSWSP.
- Read the source register through guest_gpr() instead of the GET_RS2()/GET_RS2S()/GET_RS2C() macros; which of the three register fields an encoding names is now decided by decode_ldst_insn().
- Take the faulting address from struct guest_fault, filled in by resolve_faulting_gpa(), rather than from the fault_addr parameter.
- Drop the description of a fault taken while re-reading the trapped
instruction: that code is now in the patch adding the decoding helpers, where a G-stage fault is reported to the guest as CAUSE_FETCH_ACCESS.
- Update the commit message accordingly.
---
--- xen/arch/riscv/emulate.c | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-)
xen/arch/riscv/emulate.c +21 -2
@@ -453,9 +453,28 @@ static int emulate_load(const struct guest_fault *gf)return 0 ; } -static int emulate_store (struct guest_fault *gf) +static int emulate_store (const struct guest_fault *gf) { -return -EOPNOTSUPP ; +struct cpu_user_regs *regs = gf->regs; +mmio_info_t info = { .is_write = true }; +struct decoded_insn di; +int rc; + +if (insn_fetch_faulted (gf, &di) ) +return 0 ; + +if ( !decode_ldst_insn (&di,guest_xlen (regs)) || !di.is_write ) +return -EOPNOTSUPP ; + + info.data = *guest_gpr (regs, di.reg); + + rc =do_mmio (&info, gf->gpa, di.len); +if ( rc ) +return rc; + +advance_pc (regs, di.insn_len); + +return 0 ; }static void inject_access_fault (const struct guest_fault *gf)
Signature · 1 line
2.55.0
PATCH v2 25/39 xen/riscv: add guest load emulation for trapped MMIO accesses
In reply to Oleksii KurochkoImplement emulate_load() on top of the decoding interface introduced by the previous patch: fetch the trapped instruction, decode it, dispatch the access to a registered MMIO handler via do_mmio(), write the result back into the destination register and step over the instruction.
Xen dispatches MMIO synchronously to an in-hypervisor handler, so unlike KVM RISC-V there is no userspace exit/return step and no equivalent of the kvm_io_bus_read() / KVM_EXIT_MMIO / kvm_riscv_vcpu_mmio_return() split; the result is consumed in place.
Sign extension is done here rather than in the handlers: a signed load is normalized by a shift pair, so a handler need only report the value it read.
At the moment vINTC is the only backend registered with the MMIO dispatch, so in practice this only covers vINTC traps. An access which no handler claims currently crashes the domain; injecting an access fault into the guest instead is left for later.
---
Changes in v2:
- Move the emulation code to the new arch/riscv/emulate.c, leaving traps.c with trap dispatch only.
- Split the patch up: struct decoded_insn and the decoding helpers are introduced by "xen/riscv: introduce the interface for trapped instruction decoding" and filled in by "xen/riscv: implement trapped instruction decoding", so only emulate_load() itself is left here.
- do_mmio() is no longer defined alongside emulate_load(); it now lives in mmio.c, next to the dispatch it drives.
- Don't write the result of a load into x0. SET_RD() wrote rd unconditionally, so a load into x0 clobbered regs->zero and broke the invariant that it reads as zero when x0 is a source operand elsewhere.
- Recognize the XLEN=64-only encodings by the guest's effective XLEN (guest_xlen()) rather than by Xen's own (CONFIG_RISCV_32). Besides those encodings simply being reserved on RV32, the compressed ones are ambiguous
there: C.LD and C.FLW share the encoding 0x6000 (mask 0xe003), and likewise C.SD/C.FSW, C.LDSP/C.FLWSP and C.SDSP/C.FSWSP.
- Take the faulting address from struct guest_fault, filled in by resolve_faulting_gpa(), rather than from get_faulting_gpa().
- Drop the description of a fault taken while re-reading the trapped
instruction: that code is now in the patch implementing fetch_trapped_insn(), where a G-stage fault is reported to the guest as CAUSE_FETCH_ACCESS instead of hitting a BUG_ON().
- Update the commit message accordingly.
---
--- xen/arch/riscv/emulate.c | 53 +++++++++++++++++++++++++++++++--------- 1 file changed, 42 insertions(+), 11 deletions(-)
xen/arch/riscv/emulate.c +42 -11
@@ -5,7 +5,6 @@*/ #include <xen/bug.h> -#include <xen/compiler.h> #include <xen/errno.h> #include <xen/sched.h> #include <xen/types.h>
@@ -15,6 +14,7 @@#include <asm/current.h> #include <asm/emulate.h> #include <asm/guest_access.h> +#include <asm/mmio.h> #include <asm/processor.h> #include <asm/riscv_encoding.h> #include <asm/traps.h>
@@ -65,8 +65,7 @@ static bool is_load_guest_page_fault(unsigned long scause)return scause ==CAUSE_LOAD_GUEST_PAGE_FAULT ; } -static __maybe_unused void advance_pc (struct cpu_user_regs *regs, -unsigned int step) +static void advance_pc (struct cpu_user_regs *regs,unsigned int step) { regs->sepc += step; }
@@ -88,7 +87,7 @@ static __maybe_unused void advance_pc(struct cpu_user_regs *regs,* IS_ENABLED() can't be used here as HSTATUS_VSXL is defined for * __riscv_xlen == 64 only, the field not existing on RV32 in the first place. */ -static __maybe_unused unsigned int guest_xlen (const struct cpu_user_regs *regs) +static unsigned int guest_xlen (const struct cpu_user_regs *regs) {#ifdef CONFIG_RISCV_32 return 32 ;
@@ -179,8 +178,7 @@ static void resolve_faulting_gpa(struct guest_fault *gf)* Relies on x0..x31 being laid out at the start of struct cpu_user_regs in * architectural register-number order; see the comment there. */ -static __maybe_unused unsigned long *guest_gpr (struct cpu_user_regs *regs, -unsigned int reg) +static unsigned long *guest_gpr (struct cpu_user_regs *regs,unsigned int reg) {ASSERT (reg <32 );
@@ -197,8 +195,8 @@ static __maybe_unused unsigned long *guest_gpr(struct cpu_user_regs *regs,* caller to do. Where it returns false, @di has been filled in and emulation * is to continue. */ -static bool __maybe_unused insn_fetch_faulted (const struct guest_fault *gf, -struct decoded_insn *di) +static bool insn_fetch_faulted (const struct guest_fault *gf, +struct decoded_insn *di) {unsigned long htinst = gf->htinst;
@@ -306,8 +304,7 @@ static bool __maybe_unused insn_fetch_faulted(const struct guest_fault *gf,* Returns false if the instruction is not a load or store which can be * emulated here. */ -static __maybe_unused bool decode_ldst_insn (struct decoded_insn *di, -unsigned int xlen) +static bool decode_ldst_insn (struct decoded_insn *di,unsigned int xlen) {unsigned long insn = di->insn;/* Register fields of the uncompressed forms ... */
@@ -419,7 +416,41 @@ static __maybe_unused bool decode_ldst_insn(struct decoded_insn *di,static int emulate_load (const struct guest_fault *gf) { -return -EOPNOTSUPP ; +struct cpu_user_regs *regs = gf->regs; +mmio_info_t info = { .is_write = false }; +struct decoded_insn di; +unsigned int shift =0 ; +int rc; + +/* A fault taken re-reading the instruction is redirected to the guest. */ +if (insn_fetch_faulted (gf, &di) ) +return 0 ; + +if ( !decode_ldst_insn (&di,guest_xlen (regs)) || di.is_write ) +return -EOPNOTSUPP ; + +if ( !di.is_unsigned ) + shift =BITS_PER_BYTE * (sizeof (unsigned long ) - di.len); + +#ifdef EMULATE_LOAD_DEBUG +gdprintk (XENLOG_DEBUG ,"pc=%#lx, addr=%#" PRIpaddr", len=%u, shift=%u\n" , + regs->sepc, gf->gpa, di.len, shift); +#endif + + rc =do_mmio (&info, gf->gpa, di.len); +if ( rc ) +return rc; + +/* +* A load into x0 discards its result: writing regs->zero would break the +* invariant that it reads as zero when x0 is a source operand elsewhere. +*/ +if ( di.reg ) + *guest_gpr (regs, di.reg) = (long )(info.data << shift) >> shift; + +advance_pc (regs, di.insn_len); + +return 0 ; }static int emulate_store (struct guest_fault *gf)
Signature · 1 line
2.55.0
PATCH v2 28/39 xen/riscv: handle the case when no vCPU migration is needed
In reply to Oleksii KurochkoThe IMSIC vsfile mapping is performed in continue_new_vcpu(), since the target pCPU must be known at that point. It is therefore possible for imsic_migrate_vcpu() to be called before continue_new_vcpu() has executed, in which case v->arch.last_pcpu is NR_CPUS and there is nothing to migrate.
Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/imsic.c | 10 ++++++++++ 1 file changed, 10 insertions(+)
xen/arch/riscv/imsic.c +10 -0
@@ -689,5 +689,15 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,void imsic_migrate_vcpu (struct vcpu *v) { +/* +* The scheduler can mark a freshly created vCPU's unit as migrated and +* invoke this before the vCPU has ever run (see the migrated branch in +* schedule()). No need to do migration for such vCPUs as they aren't fully +* initialized (for example, context_switch() will be called after +* imsic_migrate_vcpu()). +*/ +if ( v->arch.last_cpu ==NR_CPUS ) +return ; +BUG_ON ("unimplemented" ); }
Signature · 1 line
2.55.0
PATCH v2 27/39 xen/riscv: introduce arch_move_irqs()
In reply to Oleksii KurochkoWhen migrating a vCPU between pCPUs the hypervisor must also migrate the associated virtual interrupt state. arch_move_irqs() is the per-arch hook called by generic code to trigger that.
Replace the static inline BUG_ON placeholder in asm/irq.h with a real implementation in intc.c dispatching through a new move_irqs vintc_ops callback. Wire it up in vAPLIC, which delegates to imsic_migrate_vcpu() which itself still a stub to be implemented in follow-up patches.
Note that technically ASSERT() in arch_move_irqs() could be skipped as it will be anyway NULL pointer dereference (and a trap will occur) if something isn't properly initialized but sometimes it is harder to find place where NULL pointer derefence happened as it isn't guaraunted that all necessary registers will be filled with something useful.
As at the moment I don't find any case when ->move_irqs() could be skipped, the check that ->move_irq isn't NULL is added to ASSERT() instead of adding "if ( ...->move_irq) vitnc->ops->move_irqs(v)".
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/imsic.c | 5 +++++ xen/arch/riscv/include/asm/imsic.h | 2 ++ xen/arch/riscv/include/asm/intc.h | 3 +++ xen/arch/riscv/include/asm/irq.h | 5 +---- xen/arch/riscv/intc.c | 8 ++++++++ xen/arch/riscv/vaplic.c | 1 + 6 files changed, 20 insertions(+), 4 deletions(-)
xen/arch/riscv/imsic.c +5 -0
@@ -686,3 +686,8 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,return fdt_end_node (fdt); } + +void imsic_migrate_vcpu (struct vcpu *v) +{ +BUG_ON ("unimplemented" ); +}
xen/arch/riscv/include/asm/imsic.h +2 -0
@@ -112,4 +112,6 @@ int vimsic_make_domu_dt_node(struct kernel_info *kinfo, unsigned int *phandle);void imsic_ctxt_switch_from (struct vcpu *v);void imsic_ctxt_switch_to (struct vcpu *v); +void imsic_migrate_vcpu (struct vcpu *v); +#endif /* ASM_RISCV_IMSIC_H */
xen/arch/riscv/include/asm/intc.h +3 -0
@@ -70,6 +70,9 @@ struct vintc_ops {/* Restore vINTC state of the vCPU being switched in */ void (*ctxt_switch_to)(struct vcpu *v); + +/* Move interrupts of vCPU to a different pCPU */ +void (*move_irqs)(struct vcpu *v); };struct vintc {
xen/arch/riscv/include/asm/irq.h +1 -4
@@ -41,10 +41,7 @@ struct irq_desc *irq_to_desc(unsigned int irq);struct cpu_user_regs ;struct dt_device_node ; -static inline void arch_move_irqs (struct vcpu *v) -{ -BUG_ON ("unimplemented" ); -} +void arch_move_irqs (struct vcpu *v);int platform_get_irq (const struct dt_device_node *device,int index);
xen/arch/riscv/intc.c +8 -0
@@ -192,3 +192,11 @@ void vintc_ctxt_switch_to(struct vcpu *v) ops->ctxt_switch_to (v); } + +/* Move vCPU's IRQs from one pCPU to another */ +void arch_move_irqs (struct vcpu *v) +{ +const struct vintc_ops *ops = v->domain->arch.vintc->ops; + + ops->move_irqs (v); +}
xen/arch/riscv/vaplic.c +1 -0
@@ -429,6 +429,7 @@ static const struct vintc_ops vintc_ops = {*/ .ctxt_switch_from = imsic_ctxt_switch_from, .ctxt_switch_to = imsic_ctxt_switch_to, + .move_irqs = imsic_migrate_vcpu, };int domain_vaplic_init (struct domain *d)
Signature · 1 line
2.55.0
PATCH v2 30/39 xen/riscv: prepare new IMSIC VS-file
In reply to Oleksii KurochkoImplement first steps of migration a vCPU to a different guest interrupt file procedure:
- At the old interrupt file, save to memory the values of registers eidelivery and eithreshold, and set eidelivery = 0.
- At the new interrupt file, set eidelivery = 0, and zero all implemented interrupt-pending bits (the eip array).
The following steps will be introduced in follow-up patches.
Add a BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.
vgein_assign() will be introduced later in a separate patch, for not it is only stub.
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/aia.c | 9 ++ xen/arch/riscv/imsic.c | 159 +++++++++++++++++++++++++++++++ xen/arch/riscv/include/asm/aia.h | 4 + xen/include/xen/config.h | 1 + 4 files changed, 173 insertions(+)
xen/arch/riscv/aia.c +9 -0
@@ -1,8 +1,10 @@/* SPDX-License-Identifier: GPL-2.0-only */ +#include <xen/bug.h> #include <xen/errno.h> #include <xen/init.h> #include <xen/sections.h> +#include <xen/sched.h> #include <xen/types.h> #include <asm/cpufeature.h>
@@ -21,3 +23,10 @@ void __init aia_init(void) _aia_usable = true; } + +unsigned int vgein_assign (struct vcpu *v) +{ +BUG_ON ("unimplemented\n" ); + +return 0 ; +}
xen/arch/riscv/imsic.c +159 -0
188 lines not on this page · raw message
xen/arch/riscv/include/asm/aia.h +4 -0
@@ -3,8 +3,12 @@#ifndef RISCV_AIA_H #define RISCV_AIA_H +struct vcpu ; +bool aia_usable (void );void aia_init (void ); +unsigned int vgein_assign (struct vcpu *v); +#endif /* RISCV_AIA_H */
xen/include/xen/config.h +1 -0
@@ -100,6 +100,7 @@#define BITS_PER_INT (BITS_PER_BYTE * __SIZEOF_INT__)#define BITS_PER_LONG (BITS_PER_BYTE * BYTES_PER_LONG)#define BITS_PER_LLONG (BITS_PER_BYTE * __SIZEOF_LONG_LONG__) +#define BITS_PER_TYPE (type) (sizeof(type) * BITS_PER_BYTE)/* It is assumed that sizeof(void *) == __alignof(void *) */ #define POINTER_ALIGN __SIZEOF_POINTER__
Signature · 1 line
2.55.0
PATCH v2 29/39 xen/riscv: introduce aplic_reconfigure_target()
In reply to Oleksii KurochkoWhen a vCPU is migrated to a different pCPU, its IMSIC guest interrupt file changes. Any APLIC interrupt previously configured to deliver an MSI to the old interrupt file must be retargeted to the new one.
Implement aplic_reconfigure_target() to scan all interrupts allocated to the domain and update their APLIC TARGET registers accordingly.
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/aplic.c | 42 ++++++++++++++++++++++++++++++ xen/arch/riscv/include/asm/aplic.h | 4 +++ 2 files changed, 46 insertions(+)
xen/arch/riscv/aplic.c +42 -0
@@ -138,6 +138,48 @@ uint32_t aplic_msi_target_gen(const struct vcpu *target_vcpu,return base_val; } +void aplic_reconfigure_target (const struct vcpu *v, +unsigned int old_guest_file_id, +unsigned int old_cpu) +{ +const struct vintc *vintc = v->domain->arch.vintc; +const unsigned long *auth_irq_bmp = vintc->used_irqs; +unsigned long old_hart_field =aplic_hart_field (old_cpu); +unsigned long flags; +unsigned int irqn; + +/* Support only MSI mode at the moment */ +BUG_ON (!aplic_msi_mode ()); + +spin_lock_irqsave (&aplic.lock, flags); + + bitmap_for_each ( irqn, auth_irq_bmp, vintc->nr_virqs ) + { +volatile uint32_t __iomem *ptarget; +uint32_t target_val; +unsigned int guest_index, hart_index; + +if ( !irqn ) +continue ; + + ptarget = &aplic.regs->target[irqn -1 ]; + target_val =readl (ptarget); + + guest_index =MASK_EXTR (target_val,APLIC_TARGET_GUEST_IDX ); + hart_index =MASK_EXTR (target_val,APLIC_TARGET_HART_IDX ); + +if ( (guest_index != old_guest_file_id) || + (hart_index != old_hart_field) ) +continue ; + + target_val =aplic_msi_target_gen (v, target_val); + +writel (target_val, ptarget); + } + +spin_unlock_irqrestore (&aplic.lock, flags); +} +uint32_t aplic_hw_read_reg (unsigned int offset) {unsigned long flags;
xen/arch/riscv/include/asm/aplic.h +4 -0
@@ -174,4 +174,8 @@ struct aplic_regs {uint32_t aplic_hw_read_reg (unsigned int offset);void aplic_hw_write_reg (unsigned int offset,uint32_t value); +void aplic_reconfigure_target (const struct vcpu *v, +unsigned int old_guest_file_id, +unsigned int old_cpu); +#endif /* ASM_RISCV_APLIC_H */
Signature · 1 line
2.55.0
PATCH v2 32/39 xen/riscv: remap interrupts to new IMSIC VS-file
In reply to Oleksii KurochkoAfter new IMSIC VS-file is zeroed-out it is necessary to do G-stage remaping fo new IMSIC VS-file. Also, if any interrupts at an APLIC are forwarded by MSIs to the old interrupt file, reconfigure the APLIC to send them to the new interrupt file.
Generally it is needed also to modify the relevant translation tables at all IOMMUs so that MSIs for this virtual interrupt file are now sent to the new physical interrupt file but it is skipped for now there is no IOMMU support for RISC-V.
Synchronize with APLIC to ensure that no straggler MSIs will arrive at the old interrupt file by using of aplic_genmsi_barrier().
Technically there is no need for read_lock_irqsave() and read_unlock_irqrestore() around reading of ->guest_file_id, as a write cannot happen in parallel: any update to ->guest_file_id for a vCPU will happen either in imsic_migrate_vcpu() itself or before the vCPU first gains control (in continue_new_vcpu()), so there is no concurrent access to it in imsic_migrate_vcpu(). The lock is added here for potential future cases.
Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.
imsic_map_guest_file() and imsic_update_state() are stubs for now and will be introduced later in a separate patch.
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/imsic.c | 103 +++++++++++++++++++++++++++++ xen/arch/riscv/include/asm/imsic.h | 3 + 2 files changed, 106 insertions(+)
xen/arch/riscv/imsic.c +103 -0
@@ -27,6 +27,7 @@#include <xen/xvmalloc.h> #include <asm/aia.h> +#include <asm/aplic.h> #include <asm/imsic.h> #define IMSIC_HART_SIZE (guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -60,6 +61,12 @@ static unsigned int __ro_after_init guest_num_msis;#define IMSIC_DISABLE_EITHRESHOLD 1#define IMSIC_ENABLE_EITHRESHOLD 0 +#define imsic_csr_read (c) \ +({ \ + csr_write(CSR_SISELECT, (c)); \ + csr_read(CSR_SIREG); \ +}) +#define imsic_csr_write (c, v) \ do { \ csr_write(CSR_SISELECT, c); \
@@ -141,6 +148,11 @@ unsigned int vcpu_guest_file_id(const struct vcpu *v)return ACCESS_ONCE (v->arch.vimsic_state->guest_file_id); } +void imsic_update_state (struct vcpu *v,unsigned int guest_file_id) +{ +BUG_ON ("unimplemented\n" ); +} +void __init imsic_ids_local_delivery (bool enable) {if ( enable )
@@ -242,6 +254,15 @@ void imsic_irq_disable(unsigned int irq)spin_unlock (&imsic_cfg.lock); } +static bool imsic_local_is_pending (unsigned int id) +{ +unsigned long isel = + (id /BITS_PER_LONG ) * (BITS_PER_LONG / IMSIC_EIPx_BITS) +IMSIC_EIP0 ; +unsigned long bit =BIT (id %BITS_PER_LONG ,UL ); + +return !!(imsic_csr_read (isel) & bit); +} +/* Callers aren't intended to changed imsic_cfg so return const. */ const struct imsic_config *imsic_get_config (void ) {
@@ -436,6 +457,11 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)/* Nothing to do */ } +int imsic_map_guest_file (struct vcpu *v,unsigned int vsfile_id) +{ +return -EOPNOTSUPP ; +} + int cf_check vcpu_imsic_init(struct vcpu *v) {struct vimsic_state *imsic_state;
@@ -497,6 +523,27 @@ static void imsic_call_on_cpu(unsigned int cpu, void (*func)(void *),on_selected_cpus (cpumask_of (cpu), func, data,1 ); } +/* +* Ensure that all the MSIs the APLIC has already generated for the hart this +* runs on have really reached the hart's IMSIC. +* +* The barrier is the one described by the AIA specification in +* "Synchronizing interactions between a hart and the APLIC": ask the APLIC to +* send an MSI to the hart itself and wait until it shows up as pending in the +* hart's own interrupt file. As it says nothing about MSIs on their way to +* any other hart, it has to be executed by the pCPU owning the interrupt file +* the MSIs were being sent to. +*/ +static void cf_check imsic_aplic_sync(void *data) +{ +imsic_local_eix_update (imsic_cfg.sync_id,1 , true, false); + +aplic_genmsi_barrier (); + +while ( !imsic_local_is_pending (imsic_cfg.sync_id) ) +cpu_relax (); +} + static void cf_check imsic_vsfile_local_clear(void *data) {unsigned int i;
@@ -837,6 +884,10 @@ void imsic_migrate_vcpu(struct vcpu *v)struct imsic_vsfile_data vsfile_data = { .nr_eix = nr_hw_eix, }; +struct vimsic_state *imsic_state = v->arch.vimsic_state; +unsigned long flags; +unsigned int old_vsfile_id; +unsigned int old_vsfile_cpu;/* * The scheduler can mark a freshly created vCPU's unit as migrated and
@@ -848,8 +899,22 @@ void imsic_migrate_vcpu(struct vcpu *v)if ( v->arch.last_cpu ==NR_CPUS )return ; +read_lock_irqsave (&imsic_state->vsfile_lock, flags); + old_vsfile_id = imsic_state->guest_file_id; + old_vsfile_cpu = imsic_state->vsfile_cpu; +read_unlock_irqrestore (&imsic_state->vsfile_lock, flags); + +/* +* We don't support SW interrupt files at the moment. Bail out before +* anything is touched, as the old file has no owning pCPU in that case +* and there is nothing to retarget the producers away from. +*/ +if ( old_vsfile_cpu ==NR_CPUS ) +panic ("IMSIC SW-file isn't supported\n" ); +/* * At this point, all interrupt producers are still using the old IMSIC +* VS-file so we first move all interrupt producers to the new IMSIC * VS-file. */
@@ -870,5 +935,43 @@ void imsic_migrate_vcpu(struct vcpu *v)/* Zero-out new IMSIC VS-file */ imsic_call_on_cpu (new_vsfile_cpu, imsic_vsfile_local_clear, &vsfile_data); +/* Update G-stage mapping for the new IMSIC VS-file */ +if (imsic_map_guest_file (v, new_vsfile_hgei) ) + { +domain_crash (v->domain,"Migration to hw interrupt file failed\n" ); + +return ; + } + +imsic_update_state (v, new_vsfile_hgei); + +/* +* TODO: Modify the relevant translation tables at all IOMMUs so that MSIs +* for this virtual interrupt file are now sent to the new physical +* interrupt file. +*/ +if ( iommu_enabled ) +printk_once ("IMSIC: IOMMU MSI retargeting is not implemented\n" ); + +/* +* If any interrupts at an APLIC are forwarded by MSIs to the old interrupt +* file, reconfigure the APLIC to send them to the new interrupt file. +*/ +aplic_reconfigure_target (v, old_vsfile_id, old_vsfile_cpu); + +/* +* Synchronizing interactions between a hart and the APLIC. +* +* The MSIs to be flushed are the ones still on their way to the old +* interrupt file, so the barrier has to be done by the pCPU which owns +* that file. +*/ +imsic_call_on_cpu (old_vsfile_cpu, imsic_aplic_sync,NULL ); + +/* +* At this point, all interrupt producers have been moved +* to the new IMSIC VS-file. +*/ +BUG_ON ("unimplemented" ); }
xen/arch/riscv/include/asm/imsic.h +3 -0
@@ -114,12 +114,15 @@ void imsic_ids_local_delivery(bool enable);int vcpu_imsic_init (struct vcpu *v);void vcpu_imsic_deinit (struct vcpu *v);unsigned int vcpu_guest_file_id (const struct vcpu *v); +void imsic_update_state (struct vcpu *v,unsigned int guest_file_id);int vimsic_make_domu_dt_node (struct kernel_info *kinfo,unsigned int *phandle);void imsic_ctxt_switch_from (struct vcpu *v);void imsic_ctxt_switch_to (struct vcpu *v); +int imsic_map_guest_file (struct vcpu *v,unsigned int vsfile_id); +void imsic_migrate_vcpu (struct vcpu *v);#endif /* ASM_RISCV_IMSIC_H */
Signature · 1 line
2.55.0
PATCH v2 33/39 xen/riscv: dump old interrupt file to memory
In reply to Oleksii KurochkoAt the old interrupt file, dump to memory all the eip and eie arrays). After this step is done, the old interrupt file is no longer in use so old intrrupt file VGEIN could be released.
Restoring of old interrupt file state will be done in follow-up patch.
There are cases where it is needed to specify on which cpu it is necessary to VGEIN should be released so update vgein_release() to deal with that.
Keep BUG_ON("unimplemented") placeholder in imsic_migrate_vcpu() to guard against silent incorrect behaviour or unexpected panics in guest VMs until the function is fully implemented.
vgein_release() is stub for now and will be introduced later.
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/aia.c | 5 ++ xen/arch/riscv/imsic.c | 104 +++++++++++++++++++++++++++++++ xen/arch/riscv/include/asm/aia.h | 1 + 3 files changed, 110 insertions(+)
xen/arch/riscv/aia.c +5 -0
@@ -30,3 +30,8 @@ unsigned int vgein_assign(struct vcpu *v)return 0 ; } + +void vgein_release (struct vcpu *v,unsigned int vgein_id,unsigned int cpu) +{ +BUG_ON ("unimplemented\n" ); +}
xen/arch/riscv/imsic.c +104 -0
139 lines not on this page · raw message
xen/arch/riscv/include/asm/aia.h +1 -0
@@ -10,5 +10,6 @@ bool aia_usable(void);void aia_init (void );unsigned int vgein_assign (struct vcpu *v); +void vgein_release (struct vcpu *v,unsigned int vgein_id,unsigned int cpu);#endif /* RISCV_AIA_H */
Signature · 1 line
2.55.0
PATCH v2 34/39 xen/riscv: restore register state in the new IMSIC VS-file
In reply to Oleksii KurochkoAt this point, all interrupt producers have been moved to the new IMSIC VS-file so we move register state from the old IMSIC VS/SW-file to the new IMSIC VS-file.
As new IMSIC VS-file is ready to be used update vCPU's hstatus with new VGEIN.
As the whole migration procedure is finished add some extra explanatory comments.
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/imsic.c | 82 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 76 insertions(+), 6 deletions(-)
xen/arch/riscv/imsic.c +76 -6
@@ -112,6 +112,12 @@ do { \ r_; \ }) +#define imsic_vs_csr_set (c, v) \ +do { \ + csr_write(CSR_VSISELECT, (c)); \ + csr_set(CSR_VSIREG, (v)); \ +} while ( 0 ) +#define imsic_vs_csr_write (c, v) \ do { \ csr_write(CSR_VSISELECT, (c)); \
@@ -185,6 +191,19 @@ static void imsic_eix_write(unsigned int ireg, unsigned long val) } } +static void imsic_eix_set (unsigned int ireg,unsigned long val) +{ +switch ( ireg ) + { +imsic_switchcase_64 (imsic_switchcase_break,IMSIC_EIP0 , + imsic_vs_csr_set, val) +imsic_switchcase_64 (imsic_switchcase_break,IMSIC_EIE0 , + imsic_vs_csr_set, val) +default : +ASSERT_UNREACHABLE (); + } +} +unsigned int vcpu_guest_file_id (const struct vcpu *v) {return ACCESS_ONCE (v->arch.vimsic_state->guest_file_id);
@@ -630,13 +649,13 @@ static void cf_check imsic_vsfile_local_read_clear(void *data) old_vsiselect =csr_read (CSR_VSISELECT ); old_hstatus =csr_read (CSR_HSTATUS ); new_hstatus = old_hstatus & ~HSTATUS_VGEIN ; - new_hstatus |= ((unsigned long )idata->hgei) <<HSTATUS_VGEIN_SHIFT ; + new_hstatus |=MASK_INSR (idata->hgei,HSTATUS_VGEIN );csr_write (CSR_HSTATUS , new_hstatus);/* -* There is no need to use atomic functions version to store -* values in MRIF because imsic_vsfile_read_clear() is always called -* with pointer to temporary MRIF on stack. +* No atomic accessors are needed to store the values into the MRIF here, +* as imsic_vsfile_read_clear() is always called with a pointer to a +* temporary MRIF on the stack. */ mrif->eidelivery =imsic_vs_csr_swap (IMSIC_EIDELIVERY ,0 );
@@ -972,6 +991,49 @@ int __init vimsic_make_domu_dt_node(struct kernel_info *kinfo,return fdt_end_node (fdt); } +static void cf_check imsic_vsfile_local_update(void *data) +{ +unsigned int i; +struct imsic_mrif_eix *eix; +const struct imsic_vsfile_data *idata = data; +struct imsic_mrif *mrif = idata->mrif; +unsigned long new_hstatus, old_hstatus, old_vsiselect; + +/* We can only update if we have a HW IMSIC context */ +if ( !idata->hgei ) +return ; + +/* +* No atomic accessors are needed to read the values out of the MRIF here, +* as this is always called with a pointer to a temporary MRIF on the +* stack. +*/ + + old_vsiselect =csr_read (CSR_VSISELECT ); + old_hstatus =csr_read (CSR_HSTATUS ); + new_hstatus = old_hstatus & ~HSTATUS_VGEIN ; + new_hstatus |=MASK_INSR (idata->hgei,HSTATUS_VGEIN ); +csr_write (CSR_HSTATUS , new_hstatus); + +for ( i =0 ; i < idata->nr_eix; i++ ) + { + eix = &mrif->eix[i]; + +imsic_eix_set (IMSIC_EIP0 + i *2 , eix->eip[0 ]); +imsic_eix_set (IMSIC_EIE0 + i *2 , eix->eie[0 ]); +#ifdef CONFIG_RISCV_32 +imsic_eix_set (IMSIC_EIP0 + i *2 +1 , eix->eip[1 ]); +imsic_eix_set (IMSIC_EIE0 + i *2 +1 , eix->eie[1 ]); +#endif + } + +imsic_vs_csr_write (IMSIC_EITHRESHOLD , mrif->eithreshold); +imsic_vs_csr_write (IMSIC_EIDELIVERY , mrif->eidelivery); + +csr_write (CSR_HSTATUS , old_hstatus); +csr_write (CSR_VSISELECT , old_vsiselect); +} +void imsic_migrate_vcpu (struct vcpu *v) {unsigned int new_vsfile_hgei;
@@ -1068,7 +1130,8 @@ void imsic_migrate_vcpu(struct vcpu *v)/* * At this point, all interrupt producers have been moved -* to the new IMSIC VS-file. +* to the new IMSIC VS-file so we move register state from +* the old IMSIC VS/SW-file to the new IMSIC VS-file. */ /* Read and clear register state from old IMSIC VS-file */
@@ -1077,5 +1140,12 @@ void imsic_migrate_vcpu(struct vcpu *v)/* Free-up old IMSIC VS-file */ vgein_release (v, old_vsfile_id, old_vsfile_cpu); -BUG_ON ("unimplemented" ); +/* Restore register state in the new IMSIC VS-file */ + vsfile_data.mrif = &tmrif; +imsic_call_on_cpu (new_vsfile_cpu, imsic_vsfile_local_update, &vsfile_data); + +/* Set VCPU HSTATUS.VGEIN to new IMSIC VS-file */ +vcpu_guest_cpu_user_regs (v)->hstatus &= ~HSTATUS_VGEIN ; +vcpu_guest_cpu_user_regs (v)->hstatus |= +MASK_INSR (new_vsfile_hgei,HSTATUS_VGEIN ); }
Signature · 1 line
2.55.0
PATCH v2 35/39 xen/riscv: add basic VGEIN management for AIA guests
In reply to Oleksii KurochkoIt was decided to add support for IMSIC from the start instead of having APLIC operate in direct delivery mode, as it requires a trap-and-emulation approach, which is not optimal from a performance standpoint.
AIA provides a hardware-accelerated mechanism for delivering external interrupts to domains via "guest interrupt files" located in IMSIC. A single physical hart can implement multiple such files (up to GEILEN), allowing several virtual harts to receive interrupts directly from hardware.
Introduce per-CPU tracking of guest interrupt file identifiers (VGEIN) for systems implementing AIA specification. Each CPU maintains a bitmap describing which guest interrupt files are currently in use.
Implement helpers to initialize the bitmap based on the number of available guest interrupt files (GEILEN), assign a VGEIN to a vCPU, and release it when no longer needed.
---
Also in the next patch there is other context to understand the usage of spinlock introduced here.
---
Changes in v2:
- make vgein_init() pCPU agnostic as it is working with CSR which could be read only on local pCPU itself.
- Move introduction of vgein_ctrl->owners[] to separate patch.
- Add ASSERT() and re-init vgein->bmp with 0.
- Update the commit message (drop the last sentence as ->hstatus isn't filled anymore in in vgein_*() functions).
- Introduce vgein_deinit().
---
--- xen/arch/riscv/aia.c | 141 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 137 insertions(+), 4 deletions(-)
xen/arch/riscv/aia.c +137 -4
@@ -1,13 +1,31 @@/* SPDX-License-Identifier: GPL-2.0-only */ -#include <xen/bug.h> +#include <xen/bitops.h> +#include <xen/cpu.h> #include <xen/errno.h> #include <xen/init.h> #include <xen/sections.h> #include <xen/sched.h> +#include <xen/spinlock.h> #include <xen/types.h> +#include <asm/aia.h> #include <asm/cpufeature.h> +#include <asm/csr.h> +#include <asm/current.h> + +struct vgein_ctrl { +/* The least-significant bits are implemented first, apart from bit 0 */ +unsigned long bmp; +spinlock_t lock; +unsigned int geilen; +}; + +/* +* VGEIN control structure for each physical CPU to track which VS (guest) +* interrupt file IDs are in use. +*/ +static DEFINE_PER_CPU(struct vgein_ctrl, vgein);static bool __ro_after_init _aia_usable;
@@ -16,22 +34,137 @@ bool aia_usable(void)return _aia_usable; } +/* HGEIE is a per-hart CSR, so this has to run on the CPU being initialized. */ +static int vgein_init (void ) +{ +struct vgein_ctrl *vgein = &this_cpu (vgein); + +spin_lock_init (&vgein->lock); + +csr_write (CSR_HGEIE , ~0UL ); + vgein->geilen =flsl (csr_read (CSR_HGEIE ) >>1 ); +csr_write (CSR_HGEIE ,0 ); + + vgein->bmp =0 ; + +if ( !vgein->geilen ) +return -EOPNOTSUPP ; + +return 0 ; +} + +static void vgein_deinit (void ) +{ +csr_write (CSR_HGEIE ,0 ); +} + +static int cf_check cpu_callback(struct notifier_block *nfb, +unsigned long action,void *hcpu) +{ +unsigned int cpu = (unsigned long )hcpu; +int rc =0 ; + +switch ( action ) + { +case CPU_STARTING : + rc =vgein_init (); +if ( rc ) +printk (XENLOG_ERR "AIA: failed to init vgein for CPU%u: %d\n" , + cpu, rc); +break ; + +case CPU_DYING : +vgein_deinit (); +break ; + } + +return notifier_from_errno (rc); +} + +static struct notifier_block cpu_nfb = { + .notifier_call = cpu_callback, +}; +void __init aia_init (void ) { +int rc; +if ( !riscv_isa_extension_available (NULL , RISCV_ISA_EXT_ssaia) ) + { +dprintk (XENLOG_WARNING ,"SSAIA isn't present in riscv,isa\n" );return ; + } + +if ( (rc =vgein_init ()) ) + { +dprintk (XENLOG_ERR ,"vgein_init() failed: %d\n" , rc); +return ; + } _aia_usable = true; + +register_cpu_notifier (&cpu_nfb); }unsigned int vgein_assign (struct vcpu *v) { -BUG_ON ("unimplemented\n" ); +unsigned int vgein_id; +struct vgein_ctrl *vgein = &per_cpu (vgein, v->processor); +unsigned long *bmp = &vgein->bmp; +unsigned long flags; -return 0 ; +if ( !vgein->geilen ) +return 0 ; + +spin_lock_irqsave (&vgein->lock, flags); +/* +* The vgein_id shouldn't be zero, as it will indicate that no guest +* external interrupt source is selected for VS-level external interrupts +* according to RISC-V privileged spec: +* Hypervisor Status Register (hstatus) in RISC-V privileged spec: +* +* The VGEIN (Virtual Guest External Interrupt Number) field selects +* a guest external interrupt source for VS-level external interrupts. +* VGEIN is a WLRL field that must be able to hold values between zero +* and the maximum guest external interrupt number (known as GEILEN), +* inclusive. +* When VGEIN=0, no guest external interrupt source is selected for +* VS-level external interrupts. +* +* So start to search from bit number 1. +*/ + vgein_id =find_next_zero_bit (bmp, vgein->geilen +1 ,1 ); + +if ( vgein_id > vgein->geilen ) + vgein_id =0 ; +else +__set_bit (vgein_id, bmp); + +spin_unlock_irqrestore (&vgein->lock, flags); + +#ifdef VGEIN_DEBUG +gprintk (XENLOG_DEBUG ,"%s: %pv: vgein_id(%u), xen_cpu%u_bmp=%#lx\n" , + __func__, v, vgein_id, v->processor, *bmp); +#endif + +return vgein_id; }void vgein_release (struct vcpu *v,unsigned int vgein_id,unsigned int cpu) { -BUG_ON ("unimplemented\n" ); +unsigned long flags; +struct vgein_ctrl *vgein = &per_cpu (vgein, cpu); + +if ( !vgein_id ) +return ; + +spin_lock_irqsave (&vgein->lock, flags); +if ( !__test_and_clear_bit (vgein_id, &vgein->bmp) ) +ASSERT_UNREACHABLE (); +spin_unlock_irqrestore (&vgein->lock, flags); + +#ifdef VGEIN_DEBUG +gprintk (XENLOG_DEBUG ,"%s: %pv: vgein_id(%u), xen_cpu%u_bmp=%#lx\n" , + __func__, v, vgein_id, cpu, vgein->bmp); +#endif }
Signature · 1 line
2.55.0
PATCH v2 31/39 xen/riscv: implement APLIC-hart sync barrier for vCPU migration
In reply to Oleksii KurochkoDuring migration of a virtual hart to a different guest interrupt file, straggler MSIs from the APLIC could arrive at the old interrupt file after the switch.
genmsi is used despite not supporting guest interrupt files because the AIA spec guarantees that all MSIs previously sent from the APLIC to the same hart are visible at the hart's IMSIC before the extempore MSI from genmsi becomes visible.
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/aplic.c | 26 ++++++++++++++++++++++++++ xen/arch/riscv/imsic.c | 12 ++++++++++++ xen/arch/riscv/include/asm/aplic.h | 3 +++ xen/arch/riscv/include/asm/imsic.h | 8 ++++++++ 4 files changed, 49 insertions(+)
xen/arch/riscv/aplic.c +26 -0
@@ -27,7 +27,9 @@#include <asm/imsic.h> #include <asm/intc.h> #include <asm/io.h> +#include <asm/processor.h> #include <asm/riscv_encoding.h> +#include <asm/smp.h> static struct aplic_priv aplic = { .lock =SPIN_LOCK_UNLOCKED ,
@@ -205,6 +207,30 @@ void aplic_hw_write_reg(unsigned int offset, uint32_t value)spin_unlock_irqrestore (&aplic.lock, flags); } +/* +* As needed, synchronize with all IOMMUs and APLICs to ensure that no +* straggler MSIs will arrive at the old interrupt file after this step. +*/ +void aplic_genmsi_barrier (void ) +{ +const struct imsic_config *imsic =imsic_get_config (); +unsigned int cpu =smp_processor_id (); +unsigned long flags; +uint32_t val; + + val =MASK_INSR (aplic_hart_field (cpu),APLIC_TARGET_HART_IDX ) | + (imsic->sync_id &APLIC_TARGET_EIID ); + +spin_lock_irqsave (&aplic.lock, flags); + +writel (val, &aplic.regs->genmsi); + +while (readl (&aplic.regs->genmsi) &APLIC_GENMSI_BUSY ) +cpu_relax (); + +spin_unlock_irqrestore (&aplic.lock, flags); +} +static void __init aplic_init_hw_interrupts (void ) {unsigned int i;
xen/arch/riscv/imsic.c +12 -0
@@ -195,6 +195,15 @@ void imsic_irq_enable(unsigned int irq)*/ ASSERT (!local_irq_is_enabled ()); +if ( irq == imsic_cfg.sync_id ) + { +printk (XENLOG_WARNING +"irq%u is reserved for APLIC sync so shouldn't be set by %s\n" , + irq, __func__); + +return ; + } +spin_lock (&imsic_cfg.lock);/* * There is no irq - 1 here (look at aplic_set_irq_type()) because:
@@ -377,6 +386,9 @@ static int __init imsic_parse_node(const struct dt_device_node *node,return -ENOENT ; } +/* Reserve last identity for APLIC-to-hart synchronization */ + imsic_cfg.sync_id = imsic_cfg.nr_ids; +/* Compute base address */ *nr_mmios =0 ; rc =dt_device_get_address (node, *nr_mmios, &base_addr,NULL );
xen/arch/riscv/include/asm/aplic.h +3 -0
@@ -88,6 +88,7 @@#define APLIC_SETIPNUM_LE 0x2000#define APLIC_GENMSI 0x3000 +#define APLIC_GENMSI_BUSY BIT(12, U)#define APLIC_TARGET_BASE 0x3004#define APLIC_TARGET_LAST 0x3ffc
@@ -178,4 +179,6 @@ void aplic_reconfigure_target(const struct vcpu *v,unsigned int old_guest_file_id, unsigned int old_cpu); +void aplic_genmsi_barrier (void ); +#endif /* ASM_RISCV_APLIC_H */
xen/arch/riscv/include/asm/imsic.h +8 -0
@@ -68,6 +68,14 @@ struct imsic_config {/* Number off interrupt identities */ unsigned int nr_ids; +/* +* Interrupt identity reserved exclusively for APLIC-to-hart +* synchronization. +* +* Must not be allocated to any interrupt source. +*/ +unsigned int sync_id; +/* MSI */ const struct imsic_msi *msi;
Signature · 1 line
2.55.0
PATCH v2 37/39 xen/riscv: map IMSIC interrupt file for vCPUs
In reply to Oleksii KurochkoA guest running in VS-mode expects its own IMSIC S-file at offset 0 of its guest-physical IMSIC block. Physically, the guest-file (G-file) assigned to this vCPU lives at a hart-relative offset given by guest_file_id (assigned via the vGEIN allocator). Therefore, imsic_map_guest_file() uses stage-2 translation to redirect the guest's fixed per-vCPU GPA page (offset 0) to the specific physical guest-file page.
---
Changes in v2:
- Use GUEST_IMSIC_S_BASE instead of imsic_cfg.base_addr as the base of the guest address to map to, and change the type of gaddr to paddr_t as it holds a guest physical address.
- Rename guest_stride to guest_offset: it is an offset of the VS-file inside the pCPU's IMSIC block, not a stride.
- Use PRIpaddr for physical addresses and %u for unsigned values in the debug/error messages.
- Switch the mapping failure message from printk() to dprintk(XENLOG_ERR, ...).
- Update the comment above imsic_map_guest_file(): vCPUs aren't pinned, they run on the pCPU chosen by the scheduler, and mention that on migration a VS-file is acquired on the new pCPU and mapped at the same GFN, so the stale mapping is replaced rather than explicitly torn down.
---
--- xen/arch/riscv/imsic.c | 66 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 65 insertions(+), 1 deletion(-)
xen/arch/riscv/imsic.c +65 -1
@@ -29,6 +29,7 @@#include <asm/aia.h> #include <asm/aplic.h> #include <asm/imsic.h> +#include <asm/p2m.h> #define IMSIC_HART_SIZE (guest_bits) (BIT(guest_bits, U) * IMSIC_MMIO_PAGE_SZ)
@@ -537,9 +538,72 @@ void cf_check imsic_ctxt_switch_to(struct vcpu *v)read_unlock_irqrestore (&imsic_state->vsfile_lock, flags); } +/* +* Map the physical IMSIC guest interrupt file (G-file) assigned to vCPU +* into the domain's stage-2 guest-physical address space. +* +* In the machine's physical address space (SPA), each hart's IMSIC +* supervisor-level file (S-file) is located at offset 0 of its address block, +* followed contiguously by GEILEN guest files at offsets of 1, 2, ..., N pages. +* +* Because a guest OS running in VS-mode expects its own supervisor-level +* interrupt file to be at offset 0 of its guest-physical IMSIC block, the +* hypervisor must use stage-2 address translation to map the vCPU's +* guest-physical "supervisor" page (GPA offset 0) to the specific +* physical guest file page (SPA offset guest_file_id) on the physical hart. +* +* A vCPU runs on the pCPU the scheduler picked for it (v->processor), and +* the guest file it is given (guest_file_id, from the vGEIN allocator) +* belongs to that very pCPU's IMSIC. A guest_file_id of 0 indicates that no +* hardware guest file is selected (matching the architectural behavior where +* vGEIN = 0 in the hstatus CSR selects no guest external interrupt source), +* requiring the VS-file to be emulated in software. +* +* Consequently the mapping installed here is only valid as long as the vCPU +* stays on that pCPU. When it migrates, a VS-file is acquired on the new +* pCPU and mapped at the very same GFN, so the stale mapping needs no +* explicit tear-down: it is simply replaced. +* +* The base guest-physical address advertised to the guest in the device +* tree matches offset 0 of the vCPU's virtual IMSIC block. Stage-2 +* translation ensures that guest supervisor accesses to this page are +* transparently routed to the real hardware VS-file granted to it on +* the pCPU it currently runs on. +*/ int imsic_map_guest_file (struct vcpu *v,unsigned int vsfile_id) { -return -EOPNOTSUPP ; +struct domain *d = v->domain; +unsigned int cpu = v->processor; +paddr_t gaddr =GUEST_IMSIC_S_BASE + (IMSIC_MMIO_PAGE_SZ * v->vcpu_id); +paddr_t paddr, guest_offset; +int res; + +/* Nothing to map in the case of sw interrupt file. */ +if ( !vsfile_id ) +return 0 ; + + guest_offset = vsfile_id *IMSIC_MMIO_PAGE_SZ ; + + paddr = imsic_cfg.msi[cpu].base_addr + imsic_cfg.msi[cpu].offset + + guest_offset; + +#ifdef IMSIC_DEBUG +printk (XENLOG_DEBUG +"%s: %pv: ga(%#" PRIpaddr") -> pa(%#" PRIpaddr"), cpu(%u), " +"guest_file_id(%u) base_addr(%#" PRIpaddr") offset(%#lx)\n" , + __func__, v, gaddr, paddr, cpu, vsfile_id, + imsic_cfg.msi[cpu].base_addr, imsic_cfg.msi[cpu].offset); +#endif + + res =map_regions_p2mt (d,gaddr_to_gfn (gaddr), +PFN_DOWN (IMSIC_MMIO_PAGE_SZ ),maddr_to_mfn (paddr), +arch_dt_passthrough_p2m_type ()); +if ( res ) +dprintk (XENLOG_ERR , +"%s: Failed to map %#" PRIpaddr" to the guest at %#" PRIpaddr"\n" , + __func__, paddr, gaddr); + +return res; } int cf_check vcpu_imsic_init(struct vcpu *v)
Signature · 1 line
2.55.0
PATCH v2 38/39 xen/riscv: implement continue_new_vcpu()
In reply to Oleksii Kurochkocontinue_new_vcpu() is the arch hook invoked the first time a freshly created vCPU is scheduled. Implement both cases it has to cover:
- for the idle vCPU, switch to its own stack and jump to idle_loop();
- for a guest vCPU, restore hstatus and enter the guest through the new return_to_new_vcpu() path in entry.S, which loads sepc, passes the hart id in a0 and the DTB address in a1 as expected by the RISC-V boot protocol, sets sstatus.SPP and executes sret.
Interrupts have to stay disabled across the restore. The trap entry logic implicitly clears hstatus.SPV, so an interrupt taken between the write of hstatus and sret would make sret return to HS-mode instead of VS-mode, and restoring SPV afterwards is non-trivial. Instead interrupts are simply kept off and sstatus.SPIE is set, so that SIE is restored from SPIE once sret has been executed. Also, it follows what hardware will do with real CPU which is also started with interrupts disabled.
Introduce get_cpu_info() and reset_stack_and_jump() in asm/current.h, needed by the above. get_cpu_info() is a macro rather than a static inline because asm/current.h is pulled in by <xen/percpu.h> before this_cpu() is defined and before <xen/sched.h> completes struct vcpu.
idle_loop() is added as a stub on purpose; its real implementation will come separately later.
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/domain.c | 44 +++++++++++++++++++++++++++- xen/arch/riscv/entry.S | 23 +++++++++++++++ xen/arch/riscv/include/asm/current.h | 4 +++ 3 files changed, 70 insertions(+), 1 deletion(-)
xen/arch/riscv/domain.c +43 -1
@@ -8,10 +8,13 @@#include <xen/smp.h> #include <xen/vmap.h> +#include <asm/aia.h> +#include <asm/aplic.h> #include <asm/bitops.h> #include <asm/cpufeature.h> #include <asm/csr.h> #include <asm/current.h> +#include <asm/imsic.h> #include <asm/intc.h> #include <asm/mmio.h> #include <asm/riscv_encoding.h>
@@ -140,9 +143,43 @@ static void vcpu_csr_init(struct vcpu *v) v->arch.hie =MIP_SGEIP ; } +static void schedule_tail (struct vcpu *prev); +static void noreturnidle_loop (void ); +void noreturnreturn_to_new_vcpu (void ); +static void continue_new_vcpu (struct vcpu *prev) { -BUG_ON ("unimplemented\n" ); +schedule_tail (prev); + +if (is_idle_vcpu (current) ) +reset_stack_and_jump (idle_loop); +else + { +/* +* During a context switch to a new vCPU, interrupts must be disabled +* to guarantee that the vCPU's CSR state can be safely restored into +* the hart without being clobbered by an interrupt trap. +* +* For example, when return_to_new_vcpu() finishes, it executes sret. +* At that point, the hart checks hstatus.SPV=1 and sstatus.SPP=1 in +* order to return from HS-mode into VS-mode. If an interrupt were to +* arrive before sret, the trap entry logic would implicitly clear +* hstatus.SPV to 0. Correctly restoring it afterwards is non-trivial, +* and if left as 0, sret would incorrectly return to HS-mode instead +* of VS-mode. +* +* To avoid this, interrupts are kept disabled during the restore. +* Additionally, setting sstatus.SPIE=1 ensures that after sret is +* executed (as sstatus.SIE will be loaded from SPIE), HS-mode will +* continue to receive interrupts normally. +*/ +local_irq_disable (); +csr_set (CSR_SSTATUS ,SSTATUS_SPIE ); + +csr_write (CSR_HSTATUS ,vcpu_guest_cpu_user_regs (current)->hstatus); + +reset_stack_and_jump (return_to_new_vcpu); + } }int arch_vcpu_create (struct vcpu *v)
@@ -551,3 +588,8 @@ static void __init __maybe_unused build_assertions(void)*/ BUILD_BUG_ON (offsetof(struct cpu_info , guest_cpu_user_regs)); } + +static void noreturnidle_loop (void ) +{ +BUG_ON ("unimplemented" ); +}
xen/arch/riscv/entry.S +23 -0
@@ -143,3 +143,26 @@ FUNC(__context_switch) ret END(__context_switch) + +/* t0 is used as a temporary reg and is clobbered to oblivion */ +FUNC(return_to_new_vcpu) + /* Swap tp with sscratch */ + csrrw tp, CSR_SSCRATCH, tp + + /* Set vCPU registers */ + REG_L t0, CPU_USER_REGS_SEPC(sp) + csrw sepc, t0 + + /* Hartid goes to a0 */ + REG_L a0, CPU_USER_REGS_A0(sp) + + /* DTB goes to a1 */ + REG_L a1, CPU_USER_REGS_A1(sp) + + /* Set guest mode to supervisor */ + li t0, SSTATUS_SPP + csrs CSR_SSTATUS, t0 + + /* Enter guest */ + sret +END(return_to_new_vcpu)
xen/arch/riscv/include/asm/current.h +4 -0
@@ -47,6 +47,8 @@ DECLARE_PER_CPU(struct vcpu *, curr_vcpu);#define set_current (vcpu) do { current = (vcpu); } while (0)#define get_cpu_current (cpu) per_cpu(curr_vcpu, cpu) +#define get_cpu_info () (current->arch.cpu_info) +#define guest_cpu_user_regs () ({ BUG_ON("unimplemented"); NULL; })#define vcpu_guest_cpu_user_regs (vcpu) \ (&(vcpu)->arch.cpu_info->guest_cpu_user_regs)
@@ -58,6 +60,8 @@ DECLARE_PER_CPU(struct vcpu *, curr_vcpu);unreachable (); \ } while ( false ) +#define reset_stack_and_jump (fn) switch_stack_and_jump(get_cpu_info(), fn) +#define get_per_cpu_offset () __per_cpu_offset[smp_processor_id()]#endif /* __ASSEMBLER__ */
Signature · 1 line
2.55.0
PATCH v2 39/39 xen/riscv: introduce IMSIC h/w interrupt file attaching to vcpu
In reply to Oleksii KurochkoIntroduce imsic_vsfile_attach() to initialize the AIA-related state needed for a vCPU to have a working guest interrupt file.
A guest (VS) interrupt file must be mapped to one of a pCPU's hardware interrupt files (if they exist), so the pCPU a vCPU will actually run on needs to be known first. arch_vcpu_create() is therefore not a suitable place to call vcpu_aia_init(), since the pCPU assigned to a vCPU can still change before it is first scheduled. To avoid reassigning the VS interrupt file id and remapping it to a different pCPU's hardware interrupt file, imsic_vsfile_attach() is called from a later point in the scheduling path (e.g. continue_new_vcpu()). Since it will end up being called from a non-__init context, it is not itself marked __init.
Introduce imsic_update_state() to update a vCPU's guest IMSIC state (the guest interrupt file id and the pCPU whose hardware interrupt file it is mapped to) as a single consistent unit. This state can be read concurrently, e.g. by a future helper that checks whether a vCPU has a pending IMSIC interrupt, though no such consumer exists yet at this stage, so it is protected by a lock.
---
Changes in v2:
- Update vcpu_aia_init() to catch sw interrupt file and update some debug messages in it.
- Add vgein_release() if IMSIC h/w mapping failed.
- imsic_update_state(): store v->processor rather than cpuid_to_hartid(), as ->vsfile_cpu is consumed as a Xen CPU id (aplic_hart_field(), cpumask_of()) and its NR_CPUS sentinel lives in that numbering space.
- Drop parantethis aroud guest_file_id ? ... in imsic_update_state().
- Rename vcpu_aia_init to imsic_vsfile_attach() and move the code to imsic.c.
---
--- xen/arch/riscv/domain.c | 2 + xen/arch/riscv/imsic.c | 146 +++++++++++++++++++++++------ xen/arch/riscv/include/asm/imsic.h | 2 + 3 files changed, 121 insertions(+), 29 deletions(-)
xen/arch/riscv/domain.c +2 -0
@@ -155,6 +155,8 @@ static void continue_new_vcpu(struct vcpu *prev)reset_stack_and_jump (idle_loop); else { +imsic_vsfile_attach (current); +/* * During a context switch to a new vCPU, interrupts must be disabled * to guarantee that the vCPU's CSR state can be safely restored into
xen/arch/riscv/imsic.c +117 -29
189 lines not on this page · raw message
xen/arch/riscv/include/asm/imsic.h +2 -0
@@ -125,4 +125,6 @@ int imsic_map_guest_file(struct vcpu *v, unsigned int vsfile_id);void imsic_migrate_vcpu (struct vcpu *v); +void imsic_vsfile_attach (struct vcpu *v); +#endif /* ASM_RISCV_IMSIC_H */
Signature · 1 line
2.55.0
PATCH v2 36/39 xen/riscv: wake up a descheduled vCPU on a guest external interrupt
In reply to Oleksii KurochkoWhile a vCPU is running, MSIs written to its h/w IMSIC guest interrupt file are delivered straight to VS-mode. Once the vCPU is descheduled nobody observes that file anymore, so a guest blocked on such an interrupt would stay blocked until some unrelated event happens to schedule it again.
Let Xen observe the file in that window: on deschedule set the vCPU's bit in HGEIE, which turns an interrupt pending in its VS-file into an HS-level SGEI, and clear the bit again on schedule-in. HGEIP only reports a file number, so to get from it back to a vCPU keep an owners[] map per pCPU, filled by vgein_{assign,release} alongside the VGEIN bitmap, and kick the vCPU it points at.
v->arch.hie is only initialized here and is written to the CSR later, on the context switch to the vCPU.
vgein_release() still has no caller: a vCPU going away has to both free its VGEIN slot and drop the owners[] entry, but there is no vCPU teardown path to hook it into yet. vgein_deinit() only covers a pCPU going offline.
---
Changes in v2:
- New patch.
---
--- xen/arch/riscv/aia.c | 52 +++++++++++++++++++++++++-- xen/arch/riscv/domain.c | 3 ++ xen/arch/riscv/imsic.c | 55 ++++++++++++++++++++++++++++- xen/arch/riscv/include/asm/aia.h | 2 ++ xen/arch/riscv/include/asm/domain.h | 1 + xen/arch/riscv/traps.c | 7 +++- 6 files changed, 115 insertions(+), 5 deletions(-)
xen/arch/riscv/aia.c +49 -3
@@ -18,6 +18,13 @@ struct vgein_ctrl {/* The least-significant bits are implemented first, apart from bit 0 */ unsigned long bmp;spinlock_t lock; +/* +* Guest interrupt file IDs run from 1 to geilen inclusive (0 means that +* no guest external interrupt source is selected), and geilen can never +* exceed BITS_PER_LONG - 1, so indexing this array by the ID directly +* always fits. +*/ +struct vcpu *owners[BITS_PER_LONG ];unsigned int geilen; };
@@ -62,23 +69,25 @@ static int cf_check cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu) {unsigned int cpu = (unsigned long )hcpu; -int rc =0 ;switch ( action ) {case CPU_STARTING : - rc =vgein_init (); + { +int rc =vgein_init (); +if ( rc )printk (XENLOG_ERR "AIA: failed to init vgein for CPU%u: %d\n" , cpu, rc);break ; + }case CPU_DYING :vgein_deinit ();break ; } -return notifier_from_errno (rc); +return NOTIFY_DONE ; }static struct notifier_block cpu_nfb = {
@@ -138,7 +147,10 @@ unsigned int vgein_assign(struct vcpu *v)if ( vgein_id > vgein->geilen ) vgein_id =0 ;else + {__set_bit (vgein_id, bmp); + vgein->owners[vgein_id] = v; + }spin_unlock_irqrestore (&vgein->lock, flags);
@@ -161,6 +173,7 @@ void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu)spin_lock_irqsave (&vgein->lock, flags);if ( !__test_and_clear_bit (vgein_id, &vgein->bmp) )ASSERT_UNREACHABLE (); + vgein->owners[vgein_id] =NULL ;spin_unlock_irqrestore (&vgein->lock, flags);#ifdef VGEIN_DEBUG
@@ -168,3 +181,36 @@ void vgein_release(struct vcpu *v, unsigned int vgein_id, unsigned int cpu) __func__, v, vgein_id, cpu, vgein->bmp);#endif } + +void hgei_interrupt (void ) +{ +unsigned long hgei_mask, flags; +struct vgein_ctrl *vgein = &this_cpu (vgein); + + hgei_mask =csr_read (CSR_HGEIP ) &csr_read (CSR_HGEIE ); +csr_clear (CSR_HGEIE , hgei_mask); + +spin_lock_irqsave (&vgein->lock, flags); + + for_each_set_bit ( guest_file_id, hgei_mask ) + { +/* +* guest_file_id shouldn't be zero, as it will indicate that no +* guest external interrupt source is selected for VS-level external +* interrupts. +*/ +ASSERT (guest_file_id); + +if ( vgein->owners[guest_file_id] ) + { +#ifdef VGEIN_DEBUG +gprintk (XENLOG_DEBUG ,"%s: kick ->%pv, hgei_mask(%#lx)\n" , + __func__, vgein->owners[guest_file_id], hgei_mask); +#endif + +vcpu_kick (vgein->owners[guest_file_id]); + } + } + +spin_unlock_irqrestore (&vgein->lock, flags); +}
xen/arch/riscv/domain.c +3 -0
@@ -136,6 +136,8 @@ static void vcpu_csr_init(struct vcpu *v) v->arch.hstateen0 = (hstateen0 & csr_masks.hstateen0) | csr_masks.ro_one.hstateen0; } + + v->arch.hie =MIP_SGEIP ; }static void continue_new_vcpu (struct vcpu *prev)
@@ -398,6 +400,7 @@ static void restore_csr_regs(struct vcpu *vcpu)csr_write (CSR_HEDELEG , vcpu->arch.hedeleg);csr_write (CSR_HIDELEG , vcpu->arch.hideleg);csr_write (CSR_HVIP , vcpu->arch.hvip); +csr_write (CSR_HIE , vcpu->arch.hie);csr_write64 (CSR_HENVCFG , vcpu->arch.henvcfg);csr_write (CSR_HCOUNTEREN , vcpu->arch.hcounteren);csr_write64 (CSR_HTIMEDELTA , vcpu->arch.htimedelta);
xen/arch/riscv/imsic.c +54 -1
84 lines not on this page · raw message
xen/arch/riscv/include/asm/aia.h +2 -0
@@ -12,4 +12,6 @@ void aia_init(void);unsigned int vgein_assign (struct vcpu *v);void vgein_release (struct vcpu *v,unsigned int vgein_id,unsigned int cpu); +void hgei_interrupt (void ); +#endif /* RISCV_AIA_H */
xen/arch/riscv/include/asm/domain.h +1 -0
@@ -72,6 +72,7 @@ struct arch_vcpu {register_t hvip;uint64_t hviprio1;uint64_t hviprio2; +register_t hie;register_t vsatp;register_t vscause;
xen/arch/riscv/traps.c +6 -1
@@ -12,9 +12,10 @@#include <xen/sched.h> #include <xen/softirq.h> -#include <asm/extable.h> +#include <asm/aia.h> #include <asm/cpufeature.h> #include <asm/emulate.h> +#include <asm/extable.h> #include <asm/intc.h> #include <asm/processor.h> #include <asm/riscv_encoding.h>
@@ -273,6 +274,10 @@ void do_trap(struct cpu_user_regs *cpu_regs)timer_interrupt ();break ; +case IRQ_S_GEXT : +hgei_interrupt (); +break ; +default : intr_handled = false;break ;
Signature · 1 line
2.55.0
Re: [PATCH v2 04/39] xen/riscv: introduce csr_read64()
In reply to Oleksii KurochkoQuoted 16 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/csr.h +8
-0@@ -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
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@@ -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
Re: [PATCH v2 01/39] xen/riscv: drop pregs from struct cpu_user_regs
In reply to Oleksii KurochkoQuoted 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]>
Re: [PATCH v2 02/39] xen/riscv: drop bug.h's duplicate instruction length helpers
In reply to Oleksii KurochkoQuoted 8 lines · Oleksii Kurochko
asm/riscv_encoding.halready providesINSN_16BIT_MASKandINSN_LEN(), andemulate.cuses them, so the tree carried two spellings of the same thing which could drift apart.COMPRESSED_INSN_MASKnever had a user.No functional change.
[...]
Signature · 1 line
Baptiste Le Duc <[email protected]>
Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL
In reply to Oleksii KurochkoQuoted 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]>
Re: [PATCH v2 05/39] xen/riscv: request a G-stage flush on vmenter when VMIDs are disabled
In reply to Oleksii KurochkoQuoted 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")Signed-off-by Oleksii Kurochko <[email protected]>
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]>
Re: [PATCH v2 06/39] xen/riscv: use UINT64_MAX to disable the VS-timer
In reply to Oleksii KurochkoQuoted 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 passingULONG_MAX(0xffffffffthere) writes all ones to the low half and zero to the high half, leaving the CSR at0x00000000ffffffffrather 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]>
Jan Beulich
Acked-byRe: [PATCH v2 01/39] xen/riscv: drop pregs from struct cpu_user_regs
In reply to Baptiste Le DucQuoted 6 lines · Baptiste Le Duc
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.Reviewed-by Baptiste Le Duc <[email protected]>
Re: [PATCH v2 02/39] xen/riscv: drop bug.h's duplicate instruction length helpers
In reply to Oleksii KurochkoQuoted 7 lines · Oleksii Kurochko
asm/riscv_encoding.halready providesINSN_16BIT_MASKandINSN_LEN(), andemulate.cuses them, so the tree carried two spellings of the same thing which could drift apart.COMPRESSED_INSN_MASKnever had a user.No functional change.
Signed-off-by Oleksii Kurochko <[email protected]>
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
Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL
In reply to Baptiste Le DucQuoted 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()inemulate.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 inemulate.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
Re: [PATCH v2 04/39] xen/riscv: introduce csr_read64()
In reply to Oleksii KurochkoQuoted 55 lines · Oleksii Kurochko
Quoted 30 lines · Andrew Cooper
Quoted 16 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/csr.h +8
-0@@ -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
Re: [PATCH v2 06/39] xen/riscv: use UINT64_MAX to disable the VS-timer
In reply to Oleksii KurochkoQuoted 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 passingULONG_MAX(0xffffffffthere) writes all ones to the low half and zero to the high half, leaving the CSR at0x00000000ffffffffrather 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 toULONG_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
Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL
In reply to Baptiste Le DucQuoted 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()inemulate.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 inemulate.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
Re: [PATCH v2 05/39] xen/riscv: request a G-stage flush on vmenter when VMIDs are disabled
In reply to Baptiste Le DucQuoted 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")Signed-off-by Oleksii Kurochko <[email protected]>FWIW this comment and
p2m_handle_vmenter()itself get dropped a few patches later in "implement vCPU context switching", which folds the VMID claim intop2m_ctxt_switch_to(). The fix survives there via theneed_flushcheck. 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
Re: [PATCH v2 06/39] xen/riscv: use UINT64_MAX to disable the VS-timer
In reply to Jan BeulichQuoted 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 passingULONG_MAX(0xffffffffthere) writes all ones to the low half and zero to the high half, leaving the CSR at0x00000000ffffffffrather 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 toULONG_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
Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL
In reply to Baptiste Le DucQuoted 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()inemulate.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 inemulate.c, needs...").
Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL
In reply to Oleksii KurochkoQuoted 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
-1v->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
Re: [PATCH v2 07/39] xen/riscv: add missing APLIC register offsets, masks to asm/aplic.h
In reply to Oleksii KurochkoQuoted 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]>
Re: [PATCH v2 08/39] xen/riscv: introduce device-agnostic MMIO emulation dispatch
In reply to Oleksii KurochkoQuoted 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
Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/Makefile +1
-0@@ -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.oxen/arch/riscv/domain.c +3
-0@@ -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@@ -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@@ -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@@ -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]>
Jan Beulich
Acked-byRe: [PATCH v2 07/39] xen/riscv: add missing APLIC register offsets, masks to asm/aplic.h
In reply to Baptiste Le DucQuoted 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
[...]
Reviewed-by Baptiste Le Duc <[email protected]>
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
Re: [PATCH v2 02/39] xen/riscv: drop bug.h's duplicate instruction length helpers
In reply to Jan BeulichQuoted 11 lines · Jan Beulich
Quoted 7 lines · Oleksii Kurochko
asm/riscv_encoding.halready providesINSN_16BIT_MASKandINSN_LEN(), andemulate.cuses them, so the tree carried two spellings of the same thing which could drift apart.COMPRESSED_INSN_MASKnever had a user.No functional change.
Signed-off-by Oleksii Kurochko <[email protected]>As I'm happy to see the duplication go away:
Acked-by Jan Beulich <[email protected]>
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_MASK0x3
#defineINSN_32BIT_MASK0x1care 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
Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL
In reply to Jan BeulichQuoted 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
Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation
In reply to Oleksii KurochkoQuoted 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.Co-developed-by Romain Caritey <[email protected]>Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/aplic-priv.h +3
-0@@ -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@@ -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@@ -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@@ -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@@ -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@@ -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]>
Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation
In reply to Oleksii KurochkoQuoted 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.Co-developed-by Romain Caritey <[email protected]>Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/aplic-priv.h +3
-0@@ -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@@ -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@@ -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@@ -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@@ -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@@ -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]>
Re: [PATCH v2 02/39] xen/riscv: drop bug.h's duplicate instruction length helpers
In reply to Oleksii KurochkoQuoted 8 lines · Oleksii Kurochko
Quoted 6 lines · Jan Beulich
And then
#define
INSN_16BIT_MASK0x3
#defineINSN_32BIT_MASK0x1care 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_LENand just return 0 as suggested above.
Suitably commented upon that would certainly be okay with me.
Jan
Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL
In reply to Oleksii KurochkoQuoted 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. Theswitch()
* deliberately has no default case, so that adding a newdomain_type(a
* 128-bit one, in particular) fails to build until this mapping is
updated.
*/
static unsigned intdomain_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 iscreated. */
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
Re: [PATCH v2 07/39] xen/riscv: add missing APLIC register offsets, masks to asm/aplic.h
In reply to Jan BeulichQuoted 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
Reviewed-by Baptiste Le Duc <[email protected]>Acked-by Jan Beulich <[email protected]>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
Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL
In reply to Jan BeulichQuoted 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. Theswitch()
* deliberately has no default case, so that adding a newdomain_type(a
* 128-bit one, in particular) fails to build until this mapping is
updated.
*/
static unsigned intdomain_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 iscreated. */
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 underneathvcpu_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
Re: [PATCH v2 02/39] xen/riscv: drop bug.h's duplicate instruction length helpers
In reply to Jan BeulichQuoted 17 lines · Jan Beulich
Quoted 8 lines · Oleksii Kurochko
Quoted 6 lines · Jan Beulich
And then
#define
INSN_16BIT_MASK0x3
#defineINSN_32BIT_MASK0x1care 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_LENand 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
Re: [PATCH v2 07/39] xen/riscv: add missing APLIC register offsets, masks to asm/aplic.h
In reply to Jan BeulichQuoted 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
[...]
Reviewed-by Baptiste Le Duc <[email protected]>Acked-by Jan Beulich <[email protected]>
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
Re: [PATCH v2 02/39] xen/riscv: drop bug.h's duplicate instruction length helpers
In reply to Oleksii KurochkoQuoted 38 lines · Oleksii Kurochko
Quoted 17 lines · Jan Beulich
Quoted 8 lines · Oleksii Kurochko
Quoted 6 lines · Jan Beulich
And then
#define
INSN_16BIT_MASK0x3
#defineINSN_32BIT_MASK0x1care 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 0x1cQuoted 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 (exceptINSN_IS_32BIT()andINSN_IS_16BIT()) ininsn_fetch_faulted()introduced later in this patch series:di->insn = htinst | INSN_16BIT_MASK;
INSN_32BIT_MASK- is used only insideINSN_IS_32BIT().And
INSN_IS_32BIT()andINSN_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. */
#defineINSN_IS_16BIT(insn)(((insn) &0x3) !=0x3)
#defineINSN_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 */
#defineINSN_LEN_1_0_MASK0x3/* Bits [1:0] for 16-bit vsQuoted 1 line
=32-bit */
#define
INSN_LEN_4_2_MASK0x1c/* Bits [4:2] for 32-bit vsQuoted 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_LENand 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
Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL
In reply to Oleksii KurochkoQuoted 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 iscreated. */
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 underneathvcpu_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)afterset_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()whered->typeis 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
Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching
In reply to Oleksii KurochkoQuoted 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@@ -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
Re: [PATCH v2 03/39] xen/riscv: set the guest's XLEN explicitly in hstatus.VSXL
In reply to Jan BeulichQuoted 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 iscreated. */
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 underneathvcpu_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)afterset_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
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 iscreated. */
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 underneathvcpu_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)afterset_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
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 iscreated. */
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 underneathvcpu_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)afterset_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 theconstruct_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
Re: [PATCH v2 08/39] xen/riscv: introduce device-agnostic MMIO emulation dispatch
In reply to Baptiste Le DucQuoted 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
Re: [PATCH v2 11/39] xen/riscv: add helper to check APLIC MSI mode
In reply to Oleksii KurochkoQuoted 1 line · Oleksii Kurochko
Use convient helper instead of open-coding the things.
Signature · 1 line
Baptiste Le Duc <[email protected]>
Re: [PATCH v2 10/39] xen/riscv: build the target hart index via aplic_hart_field()
In reply to Oleksii KurochkoQuoted 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]>
Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching
In reply to Oleksii KurochkoAs 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_contexttoasm-offsets.cfor use by__context_switch().henvcfg and htimedelta are 64-bit on both RV32 and RV64, so store them as
uint64_tand use csr_{read,write}64() instead of open-coding accesses to the high halves.A hart which drops out of a domain's
dirty_cpumaskstops being a target ofp2m_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 fromcheck_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, andvmid_flush_hart()runs either fromschedule_tail(), ahead ofctxt_switch_to(), or from the wrap path ofvmid_handle_vmenter()itself. A P2M change on another hart doesn't invalidate it either, asp2m_tlb_flush()drops the stale entries directly withsbi_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
Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/domain.c +47
-0@@ -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]>
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
previousbut I think the_fromalone 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
Re: [PATCH v2 13/39] xen/riscv: save and restore AIA state on vCPU context switch
In reply to Oleksii KurochkoQuoted 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]>
Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching
In reply to Jan BeulichQuoted 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
previousbut I think the_fromalone 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
Re: [PATCH v2 14/39] xen/riscv: introduce vintc_ctxt_switch_{from,to}()
In reply to Oleksii KurochkoQuoted 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]>
Re: [PATCH v2 15/39] xen/riscv: add IMSIC vCPU context switch handlers
In reply to Oleksii KurochkoQuoted 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 getcf_check.Co-developed-by Romain Caritey <[email protected]>Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/imsic.c +23
-0@@ -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@@ -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
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]>
Oleksii Kurochko
AppliedRe: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation
In reply to Baptiste Le DucQuoted 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
guestwording:( 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
gandh.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 longaplic_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_addrcorresponds 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_indextoo, 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@@ -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 0x0ffcxen/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@@ -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
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_idit 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
Re: [PATCH v2 09/39] xen/riscv: implement virtual APLIC MMIO emulation
In reply to Baptiste Le DucQuoted 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_WMASKincludesAPLIC_DOMAINCFG_DM, so
the guest can clear DM through this write. Butaplic.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
Re: [PATCH v2 10/39] xen/riscv: build the target hart index via aplic_hart_field()
In reply to Baptiste Le DucQuoted 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;[...]
Reviewed-by Baptiste Le Duc <[email protected]>
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
Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching
In reply to Baptiste Le DucQuoted 8 lines · Baptiste Le Duc
As I understand it, a generation wrap doesn't retire a single VMID, it resets
next_vmidto 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_contexttoasm-offsets.cfor use by__context_switch().henvcfg and htimedelta are 64-bit on both RV32 and RV64, so store them as
uint64_tand use csr_{read,write}64() instead of open-coding accesses to the high halves.A hart which drops out of a domain's
dirty_cpumaskstops being a target ofp2m_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 fromcheck_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, andvmid_flush_hart()runs either fromschedule_tail(), ahead ofctxt_switch_to(), or from the wrap path ofvmid_handle_vmenter()itself. A P2M change on another hart doesn't invalidate it either, asp2m_tlb_flush()drops the stale entries directly withsbi_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
Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/domain.c +47
-0@@ -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
previousbut I think the_fromalone 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
Re: [PATCH v2 13/39] xen/riscv: save and restore AIA state on vCPU context switch
In reply to Baptiste Le DucQuoted 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
@@ -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
@@ -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
Re: [PATCH v2 14/39] xen/riscv: introduce vintc_ctxt_switch_{from,to}()
In reply to Baptiste Le DucQuoted 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 structvintc_opsvintc_ops= {
.vcpu_init =vcpu_imsic_init,
.vcpu_deinit =vcpu_imsic_deinit,
};
Quoted 4 lines
So
ops->ctxt_switch_from(v)orops->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
Re: [PATCH v2 15/39] xen/riscv: add IMSIC vCPU context switch handlers
In reply to Baptiste Le DucQuoted 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 getcf_check.Co-developed-by Romain Caritey <[email protected]>Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/imsic.c +23
-0@@ -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@@ -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@@ -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
Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching
In reply to Oleksii KurochkoI'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
@@ -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 (¤t->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 (¤t->dirty_cpu, cpu);ctxt_switch_to (current); -write_atomic (&prev->dirty_cpu,VCPU_CPU_CLEAN ); +write_atomic (¤t->dirty_cpu, cpu); current->arch.last_cpu = cpu;
xen/arch/riscv/p2m.c +9 -10
@@ -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
Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching
In reply to Oleksii KurochkoQuoted 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_vmidto 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 VMIDWe 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_gvmaonly 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_vmidis 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_contexttoasm-offsets.cfor use by__context_switch().henvcfg and htimedelta are 64-bit on both RV32 and RV64, so store them as
uint64_tand use csr_{read,write}64() instead of open-coding accesses to the high halves.A hart which drops out of a domain's
dirty_cpumaskstops being a target ofp2m_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 fromcheck_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, andvmid_flush_hart()runs either fromschedule_tail(), ahead ofctxt_switch_to(), or from the wrap path ofvmid_handle_vmenter()itself. A P2M change on another hart doesn't invalidate it either, asp2m_tlb_flush()drops the stale entries directly withsbi_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
Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/domain.c +47
-0@@ -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
previousbut I think the_fromalone 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
Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields
In reply to Oleksii KurochkoQuoted 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_FIXUPentries.Introduce a generic
ASM_EXTABLE_RAW()helper to describe entries with a handler type and associated data. ReimplementASM_EXTABLE()in terms of it usingEX_TYPE_FIXUPfor compatibility.Add
EX_TYPE_TRAP_INFOto 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 structtrap_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.
Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/extable.c +68
-2@@ -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@@ -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
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@@ -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]>
Re: [PATCH v2 17/39] xen/riscv: decouple INSN_PSEUDO_VS_* from the hypervisor's XLEN
In reply to Oleksii KurochkoQuoted 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.handasm/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.
Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/include/asm/riscv_encoding.h +1
-5@@ -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]>
Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest
In reply to Oleksii KurochkoQuoted 7 lines
Some traps taken by Xen on behalf of a guest can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead: the access faults which
handle_guest_page_fault()injects for a fault that can never become an emulated access, and, later on, a fault taken by the hlv/hlvx sequences ofriscv_read_guest()while accessing guest memory on a vCPU's behalf.
Access faults from handle_guest_page_fault() aren't "taken by Xen on behalf of a guest" as those are guest-page faults taken directly from the guest's own execution. Xen just decides they can't be emulated and reflects them back as access faults. Only the hlv/hlvx case is Xen trapping on the guest's behalf (Xen itself executes the faulting access). Conflating the two under one description makes the paragraph confusing.
Suggest splitting into two:
Two kinds of traps can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead:
- Traps Xen takes on the guest's behalf: the hlv/hlvx sequences riscv_read_guest() uses to access guest memory.
- Access faults handle_guest_page_fault() injects for a guest-page fault that can never become an emulated access.
Quoted 32 lines
Implement
trap_redirect(), until now aBUG_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.Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/include/asm/riscv_encoding.h +0
-0
xen/arch/riscv/include/asm/riscv_encoding.h line 116
Quoted 8 lines
xen/arch/riscv/include/asm/riscv_encoding.h +5
-0@@ -109,6 +109,12 @@#define SIP_SSIP MIP_SSIP#define SIP_STIP MIP_STIP +/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */ +#define STVEC_MODE_MASK _UL(0x3) +#define STVEC_MODE_DIRECT _UL(0x0) +#define STVEC_MODE_VECTORED _UL(0x1) +#define STVEC_BASE_MASK (~STVEC_MODE_MASK)
Nit: STVEC_MODE_DIRECT and STVEC_MODE_VECTORED aren't used anywhere in this patch (only STVEC_BASE_MASK is). Either use them where you decide exceptions always target BASE regardless of MODE, or drop them until a patch that needs them.
Signature · 1 line
Baptiste Le Duc <[email protected]>
Re: [PATCH v2 20/39] xen/riscv: detect Shtvala
In reply to Oleksii KurochkoQuoted 6 lines
Shtvala says that htval is written with the faulting guest physical address on a guest-page fault. The H extension itself allows an implementation to write htval with either that address or with zero, so where the extension is absent a zero htval cannot be told apart from a genuine fault on guest physical address 0-3.
Quoted 7 lines
It is not offered to guests. Shtvala describes the HS-mode trap interface, which a VS-mode guest never sees, and the H extension it belongs to is already withheld from guests. Its guest-facing counterpart is a separate extension, Shvstvala.
Signed-off-by Oleksii Kurochko <[email protected]>
I thought this commit message is not very clear. Here is a more direct suggestion:
``` The H extension allows htval, on a guest-page fault, to be written with either the faulting guest physical address or zero. Shtvala extension removes the ambiguity of this zero-write by guaranteeing that htval is written with the faulting guest physical address in every circumstance permitted by the ISA. Not offered to guests: Shtvala describes htval, an HS-mode-only trap register a VS-mode guest never touches and the H extension it belongs to is already hidden from guests. The guest-visible equivalent is a separate extension, Shvstvala, covering vstval instead. ```
Btw, I saw Linux has Documentation/devicetree/bindings/riscv/extensions.yaml which describes all of the extensions supported, don't you think it would be useful to have the same in docs/misc/devicetree/...?
Signature · 1 line
Baptiste Le Duc <[email protected]>
Re: [PATCH v2 18/39] xen/riscv: add guest page fault handling stub
In reply to Oleksii KurochkoQuoted 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()andtrap_redirect(), areBUG_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 todo_unexpected_trap()anddie(). Implementing the helpers is left to later patches.Signed-off-by Oleksii Kurochko <[email protected]>
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]>
Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields
In reply to Baptiste Le DucQuoted 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
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.hComment 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
Re: [PATCH v2 12/39] xen/riscv: implement vCPU context switching
In reply to Jan BeulichQuoted 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_vmidto 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 VMIDWe 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_gvmaonly 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_vmidis 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_contexttoasm-offsets.cfor use by__context_switch().henvcfg and htimedelta are 64-bit on both RV32 and RV64, so store them as
uint64_tand use csr_{read,write}64() instead of open-coding accesses to the high halves.A hart which drops out of a domain's
dirty_cpumaskstops being a target ofp2m_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 fromcheck_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, andvmid_flush_hart()runs either fromschedule_tail(), ahead ofctxt_switch_to(), or from the wrap path ofvmid_handle_vmenter()itself. A P2M change on another hart doesn't invalidate it either, asp2m_tlb_flush()drops the stale entries directly withsbi_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
Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/domain.c +47
-0@@ -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
previousbut I think the_fromalone 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
Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields
In reply to Baptiste Le DucQuoted 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_FIXUPentries.Introduce a generic
ASM_EXTABLE_RAW()helper to describe entries with a handler type and associated data. ReimplementASM_EXTABLE()in terms of it usingEX_TYPE_FIXUPfor compatibility.Add
EX_TYPE_TRAP_INFOto 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 structtrap_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.
Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/extable.c +68
-2@@ -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@@ -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
-0xen/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 onlinux/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@@ -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
Re: [PATCH v2 17/39] xen/riscv: decouple INSN_PSEUDO_VS_* from the hypervisor's XLEN
In reply to Baptiste Le DucQuoted 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.handasm/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.
Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/include/asm/riscv_encoding.h +3
-7@@ -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
Re: [PATCH v2 18/39] xen/riscv: add guest page fault handling stub
In reply to Baptiste Le DucQuoted 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()andtrap_redirect(), areBUG_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 todo_unexpected_trap()anddie(). Implementing the helpers is left to later patches.Signed-off-by Oleksii Kurochko <[email protected]>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
Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest
In reply to Baptiste Le DucQuoted 15 lines · Baptiste Le Duc
Quoted 7 lines
Some traps taken by Xen on behalf of a guest can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead: the access faults which
handle_guest_page_fault()injects for a fault that can never become an emulated access, and, later on, a fault taken by the hlv/hlvx sequences ofriscv_read_guest()while accessing guest memory on a vCPU's behalf.Access faults from
handle_guest_page_fault()aren't "taken by Xen on
behalf of a guest" as those are guest-page faults taken directly from the
guest's own execution. Xen just decides they can't be emulated and
reflects them back as access faults. Only the hlv/hlvx case is Xen
trapping on the guest's behalf (Xen itself executes the faulting access).> Conflating the two under one description makes the paragraph confusing.Suggest splitting into two:
Quoted 7 lines
Two kinds of traps can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead:
- Traps Xen takes on the guest's behalf: the hlv/hlvx sequences
riscv_read_guest()uses to access guest memory.
- Access faultshandle_guest_page_fault()injects for a guest-page fault that can never become an emulated access.
Thanks, I'll update original paragraph with what you suggested.>
Quoted 35 lines
Quoted 35 lines
Implement
trap_redirect(), until now aBUG_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.Signed-off-by Oleksii Kurochko <[email protected]>xen/arch/riscv/include/asm/riscv_encoding.h +0
-0@@ -109,6 +109,12 @@#define SIP_SSIP MIP_SSIP#define SIP_STIP MIP_STIP
Quoted 9 lines
xen/arch/riscv/include/asm/riscv_encoding.h line 116
Quoted 5 lines
xen/arch/riscv/include/asm/riscv_encoding.h +5
-0+/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */ +#define STVEC_MODE_MASK _UL(0x3) +#define STVEC_MODE_DIRECT _UL(0x0) +#define STVEC_MODE_VECTORED _UL(0x1) +#define STVEC_BASE_MASK (~STVEC_MODE_MASK)Nit:
STVEC_MODE_DIRECTandSTVEC_MODE_VECTOREDaren't used anywhere in this patch (onlySTVEC_BASE_MASKis). Either use them where you decide exceptions always target BASE regardless of MODE, or drop them until a patch that needs them.
IMO it is fine to introduce *_DIRECT/VECORED here as they are used implicitly through STVEC_BASE_MASK and thereby it will be better to introduce them here now instead of open-code them and then just update STVEC_BASE_MASK again when *_DIRECT/VECORED will be re-introduced.
Thanks for review.
~ Oleksii
Re: [PATCH v2 20/39] xen/riscv: detect Shtvala
In reply to Baptiste Le DucQuoted 16 lines · Baptiste Le Duc
Quoted 6 lines
Shtvala says that htval is written with the faulting guest physical address on a guest-page fault. The H extension itself allows an implementation to write htval with either that address or with zero, so where the extension is absent a zero htval cannot be told apart from a genuine fault on guest physical address 0-3.
Quoted 7 lines
It is not offered to guests. Shtvala describes the HS-mode trap interface, which a VS-mode guest never sees, and the H extension it belongs to is already withheld from guests. Its guest-facing counterpart is a separate extension, Shvstvala.
Signed-off-by Oleksii Kurochko <[email protected]>I thought this commit message is not very clear. Here is a more direct suggestion:
Quoted 12 lines
``` The H extension allows htval, on a guest-page fault, to be written with either the faulting guest physical address or zero. Shtvala extension removes the ambiguity of this zero-write by guaranteeing that htval is written with the faulting guest physical address in every circumstance permitted by the ISA. Not offered to guests: Shtvala describes htval, an HS-mode-only trap register a VS-mode guest never touches and the H extension it belongs to is already hidden from guests. The guest-visible equivalent is a separate extension, Shvstvala, covering vstval instead. ```
Sounds good to me. I will apply your suggestion.
Quoted 4 lines
Btw, I saw Linux has
Documentation/devicetree/bindings/riscv/extensions.yamlwhich describes all of the extensions supported, don't you think it would be useful to have the same in docs/misc/devicetree/...?
I think it could be useful.
I think also about booting.txt already exitsted in the codebase. Would you be okay with that? I think I will add the section to booting.txt and pointing to riscv_isa_ext[] in cpufeature.c and so we won't miss an update of doc if we will add or remove support of an extension. Does it sound good to you?
~ Oleksii
Re: [PATCH v2 16/39] xen/riscv: extend exception tables with type and data fields
In reply to Oleksii Kurochkoxen/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 structcpu_user_regsis
+ * checked against it at build time (seeregs_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
Re: [PATCH v2 18/39] xen/riscv: add guest page fault handling stub
In reply to Oleksii KurochkoQuoted 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
Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest
In reply to Oleksii Kurochkoxen/arch/riscv/include/asm/riscv_encoding.h line 115
Quoted 10 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/riscv_encoding.h +4
-0@@ -109,6 +109,12 @@#define SIP_SSIP MIP_SSIP#define SIP_STIP MIP_STIP +/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */ +#define STVEC_MODE_MASK _UL(0x3) +#define STVEC_MODE_DIRECT _UL(0x0) +#define STVEC_MODE_VECTORED _UL(0x1)
As on earlier occasions: Do the 0x here actually add any value? There are none ...
xen/arch/riscv/include/asm/riscv_encoding.h line 120
Quoted 5 lines
xen/arch/riscv/include/asm/riscv_encoding.h +2
-0+#define STVEC_BASE_MASK (~STVEC_MODE_MASK) +#define PRV_U _UL(0)#define PRV_S _UL(1)#define PRV_M _UL(3)
... here, for example.
Quoted 43 lines
xen/arch/riscv/traps.c +36
-1@@ -294,5 +294,53 @@ enum mc_disposition arch_do_multicall_call(struct mc_state *state)/* Redirect trap to Guest. */ void trap_redirect (const struct trap_info *trap) { -BUG_ON ("unimplemented" ); +struct cpu_user_regs *regs =vcpu_guest_cpu_user_regs (current); +unsigned long vsstatus =csr_read (CSR_VSSTATUS ); + +/* +* Redirecting a trap makes sense only if the trap was taken from +* virtualized mode, i.e. sret is going to return to VS-mode. +*/ +ASSERT (regs->hstatus &HSTATUS_SPV ); + +/* +* Only synchronous exceptions can be redirected. Interrupts must be +* injected via hvip instead, so that the hardware itself performs +* VS-mode trap entry, respecting vsstatus.SIE and the vectored +* dispatch (BASE + 4 * cause) if vstvec is configured so. +*/ +ASSERT (!(trap->scause &CAUSE_IRQ_FLAG )); + +/* Change Guest SSTATUS.SPP bit */ + vsstatus &= ~SSTATUS_SPP ; +if ( regs->sstatus &SSTATUS_SPP ) + vsstatus |=SSTATUS_SPP ; + +/* Change Guest SSTATUS.SPIE bit */ + vsstatus &= ~SSTATUS_SPIE ; +if ( vsstatus &SSTATUS_SIE ) + vsstatus |=SSTATUS_SPIE ; + +/* Clear Guest SSTATUS.SIE bit */ + vsstatus &= ~SSTATUS_SIE ; + +/* Update Guest SSTATUS */ +csr_write (CSR_VSSTATUS , vsstatus); + +/* Update Guest SCAUSE, STVAL, and SEPC */ +csr_write (CSR_VSCAUSE , trap->scause); +csr_write (CSR_VSTVAL , trap->stval);
xen/arch/riscv/traps.c enum mc_disposition arch_do_multicall_call(struct mc_state *state) · line 342
Quoted 10 lines
xen/arch/riscv/traps.c +10
-0+csr_write (CSR_VSEPC , trap->sepc); + +/* +* Set Guest PC to Guest exception vector. +* +* vstvec's MODE field is not part of the address. Exceptions always +* target BASE regardless of MODE, so mask it off explicitly instead of +* relying on the hardwired zero bit of sepc to drop it. +*/ + regs->sepc =csr_read (CSR_VSTVEC ) &STVEC_BASE_MASK ;
Nit: Given how much the comment talks about MODE, imo using ~STVEC_MODE_MASK here directly (and dropping STVEC_BASE_MASK) might be better.
Jan
Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest
In reply to Oleksii Kurochkoxen/arch/riscv/include/asm/riscv_encoding.h line 115
Quoted 10 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/riscv_encoding.h +4
-0@@ -109,6 +109,12 @@#define SIP_SSIP MIP_SSIP#define SIP_STIP MIP_STIP +/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */ +#define STVEC_MODE_MASK _UL(0x3) +#define STVEC_MODE_DIRECT _UL(0x0) +#define STVEC_MODE_VECTORED _UL(0x1)
As on earlier occasions: Do the 0x here actually add any value? There are none ...
xen/arch/riscv/include/asm/riscv_encoding.h line 120
Quoted 5 lines
xen/arch/riscv/include/asm/riscv_encoding.h +2
-0+#define STVEC_BASE_MASK (~STVEC_MODE_MASK) +#define PRV_U _UL(0)#define PRV_S _UL(1)#define PRV_M _UL(3)
... here, for example.
Quoted 43 lines
xen/arch/riscv/traps.c +36
-1@@ -294,5 +294,53 @@ enum mc_disposition arch_do_multicall_call(struct mc_state *state)/* Redirect trap to Guest. */ void trap_redirect (const struct trap_info *trap) { -BUG_ON ("unimplemented" ); +struct cpu_user_regs *regs =vcpu_guest_cpu_user_regs (current); +unsigned long vsstatus =csr_read (CSR_VSSTATUS ); + +/* +* Redirecting a trap makes sense only if the trap was taken from +* virtualized mode, i.e. sret is going to return to VS-mode. +*/ +ASSERT (regs->hstatus &HSTATUS_SPV ); + +/* +* Only synchronous exceptions can be redirected. Interrupts must be +* injected via hvip instead, so that the hardware itself performs +* VS-mode trap entry, respecting vsstatus.SIE and the vectored +* dispatch (BASE + 4 * cause) if vstvec is configured so. +*/ +ASSERT (!(trap->scause &CAUSE_IRQ_FLAG )); + +/* Change Guest SSTATUS.SPP bit */ + vsstatus &= ~SSTATUS_SPP ; +if ( regs->sstatus &SSTATUS_SPP ) + vsstatus |=SSTATUS_SPP ; + +/* Change Guest SSTATUS.SPIE bit */ + vsstatus &= ~SSTATUS_SPIE ; +if ( vsstatus &SSTATUS_SIE ) + vsstatus |=SSTATUS_SPIE ; + +/* Clear Guest SSTATUS.SIE bit */ + vsstatus &= ~SSTATUS_SIE ; + +/* Update Guest SSTATUS */ +csr_write (CSR_VSSTATUS , vsstatus); + +/* Update Guest SCAUSE, STVAL, and SEPC */ +csr_write (CSR_VSCAUSE , trap->scause); +csr_write (CSR_VSTVAL , trap->stval);
xen/arch/riscv/traps.c enum mc_disposition arch_do_multicall_call(struct mc_state *state) · line 342
Quoted 10 lines
xen/arch/riscv/traps.c +10
-0+csr_write (CSR_VSEPC , trap->sepc); + +/* +* Set Guest PC to Guest exception vector. +* +* vstvec's MODE field is not part of the address. Exceptions always +* target BASE regardless of MODE, so mask it off explicitly instead of +* relying on the hardwired zero bit of sepc to drop it. +*/ + regs->sepc =csr_read (CSR_VSTVEC ) &STVEC_BASE_MASK ;
Nit: Given how much the comment talks about MODE, imo using ~STVEC_MODE_MASK here directly (and dropping STVEC_BASE_MASK) might be better.
Jan
Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest
In reply to Oleksii KurochkoQuoted 71 lines · Oleksii Kurochko
Quoted 15 lines · Baptiste Le Duc
Quoted 7 lines
Some traps taken by Xen on behalf of a guest can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead: the access faults which
handle_guest_page_fault()injects for a fault that can never become an emulated access, and, later on, a fault taken by the hlv/hlvx sequences ofriscv_read_guest()while accessing guest memory on a vCPU's behalf.Access faults from
handle_guest_page_fault()aren't "taken by Xen on
behalf of a guest" as those are guest-page faults taken directly from the
guest's own execution. Xen just decides they can't be emulated and
reflects them back as access faults. Only the hlv/hlvx case is Xen
trapping on the guest's behalf (Xen itself executes the faulting access).> Conflating the two under one description makes the paragraph confusing.Suggest splitting into two:
Quoted 7 lines
Two kinds of traps can't or shouldn't be handled by the hypervisor and have to be reflected to the guest's own S-mode trap handler instead:
- Traps Xen takes on the guest's behalf: the hlv/hlvx sequences
riscv_read_guest()uses to access guest memory.
- Access faultshandle_guest_page_fault()injects for a guest-page fault that can never become an emulated access.Thanks, I'll update original paragraph with what you suggested.>
Quoted 27 lines
Quoted 27 lines
Implement
trap_redirect(), until now aBUG_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.Signed-off-by Oleksii Kurochko <[email protected]>Quoted 16 lines
xen/arch/riscv/include/asm/riscv_encoding.h line 115
Quoted 12 lines
xen/arch/riscv/include/asm/riscv_encoding.h +5
-0@@ -109,6 +109,12 @@ #define SIP_SSIP MIP_SSIP #define SIP_STIP MIP_STIP +/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */ +#define STVEC_MODE_MASK _UL(0x3) +#define STVEC_MODE_DIRECT _UL(0x0) +#define STVEC_MODE_VECTORED _UL(0x1) +#define STVEC_BASE_MASK (~STVEC_MODE_MASK)Nit:
STVEC_MODE_DIRECTandSTVEC_MODE_VECTOREDaren't used anywhere in this patch (onlySTVEC_BASE_MASKis). Either use them where you decide exceptions always target BASE regardless of MODE, or drop them until a patch that needs them.
Quoted 2 lines
IMO it is fine to introduce *_DIRECT/VECORED here as they are used implicitly through
STVEC_BASE_MASKand thereby it will be better to introduce them here now instead of open-code them and then just updateSTVEC_BASE_MASKagain when *_DIRECT/VECORED will be re-introduced.
Oh, sorry, you are right. STVEC_MODE_DIRECT and STVEC_MODE_VECTORED are really not used here (in this implementation). I planned to do:
#define STVEC_MODE_MASK (STVEC_MODE_DIRECT | STVEC_MODE_VECTORED)
But I missed to do in that way.
I will update the defintion of STVEC_MODE_MASK in suggested above way.
~ Oleksii
Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest
Quoted 23 lines · Oleksii Kurochko
Quoted 16 lines · Oleksii Kurochko
Quoted 6 lines · Baptiste Le Duc
Quoted 6 lines
xen/arch/riscv/include/asm/riscv_encoding.h +1
-0@@ -109,6 +109,12 @@ #define SIP_SSIP MIP_SSIP #define SIP_STIP MIP_STIP +/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */ Quoted 8 lines
xen/arch/riscv/include/asm/riscv_encoding.h line 116
Quoted 4 lines
xen/arch/riscv/include/asm/riscv_encoding.h +4
-0+#define STVEC_MODE_MASK _UL(0x3) +#define STVEC_MODE_DIRECT _UL(0x0) +#define STVEC_MODE_VECTORED _UL(0x1) +#define STVEC_BASE_MASK (~STVEC_MODE_MASK)Nit:
STVEC_MODE_DIRECTandSTVEC_MODE_VECTOREDaren't used anywhere in this patch (onlySTVEC_BASE_MASKis). Either use them where you decide exceptions always target BASE regardless of MODE, or drop them until a patch that needs them.Quoted 5 lines
IMO it is fine to introduce *_DIRECT/VECORED here as they are used implicitly through
STVEC_BASE_MASKand thereby it will be better to introduce them here now instead of open-code them and then just updateSTVEC_BASE_MASKagain when *_DIRECT/VECORED will be re-introduced.
Quoted 8 lines
Oh, sorry, you are right.
STVEC_MODE_DIRECTandSTVEC_MODE_VECTOREDare really not used here (in this implementation). I planned to do:#define
STVEC_MODE_MASK(STVEC_MODE_DIRECT|STVEC_MODE_VECTORED)But I missed to do in that way.
I will update the defintion of
STVEC_MODE_MASKin suggested above way.
But that's yield a mask value of 1, when you want it to be 3. That ORing together looks bogus to me anyway.
Jan
Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest
In reply to Jan BeulichQuoted 15 lines · Jan Beulich
xen/arch/riscv/include/asm/riscv_encoding.h line 115
Quoted 10 lines · Oleksii Kurochko
xen/arch/riscv/include/asm/riscv_encoding.h +4
-0@@ -109,6 +109,12 @@#define SIP_SSIP MIP_SSIP#define SIP_STIP MIP_STIP +/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */ +#define STVEC_MODE_MASK _UL(0x3) +#define STVEC_MODE_DIRECT _UL(0x0) +#define STVEC_MODE_VECTORED _UL(0x1)As on earlier occasions: Do the 0x here actually add any value? There are none ...
Quoted 7 lines
xen/arch/riscv/include/asm/riscv_encoding.h line 120
Quoted 5 lines
xen/arch/riscv/include/asm/riscv_encoding.h +2
-0+#define STVEC_BASE_MASK (~STVEC_MODE_MASK) +#define PRV_U _UL(0)#define PRV_S _UL(1)#define PRV_M _UL(3)... here, for example.
Agree, not too much sense.
Quoted 49 lines
Quoted 49 lines
xen/arch/riscv/traps.c +41
-1@@ -294,5 +294,53 @@ enum mc_disposition arch_do_multicall_call(struct mc_state *state)/* Redirect trap to Guest. */ void trap_redirect (const struct trap_info *trap) { -BUG_ON ("unimplemented" ); +struct cpu_user_regs *regs =vcpu_guest_cpu_user_regs (current); +unsigned long vsstatus =csr_read (CSR_VSSTATUS ); + +/* +* Redirecting a trap makes sense only if the trap was taken from +* virtualized mode, i.e. sret is going to return to VS-mode. +*/ +ASSERT (regs->hstatus &HSTATUS_SPV ); + +/* +* Only synchronous exceptions can be redirected. Interrupts must be +* injected via hvip instead, so that the hardware itself performs +* VS-mode trap entry, respecting vsstatus.SIE and the vectored +* dispatch (BASE + 4 * cause) if vstvec is configured so. +*/ +ASSERT (!(trap->scause &CAUSE_IRQ_FLAG )); + +/* Change Guest SSTATUS.SPP bit */ + vsstatus &= ~SSTATUS_SPP ; +if ( regs->sstatus &SSTATUS_SPP ) + vsstatus |=SSTATUS_SPP ; + +/* Change Guest SSTATUS.SPIE bit */ + vsstatus &= ~SSTATUS_SPIE ; +if ( vsstatus &SSTATUS_SIE ) + vsstatus |=SSTATUS_SPIE ; + +/* Clear Guest SSTATUS.SIE bit */ + vsstatus &= ~SSTATUS_SIE ; + +/* Update Guest SSTATUS */ +csr_write (CSR_VSSTATUS , vsstatus); + +/* Update Guest SCAUSE, STVAL, and SEPC */ +csr_write (CSR_VSCAUSE , trap->scause); +csr_write (CSR_VSTVAL , trap->stval); +csr_write (CSR_VSEPC , trap->sepc); + +/* +* Set Guest PC to Guest exception vector. +*
Quoted 9 lines
xen/arch/riscv/traps.c enum mc_disposition arch_do_multicall_call(struct mc_state *state) · line 342
Quoted 5 lines
xen/arch/riscv/traps.c +5
-0+* vstvec's MODE field is not part of the address. Exceptions always +* target BASE regardless of MODE, so mask it off explicitly instead of +* relying on the hardwired zero bit of sepc to drop it. +*/ + regs->sepc =csr_read (CSR_VSTVEC ) &STVEC_BASE_MASK ;Nit: Given how much the comment talks about MODE, imo using ~STVEC_MODE_MASK here directly (and dropping
STVEC_BASE_MASK) might be better.
Agree, it could be dropped. I will update that in v3.
Thanks.
~ Oleksii
Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest
In reply to Jan BeulichQuoted 27 lines · Jan Beulich
Quoted 26 lines · Oleksii Kurochko
Quoted 16 lines · Oleksii Kurochko
Quoted 6 lines · Baptiste Le Duc
Quoted 6 lines
xen/arch/riscv/include/asm/riscv_encoding.h +1
-0@@ -109,6 +109,12 @@ #define SIP_SSIP MIP_SSIP #define SIP_STIP MIP_STIP +/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */ Quoted 8 lines
xen/arch/riscv/include/asm/riscv_encoding.h line 116
Quoted 4 lines
xen/arch/riscv/include/asm/riscv_encoding.h +4
-0+#define STVEC_MODE_MASK _UL(0x3) +#define STVEC_MODE_DIRECT _UL(0x0) +#define STVEC_MODE_VECTORED _UL(0x1) +#define STVEC_BASE_MASK (~STVEC_MODE_MASK)Nit:
STVEC_MODE_DIRECTandSTVEC_MODE_VECTOREDaren't used anywhere in this patch (onlySTVEC_BASE_MASKis). Either use them where you decide exceptions always target BASE regardless of MODE, or drop them until a patch that needs them.Quoted 5 lines
IMO it is fine to introduce *_DIRECT/VECORED here as they are used implicitly through
STVEC_BASE_MASKand thereby it will be better to introduce them here now instead of open-code them and then just updateSTVEC_BASE_MASKagain when *_DIRECT/VECORED will be re-introduced.Oh, sorry, you are right.
STVEC_MODE_DIRECTandSTVEC_MODE_VECTOREDare really not used here (in this implementation). I planned to do:
Quoted 9 lines
Quoted 5 lines
#define
STVEC_MODE_MASK(STVEC_MODE_DIRECT|STVEC_MODE_VECTORED)But I missed to do in that way.
I will update the defintion of
STVEC_MODE_MASKin suggested above way.But that's yield a mask value of 1, when you want it to be 3. That ORing together looks bogus to me anyway.
Yes I agree. It might be enough, for the moment, to only keep #define STVEC_MODE_MASK _UL(3) and drop the others defines (even STVEC_BASE_MASK as Jan mentioned the comment in the caller is already precise enough).
Quoted 4 lines
Jan
Re: [PATCH v2 20/39] xen/riscv: detect Shtvala
In reply to Oleksii KurochkoQuoted 39 lines · Oleksii Kurochko
Quoted 16 lines · Baptiste Le Duc
Quoted 6 lines
Shtvala says that htval is written with the faulting guest physical address on a guest-page fault. The H extension itself allows an implementation to write htval with either that address or with zero, so where the extension is absent a zero htval cannot be told apart from a genuine fault on guest physical address 0-3.
Quoted 7 lines
It is not offered to guests. Shtvala describes the HS-mode trap interface, which a VS-mode guest never sees, and the H extension it belongs to is already withheld from guests. Its guest-facing counterpart is a separate extension, Shvstvala.
Signed-off-by Oleksii Kurochko <[email protected]>I thought this commit message is not very clear. Here is a more direct suggestion:
Quoted 12 lines
``` The H extension allows htval, on a guest-page fault, to be written with either the faulting guest physical address or zero. Shtvala extension removes the ambiguity of this zero-write by guaranteeing that htval is written with the faulting guest physical address in every circumstance permitted by the ISA. Not offered to guests: Shtvala describes htval, an HS-mode-only trap register a VS-mode guest never touches and the H extension it belongs to is already hidden from guests. The guest-visible equivalent is a separate extension, Shvstvala, covering vstval instead. ```Sounds good to me. I will apply your suggestion.
Quoted 4 lines
Btw, I saw Linux has
Documentation/devicetree/bindings/riscv/extensions.yamlwhich describes all of the extensions supported, don't you think it would be useful to have the same in docs/misc/devicetree/...?
Quoted 8 lines
I think it could be useful.
I think also about booting.txt already exitsted in the codebase. Would you be okay with that? I think I will add the section to booting.txt and pointing to riscv_isa_ext[] in
cpufeature.cand so we won't miss an update of doc if we will add or remove support of an extension. Does it sound good to you?
Yes it sounds okay!
Thanks
Quoted 5 lines
~ Oleksii
Re: [PATCH v2 19/39] xen/riscv: implement trap redirection to a guest
In reply to Baptiste Le DucQuoted 32 lines · Baptiste Le Duc
Quoted 31 lines · Jan Beulich
Quoted 30 lines · Oleksii Kurochko
Quoted 16 lines · Oleksii Kurochko
Quoted 6 lines · Baptiste Le Duc
Quoted 6 lines
xen/arch/riscv/include/asm/riscv_encoding.h +1
-0@@ -109,6 +109,12 @@ #define SIP_SSIP MIP_SSIP #define SIP_STIP MIP_STIP +/* stvec/vstvec: MODE is bits [1:0], BASE is bits [XLEN-1:2] */ Quoted 8 lines
xen/arch/riscv/include/asm/riscv_encoding.h line 116
Quoted 4 lines
xen/arch/riscv/include/asm/riscv_encoding.h +4
-0+#define STVEC_MODE_MASK _UL(0x3) +#define STVEC_MODE_DIRECT _UL(0x0) +#define STVEC_MODE_VECTORED _UL(0x1) +#define STVEC_BASE_MASK (~STVEC_MODE_MASK)Nit:
STVEC_MODE_DIRECTandSTVEC_MODE_VECTOREDaren't used anywhere in this patch (onlySTVEC_BASE_MASKis). Either use them where you decide exceptions always target BASE regardless of MODE, or drop them until a patch that needs them.Quoted 5 lines
IMO it is fine to introduce *_DIRECT/VECORED here as they are used implicitly through
STVEC_BASE_MASKand thereby it will be better to introduce them here now instead of open-code them and then just updateSTVEC_BASE_MASKagain when *_DIRECT/VECORED will be re-introduced.Oh, sorry, you are right.
STVEC_MODE_DIRECTandSTVEC_MODE_VECTOREDare really not used here (in this implementation). I planned to do:#define
STVEC_MODE_MASK(STVEC_MODE_DIRECT|STVEC_MODE_VECTORED)But I missed to do in that way.
Quoted 8 lines
Quoted 5 lines
Quoted 1 line
I will update the defintion of
STVEC_MODE_MASKin suggested above way.But that's yield a mask value of 1, when you want it to be 3. That ORing together looks bogus to me anyway.
Yes I agree. It might be enough, for the moment, to only keep #define
STVEC_MODE_MASK_UL(3)and drop the others defines (evenSTVEC_BASE_MASKas Jan mentioned the comment in the caller is already precise enough).
To me having STVEC_MODE_MASK without at least one of STVEC_MODE_{DIRECT,VECTORED} would feel odd / incomplete.
Jan